component.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import {
  2. type EffectScope,
  3. ReactiveEffect,
  4. type Ref,
  5. inject,
  6. nextTick,
  7. onMounted,
  8. onUpdated,
  9. provide,
  10. ref,
  11. toDisplayString,
  12. useAttrs,
  13. watch,
  14. watchEffect,
  15. } from '@vue/runtime-dom'
  16. import {
  17. createComponent,
  18. createIf,
  19. createTextNode,
  20. defineVaporComponent,
  21. renderEffect,
  22. setInsertionState,
  23. template,
  24. txt,
  25. } from '../src'
  26. import { makeRender } from './_utils'
  27. import type { VaporComponentInstance } from '../src/component'
  28. import { setElementText, setText } from '../src/dom/prop'
  29. const define = makeRender()
  30. describe('component', () => {
  31. it('should update parent(hoc) component host el when child component self update', async () => {
  32. const value = ref(true)
  33. let childNode1: Node | null = null
  34. let childNode2: Node | null = null
  35. const { component: Child } = define({
  36. setup() {
  37. return createIf(
  38. () => value.value,
  39. () => (childNode1 = template('<div></div>')()),
  40. () => (childNode2 = template('<span></span>')()),
  41. )
  42. },
  43. })
  44. const { host } = define({
  45. setup() {
  46. return createComponent(Child)
  47. },
  48. }).render()
  49. expect(host.innerHTML).toBe('<div></div><!--if-->')
  50. expect(host.children[0]).toBe(childNode1)
  51. value.value = false
  52. await nextTick()
  53. expect(host.innerHTML).toBe('<span></span><!--if-->')
  54. expect(host.children[0]).toBe(childNode2)
  55. })
  56. it('should create a component with props', () => {
  57. const { component: Comp } = define({
  58. setup() {
  59. return template('<div>', true)()
  60. },
  61. })
  62. const { host } = define({
  63. setup() {
  64. return createComponent(Comp, { id: () => 'foo', class: () => 'bar' })
  65. },
  66. }).render()
  67. expect(host.innerHTML).toBe('<div id="foo" class="bar"></div>')
  68. })
  69. it('should not update Component if only changed props are declared emit listeners', async () => {
  70. const updatedSyp = vi.fn()
  71. const { component: Comp } = define({
  72. emits: ['foo'],
  73. setup() {
  74. onUpdated(updatedSyp)
  75. return template('<div>', true)()
  76. },
  77. })
  78. const toggle = ref(true)
  79. const fn1 = () => {}
  80. const fn2 = () => {}
  81. define({
  82. setup() {
  83. const _on_foo = () => (toggle.value ? fn1() : fn2())
  84. return createComponent(Comp, { onFoo: () => _on_foo })
  85. },
  86. }).render()
  87. expect(updatedSyp).toHaveBeenCalledTimes(0)
  88. toggle.value = false
  89. await nextTick()
  90. expect(updatedSyp).toHaveBeenCalledTimes(0)
  91. })
  92. it('component child synchronously updating parent state should trigger parent re-render', async () => {
  93. const { component: Child } = define({
  94. setup() {
  95. const n = inject<Ref<number>>('foo')!
  96. n.value++
  97. const n0 = template('<div></div>')()
  98. renderEffect(() => setElementText(n0, n.value))
  99. return n0
  100. },
  101. })
  102. const { host } = define({
  103. setup() {
  104. const n = ref(0)
  105. provide('foo', n)
  106. const n0 = template('<div></div>')()
  107. renderEffect(() => setElementText(n0, n.value))
  108. return [n0, createComponent(Child)]
  109. },
  110. }).render()
  111. expect(host.innerHTML).toBe('<div>0</div><div>1</div>')
  112. await nextTick()
  113. expect(host.innerHTML).toBe('<div>1</div><div>1</div>')
  114. })
  115. it('component child updating parent state in pre-flush should trigger parent re-render', async () => {
  116. const { component: Child } = define({
  117. props: ['value'],
  118. setup(props: any, { emit }) {
  119. watch(
  120. () => props.value,
  121. val => emit('update', val),
  122. )
  123. const n0 = template('<div></div>')()
  124. renderEffect(() => setElementText(n0, props.value))
  125. return n0
  126. },
  127. })
  128. const outer = ref(0)
  129. const { host } = define({
  130. setup() {
  131. const inner = ref(0)
  132. const n0 = template('<div></div>')()
  133. renderEffect(() => setElementText(n0, inner.value))
  134. const n1 = createComponent(Child, {
  135. value: () => outer.value,
  136. onUpdate: () => (val: number) => (inner.value = val),
  137. })
  138. return [n0, n1]
  139. },
  140. }).render()
  141. expect(host.innerHTML).toBe('<div>0</div><div>0</div>')
  142. outer.value++
  143. await nextTick()
  144. expect(host.innerHTML).toBe('<div>1</div><div>1</div>')
  145. })
  146. it('events in dynamic props', async () => {
  147. const { component: Child } = define({
  148. props: ['count'],
  149. setup(props: any, { emit }) {
  150. emit('update', props.count + 1)
  151. const n0 = template('<div></div>')()
  152. renderEffect(() => setElementText(n0, props.count))
  153. return n0
  154. },
  155. })
  156. const count = ref(0)
  157. const { host } = define({
  158. setup() {
  159. const n0 = createComponent(Child, {
  160. $: [
  161. () => ({
  162. count: count.value,
  163. }),
  164. { onUpdate: () => (val: number) => (count.value = val) },
  165. ],
  166. })
  167. return n0
  168. },
  169. }).render()
  170. expect(host.innerHTML).toBe('<div>1</div>')
  171. })
  172. it('child only updates once when triggered in multiple ways', async () => {
  173. const a = ref(0)
  174. const calls: string[] = []
  175. const { component: Child } = define({
  176. props: ['count'],
  177. setup(props: any) {
  178. onUpdated(() => calls.push('update child'))
  179. const n = createTextNode()
  180. renderEffect(() => {
  181. setText(n, `${props.count} - ${a.value}`)
  182. })
  183. return n
  184. },
  185. })
  186. const { host } = define({
  187. setup() {
  188. return createComponent(Child, { count: () => a.value })
  189. },
  190. }).render()
  191. expect(host.innerHTML).toBe('0 - 0')
  192. expect(calls).toEqual([])
  193. // This will trigger child rendering directly, as well as via a prop change
  194. a.value++
  195. await nextTick()
  196. expect(host.innerHTML).toBe('1 - 1')
  197. expect(calls).toEqual(['update child'])
  198. })
  199. it(`an earlier update doesn't lead to excessive subsequent updates`, async () => {
  200. const globalCount = ref(0)
  201. const parentCount = ref(0)
  202. const calls: string[] = []
  203. const { component: Child } = define({
  204. props: ['count'],
  205. setup(props: any) {
  206. watch(
  207. () => props.count,
  208. () => {
  209. calls.push('child watcher')
  210. globalCount.value = props.count
  211. },
  212. )
  213. onUpdated(() => calls.push('update child'))
  214. return []
  215. },
  216. })
  217. const { component: Parent } = define({
  218. props: ['count'],
  219. setup(props: any) {
  220. onUpdated(() => calls.push('update parent'))
  221. const n1 = createTextNode()
  222. const n2 = createComponent(Child, { count: () => parentCount.value })
  223. renderEffect(() => {
  224. setText(n1, `${globalCount.value} - ${props.count}`)
  225. })
  226. return [n1, n2]
  227. },
  228. })
  229. const { host } = define({
  230. setup() {
  231. onUpdated(() => calls.push('update root'))
  232. return createComponent(Parent, { count: () => globalCount.value })
  233. },
  234. }).render()
  235. expect(host.innerHTML).toBe(`0 - 0`)
  236. expect(calls).toEqual([])
  237. parentCount.value++
  238. await nextTick()
  239. expect(host.innerHTML).toBe(`1 - 1`)
  240. expect(calls).toEqual(['child watcher', 'update parent'])
  241. })
  242. it('child component props update should not lead to double update', async () => {
  243. const text = ref(0)
  244. const spy = vi.fn()
  245. const { component: Comp } = define({
  246. props: ['text'],
  247. setup(props: any) {
  248. const n1 = template('<h1></h1>')()
  249. renderEffect(() => {
  250. spy()
  251. setElementText(n1, props.text)
  252. })
  253. return n1
  254. },
  255. })
  256. const { host } = define({
  257. setup() {
  258. return createComponent(Comp, { text: () => text.value })
  259. },
  260. }).render()
  261. expect(host.innerHTML).toBe('<h1>0</h1>')
  262. expect(spy).toHaveBeenCalledTimes(1)
  263. text.value++
  264. await nextTick()
  265. expect(host.innerHTML).toBe('<h1>1</h1>')
  266. expect(spy).toHaveBeenCalledTimes(2)
  267. })
  268. it('properly mount child component when using setInsertionState', async () => {
  269. const spy = vi.fn()
  270. const { component: Comp } = define({
  271. setup() {
  272. onMounted(spy)
  273. return template('<h1>hi</h1>')()
  274. },
  275. })
  276. const { host } = define({
  277. setup() {
  278. const n2 = template('<div></div>', true)()
  279. setInsertionState(n2 as any)
  280. createComponent(Comp)
  281. return n2
  282. },
  283. }).render()
  284. expect(host.innerHTML).toBe('<div><h1>hi</h1></div>')
  285. expect(spy).toHaveBeenCalledTimes(1)
  286. })
  287. it('unmount component', async () => {
  288. const { host, app, instance } = define(() => {
  289. const count = ref(0)
  290. const t0 = template('<div></div>')
  291. const n0 = t0()
  292. watchEffect(() => {
  293. setElementText(n0, count.value)
  294. })
  295. renderEffect(() => {})
  296. return n0
  297. }).render()
  298. const i = instance as VaporComponentInstance
  299. // watchEffect + renderEffect + props validation effect
  300. expect(getEffectsCount(i.scope)).toBe(3)
  301. expect(host.innerHTML).toBe('<div>0</div>')
  302. app.unmount()
  303. expect(host.innerHTML).toBe('')
  304. expect(getEffectsCount(i.scope)).toBe(0)
  305. })
  306. it('work with v-once + props', () => {
  307. const Child = defineVaporComponent({
  308. props: {
  309. count: Number,
  310. },
  311. setup(props) {
  312. const n0 = template(' ')() as any
  313. renderEffect(() => setText(n0, String(props.count)))
  314. return n0
  315. },
  316. })
  317. const count = ref(0)
  318. const { html } = define({
  319. setup() {
  320. return createComponent(
  321. Child,
  322. { count: () => count.value },
  323. null,
  324. true,
  325. true, // v-once
  326. )
  327. },
  328. }).render()
  329. expect(html()).toBe('0')
  330. count.value++
  331. expect(html()).toBe('0')
  332. })
  333. it('work with v-once + attrs', () => {
  334. const Child = defineVaporComponent({
  335. setup() {
  336. const attrs = useAttrs()
  337. const n0 = template(' ')() as any
  338. renderEffect(() => setText(n0, attrs.count as string))
  339. return n0
  340. },
  341. })
  342. const count = ref(0)
  343. const { html } = define({
  344. setup() {
  345. return createComponent(
  346. Child,
  347. { count: () => count.value },
  348. null,
  349. true,
  350. true, // v-once
  351. )
  352. },
  353. }).render()
  354. expect(html()).toBe('0')
  355. count.value++
  356. expect(html()).toBe('0')
  357. })
  358. it('v-once props should be frozen and not update when parent changes', async () => {
  359. const localCount = ref(0)
  360. const Child = defineVaporComponent({
  361. props: {
  362. count: Number,
  363. },
  364. setup(props) {
  365. const n0 = template('<div></div>')() as any
  366. renderEffect(() =>
  367. setElementText(n0, `${localCount.value} - ${props.count}`),
  368. )
  369. return n0
  370. },
  371. })
  372. const parentCount = ref(0)
  373. const { html } = define({
  374. setup() {
  375. return createComponent(
  376. Child,
  377. { count: () => parentCount.value },
  378. null,
  379. true,
  380. true, // v-once
  381. )
  382. },
  383. }).render()
  384. expect(html()).toBe('<div>0 - 0</div>')
  385. parentCount.value++
  386. await nextTick()
  387. expect(html()).toBe('<div>0 - 0</div>')
  388. localCount.value++
  389. await nextTick()
  390. expect(html()).toBe('<div>1 - 0</div>')
  391. })
  392. it('v-once attrs should be frozen and not update when parent changes', async () => {
  393. const localCount = ref(0)
  394. const Child = defineVaporComponent({
  395. inheritAttrs: false,
  396. setup() {
  397. const attrs = useAttrs()
  398. const n0 = template('<div></div>')() as any
  399. renderEffect(() =>
  400. setElementText(n0, `${localCount.value} - ${attrs.count}`),
  401. )
  402. return n0
  403. },
  404. })
  405. const parentCount = ref(0)
  406. const { html } = define({
  407. setup() {
  408. return createComponent(
  409. Child,
  410. { count: () => parentCount.value },
  411. null,
  412. true,
  413. true, // v-once
  414. )
  415. },
  416. }).render()
  417. expect(html()).toBe('<div>0 - 0</div>')
  418. parentCount.value++
  419. await nextTick()
  420. expect(html()).toBe('<div>0 - 0</div>')
  421. localCount.value++
  422. await nextTick()
  423. expect(html()).toBe('<div>1 - 0</div>')
  424. })
  425. test('should mount component only with template in production mode', () => {
  426. __DEV__ = false
  427. const { component: Child } = define({
  428. render() {
  429. return template('<div> HI </div>', true)()
  430. },
  431. })
  432. const { host } = define({
  433. setup() {
  434. return createComponent(Child, null, null, true)
  435. },
  436. }).render()
  437. expect(host.innerHTML).toBe('<div> HI </div>')
  438. __DEV__ = true
  439. })
  440. it('warn if functional vapor component not return a block', () => {
  441. // @ts-expect-error
  442. define(() => {
  443. return () => {}
  444. }).render()
  445. expect(
  446. 'Functional vapor component must return a block directly',
  447. ).toHaveBeenWarned()
  448. })
  449. it('warn if setup return a function and no render function', () => {
  450. define({
  451. setup() {
  452. return () => []
  453. },
  454. }).render()
  455. expect(
  456. 'Vapor component setup() returned non-block value, and has no render function',
  457. ).toHaveBeenWarned()
  458. })
  459. it('warn non-existent property access', () => {
  460. define({
  461. setup() {
  462. return {}
  463. },
  464. render(ctx: any) {
  465. ctx.foo
  466. return []
  467. },
  468. }).render()
  469. expect(
  470. 'Property "foo" was accessed during render but is not defined on instance.',
  471. ).toHaveBeenWarned()
  472. })
  473. test('display attrs', () => {
  474. const App = defineVaporComponent({
  475. props: {},
  476. emits: [],
  477. setup(props, { attrs }) {
  478. const n0 = template('<div> ')() as any
  479. const x0 = txt(n0) as any
  480. renderEffect(() => setText(x0, toDisplayString(attrs)))
  481. return n0
  482. },
  483. })
  484. const { render } = define(App)
  485. expect(render).not.toThrow(TypeError)
  486. expect(
  487. 'Unhandled error during execution of setup function',
  488. ).not.toHaveBeenWarned()
  489. })
  490. })
  491. function getEffectsCount(scope: EffectScope): number {
  492. let n = 0
  493. for (let dep = scope.deps; dep !== undefined; dep = dep.nextDep) {
  494. if (dep.dep instanceof ReactiveEffect) {
  495. n++
  496. }
  497. }
  498. return n
  499. }