customElement.spec.ts 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. import type { MockedFunction } from 'vitest'
  2. import {
  3. type HMRRuntime,
  4. type Ref,
  5. Teleport,
  6. type VueElement,
  7. createApp,
  8. defineAsyncComponent,
  9. defineComponent,
  10. defineCustomElement,
  11. h,
  12. inject,
  13. nextTick,
  14. onMounted,
  15. provide,
  16. ref,
  17. render,
  18. renderSlot,
  19. useHost,
  20. useShadowRoot,
  21. } from '../src'
  22. declare var __VUE_HMR_RUNTIME__: HMRRuntime
  23. describe('defineCustomElement', () => {
  24. const container = document.createElement('div')
  25. document.body.appendChild(container)
  26. beforeEach(() => {
  27. container.innerHTML = ''
  28. })
  29. describe('mounting/unmount', () => {
  30. const E = defineCustomElement({
  31. props: {
  32. msg: {
  33. type: String,
  34. default: 'hello',
  35. },
  36. },
  37. render() {
  38. return h('div', this.msg)
  39. },
  40. })
  41. customElements.define('my-element', E)
  42. test('should work', () => {
  43. container.innerHTML = `<my-element></my-element>`
  44. const e = container.childNodes[0] as VueElement
  45. expect(e).toBeInstanceOf(E)
  46. expect(e._instance).toBeTruthy()
  47. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  48. })
  49. test('should work w/ manual instantiation', () => {
  50. const e = new E({ msg: 'inline' })
  51. // should lazy init
  52. expect(e._instance).toBe(null)
  53. // should initialize on connect
  54. container.appendChild(e)
  55. expect(e._instance).toBeTruthy()
  56. expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
  57. })
  58. test('should unmount on remove', async () => {
  59. container.innerHTML = `<my-element></my-element>`
  60. const e = container.childNodes[0] as VueElement
  61. container.removeChild(e)
  62. await nextTick()
  63. expect(e._instance).toBe(null)
  64. expect(e.shadowRoot!.innerHTML).toBe('')
  65. })
  66. // #10610
  67. test('When elements move, avoid prematurely disconnecting MutationObserver', async () => {
  68. const CustomInput = defineCustomElement({
  69. props: ['value'],
  70. emits: ['update'],
  71. setup(props, { emit }) {
  72. return () =>
  73. h('input', {
  74. type: 'number',
  75. value: props.value,
  76. onInput: (e: InputEvent) => {
  77. const num = (e.target! as HTMLInputElement).valueAsNumber
  78. emit('update', Number.isNaN(num) ? null : num)
  79. },
  80. })
  81. },
  82. })
  83. customElements.define('my-el-input', CustomInput)
  84. const num = ref('12')
  85. const containerComp = defineComponent({
  86. setup() {
  87. return () => {
  88. return h('div', [
  89. h('my-el-input', {
  90. value: num.value,
  91. onUpdate: ($event: CustomEvent) => {
  92. num.value = $event.detail[0]
  93. },
  94. }),
  95. h('div', { id: 'move' }),
  96. ])
  97. }
  98. },
  99. })
  100. const app = createApp(containerComp)
  101. const container = document.createElement('div')
  102. document.body.appendChild(container)
  103. app.mount(container)
  104. const myInputEl = container.querySelector('my-el-input')!
  105. const inputEl = myInputEl.shadowRoot!.querySelector('input')!
  106. await nextTick()
  107. expect(inputEl.value).toBe('12')
  108. const moveEl = container.querySelector('#move')!
  109. moveEl.append(myInputEl)
  110. await nextTick()
  111. myInputEl.removeAttribute('value')
  112. await nextTick()
  113. expect(inputEl.value).toBe('')
  114. })
  115. test('should not unmount on move', async () => {
  116. container.innerHTML = `<div><my-element></my-element></div>`
  117. const e = container.childNodes[0].childNodes[0] as VueElement
  118. const i = e._instance
  119. // moving from one parent to another - this will trigger both disconnect
  120. // and connected callbacks synchronously
  121. container.appendChild(e)
  122. await nextTick()
  123. // should be the same instance
  124. expect(e._instance).toBe(i)
  125. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  126. })
  127. test('remove then insert again', async () => {
  128. container.innerHTML = `<my-element></my-element>`
  129. const e = container.childNodes[0] as VueElement
  130. container.removeChild(e)
  131. await nextTick()
  132. expect(e._instance).toBe(null)
  133. expect(e.shadowRoot!.innerHTML).toBe('')
  134. container.appendChild(e)
  135. expect(e._instance).toBeTruthy()
  136. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  137. })
  138. })
  139. describe('props', () => {
  140. const E = defineCustomElement({
  141. props: {
  142. foo: [String, null],
  143. bar: Object,
  144. bazQux: null,
  145. value: null,
  146. },
  147. render() {
  148. return [
  149. h('div', null, this.foo || ''),
  150. h('div', null, this.bazQux || (this.bar && this.bar.x)),
  151. ]
  152. },
  153. })
  154. customElements.define('my-el-props', E)
  155. test('renders custom element w/ correct object prop value', () => {
  156. render(h('my-el-props', { value: { x: 1 } }), container)
  157. const el = container.children[0]
  158. expect((el as any).value).toEqual({ x: 1 })
  159. })
  160. test('props via attribute', async () => {
  161. // bazQux should map to `baz-qux` attribute
  162. container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
  163. const e = container.childNodes[0] as VueElement
  164. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
  165. // change attr
  166. e.setAttribute('foo', 'changed')
  167. await nextTick()
  168. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
  169. e.setAttribute('baz-qux', 'changed')
  170. await nextTick()
  171. expect(e.shadowRoot!.innerHTML).toBe(
  172. '<div>changed</div><div>changed</div>',
  173. )
  174. })
  175. test('props via properties', async () => {
  176. const e = new E()
  177. e.foo = 'one'
  178. e.bar = { x: 'two' }
  179. container.appendChild(e)
  180. expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
  181. // reflect
  182. // should reflect primitive value
  183. expect(e.getAttribute('foo')).toBe('one')
  184. // should not reflect rich data
  185. expect(e.hasAttribute('bar')).toBe(false)
  186. e.foo = 'three'
  187. await nextTick()
  188. expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
  189. expect(e.getAttribute('foo')).toBe('three')
  190. e.foo = null
  191. await nextTick()
  192. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  193. expect(e.hasAttribute('foo')).toBe(false)
  194. e.foo = undefined
  195. await nextTick()
  196. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  197. expect(e.hasAttribute('foo')).toBe(false)
  198. expect(e.foo).toBe(undefined)
  199. e.bazQux = 'four'
  200. await nextTick()
  201. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
  202. expect(e.getAttribute('baz-qux')).toBe('four')
  203. })
  204. test('props via hyphen property', async () => {
  205. const Comp = defineCustomElement({
  206. props: {
  207. fooBar: Boolean,
  208. },
  209. render() {
  210. return 'Comp'
  211. },
  212. })
  213. customElements.define('my-el-comp', Comp)
  214. render(h('my-el-comp', { 'foo-bar': true }), container)
  215. const el = container.children[0]
  216. expect((el as any).outerHTML).toBe('<my-el-comp foo-bar=""></my-el-comp>')
  217. })
  218. test('attribute -> prop type casting', async () => {
  219. const E = defineCustomElement({
  220. props: {
  221. fooBar: Number, // test casting of camelCase prop names
  222. bar: Boolean,
  223. baz: String,
  224. },
  225. render() {
  226. return [
  227. this.fooBar,
  228. typeof this.fooBar,
  229. this.bar,
  230. typeof this.bar,
  231. this.baz,
  232. typeof this.baz,
  233. ].join(' ')
  234. },
  235. })
  236. customElements.define('my-el-props-cast', E)
  237. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  238. const e = container.childNodes[0] as VueElement
  239. expect(e.shadowRoot!.innerHTML).toBe(
  240. `1 number false boolean 12345 string`,
  241. )
  242. e.setAttribute('bar', '')
  243. await nextTick()
  244. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  245. e.setAttribute('foo-bar', '2e1')
  246. await nextTick()
  247. expect(e.shadowRoot!.innerHTML).toBe(
  248. `20 number true boolean 12345 string`,
  249. )
  250. e.setAttribute('baz', '2e1')
  251. await nextTick()
  252. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  253. })
  254. // #4772
  255. test('attr casting w/ programmatic creation', () => {
  256. const E = defineCustomElement({
  257. props: {
  258. foo: Number,
  259. },
  260. render() {
  261. return `foo type: ${typeof this.foo}`
  262. },
  263. })
  264. customElements.define('my-element-programmatic', E)
  265. const el = document.createElement('my-element-programmatic') as any
  266. el.setAttribute('foo', '123')
  267. container.appendChild(el)
  268. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  269. })
  270. test('handling properties set before upgrading', () => {
  271. const E = defineCustomElement({
  272. props: {
  273. foo: String,
  274. dataAge: Number,
  275. },
  276. setup(props) {
  277. expect(props.foo).toBe('hello')
  278. expect(props.dataAge).toBe(5)
  279. },
  280. render() {
  281. return h('div', `foo: ${this.foo}`)
  282. },
  283. })
  284. const el = document.createElement('my-el-upgrade') as any
  285. el.foo = 'hello'
  286. el.dataset.age = 5
  287. el.notProp = 1
  288. container.appendChild(el)
  289. customElements.define('my-el-upgrade', E)
  290. expect(el.shadowRoot.firstChild.innerHTML).toBe(`foo: hello`)
  291. // should not reflect if not declared as a prop
  292. expect(el.hasAttribute('not-prop')).toBe(false)
  293. })
  294. test('handle properties set before connecting', () => {
  295. const obj = { a: 1 }
  296. const E = defineCustomElement({
  297. props: {
  298. foo: String,
  299. post: Object,
  300. },
  301. setup(props) {
  302. expect(props.foo).toBe('hello')
  303. expect(props.post).toBe(obj)
  304. },
  305. render() {
  306. return JSON.stringify(this.post)
  307. },
  308. })
  309. customElements.define('my-el-preconnect', E)
  310. const el = document.createElement('my-el-preconnect') as any
  311. el.foo = 'hello'
  312. el.post = obj
  313. container.appendChild(el)
  314. expect(el.shadowRoot.innerHTML).toBe(JSON.stringify(obj))
  315. })
  316. // https://github.com/vuejs/core/issues/6163
  317. test('handle components with no props', async () => {
  318. const E = defineCustomElement({
  319. render() {
  320. return h('div', 'foo')
  321. },
  322. })
  323. customElements.define('my-element-noprops', E)
  324. const el = document.createElement('my-element-noprops')
  325. container.appendChild(el)
  326. await nextTick()
  327. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  328. })
  329. // #5793
  330. test('set number value in dom property', () => {
  331. const E = defineCustomElement({
  332. props: {
  333. 'max-age': Number,
  334. },
  335. render() {
  336. // @ts-expect-error
  337. return `max age: ${this.maxAge}/type: ${typeof this.maxAge}`
  338. },
  339. })
  340. customElements.define('my-element-number-property', E)
  341. const el = document.createElement('my-element-number-property') as any
  342. container.appendChild(el)
  343. el.maxAge = 50
  344. expect(el.maxAge).toBe(50)
  345. expect(el.shadowRoot.innerHTML).toBe('max age: 50/type: number')
  346. })
  347. // #9006
  348. test('should reflect default value', () => {
  349. const E = defineCustomElement({
  350. props: {
  351. value: {
  352. type: String,
  353. default: 'hi',
  354. },
  355. },
  356. render() {
  357. return this.value
  358. },
  359. })
  360. customElements.define('my-el-default-val', E)
  361. container.innerHTML = `<my-el-default-val></my-el-default-val>`
  362. const e = container.childNodes[0] as any
  363. expect(e.value).toBe('hi')
  364. })
  365. // #12214
  366. test('Boolean prop with default true', async () => {
  367. const E = defineCustomElement({
  368. props: {
  369. foo: {
  370. type: Boolean,
  371. default: true,
  372. },
  373. },
  374. render() {
  375. return String(this.foo)
  376. },
  377. })
  378. customElements.define('my-el-default-true', E)
  379. container.innerHTML = `<my-el-default-true></my-el-default-true>`
  380. const e = container.childNodes[0] as HTMLElement & { foo: any },
  381. shadowRoot = e.shadowRoot as ShadowRoot
  382. expect(shadowRoot.innerHTML).toBe('true')
  383. e.foo = undefined
  384. await nextTick()
  385. expect(shadowRoot.innerHTML).toBe('true')
  386. e.foo = false
  387. await nextTick()
  388. expect(shadowRoot.innerHTML).toBe('false')
  389. e.foo = null
  390. await nextTick()
  391. expect(shadowRoot.innerHTML).toBe('null')
  392. e.foo = ''
  393. await nextTick()
  394. expect(shadowRoot.innerHTML).toBe('true')
  395. })
  396. test('support direct setup function syntax with extra options', () => {
  397. const E = defineCustomElement(
  398. props => {
  399. return () => props.text
  400. },
  401. {
  402. props: {
  403. text: String,
  404. },
  405. },
  406. )
  407. customElements.define('my-el-setup-with-props', E)
  408. container.innerHTML = `<my-el-setup-with-props text="hello"></my-el-setup-with-props>`
  409. const e = container.childNodes[0] as VueElement
  410. expect(e.shadowRoot!.innerHTML).toBe('hello')
  411. })
  412. test('prop types validation', async () => {
  413. const E = defineCustomElement({
  414. props: {
  415. num: {
  416. type: [Number, String],
  417. },
  418. bool: {
  419. type: Boolean,
  420. },
  421. },
  422. render() {
  423. return h('div', [
  424. h('span', [`${this.num} is ${typeof this.num}`]),
  425. h('span', [`${this.bool} is ${typeof this.bool}`]),
  426. ])
  427. },
  428. })
  429. customElements.define('my-el-with-type-props', E)
  430. render(h('my-el-with-type-props', { num: 1, bool: true }), container)
  431. const e = container.childNodes[0] as VueElement
  432. // @ts-expect-error
  433. expect(e.num).toBe(1)
  434. // @ts-expect-error
  435. expect(e.bool).toBe(true)
  436. expect(e.shadowRoot!.innerHTML).toBe(
  437. '<div><span>1 is number</span><span>true is boolean</span></div>',
  438. )
  439. })
  440. })
  441. describe('attrs', () => {
  442. const E = defineCustomElement({
  443. render() {
  444. return [h('div', null, this.$attrs.foo as string)]
  445. },
  446. })
  447. customElements.define('my-el-attrs', E)
  448. test('attrs via attribute', async () => {
  449. container.innerHTML = `<my-el-attrs foo="hello"></my-el-attrs>`
  450. const e = container.childNodes[0] as VueElement
  451. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  452. e.setAttribute('foo', 'changed')
  453. await nextTick()
  454. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div>')
  455. })
  456. test('non-declared properties should not show up in $attrs', () => {
  457. const e = new E()
  458. // @ts-expect-error
  459. e.foo = '123'
  460. container.appendChild(e)
  461. expect(e.shadowRoot!.innerHTML).toBe('<div></div>')
  462. })
  463. })
  464. describe('emits', () => {
  465. const CompDef = defineComponent({
  466. setup(_, { emit }) {
  467. emit('created')
  468. return () =>
  469. h('div', {
  470. onClick: () => {
  471. emit('my-click', 1)
  472. },
  473. onMousedown: () => {
  474. emit('myEvent', 1) // validate hyphenation
  475. },
  476. onWheel: () => {
  477. emit('my-wheel', { bubbles: true }, 1)
  478. },
  479. })
  480. },
  481. })
  482. const E = defineCustomElement(CompDef)
  483. customElements.define('my-el-emits', E)
  484. test('emit on connect', () => {
  485. const e = new E()
  486. const spy = vi.fn()
  487. e.addEventListener('created', spy)
  488. container.appendChild(e)
  489. expect(spy).toHaveBeenCalled()
  490. })
  491. test('emit on interaction', () => {
  492. container.innerHTML = `<my-el-emits></my-el-emits>`
  493. const e = container.childNodes[0] as VueElement
  494. const spy = vi.fn()
  495. e.addEventListener('my-click', spy)
  496. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  497. expect(spy).toHaveBeenCalledTimes(1)
  498. expect(spy.mock.calls[0][0]).toMatchObject({
  499. detail: [1],
  500. })
  501. })
  502. // #5373
  503. test('case transform for camelCase event', () => {
  504. container.innerHTML = `<my-el-emits></my-el-emits>`
  505. const e = container.childNodes[0] as VueElement
  506. const spy1 = vi.fn()
  507. e.addEventListener('myEvent', spy1)
  508. const spy2 = vi.fn()
  509. // emitting myEvent, but listening for my-event. This happens when
  510. // using the custom element in a Vue template
  511. e.addEventListener('my-event', spy2)
  512. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('mousedown'))
  513. expect(spy1).toHaveBeenCalledTimes(1)
  514. expect(spy2).toHaveBeenCalledTimes(1)
  515. })
  516. test('emit from within async component wrapper', async () => {
  517. const p = new Promise<typeof CompDef>(res => res(CompDef as any))
  518. const E = defineCustomElement(defineAsyncComponent(() => p))
  519. customElements.define('my-async-el-emits', E)
  520. container.innerHTML = `<my-async-el-emits></my-async-el-emits>`
  521. const e = container.childNodes[0] as VueElement
  522. const spy = vi.fn()
  523. e.addEventListener('my-click', spy)
  524. // this feels brittle but seems necessary to reach the node in the DOM.
  525. await customElements.whenDefined('my-async-el-emits')
  526. await nextTick()
  527. await nextTick()
  528. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  529. expect(spy).toHaveBeenCalled()
  530. expect(spy.mock.calls[0][0]).toMatchObject({
  531. detail: [1],
  532. })
  533. })
  534. // #7293
  535. test('emit in an async component wrapper with properties bound', async () => {
  536. const E = defineCustomElement(
  537. defineAsyncComponent(
  538. () => new Promise<typeof CompDef>(res => res(CompDef as any)),
  539. ),
  540. )
  541. customElements.define('my-async-el-props-emits', E)
  542. container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>`
  543. const e = container.childNodes[0] as VueElement
  544. const spy = vi.fn()
  545. e.addEventListener('my-click', spy)
  546. await customElements.whenDefined('my-async-el-props-emits')
  547. await nextTick()
  548. await nextTick()
  549. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  550. expect(spy).toHaveBeenCalled()
  551. expect(spy.mock.calls[0][0]).toMatchObject({
  552. detail: [1],
  553. })
  554. })
  555. test('emit with options', async () => {
  556. container.innerHTML = `<my-el-emits></my-el-emits>`
  557. const e = container.childNodes[0] as VueElement
  558. const spy = vi.fn()
  559. e.addEventListener('my-wheel', spy)
  560. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('wheel'))
  561. expect(spy).toHaveBeenCalledTimes(1)
  562. expect(spy.mock.calls[0][0]).toMatchObject({
  563. bubbles: true,
  564. detail: [{ bubbles: true }, 1],
  565. })
  566. })
  567. })
  568. describe('slots', () => {
  569. const E = defineCustomElement({
  570. render() {
  571. return [
  572. h('div', null, [
  573. renderSlot(this.$slots, 'default', undefined, () => [
  574. h('div', 'fallback'),
  575. ]),
  576. ]),
  577. h('div', null, renderSlot(this.$slots, 'named')),
  578. ]
  579. },
  580. })
  581. customElements.define('my-el-slots', E)
  582. test('render slots correctly', () => {
  583. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  584. const e = container.childNodes[0] as VueElement
  585. // native slots allocation does not affect innerHTML, so we just
  586. // verify that we've rendered the correct native slots here...
  587. expect(e.shadowRoot!.innerHTML).toBe(
  588. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  589. )
  590. })
  591. })
  592. describe('provide/inject', () => {
  593. const Consumer = defineCustomElement({
  594. setup() {
  595. const foo = inject<Ref>('foo')!
  596. return () => h('div', foo.value)
  597. },
  598. })
  599. customElements.define('my-consumer', Consumer)
  600. test('over nested usage', async () => {
  601. const foo = ref('injected!')
  602. const Provider = defineCustomElement({
  603. provide: {
  604. foo,
  605. },
  606. render() {
  607. return h('my-consumer')
  608. },
  609. })
  610. customElements.define('my-provider', Provider)
  611. container.innerHTML = `<my-provider><my-provider>`
  612. const provider = container.childNodes[0] as VueElement
  613. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  614. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  615. foo.value = 'changed!'
  616. await nextTick()
  617. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  618. })
  619. test('over slot composition', async () => {
  620. const foo = ref('injected!')
  621. const Provider = defineCustomElement({
  622. provide: {
  623. foo,
  624. },
  625. render() {
  626. return renderSlot(this.$slots, 'default')
  627. },
  628. })
  629. customElements.define('my-provider-2', Provider)
  630. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  631. const provider = container.childNodes[0]
  632. const consumer = provider.childNodes[0] as VueElement
  633. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  634. foo.value = 'changed!'
  635. await nextTick()
  636. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  637. })
  638. test('inherited from ancestors', async () => {
  639. const fooA = ref('FooA!')
  640. const fooB = ref('FooB!')
  641. const ProviderA = defineCustomElement({
  642. provide: {
  643. fooA,
  644. },
  645. render() {
  646. return h('provider-b')
  647. },
  648. })
  649. const ProviderB = defineCustomElement({
  650. provide: {
  651. fooB,
  652. },
  653. render() {
  654. return h('my-multi-consumer')
  655. },
  656. })
  657. const Consumer = defineCustomElement({
  658. setup() {
  659. const fooA = inject<Ref>('fooA')!
  660. const fooB = inject<Ref>('fooB')!
  661. return () => h('div', `${fooA.value} ${fooB.value}`)
  662. },
  663. })
  664. customElements.define('provider-a', ProviderA)
  665. customElements.define('provider-b', ProviderB)
  666. customElements.define('my-multi-consumer', Consumer)
  667. container.innerHTML = `<provider-a><provider-a>`
  668. const providerA = container.childNodes[0] as VueElement
  669. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  670. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  671. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  672. fooA.value = 'changedA!'
  673. fooB.value = 'changedB!'
  674. await nextTick()
  675. expect(consumer.shadowRoot!.innerHTML).toBe(
  676. `<div>changedA! changedB!</div>`,
  677. )
  678. })
  679. // #13212
  680. test('inherited from app context within nested elements', async () => {
  681. const outerValues: (string | undefined)[] = []
  682. const innerValues: (string | undefined)[] = []
  683. const innerChildValues: (string | undefined)[] = []
  684. const Outer = defineCustomElement(
  685. {
  686. setup() {
  687. outerValues.push(
  688. inject<string>('shared'),
  689. inject<string>('outer'),
  690. inject<string>('inner'),
  691. )
  692. },
  693. render() {
  694. return h('div', [renderSlot(this.$slots, 'default')])
  695. },
  696. },
  697. {
  698. configureApp(app) {
  699. app.provide('shared', 'shared')
  700. app.provide('outer', 'outer')
  701. },
  702. },
  703. )
  704. const Inner = defineCustomElement(
  705. {
  706. setup() {
  707. // ensure values are not self-injected
  708. provide('inner', 'inner-child')
  709. innerValues.push(
  710. inject<string>('shared'),
  711. inject<string>('outer'),
  712. inject<string>('inner'),
  713. )
  714. },
  715. render() {
  716. return h('div', [renderSlot(this.$slots, 'default')])
  717. },
  718. },
  719. {
  720. configureApp(app) {
  721. app.provide('outer', 'override-outer')
  722. app.provide('inner', 'inner')
  723. },
  724. },
  725. )
  726. const InnerChild = defineCustomElement({
  727. setup() {
  728. innerChildValues.push(
  729. inject<string>('shared'),
  730. inject<string>('outer'),
  731. inject<string>('inner'),
  732. )
  733. },
  734. render() {
  735. return h('div')
  736. },
  737. })
  738. customElements.define('provide-from-app-outer', Outer)
  739. customElements.define('provide-from-app-inner', Inner)
  740. customElements.define('provide-from-app-inner-child', InnerChild)
  741. container.innerHTML =
  742. '<provide-from-app-outer>' +
  743. '<provide-from-app-inner>' +
  744. '<provide-from-app-inner-child></provide-from-app-inner-child>' +
  745. '</provide-from-app-inner>' +
  746. '</provide-from-app-outer>'
  747. const outer = container.childNodes[0] as VueElement
  748. expect(outer.shadowRoot!.innerHTML).toBe('<div><slot></slot></div>')
  749. expect('[Vue warn]: injection "inner" not found.').toHaveBeenWarnedTimes(
  750. 1,
  751. )
  752. expect(
  753. '[Vue warn]: App already provides property with key "outer" inherited from its parent element. ' +
  754. 'It will be overwritten with the new value.',
  755. ).toHaveBeenWarnedTimes(1)
  756. expect(outerValues).toEqual(['shared', 'outer', undefined])
  757. expect(innerValues).toEqual(['shared', 'override-outer', 'inner'])
  758. expect(innerChildValues).toEqual([
  759. 'shared',
  760. 'override-outer',
  761. 'inner-child',
  762. ])
  763. })
  764. })
  765. describe('styles', () => {
  766. function assertStyles(el: VueElement, css: string[]) {
  767. const styles = el.shadowRoot?.querySelectorAll('style')!
  768. expect(styles.length).toBe(css.length) // should not duplicate multiple copies from Bar
  769. for (let i = 0; i < css.length; i++) {
  770. expect(styles[i].textContent).toBe(css[i])
  771. }
  772. }
  773. test('should attach styles to shadow dom', async () => {
  774. const def = defineComponent({
  775. __hmrId: 'foo',
  776. styles: [`div { color: red; }`],
  777. render() {
  778. return h('div', 'hello')
  779. },
  780. })
  781. const Foo = defineCustomElement(def)
  782. customElements.define('my-el-with-styles', Foo)
  783. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  784. const el = container.childNodes[0] as VueElement
  785. const style = el.shadowRoot?.querySelector('style')!
  786. expect(style.textContent).toBe(`div { color: red; }`)
  787. // hmr
  788. __VUE_HMR_RUNTIME__.reload('foo', {
  789. ...def,
  790. styles: [`div { color: blue; }`, `div { color: yellow; }`],
  791. } as any)
  792. await nextTick()
  793. assertStyles(el, [`div { color: blue; }`, `div { color: yellow; }`])
  794. })
  795. test("child components should inject styles to root element's shadow root", async () => {
  796. const Baz = () => h(Bar)
  797. const Bar = defineComponent({
  798. __hmrId: 'bar',
  799. styles: [`div { color: green; }`, `div { color: blue; }`],
  800. render() {
  801. return 'bar'
  802. },
  803. })
  804. const Foo = defineCustomElement({
  805. styles: [`div { color: red; }`],
  806. render() {
  807. return [h(Baz), h(Baz)]
  808. },
  809. })
  810. customElements.define('my-el-with-child-styles', Foo)
  811. container.innerHTML = `<my-el-with-child-styles></my-el-with-child-styles>`
  812. const el = container.childNodes[0] as VueElement
  813. // inject order should be child -> parent
  814. assertStyles(el, [
  815. `div { color: green; }`,
  816. `div { color: blue; }`,
  817. `div { color: red; }`,
  818. ])
  819. // hmr
  820. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  821. ...Bar,
  822. styles: [`div { color: red; }`, `div { color: yellow; }`],
  823. } as any)
  824. await nextTick()
  825. assertStyles(el, [
  826. `div { color: red; }`,
  827. `div { color: yellow; }`,
  828. `div { color: red; }`,
  829. ])
  830. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  831. ...Bar,
  832. styles: [`div { color: blue; }`],
  833. } as any)
  834. await nextTick()
  835. assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
  836. })
  837. test('with nonce', () => {
  838. const Foo = defineCustomElement(
  839. {
  840. styles: [`div { color: red; }`],
  841. render() {
  842. return h('div', 'hello')
  843. },
  844. },
  845. { nonce: 'xxx' },
  846. )
  847. customElements.define('my-el-with-nonce', Foo)
  848. container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
  849. const el = container.childNodes[0] as VueElement
  850. const style = el.shadowRoot?.querySelector('style')!
  851. expect(style.getAttribute('nonce')).toBe('xxx')
  852. })
  853. })
  854. describe('async', () => {
  855. test('should work', async () => {
  856. const loaderSpy = vi.fn()
  857. const E = defineCustomElement(
  858. defineAsyncComponent(() => {
  859. loaderSpy()
  860. return Promise.resolve({
  861. props: ['msg'],
  862. styles: [`div { color: red }`],
  863. render(this: any) {
  864. return h('div', null, this.msg)
  865. },
  866. })
  867. }),
  868. )
  869. customElements.define('my-el-async', E)
  870. container.innerHTML =
  871. `<my-el-async msg="hello"></my-el-async>` +
  872. `<my-el-async msg="world"></my-el-async>`
  873. await new Promise(r => setTimeout(r))
  874. // loader should be called only once
  875. expect(loaderSpy).toHaveBeenCalledTimes(1)
  876. const e1 = container.childNodes[0] as VueElement
  877. const e2 = container.childNodes[1] as VueElement
  878. // should inject styles
  879. expect(e1.shadowRoot!.innerHTML).toBe(
  880. `<style>div { color: red }</style><div>hello</div>`,
  881. )
  882. expect(e2.shadowRoot!.innerHTML).toBe(
  883. `<style>div { color: red }</style><div>world</div>`,
  884. )
  885. // attr
  886. e1.setAttribute('msg', 'attr')
  887. await nextTick()
  888. expect((e1 as any).msg).toBe('attr')
  889. expect(e1.shadowRoot!.innerHTML).toBe(
  890. `<style>div { color: red }</style><div>attr</div>`,
  891. )
  892. // props
  893. expect(`msg` in e1).toBe(true)
  894. ;(e1 as any).msg = 'prop'
  895. expect(e1.getAttribute('msg')).toBe('prop')
  896. expect(e1.shadowRoot!.innerHTML).toBe(
  897. `<style>div { color: red }</style><div>prop</div>`,
  898. )
  899. })
  900. test('set DOM property before resolve', async () => {
  901. const E = defineCustomElement(
  902. defineAsyncComponent(() => {
  903. return Promise.resolve({
  904. props: ['msg'],
  905. setup(props) {
  906. expect(typeof props.msg).toBe('string')
  907. },
  908. render(this: any) {
  909. return h('div', this.msg)
  910. },
  911. })
  912. }),
  913. )
  914. customElements.define('my-el-async-2', E)
  915. const e1 = new E()
  916. // set property before connect
  917. e1.msg = 'hello'
  918. const e2 = new E()
  919. container.appendChild(e1)
  920. container.appendChild(e2)
  921. // set property after connect but before resolve
  922. e2.msg = 'world'
  923. await new Promise(r => setTimeout(r))
  924. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  925. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  926. e1.msg = 'world'
  927. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  928. e2.msg = 'hello'
  929. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  930. })
  931. test('Number prop casting before resolve', async () => {
  932. const E = defineCustomElement(
  933. defineAsyncComponent(() => {
  934. return Promise.resolve({
  935. props: { n: Number },
  936. setup(props) {
  937. expect(props.n).toBe(20)
  938. },
  939. render(this: any) {
  940. return h('div', this.n + ',' + typeof this.n)
  941. },
  942. })
  943. }),
  944. )
  945. customElements.define('my-el-async-3', E)
  946. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  947. await new Promise(r => setTimeout(r))
  948. const e = container.childNodes[0] as VueElement
  949. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  950. })
  951. test('with slots', async () => {
  952. const E = defineCustomElement(
  953. defineAsyncComponent(() => {
  954. return Promise.resolve({
  955. render(this: any) {
  956. return [
  957. h('div', null, [
  958. renderSlot(this.$slots, 'default', undefined, () => [
  959. h('div', 'fallback'),
  960. ]),
  961. ]),
  962. h('div', null, renderSlot(this.$slots, 'named')),
  963. ]
  964. },
  965. })
  966. }),
  967. )
  968. customElements.define('my-el-async-slots', E)
  969. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  970. await new Promise(r => setTimeout(r))
  971. const e = container.childNodes[0] as VueElement
  972. expect(e.shadowRoot!.innerHTML).toBe(
  973. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  974. )
  975. })
  976. })
  977. describe('shadowRoot: false', () => {
  978. const E = defineCustomElement({
  979. shadowRoot: false,
  980. props: {
  981. msg: {
  982. type: String,
  983. default: 'hello',
  984. },
  985. },
  986. render() {
  987. return h('div', this.msg)
  988. },
  989. })
  990. customElements.define('my-el-shadowroot-false', E)
  991. test('should work', async () => {
  992. function raf() {
  993. return new Promise(resolve => {
  994. requestAnimationFrame(resolve)
  995. })
  996. }
  997. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  998. const e = container.childNodes[0] as VueElement
  999. await raf()
  1000. expect(e).toBeInstanceOf(E)
  1001. expect(e._instance).toBeTruthy()
  1002. expect(e.innerHTML).toBe(`<div>hello</div>`)
  1003. expect(e.shadowRoot).toBe(null)
  1004. })
  1005. const toggle = ref(true)
  1006. const ES = defineCustomElement(
  1007. {
  1008. render() {
  1009. return [
  1010. renderSlot(this.$slots, 'default'),
  1011. toggle.value ? renderSlot(this.$slots, 'named') : null,
  1012. renderSlot(this.$slots, 'omitted', {}, () => [
  1013. h('div', 'fallback'),
  1014. ]),
  1015. ]
  1016. },
  1017. },
  1018. { shadowRoot: false },
  1019. )
  1020. customElements.define('my-el-shadowroot-false-slots', ES)
  1021. test('should render slots', async () => {
  1022. container.innerHTML =
  1023. `<my-el-shadowroot-false-slots>` +
  1024. `<span>default</span>text` +
  1025. `<div slot="named">named</div>` +
  1026. `</my-el-shadowroot-false-slots>`
  1027. const e = container.childNodes[0] as VueElement
  1028. // native slots allocation does not affect innerHTML, so we just
  1029. // verify that we've rendered the correct native slots here...
  1030. expect(e.innerHTML).toBe(
  1031. `<span>default</span>text` +
  1032. `<div slot="named">named</div>` +
  1033. `<div>fallback</div>`,
  1034. )
  1035. toggle.value = false
  1036. await nextTick()
  1037. expect(e.innerHTML).toBe(
  1038. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  1039. )
  1040. })
  1041. test('render nested customElement w/ shadowRoot false', async () => {
  1042. const calls: string[] = []
  1043. const Child = defineCustomElement(
  1044. {
  1045. setup() {
  1046. calls.push('child rendering')
  1047. onMounted(() => {
  1048. calls.push('child mounted')
  1049. })
  1050. },
  1051. render() {
  1052. return renderSlot(this.$slots, 'default')
  1053. },
  1054. },
  1055. { shadowRoot: false },
  1056. )
  1057. customElements.define('my-child', Child)
  1058. const Parent = defineCustomElement(
  1059. {
  1060. setup() {
  1061. calls.push('parent rendering')
  1062. onMounted(() => {
  1063. calls.push('parent mounted')
  1064. })
  1065. },
  1066. render() {
  1067. return renderSlot(this.$slots, 'default')
  1068. },
  1069. },
  1070. { shadowRoot: false },
  1071. )
  1072. customElements.define('my-parent', Parent)
  1073. const App = {
  1074. render() {
  1075. return h('my-parent', null, {
  1076. default: () => [
  1077. h('my-child', null, {
  1078. default: () => [h('span', null, 'default')],
  1079. }),
  1080. ],
  1081. })
  1082. },
  1083. }
  1084. const app = createApp(App)
  1085. app.mount(container)
  1086. await nextTick()
  1087. const e = container.childNodes[0] as VueElement
  1088. expect(e.innerHTML).toBe(
  1089. `<my-child data-v-app=""><span>default</span></my-child>`,
  1090. )
  1091. expect(calls).toEqual([
  1092. 'parent rendering',
  1093. 'parent mounted',
  1094. 'child rendering',
  1095. 'child mounted',
  1096. ])
  1097. app.unmount()
  1098. })
  1099. test('render nested Teleport w/ shadowRoot false', async () => {
  1100. const target = document.createElement('div')
  1101. const Child = defineCustomElement(
  1102. {
  1103. render() {
  1104. return h(
  1105. Teleport,
  1106. { to: target },
  1107. {
  1108. default: () => [renderSlot(this.$slots, 'default')],
  1109. },
  1110. )
  1111. },
  1112. },
  1113. { shadowRoot: false },
  1114. )
  1115. customElements.define('my-el-teleport-child', Child)
  1116. const Parent = defineCustomElement(
  1117. {
  1118. render() {
  1119. return renderSlot(this.$slots, 'default')
  1120. },
  1121. },
  1122. { shadowRoot: false },
  1123. )
  1124. customElements.define('my-el-teleport-parent', Parent)
  1125. const App = {
  1126. render() {
  1127. return h('my-el-teleport-parent', null, {
  1128. default: () => [
  1129. h('my-el-teleport-child', null, {
  1130. default: () => [h('span', null, 'default')],
  1131. }),
  1132. ],
  1133. })
  1134. },
  1135. }
  1136. const app = createApp(App)
  1137. app.mount(container)
  1138. await nextTick()
  1139. expect(target.innerHTML).toBe(`<span>default</span>`)
  1140. app.unmount()
  1141. })
  1142. test('toggle nested custom element with shadowRoot: false', async () => {
  1143. customElements.define(
  1144. 'my-el-child-shadow-false',
  1145. defineCustomElement(
  1146. {
  1147. render(ctx: any) {
  1148. return h('div', null, [renderSlot(ctx.$slots, 'default')])
  1149. },
  1150. },
  1151. { shadowRoot: false },
  1152. ),
  1153. )
  1154. const ChildWrapper = {
  1155. render() {
  1156. return h('my-el-child-shadow-false', null, 'child')
  1157. },
  1158. }
  1159. customElements.define(
  1160. 'my-el-parent-shadow-false',
  1161. defineCustomElement(
  1162. {
  1163. props: {
  1164. isShown: { type: Boolean, required: true },
  1165. },
  1166. render(ctx: any, _: any, $props: any) {
  1167. return $props.isShown
  1168. ? h('div', { key: 0 }, [renderSlot(ctx.$slots, 'default')])
  1169. : null
  1170. },
  1171. },
  1172. { shadowRoot: false },
  1173. ),
  1174. )
  1175. const ParentWrapper = {
  1176. props: {
  1177. isShown: { type: Boolean, required: true },
  1178. },
  1179. render(ctx: any, _: any, $props: any) {
  1180. return h('my-el-parent-shadow-false', { isShown: $props.isShown }, [
  1181. renderSlot(ctx.$slots, 'default'),
  1182. ])
  1183. },
  1184. }
  1185. const isShown = ref(true)
  1186. const App = {
  1187. render() {
  1188. return h(ParentWrapper, { isShown: isShown.value } as any, {
  1189. default: () => [h(ChildWrapper)],
  1190. })
  1191. },
  1192. }
  1193. const container = document.createElement('div')
  1194. document.body.appendChild(container)
  1195. const app = createApp(App)
  1196. app.mount(container)
  1197. expect(container.innerHTML).toBe(
  1198. `<my-el-parent-shadow-false is-shown="" data-v-app="">` +
  1199. `<div>` +
  1200. `<my-el-child-shadow-false data-v-app="">` +
  1201. `<div>child</div>` +
  1202. `</my-el-child-shadow-false>` +
  1203. `</div>` +
  1204. `</my-el-parent-shadow-false>`,
  1205. )
  1206. isShown.value = false
  1207. await nextTick()
  1208. expect(container.innerHTML).toBe(
  1209. `<my-el-parent-shadow-false data-v-app=""><!----></my-el-parent-shadow-false>`,
  1210. )
  1211. isShown.value = true
  1212. await nextTick()
  1213. expect(container.innerHTML).toBe(
  1214. `<my-el-parent-shadow-false data-v-app="" is-shown="">` +
  1215. `<div>` +
  1216. `<my-el-child-shadow-false data-v-app="">` +
  1217. `<div>child</div>` +
  1218. `</my-el-child-shadow-false>` +
  1219. `</div>` +
  1220. `</my-el-parent-shadow-false>`,
  1221. )
  1222. })
  1223. })
  1224. describe('helpers', () => {
  1225. test('useHost', () => {
  1226. const Foo = defineCustomElement({
  1227. setup() {
  1228. const host = useHost()!
  1229. host.setAttribute('id', 'host')
  1230. return () => h('div', 'hello')
  1231. },
  1232. })
  1233. customElements.define('my-el-use-host', Foo)
  1234. container.innerHTML = `<my-el-use-host>`
  1235. const el = container.childNodes[0] as VueElement
  1236. expect(el.id).toBe('host')
  1237. })
  1238. test('useShadowRoot for style injection', () => {
  1239. const Foo = defineCustomElement({
  1240. setup() {
  1241. const root = useShadowRoot()!
  1242. const style = document.createElement('style')
  1243. style.innerHTML = `div { color: red; }`
  1244. root.appendChild(style)
  1245. return () => h('div', 'hello')
  1246. },
  1247. })
  1248. customElements.define('my-el-use-shadow-root', Foo)
  1249. container.innerHTML = `<my-el-use-shadow-root>`
  1250. const el = container.childNodes[0] as VueElement
  1251. const style = el.shadowRoot?.querySelector('style')!
  1252. expect(style.textContent).toBe(`div { color: red; }`)
  1253. })
  1254. })
  1255. describe('expose', () => {
  1256. test('expose attributes and callback', async () => {
  1257. type SetValue = (value: string) => void
  1258. let fn: MockedFunction<SetValue>
  1259. const E = defineCustomElement({
  1260. setup(_, { expose }) {
  1261. const value = ref('hello')
  1262. const setValue = (fn = vi.fn((_value: string) => {
  1263. value.value = _value
  1264. }))
  1265. expose({
  1266. setValue,
  1267. value,
  1268. })
  1269. return () => h('div', null, [value.value])
  1270. },
  1271. })
  1272. customElements.define('my-el-expose', E)
  1273. container.innerHTML = `<my-el-expose></my-el-expose>`
  1274. const e = container.childNodes[0] as VueElement & {
  1275. value: string
  1276. setValue: MockedFunction<SetValue>
  1277. }
  1278. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1279. expect(e.value).toBe('hello')
  1280. expect(e.setValue).toBe(fn!)
  1281. e.setValue('world')
  1282. expect(e.value).toBe('world')
  1283. await nextTick()
  1284. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1285. })
  1286. test('warning when exposing an existing property', () => {
  1287. const E = defineCustomElement({
  1288. props: {
  1289. value: String,
  1290. },
  1291. setup(props, { expose }) {
  1292. expose({
  1293. value: 'hello',
  1294. })
  1295. return () => h('div', null, [props.value])
  1296. },
  1297. })
  1298. customElements.define('my-el-expose-two', E)
  1299. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  1300. expect(
  1301. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  1302. ).toHaveBeenWarned()
  1303. })
  1304. })
  1305. test('async & nested custom elements', async () => {
  1306. let fooVal: string | undefined = ''
  1307. const E = defineCustomElement(
  1308. defineAsyncComponent(() => {
  1309. return Promise.resolve({
  1310. setup(props) {
  1311. provide('foo', 'foo')
  1312. },
  1313. render(this: any) {
  1314. return h('div', null, [renderSlot(this.$slots, 'default')])
  1315. },
  1316. })
  1317. }),
  1318. )
  1319. const EChild = defineCustomElement({
  1320. setup(props) {
  1321. fooVal = inject('foo')
  1322. },
  1323. render(this: any) {
  1324. return h('div', null, 'child')
  1325. },
  1326. })
  1327. customElements.define('my-el-async-nested-ce', E)
  1328. customElements.define('slotted-child', EChild)
  1329. container.innerHTML = `<my-el-async-nested-ce><div><slotted-child></slotted-child></div></my-el-async-nested-ce>`
  1330. await new Promise(r => setTimeout(r))
  1331. const e = container.childNodes[0] as VueElement
  1332. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1333. expect(fooVal).toBe('foo')
  1334. })
  1335. test('async & multiple levels of nested custom elements', async () => {
  1336. let fooVal: string | undefined = ''
  1337. let barVal: string | undefined = ''
  1338. const E = defineCustomElement(
  1339. defineAsyncComponent(() => {
  1340. return Promise.resolve({
  1341. setup(props) {
  1342. provide('foo', 'foo')
  1343. },
  1344. render(this: any) {
  1345. return h('div', null, [renderSlot(this.$slots, 'default')])
  1346. },
  1347. })
  1348. }),
  1349. )
  1350. const EChild = defineCustomElement({
  1351. setup(props) {
  1352. provide('bar', 'bar')
  1353. },
  1354. render(this: any) {
  1355. return h('div', null, [renderSlot(this.$slots, 'default')])
  1356. },
  1357. })
  1358. const EChild2 = defineCustomElement({
  1359. setup(props) {
  1360. fooVal = inject('foo')
  1361. barVal = inject('bar')
  1362. },
  1363. render(this: any) {
  1364. return h('div', null, 'child')
  1365. },
  1366. })
  1367. customElements.define('my-el-async-nested-m-ce', E)
  1368. customElements.define('slotted-child-m', EChild)
  1369. customElements.define('slotted-child2-m', EChild2)
  1370. container.innerHTML =
  1371. `<my-el-async-nested-m-ce>` +
  1372. `<div><slotted-child-m>` +
  1373. `<slotted-child2-m></slotted-child2-m>` +
  1374. `</slotted-child-m></div>` +
  1375. `</my-el-async-nested-m-ce>`
  1376. await new Promise(r => setTimeout(r))
  1377. const e = container.childNodes[0] as VueElement
  1378. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1379. expect(fooVal).toBe('foo')
  1380. expect(barVal).toBe('bar')
  1381. })
  1382. describe('configureApp', () => {
  1383. test('should work', () => {
  1384. const E = defineCustomElement(
  1385. () => {
  1386. const msg = inject('msg')
  1387. return () => h('div', msg!)
  1388. },
  1389. {
  1390. configureApp(app) {
  1391. app.provide('msg', 'app-injected')
  1392. },
  1393. },
  1394. )
  1395. customElements.define('my-element-with-app', E)
  1396. container.innerHTML = `<my-element-with-app></my-element-with-app>`
  1397. const e = container.childNodes[0] as VueElement
  1398. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1399. })
  1400. test('with hmr reload', async () => {
  1401. const __hmrId = '__hmrWithApp'
  1402. const def = defineComponent({
  1403. __hmrId,
  1404. setup() {
  1405. const msg = inject('msg')
  1406. return { msg }
  1407. },
  1408. render(this: any) {
  1409. return h('div', [h('span', this.msg), h('span', this.$foo)])
  1410. },
  1411. })
  1412. const E = defineCustomElement(def, {
  1413. configureApp(app) {
  1414. app.provide('msg', 'app-injected')
  1415. app.config.globalProperties.$foo = 'foo'
  1416. },
  1417. })
  1418. customElements.define('my-element-with-app-hmr', E)
  1419. container.innerHTML = `<my-element-with-app-hmr></my-element-with-app-hmr>`
  1420. const el = container.childNodes[0] as VueElement
  1421. expect(el.shadowRoot?.innerHTML).toBe(
  1422. `<div><span>app-injected</span><span>foo</span></div>`,
  1423. )
  1424. // hmr
  1425. __VUE_HMR_RUNTIME__.reload(__hmrId, def as any)
  1426. await nextTick()
  1427. expect(el.shadowRoot?.innerHTML).toBe(
  1428. `<div><span>app-injected</span><span>foo</span></div>`,
  1429. )
  1430. })
  1431. })
  1432. // #9885
  1433. test('avoid double mount when prop is set immediately after mount', () => {
  1434. customElements.define(
  1435. 'my-input-dupe',
  1436. defineCustomElement({
  1437. props: {
  1438. value: String,
  1439. },
  1440. render() {
  1441. return 'hello'
  1442. },
  1443. }),
  1444. )
  1445. const container = document.createElement('div')
  1446. document.body.appendChild(container)
  1447. createApp({
  1448. render() {
  1449. return h('div', [
  1450. h('my-input-dupe', {
  1451. onVnodeMounted(vnode) {
  1452. vnode.el!.value = 'fesfes'
  1453. },
  1454. }),
  1455. ])
  1456. },
  1457. }).mount(container)
  1458. expect(container.children[0].children[0].shadowRoot?.innerHTML).toBe(
  1459. 'hello',
  1460. )
  1461. })
  1462. // #11081
  1463. test('Props can be casted when mounting custom elements in component rendering functions', async () => {
  1464. const E = defineCustomElement(
  1465. defineAsyncComponent(() =>
  1466. Promise.resolve({
  1467. props: ['fooValue'],
  1468. setup(props) {
  1469. expect(props.fooValue).toBe('fooValue')
  1470. return () => h('div', props.fooValue)
  1471. },
  1472. }),
  1473. ),
  1474. )
  1475. customElements.define('my-el-async-4', E)
  1476. const R = defineComponent({
  1477. setup() {
  1478. const fooValue = ref('fooValue')
  1479. return () => {
  1480. return h('div', null, [
  1481. h('my-el-async-4', {
  1482. fooValue: fooValue.value,
  1483. }),
  1484. ])
  1485. }
  1486. },
  1487. })
  1488. const app = createApp(R)
  1489. app.mount(container)
  1490. await new Promise(r => setTimeout(r))
  1491. const e = container.querySelector('my-el-async-4') as VueElement
  1492. expect(e.shadowRoot!.innerHTML).toBe(`<div>fooValue</div>`)
  1493. app.unmount()
  1494. })
  1495. // #11276
  1496. test('delete prop on attr removal', async () => {
  1497. const E = defineCustomElement({
  1498. props: {
  1499. boo: {
  1500. type: Boolean,
  1501. },
  1502. },
  1503. render() {
  1504. return this.boo + ',' + typeof this.boo
  1505. },
  1506. })
  1507. customElements.define('el-attr-removal', E)
  1508. container.innerHTML = '<el-attr-removal boo>'
  1509. const e = container.childNodes[0] as VueElement
  1510. expect(e.shadowRoot!.innerHTML).toBe(`true,boolean`)
  1511. e.removeAttribute('boo')
  1512. await nextTick()
  1513. expect(e.shadowRoot!.innerHTML).toBe(`false,boolean`)
  1514. })
  1515. test('hyphenated attr removal', async () => {
  1516. const E = defineCustomElement({
  1517. props: {
  1518. fooBar: {
  1519. type: Boolean,
  1520. },
  1521. },
  1522. render() {
  1523. return this.fooBar
  1524. },
  1525. })
  1526. customElements.define('el-hyphenated-attr-removal', E)
  1527. const toggle = ref(true)
  1528. const Comp = {
  1529. render() {
  1530. return h('el-hyphenated-attr-removal', {
  1531. 'foo-bar': toggle.value ? '' : null,
  1532. })
  1533. },
  1534. }
  1535. render(h(Comp), container)
  1536. const el = container.children[0]
  1537. expect(el.hasAttribute('foo-bar')).toBe(true)
  1538. expect((el as any).outerHTML).toBe(
  1539. `<el-hyphenated-attr-removal foo-bar=""></el-hyphenated-attr-removal>`,
  1540. )
  1541. toggle.value = false
  1542. await nextTick()
  1543. expect(el.hasAttribute('foo-bar')).toBe(false)
  1544. expect((el as any).outerHTML).toBe(
  1545. `<el-hyphenated-attr-removal></el-hyphenated-attr-removal>`,
  1546. )
  1547. })
  1548. })