@ecopages/react 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/package.json +5 -8
- package/src/bundling/runtime-interop-plugin.js +2 -2
- package/src/client-graph/boundary-plugin-read-file-inline.js +3 -3
- package/src/client-graph/boundary-plugin.js +3 -3
- package/src/hydration/browser/island-hydration.d.ts +0 -1
- package/src/hydration/browser/island-hydration.js +5 -9
- package/src/hydration/hydration-asset.d.ts +1 -0
- package/src/hydration/hydration-asset.js +21 -12
- package/src/hydration/hydration-page-entry-source.js +1 -1
- package/src/hydration/hydration-script-compiler.d.ts +0 -1
- package/src/hydration/hydration-script-compiler.js +4 -4
- package/src/app/dynamic.test.browser.d.ts +0 -1
- package/src/app/dynamic.test.browser.js +0 -38
- package/src/hydration/assert-no-bare-ecopages-imports.d.ts +0 -4
- package/src/hydration/assert-no-bare-ecopages-imports.js +0 -7
- package/src/hydration/hydration-lifecycle.test.browser.d.ts +0 -1
- package/src/hydration/hydration-lifecycle.test.browser.js +0 -461
package/README.md
CHANGED
|
@@ -27,6 +27,7 @@ For component-level islands, Ecopages React uses this contract:
|
|
|
27
27
|
- SSR output preserves the authored DOM structure (no unnecessary wrapper elements).
|
|
28
28
|
- A stable island host contract is stamped on the component SSR root via core (`data-eco-island`, `data-eco-island-integration`, `data-eco-component-id`, optional `data-eco-component-key` / `data-eco-props`).
|
|
29
29
|
- During non-HMR runtime rendering, island and lazy-entry client modules are built together from the page client plan, in one grouped browser build during route preparation. Static production export contributes React hydration and lazy entries, every Integration's Page Browser Graph entries, and HTML Page and `html.html` shell module scripts to compatible app-wide browser build groups. Hydration scripts import the recorded output URLs. Same-integration Page, Layout, and includes are hydrated by the page bootstrap. The Html shell is not an island, even when its Integration differs from the page owner. Only a React component whose Integration differs from its parent's, on another owner's page, receives a per-component island script. SSR stamps the host and attaches those assets; it does not start a per-island build.
|
|
30
|
+
- Each island component gets its own hydration script, keyed by its component identity. A file that exports several island components is built once and its declared modules are merged, while each component's hosts hydrate the export whose identity matches.
|
|
30
31
|
- The island runtime keeps the SSR host and its children in place and hydrates that host with `hydrateRoot()`. The host uses `display: contents` so it does not introduce an extra layout box. Full-page hydration paths also use `hydrateRoot()`.
|
|
31
32
|
|
|
32
33
|
> [!TIP]
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/react",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "React integration for Ecopages",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ecopages",
|
|
@@ -104,21 +104,18 @@
|
|
|
104
104
|
"directory": "packages/integrations/react"
|
|
105
105
|
},
|
|
106
106
|
"peerDependencies": {
|
|
107
|
-
"@ecopages/core": "0.3.
|
|
107
|
+
"@ecopages/core": "0.3.1",
|
|
108
108
|
"@types/react": "^19",
|
|
109
109
|
"@types/react-dom": "^19",
|
|
110
110
|
"react": "^19",
|
|
111
111
|
"react-dom": "^19"
|
|
112
112
|
},
|
|
113
113
|
"dependencies": {
|
|
114
|
-
"@ecopages/file-system": "0.3.
|
|
114
|
+
"@ecopages/file-system": "0.3.1",
|
|
115
115
|
"@ecopages/logger": "^0.2.3",
|
|
116
|
-
"@ecopages/mdx": "0.3.
|
|
116
|
+
"@ecopages/mdx": "0.3.1",
|
|
117
117
|
"@mdx-js/mdx": "^3.1.1",
|
|
118
118
|
"oxc-parser": "^0.141.0",
|
|
119
|
-
"
|
|
120
|
-
"rolldown": "^1.1.0",
|
|
121
|
-
"source-map": "^0.8.0",
|
|
122
|
-
"vfile": "^6.0.3"
|
|
119
|
+
"rolldown": "^1.1.0"
|
|
123
120
|
}
|
|
124
121
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { fileSystem } from '@ecopages/file-system';
|
|
2
2
|
function escapeRegExp(value) {
|
|
3
3
|
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
4
4
|
}
|
|
@@ -16,7 +16,7 @@ export function createReactDomRuntimeInteropPlugin(options) {
|
|
|
16
16
|
}));
|
|
17
17
|
}
|
|
18
18
|
build.onLoad({ filter: reactDomFileFilter }, (args) => {
|
|
19
|
-
const content =
|
|
19
|
+
const content = fileSystem.readFileSync(args.path);
|
|
20
20
|
if (!reactRequirePattern.test(content)) {
|
|
21
21
|
return undefined;
|
|
22
22
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { fileSystem } from '@ecopages/file-system';
|
|
2
2
|
import { dirname, resolve, sep } from 'node:path';
|
|
3
3
|
const READ_FILE_SYNC_PATTERN = /\bfs\.readFileSync\s*\(\s*path\.resolve\s*\(\s*(['"`])([^'"`\n]+)\1\s*\)\s*,\s*['"`]utf-?8['"`]\s*\)/g;
|
|
4
4
|
function inferProjectRootFromSourcePath(filePath) {
|
|
@@ -17,7 +17,7 @@ function resolveReadFileCandidate(relPath, sourcePath, absWorkingDir) {
|
|
|
17
17
|
resolve(sourceDir, relPath),
|
|
18
18
|
...(inferredProjectRoot ? [resolve(inferredProjectRoot, relPath)] : []),
|
|
19
19
|
];
|
|
20
|
-
return candidates.find((candidate) =>
|
|
20
|
+
return candidates.find((candidate) => fileSystem.exists(candidate));
|
|
21
21
|
}
|
|
22
22
|
/**
|
|
23
23
|
* Inlines `fs.readFileSync(path.resolve(...), 'utf8')` calls when the target file exists.
|
|
@@ -33,7 +33,7 @@ export function inlineReadFileSyncCalls(source, sourcePath, absWorkingDir) {
|
|
|
33
33
|
const absolutePath = resolveReadFileCandidate(relPath, sourcePath, absWorkingDir);
|
|
34
34
|
if (!absolutePath)
|
|
35
35
|
return '""';
|
|
36
|
-
return JSON.stringify(readFileSync(absolutePath
|
|
36
|
+
return JSON.stringify(fileSystem.readFileSync(absolutePath));
|
|
37
37
|
}
|
|
38
38
|
catch {
|
|
39
39
|
return '""';
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Build plugin securing the Ecopages isomorphic compilation pipeline.
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
6
|
+
import { fileSystem } from '@ecopages/file-system';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import { parseDeclaredModules, toModuleBaseSpecifier } from './specifier-classification.js';
|
|
9
9
|
import { classifyClientGraphModule } from './module-classification.js';
|
|
@@ -81,7 +81,7 @@ function loadClientGraphBoundaryModule(args, options, requestedExports, isEntryp
|
|
|
81
81
|
}
|
|
82
82
|
let source;
|
|
83
83
|
try {
|
|
84
|
-
source = readFileSync(args.path
|
|
84
|
+
source = fileSystem.readFileSync(args.path);
|
|
85
85
|
}
|
|
86
86
|
catch {
|
|
87
87
|
return undefined;
|
|
@@ -98,7 +98,7 @@ function loadClientGraphBoundaryModule(args, options, requestedExports, isEntryp
|
|
|
98
98
|
}
|
|
99
99
|
function resolveEntryImports(entrypointFiles, entrypoint) {
|
|
100
100
|
try {
|
|
101
|
-
const source = readFileSync(entrypoint
|
|
101
|
+
const source = fileSystem.readFileSync(entrypoint);
|
|
102
102
|
const wrapper = /^\s*(?:export\s+\*\s+from|import)\s+(['"])([^'"\n]+)\1\s*;?\s*$/.exec(source);
|
|
103
103
|
const specifier = wrapper?.[2];
|
|
104
104
|
if (!specifier)
|
|
@@ -55,22 +55,18 @@ export function registerIslandHmr(options, importModule, importPath) {
|
|
|
55
55
|
* Selects the component exported by a browser entry for the current Island Host.
|
|
56
56
|
*
|
|
57
57
|
* @remarks
|
|
58
|
-
* Component identity is preferred when a file exports several components
|
|
58
|
+
* Component identity is preferred when a file exports several components; each
|
|
59
|
+
* declaration has its own id, so the file alone cannot tell them apart. The
|
|
59
60
|
* default export and then the first function remain compatibility fallbacks for
|
|
60
61
|
* entries without framework identity metadata.
|
|
61
62
|
*/
|
|
62
|
-
function resolveComponent(module, componentRef
|
|
63
|
+
function resolveComponent(module, componentRef) {
|
|
63
64
|
const values = Object.values(module).filter((entry) => typeof entry === 'function');
|
|
64
65
|
if (componentRef) {
|
|
65
66
|
const matchById = values.find((entry) => entry.config?.identity?.id === componentRef);
|
|
66
67
|
if (matchById)
|
|
67
68
|
return matchById;
|
|
68
69
|
}
|
|
69
|
-
if (componentFile) {
|
|
70
|
-
const matchByFile = values.find((entry) => entry.config?.identity?.file === componentFile);
|
|
71
|
-
if (matchByFile)
|
|
72
|
-
return matchByFile;
|
|
73
|
-
}
|
|
74
70
|
if (typeof module.default === 'function')
|
|
75
71
|
return module.default;
|
|
76
72
|
return values[0] ?? null;
|
|
@@ -195,7 +191,7 @@ function hydrateTarget(target, component, runtime, runtimeState) {
|
|
|
195
191
|
* @param options - Component, selector, React runtime, and shared state for the entry.
|
|
196
192
|
*/
|
|
197
193
|
export function mountIslands(options) {
|
|
198
|
-
const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? ''
|
|
194
|
+
const resolvedComponent = resolveComponent(options.componentModule, options.componentRef ?? '');
|
|
199
195
|
ensureObserver(options.runtimeState);
|
|
200
196
|
const pageRuntime = (window.__ECO_PAGES__ ??= {});
|
|
201
197
|
pageRuntime.rerunScripts ??= {};
|
|
@@ -223,7 +219,7 @@ export function mountIslands(options) {
|
|
|
223
219
|
* @param newModule - Newly imported component module.
|
|
224
220
|
*/
|
|
225
221
|
export function updateIslands(options, newModule) {
|
|
226
|
-
const component = resolveComponent(newModule, options.componentRef ?? ''
|
|
222
|
+
const component = resolveComponent(newModule, options.componentRef ?? '');
|
|
227
223
|
if (!component)
|
|
228
224
|
return;
|
|
229
225
|
options.componentModule = newModule;
|
|
@@ -100,6 +100,7 @@ export declare class HydrationAssetService {
|
|
|
100
100
|
file: string;
|
|
101
101
|
config?: EcoComponentConfig;
|
|
102
102
|
}>): Promise<PageClientBuildEntry[]>;
|
|
103
|
+
/** Keeps one entry per component; a file that declares several island components keeps each of them. */
|
|
103
104
|
private uniqueIslands;
|
|
104
105
|
private buildHmrPageClientRenderAssets;
|
|
105
106
|
private buildGroupedPageClientRenderAssets;
|
|
@@ -158,7 +158,7 @@ export class HydrationAssetService {
|
|
|
158
158
|
/** Collects React island hydration entries for the production app browser build. */
|
|
159
159
|
async collectAppBrowserClientBuildEntries(islands) {
|
|
160
160
|
const uniqueIslands = this.uniqueIslands(islands);
|
|
161
|
-
const groupedEntrypointFiles = uniqueIslands.map(({ file }) => file);
|
|
161
|
+
const groupedEntrypointFiles = [...new Set(uniqueIslands.map(({ file }) => file))];
|
|
162
162
|
const groupedDeclaredModules = [
|
|
163
163
|
...new Set(uniqueIslands.flatMap(({ config }) => collectDeclaredModulesInConfig(config))),
|
|
164
164
|
];
|
|
@@ -185,14 +185,16 @@ export class HydrationAssetService {
|
|
|
185
185
|
}
|
|
186
186
|
return entries;
|
|
187
187
|
}
|
|
188
|
+
/** Keeps one entry per component; a file that declares several island components keeps each of them. */
|
|
188
189
|
uniqueIslands(islands) {
|
|
189
190
|
const uniqueIslands = [];
|
|
190
|
-
const
|
|
191
|
+
const seenKeys = new Set();
|
|
191
192
|
for (const island of islands) {
|
|
192
|
-
|
|
193
|
+
const key = getIslandComponentKey(island.file, island.config);
|
|
194
|
+
if (seenKeys.has(key)) {
|
|
193
195
|
continue;
|
|
194
196
|
}
|
|
195
|
-
|
|
197
|
+
seenKeys.add(key);
|
|
196
198
|
uniqueIslands.push(island);
|
|
197
199
|
}
|
|
198
200
|
return uniqueIslands;
|
|
@@ -203,7 +205,7 @@ export class HydrationAssetService {
|
|
|
203
205
|
for (const island of uniqueIslands) {
|
|
204
206
|
this.config.hmrPageMetadataCache?.markOwnedEntrypoint(island.file);
|
|
205
207
|
const assets = await this.buildHmrIslandRenderAssets(island.file, island.config);
|
|
206
|
-
assetsByFile.set(island.file, assets);
|
|
208
|
+
assetsByFile.set(island.file, [...(assetsByFile.get(island.file) ?? []), ...assets]);
|
|
207
209
|
processedAssets.push(...assets);
|
|
208
210
|
}
|
|
209
211
|
if (lazyEntries?.length) {
|
|
@@ -229,16 +231,23 @@ export class HydrationAssetService {
|
|
|
229
231
|
}
|
|
230
232
|
async createGroupedIslandEntries(uniqueIslands) {
|
|
231
233
|
const islandEntries = [];
|
|
232
|
-
const
|
|
234
|
+
const declaredModulesByFile = new Map();
|
|
235
|
+
for (const { file, config } of uniqueIslands) {
|
|
236
|
+
const declaredModules = declaredModulesByFile.get(file) ?? new Set();
|
|
237
|
+
for (const module of collectDeclaredModulesInConfig(config))
|
|
238
|
+
declaredModules.add(module);
|
|
239
|
+
declaredModulesByFile.set(file, declaredModules);
|
|
240
|
+
}
|
|
241
|
+
const groupedEntrypointFiles = [...declaredModulesByFile.keys()];
|
|
233
242
|
const groupedDeclaredModules = [
|
|
234
243
|
...new Set(uniqueIslands.flatMap(({ config }) => collectDeclaredModulesInConfig(config))),
|
|
235
244
|
];
|
|
236
|
-
for (const
|
|
237
|
-
const componentName = this.getIslandBundleName(
|
|
238
|
-
const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, false,
|
|
245
|
+
for (const [file, declaredModules] of declaredModulesByFile) {
|
|
246
|
+
const componentName = this.getIslandBundleName(file);
|
|
247
|
+
const bundleOptions = await this.config.bundleService.createBundleOptions(componentName, false, [...declaredModules], {}, file, groupedEntrypointFiles, groupedDeclaredModules);
|
|
239
248
|
islandEntries.push(createAppBrowserClientEntry({
|
|
240
249
|
entryName: componentName,
|
|
241
|
-
importPath:
|
|
250
|
+
importPath: file,
|
|
242
251
|
reexport: true,
|
|
243
252
|
packageRole: 'dynamic-chunk',
|
|
244
253
|
bundleOptions,
|
|
@@ -286,8 +295,9 @@ export class HydrationAssetService {
|
|
|
286
295
|
const componentName = this.getIslandBundleName(island.file);
|
|
287
296
|
const hydrationName = this.getIslandHydrationName(componentName, getIslandComponentKey(island.file, island.config));
|
|
288
297
|
const islandAsset = processedClientEntries.find((processed) => processed.groupedBundle?.entryName === componentName);
|
|
298
|
+
const fileAssets = assetsByFile.get(island.file);
|
|
289
299
|
assetsByFile.set(island.file, [
|
|
290
|
-
...(islandAsset ? [islandAsset] : []),
|
|
300
|
+
...(fileAssets ?? (islandAsset ? [islandAsset] : [])),
|
|
291
301
|
...(hydrationByName.get(hydrationName) ?? []),
|
|
292
302
|
]);
|
|
293
303
|
}
|
|
@@ -310,7 +320,6 @@ export class HydrationAssetService {
|
|
|
310
320
|
reactDomClientImportPath: runtimeImports.reactDomClient,
|
|
311
321
|
targetSelector: `[data-eco-component-key="${componentKey}"]`,
|
|
312
322
|
componentRef: config?.identity?.id,
|
|
313
|
-
componentFile,
|
|
314
323
|
minify: !hmrEnabled,
|
|
315
324
|
hmrEnabled,
|
|
316
325
|
});
|
|
@@ -41,7 +41,7 @@ function buildHmrOptions(options) {
|
|
|
41
41
|
if (!options.hmrEnabled)
|
|
42
42
|
return '';
|
|
43
43
|
const layoutStack = options.routerComponents
|
|
44
|
-
? 'getLayoutStack: (Page) => (Page.config?.layouts ?? []).map((layout) => layout?.config?.identity?.
|
|
44
|
+
? 'getLayoutStack: (Page) => (Page.config?.layouts ?? []).map((layout) => layout?.config?.identity?.id ?? "").join("|"),'
|
|
45
45
|
: '';
|
|
46
46
|
return `hmr: {
|
|
47
47
|
importPath: ${JSON.stringify(options.importPath)},
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import { fileSystem } from '@ecopages/file-system';
|
|
2
3
|
import { rolldown } from 'rolldown';
|
|
3
4
|
const ISLAND_BOOTSTRAP_ID = '\0ecopages-react-island-bootstrap';
|
|
4
5
|
const PAGE_BOOTSTRAP_ID = '\0ecopages-react-page-bootstrap';
|
|
@@ -29,7 +30,6 @@ const configuration = {
|
|
|
29
30
|
targetSelector: ${JSON.stringify(options.targetSelector)},
|
|
30
31
|
componentModule: ComponentModule,
|
|
31
32
|
componentRef: ${JSON.stringify(options.componentRef ?? '')},
|
|
32
|
-
componentFile: ${JSON.stringify(options.componentFile ?? '')},
|
|
33
33
|
scriptId: ${JSON.stringify(options.scriptId)},
|
|
34
34
|
runtime: { hydrateRoot, createElement, useEffect },
|
|
35
35
|
runtimeState: getIslandHydrationRuntime()
|
|
@@ -57,7 +57,7 @@ function createBootstrapPlugin() {
|
|
|
57
57
|
throw new Error(`Unknown hydration bootstrap module: ${id}`);
|
|
58
58
|
for (const relativePath of candidates) {
|
|
59
59
|
try {
|
|
60
|
-
return readFileSync(new URL(`./browser/${relativePath}`, import.meta.url)
|
|
60
|
+
return fileSystem.readFileSync(fileURLToPath(new URL(`./browser/${relativePath}`, import.meta.url)));
|
|
61
61
|
}
|
|
62
62
|
catch {
|
|
63
63
|
continue;
|
|
@@ -87,7 +87,7 @@ function createBootstrapPlugin() {
|
|
|
87
87
|
load(id) {
|
|
88
88
|
if (id === PAGE_DATA_MANIFEST_ID) {
|
|
89
89
|
return {
|
|
90
|
-
code: readFileSync(new URL('./page-data-manifest.js', import.meta.url)
|
|
90
|
+
code: fileSystem.readFileSync(fileURLToPath(new URL('./page-data-manifest.js', import.meta.url))),
|
|
91
91
|
moduleType: 'ts',
|
|
92
92
|
};
|
|
93
93
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { Suspense } from 'react';
|
|
3
|
-
import { createRoot } from 'react-dom/client';
|
|
4
|
-
import { afterEach, describe, expect, it } from 'vitest';
|
|
5
|
-
import { page } from 'vitest/browser';
|
|
6
|
-
import { dynamic } from './dynamic.js';
|
|
7
|
-
function createDeferredImport() {
|
|
8
|
-
let resolve;
|
|
9
|
-
const promise = new Promise((innerResolve) => {
|
|
10
|
-
resolve = innerResolve;
|
|
11
|
-
});
|
|
12
|
-
return {
|
|
13
|
-
promise,
|
|
14
|
-
resolve,
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
describe('dynamic', () => {
|
|
18
|
-
let container;
|
|
19
|
-
let root;
|
|
20
|
-
afterEach(() => {
|
|
21
|
-
root.unmount();
|
|
22
|
-
container.remove();
|
|
23
|
-
});
|
|
24
|
-
it('returns a browser lazy component that resolves through Suspense', async () => {
|
|
25
|
-
const deferredImport = createDeferredImport();
|
|
26
|
-
const DynamicComponent = dynamic(() => deferredImport.promise);
|
|
27
|
-
container = document.createElement('div');
|
|
28
|
-
document.body.appendChild(container);
|
|
29
|
-
root = createRoot(container);
|
|
30
|
-
root.render(_jsx(Suspense, { fallback: _jsx("span", { children: "Loading dynamic component" }), children: _jsx(DynamicComponent, {}) }));
|
|
31
|
-
await expect.element(page.getByText('Loading dynamic component')).toBeInTheDocument();
|
|
32
|
-
deferredImport.resolve({
|
|
33
|
-
default: () => _jsx("span", { children: "Dynamic content" }),
|
|
34
|
-
});
|
|
35
|
-
await expect.element(page.getByText('Dynamic content')).toBeInTheDocument();
|
|
36
|
-
await expect.element(page.getByText('Loading dynamic component')).not.toBeInTheDocument();
|
|
37
|
-
});
|
|
38
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,461 +0,0 @@
|
|
|
1
|
-
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
-
import { createElement, useEffect } from 'react';
|
|
3
|
-
import { hydrateRoot } from 'react-dom/client';
|
|
4
|
-
import { mountIslands, updateIslands } from './browser/island-hydration.js';
|
|
5
|
-
import { startPageHydration } from './browser/page-hydration.js';
|
|
6
|
-
/**
|
|
7
|
-
* Resolves after the browser has run every task queued before the call.
|
|
8
|
-
*
|
|
9
|
-
* @remarks
|
|
10
|
-
* For asserting that something did not happen. A message-channel round trip runs after all pending
|
|
11
|
-
* promise reactions without a timer, so it cannot be mistaken for waiting out a delay.
|
|
12
|
-
*/
|
|
13
|
-
function flushTasks() {
|
|
14
|
-
return new Promise((resolve) => {
|
|
15
|
-
const channel = new MessageChannel();
|
|
16
|
-
channel.port1.onmessage = () => resolve();
|
|
17
|
-
channel.port2.postMessage(null);
|
|
18
|
-
});
|
|
19
|
-
}
|
|
20
|
-
function createPageOptions(testWindow, router, pageRoot) {
|
|
21
|
-
const runtime = testWindow.__ECO_REACT_HYDRATION_TEST__;
|
|
22
|
-
const Page = () => null;
|
|
23
|
-
const reactRuntime = {
|
|
24
|
-
hydrateRoot: (target, tree, options) => {
|
|
25
|
-
runtime.hydrateCalls.push({
|
|
26
|
-
containerTag: target.tagName,
|
|
27
|
-
hasRecoverableErrorHandler: typeof options?.onRecoverableError === 'function',
|
|
28
|
-
tree,
|
|
29
|
-
});
|
|
30
|
-
return (pageRoot ?? {
|
|
31
|
-
render: (nextTree) => runtime.renderCalls.push(nextTree),
|
|
32
|
-
unmount: () => {
|
|
33
|
-
runtime.unmountCount += 1;
|
|
34
|
-
},
|
|
35
|
-
});
|
|
36
|
-
},
|
|
37
|
-
createElement: (...args) => ({ args }),
|
|
38
|
-
};
|
|
39
|
-
return {
|
|
40
|
-
scriptId: 'ecopages-react-page',
|
|
41
|
-
pageModuleUrl: '/assets/page.js',
|
|
42
|
-
Page,
|
|
43
|
-
pageDataReader: {
|
|
44
|
-
readPageDataDocument: () => ({ props: { title: 'Hello React', locals: { theme: 'dark' } } }),
|
|
45
|
-
getPageDataFromDocument: () => ({ title: 'Hello React' }),
|
|
46
|
-
},
|
|
47
|
-
runtime: reactRuntime,
|
|
48
|
-
createTree: (Component, props) => ({ Component, props }),
|
|
49
|
-
hasRouter: router,
|
|
50
|
-
isMdx: false,
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
describe('React page lifecycle', () => {
|
|
54
|
-
afterEach(() => {
|
|
55
|
-
document.body.innerHTML = '';
|
|
56
|
-
delete window.__ECO_PAGES__;
|
|
57
|
-
delete window.__ECO_REACT_HYDRATION_TEST__;
|
|
58
|
-
});
|
|
59
|
-
it('registers router ownership and cleanup', async () => {
|
|
60
|
-
const testWindow = window;
|
|
61
|
-
const testState = {
|
|
62
|
-
hydrateCalls: [],
|
|
63
|
-
renderCalls: [],
|
|
64
|
-
claimedOwners: [],
|
|
65
|
-
releasedOwners: [],
|
|
66
|
-
registrations: [],
|
|
67
|
-
unmountCount: 0,
|
|
68
|
-
};
|
|
69
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = testState;
|
|
70
|
-
testWindow.__ECO_PAGES__ = {
|
|
71
|
-
navigation: {
|
|
72
|
-
getOwnerState: () => ({ owner: 'html', canHandleSpaNavigation: false }),
|
|
73
|
-
register: (registration) => testState.registrations.push(registration),
|
|
74
|
-
claimOwnership: (owner) => testState.claimedOwners.push(owner),
|
|
75
|
-
releaseOwnership: (owner) => testState.releasedOwners.push(owner),
|
|
76
|
-
},
|
|
77
|
-
};
|
|
78
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
79
|
-
startPageHydration(createPageOptions(testWindow, true));
|
|
80
|
-
await vi.waitFor(() => expect(testState.hydrateCalls).toHaveLength(1), { interval: 1 });
|
|
81
|
-
expect(testState.hydrateCalls).toHaveLength(1);
|
|
82
|
-
expect(testState.hydrateCalls[0].containerTag).toBe('BODY');
|
|
83
|
-
expect(testState.hydrateCalls[0].hasRecoverableErrorHandler).toBe(true);
|
|
84
|
-
expect(testState.claimedOwners).toEqual(['react-router']);
|
|
85
|
-
expect(testState.registrations).toHaveLength(1);
|
|
86
|
-
expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe('function');
|
|
87
|
-
await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
|
|
88
|
-
expect(testState.unmountCount).toBe(1);
|
|
89
|
-
expect(testState.releasedOwners).toEqual(['react-router']);
|
|
90
|
-
expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
|
|
91
|
-
expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
|
|
92
|
-
});
|
|
93
|
-
it('reuses an existing router-owned page root on rerun', async () => {
|
|
94
|
-
const testWindow = window;
|
|
95
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = {
|
|
96
|
-
hydrateCalls: [],
|
|
97
|
-
renderCalls: [],
|
|
98
|
-
claimedOwners: [],
|
|
99
|
-
releasedOwners: [],
|
|
100
|
-
registrations: [],
|
|
101
|
-
unmountCount: 0,
|
|
102
|
-
};
|
|
103
|
-
const existingRoot = {
|
|
104
|
-
render: (tree) => testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree),
|
|
105
|
-
unmount: () => {
|
|
106
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
|
|
107
|
-
},
|
|
108
|
-
};
|
|
109
|
-
testWindow.__ECO_PAGES__ = {
|
|
110
|
-
navigation: {
|
|
111
|
-
getOwnerState: () => ({ owner: 'react-router', canHandleSpaNavigation: true }),
|
|
112
|
-
},
|
|
113
|
-
react: { pageRoot: existingRoot },
|
|
114
|
-
};
|
|
115
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
116
|
-
startPageHydration(createPageOptions(testWindow, true, existingRoot));
|
|
117
|
-
await flushTasks();
|
|
118
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
|
|
119
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
|
|
120
|
-
expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
|
|
121
|
-
});
|
|
122
|
-
it('coalesces concurrent startup and cancels a preload after cleanup', async () => {
|
|
123
|
-
const testWindow = window;
|
|
124
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = {
|
|
125
|
-
hydrateCalls: [],
|
|
126
|
-
renderCalls: [],
|
|
127
|
-
claimedOwners: [],
|
|
128
|
-
releasedOwners: [],
|
|
129
|
-
registrations: [],
|
|
130
|
-
unmountCount: 0,
|
|
131
|
-
};
|
|
132
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
133
|
-
let resolvePreload;
|
|
134
|
-
const preload = new Promise((resolve) => {
|
|
135
|
-
resolvePreload = resolve;
|
|
136
|
-
});
|
|
137
|
-
const options = createPageOptions(testWindow, false);
|
|
138
|
-
options.preload = () => preload;
|
|
139
|
-
options.hmr = { importPath: '/assets/page.js' };
|
|
140
|
-
startPageHydration(options);
|
|
141
|
-
expect(typeof testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js']).toBe('function');
|
|
142
|
-
const rerun = testWindow.__ECO_PAGES__?.rerunScripts?.['ecopages-react-page'];
|
|
143
|
-
rerun?.();
|
|
144
|
-
await Promise.resolve();
|
|
145
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
|
|
146
|
-
await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
|
|
147
|
-
resolvePreload();
|
|
148
|
-
await flushTasks();
|
|
149
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
|
|
150
|
-
});
|
|
151
|
-
it('ignores an HMR update that settles after navigation cleanup', async () => {
|
|
152
|
-
const testWindow = window;
|
|
153
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = {
|
|
154
|
-
hydrateCalls: [],
|
|
155
|
-
renderCalls: [],
|
|
156
|
-
claimedOwners: [],
|
|
157
|
-
releasedOwners: [],
|
|
158
|
-
registrations: [],
|
|
159
|
-
unmountCount: 0,
|
|
160
|
-
};
|
|
161
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
162
|
-
const options = createPageOptions(testWindow, false);
|
|
163
|
-
options.hmr = { importPath: '/assets/page.js' };
|
|
164
|
-
startPageHydration(options);
|
|
165
|
-
await vi.waitFor(() => expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1), {
|
|
166
|
-
interval: 1,
|
|
167
|
-
});
|
|
168
|
-
let resolveUpdate;
|
|
169
|
-
globalThis.__ECO_TEST_HMR_RELEASE__ = new Promise((resolve) => {
|
|
170
|
-
resolveUpdate = resolve;
|
|
171
|
-
});
|
|
172
|
-
const source = [
|
|
173
|
-
'export default function UpdatedPage() {}',
|
|
174
|
-
'export async function preload() {',
|
|
175
|
-
' globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__ = true',
|
|
176
|
-
' await globalThis.__ECO_TEST_HMR_RELEASE__',
|
|
177
|
-
'}',
|
|
178
|
-
].join('\n');
|
|
179
|
-
const hmrHandler = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
|
|
180
|
-
expect(hmrHandler).toBeDefined();
|
|
181
|
-
const update = hmrHandler?.(`data:text/javascript;charset=utf-8,${encodeURIComponent(source)}`);
|
|
182
|
-
await vi.waitFor(() => expect(globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__).toBe(true), {
|
|
183
|
-
interval: 1,
|
|
184
|
-
});
|
|
185
|
-
await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
|
|
186
|
-
const replacementRoot = {
|
|
187
|
-
render: (tree) => testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree),
|
|
188
|
-
unmount: () => undefined,
|
|
189
|
-
};
|
|
190
|
-
testWindow.__ECO_PAGES__.react.pageRoot = replacementRoot;
|
|
191
|
-
resolveUpdate();
|
|
192
|
-
await update;
|
|
193
|
-
await hmrHandler?.('data:text/javascript,export default function RemovedPage() {}');
|
|
194
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
|
|
195
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
|
|
196
|
-
delete globalThis.__ECO_TEST_HMR_RELEASE__;
|
|
197
|
-
delete globalThis.__ECO_TEST_HMR_PRELOAD_STARTED__;
|
|
198
|
-
});
|
|
199
|
-
it('restores HMR handler with updated generation on page reactivation after cleanup', async () => {
|
|
200
|
-
const testWindow = window;
|
|
201
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = {
|
|
202
|
-
hydrateCalls: [],
|
|
203
|
-
renderCalls: [],
|
|
204
|
-
claimedOwners: [],
|
|
205
|
-
releasedOwners: [],
|
|
206
|
-
registrations: [],
|
|
207
|
-
unmountCount: 0,
|
|
208
|
-
};
|
|
209
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
210
|
-
const options = createPageOptions(testWindow, false);
|
|
211
|
-
options.hmr = { importPath: '/assets/page.js' };
|
|
212
|
-
startPageHydration(options);
|
|
213
|
-
await vi.waitFor(() => expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1), {
|
|
214
|
-
interval: 1,
|
|
215
|
-
});
|
|
216
|
-
const initialHmr = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
|
|
217
|
-
expect(initialHmr).toBeDefined();
|
|
218
|
-
await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
|
|
219
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
|
|
220
|
-
await initialHmr?.('data:text/javascript,export default function IgnoredPage() {}');
|
|
221
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
|
|
222
|
-
await testWindow.__ECO_PAGES__.rerunScripts['ecopages-react-page']();
|
|
223
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(2);
|
|
224
|
-
const restoredHmr = testWindow.__ECO_PAGES__?.hmrHandlers?.['/assets/page.js'];
|
|
225
|
-
expect(restoredHmr).toBeDefined();
|
|
226
|
-
await restoredHmr?.('data:text/javascript,export default function UpdatedPage() {}');
|
|
227
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(1);
|
|
228
|
-
});
|
|
229
|
-
it('publishes a replacement only after its preload completes', async () => {
|
|
230
|
-
const testWindow = window;
|
|
231
|
-
testWindow.__ECO_REACT_HYDRATION_TEST__ = {
|
|
232
|
-
hydrateCalls: [],
|
|
233
|
-
renderCalls: [],
|
|
234
|
-
claimedOwners: [],
|
|
235
|
-
releasedOwners: [],
|
|
236
|
-
registrations: [],
|
|
237
|
-
unmountCount: 0,
|
|
238
|
-
};
|
|
239
|
-
document.body.innerHTML = '<script data-eco-script-id="ecopages-react-page"></script>';
|
|
240
|
-
let releaseInitial;
|
|
241
|
-
let releaseUpdate;
|
|
242
|
-
let signalUpdate;
|
|
243
|
-
const initialPreload = new Promise((resolve) => {
|
|
244
|
-
releaseInitial = resolve;
|
|
245
|
-
});
|
|
246
|
-
const updateStarted = new Promise((resolve) => {
|
|
247
|
-
signalUpdate = resolve;
|
|
248
|
-
});
|
|
249
|
-
const updatePreload = new Promise((resolve) => {
|
|
250
|
-
releaseUpdate = resolve;
|
|
251
|
-
});
|
|
252
|
-
const testGlobals = globalThis;
|
|
253
|
-
testGlobals.__ECO_TEST_PENDING_PRELOAD__ = () => {
|
|
254
|
-
signalUpdate();
|
|
255
|
-
return updatePreload;
|
|
256
|
-
};
|
|
257
|
-
const options = createPageOptions(testWindow, false);
|
|
258
|
-
const initialPage = options.Page;
|
|
259
|
-
options.preload = () => initialPreload;
|
|
260
|
-
options.hmr = { importPath: '/assets/page.js' };
|
|
261
|
-
try {
|
|
262
|
-
startPageHydration(options);
|
|
263
|
-
const handler = testWindow.__ECO_PAGES__.hmrHandlers['/assets/page.js'];
|
|
264
|
-
const source = 'export default function ReadyPage() {} export const preload = () => globalThis.__ECO_TEST_PENDING_PRELOAD__();';
|
|
265
|
-
const update = handler(`data:text/javascript,${encodeURIComponent(source)}`);
|
|
266
|
-
await updateStarted;
|
|
267
|
-
expect(options.Page).toBe(initialPage);
|
|
268
|
-
releaseInitial();
|
|
269
|
-
await testWindow.__ECO_PAGES__.rerunScripts['ecopages-react-page']();
|
|
270
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__.hydrateCalls[0]?.tree).toMatchObject({
|
|
271
|
-
Component: initialPage,
|
|
272
|
-
});
|
|
273
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__.renderCalls).toHaveLength(0);
|
|
274
|
-
releaseUpdate();
|
|
275
|
-
await update;
|
|
276
|
-
expect(options.Page).not.toBe(initialPage);
|
|
277
|
-
expect(testWindow.__ECO_REACT_HYDRATION_TEST__.renderCalls).toEqual([
|
|
278
|
-
{ Component: options.Page, props: { title: 'Hello React' } },
|
|
279
|
-
]);
|
|
280
|
-
}
|
|
281
|
-
finally {
|
|
282
|
-
releaseInitial();
|
|
283
|
-
releaseUpdate();
|
|
284
|
-
delete testGlobals.__ECO_TEST_PENDING_PRELOAD__;
|
|
285
|
-
}
|
|
286
|
-
});
|
|
287
|
-
});
|
|
288
|
-
describe('React Island Host lifecycle', () => {
|
|
289
|
-
afterEach(() => {
|
|
290
|
-
document.body.innerHTML = '';
|
|
291
|
-
});
|
|
292
|
-
it('hydrates in place, ignores repeated startup, and releases removed hosts', async () => {
|
|
293
|
-
const host = document.createElement('eco-island');
|
|
294
|
-
host.setAttribute('data-eco-island', '');
|
|
295
|
-
host.setAttribute('data-eco-island-integration', 'react');
|
|
296
|
-
host.setAttribute('data-eco-component-id', 'instance-1');
|
|
297
|
-
host.setAttribute('data-eco-component-key', 'component-1');
|
|
298
|
-
host.setAttribute('data-eco-props', btoa(JSON.stringify({ value: 'server' })));
|
|
299
|
-
const child = document.createElement('input');
|
|
300
|
-
child.value = 'typed before hydration';
|
|
301
|
-
host.appendChild(child);
|
|
302
|
-
document.body.appendChild(host);
|
|
303
|
-
const calls = { hydrate: 0, render: 0, unmount: 0, recoverableErrors: 0 };
|
|
304
|
-
const hydratedComponents = [];
|
|
305
|
-
const runtime = { islandRoots: {}, islandComponents: {} };
|
|
306
|
-
const reactRuntime = {
|
|
307
|
-
hydrateRoot: (target, tree, options) => {
|
|
308
|
-
calls.hydrate += 1;
|
|
309
|
-
if (options?.onRecoverableError)
|
|
310
|
-
calls.recoverableErrors += 1;
|
|
311
|
-
hydratedComponents.push(tree.props.Component);
|
|
312
|
-
const root = {
|
|
313
|
-
render: (nextTree) => {
|
|
314
|
-
calls.render += 1;
|
|
315
|
-
hydratedComponents.push(nextTree.props.Component);
|
|
316
|
-
},
|
|
317
|
-
unmount: () => {
|
|
318
|
-
calls.unmount += 1;
|
|
319
|
-
},
|
|
320
|
-
};
|
|
321
|
-
tree.type(tree.props);
|
|
322
|
-
void target;
|
|
323
|
-
return root;
|
|
324
|
-
},
|
|
325
|
-
createElement: (type, props) => ({ type, props }),
|
|
326
|
-
useEffect: (effect) => queueMicrotask(effect),
|
|
327
|
-
};
|
|
328
|
-
const Component = () => null;
|
|
329
|
-
const options = {
|
|
330
|
-
targetSelector: '[data-eco-component-key="component-1"]',
|
|
331
|
-
componentModule: { default: Component },
|
|
332
|
-
scriptId: 'island-script',
|
|
333
|
-
runtime: reactRuntime,
|
|
334
|
-
runtimeState: runtime,
|
|
335
|
-
};
|
|
336
|
-
mountIslands(options);
|
|
337
|
-
mountIslands(options);
|
|
338
|
-
await flushTasks();
|
|
339
|
-
expect(calls.hydrate).toBe(1);
|
|
340
|
-
expect(host.firstElementChild).toBe(child);
|
|
341
|
-
expect(host.getAttribute('data-eco-hydrated')).toBe('true');
|
|
342
|
-
expect(calls.recoverableErrors).toBe(1);
|
|
343
|
-
const NextComponent = () => null;
|
|
344
|
-
updateIslands(options, { default: NextComponent });
|
|
345
|
-
expect(calls.render).toBe(1);
|
|
346
|
-
expect(hydratedComponents[hydratedComponents.length - 1]).toBe(NextComponent);
|
|
347
|
-
const secondHost = host.cloneNode(false);
|
|
348
|
-
document.body.appendChild(secondHost);
|
|
349
|
-
mountIslands(options);
|
|
350
|
-
expect(calls.hydrate).toBe(2);
|
|
351
|
-
expect(hydratedComponents[hydratedComponents.length - 1]).toBe(NextComponent);
|
|
352
|
-
host.remove();
|
|
353
|
-
await vi.waitFor(() => expect(calls.unmount).toBe(1), { interval: 1 });
|
|
354
|
-
runtime.observer?.disconnect();
|
|
355
|
-
});
|
|
356
|
-
it('hydrates with props that contain non-Latin-1 text', () => {
|
|
357
|
-
const host = document.createElement('eco-island');
|
|
358
|
-
host.setAttribute('data-eco-island', '');
|
|
359
|
-
host.setAttribute('data-eco-component-key', 'component-unicode');
|
|
360
|
-
/** Props `{ label: '10 €', city: '東京', icon: '🙂' }` as core's `encodeIslandProps` writes them. */
|
|
361
|
-
host.setAttribute('data-eco-props', 'eyJsYWJlbCI6IjEwIOKCrCIsImNpdHkiOiLmnbHkuqwiLCJpY29uIjoi8J+ZgiJ9');
|
|
362
|
-
document.body.appendChild(host);
|
|
363
|
-
const Component = () => null;
|
|
364
|
-
const renderedProps = [];
|
|
365
|
-
const runtime = { islandRoots: {}, islandComponents: {} };
|
|
366
|
-
mountIslands({
|
|
367
|
-
targetSelector: '[data-eco-component-key="component-unicode"]',
|
|
368
|
-
componentModule: { default: Component },
|
|
369
|
-
scriptId: 'island-script-unicode',
|
|
370
|
-
runtimeState: runtime,
|
|
371
|
-
runtime: {
|
|
372
|
-
hydrateRoot: (_target, tree) => {
|
|
373
|
-
const element = tree;
|
|
374
|
-
element.type(element.props);
|
|
375
|
-
return { render: () => { }, unmount: () => { } };
|
|
376
|
-
},
|
|
377
|
-
createElement: (type, elementProps) => {
|
|
378
|
-
if (type === Component)
|
|
379
|
-
renderedProps.push(elementProps);
|
|
380
|
-
return { type, props: elementProps };
|
|
381
|
-
},
|
|
382
|
-
useEffect: () => { },
|
|
383
|
-
},
|
|
384
|
-
});
|
|
385
|
-
expect(renderedProps).toEqual([{ label: '10 €', city: '東京', icon: '🙂' }]);
|
|
386
|
-
runtime.observer?.disconnect();
|
|
387
|
-
});
|
|
388
|
-
it('preserves a focused uncontrolled input with the real React hydrator', async () => {
|
|
389
|
-
const host = document.createElement('eco-island');
|
|
390
|
-
host.setAttribute('data-eco-island', '');
|
|
391
|
-
host.setAttribute('data-eco-component-id', 'real-instance');
|
|
392
|
-
host.setAttribute('data-eco-component-key', 'real-component');
|
|
393
|
-
host.setAttribute('data-eco-props', btoa(JSON.stringify({ value: 'server value' })));
|
|
394
|
-
const input = document.createElement('input');
|
|
395
|
-
input.defaultValue = 'server value';
|
|
396
|
-
input.value = 'typed before hydration';
|
|
397
|
-
host.appendChild(input);
|
|
398
|
-
document.body.appendChild(host);
|
|
399
|
-
input.focus();
|
|
400
|
-
const Component = (props) => createElement('input', { defaultValue: String(props.value ?? '') });
|
|
401
|
-
const reactRuntime = {
|
|
402
|
-
hydrateRoot: (target, tree, options) => {
|
|
403
|
-
const root = hydrateRoot(target, tree, options);
|
|
404
|
-
return {
|
|
405
|
-
render: (nextTree) => root.render(nextTree),
|
|
406
|
-
unmount: () => root.unmount(),
|
|
407
|
-
};
|
|
408
|
-
},
|
|
409
|
-
createElement: (type, props) => createElement(type, props),
|
|
410
|
-
useEffect: (effect) => {
|
|
411
|
-
useEffect(effect);
|
|
412
|
-
},
|
|
413
|
-
};
|
|
414
|
-
const runtime = { islandRoots: {}, islandComponents: {} };
|
|
415
|
-
mountIslands({
|
|
416
|
-
targetSelector: '[data-eco-component-key="real-component"]',
|
|
417
|
-
componentModule: { default: Component },
|
|
418
|
-
scriptId: 'real-island-script',
|
|
419
|
-
runtime: reactRuntime,
|
|
420
|
-
runtimeState: runtime,
|
|
421
|
-
});
|
|
422
|
-
await vi.waitFor(() => expect(host.getAttribute('data-eco-hydrated')).toBe('true'), { interval: 1 });
|
|
423
|
-
expect(host.firstElementChild).toBe(input);
|
|
424
|
-
expect(input.value).toBe('typed before hydration');
|
|
425
|
-
expect(document.activeElement).toBe(input);
|
|
426
|
-
expect(host.getAttribute('data-eco-hydrated')).toBe('true');
|
|
427
|
-
runtime.observer?.disconnect();
|
|
428
|
-
});
|
|
429
|
-
it('resolves the component matching componentRef when a module exports multiple components from the same file', async () => {
|
|
430
|
-
const host = document.createElement('eco-island');
|
|
431
|
-
host.setAttribute('data-eco-island', '');
|
|
432
|
-
host.setAttribute('data-eco-component-id', 'multi-instance');
|
|
433
|
-
host.setAttribute('data-eco-component-key', 'multi-component');
|
|
434
|
-
document.body.appendChild(host);
|
|
435
|
-
const Helper = () => null;
|
|
436
|
-
Helper.config = { identity: { id: 'Helper', file: '/app/Counter.tsx' } };
|
|
437
|
-
const Target = () => null;
|
|
438
|
-
Target.config = { identity: { id: 'Target', file: '/app/Counter.tsx' } };
|
|
439
|
-
let hydratedComponent;
|
|
440
|
-
const reactRuntime = {
|
|
441
|
-
hydrateRoot: (_target, tree) => {
|
|
442
|
-
hydratedComponent = tree.props.Component;
|
|
443
|
-
return { render: () => { }, unmount: () => { } };
|
|
444
|
-
},
|
|
445
|
-
createElement: (type, props) => ({ type, props }),
|
|
446
|
-
useEffect: () => { },
|
|
447
|
-
};
|
|
448
|
-
const runtime = { islandRoots: {}, islandComponents: {} };
|
|
449
|
-
mountIslands({
|
|
450
|
-
targetSelector: '[data-eco-component-key="multi-component"]',
|
|
451
|
-
componentModule: { Helper, Target },
|
|
452
|
-
componentRef: 'Target',
|
|
453
|
-
componentFile: '/app/Counter.tsx',
|
|
454
|
-
scriptId: 'multi-island-script',
|
|
455
|
-
runtime: reactRuntime,
|
|
456
|
-
runtimeState: runtime,
|
|
457
|
-
});
|
|
458
|
-
expect(hydratedComponent).toBe(Target);
|
|
459
|
-
runtime.observer?.disconnect();
|
|
460
|
-
});
|
|
461
|
-
});
|