customElement.spec.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  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('attribute -> prop type casting', async () => {
  205. const E = defineCustomElement({
  206. props: {
  207. fooBar: Number, // test casting of camelCase prop names
  208. bar: Boolean,
  209. baz: String,
  210. },
  211. render() {
  212. return [
  213. this.fooBar,
  214. typeof this.fooBar,
  215. this.bar,
  216. typeof this.bar,
  217. this.baz,
  218. typeof this.baz,
  219. ].join(' ')
  220. },
  221. })
  222. customElements.define('my-el-props-cast', E)
  223. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  224. const e = container.childNodes[0] as VueElement
  225. expect(e.shadowRoot!.innerHTML).toBe(
  226. `1 number false boolean 12345 string`,
  227. )
  228. e.setAttribute('bar', '')
  229. await nextTick()
  230. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  231. e.setAttribute('foo-bar', '2e1')
  232. await nextTick()
  233. expect(e.shadowRoot!.innerHTML).toBe(
  234. `20 number true boolean 12345 string`,
  235. )
  236. e.setAttribute('baz', '2e1')
  237. await nextTick()
  238. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  239. })
  240. // #4772
  241. test('attr casting w/ programmatic creation', () => {
  242. const E = defineCustomElement({
  243. props: {
  244. foo: Number,
  245. },
  246. render() {
  247. return `foo type: ${typeof this.foo}`
  248. },
  249. })
  250. customElements.define('my-element-programmatic', E)
  251. const el = document.createElement('my-element-programmatic') as any
  252. el.setAttribute('foo', '123')
  253. container.appendChild(el)
  254. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  255. })
  256. test('handling properties set before upgrading', () => {
  257. const E = defineCustomElement({
  258. props: {
  259. foo: String,
  260. dataAge: Number,
  261. },
  262. setup(props) {
  263. expect(props.foo).toBe('hello')
  264. expect(props.dataAge).toBe(5)
  265. },
  266. render() {
  267. return h('div', `foo: ${this.foo}`)
  268. },
  269. })
  270. const el = document.createElement('my-el-upgrade') as any
  271. el.foo = 'hello'
  272. el.dataset.age = 5
  273. el.notProp = 1
  274. container.appendChild(el)
  275. customElements.define('my-el-upgrade', E)
  276. expect(el.shadowRoot.firstChild.innerHTML).toBe(`foo: hello`)
  277. // should not reflect if not declared as a prop
  278. expect(el.hasAttribute('not-prop')).toBe(false)
  279. })
  280. test('handle properties set before connecting', () => {
  281. const obj = { a: 1 }
  282. const E = defineCustomElement({
  283. props: {
  284. foo: String,
  285. post: Object,
  286. },
  287. setup(props) {
  288. expect(props.foo).toBe('hello')
  289. expect(props.post).toBe(obj)
  290. },
  291. render() {
  292. return JSON.stringify(this.post)
  293. },
  294. })
  295. customElements.define('my-el-preconnect', E)
  296. const el = document.createElement('my-el-preconnect') as any
  297. el.foo = 'hello'
  298. el.post = obj
  299. container.appendChild(el)
  300. expect(el.shadowRoot.innerHTML).toBe(JSON.stringify(obj))
  301. })
  302. // https://github.com/vuejs/core/issues/6163
  303. test('handle components with no props', async () => {
  304. const E = defineCustomElement({
  305. render() {
  306. return h('div', 'foo')
  307. },
  308. })
  309. customElements.define('my-element-noprops', E)
  310. const el = document.createElement('my-element-noprops')
  311. container.appendChild(el)
  312. await nextTick()
  313. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  314. })
  315. // #5793
  316. test('set number value in dom property', () => {
  317. const E = defineCustomElement({
  318. props: {
  319. 'max-age': Number,
  320. },
  321. render() {
  322. // @ts-expect-error
  323. return `max age: ${this.maxAge}/type: ${typeof this.maxAge}`
  324. },
  325. })
  326. customElements.define('my-element-number-property', E)
  327. const el = document.createElement('my-element-number-property') as any
  328. container.appendChild(el)
  329. el.maxAge = 50
  330. expect(el.maxAge).toBe(50)
  331. expect(el.shadowRoot.innerHTML).toBe('max age: 50/type: number')
  332. })
  333. // #9006
  334. test('should reflect default value', () => {
  335. const E = defineCustomElement({
  336. props: {
  337. value: {
  338. type: String,
  339. default: 'hi',
  340. },
  341. },
  342. render() {
  343. return this.value
  344. },
  345. })
  346. customElements.define('my-el-default-val', E)
  347. container.innerHTML = `<my-el-default-val></my-el-default-val>`
  348. const e = container.childNodes[0] as any
  349. expect(e.value).toBe('hi')
  350. })
  351. test('support direct setup function syntax with extra options', () => {
  352. const E = defineCustomElement(
  353. props => {
  354. return () => props.text
  355. },
  356. {
  357. props: {
  358. text: String,
  359. },
  360. },
  361. )
  362. customElements.define('my-el-setup-with-props', E)
  363. container.innerHTML = `<my-el-setup-with-props text="hello"></my-el-setup-with-props>`
  364. const e = container.childNodes[0] as VueElement
  365. expect(e.shadowRoot!.innerHTML).toBe('hello')
  366. })
  367. })
  368. describe('attrs', () => {
  369. const E = defineCustomElement({
  370. render() {
  371. return [h('div', null, this.$attrs.foo as string)]
  372. },
  373. })
  374. customElements.define('my-el-attrs', E)
  375. test('attrs via attribute', async () => {
  376. container.innerHTML = `<my-el-attrs foo="hello"></my-el-attrs>`
  377. const e = container.childNodes[0] as VueElement
  378. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  379. e.setAttribute('foo', 'changed')
  380. await nextTick()
  381. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div>')
  382. })
  383. test('non-declared properties should not show up in $attrs', () => {
  384. const e = new E()
  385. // @ts-expect-error
  386. e.foo = '123'
  387. container.appendChild(e)
  388. expect(e.shadowRoot!.innerHTML).toBe('<div></div>')
  389. })
  390. })
  391. describe('emits', () => {
  392. const CompDef = defineComponent({
  393. setup(_, { emit }) {
  394. emit('created')
  395. return () =>
  396. h('div', {
  397. onClick: () => {
  398. emit('my-click', 1)
  399. },
  400. onMousedown: () => {
  401. emit('myEvent', 1) // validate hyphenation
  402. },
  403. onWheel: () => {
  404. emit('my-wheel', { bubbles: true }, 1)
  405. },
  406. })
  407. },
  408. })
  409. const E = defineCustomElement(CompDef)
  410. customElements.define('my-el-emits', E)
  411. test('emit on connect', () => {
  412. const e = new E()
  413. const spy = vi.fn()
  414. e.addEventListener('created', spy)
  415. container.appendChild(e)
  416. expect(spy).toHaveBeenCalled()
  417. })
  418. test('emit on interaction', () => {
  419. container.innerHTML = `<my-el-emits></my-el-emits>`
  420. const e = container.childNodes[0] as VueElement
  421. const spy = vi.fn()
  422. e.addEventListener('my-click', spy)
  423. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  424. expect(spy).toHaveBeenCalledTimes(1)
  425. expect(spy.mock.calls[0][0]).toMatchObject({
  426. detail: [1],
  427. })
  428. })
  429. // #5373
  430. test('case transform for camelCase event', () => {
  431. container.innerHTML = `<my-el-emits></my-el-emits>`
  432. const e = container.childNodes[0] as VueElement
  433. const spy1 = vi.fn()
  434. e.addEventListener('myEvent', spy1)
  435. const spy2 = vi.fn()
  436. // emitting myEvent, but listening for my-event. This happens when
  437. // using the custom element in a Vue template
  438. e.addEventListener('my-event', spy2)
  439. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('mousedown'))
  440. expect(spy1).toHaveBeenCalledTimes(1)
  441. expect(spy2).toHaveBeenCalledTimes(1)
  442. })
  443. test('emit from within async component wrapper', async () => {
  444. const p = new Promise<typeof CompDef>(res => res(CompDef as any))
  445. const E = defineCustomElement(defineAsyncComponent(() => p))
  446. customElements.define('my-async-el-emits', E)
  447. container.innerHTML = `<my-async-el-emits></my-async-el-emits>`
  448. const e = container.childNodes[0] as VueElement
  449. const spy = vi.fn()
  450. e.addEventListener('my-click', spy)
  451. // this feels brittle but seems necessary to reach the node in the DOM.
  452. await customElements.whenDefined('my-async-el-emits')
  453. await nextTick()
  454. await nextTick()
  455. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  456. expect(spy).toHaveBeenCalled()
  457. expect(spy.mock.calls[0][0]).toMatchObject({
  458. detail: [1],
  459. })
  460. })
  461. // #7293
  462. test('emit in an async component wrapper with properties bound', async () => {
  463. const E = defineCustomElement(
  464. defineAsyncComponent(
  465. () => new Promise<typeof CompDef>(res => res(CompDef as any)),
  466. ),
  467. )
  468. customElements.define('my-async-el-props-emits', E)
  469. container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>`
  470. const e = container.childNodes[0] as VueElement
  471. const spy = vi.fn()
  472. e.addEventListener('my-click', spy)
  473. await customElements.whenDefined('my-async-el-props-emits')
  474. await nextTick()
  475. await nextTick()
  476. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  477. expect(spy).toHaveBeenCalled()
  478. expect(spy.mock.calls[0][0]).toMatchObject({
  479. detail: [1],
  480. })
  481. })
  482. test('emit with options', async () => {
  483. container.innerHTML = `<my-el-emits></my-el-emits>`
  484. const e = container.childNodes[0] as VueElement
  485. const spy = vi.fn()
  486. e.addEventListener('my-wheel', spy)
  487. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('wheel'))
  488. expect(spy).toHaveBeenCalledTimes(1)
  489. expect(spy.mock.calls[0][0]).toMatchObject({
  490. bubbles: true,
  491. detail: [{ bubbles: true }, 1],
  492. })
  493. })
  494. })
  495. describe('slots', () => {
  496. const E = defineCustomElement({
  497. render() {
  498. return [
  499. h('div', null, [
  500. renderSlot(this.$slots, 'default', undefined, () => [
  501. h('div', 'fallback'),
  502. ]),
  503. ]),
  504. h('div', null, renderSlot(this.$slots, 'named')),
  505. ]
  506. },
  507. })
  508. customElements.define('my-el-slots', E)
  509. test('render slots correctly', () => {
  510. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  511. const e = container.childNodes[0] as VueElement
  512. // native slots allocation does not affect innerHTML, so we just
  513. // verify that we've rendered the correct native slots here...
  514. expect(e.shadowRoot!.innerHTML).toBe(
  515. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  516. )
  517. })
  518. })
  519. describe('provide/inject', () => {
  520. const Consumer = defineCustomElement({
  521. setup() {
  522. const foo = inject<Ref>('foo')!
  523. return () => h('div', foo.value)
  524. },
  525. })
  526. customElements.define('my-consumer', Consumer)
  527. test('over nested usage', async () => {
  528. const foo = ref('injected!')
  529. const Provider = defineCustomElement({
  530. provide: {
  531. foo,
  532. },
  533. render() {
  534. return h('my-consumer')
  535. },
  536. })
  537. customElements.define('my-provider', Provider)
  538. container.innerHTML = `<my-provider><my-provider>`
  539. const provider = container.childNodes[0] as VueElement
  540. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  541. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  542. foo.value = 'changed!'
  543. await nextTick()
  544. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  545. })
  546. test('over slot composition', async () => {
  547. const foo = ref('injected!')
  548. const Provider = defineCustomElement({
  549. provide: {
  550. foo,
  551. },
  552. render() {
  553. return renderSlot(this.$slots, 'default')
  554. },
  555. })
  556. customElements.define('my-provider-2', Provider)
  557. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  558. const provider = container.childNodes[0]
  559. const consumer = provider.childNodes[0] as VueElement
  560. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  561. foo.value = 'changed!'
  562. await nextTick()
  563. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  564. })
  565. test('inherited from ancestors', async () => {
  566. const fooA = ref('FooA!')
  567. const fooB = ref('FooB!')
  568. const ProviderA = defineCustomElement({
  569. provide: {
  570. fooA,
  571. },
  572. render() {
  573. return h('provider-b')
  574. },
  575. })
  576. const ProviderB = defineCustomElement({
  577. provide: {
  578. fooB,
  579. },
  580. render() {
  581. return h('my-multi-consumer')
  582. },
  583. })
  584. const Consumer = defineCustomElement({
  585. setup() {
  586. const fooA = inject<Ref>('fooA')!
  587. const fooB = inject<Ref>('fooB')!
  588. return () => h('div', `${fooA.value} ${fooB.value}`)
  589. },
  590. })
  591. customElements.define('provider-a', ProviderA)
  592. customElements.define('provider-b', ProviderB)
  593. customElements.define('my-multi-consumer', Consumer)
  594. container.innerHTML = `<provider-a><provider-a>`
  595. const providerA = container.childNodes[0] as VueElement
  596. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  597. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  598. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  599. fooA.value = 'changedA!'
  600. fooB.value = 'changedB!'
  601. await nextTick()
  602. expect(consumer.shadowRoot!.innerHTML).toBe(
  603. `<div>changedA! changedB!</div>`,
  604. )
  605. })
  606. })
  607. describe('styles', () => {
  608. function assertStyles(el: VueElement, css: string[]) {
  609. const styles = el.shadowRoot?.querySelectorAll('style')!
  610. expect(styles.length).toBe(css.length) // should not duplicate multiple copies from Bar
  611. for (let i = 0; i < css.length; i++) {
  612. expect(styles[i].textContent).toBe(css[i])
  613. }
  614. }
  615. test('should attach styles to shadow dom', async () => {
  616. const def = defineComponent({
  617. __hmrId: 'foo',
  618. styles: [`div { color: red; }`],
  619. render() {
  620. return h('div', 'hello')
  621. },
  622. })
  623. const Foo = defineCustomElement(def)
  624. customElements.define('my-el-with-styles', Foo)
  625. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  626. const el = container.childNodes[0] as VueElement
  627. const style = el.shadowRoot?.querySelector('style')!
  628. expect(style.textContent).toBe(`div { color: red; }`)
  629. // hmr
  630. __VUE_HMR_RUNTIME__.reload('foo', {
  631. ...def,
  632. styles: [`div { color: blue; }`, `div { color: yellow; }`],
  633. } as any)
  634. await nextTick()
  635. assertStyles(el, [`div { color: blue; }`, `div { color: yellow; }`])
  636. })
  637. test("child components should inject styles to root element's shadow root", async () => {
  638. const Baz = () => h(Bar)
  639. const Bar = defineComponent({
  640. __hmrId: 'bar',
  641. styles: [`div { color: green; }`, `div { color: blue; }`],
  642. render() {
  643. return 'bar'
  644. },
  645. })
  646. const Foo = defineCustomElement({
  647. styles: [`div { color: red; }`],
  648. render() {
  649. return [h(Baz), h(Baz)]
  650. },
  651. })
  652. customElements.define('my-el-with-child-styles', Foo)
  653. container.innerHTML = `<my-el-with-child-styles></my-el-with-child-styles>`
  654. const el = container.childNodes[0] as VueElement
  655. // inject order should be child -> parent
  656. assertStyles(el, [
  657. `div { color: green; }`,
  658. `div { color: blue; }`,
  659. `div { color: red; }`,
  660. ])
  661. // hmr
  662. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  663. ...Bar,
  664. styles: [`div { color: red; }`, `div { color: yellow; }`],
  665. } as any)
  666. await nextTick()
  667. assertStyles(el, [
  668. `div { color: red; }`,
  669. `div { color: yellow; }`,
  670. `div { color: red; }`,
  671. ])
  672. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  673. ...Bar,
  674. styles: [`div { color: blue; }`],
  675. } as any)
  676. await nextTick()
  677. assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
  678. })
  679. test('with nonce', () => {
  680. const Foo = defineCustomElement(
  681. {
  682. styles: [`div { color: red; }`],
  683. render() {
  684. return h('div', 'hello')
  685. },
  686. },
  687. { nonce: 'xxx' },
  688. )
  689. customElements.define('my-el-with-nonce', Foo)
  690. container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
  691. const el = container.childNodes[0] as VueElement
  692. const style = el.shadowRoot?.querySelector('style')!
  693. expect(style.getAttribute('nonce')).toBe('xxx')
  694. })
  695. })
  696. describe('async', () => {
  697. test('should work', async () => {
  698. const loaderSpy = vi.fn()
  699. const E = defineCustomElement(
  700. defineAsyncComponent(() => {
  701. loaderSpy()
  702. return Promise.resolve({
  703. props: ['msg'],
  704. styles: [`div { color: red }`],
  705. render(this: any) {
  706. return h('div', null, this.msg)
  707. },
  708. })
  709. }),
  710. )
  711. customElements.define('my-el-async', E)
  712. container.innerHTML =
  713. `<my-el-async msg="hello"></my-el-async>` +
  714. `<my-el-async msg="world"></my-el-async>`
  715. await new Promise(r => setTimeout(r))
  716. // loader should be called only once
  717. expect(loaderSpy).toHaveBeenCalledTimes(1)
  718. const e1 = container.childNodes[0] as VueElement
  719. const e2 = container.childNodes[1] as VueElement
  720. // should inject styles
  721. expect(e1.shadowRoot!.innerHTML).toBe(
  722. `<style>div { color: red }</style><div>hello</div>`,
  723. )
  724. expect(e2.shadowRoot!.innerHTML).toBe(
  725. `<style>div { color: red }</style><div>world</div>`,
  726. )
  727. // attr
  728. e1.setAttribute('msg', 'attr')
  729. await nextTick()
  730. expect((e1 as any).msg).toBe('attr')
  731. expect(e1.shadowRoot!.innerHTML).toBe(
  732. `<style>div { color: red }</style><div>attr</div>`,
  733. )
  734. // props
  735. expect(`msg` in e1).toBe(true)
  736. ;(e1 as any).msg = 'prop'
  737. expect(e1.getAttribute('msg')).toBe('prop')
  738. expect(e1.shadowRoot!.innerHTML).toBe(
  739. `<style>div { color: red }</style><div>prop</div>`,
  740. )
  741. })
  742. test('set DOM property before resolve', async () => {
  743. const E = defineCustomElement(
  744. defineAsyncComponent(() => {
  745. return Promise.resolve({
  746. props: ['msg'],
  747. setup(props) {
  748. expect(typeof props.msg).toBe('string')
  749. },
  750. render(this: any) {
  751. return h('div', this.msg)
  752. },
  753. })
  754. }),
  755. )
  756. customElements.define('my-el-async-2', E)
  757. const e1 = new E()
  758. // set property before connect
  759. e1.msg = 'hello'
  760. const e2 = new E()
  761. container.appendChild(e1)
  762. container.appendChild(e2)
  763. // set property after connect but before resolve
  764. e2.msg = 'world'
  765. await new Promise(r => setTimeout(r))
  766. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  767. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  768. e1.msg = 'world'
  769. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  770. e2.msg = 'hello'
  771. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  772. })
  773. test('Number prop casting before resolve', async () => {
  774. const E = defineCustomElement(
  775. defineAsyncComponent(() => {
  776. return Promise.resolve({
  777. props: { n: Number },
  778. setup(props) {
  779. expect(props.n).toBe(20)
  780. },
  781. render(this: any) {
  782. return h('div', this.n + ',' + typeof this.n)
  783. },
  784. })
  785. }),
  786. )
  787. customElements.define('my-el-async-3', E)
  788. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  789. await new Promise(r => setTimeout(r))
  790. const e = container.childNodes[0] as VueElement
  791. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  792. })
  793. test('with slots', async () => {
  794. const E = defineCustomElement(
  795. defineAsyncComponent(() => {
  796. return Promise.resolve({
  797. render(this: any) {
  798. return [
  799. h('div', null, [
  800. renderSlot(this.$slots, 'default', undefined, () => [
  801. h('div', 'fallback'),
  802. ]),
  803. ]),
  804. h('div', null, renderSlot(this.$slots, 'named')),
  805. ]
  806. },
  807. })
  808. }),
  809. )
  810. customElements.define('my-el-async-slots', E)
  811. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  812. await new Promise(r => setTimeout(r))
  813. const e = container.childNodes[0] as VueElement
  814. expect(e.shadowRoot!.innerHTML).toBe(
  815. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  816. )
  817. })
  818. })
  819. describe('shadowRoot: false', () => {
  820. const E = defineCustomElement({
  821. shadowRoot: false,
  822. props: {
  823. msg: {
  824. type: String,
  825. default: 'hello',
  826. },
  827. },
  828. render() {
  829. return h('div', this.msg)
  830. },
  831. })
  832. customElements.define('my-el-shadowroot-false', E)
  833. test('should work', async () => {
  834. function raf() {
  835. return new Promise(resolve => {
  836. requestAnimationFrame(resolve)
  837. })
  838. }
  839. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  840. const e = container.childNodes[0] as VueElement
  841. await raf()
  842. expect(e).toBeInstanceOf(E)
  843. expect(e._instance).toBeTruthy()
  844. expect(e.innerHTML).toBe(`<div>hello</div>`)
  845. expect(e.shadowRoot).toBe(null)
  846. })
  847. const toggle = ref(true)
  848. const ES = defineCustomElement(
  849. {
  850. render() {
  851. return [
  852. renderSlot(this.$slots, 'default'),
  853. toggle.value ? renderSlot(this.$slots, 'named') : null,
  854. renderSlot(this.$slots, 'omitted', {}, () => [
  855. h('div', 'fallback'),
  856. ]),
  857. ]
  858. },
  859. },
  860. { shadowRoot: false },
  861. )
  862. customElements.define('my-el-shadowroot-false-slots', ES)
  863. test('should render slots', async () => {
  864. container.innerHTML =
  865. `<my-el-shadowroot-false-slots>` +
  866. `<span>default</span>text` +
  867. `<div slot="named">named</div>` +
  868. `</my-el-shadowroot-false-slots>`
  869. const e = container.childNodes[0] as VueElement
  870. // native slots allocation does not affect innerHTML, so we just
  871. // verify that we've rendered the correct native slots here...
  872. expect(e.innerHTML).toBe(
  873. `<span>default</span>text` +
  874. `<div slot="named">named</div>` +
  875. `<div>fallback</div>`,
  876. )
  877. toggle.value = false
  878. await nextTick()
  879. expect(e.innerHTML).toBe(
  880. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  881. )
  882. })
  883. test('render nested customElement w/ shadowRoot false', async () => {
  884. const calls: string[] = []
  885. const Child = defineCustomElement(
  886. {
  887. setup() {
  888. calls.push('child rendering')
  889. onMounted(() => {
  890. calls.push('child mounted')
  891. })
  892. },
  893. render() {
  894. return renderSlot(this.$slots, 'default')
  895. },
  896. },
  897. { shadowRoot: false },
  898. )
  899. customElements.define('my-child', Child)
  900. const Parent = defineCustomElement(
  901. {
  902. setup() {
  903. calls.push('parent rendering')
  904. onMounted(() => {
  905. calls.push('parent mounted')
  906. })
  907. },
  908. render() {
  909. return renderSlot(this.$slots, 'default')
  910. },
  911. },
  912. { shadowRoot: false },
  913. )
  914. customElements.define('my-parent', Parent)
  915. const App = {
  916. render() {
  917. return h('my-parent', null, {
  918. default: () => [
  919. h('my-child', null, {
  920. default: () => [h('span', null, 'default')],
  921. }),
  922. ],
  923. })
  924. },
  925. }
  926. const app = createApp(App)
  927. app.mount(container)
  928. await nextTick()
  929. const e = container.childNodes[0] as VueElement
  930. expect(e.innerHTML).toBe(
  931. `<my-child data-v-app=""><span>default</span></my-child>`,
  932. )
  933. expect(calls).toEqual([
  934. 'parent rendering',
  935. 'parent mounted',
  936. 'child rendering',
  937. 'child mounted',
  938. ])
  939. app.unmount()
  940. })
  941. test('render nested Teleport w/ shadowRoot false', async () => {
  942. const target = document.createElement('div')
  943. const Child = defineCustomElement(
  944. {
  945. render() {
  946. return h(
  947. Teleport,
  948. { to: target },
  949. {
  950. default: () => [renderSlot(this.$slots, 'default')],
  951. },
  952. )
  953. },
  954. },
  955. { shadowRoot: false },
  956. )
  957. customElements.define('my-el-teleport-child', Child)
  958. const Parent = defineCustomElement(
  959. {
  960. render() {
  961. return renderSlot(this.$slots, 'default')
  962. },
  963. },
  964. { shadowRoot: false },
  965. )
  966. customElements.define('my-el-teleport-parent', Parent)
  967. const App = {
  968. render() {
  969. return h('my-el-teleport-parent', null, {
  970. default: () => [
  971. h('my-el-teleport-child', null, {
  972. default: () => [h('span', null, 'default')],
  973. }),
  974. ],
  975. })
  976. },
  977. }
  978. const app = createApp(App)
  979. app.mount(container)
  980. await nextTick()
  981. expect(target.innerHTML).toBe(`<span>default</span>`)
  982. app.unmount()
  983. })
  984. })
  985. describe('helpers', () => {
  986. test('useHost', () => {
  987. const Foo = defineCustomElement({
  988. setup() {
  989. const host = useHost()!
  990. host.setAttribute('id', 'host')
  991. return () => h('div', 'hello')
  992. },
  993. })
  994. customElements.define('my-el-use-host', Foo)
  995. container.innerHTML = `<my-el-use-host>`
  996. const el = container.childNodes[0] as VueElement
  997. expect(el.id).toBe('host')
  998. })
  999. test('useShadowRoot for style injection', () => {
  1000. const Foo = defineCustomElement({
  1001. setup() {
  1002. const root = useShadowRoot()!
  1003. const style = document.createElement('style')
  1004. style.innerHTML = `div { color: red; }`
  1005. root.appendChild(style)
  1006. return () => h('div', 'hello')
  1007. },
  1008. })
  1009. customElements.define('my-el-use-shadow-root', Foo)
  1010. container.innerHTML = `<my-el-use-shadow-root>`
  1011. const el = container.childNodes[0] as VueElement
  1012. const style = el.shadowRoot?.querySelector('style')!
  1013. expect(style.textContent).toBe(`div { color: red; }`)
  1014. })
  1015. })
  1016. describe('expose', () => {
  1017. test('expose attributes and callback', async () => {
  1018. type SetValue = (value: string) => void
  1019. let fn: MockedFunction<SetValue>
  1020. const E = defineCustomElement({
  1021. setup(_, { expose }) {
  1022. const value = ref('hello')
  1023. const setValue = (fn = vi.fn((_value: string) => {
  1024. value.value = _value
  1025. }))
  1026. expose({
  1027. setValue,
  1028. value,
  1029. })
  1030. return () => h('div', null, [value.value])
  1031. },
  1032. })
  1033. customElements.define('my-el-expose', E)
  1034. container.innerHTML = `<my-el-expose></my-el-expose>`
  1035. const e = container.childNodes[0] as VueElement & {
  1036. value: string
  1037. setValue: MockedFunction<SetValue>
  1038. }
  1039. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1040. expect(e.value).toBe('hello')
  1041. expect(e.setValue).toBe(fn!)
  1042. e.setValue('world')
  1043. expect(e.value).toBe('world')
  1044. await nextTick()
  1045. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1046. })
  1047. test('warning when exposing an existing property', () => {
  1048. const E = defineCustomElement({
  1049. props: {
  1050. value: String,
  1051. },
  1052. setup(props, { expose }) {
  1053. expose({
  1054. value: 'hello',
  1055. })
  1056. return () => h('div', null, [props.value])
  1057. },
  1058. })
  1059. customElements.define('my-el-expose-two', E)
  1060. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  1061. expect(
  1062. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  1063. ).toHaveBeenWarned()
  1064. })
  1065. })
  1066. test('async & nested custom elements', async () => {
  1067. let fooVal: string | undefined = ''
  1068. const E = defineCustomElement(
  1069. defineAsyncComponent(() => {
  1070. return Promise.resolve({
  1071. setup(props) {
  1072. provide('foo', 'foo')
  1073. },
  1074. render(this: any) {
  1075. return h('div', null, [renderSlot(this.$slots, 'default')])
  1076. },
  1077. })
  1078. }),
  1079. )
  1080. const EChild = defineCustomElement({
  1081. setup(props) {
  1082. fooVal = inject('foo')
  1083. },
  1084. render(this: any) {
  1085. return h('div', null, 'child')
  1086. },
  1087. })
  1088. customElements.define('my-el-async-nested-ce', E)
  1089. customElements.define('slotted-child', EChild)
  1090. container.innerHTML = `<my-el-async-nested-ce><div><slotted-child></slotted-child></div></my-el-async-nested-ce>`
  1091. await new Promise(r => setTimeout(r))
  1092. const e = container.childNodes[0] as VueElement
  1093. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1094. expect(fooVal).toBe('foo')
  1095. })
  1096. test('async & multiple levels of nested custom elements', async () => {
  1097. let fooVal: string | undefined = ''
  1098. let barVal: string | undefined = ''
  1099. const E = defineCustomElement(
  1100. defineAsyncComponent(() => {
  1101. return Promise.resolve({
  1102. setup(props) {
  1103. provide('foo', 'foo')
  1104. },
  1105. render(this: any) {
  1106. return h('div', null, [renderSlot(this.$slots, 'default')])
  1107. },
  1108. })
  1109. }),
  1110. )
  1111. const EChild = defineCustomElement({
  1112. setup(props) {
  1113. provide('bar', 'bar')
  1114. },
  1115. render(this: any) {
  1116. return h('div', null, [renderSlot(this.$slots, 'default')])
  1117. },
  1118. })
  1119. const EChild2 = defineCustomElement({
  1120. setup(props) {
  1121. fooVal = inject('foo')
  1122. barVal = inject('bar')
  1123. },
  1124. render(this: any) {
  1125. return h('div', null, 'child')
  1126. },
  1127. })
  1128. customElements.define('my-el-async-nested-m-ce', E)
  1129. customElements.define('slotted-child-m', EChild)
  1130. customElements.define('slotted-child2-m', EChild2)
  1131. container.innerHTML =
  1132. `<my-el-async-nested-m-ce>` +
  1133. `<div><slotted-child-m>` +
  1134. `<slotted-child2-m></slotted-child2-m>` +
  1135. `</slotted-child-m></div>` +
  1136. `</my-el-async-nested-m-ce>`
  1137. await new Promise(r => setTimeout(r))
  1138. const e = container.childNodes[0] as VueElement
  1139. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1140. expect(fooVal).toBe('foo')
  1141. expect(barVal).toBe('bar')
  1142. })
  1143. describe('configureApp', () => {
  1144. test('should work', () => {
  1145. const E = defineCustomElement(
  1146. () => {
  1147. const msg = inject('msg')
  1148. return () => h('div', msg!)
  1149. },
  1150. {
  1151. configureApp(app) {
  1152. app.provide('msg', 'app-injected')
  1153. },
  1154. },
  1155. )
  1156. customElements.define('my-element-with-app', E)
  1157. container.innerHTML = `<my-element-with-app></my-element-with-app>`
  1158. const e = container.childNodes[0] as VueElement
  1159. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1160. })
  1161. })
  1162. // #9885
  1163. test('avoid double mount when prop is set immediately after mount', () => {
  1164. customElements.define(
  1165. 'my-input-dupe',
  1166. defineCustomElement({
  1167. props: {
  1168. value: String,
  1169. },
  1170. render() {
  1171. return 'hello'
  1172. },
  1173. }),
  1174. )
  1175. const container = document.createElement('div')
  1176. document.body.appendChild(container)
  1177. createApp({
  1178. render() {
  1179. return h('div', [
  1180. h('my-input-dupe', {
  1181. onVnodeMounted(vnode) {
  1182. vnode.el!.value = 'fesfes'
  1183. },
  1184. }),
  1185. ])
  1186. },
  1187. }).mount(container)
  1188. expect(container.children[0].children[0].shadowRoot?.innerHTML).toBe(
  1189. 'hello',
  1190. )
  1191. })
  1192. // #11081
  1193. test('Props can be casted when mounting custom elements in component rendering functions', async () => {
  1194. const E = defineCustomElement(
  1195. defineAsyncComponent(() =>
  1196. Promise.resolve({
  1197. props: ['fooValue'],
  1198. setup(props) {
  1199. expect(props.fooValue).toBe('fooValue')
  1200. return () => h('div', props.fooValue)
  1201. },
  1202. }),
  1203. ),
  1204. )
  1205. customElements.define('my-el-async-4', E)
  1206. const R = defineComponent({
  1207. setup() {
  1208. const fooValue = ref('fooValue')
  1209. return () => {
  1210. return h('div', null, [
  1211. h('my-el-async-4', {
  1212. fooValue: fooValue.value,
  1213. }),
  1214. ])
  1215. }
  1216. },
  1217. })
  1218. const app = createApp(R)
  1219. app.mount(container)
  1220. await new Promise(r => setTimeout(r))
  1221. const e = container.querySelector('my-el-async-4') as VueElement
  1222. expect(e.shadowRoot!.innerHTML).toBe(`<div>fooValue</div>`)
  1223. app.unmount()
  1224. })
  1225. // #11276
  1226. test('delete prop on attr removal', async () => {
  1227. const E = defineCustomElement({
  1228. props: {
  1229. boo: {
  1230. type: Boolean,
  1231. },
  1232. },
  1233. render() {
  1234. return this.boo + ',' + typeof this.boo
  1235. },
  1236. })
  1237. customElements.define('el-attr-removal', E)
  1238. container.innerHTML = '<el-attr-removal boo>'
  1239. const e = container.childNodes[0] as VueElement
  1240. expect(e.shadowRoot!.innerHTML).toBe(`true,boolean`)
  1241. e.removeAttribute('boo')
  1242. await nextTick()
  1243. expect(e.shadowRoot!.innerHTML).toBe(`false,boolean`)
  1244. })
  1245. })