customElement.spec.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  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. test('render slot props', async () => {
  592. const foo = ref('foo')
  593. const E = defineCustomElement({
  594. render() {
  595. return [
  596. h(
  597. 'div',
  598. null,
  599. renderSlot(this.$slots, 'default', { class: foo.value }),
  600. ),
  601. ]
  602. },
  603. })
  604. customElements.define('my-el-slot-props', E)
  605. container.innerHTML = `<my-el-slot-props><span>hi</span></my-el-slot-props>`
  606. const e = container.childNodes[0] as VueElement
  607. expect(e.shadowRoot!.innerHTML).toBe(
  608. `<div><slot class="foo"></slot></div>`,
  609. )
  610. foo.value = 'bar'
  611. await nextTick()
  612. expect(e.shadowRoot!.innerHTML).toBe(
  613. `<div><slot class="bar"></slot></div>`,
  614. )
  615. })
  616. })
  617. describe('provide/inject', () => {
  618. const Consumer = defineCustomElement({
  619. setup() {
  620. const foo = inject<Ref>('foo')!
  621. return () => h('div', foo.value)
  622. },
  623. })
  624. customElements.define('my-consumer', Consumer)
  625. test('over nested usage', async () => {
  626. const foo = ref('injected!')
  627. const Provider = defineCustomElement({
  628. provide: {
  629. foo,
  630. },
  631. render() {
  632. return h('my-consumer')
  633. },
  634. })
  635. customElements.define('my-provider', Provider)
  636. container.innerHTML = `<my-provider><my-provider>`
  637. const provider = container.childNodes[0] as VueElement
  638. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  639. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  640. foo.value = 'changed!'
  641. await nextTick()
  642. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  643. })
  644. test('over slot composition', async () => {
  645. const foo = ref('injected!')
  646. const Provider = defineCustomElement({
  647. provide: {
  648. foo,
  649. },
  650. render() {
  651. return renderSlot(this.$slots, 'default')
  652. },
  653. })
  654. customElements.define('my-provider-2', Provider)
  655. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  656. const provider = container.childNodes[0]
  657. const consumer = provider.childNodes[0] as VueElement
  658. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  659. foo.value = 'changed!'
  660. await nextTick()
  661. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  662. })
  663. test('inherited from ancestors', async () => {
  664. const fooA = ref('FooA!')
  665. const fooB = ref('FooB!')
  666. const ProviderA = defineCustomElement({
  667. provide: {
  668. fooA,
  669. },
  670. render() {
  671. return h('provider-b')
  672. },
  673. })
  674. const ProviderB = defineCustomElement({
  675. provide: {
  676. fooB,
  677. },
  678. render() {
  679. return h('my-multi-consumer')
  680. },
  681. })
  682. const Consumer = defineCustomElement({
  683. setup() {
  684. const fooA = inject<Ref>('fooA')!
  685. const fooB = inject<Ref>('fooB')!
  686. return () => h('div', `${fooA.value} ${fooB.value}`)
  687. },
  688. })
  689. customElements.define('provider-a', ProviderA)
  690. customElements.define('provider-b', ProviderB)
  691. customElements.define('my-multi-consumer', Consumer)
  692. container.innerHTML = `<provider-a><provider-a>`
  693. const providerA = container.childNodes[0] as VueElement
  694. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  695. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  696. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  697. fooA.value = 'changedA!'
  698. fooB.value = 'changedB!'
  699. await nextTick()
  700. expect(consumer.shadowRoot!.innerHTML).toBe(
  701. `<div>changedA! changedB!</div>`,
  702. )
  703. })
  704. // #13212
  705. test('inherited from app context within nested elements', async () => {
  706. const outerValues: (string | undefined)[] = []
  707. const innerValues: (string | undefined)[] = []
  708. const innerChildValues: (string | undefined)[] = []
  709. const Outer = defineCustomElement(
  710. {
  711. setup() {
  712. outerValues.push(
  713. inject<string>('shared'),
  714. inject<string>('outer'),
  715. inject<string>('inner'),
  716. )
  717. },
  718. render() {
  719. return h('div', [renderSlot(this.$slots, 'default')])
  720. },
  721. },
  722. {
  723. configureApp(app) {
  724. app.provide('shared', 'shared')
  725. app.provide('outer', 'outer')
  726. },
  727. },
  728. )
  729. const Inner = defineCustomElement(
  730. {
  731. setup() {
  732. // ensure values are not self-injected
  733. provide('inner', 'inner-child')
  734. innerValues.push(
  735. inject<string>('shared'),
  736. inject<string>('outer'),
  737. inject<string>('inner'),
  738. )
  739. },
  740. render() {
  741. return h('div', [renderSlot(this.$slots, 'default')])
  742. },
  743. },
  744. {
  745. configureApp(app) {
  746. app.provide('outer', 'override-outer')
  747. app.provide('inner', 'inner')
  748. },
  749. },
  750. )
  751. const InnerChild = defineCustomElement({
  752. setup() {
  753. innerChildValues.push(
  754. inject<string>('shared'),
  755. inject<string>('outer'),
  756. inject<string>('inner'),
  757. )
  758. },
  759. render() {
  760. return h('div')
  761. },
  762. })
  763. customElements.define('provide-from-app-outer', Outer)
  764. customElements.define('provide-from-app-inner', Inner)
  765. customElements.define('provide-from-app-inner-child', InnerChild)
  766. container.innerHTML =
  767. '<provide-from-app-outer>' +
  768. '<provide-from-app-inner>' +
  769. '<provide-from-app-inner-child></provide-from-app-inner-child>' +
  770. '</provide-from-app-inner>' +
  771. '</provide-from-app-outer>'
  772. const outer = container.childNodes[0] as VueElement
  773. expect(outer.shadowRoot!.innerHTML).toBe('<div><slot></slot></div>')
  774. expect('[Vue warn]: injection "inner" not found.').toHaveBeenWarnedTimes(
  775. 1,
  776. )
  777. expect(
  778. '[Vue warn]: App already provides property with key "outer" inherited from its parent element. ' +
  779. 'It will be overwritten with the new value.',
  780. ).toHaveBeenWarnedTimes(1)
  781. expect(outerValues).toEqual(['shared', 'outer', undefined])
  782. expect(innerValues).toEqual(['shared', 'override-outer', 'inner'])
  783. expect(innerChildValues).toEqual([
  784. 'shared',
  785. 'override-outer',
  786. 'inner-child',
  787. ])
  788. })
  789. })
  790. describe('styles', () => {
  791. function assertStyles(el: VueElement, css: string[]) {
  792. const styles = el.shadowRoot?.querySelectorAll('style')!
  793. expect(styles.length).toBe(css.length) // should not duplicate multiple copies from Bar
  794. for (let i = 0; i < css.length; i++) {
  795. expect(styles[i].textContent).toBe(css[i])
  796. }
  797. }
  798. test('should attach styles to shadow dom', async () => {
  799. const def = defineComponent({
  800. __hmrId: 'foo',
  801. styles: [`div { color: red; }`],
  802. render() {
  803. return h('div', 'hello')
  804. },
  805. })
  806. const Foo = defineCustomElement(def)
  807. customElements.define('my-el-with-styles', Foo)
  808. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  809. const el = container.childNodes[0] as VueElement
  810. const style = el.shadowRoot?.querySelector('style')!
  811. expect(style.textContent).toBe(`div { color: red; }`)
  812. // hmr
  813. __VUE_HMR_RUNTIME__.reload('foo', {
  814. ...def,
  815. styles: [`div { color: blue; }`, `div { color: yellow; }`],
  816. } as any)
  817. await nextTick()
  818. assertStyles(el, [`div { color: blue; }`, `div { color: yellow; }`])
  819. })
  820. test("child components should inject styles to root element's shadow root", async () => {
  821. const Baz = () => h(Bar)
  822. const Bar = defineComponent({
  823. __hmrId: 'bar',
  824. styles: [`div { color: green; }`, `div { color: blue; }`],
  825. render() {
  826. return 'bar'
  827. },
  828. })
  829. const Foo = defineCustomElement({
  830. styles: [`div { color: red; }`],
  831. render() {
  832. return [h(Baz), h(Baz)]
  833. },
  834. })
  835. customElements.define('my-el-with-child-styles', Foo)
  836. container.innerHTML = `<my-el-with-child-styles></my-el-with-child-styles>`
  837. const el = container.childNodes[0] as VueElement
  838. // inject order should be child -> parent
  839. assertStyles(el, [
  840. `div { color: green; }`,
  841. `div { color: blue; }`,
  842. `div { color: red; }`,
  843. ])
  844. // hmr
  845. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  846. ...Bar,
  847. styles: [`div { color: red; }`, `div { color: yellow; }`],
  848. } as any)
  849. await nextTick()
  850. assertStyles(el, [
  851. `div { color: red; }`,
  852. `div { color: yellow; }`,
  853. `div { color: red; }`,
  854. ])
  855. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  856. ...Bar,
  857. styles: [`div { color: blue; }`],
  858. } as any)
  859. await nextTick()
  860. assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
  861. })
  862. test("child components should not inject styles to root element's shadow root w/ shadowRoot false", async () => {
  863. const Bar = defineComponent({
  864. styles: [`div { color: green; }`],
  865. render() {
  866. return 'bar'
  867. },
  868. })
  869. const Baz = () => h(Bar)
  870. const Foo = defineCustomElement(
  871. {
  872. render() {
  873. return [h(Baz)]
  874. },
  875. },
  876. { shadowRoot: false },
  877. )
  878. customElements.define('my-foo-with-shadowroot-false', Foo)
  879. container.innerHTML = `<my-foo-with-shadowroot-false></my-foo-with-shadowroot-false>`
  880. const el = container.childNodes[0] as VueElement
  881. const style = el.shadowRoot?.querySelector('style')
  882. expect(style).toBeUndefined()
  883. })
  884. test('with nonce', () => {
  885. const Foo = defineCustomElement(
  886. {
  887. styles: [`div { color: red; }`],
  888. render() {
  889. return h('div', 'hello')
  890. },
  891. },
  892. { nonce: 'xxx' },
  893. )
  894. customElements.define('my-el-with-nonce', Foo)
  895. container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
  896. const el = container.childNodes[0] as VueElement
  897. const style = el.shadowRoot?.querySelector('style')!
  898. expect(style.getAttribute('nonce')).toBe('xxx')
  899. })
  900. })
  901. describe('async', () => {
  902. test('should work', async () => {
  903. const loaderSpy = vi.fn()
  904. const E = defineCustomElement(
  905. defineAsyncComponent(() => {
  906. loaderSpy()
  907. return Promise.resolve({
  908. props: ['msg'],
  909. styles: [`div { color: red }`],
  910. render(this: any) {
  911. return h('div', null, this.msg)
  912. },
  913. })
  914. }),
  915. )
  916. customElements.define('my-el-async', E)
  917. container.innerHTML =
  918. `<my-el-async msg="hello"></my-el-async>` +
  919. `<my-el-async msg="world"></my-el-async>`
  920. await new Promise(r => setTimeout(r))
  921. // loader should be called only once
  922. expect(loaderSpy).toHaveBeenCalledTimes(1)
  923. const e1 = container.childNodes[0] as VueElement
  924. const e2 = container.childNodes[1] as VueElement
  925. // should inject styles
  926. expect(e1.shadowRoot!.innerHTML).toBe(
  927. `<style>div { color: red }</style><div>hello</div>`,
  928. )
  929. expect(e2.shadowRoot!.innerHTML).toBe(
  930. `<style>div { color: red }</style><div>world</div>`,
  931. )
  932. // attr
  933. e1.setAttribute('msg', 'attr')
  934. await nextTick()
  935. expect((e1 as any).msg).toBe('attr')
  936. expect(e1.shadowRoot!.innerHTML).toBe(
  937. `<style>div { color: red }</style><div>attr</div>`,
  938. )
  939. // props
  940. expect(`msg` in e1).toBe(true)
  941. ;(e1 as any).msg = 'prop'
  942. expect(e1.getAttribute('msg')).toBe('prop')
  943. expect(e1.shadowRoot!.innerHTML).toBe(
  944. `<style>div { color: red }</style><div>prop</div>`,
  945. )
  946. })
  947. test('set DOM property before resolve', async () => {
  948. const E = defineCustomElement(
  949. defineAsyncComponent(() => {
  950. return Promise.resolve({
  951. props: ['msg'],
  952. setup(props) {
  953. expect(typeof props.msg).toBe('string')
  954. },
  955. render(this: any) {
  956. return h('div', this.msg)
  957. },
  958. })
  959. }),
  960. )
  961. customElements.define('my-el-async-2', E)
  962. const e1 = new E()
  963. // set property before connect
  964. e1.msg = 'hello'
  965. const e2 = new E()
  966. container.appendChild(e1)
  967. container.appendChild(e2)
  968. // set property after connect but before resolve
  969. e2.msg = 'world'
  970. await new Promise(r => setTimeout(r))
  971. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  972. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  973. e1.msg = 'world'
  974. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  975. e2.msg = 'hello'
  976. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  977. })
  978. test('Number prop casting before resolve', async () => {
  979. const E = defineCustomElement(
  980. defineAsyncComponent(() => {
  981. return Promise.resolve({
  982. props: { n: Number },
  983. setup(props) {
  984. expect(props.n).toBe(20)
  985. },
  986. render(this: any) {
  987. return h('div', this.n + ',' + typeof this.n)
  988. },
  989. })
  990. }),
  991. )
  992. customElements.define('my-el-async-3', E)
  993. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  994. await new Promise(r => setTimeout(r))
  995. const e = container.childNodes[0] as VueElement
  996. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  997. })
  998. test('with slots', async () => {
  999. const E = defineCustomElement(
  1000. defineAsyncComponent(() => {
  1001. return Promise.resolve({
  1002. render(this: any) {
  1003. return [
  1004. h('div', null, [
  1005. renderSlot(this.$slots, 'default', undefined, () => [
  1006. h('div', 'fallback'),
  1007. ]),
  1008. ]),
  1009. h('div', null, renderSlot(this.$slots, 'named')),
  1010. ]
  1011. },
  1012. })
  1013. }),
  1014. )
  1015. customElements.define('my-el-async-slots', E)
  1016. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  1017. await new Promise(r => setTimeout(r))
  1018. const e = container.childNodes[0] as VueElement
  1019. expect(e.shadowRoot!.innerHTML).toBe(
  1020. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  1021. )
  1022. })
  1023. })
  1024. describe('shadowRoot: false', () => {
  1025. const E = defineCustomElement({
  1026. shadowRoot: false,
  1027. props: {
  1028. msg: {
  1029. type: String,
  1030. default: 'hello',
  1031. },
  1032. },
  1033. render() {
  1034. return h('div', this.msg)
  1035. },
  1036. })
  1037. customElements.define('my-el-shadowroot-false', E)
  1038. test('should work', async () => {
  1039. function raf() {
  1040. return new Promise(resolve => {
  1041. requestAnimationFrame(resolve)
  1042. })
  1043. }
  1044. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  1045. const e = container.childNodes[0] as VueElement
  1046. await raf()
  1047. expect(e).toBeInstanceOf(E)
  1048. expect(e._instance).toBeTruthy()
  1049. expect(e.innerHTML).toBe(`<div>hello</div>`)
  1050. expect(e.shadowRoot).toBe(null)
  1051. })
  1052. const toggle = ref(true)
  1053. const ES = defineCustomElement(
  1054. {
  1055. render() {
  1056. return [
  1057. renderSlot(this.$slots, 'default'),
  1058. toggle.value ? renderSlot(this.$slots, 'named') : null,
  1059. renderSlot(this.$slots, 'omitted', {}, () => [
  1060. h('div', 'fallback'),
  1061. ]),
  1062. ]
  1063. },
  1064. },
  1065. { shadowRoot: false },
  1066. )
  1067. customElements.define('my-el-shadowroot-false-slots', ES)
  1068. test('should render slots', async () => {
  1069. container.innerHTML =
  1070. `<my-el-shadowroot-false-slots>` +
  1071. `<span>default</span>text` +
  1072. `<div slot="named">named</div>` +
  1073. `</my-el-shadowroot-false-slots>`
  1074. const e = container.childNodes[0] as VueElement
  1075. // native slots allocation does not affect innerHTML, so we just
  1076. // verify that we've rendered the correct native slots here...
  1077. expect(e.innerHTML).toBe(
  1078. `<span>default</span>text` +
  1079. `<div slot="named">named</div>` +
  1080. `<div>fallback</div>`,
  1081. )
  1082. toggle.value = false
  1083. await nextTick()
  1084. expect(e.innerHTML).toBe(
  1085. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  1086. )
  1087. })
  1088. test('render nested customElement w/ shadowRoot false', async () => {
  1089. const calls: string[] = []
  1090. const Child = defineCustomElement(
  1091. {
  1092. setup() {
  1093. calls.push('child rendering')
  1094. onMounted(() => {
  1095. calls.push('child mounted')
  1096. })
  1097. },
  1098. render() {
  1099. return renderSlot(this.$slots, 'default')
  1100. },
  1101. },
  1102. { shadowRoot: false },
  1103. )
  1104. customElements.define('my-child', Child)
  1105. const Parent = defineCustomElement(
  1106. {
  1107. setup() {
  1108. calls.push('parent rendering')
  1109. onMounted(() => {
  1110. calls.push('parent mounted')
  1111. })
  1112. },
  1113. render() {
  1114. return renderSlot(this.$slots, 'default')
  1115. },
  1116. },
  1117. { shadowRoot: false },
  1118. )
  1119. customElements.define('my-parent', Parent)
  1120. const App = {
  1121. render() {
  1122. return h('my-parent', null, {
  1123. default: () => [
  1124. h('my-child', null, {
  1125. default: () => [h('span', null, 'default')],
  1126. }),
  1127. ],
  1128. })
  1129. },
  1130. }
  1131. const app = createApp(App)
  1132. app.mount(container)
  1133. await nextTick()
  1134. const e = container.childNodes[0] as VueElement
  1135. expect(e.innerHTML).toBe(
  1136. `<my-child data-v-app=""><span>default</span></my-child>`,
  1137. )
  1138. expect(calls).toEqual([
  1139. 'parent rendering',
  1140. 'parent mounted',
  1141. 'child rendering',
  1142. 'child mounted',
  1143. ])
  1144. app.unmount()
  1145. })
  1146. test('render nested Teleport w/ shadowRoot false', async () => {
  1147. const target = document.createElement('div')
  1148. const Child = defineCustomElement(
  1149. {
  1150. render() {
  1151. return h(
  1152. Teleport,
  1153. { to: target },
  1154. {
  1155. default: () => [renderSlot(this.$slots, 'default')],
  1156. },
  1157. )
  1158. },
  1159. },
  1160. { shadowRoot: false },
  1161. )
  1162. customElements.define('my-el-teleport-child', Child)
  1163. const Parent = defineCustomElement(
  1164. {
  1165. render() {
  1166. return renderSlot(this.$slots, 'default')
  1167. },
  1168. },
  1169. { shadowRoot: false },
  1170. )
  1171. customElements.define('my-el-teleport-parent', Parent)
  1172. const App = {
  1173. render() {
  1174. return h('my-el-teleport-parent', null, {
  1175. default: () => [
  1176. h('my-el-teleport-child', null, {
  1177. default: () => [h('span', null, 'default')],
  1178. }),
  1179. ],
  1180. })
  1181. },
  1182. }
  1183. const app = createApp(App)
  1184. app.mount(container)
  1185. await nextTick()
  1186. expect(target.innerHTML).toBe(`<span>default</span>`)
  1187. app.unmount()
  1188. })
  1189. test('render two Teleports w/ shadowRoot false', async () => {
  1190. const target1 = document.createElement('div')
  1191. const target2 = document.createElement('span')
  1192. const Child = defineCustomElement(
  1193. {
  1194. render() {
  1195. return [
  1196. h(Teleport, { to: target1 }, [renderSlot(this.$slots, 'header')]),
  1197. h(Teleport, { to: target2 }, [renderSlot(this.$slots, 'body')]),
  1198. ]
  1199. },
  1200. },
  1201. { shadowRoot: false },
  1202. )
  1203. customElements.define('my-el-two-teleport-child', Child)
  1204. const App = {
  1205. render() {
  1206. return h('my-el-two-teleport-child', null, {
  1207. default: () => [
  1208. h('div', { slot: 'header' }, 'header'),
  1209. h('span', { slot: 'body' }, 'body'),
  1210. ],
  1211. })
  1212. },
  1213. }
  1214. const app = createApp(App)
  1215. app.mount(container)
  1216. await nextTick()
  1217. expect(target1.outerHTML).toBe(
  1218. `<div><div slot="header">header</div></div>`,
  1219. )
  1220. expect(target2.outerHTML).toBe(
  1221. `<span><span slot="body">body</span></span>`,
  1222. )
  1223. app.unmount()
  1224. })
  1225. test('render two Teleports w/ shadowRoot false (with disabled)', async () => {
  1226. const target1 = document.createElement('div')
  1227. const target2 = document.createElement('span')
  1228. const Child = defineCustomElement(
  1229. {
  1230. render() {
  1231. return [
  1232. // with disabled: true
  1233. h(Teleport, { to: target1, disabled: true }, [
  1234. renderSlot(this.$slots, 'header'),
  1235. ]),
  1236. h(Teleport, { to: target2 }, [renderSlot(this.$slots, 'body')]),
  1237. ]
  1238. },
  1239. },
  1240. { shadowRoot: false },
  1241. )
  1242. customElements.define('my-el-two-teleport-child-0', Child)
  1243. const App = {
  1244. render() {
  1245. return h('my-el-two-teleport-child-0', null, {
  1246. default: () => [
  1247. h('div', { slot: 'header' }, 'header'),
  1248. h('span', { slot: 'body' }, 'body'),
  1249. ],
  1250. })
  1251. },
  1252. }
  1253. const app = createApp(App)
  1254. app.mount(container)
  1255. await nextTick()
  1256. expect(target1.outerHTML).toBe(`<div></div>`)
  1257. expect(target2.outerHTML).toBe(
  1258. `<span><span slot="body">body</span></span>`,
  1259. )
  1260. app.unmount()
  1261. })
  1262. test('toggle nested custom element with shadowRoot: false', async () => {
  1263. customElements.define(
  1264. 'my-el-child-shadow-false',
  1265. defineCustomElement(
  1266. {
  1267. render(ctx: any) {
  1268. return h('div', null, [renderSlot(ctx.$slots, 'default')])
  1269. },
  1270. },
  1271. { shadowRoot: false },
  1272. ),
  1273. )
  1274. const ChildWrapper = {
  1275. render() {
  1276. return h('my-el-child-shadow-false', null, 'child')
  1277. },
  1278. }
  1279. customElements.define(
  1280. 'my-el-parent-shadow-false',
  1281. defineCustomElement(
  1282. {
  1283. props: {
  1284. isShown: { type: Boolean, required: true },
  1285. },
  1286. render(ctx: any, _: any, $props: any) {
  1287. return $props.isShown
  1288. ? h('div', { key: 0 }, [renderSlot(ctx.$slots, 'default')])
  1289. : null
  1290. },
  1291. },
  1292. { shadowRoot: false },
  1293. ),
  1294. )
  1295. const ParentWrapper = {
  1296. props: {
  1297. isShown: { type: Boolean, required: true },
  1298. },
  1299. render(ctx: any, _: any, $props: any) {
  1300. return h('my-el-parent-shadow-false', { isShown: $props.isShown }, [
  1301. renderSlot(ctx.$slots, 'default'),
  1302. ])
  1303. },
  1304. }
  1305. const isShown = ref(true)
  1306. const App = {
  1307. render() {
  1308. return h(ParentWrapper, { isShown: isShown.value } as any, {
  1309. default: () => [h(ChildWrapper)],
  1310. })
  1311. },
  1312. }
  1313. const container = document.createElement('div')
  1314. document.body.appendChild(container)
  1315. const app = createApp(App)
  1316. app.mount(container)
  1317. expect(container.innerHTML).toBe(
  1318. `<my-el-parent-shadow-false is-shown="" data-v-app="">` +
  1319. `<div>` +
  1320. `<my-el-child-shadow-false data-v-app="">` +
  1321. `<div>child</div>` +
  1322. `</my-el-child-shadow-false>` +
  1323. `</div>` +
  1324. `</my-el-parent-shadow-false>`,
  1325. )
  1326. isShown.value = false
  1327. await nextTick()
  1328. expect(container.innerHTML).toBe(
  1329. `<my-el-parent-shadow-false data-v-app=""><!----></my-el-parent-shadow-false>`,
  1330. )
  1331. isShown.value = true
  1332. await nextTick()
  1333. expect(container.innerHTML).toBe(
  1334. `<my-el-parent-shadow-false data-v-app="" is-shown="">` +
  1335. `<div>` +
  1336. `<my-el-child-shadow-false data-v-app="">` +
  1337. `<div>child</div>` +
  1338. `</my-el-child-shadow-false>` +
  1339. `</div>` +
  1340. `</my-el-parent-shadow-false>`,
  1341. )
  1342. })
  1343. })
  1344. describe('helpers', () => {
  1345. test('useHost', () => {
  1346. const Foo = defineCustomElement({
  1347. setup() {
  1348. const host = useHost()!
  1349. host.setAttribute('id', 'host')
  1350. return () => h('div', 'hello')
  1351. },
  1352. })
  1353. customElements.define('my-el-use-host', Foo)
  1354. container.innerHTML = `<my-el-use-host>`
  1355. const el = container.childNodes[0] as VueElement
  1356. expect(el.id).toBe('host')
  1357. })
  1358. test('useShadowRoot for style injection', () => {
  1359. const Foo = defineCustomElement({
  1360. setup() {
  1361. const root = useShadowRoot()!
  1362. const style = document.createElement('style')
  1363. style.innerHTML = `div { color: red; }`
  1364. root.appendChild(style)
  1365. return () => h('div', 'hello')
  1366. },
  1367. })
  1368. customElements.define('my-el-use-shadow-root', Foo)
  1369. container.innerHTML = `<my-el-use-shadow-root>`
  1370. const el = container.childNodes[0] as VueElement
  1371. const style = el.shadowRoot?.querySelector('style')!
  1372. expect(style.textContent).toBe(`div { color: red; }`)
  1373. })
  1374. })
  1375. describe('expose', () => {
  1376. test('expose w/ options api', async () => {
  1377. const E = defineCustomElement({
  1378. data() {
  1379. return {
  1380. value: 0,
  1381. }
  1382. },
  1383. methods: {
  1384. foo() {
  1385. ;(this as any).value++
  1386. },
  1387. },
  1388. expose: ['foo'],
  1389. render(_ctx: any) {
  1390. return h('div', null, _ctx.value)
  1391. },
  1392. })
  1393. customElements.define('my-el-expose-options-api', E)
  1394. container.innerHTML = `<my-el-expose-options-api></my-el-expose-options-api>`
  1395. const e = container.childNodes[0] as VueElement & {
  1396. foo: () => void
  1397. }
  1398. expect(e.shadowRoot!.innerHTML).toBe(`<div>0</div>`)
  1399. e.foo()
  1400. await nextTick()
  1401. expect(e.shadowRoot!.innerHTML).toBe(`<div>1</div>`)
  1402. })
  1403. test('expose attributes and callback', async () => {
  1404. type SetValue = (value: string) => void
  1405. let fn: MockedFunction<SetValue>
  1406. const E = defineCustomElement({
  1407. setup(_, { expose }) {
  1408. const value = ref('hello')
  1409. const setValue = (fn = vi.fn((_value: string) => {
  1410. value.value = _value
  1411. }))
  1412. expose({
  1413. setValue,
  1414. value,
  1415. })
  1416. return () => h('div', null, [value.value])
  1417. },
  1418. })
  1419. customElements.define('my-el-expose', E)
  1420. container.innerHTML = `<my-el-expose></my-el-expose>`
  1421. const e = container.childNodes[0] as VueElement & {
  1422. value: string
  1423. setValue: MockedFunction<SetValue>
  1424. }
  1425. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1426. expect(e.value).toBe('hello')
  1427. expect(e.setValue).toBe(fn!)
  1428. e.setValue('world')
  1429. expect(e.value).toBe('world')
  1430. await nextTick()
  1431. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1432. })
  1433. test('warning when exposing an existing property', () => {
  1434. const E = defineCustomElement({
  1435. props: {
  1436. value: String,
  1437. },
  1438. setup(props, { expose }) {
  1439. expose({
  1440. value: 'hello',
  1441. })
  1442. return () => h('div', null, [props.value])
  1443. },
  1444. })
  1445. customElements.define('my-el-expose-two', E)
  1446. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  1447. expect(
  1448. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  1449. ).toHaveBeenWarned()
  1450. })
  1451. })
  1452. test('async & nested custom elements', async () => {
  1453. let fooVal: string | undefined = ''
  1454. const E = defineCustomElement(
  1455. defineAsyncComponent(() => {
  1456. return Promise.resolve({
  1457. setup(props) {
  1458. provide('foo', 'foo')
  1459. },
  1460. render(this: any) {
  1461. return h('div', null, [renderSlot(this.$slots, 'default')])
  1462. },
  1463. })
  1464. }),
  1465. )
  1466. const EChild = defineCustomElement({
  1467. setup(props) {
  1468. fooVal = inject('foo')
  1469. },
  1470. render(this: any) {
  1471. return h('div', null, 'child')
  1472. },
  1473. })
  1474. customElements.define('my-el-async-nested-ce', E)
  1475. customElements.define('slotted-child', EChild)
  1476. container.innerHTML = `<my-el-async-nested-ce><div><slotted-child></slotted-child></div></my-el-async-nested-ce>`
  1477. await new Promise(r => setTimeout(r))
  1478. const e = container.childNodes[0] as VueElement
  1479. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1480. expect(fooVal).toBe('foo')
  1481. })
  1482. test('async & multiple levels of nested custom elements', async () => {
  1483. let fooVal: string | undefined = ''
  1484. let barVal: string | undefined = ''
  1485. const E = defineCustomElement(
  1486. defineAsyncComponent(() => {
  1487. return Promise.resolve({
  1488. setup(props) {
  1489. provide('foo', 'foo')
  1490. },
  1491. render(this: any) {
  1492. return h('div', null, [renderSlot(this.$slots, 'default')])
  1493. },
  1494. })
  1495. }),
  1496. )
  1497. const EChild = defineCustomElement({
  1498. setup(props) {
  1499. provide('bar', 'bar')
  1500. },
  1501. render(this: any) {
  1502. return h('div', null, [renderSlot(this.$slots, 'default')])
  1503. },
  1504. })
  1505. const EChild2 = defineCustomElement({
  1506. setup(props) {
  1507. fooVal = inject('foo')
  1508. barVal = inject('bar')
  1509. },
  1510. render(this: any) {
  1511. return h('div', null, 'child')
  1512. },
  1513. })
  1514. customElements.define('my-el-async-nested-m-ce', E)
  1515. customElements.define('slotted-child-m', EChild)
  1516. customElements.define('slotted-child2-m', EChild2)
  1517. container.innerHTML =
  1518. `<my-el-async-nested-m-ce>` +
  1519. `<div><slotted-child-m>` +
  1520. `<slotted-child2-m></slotted-child2-m>` +
  1521. `</slotted-child-m></div>` +
  1522. `</my-el-async-nested-m-ce>`
  1523. await new Promise(r => setTimeout(r))
  1524. const e = container.childNodes[0] as VueElement
  1525. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1526. expect(fooVal).toBe('foo')
  1527. expect(barVal).toBe('bar')
  1528. })
  1529. describe('configureApp', () => {
  1530. test('should work', () => {
  1531. const E = defineCustomElement(
  1532. () => {
  1533. const msg = inject('msg')
  1534. return () => h('div', msg!)
  1535. },
  1536. {
  1537. configureApp(app) {
  1538. app.provide('msg', 'app-injected')
  1539. },
  1540. },
  1541. )
  1542. customElements.define('my-element-with-app', E)
  1543. container.innerHTML = `<my-element-with-app></my-element-with-app>`
  1544. const e = container.childNodes[0] as VueElement
  1545. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1546. })
  1547. // #12448
  1548. test('work with async component', async () => {
  1549. const AsyncComp = defineAsyncComponent(() => {
  1550. return Promise.resolve({
  1551. render() {
  1552. const msg: string | undefined = inject('msg')
  1553. return h('div', {}, msg)
  1554. },
  1555. } as any)
  1556. })
  1557. const E = defineCustomElement(AsyncComp, {
  1558. configureApp(app) {
  1559. app.provide('msg', 'app-injected')
  1560. },
  1561. })
  1562. customElements.define('my-async-element-with-app', E)
  1563. container.innerHTML = `<my-async-element-with-app></my-async-element-with-app>`
  1564. const e = container.childNodes[0] as VueElement
  1565. await new Promise(r => setTimeout(r))
  1566. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1567. })
  1568. test('with hmr reload', async () => {
  1569. const __hmrId = '__hmrWithApp'
  1570. const def = defineComponent({
  1571. __hmrId,
  1572. setup() {
  1573. const msg = inject('msg')
  1574. return { msg }
  1575. },
  1576. render(this: any) {
  1577. return h('div', [h('span', this.msg), h('span', this.$foo)])
  1578. },
  1579. })
  1580. const E = defineCustomElement(def, {
  1581. configureApp(app) {
  1582. app.provide('msg', 'app-injected')
  1583. app.config.globalProperties.$foo = 'foo'
  1584. },
  1585. })
  1586. customElements.define('my-element-with-app-hmr', E)
  1587. container.innerHTML = `<my-element-with-app-hmr></my-element-with-app-hmr>`
  1588. const el = container.childNodes[0] as VueElement
  1589. expect(el.shadowRoot?.innerHTML).toBe(
  1590. `<div><span>app-injected</span><span>foo</span></div>`,
  1591. )
  1592. // hmr
  1593. __VUE_HMR_RUNTIME__.reload(__hmrId, def as any)
  1594. await nextTick()
  1595. expect(el.shadowRoot?.innerHTML).toBe(
  1596. `<div><span>app-injected</span><span>foo</span></div>`,
  1597. )
  1598. })
  1599. })
  1600. // #9885
  1601. test('avoid double mount when prop is set immediately after mount', () => {
  1602. customElements.define(
  1603. 'my-input-dupe',
  1604. defineCustomElement({
  1605. props: {
  1606. value: String,
  1607. },
  1608. render() {
  1609. return 'hello'
  1610. },
  1611. }),
  1612. )
  1613. const container = document.createElement('div')
  1614. document.body.appendChild(container)
  1615. createApp({
  1616. render() {
  1617. return h('div', [
  1618. h('my-input-dupe', {
  1619. onVnodeMounted(vnode) {
  1620. vnode.el!.value = 'fesfes'
  1621. },
  1622. }),
  1623. ])
  1624. },
  1625. }).mount(container)
  1626. expect(container.children[0].children[0].shadowRoot?.innerHTML).toBe(
  1627. 'hello',
  1628. )
  1629. })
  1630. // #11081
  1631. test('Props can be casted when mounting custom elements in component rendering functions', async () => {
  1632. const E = defineCustomElement(
  1633. defineAsyncComponent(() =>
  1634. Promise.resolve({
  1635. props: ['fooValue'],
  1636. setup(props) {
  1637. expect(props.fooValue).toBe('fooValue')
  1638. return () => h('div', props.fooValue)
  1639. },
  1640. }),
  1641. ),
  1642. )
  1643. customElements.define('my-el-async-4', E)
  1644. const R = defineComponent({
  1645. setup() {
  1646. const fooValue = ref('fooValue')
  1647. return () => {
  1648. return h('div', null, [
  1649. h('my-el-async-4', {
  1650. fooValue: fooValue.value,
  1651. }),
  1652. ])
  1653. }
  1654. },
  1655. })
  1656. const app = createApp(R)
  1657. app.mount(container)
  1658. await new Promise(r => setTimeout(r))
  1659. const e = container.querySelector('my-el-async-4') as VueElement
  1660. expect(e.shadowRoot!.innerHTML).toBe(`<div>fooValue</div>`)
  1661. app.unmount()
  1662. })
  1663. // #11276
  1664. test('delete prop on attr removal', async () => {
  1665. const E = defineCustomElement({
  1666. props: {
  1667. boo: {
  1668. type: Boolean,
  1669. },
  1670. },
  1671. render() {
  1672. return this.boo + ',' + typeof this.boo
  1673. },
  1674. })
  1675. customElements.define('el-attr-removal', E)
  1676. container.innerHTML = '<el-attr-removal boo>'
  1677. const e = container.childNodes[0] as VueElement
  1678. expect(e.shadowRoot!.innerHTML).toBe(`true,boolean`)
  1679. e.removeAttribute('boo')
  1680. await nextTick()
  1681. expect(e.shadowRoot!.innerHTML).toBe(`false,boolean`)
  1682. })
  1683. test('hyphenated attr removal', async () => {
  1684. const E = defineCustomElement({
  1685. props: {
  1686. fooBar: {
  1687. type: Boolean,
  1688. },
  1689. },
  1690. render() {
  1691. return this.fooBar
  1692. },
  1693. })
  1694. customElements.define('el-hyphenated-attr-removal', E)
  1695. const toggle = ref(true)
  1696. const Comp = {
  1697. render() {
  1698. return h('el-hyphenated-attr-removal', {
  1699. 'foo-bar': toggle.value ? '' : null,
  1700. })
  1701. },
  1702. }
  1703. render(h(Comp), container)
  1704. const el = container.children[0]
  1705. expect(el.hasAttribute('foo-bar')).toBe(true)
  1706. expect((el as any).outerHTML).toBe(
  1707. `<el-hyphenated-attr-removal foo-bar=""></el-hyphenated-attr-removal>`,
  1708. )
  1709. toggle.value = false
  1710. await nextTick()
  1711. expect(el.hasAttribute('foo-bar')).toBe(false)
  1712. expect((el as any).outerHTML).toBe(
  1713. `<el-hyphenated-attr-removal></el-hyphenated-attr-removal>`,
  1714. )
  1715. })
  1716. test('no unexpected mutation of the 1st argument', () => {
  1717. const Foo = {
  1718. name: 'Foo',
  1719. }
  1720. defineCustomElement(Foo, { shadowRoot: false })
  1721. expect(Foo).toEqual({
  1722. name: 'Foo',
  1723. })
  1724. })
  1725. })