customElement.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. import type { MockedFunction } from 'vitest'
  2. import {
  3. type Ref,
  4. type VueElement,
  5. createApp,
  6. defineAsyncComponent,
  7. defineComponent,
  8. defineCustomElement,
  9. h,
  10. inject,
  11. nextTick,
  12. ref,
  13. render,
  14. renderSlot,
  15. useShadowRoot,
  16. } from '../src'
  17. describe('defineCustomElement', () => {
  18. const container = document.createElement('div')
  19. document.body.appendChild(container)
  20. beforeEach(() => {
  21. container.innerHTML = ''
  22. })
  23. describe('mounting/unmount', () => {
  24. const E = defineCustomElement({
  25. props: {
  26. msg: {
  27. type: String,
  28. default: 'hello',
  29. },
  30. },
  31. render() {
  32. return h('div', this.msg)
  33. },
  34. })
  35. customElements.define('my-element', E)
  36. test('should work', () => {
  37. container.innerHTML = `<my-element></my-element>`
  38. const e = container.childNodes[0] as VueElement
  39. expect(e).toBeInstanceOf(E)
  40. expect(e._instance).toBeTruthy()
  41. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  42. })
  43. test('should work w/ manual instantiation', () => {
  44. const e = new E({ msg: 'inline' })
  45. // should lazy init
  46. expect(e._instance).toBe(null)
  47. // should initialize on connect
  48. container.appendChild(e)
  49. expect(e._instance).toBeTruthy()
  50. expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
  51. })
  52. test('should unmount on remove', async () => {
  53. container.innerHTML = `<my-element></my-element>`
  54. const e = container.childNodes[0] as VueElement
  55. container.removeChild(e)
  56. await nextTick()
  57. expect(e._instance).toBe(null)
  58. expect(e.shadowRoot!.innerHTML).toBe('')
  59. })
  60. // #10610
  61. test('When elements move, avoid prematurely disconnecting MutationObserver', async () => {
  62. const CustomInput = defineCustomElement({
  63. props: ['value'],
  64. emits: ['update'],
  65. setup(props, { emit }) {
  66. return () =>
  67. h('input', {
  68. type: 'number',
  69. value: props.value,
  70. onInput: (e: InputEvent) => {
  71. const num = (e.target! as HTMLInputElement).valueAsNumber
  72. emit('update', Number.isNaN(num) ? null : num)
  73. },
  74. })
  75. },
  76. })
  77. customElements.define('my-el-input', CustomInput)
  78. const num = ref('12')
  79. const containerComp = defineComponent({
  80. setup() {
  81. return () => {
  82. return h('div', [
  83. h('my-el-input', {
  84. value: num.value,
  85. onUpdate: ($event: CustomEvent) => {
  86. num.value = $event.detail[0]
  87. },
  88. }),
  89. h('div', { id: 'move' }),
  90. ])
  91. }
  92. },
  93. })
  94. const app = createApp(containerComp)
  95. app.mount(container)
  96. const myInputEl = container.querySelector('my-el-input')!
  97. const inputEl = myInputEl.shadowRoot!.querySelector('input')!
  98. await nextTick()
  99. expect(inputEl.value).toBe('12')
  100. const moveEl = container.querySelector('#move')!
  101. moveEl.append(myInputEl)
  102. await nextTick()
  103. myInputEl.removeAttribute('value')
  104. await nextTick()
  105. expect(inputEl.value).toBe('')
  106. })
  107. test('should not unmount on move', async () => {
  108. container.innerHTML = `<div><my-element></my-element></div>`
  109. const e = container.childNodes[0].childNodes[0] as VueElement
  110. const i = e._instance
  111. // moving from one parent to another - this will trigger both disconnect
  112. // and connected callbacks synchronously
  113. container.appendChild(e)
  114. await nextTick()
  115. // should be the same instance
  116. expect(e._instance).toBe(i)
  117. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  118. })
  119. test('remove then insert again', async () => {
  120. container.innerHTML = `<my-element></my-element>`
  121. const e = container.childNodes[0] as VueElement
  122. container.removeChild(e)
  123. await nextTick()
  124. expect(e._instance).toBe(null)
  125. expect(e.shadowRoot!.innerHTML).toBe('')
  126. container.appendChild(e)
  127. expect(e._instance).toBeTruthy()
  128. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  129. })
  130. })
  131. describe('props', () => {
  132. const E = defineCustomElement({
  133. props: {
  134. foo: [String, null],
  135. bar: Object,
  136. bazQux: null,
  137. value: null,
  138. },
  139. render() {
  140. return [
  141. h('div', null, this.foo || ''),
  142. h('div', null, this.bazQux || (this.bar && this.bar.x)),
  143. ]
  144. },
  145. })
  146. customElements.define('my-el-props', E)
  147. test('renders custom element w/ correct object prop value', () => {
  148. render(h('my-el-props', { value: { x: 1 } }), container)
  149. const el = container.children[0]
  150. expect((el as any).value).toEqual({ x: 1 })
  151. })
  152. test('props via attribute', async () => {
  153. // bazQux should map to `baz-qux` attribute
  154. container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
  155. const e = container.childNodes[0] as VueElement
  156. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
  157. // change attr
  158. e.setAttribute('foo', 'changed')
  159. await nextTick()
  160. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
  161. e.setAttribute('baz-qux', 'changed')
  162. await nextTick()
  163. expect(e.shadowRoot!.innerHTML).toBe(
  164. '<div>changed</div><div>changed</div>',
  165. )
  166. })
  167. test('props via properties', async () => {
  168. const e = new E()
  169. e.foo = 'one'
  170. e.bar = { x: 'two' }
  171. container.appendChild(e)
  172. expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
  173. // reflect
  174. // should reflect primitive value
  175. expect(e.getAttribute('foo')).toBe('one')
  176. // should not reflect rich data
  177. expect(e.hasAttribute('bar')).toBe(false)
  178. e.foo = 'three'
  179. await nextTick()
  180. expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
  181. expect(e.getAttribute('foo')).toBe('three')
  182. e.foo = null
  183. await nextTick()
  184. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  185. expect(e.hasAttribute('foo')).toBe(false)
  186. e.foo = undefined
  187. await nextTick()
  188. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
  189. expect(e.hasAttribute('foo')).toBe(false)
  190. expect(e.foo).toBe(undefined)
  191. e.bazQux = 'four'
  192. await nextTick()
  193. expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
  194. expect(e.getAttribute('baz-qux')).toBe('four')
  195. })
  196. test('attribute -> prop type casting', async () => {
  197. const E = defineCustomElement({
  198. props: {
  199. fooBar: Number, // test casting of camelCase prop names
  200. bar: Boolean,
  201. baz: String,
  202. },
  203. render() {
  204. return [
  205. this.fooBar,
  206. typeof this.fooBar,
  207. this.bar,
  208. typeof this.bar,
  209. this.baz,
  210. typeof this.baz,
  211. ].join(' ')
  212. },
  213. })
  214. customElements.define('my-el-props-cast', E)
  215. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  216. const e = container.childNodes[0] as VueElement
  217. expect(e.shadowRoot!.innerHTML).toBe(
  218. `1 number false boolean 12345 string`,
  219. )
  220. e.setAttribute('bar', '')
  221. await nextTick()
  222. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  223. e.setAttribute('foo-bar', '2e1')
  224. await nextTick()
  225. expect(e.shadowRoot!.innerHTML).toBe(
  226. `20 number true boolean 12345 string`,
  227. )
  228. e.setAttribute('baz', '2e1')
  229. await nextTick()
  230. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  231. })
  232. // #4772
  233. test('attr casting w/ programmatic creation', () => {
  234. const E = defineCustomElement({
  235. props: {
  236. foo: Number,
  237. },
  238. render() {
  239. return `foo type: ${typeof this.foo}`
  240. },
  241. })
  242. customElements.define('my-element-programmatic', E)
  243. const el = document.createElement('my-element-programmatic') as any
  244. el.setAttribute('foo', '123')
  245. container.appendChild(el)
  246. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  247. })
  248. test('handling properties set before upgrading', () => {
  249. const E = defineCustomElement({
  250. props: {
  251. foo: String,
  252. dataAge: Number,
  253. },
  254. setup(props) {
  255. expect(props.foo).toBe('hello')
  256. expect(props.dataAge).toBe(5)
  257. },
  258. render() {
  259. return h('div', `foo: ${this.foo}`)
  260. },
  261. })
  262. const el = document.createElement('my-el-upgrade') as any
  263. el.foo = 'hello'
  264. el.dataset.age = 5
  265. el.notProp = 1
  266. container.appendChild(el)
  267. customElements.define('my-el-upgrade', E)
  268. expect(el.shadowRoot.firstChild.innerHTML).toBe(`foo: hello`)
  269. // should not reflect if not declared as a prop
  270. expect(el.hasAttribute('not-prop')).toBe(false)
  271. })
  272. test('handle properties set before connecting', () => {
  273. const obj = { a: 1 }
  274. const E = defineCustomElement({
  275. props: {
  276. foo: String,
  277. post: Object,
  278. },
  279. setup(props) {
  280. expect(props.foo).toBe('hello')
  281. expect(props.post).toBe(obj)
  282. },
  283. render() {
  284. return JSON.stringify(this.post)
  285. },
  286. })
  287. customElements.define('my-el-preconnect', E)
  288. const el = document.createElement('my-el-preconnect') as any
  289. el.foo = 'hello'
  290. el.post = obj
  291. container.appendChild(el)
  292. expect(el.shadowRoot.innerHTML).toBe(JSON.stringify(obj))
  293. })
  294. // https://github.com/vuejs/core/issues/6163
  295. test('handle components with no props', async () => {
  296. const E = defineCustomElement({
  297. render() {
  298. return h('div', 'foo')
  299. },
  300. })
  301. customElements.define('my-element-noprops', E)
  302. const el = document.createElement('my-element-noprops')
  303. container.appendChild(el)
  304. await nextTick()
  305. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  306. })
  307. // # 5793
  308. test('set number value in dom property', () => {
  309. const E = defineCustomElement({
  310. props: {
  311. 'max-age': Number,
  312. },
  313. render() {
  314. // @ts-expect-error
  315. return `max age: ${this.maxAge}/type: ${typeof this.maxAge}`
  316. },
  317. })
  318. customElements.define('my-element-number-property', E)
  319. const el = document.createElement('my-element-number-property') as any
  320. container.appendChild(el)
  321. el.maxAge = 50
  322. expect(el.maxAge).toBe(50)
  323. expect(el.shadowRoot.innerHTML).toBe('max age: 50/type: number')
  324. })
  325. test('support direct setup function syntax with extra options', () => {
  326. const E = defineCustomElement(
  327. props => {
  328. return () => props.text
  329. },
  330. {
  331. props: {
  332. text: String,
  333. },
  334. },
  335. )
  336. customElements.define('my-el-setup-with-props', E)
  337. container.innerHTML = `<my-el-setup-with-props text="hello"></my-el-setup-with-props>`
  338. const e = container.childNodes[0] as VueElement
  339. expect(e.shadowRoot!.innerHTML).toBe('hello')
  340. })
  341. })
  342. describe('attrs', () => {
  343. const E = defineCustomElement({
  344. render() {
  345. return [h('div', null, this.$attrs.foo as string)]
  346. },
  347. })
  348. customElements.define('my-el-attrs', E)
  349. test('attrs via attribute', async () => {
  350. container.innerHTML = `<my-el-attrs foo="hello"></my-el-attrs>`
  351. const e = container.childNodes[0] as VueElement
  352. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  353. e.setAttribute('foo', 'changed')
  354. await nextTick()
  355. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div>')
  356. })
  357. test('non-declared properties should not show up in $attrs', () => {
  358. const e = new E()
  359. // @ts-expect-error
  360. e.foo = '123'
  361. container.appendChild(e)
  362. expect(e.shadowRoot!.innerHTML).toBe('<div></div>')
  363. })
  364. })
  365. describe('emits', () => {
  366. const CompDef = defineComponent({
  367. setup(_, { emit }) {
  368. emit('created')
  369. return () =>
  370. h('div', {
  371. onClick: () => {
  372. emit('my-click', 1)
  373. },
  374. onMousedown: () => {
  375. emit('myEvent', 1) // validate hyphenation
  376. },
  377. onWheel: () => {
  378. emit('my-wheel', { bubbles: true }, 1)
  379. },
  380. })
  381. },
  382. })
  383. const E = defineCustomElement(CompDef)
  384. customElements.define('my-el-emits', E)
  385. test('emit on connect', () => {
  386. const e = new E()
  387. const spy = vi.fn()
  388. e.addEventListener('created', spy)
  389. container.appendChild(e)
  390. expect(spy).toHaveBeenCalled()
  391. })
  392. test('emit on interaction', () => {
  393. container.innerHTML = `<my-el-emits></my-el-emits>`
  394. const e = container.childNodes[0] as VueElement
  395. const spy = vi.fn()
  396. e.addEventListener('my-click', spy)
  397. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  398. expect(spy).toHaveBeenCalledTimes(1)
  399. expect(spy.mock.calls[0][0]).toMatchObject({
  400. detail: [1],
  401. })
  402. })
  403. // #5373
  404. test('case transform for camelCase event', () => {
  405. container.innerHTML = `<my-el-emits></my-el-emits>`
  406. const e = container.childNodes[0] as VueElement
  407. const spy1 = vi.fn()
  408. e.addEventListener('myEvent', spy1)
  409. const spy2 = vi.fn()
  410. // emitting myEvent, but listening for my-event. This happens when
  411. // using the custom element in a Vue template
  412. e.addEventListener('my-event', spy2)
  413. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('mousedown'))
  414. expect(spy1).toHaveBeenCalledTimes(1)
  415. expect(spy2).toHaveBeenCalledTimes(1)
  416. })
  417. test('emit from within async component wrapper', async () => {
  418. const p = new Promise<typeof CompDef>(res => res(CompDef as any))
  419. const E = defineCustomElement(defineAsyncComponent(() => p))
  420. customElements.define('my-async-el-emits', E)
  421. container.innerHTML = `<my-async-el-emits></my-async-el-emits>`
  422. const e = container.childNodes[0] as VueElement
  423. const spy = vi.fn()
  424. e.addEventListener('my-click', spy)
  425. // this feels brittle but seems necessary to reach the node in the DOM.
  426. await customElements.whenDefined('my-async-el-emits')
  427. await nextTick()
  428. await nextTick()
  429. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  430. expect(spy).toHaveBeenCalled()
  431. expect(spy.mock.calls[0][0]).toMatchObject({
  432. detail: [1],
  433. })
  434. })
  435. // #7293
  436. test('emit in an async component wrapper with properties bound', async () => {
  437. const E = defineCustomElement(
  438. defineAsyncComponent(
  439. () => new Promise<typeof CompDef>(res => res(CompDef as any)),
  440. ),
  441. )
  442. customElements.define('my-async-el-props-emits', E)
  443. container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>`
  444. const e = container.childNodes[0] as VueElement
  445. const spy = vi.fn()
  446. e.addEventListener('my-click', spy)
  447. await customElements.whenDefined('my-async-el-props-emits')
  448. await nextTick()
  449. await nextTick()
  450. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  451. expect(spy).toHaveBeenCalled()
  452. expect(spy.mock.calls[0][0]).toMatchObject({
  453. detail: [1],
  454. })
  455. })
  456. test('emit with options', async () => {
  457. container.innerHTML = `<my-el-emits></my-el-emits>`
  458. const e = container.childNodes[0] as VueElement
  459. const spy = vi.fn()
  460. e.addEventListener('my-wheel', spy)
  461. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('wheel'))
  462. expect(spy).toHaveBeenCalledTimes(1)
  463. expect(spy.mock.calls[0][0]).toMatchObject({
  464. bubbles: true,
  465. detail: [{ bubbles: true }, 1],
  466. })
  467. })
  468. })
  469. describe('slots', () => {
  470. const E = defineCustomElement({
  471. render() {
  472. return [
  473. h('div', null, [
  474. renderSlot(this.$slots, 'default', undefined, () => [
  475. h('div', 'fallback'),
  476. ]),
  477. ]),
  478. h('div', null, renderSlot(this.$slots, 'named')),
  479. ]
  480. },
  481. })
  482. customElements.define('my-el-slots', E)
  483. test('render slots correctly', () => {
  484. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  485. const e = container.childNodes[0] as VueElement
  486. // native slots allocation does not affect innerHTML, so we just
  487. // verify that we've rendered the correct native slots here...
  488. expect(e.shadowRoot!.innerHTML).toBe(
  489. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  490. )
  491. })
  492. })
  493. describe('provide/inject', () => {
  494. const Consumer = defineCustomElement({
  495. setup() {
  496. const foo = inject<Ref>('foo')!
  497. return () => h('div', foo.value)
  498. },
  499. })
  500. customElements.define('my-consumer', Consumer)
  501. test('over nested usage', async () => {
  502. const foo = ref('injected!')
  503. const Provider = defineCustomElement({
  504. provide: {
  505. foo,
  506. },
  507. render() {
  508. return h('my-consumer')
  509. },
  510. })
  511. customElements.define('my-provider', Provider)
  512. container.innerHTML = `<my-provider><my-provider>`
  513. const provider = container.childNodes[0] as VueElement
  514. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  515. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  516. foo.value = 'changed!'
  517. await nextTick()
  518. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  519. })
  520. test('over slot composition', async () => {
  521. const foo = ref('injected!')
  522. const Provider = defineCustomElement({
  523. provide: {
  524. foo,
  525. },
  526. render() {
  527. return renderSlot(this.$slots, 'default')
  528. },
  529. })
  530. customElements.define('my-provider-2', Provider)
  531. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  532. const provider = container.childNodes[0]
  533. const consumer = provider.childNodes[0] as VueElement
  534. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  535. foo.value = 'changed!'
  536. await nextTick()
  537. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  538. })
  539. test('inherited from ancestors', async () => {
  540. const fooA = ref('FooA!')
  541. const fooB = ref('FooB!')
  542. const ProviderA = defineCustomElement({
  543. provide: {
  544. fooA,
  545. },
  546. render() {
  547. return h('provider-b')
  548. },
  549. })
  550. const ProviderB = defineCustomElement({
  551. provide: {
  552. fooB,
  553. },
  554. render() {
  555. return h('my-multi-consumer')
  556. },
  557. })
  558. const Consumer = defineCustomElement({
  559. setup() {
  560. const fooA = inject<Ref>('fooA')!
  561. const fooB = inject<Ref>('fooB')!
  562. return () => h('div', `${fooA.value} ${fooB.value}`)
  563. },
  564. })
  565. customElements.define('provider-a', ProviderA)
  566. customElements.define('provider-b', ProviderB)
  567. customElements.define('my-multi-consumer', Consumer)
  568. container.innerHTML = `<provider-a><provider-a>`
  569. const providerA = container.childNodes[0] as VueElement
  570. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  571. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  572. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  573. fooA.value = 'changedA!'
  574. fooB.value = 'changedB!'
  575. await nextTick()
  576. expect(consumer.shadowRoot!.innerHTML).toBe(
  577. `<div>changedA! changedB!</div>`,
  578. )
  579. })
  580. })
  581. describe('styles', () => {
  582. test('should attach styles to shadow dom', () => {
  583. const Foo = defineCustomElement({
  584. styles: [`div { color: red; }`],
  585. render() {
  586. return h('div', 'hello')
  587. },
  588. })
  589. customElements.define('my-el-with-styles', Foo)
  590. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  591. const el = container.childNodes[0] as VueElement
  592. const style = el.shadowRoot?.querySelector('style')!
  593. expect(style.textContent).toBe(`div { color: red; }`)
  594. })
  595. })
  596. describe('async', () => {
  597. test('should work', async () => {
  598. const loaderSpy = vi.fn()
  599. const E = defineCustomElement(
  600. defineAsyncComponent(() => {
  601. loaderSpy()
  602. return Promise.resolve({
  603. props: ['msg'],
  604. styles: [`div { color: red }`],
  605. render(this: any) {
  606. return h('div', null, this.msg)
  607. },
  608. })
  609. }),
  610. )
  611. customElements.define('my-el-async', E)
  612. container.innerHTML =
  613. `<my-el-async msg="hello"></my-el-async>` +
  614. `<my-el-async msg="world"></my-el-async>`
  615. await new Promise(r => setTimeout(r))
  616. // loader should be called only once
  617. expect(loaderSpy).toHaveBeenCalledTimes(1)
  618. const e1 = container.childNodes[0] as VueElement
  619. const e2 = container.childNodes[1] as VueElement
  620. // should inject styles
  621. expect(e1.shadowRoot!.innerHTML).toBe(
  622. `<style>div { color: red }</style><div>hello</div>`,
  623. )
  624. expect(e2.shadowRoot!.innerHTML).toBe(
  625. `<style>div { color: red }</style><div>world</div>`,
  626. )
  627. // attr
  628. e1.setAttribute('msg', 'attr')
  629. await nextTick()
  630. expect((e1 as any).msg).toBe('attr')
  631. expect(e1.shadowRoot!.innerHTML).toBe(
  632. `<style>div { color: red }</style><div>attr</div>`,
  633. )
  634. // props
  635. expect(`msg` in e1).toBe(true)
  636. ;(e1 as any).msg = 'prop'
  637. expect(e1.getAttribute('msg')).toBe('prop')
  638. expect(e1.shadowRoot!.innerHTML).toBe(
  639. `<style>div { color: red }</style><div>prop</div>`,
  640. )
  641. })
  642. test('set DOM property before resolve', async () => {
  643. const E = defineCustomElement(
  644. defineAsyncComponent(() => {
  645. return Promise.resolve({
  646. props: ['msg'],
  647. setup(props) {
  648. expect(typeof props.msg).toBe('string')
  649. },
  650. render(this: any) {
  651. return h('div', this.msg)
  652. },
  653. })
  654. }),
  655. )
  656. customElements.define('my-el-async-2', E)
  657. const e1 = new E()
  658. // set property before connect
  659. e1.msg = 'hello'
  660. const e2 = new E()
  661. container.appendChild(e1)
  662. container.appendChild(e2)
  663. // set property after connect but before resolve
  664. e2.msg = 'world'
  665. await new Promise(r => setTimeout(r))
  666. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  667. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  668. e1.msg = 'world'
  669. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  670. e2.msg = 'hello'
  671. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  672. })
  673. test('Number prop casting before resolve', async () => {
  674. const E = defineCustomElement(
  675. defineAsyncComponent(() => {
  676. return Promise.resolve({
  677. props: { n: Number },
  678. setup(props) {
  679. expect(props.n).toBe(20)
  680. },
  681. render(this: any) {
  682. return h('div', this.n + ',' + typeof this.n)
  683. },
  684. })
  685. }),
  686. )
  687. customElements.define('my-el-async-3', E)
  688. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  689. await new Promise(r => setTimeout(r))
  690. const e = container.childNodes[0] as VueElement
  691. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  692. })
  693. test('with slots', async () => {
  694. const E = defineCustomElement(
  695. defineAsyncComponent(() => {
  696. return Promise.resolve({
  697. render(this: any) {
  698. return [
  699. h('div', null, [
  700. renderSlot(this.$slots, 'default', undefined, () => [
  701. h('div', 'fallback'),
  702. ]),
  703. ]),
  704. h('div', null, renderSlot(this.$slots, 'named')),
  705. ]
  706. },
  707. })
  708. }),
  709. )
  710. customElements.define('my-el-async-slots', E)
  711. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  712. await new Promise(r => setTimeout(r))
  713. const e = container.childNodes[0] as VueElement
  714. expect(e.shadowRoot!.innerHTML).toBe(
  715. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  716. )
  717. })
  718. })
  719. describe('shadowRoot: false', () => {
  720. const E = defineCustomElement({
  721. shadowRoot: false,
  722. props: {
  723. msg: {
  724. type: String,
  725. default: 'hello',
  726. },
  727. },
  728. render() {
  729. return h('div', this.msg)
  730. },
  731. })
  732. customElements.define('my-el-shadowroot-false', E)
  733. test('should work', async () => {
  734. function raf() {
  735. return new Promise(resolve => {
  736. requestAnimationFrame(resolve)
  737. })
  738. }
  739. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  740. const e = container.childNodes[0] as VueElement
  741. await raf()
  742. expect(e).toBeInstanceOf(E)
  743. expect(e._instance).toBeTruthy()
  744. expect(e.innerHTML).toBe(`<div>hello</div>`)
  745. expect(e.shadowRoot).toBe(null)
  746. })
  747. const toggle = ref(true)
  748. const ES = defineCustomElement({
  749. shadowRoot: false,
  750. render() {
  751. return [
  752. renderSlot(this.$slots, 'default'),
  753. toggle.value ? renderSlot(this.$slots, 'named') : null,
  754. renderSlot(this.$slots, 'omitted', {}, () => [h('div', 'fallback')]),
  755. ]
  756. },
  757. })
  758. customElements.define('my-el-shadowroot-false-slots', ES)
  759. test('should render slots', async () => {
  760. container.innerHTML =
  761. `<my-el-shadowroot-false-slots>` +
  762. `<span>default</span>text` +
  763. `<div slot="named">named</div>` +
  764. `</my-el-shadowroot-false-slots>`
  765. const e = container.childNodes[0] as VueElement
  766. // native slots allocation does not affect innerHTML, so we just
  767. // verify that we've rendered the correct native slots here...
  768. expect(e.innerHTML).toBe(
  769. `<span>default</span>text` +
  770. `<div slot="named">named</div>` +
  771. `<div>fallback</div>`,
  772. )
  773. toggle.value = false
  774. await nextTick()
  775. expect(e.innerHTML).toBe(
  776. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  777. )
  778. })
  779. })
  780. describe('useCustomElementRoot', () => {
  781. test('should work for style injection', () => {
  782. const Foo = defineCustomElement({
  783. setup() {
  784. const root = useShadowRoot()!
  785. const style = document.createElement('style')
  786. style.innerHTML = `div { color: red; }`
  787. root.appendChild(style)
  788. return () => h('div', 'hello')
  789. },
  790. })
  791. customElements.define('my-el', Foo)
  792. container.innerHTML = `<my-el></my-el>`
  793. const el = container.childNodes[0] as VueElement
  794. const style = el.shadowRoot?.querySelector('style')!
  795. expect(style.textContent).toBe(`div { color: red; }`)
  796. })
  797. })
  798. describe('expose', () => {
  799. test('expose attributes and callback', async () => {
  800. type SetValue = (value: string) => void
  801. let fn: MockedFunction<SetValue>
  802. const E = defineCustomElement({
  803. setup(_, { expose }) {
  804. const value = ref('hello')
  805. const setValue = (fn = vi.fn((_value: string) => {
  806. value.value = _value
  807. }))
  808. expose({
  809. setValue,
  810. value,
  811. })
  812. return () => h('div', null, [value.value])
  813. },
  814. })
  815. customElements.define('my-el-expose', E)
  816. container.innerHTML = `<my-el-expose></my-el-expose>`
  817. const e = container.childNodes[0] as VueElement & {
  818. value: string
  819. setValue: MockedFunction<SetValue>
  820. }
  821. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  822. expect(e.value).toBe('hello')
  823. expect(e.setValue).toBe(fn!)
  824. e.setValue('world')
  825. expect(e.value).toBe('world')
  826. await nextTick()
  827. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  828. })
  829. test('warning when exposing an existing property', () => {
  830. const E = defineCustomElement({
  831. props: {
  832. value: String,
  833. },
  834. setup(props, { expose }) {
  835. expose({
  836. value: 'hello',
  837. })
  838. return () => h('div', null, [props.value])
  839. },
  840. })
  841. customElements.define('my-el-expose-two', E)
  842. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  843. expect(
  844. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  845. ).toHaveBeenWarned()
  846. })
  847. })
  848. })