customElement.spec.ts 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  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 attributes and properties changed together', async () => {
  205. const e = new E()
  206. e.foo = 'foo1'
  207. e.bar = { x: 'bar1' }
  208. container.appendChild(e)
  209. await nextTick()
  210. expect(e.shadowRoot!.innerHTML).toBe('<div>foo1</div><div>bar1</div>')
  211. // change attr then property
  212. e.setAttribute('foo', 'foo2')
  213. e.bar = { x: 'bar2' }
  214. await nextTick()
  215. expect(e.shadowRoot!.innerHTML).toBe('<div>foo2</div><div>bar2</div>')
  216. expect(e.getAttribute('foo')).toBe('foo2')
  217. expect(e.hasAttribute('bar')).toBe(false)
  218. // change prop then attr
  219. e.bar = { x: 'bar3' }
  220. e.setAttribute('foo', 'foo3')
  221. await nextTick()
  222. expect(e.shadowRoot!.innerHTML).toBe('<div>foo3</div><div>bar3</div>')
  223. expect(e.getAttribute('foo')).toBe('foo3')
  224. expect(e.hasAttribute('bar')).toBe(false)
  225. })
  226. test('props via hyphen property', async () => {
  227. const Comp = defineCustomElement({
  228. props: {
  229. fooBar: Boolean,
  230. },
  231. render() {
  232. return 'Comp'
  233. },
  234. })
  235. customElements.define('my-el-comp', Comp)
  236. render(h('my-el-comp', { 'foo-bar': true }), container)
  237. const el = container.children[0]
  238. expect((el as any).outerHTML).toBe('<my-el-comp foo-bar=""></my-el-comp>')
  239. })
  240. test('attribute -> prop type casting', async () => {
  241. const E = defineCustomElement({
  242. props: {
  243. fooBar: Number, // test casting of camelCase prop names
  244. bar: Boolean,
  245. baz: String,
  246. },
  247. render() {
  248. return [
  249. this.fooBar,
  250. typeof this.fooBar,
  251. this.bar,
  252. typeof this.bar,
  253. this.baz,
  254. typeof this.baz,
  255. ].join(' ')
  256. },
  257. })
  258. customElements.define('my-el-props-cast', E)
  259. container.innerHTML = `<my-el-props-cast foo-bar="1" baz="12345"></my-el-props-cast>`
  260. const e = container.childNodes[0] as VueElement
  261. expect(e.shadowRoot!.innerHTML).toBe(
  262. `1 number false boolean 12345 string`,
  263. )
  264. e.setAttribute('bar', '')
  265. await nextTick()
  266. expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
  267. e.setAttribute('foo-bar', '2e1')
  268. await nextTick()
  269. expect(e.shadowRoot!.innerHTML).toBe(
  270. `20 number true boolean 12345 string`,
  271. )
  272. e.setAttribute('baz', '2e1')
  273. await nextTick()
  274. expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
  275. })
  276. // #4772
  277. test('attr casting w/ programmatic creation', () => {
  278. const E = defineCustomElement({
  279. props: {
  280. foo: Number,
  281. },
  282. render() {
  283. return `foo type: ${typeof this.foo}`
  284. },
  285. })
  286. customElements.define('my-element-programmatic', E)
  287. const el = document.createElement('my-element-programmatic') as any
  288. el.setAttribute('foo', '123')
  289. container.appendChild(el)
  290. expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
  291. })
  292. test('handling properties set before upgrading', () => {
  293. const E = defineCustomElement({
  294. props: {
  295. foo: String,
  296. dataAge: Number,
  297. },
  298. setup(props) {
  299. expect(props.foo).toBe('hello')
  300. expect(props.dataAge).toBe(5)
  301. },
  302. render() {
  303. return h('div', `foo: ${this.foo}`)
  304. },
  305. })
  306. const el = document.createElement('my-el-upgrade') as any
  307. el.foo = 'hello'
  308. el.dataset.age = 5
  309. el.notProp = 1
  310. container.appendChild(el)
  311. customElements.define('my-el-upgrade', E)
  312. expect(el.shadowRoot.firstChild.innerHTML).toBe(`foo: hello`)
  313. // should not reflect if not declared as a prop
  314. expect(el.hasAttribute('not-prop')).toBe(false)
  315. })
  316. test('handle properties set before connecting', () => {
  317. const obj = { a: 1 }
  318. const E = defineCustomElement({
  319. props: {
  320. foo: String,
  321. post: Object,
  322. },
  323. setup(props) {
  324. expect(props.foo).toBe('hello')
  325. expect(props.post).toBe(obj)
  326. },
  327. render() {
  328. return JSON.stringify(this.post)
  329. },
  330. })
  331. customElements.define('my-el-preconnect', E)
  332. const el = document.createElement('my-el-preconnect') as any
  333. el.foo = 'hello'
  334. el.post = obj
  335. container.appendChild(el)
  336. expect(el.shadowRoot.innerHTML).toBe(JSON.stringify(obj))
  337. })
  338. // https://github.com/vuejs/core/issues/6163
  339. test('handle components with no props', async () => {
  340. const E = defineCustomElement({
  341. render() {
  342. return h('div', 'foo')
  343. },
  344. })
  345. customElements.define('my-element-noprops', E)
  346. const el = document.createElement('my-element-noprops')
  347. container.appendChild(el)
  348. await nextTick()
  349. expect(el.shadowRoot!.innerHTML).toMatchInlineSnapshot('"<div>foo</div>"')
  350. })
  351. // #5793
  352. test('set number value in dom property', () => {
  353. const E = defineCustomElement({
  354. props: {
  355. 'max-age': Number,
  356. },
  357. render() {
  358. // @ts-expect-error
  359. return `max age: ${this.maxAge}/type: ${typeof this.maxAge}`
  360. },
  361. })
  362. customElements.define('my-element-number-property', E)
  363. const el = document.createElement('my-element-number-property') as any
  364. container.appendChild(el)
  365. el.maxAge = 50
  366. expect(el.maxAge).toBe(50)
  367. expect(el.shadowRoot.innerHTML).toBe('max age: 50/type: number')
  368. })
  369. // #9006
  370. test('should reflect default value', () => {
  371. const E = defineCustomElement({
  372. props: {
  373. value: {
  374. type: String,
  375. default: 'hi',
  376. },
  377. },
  378. render() {
  379. return this.value
  380. },
  381. })
  382. customElements.define('my-el-default-val', E)
  383. container.innerHTML = `<my-el-default-val></my-el-default-val>`
  384. const e = container.childNodes[0] as any
  385. expect(e.value).toBe('hi')
  386. })
  387. // #12214
  388. test('Boolean prop with default true', async () => {
  389. const E = defineCustomElement({
  390. props: {
  391. foo: {
  392. type: Boolean,
  393. default: true,
  394. },
  395. },
  396. render() {
  397. return String(this.foo)
  398. },
  399. })
  400. customElements.define('my-el-default-true', E)
  401. container.innerHTML = `<my-el-default-true></my-el-default-true>`
  402. const e = container.childNodes[0] as HTMLElement & { foo: any },
  403. shadowRoot = e.shadowRoot as ShadowRoot
  404. expect(shadowRoot.innerHTML).toBe('true')
  405. e.foo = undefined
  406. await nextTick()
  407. expect(shadowRoot.innerHTML).toBe('true')
  408. e.foo = false
  409. await nextTick()
  410. expect(shadowRoot.innerHTML).toBe('false')
  411. e.foo = null
  412. await nextTick()
  413. expect(shadowRoot.innerHTML).toBe('null')
  414. e.foo = ''
  415. await nextTick()
  416. expect(shadowRoot.innerHTML).toBe('true')
  417. })
  418. test('support direct setup function syntax with extra options', () => {
  419. const E = defineCustomElement(
  420. props => {
  421. return () => props.text
  422. },
  423. {
  424. props: {
  425. text: String,
  426. },
  427. },
  428. )
  429. customElements.define('my-el-setup-with-props', E)
  430. container.innerHTML = `<my-el-setup-with-props text="hello"></my-el-setup-with-props>`
  431. const e = container.childNodes[0] as VueElement
  432. expect(e.shadowRoot!.innerHTML).toBe('hello')
  433. })
  434. test('prop types validation', async () => {
  435. const E = defineCustomElement({
  436. props: {
  437. num: {
  438. type: [Number, String],
  439. },
  440. bool: {
  441. type: Boolean,
  442. },
  443. },
  444. render() {
  445. return h('div', [
  446. h('span', [`${this.num} is ${typeof this.num}`]),
  447. h('span', [`${this.bool} is ${typeof this.bool}`]),
  448. ])
  449. },
  450. })
  451. customElements.define('my-el-with-type-props', E)
  452. render(h('my-el-with-type-props', { num: 1, bool: true }), container)
  453. const e = container.childNodes[0] as VueElement
  454. // @ts-expect-error
  455. expect(e.num).toBe(1)
  456. // @ts-expect-error
  457. expect(e.bool).toBe(true)
  458. expect(e.shadowRoot!.innerHTML).toBe(
  459. '<div><span>1 is number</span><span>true is boolean</span></div>',
  460. )
  461. })
  462. })
  463. describe('attrs', () => {
  464. const E = defineCustomElement({
  465. render() {
  466. return [h('div', null, this.$attrs.foo as string)]
  467. },
  468. })
  469. customElements.define('my-el-attrs', E)
  470. test('attrs via attribute', async () => {
  471. container.innerHTML = `<my-el-attrs foo="hello"></my-el-attrs>`
  472. const e = container.childNodes[0] as VueElement
  473. expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
  474. e.setAttribute('foo', 'changed')
  475. await nextTick()
  476. expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div>')
  477. })
  478. test('non-declared properties should not show up in $attrs', () => {
  479. const e = new E()
  480. // @ts-expect-error
  481. e.foo = '123'
  482. container.appendChild(e)
  483. expect(e.shadowRoot!.innerHTML).toBe('<div></div>')
  484. })
  485. // https://github.com/vuejs/core/issues/12964
  486. // Disabled because of missing support for `delegatesFocus` in jsdom
  487. // https://github.com/jsdom/jsdom/issues/3418
  488. // eslint-disable-next-line vitest/no-disabled-tests
  489. test.skip('shadowRoot should be initialized with delegatesFocus', () => {
  490. const E = defineCustomElement(
  491. {
  492. render() {
  493. return [h('input', { tabindex: 1 })]
  494. },
  495. },
  496. { shadowRootOptions: { delegatesFocus: true } },
  497. )
  498. customElements.define('my-el-with-delegate-focus', E)
  499. const e = new E()
  500. container.appendChild(e)
  501. expect(e.shadowRoot!.delegatesFocus).toBe(true)
  502. })
  503. })
  504. describe('emits', () => {
  505. const CompDef = defineComponent({
  506. setup(_, { emit }) {
  507. emit('created')
  508. return () =>
  509. h('div', {
  510. onClick: () => {
  511. emit('my-click', 1)
  512. },
  513. onMousedown: () => {
  514. emit('myEvent', 1) // validate hyphenation
  515. },
  516. onWheel: () => {
  517. emit('my-wheel', { bubbles: true }, 1)
  518. },
  519. })
  520. },
  521. })
  522. const E = defineCustomElement(CompDef)
  523. customElements.define('my-el-emits', E)
  524. test('emit on connect', () => {
  525. const e = new E()
  526. const spy = vi.fn()
  527. e.addEventListener('created', spy)
  528. container.appendChild(e)
  529. expect(spy).toHaveBeenCalled()
  530. })
  531. test('emit on interaction', () => {
  532. container.innerHTML = `<my-el-emits></my-el-emits>`
  533. const e = container.childNodes[0] as VueElement
  534. const spy = vi.fn()
  535. e.addEventListener('my-click', spy)
  536. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  537. expect(spy).toHaveBeenCalledTimes(1)
  538. expect(spy.mock.calls[0][0]).toMatchObject({
  539. detail: [1],
  540. })
  541. })
  542. // #5373
  543. test('case transform for camelCase event', () => {
  544. container.innerHTML = `<my-el-emits></my-el-emits>`
  545. const e = container.childNodes[0] as VueElement
  546. const spy1 = vi.fn()
  547. e.addEventListener('myEvent', spy1)
  548. const spy2 = vi.fn()
  549. // emitting myEvent, but listening for my-event. This happens when
  550. // using the custom element in a Vue template
  551. e.addEventListener('my-event', spy2)
  552. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('mousedown'))
  553. expect(spy1).toHaveBeenCalledTimes(1)
  554. expect(spy2).toHaveBeenCalledTimes(1)
  555. })
  556. test('emit from within async component wrapper', async () => {
  557. const p = new Promise<typeof CompDef>(res => res(CompDef as any))
  558. const E = defineCustomElement(defineAsyncComponent(() => p))
  559. customElements.define('my-async-el-emits', E)
  560. container.innerHTML = `<my-async-el-emits></my-async-el-emits>`
  561. const e = container.childNodes[0] as VueElement
  562. const spy = vi.fn()
  563. e.addEventListener('my-click', spy)
  564. // this feels brittle but seems necessary to reach the node in the DOM.
  565. await customElements.whenDefined('my-async-el-emits')
  566. await nextTick()
  567. await nextTick()
  568. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  569. expect(spy).toHaveBeenCalled()
  570. expect(spy.mock.calls[0][0]).toMatchObject({
  571. detail: [1],
  572. })
  573. })
  574. // #7293
  575. test('emit in an async component wrapper with properties bound', async () => {
  576. const E = defineCustomElement(
  577. defineAsyncComponent(
  578. () => new Promise<typeof CompDef>(res => res(CompDef as any)),
  579. ),
  580. )
  581. customElements.define('my-async-el-props-emits', E)
  582. container.innerHTML = `<my-async-el-props-emits id="my_async_el_props_emits"></my-async-el-props-emits>`
  583. const e = container.childNodes[0] as VueElement
  584. const spy = vi.fn()
  585. e.addEventListener('my-click', spy)
  586. await customElements.whenDefined('my-async-el-props-emits')
  587. await nextTick()
  588. await nextTick()
  589. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
  590. expect(spy).toHaveBeenCalled()
  591. expect(spy.mock.calls[0][0]).toMatchObject({
  592. detail: [1],
  593. })
  594. })
  595. test('emit with options', async () => {
  596. container.innerHTML = `<my-el-emits></my-el-emits>`
  597. const e = container.childNodes[0] as VueElement
  598. const spy = vi.fn()
  599. e.addEventListener('my-wheel', spy)
  600. e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('wheel'))
  601. expect(spy).toHaveBeenCalledTimes(1)
  602. expect(spy.mock.calls[0][0]).toMatchObject({
  603. bubbles: true,
  604. detail: [{ bubbles: true }, 1],
  605. })
  606. })
  607. })
  608. describe('slots', () => {
  609. const E = defineCustomElement({
  610. render() {
  611. return [
  612. h('div', null, [
  613. renderSlot(this.$slots, 'default', undefined, () => [
  614. h('div', 'fallback'),
  615. ]),
  616. ]),
  617. h('div', null, renderSlot(this.$slots, 'named')),
  618. ]
  619. },
  620. })
  621. customElements.define('my-el-slots', E)
  622. test('render slots correctly', () => {
  623. container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
  624. const e = container.childNodes[0] as VueElement
  625. // native slots allocation does not affect innerHTML, so we just
  626. // verify that we've rendered the correct native slots here...
  627. expect(e.shadowRoot!.innerHTML).toBe(
  628. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  629. )
  630. })
  631. test('render slot props', async () => {
  632. const foo = ref('foo')
  633. const E = defineCustomElement({
  634. render() {
  635. return [
  636. h(
  637. 'div',
  638. null,
  639. renderSlot(this.$slots, 'default', { class: foo.value }),
  640. ),
  641. ]
  642. },
  643. })
  644. customElements.define('my-el-slot-props', E)
  645. container.innerHTML = `<my-el-slot-props><span>hi</span></my-el-slot-props>`
  646. const e = container.childNodes[0] as VueElement
  647. expect(e.shadowRoot!.innerHTML).toBe(
  648. `<div><slot class="foo"></slot></div>`,
  649. )
  650. foo.value = 'bar'
  651. await nextTick()
  652. expect(e.shadowRoot!.innerHTML).toBe(
  653. `<div><slot class="bar"></slot></div>`,
  654. )
  655. })
  656. })
  657. describe('provide/inject', () => {
  658. const Consumer = defineCustomElement({
  659. setup() {
  660. const foo = inject<Ref>('foo')!
  661. return () => h('div', foo.value)
  662. },
  663. })
  664. customElements.define('my-consumer', Consumer)
  665. test('over nested usage', async () => {
  666. const foo = ref('injected!')
  667. const Provider = defineCustomElement({
  668. provide: {
  669. foo,
  670. },
  671. render() {
  672. return h('my-consumer')
  673. },
  674. })
  675. customElements.define('my-provider', Provider)
  676. container.innerHTML = `<my-provider><my-provider>`
  677. const provider = container.childNodes[0] as VueElement
  678. const consumer = provider.shadowRoot!.childNodes[0] as VueElement
  679. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  680. foo.value = 'changed!'
  681. await nextTick()
  682. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  683. })
  684. test('over slot composition', async () => {
  685. const foo = ref('injected!')
  686. const Provider = defineCustomElement({
  687. provide: {
  688. foo,
  689. },
  690. render() {
  691. return renderSlot(this.$slots, 'default')
  692. },
  693. })
  694. customElements.define('my-provider-2', Provider)
  695. container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
  696. const provider = container.childNodes[0]
  697. const consumer = provider.childNodes[0] as VueElement
  698. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
  699. foo.value = 'changed!'
  700. await nextTick()
  701. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
  702. })
  703. test('inherited from ancestors', async () => {
  704. const fooA = ref('FooA!')
  705. const fooB = ref('FooB!')
  706. const ProviderA = defineCustomElement({
  707. provide: {
  708. fooA,
  709. },
  710. render() {
  711. return h('provider-b')
  712. },
  713. })
  714. const ProviderB = defineCustomElement({
  715. provide: {
  716. fooB,
  717. },
  718. render() {
  719. return h('my-multi-consumer')
  720. },
  721. })
  722. const Consumer = defineCustomElement({
  723. setup() {
  724. const fooA = inject<Ref>('fooA')!
  725. const fooB = inject<Ref>('fooB')!
  726. return () => h('div', `${fooA.value} ${fooB.value}`)
  727. },
  728. })
  729. customElements.define('provider-a', ProviderA)
  730. customElements.define('provider-b', ProviderB)
  731. customElements.define('my-multi-consumer', Consumer)
  732. container.innerHTML = `<provider-a><provider-a>`
  733. const providerA = container.childNodes[0] as VueElement
  734. const providerB = providerA.shadowRoot!.childNodes[0] as VueElement
  735. const consumer = providerB.shadowRoot!.childNodes[0] as VueElement
  736. expect(consumer.shadowRoot!.innerHTML).toBe(`<div>FooA! FooB!</div>`)
  737. fooA.value = 'changedA!'
  738. fooB.value = 'changedB!'
  739. await nextTick()
  740. expect(consumer.shadowRoot!.innerHTML).toBe(
  741. `<div>changedA! changedB!</div>`,
  742. )
  743. })
  744. // #13212
  745. test('inherited from app context within nested elements', async () => {
  746. const outerValues: (string | undefined)[] = []
  747. const innerValues: (string | undefined)[] = []
  748. const innerChildValues: (string | undefined)[] = []
  749. const Outer = defineCustomElement(
  750. {
  751. setup() {
  752. outerValues.push(
  753. inject<string>('shared'),
  754. inject<string>('outer'),
  755. inject<string>('inner'),
  756. )
  757. },
  758. render() {
  759. return h('div', [renderSlot(this.$slots, 'default')])
  760. },
  761. },
  762. {
  763. configureApp(app) {
  764. app.provide('shared', 'shared')
  765. app.provide('outer', 'outer')
  766. },
  767. },
  768. )
  769. const Inner = defineCustomElement(
  770. {
  771. setup() {
  772. // ensure values are not self-injected
  773. provide('inner', 'inner-child')
  774. innerValues.push(
  775. inject<string>('shared'),
  776. inject<string>('outer'),
  777. inject<string>('inner'),
  778. )
  779. },
  780. render() {
  781. return h('div', [renderSlot(this.$slots, 'default')])
  782. },
  783. },
  784. {
  785. configureApp(app) {
  786. app.provide('outer', 'override-outer')
  787. app.provide('inner', 'inner')
  788. },
  789. },
  790. )
  791. const InnerChild = defineCustomElement({
  792. setup() {
  793. innerChildValues.push(
  794. inject<string>('shared'),
  795. inject<string>('outer'),
  796. inject<string>('inner'),
  797. )
  798. },
  799. render() {
  800. return h('div')
  801. },
  802. })
  803. customElements.define('provide-from-app-outer', Outer)
  804. customElements.define('provide-from-app-inner', Inner)
  805. customElements.define('provide-from-app-inner-child', InnerChild)
  806. container.innerHTML =
  807. '<provide-from-app-outer>' +
  808. '<provide-from-app-inner>' +
  809. '<provide-from-app-inner-child></provide-from-app-inner-child>' +
  810. '</provide-from-app-inner>' +
  811. '</provide-from-app-outer>'
  812. const outer = container.childNodes[0] as VueElement
  813. expect(outer.shadowRoot!.innerHTML).toBe('<div><slot></slot></div>')
  814. expect('[Vue warn]: injection "inner" not found.').toHaveBeenWarnedTimes(
  815. 1,
  816. )
  817. expect(
  818. '[Vue warn]: App already provides property with key "outer" inherited from its parent element. ' +
  819. 'It will be overwritten with the new value.',
  820. ).toHaveBeenWarnedTimes(1)
  821. expect(outerValues).toEqual(['shared', 'outer', undefined])
  822. expect(innerValues).toEqual(['shared', 'override-outer', 'inner'])
  823. expect(innerChildValues).toEqual([
  824. 'shared',
  825. 'override-outer',
  826. 'inner-child',
  827. ])
  828. })
  829. })
  830. describe('styles', () => {
  831. function assertStyles(el: VueElement, css: string[]) {
  832. const styles = el.shadowRoot?.querySelectorAll('style')!
  833. expect(styles.length).toBe(css.length) // should not duplicate multiple copies from Bar
  834. for (let i = 0; i < css.length; i++) {
  835. expect(styles[i].textContent).toBe(css[i])
  836. }
  837. }
  838. test('should attach styles to shadow dom', async () => {
  839. const def = defineComponent({
  840. __hmrId: 'foo',
  841. styles: [`div { color: red; }`],
  842. render() {
  843. return h('div', 'hello')
  844. },
  845. })
  846. const Foo = defineCustomElement(def)
  847. customElements.define('my-el-with-styles', Foo)
  848. container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
  849. const el = container.childNodes[0] as VueElement
  850. const style = el.shadowRoot?.querySelector('style')!
  851. expect(style.textContent).toBe(`div { color: red; }`)
  852. // hmr
  853. __VUE_HMR_RUNTIME__.reload('foo', {
  854. ...def,
  855. styles: [`div { color: blue; }`, `div { color: yellow; }`],
  856. } as any)
  857. await nextTick()
  858. assertStyles(el, [`div { color: blue; }`, `div { color: yellow; }`])
  859. })
  860. test("child components should inject styles to root element's shadow root", async () => {
  861. const Baz = () => h(Bar)
  862. const Bar = defineComponent({
  863. __hmrId: 'bar',
  864. styles: [`div { color: green; }`, `div { color: blue; }`],
  865. render() {
  866. return 'bar'
  867. },
  868. })
  869. const Foo = defineCustomElement({
  870. styles: [`div { color: red; }`],
  871. render() {
  872. return [h(Baz), h(Baz)]
  873. },
  874. })
  875. customElements.define('my-el-with-child-styles', Foo)
  876. container.innerHTML = `<my-el-with-child-styles></my-el-with-child-styles>`
  877. const el = container.childNodes[0] as VueElement
  878. // inject order should be child -> parent
  879. assertStyles(el, [
  880. `div { color: green; }`,
  881. `div { color: blue; }`,
  882. `div { color: red; }`,
  883. ])
  884. // hmr
  885. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  886. ...Bar,
  887. styles: [`div { color: red; }`, `div { color: yellow; }`],
  888. } as any)
  889. await nextTick()
  890. assertStyles(el, [
  891. `div { color: red; }`,
  892. `div { color: yellow; }`,
  893. `div { color: red; }`,
  894. ])
  895. __VUE_HMR_RUNTIME__.reload(Bar.__hmrId!, {
  896. ...Bar,
  897. styles: [`div { color: blue; }`],
  898. } as any)
  899. await nextTick()
  900. assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
  901. })
  902. test("child components should not inject styles to root element's shadow root w/ shadowRoot false", async () => {
  903. const Bar = defineComponent({
  904. styles: [`div { color: green; }`],
  905. render() {
  906. return 'bar'
  907. },
  908. })
  909. const Baz = () => h(Bar)
  910. const Foo = defineCustomElement(
  911. {
  912. render() {
  913. return [h(Baz)]
  914. },
  915. },
  916. { shadowRoot: false },
  917. )
  918. customElements.define('my-foo-with-shadowroot-false', Foo)
  919. container.innerHTML = `<my-foo-with-shadowroot-false></my-foo-with-shadowroot-false>`
  920. const el = container.childNodes[0] as VueElement
  921. const style = el.shadowRoot?.querySelector('style')
  922. expect(style).toBeUndefined()
  923. })
  924. test('with nonce', () => {
  925. const Foo = defineCustomElement(
  926. {
  927. styles: [`div { color: red; }`],
  928. render() {
  929. return h('div', 'hello')
  930. },
  931. },
  932. { nonce: 'xxx' },
  933. )
  934. customElements.define('my-el-with-nonce', Foo)
  935. container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
  936. const el = container.childNodes[0] as VueElement
  937. const style = el.shadowRoot?.querySelector('style')!
  938. expect(style.getAttribute('nonce')).toBe('xxx')
  939. })
  940. })
  941. describe('async', () => {
  942. test('should work', async () => {
  943. const loaderSpy = vi.fn()
  944. const E = defineCustomElement(
  945. defineAsyncComponent(() => {
  946. loaderSpy()
  947. return Promise.resolve({
  948. props: ['msg'],
  949. styles: [`div { color: red }`],
  950. render(this: any) {
  951. return h('div', null, this.msg)
  952. },
  953. })
  954. }),
  955. )
  956. customElements.define('my-el-async', E)
  957. container.innerHTML =
  958. `<my-el-async msg="hello"></my-el-async>` +
  959. `<my-el-async msg="world"></my-el-async>`
  960. await new Promise(r => setTimeout(r))
  961. // loader should be called only once
  962. expect(loaderSpy).toHaveBeenCalledTimes(1)
  963. const e1 = container.childNodes[0] as VueElement
  964. const e2 = container.childNodes[1] as VueElement
  965. // should inject styles
  966. expect(e1.shadowRoot!.innerHTML).toBe(
  967. `<style>div { color: red }</style><div>hello</div>`,
  968. )
  969. expect(e2.shadowRoot!.innerHTML).toBe(
  970. `<style>div { color: red }</style><div>world</div>`,
  971. )
  972. // attr
  973. e1.setAttribute('msg', 'attr')
  974. await nextTick()
  975. expect((e1 as any).msg).toBe('attr')
  976. expect(e1.shadowRoot!.innerHTML).toBe(
  977. `<style>div { color: red }</style><div>attr</div>`,
  978. )
  979. // props
  980. expect(`msg` in e1).toBe(true)
  981. ;(e1 as any).msg = 'prop'
  982. expect(e1.getAttribute('msg')).toBe('prop')
  983. expect(e1.shadowRoot!.innerHTML).toBe(
  984. `<style>div { color: red }</style><div>prop</div>`,
  985. )
  986. })
  987. test('set DOM property before resolve', async () => {
  988. const E = defineCustomElement(
  989. defineAsyncComponent(() => {
  990. return Promise.resolve({
  991. props: ['msg'],
  992. setup(props) {
  993. expect(typeof props.msg).toBe('string')
  994. },
  995. render(this: any) {
  996. return h('div', this.msg)
  997. },
  998. })
  999. }),
  1000. )
  1001. customElements.define('my-el-async-2', E)
  1002. const e1 = new E()
  1003. // set property before connect
  1004. e1.msg = 'hello'
  1005. const e2 = new E()
  1006. container.appendChild(e1)
  1007. container.appendChild(e2)
  1008. // set property after connect but before resolve
  1009. e2.msg = 'world'
  1010. await new Promise(r => setTimeout(r))
  1011. expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1012. expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1013. e1.msg = 'world'
  1014. expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1015. e2.msg = 'hello'
  1016. expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1017. })
  1018. test('Number prop casting before resolve', async () => {
  1019. const E = defineCustomElement(
  1020. defineAsyncComponent(() => {
  1021. return Promise.resolve({
  1022. props: { n: Number },
  1023. setup(props) {
  1024. expect(props.n).toBe(20)
  1025. },
  1026. render(this: any) {
  1027. return h('div', this.n + ',' + typeof this.n)
  1028. },
  1029. })
  1030. }),
  1031. )
  1032. customElements.define('my-el-async-3', E)
  1033. container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
  1034. await new Promise(r => setTimeout(r))
  1035. const e = container.childNodes[0] as VueElement
  1036. expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
  1037. })
  1038. test('with slots', async () => {
  1039. const E = defineCustomElement(
  1040. defineAsyncComponent(() => {
  1041. return Promise.resolve({
  1042. render(this: any) {
  1043. return [
  1044. h('div', null, [
  1045. renderSlot(this.$slots, 'default', undefined, () => [
  1046. h('div', 'fallback'),
  1047. ]),
  1048. ]),
  1049. h('div', null, renderSlot(this.$slots, 'named')),
  1050. ]
  1051. },
  1052. })
  1053. }),
  1054. )
  1055. customElements.define('my-el-async-slots', E)
  1056. container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
  1057. await new Promise(r => setTimeout(r))
  1058. const e = container.childNodes[0] as VueElement
  1059. expect(e.shadowRoot!.innerHTML).toBe(
  1060. `<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`,
  1061. )
  1062. })
  1063. })
  1064. describe('shadowRoot: false', () => {
  1065. const E = defineCustomElement({
  1066. shadowRoot: false,
  1067. props: {
  1068. msg: {
  1069. type: String,
  1070. default: 'hello',
  1071. },
  1072. },
  1073. render() {
  1074. return h('div', this.msg)
  1075. },
  1076. })
  1077. customElements.define('my-el-shadowroot-false', E)
  1078. test('should work', async () => {
  1079. function raf() {
  1080. return new Promise(resolve => {
  1081. requestAnimationFrame(resolve)
  1082. })
  1083. }
  1084. container.innerHTML = `<my-el-shadowroot-false></my-el-shadowroot-false>`
  1085. const e = container.childNodes[0] as VueElement
  1086. await raf()
  1087. expect(e).toBeInstanceOf(E)
  1088. expect(e._instance).toBeTruthy()
  1089. expect(e.innerHTML).toBe(`<div>hello</div>`)
  1090. expect(e.shadowRoot).toBe(null)
  1091. })
  1092. const toggle = ref(true)
  1093. const ES = defineCustomElement(
  1094. {
  1095. render() {
  1096. return [
  1097. renderSlot(this.$slots, 'default'),
  1098. toggle.value ? renderSlot(this.$slots, 'named') : null,
  1099. renderSlot(this.$slots, 'omitted', {}, () => [
  1100. h('div', 'fallback'),
  1101. ]),
  1102. ]
  1103. },
  1104. },
  1105. { shadowRoot: false },
  1106. )
  1107. customElements.define('my-el-shadowroot-false-slots', ES)
  1108. test('should render slots', async () => {
  1109. container.innerHTML =
  1110. `<my-el-shadowroot-false-slots>` +
  1111. `<span>default</span>text` +
  1112. `<div slot="named">named</div>` +
  1113. `</my-el-shadowroot-false-slots>`
  1114. const e = container.childNodes[0] as VueElement
  1115. // native slots allocation does not affect innerHTML, so we just
  1116. // verify that we've rendered the correct native slots here...
  1117. expect(e.innerHTML).toBe(
  1118. `<span>default</span>text` +
  1119. `<div slot="named">named</div>` +
  1120. `<div>fallback</div>`,
  1121. )
  1122. toggle.value = false
  1123. await nextTick()
  1124. expect(e.innerHTML).toBe(
  1125. `<span>default</span>text` + `<!---->` + `<div>fallback</div>`,
  1126. )
  1127. })
  1128. test('render nested customElement w/ shadowRoot false', async () => {
  1129. const calls: string[] = []
  1130. const Child = defineCustomElement(
  1131. {
  1132. setup() {
  1133. calls.push('child rendering')
  1134. onMounted(() => {
  1135. calls.push('child mounted')
  1136. })
  1137. },
  1138. render() {
  1139. return renderSlot(this.$slots, 'default')
  1140. },
  1141. },
  1142. { shadowRoot: false },
  1143. )
  1144. customElements.define('my-child', Child)
  1145. const Parent = defineCustomElement(
  1146. {
  1147. setup() {
  1148. calls.push('parent rendering')
  1149. onMounted(() => {
  1150. calls.push('parent mounted')
  1151. })
  1152. },
  1153. render() {
  1154. return renderSlot(this.$slots, 'default')
  1155. },
  1156. },
  1157. { shadowRoot: false },
  1158. )
  1159. customElements.define('my-parent', Parent)
  1160. const App = {
  1161. render() {
  1162. return h('my-parent', null, {
  1163. default: () => [
  1164. h('my-child', null, {
  1165. default: () => [h('span', null, 'default')],
  1166. }),
  1167. ],
  1168. })
  1169. },
  1170. }
  1171. const app = createApp(App)
  1172. app.mount(container)
  1173. await nextTick()
  1174. const e = container.childNodes[0] as VueElement
  1175. expect(e.innerHTML).toBe(
  1176. `<my-child data-v-app=""><span>default</span></my-child>`,
  1177. )
  1178. expect(calls).toEqual([
  1179. 'parent rendering',
  1180. 'parent mounted',
  1181. 'child rendering',
  1182. 'child mounted',
  1183. ])
  1184. app.unmount()
  1185. })
  1186. test('render nested Teleport w/ shadowRoot false', async () => {
  1187. const target = document.createElement('div')
  1188. const Child = defineCustomElement(
  1189. {
  1190. render() {
  1191. return h(
  1192. Teleport,
  1193. { to: target },
  1194. {
  1195. default: () => [renderSlot(this.$slots, 'default')],
  1196. },
  1197. )
  1198. },
  1199. },
  1200. { shadowRoot: false },
  1201. )
  1202. customElements.define('my-el-teleport-child', Child)
  1203. const Parent = defineCustomElement(
  1204. {
  1205. render() {
  1206. return renderSlot(this.$slots, 'default')
  1207. },
  1208. },
  1209. { shadowRoot: false },
  1210. )
  1211. customElements.define('my-el-teleport-parent', Parent)
  1212. const App = {
  1213. render() {
  1214. return h('my-el-teleport-parent', null, {
  1215. default: () => [
  1216. h('my-el-teleport-child', null, {
  1217. default: () => [h('span', null, 'default')],
  1218. }),
  1219. ],
  1220. })
  1221. },
  1222. }
  1223. const app = createApp(App)
  1224. app.mount(container)
  1225. await nextTick()
  1226. expect(target.innerHTML).toBe(`<span>default</span>`)
  1227. app.unmount()
  1228. })
  1229. test('render two Teleports w/ shadowRoot false', async () => {
  1230. const target1 = document.createElement('div')
  1231. const target2 = document.createElement('span')
  1232. const Child = defineCustomElement(
  1233. {
  1234. render() {
  1235. return [
  1236. h(Teleport, { to: target1 }, [renderSlot(this.$slots, 'header')]),
  1237. h(Teleport, { to: target2 }, [renderSlot(this.$slots, 'body')]),
  1238. ]
  1239. },
  1240. },
  1241. { shadowRoot: false },
  1242. )
  1243. customElements.define('my-el-two-teleport-child', Child)
  1244. const App = {
  1245. render() {
  1246. return h('my-el-two-teleport-child', null, {
  1247. default: () => [
  1248. h('div', { slot: 'header' }, 'header'),
  1249. h('span', { slot: 'body' }, 'body'),
  1250. ],
  1251. })
  1252. },
  1253. }
  1254. const app = createApp(App)
  1255. app.mount(container)
  1256. await nextTick()
  1257. expect(target1.outerHTML).toBe(
  1258. `<div><div slot="header">header</div></div>`,
  1259. )
  1260. expect(target2.outerHTML).toBe(
  1261. `<span><span slot="body">body</span></span>`,
  1262. )
  1263. app.unmount()
  1264. })
  1265. test('render two Teleports w/ shadowRoot false (with disabled)', async () => {
  1266. const target1 = document.createElement('div')
  1267. const target2 = document.createElement('span')
  1268. const Child = defineCustomElement(
  1269. {
  1270. render() {
  1271. return [
  1272. // with disabled: true
  1273. h(Teleport, { to: target1, disabled: true }, [
  1274. renderSlot(this.$slots, 'header'),
  1275. ]),
  1276. h(Teleport, { to: target2 }, [renderSlot(this.$slots, 'body')]),
  1277. ]
  1278. },
  1279. },
  1280. { shadowRoot: false },
  1281. )
  1282. customElements.define('my-el-two-teleport-child-0', Child)
  1283. const App = {
  1284. render() {
  1285. return h('my-el-two-teleport-child-0', null, {
  1286. default: () => [
  1287. h('div', { slot: 'header' }, 'header'),
  1288. h('span', { slot: 'body' }, 'body'),
  1289. ],
  1290. })
  1291. },
  1292. }
  1293. const app = createApp(App)
  1294. app.mount(container)
  1295. await nextTick()
  1296. expect(target1.outerHTML).toBe(`<div></div>`)
  1297. expect(target2.outerHTML).toBe(
  1298. `<span><span slot="body">body</span></span>`,
  1299. )
  1300. app.unmount()
  1301. })
  1302. test('toggle nested custom element with shadowRoot: false', async () => {
  1303. customElements.define(
  1304. 'my-el-child-shadow-false',
  1305. defineCustomElement(
  1306. {
  1307. render(ctx: any) {
  1308. return h('div', null, [renderSlot(ctx.$slots, 'default')])
  1309. },
  1310. },
  1311. { shadowRoot: false },
  1312. ),
  1313. )
  1314. const ChildWrapper = {
  1315. render() {
  1316. return h('my-el-child-shadow-false', null, 'child')
  1317. },
  1318. }
  1319. customElements.define(
  1320. 'my-el-parent-shadow-false',
  1321. defineCustomElement(
  1322. {
  1323. props: {
  1324. isShown: { type: Boolean, required: true },
  1325. },
  1326. render(ctx: any, _: any, $props: any) {
  1327. return $props.isShown
  1328. ? h('div', { key: 0 }, [renderSlot(ctx.$slots, 'default')])
  1329. : null
  1330. },
  1331. },
  1332. { shadowRoot: false },
  1333. ),
  1334. )
  1335. const ParentWrapper = {
  1336. props: {
  1337. isShown: { type: Boolean, required: true },
  1338. },
  1339. render(ctx: any, _: any, $props: any) {
  1340. return h('my-el-parent-shadow-false', { isShown: $props.isShown }, [
  1341. renderSlot(ctx.$slots, 'default'),
  1342. ])
  1343. },
  1344. }
  1345. const isShown = ref(true)
  1346. const App = {
  1347. render() {
  1348. return h(ParentWrapper, { isShown: isShown.value } as any, {
  1349. default: () => [h(ChildWrapper)],
  1350. })
  1351. },
  1352. }
  1353. const container = document.createElement('div')
  1354. document.body.appendChild(container)
  1355. const app = createApp(App)
  1356. app.mount(container)
  1357. expect(container.innerHTML).toBe(
  1358. `<my-el-parent-shadow-false is-shown="" data-v-app="">` +
  1359. `<div>` +
  1360. `<my-el-child-shadow-false data-v-app="">` +
  1361. `<div>child</div>` +
  1362. `</my-el-child-shadow-false>` +
  1363. `</div>` +
  1364. `</my-el-parent-shadow-false>`,
  1365. )
  1366. isShown.value = false
  1367. await nextTick()
  1368. expect(container.innerHTML).toBe(
  1369. `<my-el-parent-shadow-false data-v-app=""><!----></my-el-parent-shadow-false>`,
  1370. )
  1371. isShown.value = true
  1372. await nextTick()
  1373. expect(container.innerHTML).toBe(
  1374. `<my-el-parent-shadow-false data-v-app="" is-shown="">` +
  1375. `<div>` +
  1376. `<my-el-child-shadow-false data-v-app="">` +
  1377. `<div>child</div>` +
  1378. `</my-el-child-shadow-false>` +
  1379. `</div>` +
  1380. `</my-el-parent-shadow-false>`,
  1381. )
  1382. })
  1383. })
  1384. describe('helpers', () => {
  1385. test('useHost', () => {
  1386. const Foo = defineCustomElement({
  1387. setup() {
  1388. const host = useHost()!
  1389. host.setAttribute('id', 'host')
  1390. return () => h('div', 'hello')
  1391. },
  1392. })
  1393. customElements.define('my-el-use-host', Foo)
  1394. container.innerHTML = `<my-el-use-host>`
  1395. const el = container.childNodes[0] as VueElement
  1396. expect(el.id).toBe('host')
  1397. })
  1398. test('useShadowRoot for style injection', () => {
  1399. const Foo = defineCustomElement({
  1400. setup() {
  1401. const root = useShadowRoot()!
  1402. const style = document.createElement('style')
  1403. style.innerHTML = `div { color: red; }`
  1404. root.appendChild(style)
  1405. return () => h('div', 'hello')
  1406. },
  1407. })
  1408. customElements.define('my-el-use-shadow-root', Foo)
  1409. container.innerHTML = `<my-el-use-shadow-root>`
  1410. const el = container.childNodes[0] as VueElement
  1411. const style = el.shadowRoot?.querySelector('style')!
  1412. expect(style.textContent).toBe(`div { color: red; }`)
  1413. })
  1414. })
  1415. describe('expose', () => {
  1416. test('expose w/ options api', async () => {
  1417. const E = defineCustomElement({
  1418. data() {
  1419. return {
  1420. value: 0,
  1421. }
  1422. },
  1423. methods: {
  1424. foo() {
  1425. ;(this as any).value++
  1426. },
  1427. },
  1428. expose: ['foo'],
  1429. render(_ctx: any) {
  1430. return h('div', null, _ctx.value)
  1431. },
  1432. })
  1433. customElements.define('my-el-expose-options-api', E)
  1434. container.innerHTML = `<my-el-expose-options-api></my-el-expose-options-api>`
  1435. const e = container.childNodes[0] as VueElement & {
  1436. foo: () => void
  1437. }
  1438. expect(e.shadowRoot!.innerHTML).toBe(`<div>0</div>`)
  1439. e.foo()
  1440. await nextTick()
  1441. expect(e.shadowRoot!.innerHTML).toBe(`<div>1</div>`)
  1442. })
  1443. test('expose attributes and callback', async () => {
  1444. type SetValue = (value: string) => void
  1445. let fn: MockedFunction<SetValue>
  1446. const E = defineCustomElement({
  1447. setup(_, { expose }) {
  1448. const value = ref('hello')
  1449. const setValue = (fn = vi.fn((_value: string) => {
  1450. value.value = _value
  1451. }))
  1452. expose({
  1453. setValue,
  1454. value,
  1455. })
  1456. return () => h('div', null, [value.value])
  1457. },
  1458. })
  1459. customElements.define('my-el-expose', E)
  1460. container.innerHTML = `<my-el-expose></my-el-expose>`
  1461. const e = container.childNodes[0] as VueElement & {
  1462. value: string
  1463. setValue: MockedFunction<SetValue>
  1464. }
  1465. expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
  1466. expect(e.value).toBe('hello')
  1467. expect(e.setValue).toBe(fn!)
  1468. e.setValue('world')
  1469. expect(e.value).toBe('world')
  1470. await nextTick()
  1471. expect(e.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
  1472. })
  1473. test('warning when exposing an existing property', () => {
  1474. const E = defineCustomElement({
  1475. props: {
  1476. value: String,
  1477. },
  1478. setup(props, { expose }) {
  1479. expose({
  1480. value: 'hello',
  1481. })
  1482. return () => h('div', null, [props.value])
  1483. },
  1484. })
  1485. customElements.define('my-el-expose-two', E)
  1486. container.innerHTML = `<my-el-expose-two value="world"></my-el-expose-two>`
  1487. expect(
  1488. `[Vue warn]: Exposed property "value" already exists on custom element.`,
  1489. ).toHaveBeenWarned()
  1490. })
  1491. })
  1492. test('async & nested custom elements', async () => {
  1493. let fooVal: string | undefined = ''
  1494. const E = defineCustomElement(
  1495. defineAsyncComponent(() => {
  1496. return Promise.resolve({
  1497. setup(props) {
  1498. provide('foo', 'foo')
  1499. },
  1500. render(this: any) {
  1501. return h('div', null, [renderSlot(this.$slots, 'default')])
  1502. },
  1503. })
  1504. }),
  1505. )
  1506. const EChild = defineCustomElement({
  1507. setup(props) {
  1508. fooVal = inject('foo')
  1509. },
  1510. render(this: any) {
  1511. return h('div', null, 'child')
  1512. },
  1513. })
  1514. customElements.define('my-el-async-nested-ce', E)
  1515. customElements.define('slotted-child', EChild)
  1516. container.innerHTML = `<my-el-async-nested-ce><div><slotted-child></slotted-child></div></my-el-async-nested-ce>`
  1517. await new Promise(r => setTimeout(r))
  1518. const e = container.childNodes[0] as VueElement
  1519. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1520. expect(fooVal).toBe('foo')
  1521. })
  1522. test('async & multiple levels of nested custom elements', async () => {
  1523. let fooVal: string | undefined = ''
  1524. let barVal: string | undefined = ''
  1525. const E = defineCustomElement(
  1526. defineAsyncComponent(() => {
  1527. return Promise.resolve({
  1528. setup(props) {
  1529. provide('foo', 'foo')
  1530. },
  1531. render(this: any) {
  1532. return h('div', null, [renderSlot(this.$slots, 'default')])
  1533. },
  1534. })
  1535. }),
  1536. )
  1537. const EChild = defineCustomElement({
  1538. setup(props) {
  1539. provide('bar', 'bar')
  1540. },
  1541. render(this: any) {
  1542. return h('div', null, [renderSlot(this.$slots, 'default')])
  1543. },
  1544. })
  1545. const EChild2 = defineCustomElement({
  1546. setup(props) {
  1547. fooVal = inject('foo')
  1548. barVal = inject('bar')
  1549. },
  1550. render(this: any) {
  1551. return h('div', null, 'child')
  1552. },
  1553. })
  1554. customElements.define('my-el-async-nested-m-ce', E)
  1555. customElements.define('slotted-child-m', EChild)
  1556. customElements.define('slotted-child2-m', EChild2)
  1557. container.innerHTML =
  1558. `<my-el-async-nested-m-ce>` +
  1559. `<div><slotted-child-m>` +
  1560. `<slotted-child2-m></slotted-child2-m>` +
  1561. `</slotted-child-m></div>` +
  1562. `</my-el-async-nested-m-ce>`
  1563. await new Promise(r => setTimeout(r))
  1564. const e = container.childNodes[0] as VueElement
  1565. expect(e.shadowRoot!.innerHTML).toBe(`<div><slot></slot></div>`)
  1566. expect(fooVal).toBe('foo')
  1567. expect(barVal).toBe('bar')
  1568. })
  1569. describe('configureApp', () => {
  1570. test('should work', () => {
  1571. const E = defineCustomElement(
  1572. () => {
  1573. const msg = inject('msg')
  1574. return () => h('div', msg!)
  1575. },
  1576. {
  1577. configureApp(app) {
  1578. app.provide('msg', 'app-injected')
  1579. },
  1580. },
  1581. )
  1582. customElements.define('my-element-with-app', E)
  1583. container.innerHTML = `<my-element-with-app></my-element-with-app>`
  1584. const e = container.childNodes[0] as VueElement
  1585. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1586. })
  1587. // #12448
  1588. test('work with async component', async () => {
  1589. const AsyncComp = defineAsyncComponent(() => {
  1590. return Promise.resolve({
  1591. render() {
  1592. const msg: string | undefined = inject('msg')
  1593. return h('div', {}, msg)
  1594. },
  1595. } as any)
  1596. })
  1597. const E = defineCustomElement(AsyncComp, {
  1598. configureApp(app) {
  1599. app.provide('msg', 'app-injected')
  1600. },
  1601. })
  1602. customElements.define('my-async-element-with-app', E)
  1603. container.innerHTML = `<my-async-element-with-app></my-async-element-with-app>`
  1604. const e = container.childNodes[0] as VueElement
  1605. await new Promise(r => setTimeout(r))
  1606. expect(e.shadowRoot?.innerHTML).toBe('<div>app-injected</div>')
  1607. })
  1608. test('with hmr reload', async () => {
  1609. const __hmrId = '__hmrWithApp'
  1610. const def = defineComponent({
  1611. __hmrId,
  1612. setup() {
  1613. const msg = inject('msg')
  1614. return { msg }
  1615. },
  1616. render(this: any) {
  1617. return h('div', [h('span', this.msg), h('span', this.$foo)])
  1618. },
  1619. })
  1620. const E = defineCustomElement(def, {
  1621. configureApp(app) {
  1622. app.provide('msg', 'app-injected')
  1623. app.config.globalProperties.$foo = 'foo'
  1624. },
  1625. })
  1626. customElements.define('my-element-with-app-hmr', E)
  1627. container.innerHTML = `<my-element-with-app-hmr></my-element-with-app-hmr>`
  1628. const el = container.childNodes[0] as VueElement
  1629. expect(el.shadowRoot?.innerHTML).toBe(
  1630. `<div><span>app-injected</span><span>foo</span></div>`,
  1631. )
  1632. // hmr
  1633. __VUE_HMR_RUNTIME__.reload(__hmrId, def as any)
  1634. await nextTick()
  1635. expect(el.shadowRoot?.innerHTML).toBe(
  1636. `<div><span>app-injected</span><span>foo</span></div>`,
  1637. )
  1638. })
  1639. })
  1640. // #9885
  1641. test('avoid double mount when prop is set immediately after mount', () => {
  1642. customElements.define(
  1643. 'my-input-dupe',
  1644. defineCustomElement({
  1645. props: {
  1646. value: String,
  1647. },
  1648. render() {
  1649. return 'hello'
  1650. },
  1651. }),
  1652. )
  1653. const container = document.createElement('div')
  1654. document.body.appendChild(container)
  1655. createApp({
  1656. render() {
  1657. return h('div', [
  1658. h('my-input-dupe', {
  1659. onVnodeMounted(vnode) {
  1660. vnode.el!.value = 'fesfes'
  1661. },
  1662. }),
  1663. ])
  1664. },
  1665. }).mount(container)
  1666. expect(container.children[0].children[0].shadowRoot?.innerHTML).toBe(
  1667. 'hello',
  1668. )
  1669. })
  1670. // #11081
  1671. test('Props can be casted when mounting custom elements in component rendering functions', async () => {
  1672. const E = defineCustomElement(
  1673. defineAsyncComponent(() =>
  1674. Promise.resolve({
  1675. props: ['fooValue'],
  1676. setup(props) {
  1677. expect(props.fooValue).toBe('fooValue')
  1678. return () => h('div', props.fooValue)
  1679. },
  1680. }),
  1681. ),
  1682. )
  1683. customElements.define('my-el-async-4', E)
  1684. const R = defineComponent({
  1685. setup() {
  1686. const fooValue = ref('fooValue')
  1687. return () => {
  1688. return h('div', null, [
  1689. h('my-el-async-4', {
  1690. fooValue: fooValue.value,
  1691. }),
  1692. ])
  1693. }
  1694. },
  1695. })
  1696. const app = createApp(R)
  1697. app.mount(container)
  1698. await new Promise(r => setTimeout(r))
  1699. const e = container.querySelector('my-el-async-4') as VueElement
  1700. expect(e.shadowRoot!.innerHTML).toBe(`<div>fooValue</div>`)
  1701. app.unmount()
  1702. })
  1703. // #11276
  1704. test('delete prop on attr removal', async () => {
  1705. const E = defineCustomElement({
  1706. props: {
  1707. boo: {
  1708. type: Boolean,
  1709. },
  1710. },
  1711. render() {
  1712. return this.boo + ',' + typeof this.boo
  1713. },
  1714. })
  1715. customElements.define('el-attr-removal', E)
  1716. container.innerHTML = '<el-attr-removal boo>'
  1717. const e = container.childNodes[0] as VueElement
  1718. expect(e.shadowRoot!.innerHTML).toBe(`true,boolean`)
  1719. e.removeAttribute('boo')
  1720. await nextTick()
  1721. expect(e.shadowRoot!.innerHTML).toBe(`false,boolean`)
  1722. })
  1723. test('hyphenated attr removal', async () => {
  1724. const E = defineCustomElement({
  1725. props: {
  1726. fooBar: {
  1727. type: Boolean,
  1728. },
  1729. },
  1730. render() {
  1731. return this.fooBar
  1732. },
  1733. })
  1734. customElements.define('el-hyphenated-attr-removal', E)
  1735. const toggle = ref(true)
  1736. const Comp = {
  1737. render() {
  1738. return h('el-hyphenated-attr-removal', {
  1739. 'foo-bar': toggle.value ? '' : null,
  1740. })
  1741. },
  1742. }
  1743. render(h(Comp), container)
  1744. const el = container.children[0]
  1745. expect(el.hasAttribute('foo-bar')).toBe(true)
  1746. expect((el as any).outerHTML).toBe(
  1747. `<el-hyphenated-attr-removal foo-bar=""></el-hyphenated-attr-removal>`,
  1748. )
  1749. toggle.value = false
  1750. await nextTick()
  1751. expect(el.hasAttribute('foo-bar')).toBe(false)
  1752. expect((el as any).outerHTML).toBe(
  1753. `<el-hyphenated-attr-removal></el-hyphenated-attr-removal>`,
  1754. )
  1755. })
  1756. test('no unexpected mutation of the 1st argument', () => {
  1757. const Foo = {
  1758. name: 'Foo',
  1759. }
  1760. defineCustomElement(Foo, { shadowRoot: false })
  1761. expect(Foo).toEqual({
  1762. name: 'Foo',
  1763. })
  1764. })
  1765. })