Open History to see the last commit
1import { basename, dirname, join } from 'node:path'
2import { fileURLToPath } from 'node:url'
3import { expect } from 'vitest'
4import {
5 createRoot as createOctaneRoot,
6 drainPassiveEffects,
7 flushSync,
8} from 'octane'
9import * as React from 'react'
10import { act as reactAct } from 'react'
11import { createRoot as createReactRoot } from 'react-dom/client'
12import type { Root as ReactRoot } from 'react-dom/client'
13β
14const directory = dirname(fileURLToPath(import.meta.url))
15const cacheDirectory = join(directory, '.react-cache')
16β
17;(
18 globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
19).IS_REACT_ACT_ENVIRONMENT = true
20β
21function hashString(value: string): string {
22 let hash = 5381
23 for (let index = 0; index < value.length; index++) {
24 hash = ((hash << 5) + hash + value.charCodeAt(index)) | 0
25 }
26 return Math.abs(hash).toString(36)
27}
28β
29function stripComments(value: string): string {
30 let output = ''
31 let index = 0
32 while (index < value.length) {
33 const open = value.indexOf('<!--', index)
34 if (open === -1) {
35 output += value.slice(index)
36 break
37 }
38 output += value.slice(index, open)
39 const close = value.indexOf('-->', open + 4)
40 if (close === -1) {
41 break
42 }
43 index = close + 3
44 }
45 return output
46}
47β
48function normalizeHtml(value: string): string {
49 return stripComments(value).replaceAll('\n', '').replaceAll('\t', '').trim()
50}
51β
52async function loadReactFixture(
53 sourcePath: string,
54): Promise<Record<string, unknown>> {
55 const slug = basename(sourcePath).replace(/\.tsrx$/, '')
56 const outputPath = join(
57 cacheDirectory,
58 `${slug}-${hashString(sourcePath)}.js`,
59 )
60 return import(/* @vite-ignore */ outputPath)
61}
62β
63interface DifferentialMount {
64 container: HTMLElement
65 click: (selector: string) => Promise<void>
66}
67β
68interface DifferentialPair {
69 step: (
70 name: string,
71 action: (
72 octane: DifferentialMount,
73 react: DifferentialMount,
74 ) => void | Promise<void>,
75 ) => Promise<void>
76 unmount: () => void
77}
78β
79export async function mountDifferential(
80 sourcePath: string,
81 exportName: string,
82): Promise<DifferentialPair> {
83 const octaneModule = await import(/* @vite-ignore */ sourcePath)
84 const reactModule = await loadReactFixture(sourcePath)
85 const OctaneComponent = octaneModule[exportName]
86 const ReactComponent = reactModule[exportName]
87β
88 if (typeof OctaneComponent !== 'function') {
89 throw new Error(`Octane export ${exportName} was not found`)
90 }
91 if (typeof ReactComponent !== 'function') {
92 throw new Error(`React export ${exportName} was not found`)
93 }
94β
95 const octaneContainer = document.createElement('div')
96 const reactContainer = document.createElement('div')
97 document.body.append(octaneContainer, reactContainer)
98β
99 const octaneRoot = createOctaneRoot(octaneContainer)
100 octaneRoot.render(OctaneComponent)
101 flushSync(() => {})
102β
103 const reactRoot: ReactRoot = createReactRoot(reactContainer)
104 await reactAct(async () => {
105 reactRoot.render(React.createElement(ReactComponent))
106 })
107β
108 function createMount(
109 container: HTMLElement,
110 react: boolean,
111 ): DifferentialMount {
112 return {
113 container,
114 async click(selector) {
115 let element = container.querySelector(selector)
116 if (!element && selector.startsWith('#')) {
117 const id = selector.slice(1)
118 element =
119 Array.from(container.getElementsByTagName('*')).find(
120 (candidate) => candidate.id === id,
121 ) ?? null
122 }
123 if (!(element instanceof HTMLElement)) {
124 throw new Error(`No element matches ${selector}`)
125 }
126 if (react) {
127 await reactAct(async () => element.click())
128 } else {
129 flushSync(() => element.click())
130 }
131 },
132 }
133 }
134β
135 const octane = createMount(octaneContainer, false)
136 const react = createMount(reactContainer, true)
137β
138 return {
139 async step(name, action) {
140 await action(octane, react)
141 drainPassiveEffects()
142 await reactAct(async () => {
143 await new Promise((resolve) => setTimeout(resolve, 0))
144 })
145 const octaneHtml = normalizeHtml(octaneContainer.innerHTML)
146 const reactHtml = normalizeHtml(reactContainer.innerHTML)
147 expect(octaneHtml, `Differential DOM divergence at ${name}`).toBe(
148 reactHtml,
149 )
150 },
151 unmount() {
152 octaneRoot.unmount()
153 reactAct(() => reactRoot.unmount())
154 octaneContainer.remove()
155 reactContainer.remove()
156 },
157 }
158}