customElement.spec.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749
  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("child components should not inject styles to root element's shadow root w/ shadowRoot false", async () => {
  838. const Bar = defineComponent({
  839. styles: [`div { color: green; }`],
  840. render() {
  841. return 'bar'
  842. },
  843. })
  844. const Baz = () => h(Bar)
  845. const Foo = defineCustomElement(
  846. {
  847. render() {
  848. return [h(Baz)]
  849. },
  850. },
  851. { shadowRoot: false },
  852. )
  853. customElements.define('my-foo-with-shadowroot-false', Foo)
  854. container.innerHTML = `<my-foo-with-shadowroot-false></my-foo-with-shadowroot-false>`
  855. const el = container.childNodes[0] as VueElement
  856. const style = el.shadowRoot?.querySelector('style')
  857. expect(style).toBeUndefined()
  858. })
  859. test('with nonce', () => {
  860. const Foo = defineCustomElement(
  861. {
  862. styles: [`div { color: red; }`],
  863. render() {
  864. return h('div', 'hello')
  865. },
  866. },
  867. { nonce: 'xxx' },
  868. )
  869. customElements.define('my-el-with-nonce', Foo)
  870. container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
  871. const el = container.childNodes[0] as VueElement
  872. const style = el.shadowRoot?.querySelector('style')!
  873. expect(style.getAttribute('nonce')).toBe('xxx')
  874. })
  875. })
  876. describe('async', () => {
  877. test('should work', async () => {
  878. const loaderSpy = vi.fn()
  879. const E = defineCustomElement(
  880. defineAsyncComponent(() => {
  881. loaderSpy()
  882. return Promise.resolve({
  883. props: ['msg'],
  884. styles: [`div { color: red }`],
  885. render(this: any) {
  886. return h('div', null, this.msg)
  887. },
  888. })
  889. }),
  890. )
  891. customElements.define('my-el-async', E)
  892. container.innerHTML =
  893. `<my-el-async msg="hello"></my-el-async>` +
  894. `<my-el-async msg="world"></my-el-async>`
  895. await new Promise(r => setTimeout(r))
  896. // loader should be called only once
  897. expect(loaderSpy).toHaveBeenCalledTimes(1)
  898. const e1 = container.childNodes[0] as VueElement
  899. const e2 = container.childNodes[1] as VueElement
  900. // should inject styles
  901. expect(e1.shadowRoot!.innerHTML).toBe(
  902. `<style>div { color: red }</style><div>hello</div>`,
  903. )
  904. expect(e2.shadowRoot!.innerHTML).toBe(
  905. `<style>div { color: red }</style><div>world</div>`,
  906. )
  907. // attr
  908. e1.setAttribute('msg', 'attr')
  909. await nextTick()
  910. expect((e1 as any).msg).toBe('attr')
  911. expect(e1.shadowRoot!.innerHTML).toBe(
  912. `<style>div { color: red }</style><div>attr</div>`,
  913. )
  914. // props
  915. expect(`msg` in e1).toBe(true)
  916. ;(e1 as any).msg = 'prop'
  917. expect(e1.getAttribute('msg')).toBe('prop')
  918. expect(e1.shadowRoot!.innerHTML).toBe(
  919. `<style>div { color: red }</style><div>prop</div>`,
  920. )
  921. })
  922. test('set DOM property before resolve', async () => {
  923. const E = defineCustomElement(
  924. defineAsyncComponent(() => {
  925. return Promise.resolve({
  926. props: ['msg'],
  927. setup(props) {
  928. expect(typeof props.msg).toBe('string')
  929. },
  930. render(this: any) {
  931. return h('div', this.msg)
  932. },
  933. })
  934. }),
  935. )
  936. customElements.define('my-el-async-2', E)
  937. const e1 = new E()
  938. // set property before connect
  939. e1.msg = 'hello'
  940. const e2 = new E()
  941. container.appendChild(e1)
  942. container.appendChild(e2)
  943. // set property after connect but before resolve
  944. e2.msg = 'world'
  945. await new Promise(r => setTimeout(r))
  946. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  947. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  948. e1.msg = 'world'
  949. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  950. e2.msg = 'hello'
  951. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  952. })
  953. test('Number prop casting before resolve', async () => {
  954. const E = defineCustomElement(
  955. defineAsyncComponent(() => {
  956. return Promise.resolve({
  957. props: { n: Number },
  958. setup(props) {
  959. expect(props.n).toBe(20)
  960. },
  961. render(this: any) {
  962. return h('div', this.n + ',' + typeof this.n)
  963. },
  964. })
  965. }),
  966. )
  967. customElements.define('my-el-async-3', E)
  968. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  969. await new Promise(r => setTimeout(r))
  970. const e = container.childNodes[0] as VueElement
  971. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  972. })
  973. test('with slots', async () => {
  974. const E = defineCustomElement(
  975. defineAsyncComponent(() => {
  976. return Promise.resolve({
  977. render(this: any) {
  978. return [
  979. h('div', null, [
  980. renderSlot(this.$slots, 'default', undefined, () => [
  981. h('div', 'fallback'),
  982. ]),
  983. ]),
  984. h('div', null, renderSlot(this.$slots, 'named')),
  985. ]
  986. },
  987. })
  988. }),
  989. )
  990. customElements.define('my-el-async-slots', E)
  991. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  992. await new Promise(r => setTimeout(r))
  993. const e = container.childNodes[0] as VueElement
  994. expect(e.shadowRoot!.innerHTML).toBe(
  995. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  996. )
  997. })
  998. })
  999. describe('shadowRoot: false', () => {
  1000. const E = defineCustomElement({
  1001. shadowRoot: false,
  1002. props: {
  1003. msg: {
  1004. type: String,
  1005. default: 'hello',
  1006. },
  1007. },
  1008. render() {
  1009. return h('div', this.msg)
  1010. },
  1011. })
  1012. customElements.define('my-el-shadowroot-false', E)
  1013. test('should work', async () => {
  1014. function raf() {
  1015. return new Promise(resolve => {
  1016. requestAnimationFrame(resolve)
  1017. })
  1018. }
  1019. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  1020. const e = container.childNodes[0] as VueElement
  1021. await raf()
  1022. expect(e).toBeInstanceOf(E)
  1023. expect(e._instance).toBeTruthy()
  1024. expect(e.innerHTML).toBe(`<div>hello</div>`)
  1025. expect(e.shadowRoot).toBe(null)
  1026. })
  1027. const toggle = ref(true)
  1028. const ES = defineCustomElement(
  1029. {
  1030. render() {
  1031. return [
  1032. renderSlot(this.$slots, 'default'),
  1033. toggle.value ? renderSlot(this.$slots, 'named') : null,
  1034. renderSlot(this.$slots, 'omitted', {}, () => [
  1035. h('div', 'fallback'),
  1036. ]),
  1037. ]
  1038. },
  1039. },
  1040. { shadowRoot: false },
  1041. )
  1042. customElements.define('my-el-shadowroot-false-slots', ES)
  1043. test('should render slots', async () => {
  1044. container.innerHTML =
  1045. `<my-el-shadowroot-false-slots>` +
  1046. `<span>default</span>text` +
  1047. `<div slot="named">named</div>` +
  1048. `</my-el-shadowroot-false-slots>`
  1049. const e = container.childNodes[0] as VueElement
  1050. // native slots allocation does not affect innerHTML, so we just
  1051. // verify that we've rendered the correct native slots here...
  1052. expect(e.innerHTML).toBe(
  1053. `<span>default</span>text` +
  1054. `<div slot="named">named</div>` +
  1055. `<div>fallback</div>`,
  1056. )
  1057. toggle.value = false
  1058. await nextTick()
  1059. expect(e.innerHTML).toBe(
  1060. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  1061. )
  1062. })
  1063. test('render nested customElement w/ shadowRoot false', async () => {
  1064. const calls: string[] = []
  1065. const Child = defineCustomElement(
  1066. {
  1067. setup() {
  1068. calls.push('child rendering')
  1069. onMounted(() => {
  1070. calls.push('child mounted')
  1071. })
  1072. },
  1073. render() {
  1074. return renderSlot(this.$slots, 'default')
  1075. },
  1076. },
  1077. { shadowRoot: false },
  1078. )
  1079. customElements.define('my-child', Child)
  1080. const Parent = defineCustomElement(
  1081. {
  1082. setup() {
  1083. calls.push('parent rendering')
  1084. onMounted(() => {
  1085. calls.push('parent mounted')
  1086. })
  1087. },
  1088. render() {
  1089. return renderSlot(this.$slots, 'default')
  1090. },
  1091. },
  1092. { shadowRoot: false },
  1093. )
  1094. customElements.define('my-parent', Parent)
  1095. const App = {
  1096. render() {
  1097. return h('my-parent', null, {
  1098. default: () => [
  1099. h('my-child', null, {
  1100. default: () => [h('span', null, 'default')],
  1101. }),
  1102. ],
  1103. })
  1104. },
  1105. }
  1106. const app = createApp(App)
  1107. app.mount(container)
  1108. await nextTick()
  1109. const e = container.childNodes[0] as VueElement
  1110. expect(e.innerHTML).toBe(
  1111. `<my-child data-v-app=""><span>default</span></my-child>`,
  1112. )
  1113. expect(calls).toEqual([
  1114. 'parent rendering',
  1115. 'parent mounted',
  1116. 'child rendering',
  1117. 'child mounted',
  1118. ])
  1119. app.unmount()
  1120. })
  1121. test('render nested Teleport w/ shadowRoot false', async () => {
  1122. const target = document.createElement('div')
  1123. const Child = defineCustomElement(
  1124. {
  1125. render() {
  1126. return h(
  1127. Teleport,
  1128. { to: target },
  1129. {
  1130. default: () => [renderSlot(this.$slots, 'default')],
  1131. },
  1132. )
  1133. },
  1134. },
  1135. { shadowRoot: false },
  1136. )
  1137. customElements.define('my-el-teleport-child', Child)
  1138. const Parent = defineCustomElement(
  1139. {
  1140. render() {
  1141. return renderSlot(this.$slots, 'default')
  1142. },
  1143. },
  1144. { shadowRoot: false },
  1145. )
  1146. customElements.define('my-el-teleport-parent', Parent)
  1147. const App = {
  1148. render() {
  1149. return h('my-el-teleport-parent', null, {
  1150. default: () => [
  1151. h('my-el-teleport-child', null, {
  1152. default: () => [h('span', null, 'default')],
  1153. }),
  1154. ],
  1155. })
  1156. },
  1157. }
  1158. const app = createApp(App)
  1159. app.mount(container)
  1160. await nextTick()
  1161. expect(target.innerHTML).toBe(`<span>default</span>`)
  1162. app.unmount()
  1163. })
  1164. test('toggle nested custom element with shadowRoot: false', async () => {
  1165. customElements.define(
  1166. 'my-el-child-shadow-false',
  1167. defineCustomElement(
  1168. {
  1169. render(ctx: any) {
  1170. return h('div', null, [renderSlot(ctx.$slots, 'default')])
  1171. },
  1172. },
  1173. { shadowRoot: false },
  1174. ),
  1175. )
  1176. const ChildWrapper = {
  1177. render() {
  1178. return h('my-el-child-shadow-false', null, 'child')
  1179. },
  1180. }
  1181. customElements.define(
  1182. 'my-el-parent-shadow-false',
  1183. defineCustomElement(
  1184. {
  1185. props: {
  1186. isShown: { type: Boolean, required: true },
  1187. },
  1188. render(ctx: any, _: any, $props: any) {
  1189. return $props.isShown
  1190. ? h('div', { key: 0 }, [renderSlot(ctx.$slots, 'default')])
  1191. : null
  1192. },
  1193. },
  1194. { shadowRoot: false },
  1195. ),
  1196. )
  1197. const ParentWrapper = {
  1198. props: {
  1199. isShown: { type: Boolean, required: true },
  1200. },
  1201. render(ctx: any, _: any, $props: any) {
  1202. return h('my-el-parent-shadow-false', { isShown: $props.isShown }, [
  1203. renderSlot(ctx.$slots, 'default'),
  1204. ])
  1205. },
  1206. }
  1207. const isShown = ref(true)
  1208. const App = {
  1209. render() {
  1210. return h(ParentWrapper, { isShown: isShown.value } as any, {
  1211. default: () => [h(ChildWrapper)],
  1212. })
  1213. },
  1214. }
  1215. const container = document.createElement('div')
  1216. document.body.appendChild(container)
  1217. const app = createApp(App)
  1218. app.mount(container)
  1219. expect(container.innerHTML).toBe(
  1220. `<my-el-parent-shadow-false is-shown="" data-v-app="">` +
  1221. `<div>` +
  1222. `<my-el-child-shadow-false data-v-app="">` +
  1223. `<div>child</div>` +
  1224. `</my-el-child-shadow-false>` +
  1225. `</div>` +
  1226. `</my-el-parent-shadow-false>`,
  1227. )
  1228. isShown.value = false
  1229. await nextTick()
  1230. expect(container.innerHTML).toBe(
  1231. `<my-el-parent-shadow-false data-v-app=""><!----></my-el-parent-shadow-false>`,
  1232. )
  1233. isShown.value = true
  1234. await nextTick()
  1235. expect(container.innerHTML).toBe(
  1236. `<my-el-parent-shadow-false data-v-app="" is-shown="">` +
  1237. `<div>` +
  1238. `<my-el-child-shadow-false data-v-app="">` +
  1239. `<div>child</div>` +
  1240. `</my-el-child-shadow-false>` +
  1241. `</div>` +
  1242. `</my-el-parent-shadow-false>`,
  1243. )
  1244. })
  1245. })
  1246. describe('helpers', () => {
  1247. test('useHost', () => {
  1248. const Foo = defineCustomElement({
  1249. setup() {
  1250. const host = useHost()!
  1251. host.setAttribute('id', 'host')
  1252. return () => h('div', 'hello')
  1253. },
  1254. })
  1255. customElements.define('my-el-use-host', Foo)
  1256. container.innerHTML = `<my-el-use-host>`
  1257. const el = container.childNodes[0] as VueElement
  1258. expect(el.id).toBe('host')
  1259. })
  1260. test('useShadowRoot for style injection', () => {
  1261. const Foo = defineCustomElement({
  1262. setup() {
  1263. const root = useShadowRoot()!
  1264. const style = document.createElement('style')
  1265. style.innerHTML = `div { color: red; }`
  1266. root.appendChild(style)
  1267. return () => h('div', 'hello')
  1268. },
  1269. })
  1270. customElements.define('my-el-use-shadow-root', Foo)
  1271. container.innerHTML = `<my-el-use-shadow-root>`
  1272. const el = container.childNodes[0] as VueElement
  1273. const style = el.shadowRoot?.querySelector('style')!
  1274. expect(style.textContent).toBe(`div { color: red; }`)
  1275. })
  1276. })
  1277. describe('expose', () => {
  1278. test('expose attributes and callback', async () => {
  1279. type SetValue = (value: string) => void
  1280. let fn: MockedFunction<SetValue>
  1281. const E = defineCustomElement({
  1282. setup(_, { expose }) {
  1283. const value = ref('hello')
  1284. const setValue = (fn = vi.fn((_value: string) => {
  1285. value.value = _value
  1286. }))
  1287. expose({
  1288. setValue,
  1289. value,
  1290. })
  1291. return () => h('div', null, [value.value])
  1292. },
  1293. })
  1294. customElements.define('my-el-expose', E)
  1295. container.innerHTML = `<my-el-expose></my-el-expose>`
  1296. const e = container.childNodes[0] as VueElement & {
  1297. value: string
  1298. setValue: MockedFunction<SetValue>
  1299. }
  1300. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1301. expect(e.value).toBe('hello')
  1302. expect(e.setValue).toBe(fn!)
  1303. e.setValue('world')
  1304. expect(e.value).toBe('world')
  1305. await nextTick()
  1306. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1307. })
  1308. test('warning when exposing an existing property', () => {
  1309. const E = defineCustomElement({
  1310. props: {
  1311. value: String,
  1312. },
  1313. setup(props, { expose }) {
  1314. expose({
  1315. value: 'hello',
  1316. })
  1317. return () => h('div', null, [props.value])
  1318. },
  1319. })
  1320. customElements.define('my-el-expose-two', E)
  1321. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  1322. expect(
  1323. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  1324. ).toHaveBeenWarned()
  1325. })
  1326. })
  1327. test('async & nested custom elements', async () => {
  1328. let fooVal: string | undefined = ''
  1329. const E = defineCustomElement(
  1330. defineAsyncComponent(() => {
  1331. return Promise.resolve({
  1332. setup(props) {
  1333. provide('foo', 'foo')
  1334. },
  1335. render(this: any) {
  1336. return h('div', null, [renderSlot(this.$slots, 'default')])
  1337. },
  1338. })
  1339. }),
  1340. )
  1341. const EChild = defineCustomElement({
  1342. setup(props) {
  1343. fooVal = inject('foo')
  1344. },
  1345. render(this: any) {
  1346. return h('div', null, 'child')
  1347. },
  1348. })
  1349. customElements.define('my-el-async-nested-ce', E)
  1350. customElements.define('slotted-child', EChild)
  1351. container.innerHTML = `<my-el-async-nested-ce><div><slotted-child></slotted-child></div></my-el-async-nested-ce>`
  1352. await new Promise(r => setTimeout(r))
  1353. const e = container.childNodes[0] as VueElement
  1354. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1355. expect(fooVal).toBe('foo')
  1356. })
  1357. test('async & multiple levels of nested custom elements', async () => {
  1358. let fooVal: string | undefined = ''
  1359. let barVal: string | undefined = ''
  1360. const E = defineCustomElement(
  1361. defineAsyncComponent(() => {
  1362. return Promise.resolve({
  1363. setup(props) {
  1364. provide('foo', 'foo')
  1365. },
  1366. render(this: any) {
  1367. return h('div', null, [renderSlot(this.$slots, 'default')])
  1368. },
  1369. })
  1370. }),
  1371. )
  1372. const EChild = defineCustomElement({
  1373. setup(props) {
  1374. provide('bar', 'bar')
  1375. },
  1376. render(this: any) {
  1377. return h('div', null, [renderSlot(this.$slots, 'default')])
  1378. },
  1379. })
  1380. const EChild2 = defineCustomElement({
  1381. setup(props) {
  1382. fooVal = inject('foo')
  1383. barVal = inject('bar')
  1384. },
  1385. render(this: any) {
  1386. return h('div', null, 'child')
  1387. },
  1388. })
  1389. customElements.define('my-el-async-nested-m-ce', E)
  1390. customElements.define('slotted-child-m', EChild)
  1391. customElements.define('slotted-child2-m', EChild2)
  1392. container.innerHTML =
  1393. `<my-el-async-nested-m-ce>` +
  1394. `<div><slotted-child-m>` +
  1395. `<slotted-child2-m></slotted-child2-m>` +
  1396. `</slotted-child-m></div>` +
  1397. `</my-el-async-nested-m-ce>`
  1398. await new Promise(r => setTimeout(r))
  1399. const e = container.childNodes[0] as VueElement
  1400. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1401. expect(fooVal).toBe('foo')
  1402. expect(barVal).toBe('bar')
  1403. })
  1404. describe('configureApp', () => {
  1405. test('should work', () => {
  1406. const E = defineCustomElement(
  1407. () => {
  1408. const msg = inject('msg')
  1409. return () => h('div', msg!)
  1410. },
  1411. {
  1412. configureApp(app) {
  1413. app.provide('msg', 'app-injected')
  1414. },
  1415. },
  1416. )
  1417. customElements.define('my-element-with-app', E)
  1418. container.innerHTML = `<my-element-with-app></my-element-with-app>`
  1419. const e = container.childNodes[0] as VueElement
  1420. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1421. })
  1422. // #12448
  1423. test('work with async component', async () => {
  1424. const AsyncComp = defineAsyncComponent(() => {
  1425. return Promise.resolve({
  1426. render() {
  1427. const msg: string | undefined = inject('msg')
  1428. return h('div', {}, msg)
  1429. },
  1430. } as any)
  1431. })
  1432. const E = defineCustomElement(AsyncComp, {
  1433. configureApp(app) {
  1434. app.provide('msg', 'app-injected')
  1435. },
  1436. })
  1437. customElements.define('my-async-element-with-app', E)
  1438. container.innerHTML = `<my-async-element-with-app></my-async-element-with-app>`
  1439. const e = container.childNodes[0] as VueElement
  1440. await new Promise(r => setTimeout(r))
  1441. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1442. })
  1443. test('with hmr reload', async () => {
  1444. const __hmrId = '__hmrWithApp'
  1445. const def = defineComponent({
  1446. __hmrId,
  1447. setup() {
  1448. const msg = inject('msg')
  1449. return { msg }
  1450. },
  1451. render(this: any) {
  1452. return h('div', [h('span', this.msg), h('span', this.$foo)])
  1453. },
  1454. })
  1455. const E = defineCustomElement(def, {
  1456. configureApp(app) {
  1457. app.provide('msg', 'app-injected')
  1458. app.config.globalProperties.$foo = 'foo'
  1459. },
  1460. })
  1461. customElements.define('my-element-with-app-hmr', E)
  1462. container.innerHTML = `<my-element-with-app-hmr></my-element-with-app-hmr>`
  1463. const el = container.childNodes[0] as VueElement
  1464. expect(el.shadowRoot?.innerHTML).toBe(
  1465. `<div><span>app-injected</span><span>foo</span></div>`,
  1466. )
  1467. // hmr
  1468. __VUE_HMR_RUNTIME__.reload(__hmrId, def as any)
  1469. await nextTick()
  1470. expect(el.shadowRoot?.innerHTML).toBe(
  1471. `<div><span>app-injected</span><span>foo</span></div>`,
  1472. )
  1473. })
  1474. })
  1475. // #9885
  1476. test('avoid double mount when prop is set immediately after mount', () => {
  1477. customElements.define(
  1478. 'my-input-dupe',
  1479. defineCustomElement({
  1480. props: {
  1481. value: String,
  1482. },
  1483. render() {
  1484. return 'hello'
  1485. },
  1486. }),
  1487. )
  1488. const container = document.createElement('div')
  1489. document.body.appendChild(container)
  1490. createApp({
  1491. render() {
  1492. return h('div', [
  1493. h('my-input-dupe', {
  1494. onVnodeMounted(vnode) {
  1495. vnode.el!.value = 'fesfes'
  1496. },
  1497. }),
  1498. ])
  1499. },
  1500. }).mount(container)
  1501. expect(container.children[0].children[0].shadowRoot?.innerHTML).toBe(
  1502. 'hello',
  1503. )
  1504. })
  1505. // #11081
  1506. test('Props can be casted when mounting custom elements in component rendering functions', async () => {
  1507. const E = defineCustomElement(
  1508. defineAsyncComponent(() =>
  1509. Promise.resolve({
  1510. props: ['fooValue'],
  1511. setup(props) {
  1512. expect(props.fooValue).toBe('fooValue')
  1513. return () => h('div', props.fooValue)
  1514. },
  1515. }),
  1516. ),
  1517. )
  1518. customElements.define('my-el-async-4', E)
  1519. const R = defineComponent({
  1520. setup() {
  1521. const fooValue = ref('fooValue')
  1522. return () => {
  1523. return h('div', null, [
  1524. h('my-el-async-4', {
  1525. fooValue: fooValue.value,
  1526. }),
  1527. ])
  1528. }
  1529. },
  1530. })
  1531. const app = createApp(R)
  1532. app.mount(container)
  1533. await new Promise(r => setTimeout(r))
  1534. const e = container.querySelector('my-el-async-4') as VueElement
  1535. expect(e.shadowRoot!.innerHTML).toBe(`<div>fooValue</div>`)
  1536. app.unmount()
  1537. })
  1538. // #11276
  1539. test('delete prop on attr removal', async () => {
  1540. const E = defineCustomElement({
  1541. props: {
  1542. boo: {
  1543. type: Boolean,
  1544. },
  1545. },
  1546. render() {
  1547. return this.boo + ',' + typeof this.boo
  1548. },
  1549. })
  1550. customElements.define('el-attr-removal', E)
  1551. container.innerHTML = '<el-attr-removal boo>'
  1552. const e = container.childNodes[0] as VueElement
  1553. expect(e.shadowRoot!.innerHTML).toBe(`true,boolean`)
  1554. e.removeAttribute('boo')
  1555. await nextTick()
  1556. expect(e.shadowRoot!.innerHTML).toBe(`false,boolean`)
  1557. })
  1558. test('hyphenated attr removal', async () => {
  1559. const E = defineCustomElement({
  1560. props: {
  1561. fooBar: {
  1562. type: Boolean,
  1563. },
  1564. },
  1565. render() {
  1566. return this.fooBar
  1567. },
  1568. })
  1569. customElements.define('el-hyphenated-attr-removal', E)
  1570. const toggle = ref(true)
  1571. const Comp = {
  1572. render() {
  1573. return h('el-hyphenated-attr-removal', {
  1574. 'foo-bar': toggle.value ? '' : null,
  1575. })
  1576. },
  1577. }
  1578. render(h(Comp), container)
  1579. const el = container.children[0]
  1580. expect(el.hasAttribute('foo-bar')).toBe(true)
  1581. expect((el as any).outerHTML).toBe(
  1582. `<el-hyphenated-attr-removal foo-bar=""></el-hyphenated-attr-removal>`,
  1583. )
  1584. toggle.value = false
  1585. await nextTick()
  1586. expect(el.hasAttribute('foo-bar')).toBe(false)
  1587. expect((el as any).outerHTML).toBe(
  1588. `<el-hyphenated-attr-removal></el-hyphenated-attr-removal>`,
  1589. )
  1590. })
  1591. })