Compare commits
243
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11cd967c90 | ||
|
|
8ff0e01c45 | ||
|
|
c6809293c4 | ||
|
|
bf12520d01 | ||
|
|
03569c5120 | ||
|
|
a20e728824 | ||
|
|
8a503c4267 | ||
|
|
da860e2dae | ||
|
|
94bbfd3ec9 | ||
|
|
93f0a72f2a | ||
|
|
6604ff4674 | ||
|
|
4177e5015a | ||
|
|
615a20e25b | ||
|
|
52b453eecc | ||
|
|
274ae9fc33 | ||
|
|
2dcf8b7feb | ||
|
|
37935abad8 | ||
|
|
69568e5979 | ||
|
|
04c0b0a08a | ||
|
|
41d0721028 | ||
|
|
9781e02043 | ||
|
|
65d388ff89 | ||
|
|
201486f357 | ||
|
|
28119f0666 | ||
|
|
6e48cb82b7 | ||
|
|
ed50732d58 | ||
|
|
0c9faf0495 | ||
|
|
0fe7f07162 | ||
|
|
648d6a3a51 | ||
|
|
4c1c8db97e | ||
|
|
01a78c9b3d | ||
|
|
96670b94f8 | ||
|
|
322742aa81 | ||
|
|
96274a6aa8 | ||
|
|
c71a6b64a6 | ||
|
|
2b82424d7f | ||
|
|
99d5855f6a | ||
|
|
542f5efc78 | ||
|
|
cfeeef37ce | ||
|
|
bb4fb7548b | ||
|
|
9f9be5f41a | ||
|
|
465cf17bb0 | ||
|
|
4a34781ab6 | ||
|
|
2b8b0557b2 | ||
|
|
93b3cc35af | ||
|
|
a113f25a62 | ||
|
|
6c406ca99b | ||
|
|
7a58921ba3 | ||
|
|
3413c7816d | ||
|
|
9f48b8b134 | ||
|
|
ae092990ca | ||
|
|
57734fbe51 | ||
|
|
6decf8cdb0 | ||
|
|
f6b90d393f | ||
|
|
cfa8ab2e40 | ||
|
|
304850fcd3 | ||
|
|
a406daae1e | ||
|
|
8a481a87d8 | ||
|
|
784d85346e | ||
|
|
79159dcb28 | ||
|
|
f0b3dd1dba | ||
|
|
c4f45541a3 | ||
|
|
197b9c46ab | ||
|
|
0fde4dc22f | ||
|
|
7627be78dc | ||
|
|
75bd5921da | ||
|
|
c4b6802cab | ||
|
|
2e5492600e | ||
|
|
69fd34bd7c | ||
|
|
79cdd593d9 | ||
|
|
501f276746 | ||
|
|
ba5611c3e3 | ||
|
|
dcf9c92fee | ||
|
|
d83919b89a | ||
|
|
faaa8a87a0 | ||
|
|
c34690d08b | ||
|
|
150c84065b | ||
|
|
9c61f41079 | ||
|
|
2f5c311118 | ||
|
|
179aaebe49 | ||
|
|
54920dff08 | ||
|
|
e4ba07b47e | ||
|
|
de240eee75 | ||
|
|
453268a31c | ||
|
|
fb9ac0e6c4 | ||
|
|
39e954bd77 | ||
|
|
e09a87d2a6 | ||
|
|
1190a98265 | ||
|
|
c388be7fe7 | ||
|
|
faecc76384 | ||
|
|
ab7a10073b | ||
|
|
ae02eb7d0d | ||
|
|
d75f9d90ca | ||
|
|
7d77201e5a | ||
|
|
01d5ba5496 | ||
|
|
7a1ab36e63 | ||
|
|
64fc21866c | ||
|
|
d6bfc51ae3 | ||
|
|
dc415db2d3 | ||
|
|
dbf3dda3e4 | ||
|
|
7b3baa815c | ||
|
|
bb97e5b396 | ||
|
|
92da689e62 | ||
|
|
76f0ba9ca1 | ||
|
|
bdb4789903 | ||
|
|
9d425afa29 | ||
|
|
eb401cd979 | ||
|
|
472e5e4d81 | ||
|
|
84bc626ed0 | ||
|
|
92c88496a7 | ||
|
|
49ed687c3b | ||
|
|
c62a333257 | ||
|
|
e20c604413 | ||
|
|
579ea5370c | ||
|
|
faf129c509 | ||
|
|
a2d18b7f4b | ||
|
|
6d22aabdc0 | ||
|
|
ca500d36a9 | ||
|
|
996c9e92ec | ||
|
|
37ed85bf42 | ||
|
|
4b18d68389 | ||
|
|
c00985a3a1 | ||
|
|
6afb1c9b22 | ||
|
|
7fe47160e9 | ||
|
|
ff826a03c4 | ||
|
|
6d6994f009 | ||
|
|
d4400e49ad | ||
|
|
c35a73bb12 | ||
|
|
bbae73c132 | ||
|
|
7d25bf181c | ||
|
|
e347a4334d | ||
|
|
25de75c34f | ||
|
|
aae94b1da2 | ||
|
|
822d43cf61 | ||
|
|
4bae531339 | ||
|
|
d5bfb02911 | ||
|
|
9697dc95a3 | ||
|
|
2877bc06fa | ||
|
|
ebf75ebfe0 | ||
|
|
db54341006 | ||
|
|
8227d768e6 | ||
|
|
07eba1ba69 | ||
|
|
7fb5215571 | ||
|
|
cb887bc02f | ||
|
|
dcc7e27be4 | ||
|
|
dd8b99be06 | ||
|
|
e0c48fc9b6 | ||
|
|
97469dbabf | ||
|
|
74dcbb003b | ||
|
|
761d2255f8 | ||
|
|
a16a724048 | ||
|
|
48061d37ae | ||
|
|
edae0d6107 | ||
|
|
0ac420a23c | ||
|
|
05c39961ce | ||
|
|
1d34d1b3b1 | ||
|
|
4379ffac64 | ||
|
|
d39e1ecc31 | ||
|
|
0a59294fee | ||
|
|
4a81d0b89f | ||
|
|
1eaf8e39fb | ||
|
|
eb87a39619 | ||
|
|
f75958caea | ||
|
|
c0fd183c11 | ||
|
|
a9c8f4d65a | ||
|
|
0bd6b74ba5 | ||
|
|
a80667dfe6 | ||
|
|
52477bff45 | ||
|
|
1512cb7645 | ||
|
|
092c8f6747 | ||
|
|
5430f13877 | ||
|
|
68a3734eaf | ||
|
|
2b41cd46ba | ||
|
|
c472560fb5 | ||
|
|
220f560972 | ||
|
|
7d24ca52fa | ||
|
|
2cb04d2537 | ||
|
|
c0e0003460 | ||
|
|
6e819f1ef2 | ||
|
|
c2a90cd7a7 | ||
|
|
8860349c9b | ||
|
|
6dac754602 | ||
|
|
82f8fecb77 | ||
|
|
2e51371a67 | ||
|
|
2dd362e858 | ||
|
|
c68e459430 | ||
|
|
98e32a68b9 | ||
|
|
8edc426986 | ||
|
|
d8ff295093 | ||
|
|
7e8812a752 | ||
|
|
74df8a3b70 | ||
|
|
d756a723de | ||
|
|
817028df89 | ||
|
|
4fbe109bac | ||
|
|
fad34f3e71 | ||
|
|
22c59eb970 | ||
|
|
e94bec8d58 | ||
|
|
af460f23e6 | ||
|
|
dd7a50cf3d | ||
|
|
dff17b0917 | ||
|
|
99457c5a63 | ||
|
|
9869db8514 | ||
|
|
2a6055d863 | ||
|
|
ce3db23506 | ||
|
|
8216248107 | ||
|
|
705c602a67 | ||
|
|
136e3ce6ea | ||
|
|
1f5cac2cca | ||
|
|
536b6c6b8c | ||
|
|
bee052833c | ||
|
|
5db1879c63 | ||
|
|
ec071c4c39 | ||
|
|
5f99df23a7 | ||
|
|
4a11a9e344 | ||
|
|
e5119174e7 | ||
|
|
5006089a4a | ||
|
|
045643d570 | ||
|
|
488f208262 | ||
|
|
af43af7dc1 | ||
|
|
d70f4933af | ||
|
|
7b082c8d2e | ||
|
|
2180f9a776 | ||
|
|
ae871c9cdc | ||
|
|
42700f911f | ||
|
|
f8ac1fbe42 | ||
|
|
73aa35ac96 | ||
|
|
21c2776c88 | ||
|
|
97ccbee461 | ||
|
|
572e736f1f | ||
|
|
eb134a4743 | ||
|
|
34c932fc67 | ||
|
|
a6db5438b2 | ||
|
|
a20c9bae28 | ||
|
|
c863767283 | ||
|
|
86b82ed154 | ||
|
|
9418444916 | ||
|
|
8537cacd01 | ||
|
|
2c85e33b38 | ||
|
|
a406ff8548 | ||
|
|
66e669fa01 | ||
|
|
ac490215ce | ||
|
|
9ab01021be | ||
|
|
a684d51996 |
No files matched your search
@@ -0,0 +1 @@
|
||||
cloud-hosting-platform/site-builder
|
||||
@@ -462,6 +462,31 @@ Every component has a static `toHtml(props, childrenHtml)` method. The `html-exp
|
||||
- **Type checking:** `tsc --noEmit` (part of build step)
|
||||
- **HTML export:** Verify `toHtml()` output matches expected HTML structure
|
||||
- **Device preview:** Switch between desktop/tablet/mobile and verify responsive behavior
|
||||
- **Mobile guard (real browsers):** `npm run test:browser:mobile-guard` (Chromium + Firefox, headless; jsdom has no
|
||||
layout). Exports representative pages (navbar, columns, card grids, images, long words, wide customer HtmlBlocks)
|
||||
and asserts at 360/390/768/1280: no horizontal overflow (body.scrollWidth AND the right edge of every visible box
|
||||
and text line -- the head's `html,body{overflow-x:clip}` hides overflow from documentElement.scrollWidth) and no
|
||||
sideways page scroll, columns and card grids stack on phones and keep their columns on tablet, navbar links wrap,
|
||||
full-width tables still span the screen, sticky/dropdowns/multi-root flex+grid items inside HtmlBlocks still work, deliberately
|
||||
wide customer HTML stays clipped (not reflowed), and desktop is box- and pixel-identical with the hooks removed.
|
||||
Set `CHROMIUM_PATH` / `FIREFOX_PATH` if the Playwright-pinned browsers are not installed; record/compare a desktop
|
||||
baseline across commits with `MOBILE_GUARD_RECORD=<file>` (on the base commit) / `MOBILE_GUARD_BASELINE=<file>`.
|
||||
Run it whenever a component's `toHtml`, the exporter, or the head CSS changes.
|
||||
- **Legacy grids (real browsers):** `npm run test:browser:legacy-grid` (Chromium + Firefox) renders STORED pre-hook
|
||||
HTML (the OLS home page in `tests/fixtures/legacy-grid/`, plus every card-grid emitter with `data-wsb-grid`
|
||||
stripped, colliding Galleries and an unwrapped customer grid) in the real head at 360/390/768/1280: no overflow,
|
||||
legacy card grids stack on phones (and do NOT without the legacy rules), Galleries and customer grids keep their
|
||||
columns, the legacy page is pixel-identical on phones to its re-saved form, and 768/1280 are box- and
|
||||
pixel-identical with vs without the legacy rules.
|
||||
- **Mobile hooks:** the head's `<=767px` block (RESPONSIVE_CSS in `utils/html-export.ts`, mirrored byte-for-byte by
|
||||
WHP `generateCompiledHTML`) targets `[data-wsb-grid]` (component card grids -> one column), `body` (long words
|
||||
wrap) and descendants of `[data-wsb-html]` (the inline `display:contents` wrapper the exporter puts around
|
||||
HtmlBlock output: media shrink, `<pre>` scrolls on its own; tables are left alone). Never give that wrapper a box
|
||||
or overflow: it clipped dropdowns, broke sticky and merged flex/grid items. A new component with an inline multi-column grid
|
||||
should carry `data-wsb-grid`. Pages stored before the hook are covered by whole-attribute `[style=...]` /
|
||||
`[style^=...][style$=...]` signatures of the exact inline styles FeaturesGrid / Testimonials / NumberCounter stored
|
||||
(Gallery excluded via `:not(:has(...))`), so republishing stacks them with no re-save. Those signatures are frozen: they
|
||||
describe already-stored HTML, so keep them even if an emitter's inline style changes (new output carries the hook).
|
||||
- **WHP integration:** Deploy to staging, verify save/load, verify PHP wrapper injection
|
||||
|
||||
## Development Notes
|
||||
|
||||
+3
-1
@@ -7,7 +7,9 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
|
||||
<!-- Font Awesome Free 7.3.1 + the v4 shims (editor chrome still uses FA4 names like fa fa-trash-o) -->
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.3.1/css/all.min.css" rel="stylesheet" integrity="sha384-qrALq7+6jBOZIQsNnT6xGkMDru64qD6uTlDra39xrt2SoXl4pO3FX6Roz/RpR/BS" crossorigin="anonymous" referrerpolicy="no-referrer">
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.3.1/css/v4-shims.min.css" rel="stylesheet" integrity="sha384-BOBgwI2GEcZ4l/UA/+WOVnLChe2S4c7UhUCtdmX1m0v7Wdyk0S/tDoJOBci2ywvl" crossorigin="anonymous" referrerpolicy="no-referrer">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Generated
+7
@@ -20,6 +20,7 @@
|
||||
"@craftjs/core": "^0.2.10",
|
||||
"@craftjs/layers": "^0.2.7",
|
||||
"dompurify": "^3.4.5",
|
||||
"html-to-image": "1.11.13",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
@@ -2349,6 +2350,12 @@
|
||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/html-to-image": {
|
||||
"version": "1.11.13",
|
||||
"resolved": "https://registry.npmjs.org/html-to-image/-/html-to-image-1.11.13.tgz",
|
||||
"integrity": "sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/immer": {
|
||||
"version": "9.0.21",
|
||||
"resolved": "https://registry.npmjs.org/immer/-/immer-9.0.21.tgz",
|
||||
|
||||
@@ -11,6 +11,20 @@
|
||||
"test:headed": "playwright test tests/site-builder.spec.ts --reporter=list --headed",
|
||||
"test:e2e:sitesmith": "playwright test tests/sitesmith.spec.ts --reporter=list",
|
||||
"test:unit": "vitest run",
|
||||
"test:browser:bg": "node scripts/e2e-background.mjs",
|
||||
"test:browser:canvas": "node scripts/e2e-canvas-parity.mjs",
|
||||
"test:browser:mobile": "node scripts/e2e-mobile-parity.mjs",
|
||||
"test:browser:mobile-guard": "node scripts/e2e-mobile-guard.mjs",
|
||||
"test:browser:legacy-grid": "node scripts/e2e-legacy-grid.mjs",
|
||||
"test:browser:colorpick": "node scripts/e2e-color-pick.mjs",
|
||||
"test:browser:colors": "node scripts/e2e-color-system.mjs",
|
||||
"test:browser:capture-fidelity": "node scripts/e2e-capture-fidelity.mjs",
|
||||
"test:browser:capture-security": "node scripts/e2e-capture-security.mjs",
|
||||
"test:browser:sitesmith": "node scripts/e2e-sitesmith.mjs",
|
||||
"test:browser:sitesmith-editor-assets": "node scripts/e2e-sitesmith-editor-assets.mjs",
|
||||
"test:browser:sitesmith-cleaned": "node scripts/e2e-sitesmith-cleaned.mjs",
|
||||
"test:browser:sitesmith-delete": "node scripts/e2e-sitesmith-delete.mjs",
|
||||
"test:browser:preview-assets": "node scripts/e2e-preview-assets.mjs",
|
||||
"test:unit:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -26,6 +40,7 @@
|
||||
"@craftjs/core": "^0.2.10",
|
||||
"@craftjs/layers": "^0.2.7",
|
||||
"dompurify": "^3.4.5",
|
||||
"html-to-image": "1.11.13",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// Bundled by scripts/e2e-background.mjs and mounted in real Chromium.
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { Editor, Frame } from '@craftjs/core';
|
||||
import { HeroSimple } from '../src/components/sections/HeroSimple';
|
||||
import { BackgroundSection } from '../src/components/layout/BackgroundSection';
|
||||
import { CTASection } from '../src/components/sections/CTASection';
|
||||
import { CallToAction } from '../src/components/sections/CallToAction';
|
||||
import { Container } from '../src/components/layout/Container';
|
||||
|
||||
const resolver = { HeroSimple, BackgroundSection, CTASection, CallToAction, Container };
|
||||
|
||||
(window as any).mountNode = (id: string, type: string, props: Record<string, unknown>) => {
|
||||
const data = JSON.stringify({
|
||||
ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: {}, displayName: 'Container', custom: {}, hidden: false, nodes: ['n'], linkedNodes: {} },
|
||||
n: { type: { resolvedName: type }, isCanvas: false, props, displayName: type, custom: {}, parent: 'ROOT', hidden: false, nodes: [], linkedNodes: {} },
|
||||
});
|
||||
const el = document.createElement('div');
|
||||
el.id = id;
|
||||
document.body.appendChild(el);
|
||||
createRoot(el).render(
|
||||
<Editor resolver={resolver} enabled={false}><Frame data={data} /></Editor>,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser regression test: a `background` shorthand followed by an
|
||||
* undefined/'' background longhand wipes the gradient in Chromium (React
|
||||
* assigns '' for undefined style values). jsdom cannot reproduce this, so
|
||||
* mount the real components via react-dom in headless Chromium and assert the
|
||||
* COMPUTED style. Run: npm run test:browser:bg (needs a Playwright chromium)
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await build({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-background-entry.tsx')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser',
|
||||
define: { 'process.env.NODE_ENV': '"production"' }, jsx: 'automatic', logLevel: 'error',
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
|
||||
const cases = [
|
||||
['hero gradient', 'HeroSimple', { bgType: 'gradient', bgGradientFrom: '#0f172a', bgGradientTo: '#334155' }, 'backgroundImage', /linear-gradient/],
|
||||
['hero color', 'HeroSimple', { bgType: 'color', bgColor: '#123456' }, 'backgroundColor', /rgb\(18, 52, 86\)/],
|
||||
['hero image', 'HeroSimple', { bgType: 'image', bgImage: 'https://example.invalid/a.jpg' }, 'backgroundImage', /url\(.*a\.jpg/],
|
||||
['hero video (fallback color)', 'HeroSimple', { bgType: 'video', bgVideo: 'v.mp4', bgColor: '#123456' }, 'backgroundColor', /rgb\(18, 52, 86\)/],
|
||||
['BackgroundSection image', 'BackgroundSection', { bgImage: 'https://example.invalid/b.jpg', bgColor: '#123456' }, 'backgroundImage', /url\(.*b\.jpg/],
|
||||
['BackgroundSection color', 'BackgroundSection', { bgColor: '#123456' }, 'backgroundColor', /rgb\(18, 52, 86\)/],
|
||||
['CTASection gradient', 'CTASection', { gradient: 'linear-gradient(135deg, #111111, #222222)' }, 'backgroundImage', /linear-gradient/],
|
||||
['CallToAction gradient', 'CallToAction', { bgType: 'gradient', bgValue: 'linear-gradient(135deg, #111111, #222222)' }, 'backgroundImage', /linear-gradient/],
|
||||
];
|
||||
|
||||
// Override binaries with CHROMIUM_PATH / FIREFOX_PATH when the Playwright-pinned builds are not installed.
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const page = await browser.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
await page.setContent('<!doctype html><html><body></body></html>');
|
||||
await page.addScriptTag({ content: js });
|
||||
|
||||
let failed = 0;
|
||||
for (const [i, [label, type, props, prop, re]] of cases.entries()) {
|
||||
const id = `c${i}`;
|
||||
await page.evaluate(([id, type, props]) => window.mountNode(id, type, props), [id, type, props]);
|
||||
await page.waitForSelector(`#${id} section`, { timeout: 5000 }).catch(() => {});
|
||||
const value = await page.evaluate(([id, prop]) => {
|
||||
const s = document.querySelector(`#${id} section`);
|
||||
return s ? getComputedStyle(s)[prop] : '<<no section>>';
|
||||
}, [id, prop]);
|
||||
const ok = re.test(value);
|
||||
if (!ok) failed++;
|
||||
console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}: computed ${prop} = ${value}`);
|
||||
}
|
||||
if (errors.length) console.log('page errors:', errors.join('\n'));
|
||||
await browser.close();
|
||||
return failed;
|
||||
|
||||
}
|
||||
let total = 0;
|
||||
total += await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
total += await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
process.exit(total ? 1 : 0);
|
||||
@@ -0,0 +1,15 @@
|
||||
// Bundled (esbuild) by scripts/e2e-canvas-parity.mjs and run in Node: renders what a publish
|
||||
// of the CURRENT stored state would emit, composed like TopBar's Preview
|
||||
// (header + body + footer under the real document head). Used for specs whose
|
||||
// checked-in published HTML is stale relative to the stored state.
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
|
||||
export function renderPublished(project: any, pageIdx: number): string {
|
||||
const page = project.pages_craft_state[pageIdx];
|
||||
const hdr = project.header_craft_state ? exportBodyHtml(project.header_craft_state, 'header').html : '';
|
||||
const ftr = project.footer_craft_state ? exportBodyHtml(project.footer_craft_state, 'footer').html : '';
|
||||
const body = exportBodyHtml(page.craftState).html;
|
||||
return exportComposedPreviewHtml(page.craftState, hdr + body + ftr, {
|
||||
title: page.name, includeFonts: true, headCode: project.design?.headCode, design: project.design,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser regression test: the editor CANVAS must lay page content out
|
||||
* exactly like the PUBLISHED page ("the site looks different in the builder
|
||||
* than published"). jsdom has no layout, so this mounts the REAL editor (a
|
||||
* vite build served by a tiny mock API) in headless Firefox AND Chromium,
|
||||
* loads a stored project, and compares -- element by element -- against the
|
||||
* same page's published HTML rendered in a plain page whose viewport equals
|
||||
* the canvas content width.
|
||||
*
|
||||
* Stored state is loaded VERBATIM (blank style values included). Allowed editor-only
|
||||
* differences (empty-container drop zone, empty-image placeholder) are neutralised in the
|
||||
* canvas before measuring; see the ALLOWED block in run().
|
||||
*
|
||||
* Compared per matched element: bounding box (x/y/w/h, within 1px) and the
|
||||
* computed font-size / line-height / margin / padding / colour / font-family
|
||||
* / font-weight / display. Editor-only chrome (the dashed header/footer zone
|
||||
* separators) is compensated for, not ignored.
|
||||
*
|
||||
* npm run test:browser:canvas
|
||||
*
|
||||
* Env:
|
||||
* CHROMIUM_PATH / FIREFOX_PATH override the Playwright-pinned binaries
|
||||
* WHP_CANVAS_SPECS extra comma-separated spec.json paths
|
||||
* (e.g. real customer sites kept out of git)
|
||||
* CANVAS_SHOTS=<dir> write canvas + published PNGs there
|
||||
* CANVAS_CHROME_DUMP=<file> write a computed-style snapshot of the
|
||||
* editor chrome (everything OUTSIDE the
|
||||
* canvas frame) to diff before/after a change
|
||||
* CANVAS_ONLY=chromium|firefox run a single browser
|
||||
*
|
||||
* A spec is {name, project: <project.json>, published: {<slug>: <full html>}}
|
||||
* with paths relative to the spec file. Only pages that have a published
|
||||
* file are compared.
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const VIEW_H = 1000;
|
||||
const EDITOR_W = 1500;
|
||||
const TOL = 1; // px
|
||||
|
||||
// ---------------------------------------------------------------- specs
|
||||
const specPaths = [
|
||||
path.join(root, 'tests/fixtures/canvas-parity/ols.spec.json'),
|
||||
...(process.env.WHP_CANVAS_SPECS || '').split(',').map((s) => s.trim()).filter(Boolean),
|
||||
];
|
||||
// `published` is either {slug: html file} or "generate" = render what a publish of the stored
|
||||
// state emits (scripts/e2e-canvas-export-entry.ts) -- for sites whose saved HTML is stale.
|
||||
let renderPublished = null;
|
||||
async function loadExporter() {
|
||||
if (renderPublished) return renderPublished;
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-canvas-export-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const f = path.join(os.tmpdir(), `wsb-export-${process.pid}.mjs`);
|
||||
fs.writeFileSync(f, out.outputFiles[0].text);
|
||||
renderPublished = (await import(f)).renderPublished;
|
||||
fs.rmSync(f, { force: true });
|
||||
return renderPublished;
|
||||
}
|
||||
const specs = [];
|
||||
for (const p of specPaths) {
|
||||
const dir = path.dirname(p);
|
||||
const s = JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
const project = JSON.parse(fs.readFileSync(path.resolve(dir, s.project), 'utf8'));
|
||||
let published;
|
||||
if (s.published === 'generate') {
|
||||
const render = await loadExporter();
|
||||
const only = s.pages || project.pages_craft_state.map((pg) => pg.slug);
|
||||
published = {};
|
||||
project.pages_craft_state.forEach((pg, i) => { if (only.includes(pg.slug)) published[pg.slug] = render(project, i); });
|
||||
} else {
|
||||
published = Object.fromEntries(Object.entries(s.published).map(([k, v]) => [k, fs.readFileSync(path.resolve(dir, v), 'utf8')]));
|
||||
}
|
||||
specs.push({ name: s.name, project, published });
|
||||
}
|
||||
|
||||
// NOTE: stored state is loaded VERBATIM, blank style values included (e.g.
|
||||
// {padding:'20px', paddingTop:''} left by the style panel). The harness must test what
|
||||
// the editor really renders; an earlier version stripped blanks and thereby hid a wipe bug.
|
||||
|
||||
// ---------------------------------------------------------------- build + serve the real editor
|
||||
const buildDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wsb-canvas-'));
|
||||
execFileSync(path.join(root, 'node_modules/.bin/vite'), ['build', '--outDir', buildDir, '--emptyOutDir', '--logLevel', 'error'], { cwd: root, stdio: 'inherit' });
|
||||
|
||||
let currentProject = null;
|
||||
const mime = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png', '.svg': 'image/svg+xml' };
|
||||
const server = http.createServer((req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (u.pathname === '/api/site-builder.php') {
|
||||
res.setHeader('content-type', 'application/json');
|
||||
if (u.searchParams.get('action') === 'load') {
|
||||
return res.end(JSON.stringify({ success: true, rev: 'r1', limits: {}, project: currentProject }));
|
||||
}
|
||||
return res.end(JSON.stringify({ success: true }));
|
||||
}
|
||||
const p = u.pathname === '/' ? '/index.html' : u.pathname;
|
||||
if (p === '/index.html') {
|
||||
const cfg = { user: 't', apiUrl: '/api/site-builder.php', csrfToken: 'x', siteId: 1, siteDomain: 'example.test', siteName: 'Parity', backUrl: '/', isRoot: false };
|
||||
const h = fs.readFileSync(path.join(buildDir, 'index.html'), 'utf8')
|
||||
.replace('</head>', () => `<script>window.WHP_CONFIG=${JSON.stringify(cfg)};</script></head>`);
|
||||
res.setHeader('content-type', 'text/html');
|
||||
return res.end(h);
|
||||
}
|
||||
const f = path.join(buildDir, p);
|
||||
if (f.startsWith(buildDir) && fs.existsSync(f) && fs.statSync(f).isFile()) {
|
||||
res.setHeader('content-type', mime[path.extname(f)] || 'application/octet-stream');
|
||||
return res.end(fs.readFileSync(f));
|
||||
}
|
||||
res.statusCode = 404;
|
||||
res.end('nf');
|
||||
});
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
// ---------------------------------------------------------------- in-page measurer (runs in BOTH documents)
|
||||
function measure({ rootSel, isCanvas, skipNav }) {
|
||||
const rootEl = document.querySelector(rootSel);
|
||||
const rr = rootEl.getBoundingClientRect();
|
||||
const bl = isCanvas ? parseFloat(getComputedStyle(rootEl).borderLeftWidth) || 0 : 0;
|
||||
const bt = isCanvas ? parseFloat(getComputedStyle(rootEl).borderTopWidth) || 0 : 0;
|
||||
const ox = rr.left + bl;
|
||||
const oy = rr.top + bt;
|
||||
// Editor-only dashed zone separators shift everything after them by their width.
|
||||
const zones = isCanvas ? [...rootEl.querySelectorAll('[data-zone-preview]')] : [];
|
||||
const adjustY = (el) => {
|
||||
let adj = 0;
|
||||
for (const z of zones) {
|
||||
const cs = getComputedStyle(z);
|
||||
const zone = z.getAttribute('data-zone-preview');
|
||||
const bw = parseFloat(zone === 'header' ? cs.borderBottomWidth : cs.borderTopWidth) || 0;
|
||||
if (zone === 'header' && !z.contains(el) && (z.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)) adj += bw;
|
||||
if (zone === 'footer' && (z === el || z.contains(el))) adj += bw;
|
||||
}
|
||||
return adj;
|
||||
};
|
||||
const SKIP = new Set(['STYLE', 'SCRIPT', 'NOSCRIPT', 'LINK', 'META', 'BR', 'HEAD', 'TITLE', 'PATH', 'CIRCLE', 'RECT', 'LINE', 'POLYLINE', 'POLYGON', 'G', 'USE', 'DEFS']);
|
||||
const norm = (s) => s.replace(/\s+/g, '');
|
||||
// Visible text only (never <style>/<script> bodies), whitespace-insensitive:
|
||||
// React renders no inter-element whitespace, the stored HTML does.
|
||||
const textOf = (el) => {
|
||||
let t = '';
|
||||
const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
|
||||
for (let n = w.nextNode(); n; n = w.nextNode()) {
|
||||
const pt = n.parentElement && n.parentElement.tagName;
|
||||
if (pt !== 'STYLE' && pt !== 'SCRIPT') t += n.nodeValue;
|
||||
}
|
||||
return norm(t);
|
||||
};
|
||||
const normStyle = (s) => norm((s || '').replace(/\s*([:;])\s*/g, '$1').replace(/;$/, ''));
|
||||
// Order-insensitive identity of an element's inline style (React and the exporter
|
||||
// serialise the same declarations in different orders); editor-only props dropped.
|
||||
const EDITOR_PROPS = /^(cursor|outline|user-select|pointer-events|position)/;
|
||||
const styleKey = (el) => Array.from(el.style).filter((p) => !EDITOR_PROPS.test(p)).sort()
|
||||
.map((p) => `${p}:${el.style.getPropertyValue(p)}`).join(';').replace(/\s+/g, '').slice(0, 120);
|
||||
const counts = new Map();
|
||||
const out = {};
|
||||
const walk = (el) => {
|
||||
for (const c of el.children) {
|
||||
if (SKIP.has(c.tagName.toUpperCase())) continue;
|
||||
const tag = c.tagName.toLowerCase();
|
||||
// Navbar link ORDER follows page order, which the harness rotates to open page N: skip links.
|
||||
if (skipNav && tag === 'a' && c.closest('nav')) continue;
|
||||
// Editor-only wrapper boxes (Craft frame div, RenderNode `position:relative` host, header/footer zone-preview host) have no
|
||||
// counterpart in the published DOM: descend through them without measuring.
|
||||
const bare = tag === 'div' && (c.attributes.length === 0
|
||||
|| normStyle(c.getAttribute('style')) === 'max-width:1200px;margin:0auto'
|
||||
|| (isCanvas && c.attributes.length === 1 && c.hasAttribute('style') && normStyle(c.getAttribute('style')) === 'position:relative'));
|
||||
if (c.hasAttribute('data-zone-preview') || bare) { walk(c); continue; }
|
||||
const text = textOf(c).slice(0, 40);
|
||||
const ident = tag === 'img' ? `${c.getAttribute('alt') || ''}`
|
||||
: text || styleKey(c);
|
||||
const k0 = `${tag}|${ident}`;
|
||||
const n = (counts.get(k0) || 0) + 1;
|
||||
counts.set(k0, n);
|
||||
const key = `${k0}#${n}`;
|
||||
const r = c.getBoundingClientRect();
|
||||
const cs = getComputedStyle(c);
|
||||
out[key] = {
|
||||
tag,
|
||||
x: r.left - ox, y: r.top - oy - adjustY(c), w: r.width, h: r.height,
|
||||
fontSize: cs.fontSize, lineHeight: cs.lineHeight, fontFamily: cs.fontFamily, fontWeight: cs.fontWeight,
|
||||
color: cs.color, display: cs.display, textAlign: cs.textAlign,
|
||||
margin: `${cs.marginTop} ${cs.marginRight} ${cs.marginBottom} ${cs.marginLeft}`,
|
||||
padding: `${cs.paddingTop} ${cs.paddingRight} ${cs.paddingBottom} ${cs.paddingLeft}`,
|
||||
};
|
||||
walk(c);
|
||||
}
|
||||
};
|
||||
walk(rootEl);
|
||||
return out;
|
||||
}
|
||||
|
||||
const PROPS = ['fontSize', 'lineHeight', 'fontFamily', 'fontWeight', 'color', 'display', 'textAlign', 'margin', 'padding'];
|
||||
|
||||
function chromeSnapshot() {
|
||||
const frame = document.querySelector('.canvas-device-frame');
|
||||
const rows = {};
|
||||
let i = 0;
|
||||
for (const el of document.body.querySelectorAll('*')) {
|
||||
if (frame && (frame === el || frame.contains(el))) continue;
|
||||
if (el.closest('[data-zone-preview]')) continue;
|
||||
const cs = getComputedStyle(el);
|
||||
const k = `${i++}:${el.tagName.toLowerCase()}.${String(el.className && el.className.baseVal !== undefined ? el.className.baseVal : el.className).slice(0, 40)}`;
|
||||
rows[k] = [cs.margin, cs.padding, cs.fontSize, cs.lineHeight, cs.color, cs.display, cs.fontFamily].join('|');
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- driver
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
let failed = 0;
|
||||
const offline = (route) => route.abort();
|
||||
const shotDir = process.env.CANVAS_SHOTS;
|
||||
if (shotDir) fs.mkdirSync(shotDir, { recursive: true });
|
||||
|
||||
for (const spec of specs) {
|
||||
const pages = spec.project.pages_craft_state || [];
|
||||
for (const [idx, pg] of pages.entries()) {
|
||||
const pubHtml = spec.published[pg.slug];
|
||||
if (!pubHtml) continue;
|
||||
const label = `${spec.name}/${pg.slug}`;
|
||||
// The editor opens pages_craft_state[0]; rotate so page `idx` is first.
|
||||
currentProject = { ...spec.project, pages_craft_state: [pg, ...pages.filter((_, j) => j !== idx)] };
|
||||
|
||||
const ctx = await browser.newContext({ viewport: { width: EDITOR_W, height: VIEW_H } });
|
||||
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, offline); // no web fonts / icon CDN: identical fallbacks both sides
|
||||
const ed = await ctx.newPage();
|
||||
const errors = [];
|
||||
ed.on('pageerror', (e) => errors.push(String(e)));
|
||||
await ed.goto(base + '/');
|
||||
await ed.waitForSelector('.canvas-device-frame [data-craft-container]', { timeout: 20000 });
|
||||
await ed.waitForTimeout(1500); // header/footer zone previews + layout settle
|
||||
const canvasW = await ed.evaluate(() => document.querySelector('.canvas-device-frame').clientWidth);
|
||||
// ALLOWED editor-only differences (deliberate UX with no published counterpart), neutralised
|
||||
// before measuring so they don't mask real diffs:
|
||||
// - the 40px drop zone on EMPTY containers (Container sets data-wsb-dropzone only then)
|
||||
// - the placeholder <img> shown for an image node with no src (toHtml emits nothing)
|
||||
await ed.evaluate(() => {
|
||||
const f = document.querySelector('.canvas-device-frame');
|
||||
f.querySelectorAll('[data-wsb-dropzone]').forEach((el) => el.style.setProperty('min-height', '0', 'important'));
|
||||
f.querySelectorAll('img[src^="data:image/svg"]').forEach((el) => el.style.setProperty('display', 'none', 'important'));
|
||||
});
|
||||
const canvas = await ed.evaluate(measure, { rootSel: '.canvas-device-frame', isCanvas: true, skipNav: idx > 0 });
|
||||
if (shotDir) await ed.screenshot({ path: path.join(shotDir, `${label.replace('/', '_')}.${name}.canvas.png`) });
|
||||
if (process.env.CANVAS_CHROME_DUMP && idx === 0 && spec === specs[0]) {
|
||||
fs.writeFileSync(`${process.env.CANVAS_CHROME_DUMP}.${name}.json`, JSON.stringify(await ed.evaluate(chromeSnapshot), null, 1));
|
||||
}
|
||||
const chromeBody = await ed.evaluate(() => getComputedStyle(document.body).fontSize);
|
||||
|
||||
// Published: viewport so that the layout width (excluding any scrollbar) equals the canvas content width.
|
||||
let w = canvasW;
|
||||
const pub = await ctx.newPage();
|
||||
let published;
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
await pub.setViewportSize({ width: w, height: VIEW_H });
|
||||
await pub.setContent(pubHtml, { waitUntil: 'domcontentloaded' });
|
||||
await pub.waitForTimeout(300);
|
||||
const cw = await pub.evaluate(() => document.documentElement.clientWidth);
|
||||
if (cw === canvasW) break;
|
||||
w += canvasW - cw;
|
||||
}
|
||||
published = await pub.evaluate(measure, { rootSel: 'body', isCanvas: false, skipNav: idx > 0 });
|
||||
if (shotDir) await pub.screenshot({ path: path.join(shotDir, `${label.replace('/', '_')}.${name}.published.png`) });
|
||||
|
||||
const pk = Object.keys(published);
|
||||
const matched = pk.filter((k) => k in canvas);
|
||||
const diffs = [];
|
||||
for (const k of matched) {
|
||||
const a = canvas[k], b = published[k];
|
||||
for (const f of ['x', 'y', 'w', 'h']) if (Math.abs(a[f] - b[f]) > TOL) diffs.push([k, f, a[f].toFixed(1), b[f].toFixed(1)]);
|
||||
for (const f of PROPS) if (a[f] !== b[f]) diffs.push([k, f, a[f], b[f]]);
|
||||
}
|
||||
const ratio = matched.length / pk.length;
|
||||
const bad = new Set(diffs.map((d) => d[0]));
|
||||
const ok = diffs.length === 0 && ratio >= 0.6 && errors.length === 0 && chromeBody === '13px';
|
||||
if (!ok) failed++;
|
||||
console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}: ${matched.length}/${pk.length} published elements matched, ${bad.size} elements differ (${diffs.length} property diffs), canvas width ${canvasW}, editor body font ${chromeBody}`);
|
||||
if (diffs.length) {
|
||||
// Summarise: property -> count + first examples
|
||||
const byProp = {};
|
||||
for (const [k, f, a, b] of diffs) (byProp[f] ||= []).push(`${k.split('#')[0].slice(0, 44)} canvas=${a} published=${b}`);
|
||||
for (const [f, rows] of Object.entries(byProp)) console.log(` ${f}: ${rows.length}x e.g. ${rows.slice(0, 3).join(' ;; ')}`);
|
||||
}
|
||||
if (errors.length) console.log(' page errors:', errors.join('\n'));
|
||||
if (process.env.CANVAS_JSON) {
|
||||
fs.writeFileSync(`${process.env.CANVAS_JSON}.${name}.${label.replace('/', '_')}.json`, JSON.stringify({ canvas, published, diffs }, null, 1));
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
return failed;
|
||||
}
|
||||
|
||||
let total = 0;
|
||||
try {
|
||||
if (process.env.CANVAS_ONLY !== 'firefox') total += await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (process.env.CANVAS_ONLY !== 'chromium') total += await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
} finally {
|
||||
server.close();
|
||||
fs.rmSync(buildDir, { recursive: true, force: true });
|
||||
}
|
||||
console.log(total ? `FAILED: ${total} page comparison(s) differ` : 'OK: canvas content matches published');
|
||||
process.exit(total ? 1 : 0);
|
||||
@@ -0,0 +1,25 @@
|
||||
// Bundled by scripts/e2e-capture-fidelity.mjs and run in real Firefox + Chromium.
|
||||
import { captureHtml } from '../src/utils/self-review-capture';
|
||||
import { sanitizeCaptureHtml } from '../src/utils/sanitize-capture-html';
|
||||
import { cleanAiProps } from '../src/sitesmith/clean-ai-response';
|
||||
|
||||
/** Round 6: the background URL the editor really stores for an AI hero placeholder (apply-time cleaner). */
|
||||
(window as any).cleanedBgImage = (url: string) => cleanAiProps({ bgImage: url }, 'BackgroundSection').bgImage;
|
||||
|
||||
(window as any).sanitizeCaptureHtml = sanitizeCaptureHtml;
|
||||
/** Capture through the real path, then decode the JPEG and return RGB samples at the given points. */
|
||||
(window as any).captureAndSample = async (html: string, points: Array<[number, number]>) => {
|
||||
const t0 = performance.now();
|
||||
const r = await captureHtml(html, { settleMs: 200, injectFontAwesome: false });
|
||||
const ms = Math.round(performance.now() - t0);
|
||||
if (!r.ok) return { ok: false, reason: r.reason };
|
||||
const url = URL.createObjectURL(r.blob);
|
||||
const img = new Image();
|
||||
await new Promise<void>((res, rej) => { img.onload = () => res(); img.onerror = () => rej(new Error('decode')); img.src = url; });
|
||||
const c = document.createElement('canvas');
|
||||
c.width = img.naturalWidth; c.height = img.naturalHeight;
|
||||
const ctx = c.getContext('2d')!;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
URL.revokeObjectURL(url);
|
||||
return { ok: true, w: c.width, h: c.height, strips: r.strips, cropped: r.cropped, pageHeight: r.pageHeight, bytes: r.blob.size, ms, samples: points.map(([x, y]) => Array.from(ctx.getImageData(x, y, 1, 1).data.slice(0, 3))) };
|
||||
};
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser proof (Chromium + Firefox) that the self-review capture keeps what the page shows:
|
||||
* backgrounds and borders written as CSS SHORTHAND containing var() (e.g. `background: var(--wsb-secondary)`,
|
||||
* `border: 1px solid var(--wsb-border)`). The CSSOM exposes such a declaration only as pending-substitution
|
||||
* longhands whose values read back as "", so a sanitiser that re-serialises longhands drops them and the
|
||||
* hero came out white in the screenshot the model reviewed (eval 2026-11-01). Goes through the WHOLE capture
|
||||
* path (sanitiser -> inlining -> sandboxed frame -> html-to-image), decodes the JPEG and samples pixels.
|
||||
* Run: node scripts/e2e-capture-fidelity.mjs (CHROMIUM_PATH / FIREFOX_PATH override the binaries)
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import http from 'node:http';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await build({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-capture-fidelity-entry.ts')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
|
||||
// Token CSS the way the exporter emits it (:root custom properties), bands written the four ways that occur.
|
||||
const PAGE = `<!doctype html><html><head><style>
|
||||
:root{--wsb-primary:#1f3a5f;--wsb-secondary:#101a2b;--wsb-border:#d4372c;--wsb-accent:#d9a24a;--pad:40px}
|
||||
body{margin:0;background:#ffffff}
|
||||
.sheet-bg{background:var(--wsb-secondary);height:100px}
|
||||
.sheet-border{border:12px solid var(--wsb-border);height:76px;background-color:#ffffff}
|
||||
.sheet-card{border:6px solid var(--wsb-border);border-top:14px solid var(--wsb-accent);height:60px;background-color:#ffffff}
|
||||
</style></head><body>
|
||||
<div style="background: var(--wsb-secondary); height:100px"></div>
|
||||
<div style="background-color: var(--wsb-primary); height:100px"></div>
|
||||
<div style="border:12px solid var(--wsb-border); height:76px; background-color:#ffffff"></div>
|
||||
<div class="sheet-bg"></div>
|
||||
<div class="sheet-border"></div>
|
||||
<div style="background: linear-gradient(var(--wsb-accent), var(--wsb-accent)); height:100px"></div>
|
||||
<div style="padding: var(--pad) 0 0 0; background-color:#ffffff"><div style="height:60px;background-color:#00aa00"></div></div>
|
||||
<div style="padding:0;background-color:#ffffff;border:6px solid var(--wsb-border);border-top:14px solid var(--wsb-accent);border-radius:0;height:60px"></div>
|
||||
<div style="background-color:#ffffff;border:6px solid var(--wsb-border);border-top:14px solid #00aa00;height:60px"></div>
|
||||
<div class="sheet-card"></div>
|
||||
<img alt="Team working" src="https://placehold.co/800x1000/1f3a5f/fbfaf7?text=Team+working" style="display:block;width:400px;aspect-ratio:4/3;object-fit:cover">
|
||||
<div style="background:url(https://placehold.co/1200x400/222222/eeeeee?text=Hero) center/cover #ff0000;height:100px"></div>
|
||||
<img alt="Nope" src="https://placehold.co/200x100/orange/white?text=Nope" style="display:block">
|
||||
</body></html>`;
|
||||
// [label, x, y, expected rgb]
|
||||
const POINTS = [
|
||||
['inline `background: var(--wsb-secondary)` band', 640, 50, [0x10, 0x1a, 0x2b]],
|
||||
['inline `background-color: var(--wsb-primary)` band (control)', 640, 150, [0x1f, 0x3a, 0x5f]],
|
||||
['inline `border: 12px solid var(--wsb-border)` left edge', 5, 240, [0xd4, 0x37, 0x2c]],
|
||||
['inline `border` box interior stays white', 640, 250, [0xff, 0xff, 0xff]],
|
||||
['stylesheet `.sheet-bg{background: var(--wsb-secondary)}`', 640, 350, [0x10, 0x1a, 0x2b]],
|
||||
['stylesheet `.sheet-border{border: ... var(--wsb-border)}` top edge', 640, 405, [0xd4, 0x37, 0x2c]],
|
||||
['inline `background: linear-gradient(var(--wsb-accent), ...)`', 640, 550, [0xd9, 0xa2, 0x4a]],
|
||||
['inline `padding: var(--pad) 0 0 0` keeps the 40px gap (white above the green box)', 640, 620, [0xff, 0xff, 0xff]],
|
||||
['... and the green box starts below the padding', 640, 670, [0x00, 0xaa, 0x00]],
|
||||
// A card written `border: ... var(); border-top: <override>` (the AI's "accent top" card, eval 2026-11-01):
|
||||
// the CSSOM cannot serialise the overridden var() shorthand, so the left/right/bottom sides were lost.
|
||||
...[['inline `border:var()` + `border-top:var()` card', 700, [0xd9, 0xa2, 0x4a]],
|
||||
['inline `border:var()` + literal `border-top:#00aa00` card', 780, [0x00, 0xaa, 0x00]],
|
||||
['stylesheet `.sheet-card{border:var(); border-top:var()}`', 860, [0xd9, 0xa2, 0x4a]]].flatMap(([label, y0, top]) => [
|
||||
[`${label}: top border`, 640, y0 + 7, top],
|
||||
[`${label}: left border`, 2, y0 + 50, [0xd4, 0x37, 0x2c]],
|
||||
[`${label}: right border`, 1277, y0 + 50, [0xd4, 0x37, 0x2c]],
|
||||
[`${label}: bottom border`, 640, y0 + 77, [0xd4, 0x37, 0x2c]],
|
||||
[`${label}: interior stays white`, 640, y0 + 45, [0xff, 0xff, 0xff]],
|
||||
]),
|
||||
// placehold.co images are drawn LOCALLY (no request) in the element's own box (eval 2026-11-01: blank / alt text).
|
||||
['placehold.co <img> (width 400, aspect-ratio 4/3, object-fit cover): bg colour', 10, 950, [0x1f, 0x3a, 0x5f]],
|
||||
['... box ends at 400px wide (white beyond)', 405, 950, [0xff, 0xff, 0xff]],
|
||||
['... and at 300px tall (bottom-right corner still bg)', 395, 1236, [0x1f, 0x3a, 0x5f]],
|
||||
['placehold.co CSS background (center/cover, red fallback colour): bg colour, not the fallback', 5, 1245, [0x22, 0x22, 0x22]],
|
||||
['off-spec placehold.co (named colours): plain neutral #cccccc box of the URL size', 100, 1390, [0xcc, 0xcc, 0xcc]],
|
||||
['... that is 200px wide (white beyond)', 205, 1390, [0xff, 0xff, 0xff]],
|
||||
];
|
||||
// Rows scanned for the label text colour (any pixel close to it).
|
||||
const SCANS = [
|
||||
['placehold.co <img> shows its ?text= label in the fg colour', 1090, 20, 380, [0xfb, 0xfa, 0xf7]],
|
||||
['placehold.co CSS background shows its label in the fg colour', 1290, 300, 980, [0xee, 0xee, 0xee]],
|
||||
];
|
||||
|
||||
// Tall pages -> side-by-side strips (the geometry the server-side review prompt describes): bands of 2500 px
|
||||
// (or 4000 px) each with a 100 px black bar on top, so each strip's colour AND its top edge can be checked.
|
||||
const band = (h, colors) => `<!doctype html><html><head><style>body{margin:0}</style></head><body>${colors.map((c) => `<div style="height:${h}px;background:${c}"><div style="height:100px;background:#000"></div></div>`).join('')}</body></html>`;
|
||||
const TALL = [
|
||||
{ label: '7500 px page', html: band(2500, ['#c03030', '#30c030', '#3030c0']), strips: 3, w: 3888, h: 2500, cropped: false,
|
||||
pts: [[640, 1250, [0xc0, 0x30, 0x30]], [1292, 1250, [0x80, 0x80, 0x80]], [1944, 1250, [0x30, 0xc0, 0x30]], [2596, 1250, [0x80, 0x80, 0x80]], [3248, 1250, [0x30, 0x30, 0xc0]],
|
||||
[640, 50, [0, 0, 0]], [1944, 50, [0, 0, 0]], [3248, 50, [0, 0, 0]], [1944, 2490, [0x30, 0xc0, 0x30]]] },
|
||||
{ label: '5000 px page', html: band(2500, ['#c03030', '#30c030']), strips: 2, w: 2584, h: 2500, cropped: false,
|
||||
pts: [[640, 1250, [0xc0, 0x30, 0x30]], [1292, 1250, [0x80, 0x80, 0x80]], [1944, 1250, [0x30, 0xc0, 0x30]], [1944, 50, [0, 0, 0]]] },
|
||||
// 12000 px: top 9000 only, 3 x 3000; strip 2 starts at page y 3000 (inside band 1: red), strip 3 at 6000 (green), bars at 0/4000/8000.
|
||||
{ label: '12000 px page (cropped)', html: band(4000, ['#c03030', '#30c030', '#3030c0']), strips: 3, w: 3888, h: 3000, cropped: true,
|
||||
pts: [[640, 50, [0, 0, 0]], [1944, 50, [0xc0, 0x30, 0x30]], [1944, 1050, [0, 0, 0]], [3248, 50, [0x30, 0xc0, 0x30]], [3248, 2050, [0, 0, 0]], [3248, 2990, [0x30, 0x30, 0xc0]]] },
|
||||
{ label: '1500 px page (no strips)', html: band(1500, ['#c03030']), strips: 1, w: 1280, h: 1500, cropped: false, pts: [[640, 750, [0xc0, 0x30, 0x30]]] },
|
||||
];
|
||||
|
||||
const srv = http.createServer((q, r) => { r.setHeader('content-type', 'text/html'); r.end('<!doctype html><title>host</title><body>host</body>'); }).listen(0);
|
||||
const port = srv.address().port;
|
||||
let failed = 0;
|
||||
const check = (name, label, ok, extra = '') => { if (!ok) failed++; console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}${extra ? ' ' + extra : ''}`); };
|
||||
const near = (a, b, tol = 24) => a.every((v, i) => Math.abs(v - b[i]) <= tol);
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const page = await browser.newPage();
|
||||
await page.goto(`http://localhost:${port}/`);
|
||||
await page.addScriptTag({ content: js });
|
||||
const clean = await page.evaluate((h) => window.sanitizeCaptureHtml(h), PAGE);
|
||||
check(name, 'sanitiser keeps `background: var(--wsb-secondary)` as written', clean.ok && /background:\s*var\(--wsb-secondary\)/.test(clean.html));
|
||||
check(name, 'sanitiser keeps `border: 12px solid var(--wsb-border)` as written', clean.ok && /border:\s*12px solid var\(--wsb-border\)/.test(clean.html));
|
||||
// The recovered shorthand goes through the same URL gate: a var() fallback url() to a non-allowed target is dropped.
|
||||
const hostile = await page.evaluate((h) => window.sanitizeCaptureHtml(h), '<div style="background: var(--missing, url(/beacon?x)) center; border: 1px solid var(--b)">x</div><style>.a{background:var(--q, url(https://evil.example/a.png)) no-repeat}</style>');
|
||||
check(name, 'recovered var() shorthand with a disallowed url() fallback is dropped (inline + sheet)', hostile.ok && !/beacon|evil\.example/.test(hostile.html) && /border:\s*1px solid var\(--b\)/.test(hostile.html), hostile.ok ? hostile.html.slice(0, 300) : hostile.reason);
|
||||
check(name, 'sanitiser keeps an overridden `border: ... var()` before its `border-top` override (inline + sheet)', clean.ok
|
||||
&& /border:\s*6px solid var\(--wsb-border\);\s*border-top:\s*14px solid var\(--wsb-accent\)/.test(clean.html)
|
||||
&& /border:\s*6px solid var\(--wsb-border\);\s*border-top(-width)?:\s*14px/.test(clean.html)
|
||||
&& /\.sheet-card\s*\{[^}]*border:\s*6px solid var\(--wsb-border\);\s*border-top:/.test(clean.html));
|
||||
// Recovered-from-source shorthands pass the same URL gate.
|
||||
const hostile2 = await page.evaluate((h) => window.sanitizeCaptureHtml(h), '<div style="background: var(--m, url(/beacon2?x)) center; background-color: red; border: 1px solid var(--b); border-top: 2px solid red">x</div><style>.b{background:var(--q, url(https://evil.example/b.png)) no-repeat;background-position:0 0}</style>');
|
||||
check(name, 'overridden var() shorthand with a disallowed url() fallback is still dropped (inline + sheet)', hostile2.ok && !/beacon2|evil\.example/.test(hostile2.html) && /border:\s*1px solid var\(--b\)/.test(hostile2.html), hostile2.ok ? '' : hostile2.reason);
|
||||
const scanPts = SCANS.flatMap(([, y, x0, x1]) => Array.from({ length: Math.floor((x1 - x0) / 2) }, (_, k) => [x0 + 2 * k, y]));
|
||||
const placeholdReq = [];
|
||||
page.on('request', (q) => { if (/placehold\.co/.test(q.url())) placeholdReq.push(q.url()); });
|
||||
const res = await page.evaluate(([h, pts]) => window.captureAndSample(h, pts), [PAGE, [...POINTS.map((p) => [p[1], p[2]]), ...scanPts]]);
|
||||
check(name, 'capture succeeded', res.ok === true, res.ok ? '' : res.reason);
|
||||
check(name, 'no request to placehold.co', placeholdReq.length === 0, JSON.stringify(placeholdReq));
|
||||
if (res.ok) {
|
||||
POINTS.forEach(([label, , , want], i) => check(name, label, near(res.samples[i], want), `got rgb(${res.samples[i].join(',')}) want rgb(${want.join(',')})`));
|
||||
let at = POINTS.length;
|
||||
for (const [label, , x0, x1, want] of SCANS) {
|
||||
const n = Math.floor((x1 - x0) / 2);
|
||||
const row = res.samples.slice(at, at + n); at += n;
|
||||
const hits = row.filter((px) => near(px, want, 12)).length;
|
||||
check(name, label, hits >= 3, `(${hits} pixels near rgb(${want.join(',')}))`);
|
||||
}
|
||||
}
|
||||
// Round 6 (live case 4, Firefox): a background placeholder showed a faint "1920 x 1080" ghost label behind the
|
||||
// hero in the review render (the same-colour label still antialiased). The URL the editor stores for the live
|
||||
// case's hero, through the real capture path: every pixel of the box must be the box colour (max channel
|
||||
// deviation <= 2 for JPEG), over a dense grid that covers where the label was drawn.
|
||||
{
|
||||
const LIVE = 'https://placehold.co/1920x1080/101a2b/fbfaf7?text=Team+collaborating+in+a+modern+office';
|
||||
const bgUrl = await page.evaluate((u) => window.cleanedBgImage(u), LIVE);
|
||||
check(name, 'label-free background placeholder URL (zero-width label)', /^https:\/\/placehold\.co\/1920x1080\/101a2b\/101a2b\?text=%E2%80%8B$/.test(bgUrl), bgUrl);
|
||||
// the live case-4 hero as exported (BackgroundSection: quoted url(), cover, a same-colour overlay at 0.55)
|
||||
const hero = `<!doctype html><html><head><style>body{margin:0;background:#fff}</style></head><body><section style="position:relative;width:100%;min-height:200px;background-color:#ff0000;background-image:url('${bgUrl}');background-size:cover;background-position:center;padding-top:160px;padding-bottom:160px;padding-left:24px;padding-right:24px;text-align:left"><div style="position:absolute;inset:0;background-color:#101a2b;opacity:0.55"></div><div style="position:relative;height:400px"></div></section></body></html>`;
|
||||
const grid = [];
|
||||
for (let y = 16; y <= 704; y += 4) for (let x = 16; x <= 1264; x += 4) grid.push([x, y]);
|
||||
const r = await page.evaluate(([h, pts]) => window.captureAndSample(h, pts), [hero, grid]);
|
||||
check(name, 'label-free background placeholder captured', r.ok === true, r.ok ? '' : r.reason);
|
||||
if (r.ok) {
|
||||
let worst = 0; let at = null;
|
||||
r.samples.forEach((px, i) => { const d = Math.max(...px.map((v, k) => Math.abs(v - [0x10, 0x1a, 0x2b][k]))); if (d > worst) { worst = d; at = grid[i]; } });
|
||||
check(name, `label-free background placeholder: all ${grid.length} pixels are the box colour (no ghost label)`, worst <= 2, `(max deviation ${worst} at ${JSON.stringify(at)})`);
|
||||
}
|
||||
}
|
||||
for (const t of TALL) {
|
||||
const r = await page.evaluate(([h, pts]) => window.captureAndSample(h, pts), [t.html, t.pts.map((p) => [p[0], p[1]])]);
|
||||
check(name, `${t.label}: captured`, r.ok === true, r.ok ? `(${r.bytes} bytes, ${r.ms} ms)` : r.reason);
|
||||
if (!r.ok) continue;
|
||||
check(name, `${t.label}: ${t.strips} strip(s), ${t.w}x${t.h}, cropped=${t.cropped}`, r.strips === t.strips && r.w === t.w && r.h === t.h && r.cropped === t.cropped,
|
||||
`got ${r.strips} strip(s) ${r.w}x${r.h} cropped=${r.cropped} pageHeight=${r.pageHeight}`);
|
||||
t.pts.forEach(([x, y, want], i) => check(name, `${t.label}: pixel (${x},${y})`, near(r.samples[i], want), `got rgb(${r.samples[i].join(',')}) want rgb(${want.join(',')})`));
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
srv.close();
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,16 @@
|
||||
// Bundled by scripts/e2e-capture-security.mjs and run in real Firefox + Chromium.
|
||||
import { captureHtml } from '../src/utils/self-review-capture';
|
||||
import { CAPTURE_CSP } from '../src/utils/sanitize-capture-html';
|
||||
|
||||
(window as any).captureHtml = captureHtml;
|
||||
/** Defence-in-depth probe: the capture frame WITHOUT the sanitiser (sandbox + CSP only). */
|
||||
(window as any).rawFrame = (html: string) => new Promise<void>((resolve) => {
|
||||
const f = document.createElement('iframe');
|
||||
f.setAttribute('sandbox', 'allow-same-origin');
|
||||
const CSP = CAPTURE_CSP;
|
||||
f.setAttribute('csp', CSP);
|
||||
f.style.cssText = 'position:fixed;left:-9999px;width:800px;height:600px';
|
||||
f.addEventListener('load', () => setTimeout(resolve, 800), { once: true });
|
||||
f.srcdoc = html.replace('<head>', `<head><meta http-equiv="Content-Security-Policy" content="${CSP}">`);
|
||||
document.body.appendChild(f);
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser proof (Firefox + Chromium) that the self-review capture cannot run or leak hostile page
|
||||
* markup. A malicious fixture goes through the WHOLE capture path; sentinels: window.__pwned in the
|
||||
* parent, any request to /beacon or evil.example, parent cookie/localStorage reachability, frame
|
||||
* navigation. A second probe feeds the SAME hostile page to the frame WITHOUT the sanitiser to show the
|
||||
* sandbox + CSP alone also hold. Benign pages must still capture.
|
||||
* Run: node scripts/e2e-capture-security.mjs (CHROMIUM_PATH / FIREFOX_PATH override the binaries)
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import http from 'node:http';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await build({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-capture-security-entry.ts')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
|
||||
const PWN = "(function(){try{parent.__pwned=1;top.__pwned=1}catch(e){}try{fetch('/beacon?js')}catch(e){}try{top.postMessage('pwned','*')}catch(e){}try{new Image().src='/beacon?img-js'}catch(e){}})()";
|
||||
const EVIL = `<!doctype html><html><head>
|
||||
<meta http-equiv="refresh" content="0;url=/beacon?refresh"><base href="https://evil.example/">
|
||||
<link rel="import" href="/beacon?import"><link rel="stylesheet" href="/beacon?css"><link rel="preload" href="/beacon?preload" as="script">
|
||||
<style>@import url(/beacon?atimport); body{background:url(https://evil.example/bg.png);} .pad{padding:8px}</style>
|
||||
<script>${PWN}</script></head>
|
||||
<body onload="${PWN}" style="font:16px sans-serif">
|
||||
<h1 class="pad" style="color:#123">Hostile but readable</h1>
|
||||
<img src="x" onerror="${PWN}"><img src="/beacon?img">
|
||||
<svg width="10" height="10" onload="${PWN}"><script>${PWN}</script><a xlink:href="javascript:${PWN}"><rect width="5" height="5"/></a></svg>
|
||||
<a href="javascript:${PWN}">js link</a><form action="javascript:${PWN}"><button formaction="javascript:${PWN}">b</button></form>
|
||||
<iframe srcdoc="<script>${PWN}</script>"></iframe><iframe src="/beacon?iframe"></iframe>
|
||||
<object data="/beacon?object"></object><embed src="/beacon?embed">
|
||||
<div style="background:url(/beacon?cssurl)">x</div><video src="/beacon?video"></video>
|
||||
<input autofocus onfocus="${PWN}"><details open ontoggle="${PWN}"><summary>s</summary></details>
|
||||
<style>
|
||||
.b1{background:u\\72l(/beacon?b-escape)} .b2{background-image:image-set("/beacon?b-imageset" 1x)} .b3{background:url("x)/beacon?b-paren")}
|
||||
.b4{background:ur/**/l(/beacon?b-comment)} :root{--u:url(/beacon?b-var)} .b5{background:var(--u)}
|
||||
@font-face{font-family:bx;src:url(/beacon?b-fontface)} .b6{font-family:bx}
|
||||
@font-face{font-family:by;src:url(/api/site-builder.php?action=delete_asset)} .b7{font-family:by}
|
||||
.b8{background:url(assets/%2e%2e/beacon?b-pct)} .b9{background:url(assets/%252e%252e/beacon?b-pct2)} .b10{background:url(assets/..%2fbeacon?b-pct3)}
|
||||
.b11{background:url(javascript:1)} .b12{background:url(blob:http://x/y)} .b13{background:url("data:text/html,<b>1</b>")} .b14{-moz-binding:url(/beacon?b-moz)}
|
||||
@keyframes bk{from{background:url(/beacon?b-kf)}to{color:red}} @media (min-width:1px){.b15{background:url(/beacon?b-media)}}
|
||||
:root{--vu:url(/beacon?b-var-sh);--vs:url(/beacon?b-var-src)} .b16{background:var(--vu) no-repeat;border:1px solid var(--vu);border-image:var(--vu) 30;list-style:var(--vu) inside} .b17{background:var(--missing, url(/beacon?b-var-fallback)) center}
|
||||
</style>
|
||||
<div class="b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17" style="background:u\\72l(/beacon?i-escape);background-image:image-set('/beacon?i-set' 1x)">css bypass probes</div>
|
||||
<img src="assets/%2e%2e/beacon?p1"><img src="assets/%252e%252e/beacon?p2"><img src="assets/..%2fbeacon?p3"><img src="assets/../beacon?p4"><img src="//localhost/beacon?p5"><img src="data:text/html,x"><img src="blob:http://x/y"><img src="assets\\..\\beacon?p6">
|
||||
<img src="https://placehold.co/400x300/123456/abcdef?text=%3Cscript%3E${encodeURIComponent(PWN)}%3C/script%3E%22%3E%3Cimg+src=/beacon?ph-text%3E"><img src="https://placehold.co/400x300/123/fff/x.png?text=y"><img src="http://placehold.co/400x300?text=z"><img src="https://placehold.co/400x300/url(/beacon?ph-css)/fff">
|
||||
<div style="background:url(https://placehold.co/1200x400/222/eee?text=Hero) center/cover;height:20px"></div><style>.ph{background-image:url("https://placehold.co/300x300?text=%22%29%3B%7D*%7Bbackground:url(/beacon?ph-break)")}</style><div class="ph">ph</div>
|
||||
<p style="color:#444">Visible paragraph so the capture has real content ${'lorem ipsum '.repeat(40)}</p>
|
||||
</body></html>`;
|
||||
const BENIGN = `<!doctype html><html><head><style>body{margin:0;font:20px sans-serif}.h{background:linear-gradient(135deg,#0f172a,#3b82f6);color:#fff;padding:40px}</style></head>
|
||||
<body><div class="h"><h1>Benign page</h1><p>${'Hello world. '.repeat(30)}</p></div></body></html>`;
|
||||
|
||||
const beacons = [];
|
||||
const srv = http.createServer((q, r) => {
|
||||
const p = q.url.split('?')[0];
|
||||
if (p === '/') { r.setHeader('content-type', 'text/html'); return r.end('<!doctype html><title>host</title><body>host</body>'); }
|
||||
if (p === '/beacon') { beacons.push(q.url); r.statusCode = 204; return r.end(); }
|
||||
r.statusCode = 404; r.end('nf');
|
||||
}).listen(0);
|
||||
const port = srv.address().port;
|
||||
|
||||
let failed = 0;
|
||||
const check = (name, label, ok, extra = '') => { if (!ok) failed++; console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}${extra ? ' ' + extra : ''}`); };
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
const evilReq = [];
|
||||
await ctx.route(/evil\.example/, (route) => { evilReq.push(route.request().url()); route.abort(); });
|
||||
// placehold.co images are drawn locally: not one request may be made for them.
|
||||
const placeholdReq = [];
|
||||
await ctx.route(/placehold\.co/, (route) => { placeholdReq.push(route.request().url()); route.abort(); });
|
||||
// Only requests that actually reach the network count (Playwright also reports CSP-blocked ones as 'request').
|
||||
let messages = 0;
|
||||
await page.exposeFunction('__onMsg', () => { messages++; });
|
||||
await page.goto(`http://localhost:${port}/`);
|
||||
await page.evaluate(() => { document.cookie = 'sess=SECRET; path=/'; localStorage.setItem('csrf', 'SECRET'); window.addEventListener('message', (e) => { if (e.data === 'pwned') window.__onMsg(); }); });
|
||||
await page.addScriptTag({ content: js });
|
||||
|
||||
// 1) hostile page through the whole capture path
|
||||
beacons.length = 0;
|
||||
const res = await page.evaluate(async (h) => { const r = await window.captureHtml(h, { settleMs: 300 }); return r.ok ? { ok: true, size: r.blob.size } : r; }, EVIL);
|
||||
await page.waitForTimeout(500);
|
||||
const pwned = await page.evaluate(() => window.__pwned);
|
||||
check(name, 'hostile page: parent sentinel window.__pwned untouched', pwned === undefined, `(${pwned})`);
|
||||
check(name, 'hostile page: no postMessage to the editor', messages === 0, `(${messages})`);
|
||||
check(name, 'hostile page: ZERO requests to the panel origin /beacon (every CSS/URL/encoding bypass class)', beacons.length === 0, JSON.stringify(beacons));
|
||||
check(name, 'hostile page: no request to evil.example', evilReq.length === 0, JSON.stringify(evilReq));
|
||||
check(name, 'hostile page: no request to placehold.co (placeholders are drawn locally, incl. hostile ?text=)', placeholdReq.length === 0, JSON.stringify(placeholdReq));
|
||||
check(name, 'hostile page: capture result is safe (ok, or refused) and frame removed', (res.ok || typeof res.reason === 'string') && (await page.evaluate(() => document.querySelectorAll('iframe').length)) === 0, JSON.stringify(res));
|
||||
check(name, 'hostile page: sanitised content still captured (readable page)', res.ok === true && res.size > 3000, JSON.stringify(res));
|
||||
|
||||
// 2) defence in depth: same hostile page, NO sanitiser, only sandbox + CSP
|
||||
beacons.length = 0; evilReq.length = 0; messages = 0;
|
||||
await page.evaluate((h) => window.rawFrame(h), EVIL);
|
||||
await page.waitForTimeout(500);
|
||||
const pwned2 = await page.evaluate(() => window.__pwned);
|
||||
check(name, 'unsanitised probe: sandbox+CSP alone stop script execution (__pwned)', pwned2 === undefined, `(${pwned2})`);
|
||||
check(name, 'unsanitised probe: no postMessage', messages === 0);
|
||||
// Same-origin passive GETs (img/css url) are allowed by CSP 'self'; that is why the sanitiser also restricts them. Script-initiated ones must never occur.
|
||||
check(name, 'unsanitised probe: CSP alone (img-src data:) lets no request reach the panel origin', beacons.length === 0, JSON.stringify(beacons));
|
||||
check(name, 'unsanitised probe: no evil.example requests', evilReq.length === 0, JSON.stringify(evilReq));
|
||||
await page.evaluate(() => document.querySelectorAll('iframe').forEach((f) => f.remove()));
|
||||
|
||||
// 3) benign page still captures
|
||||
const ok = await page.evaluate(async (h) => { const r = await window.captureHtml(h, { settleMs: 300 }); return r.ok ? { ok: true, size: r.blob.size, w: r.width, h: r.height } : r; }, BENIGN);
|
||||
check(name, 'benign page captures', ok.ok === true && ok.size > 3000, JSON.stringify(ok));
|
||||
await browser.close();
|
||||
}
|
||||
await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
srv.close();
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser test (headless Firefox AND Chromium) for src/utils/color-pick.ts:
|
||||
* pickFromCanvas must return the exact computed hexes + site/brand matches,
|
||||
* Esc must cancel, a pick click must NOT reach the clicked element (no craft
|
||||
* node selection), and EyeDropper availability is reported per browser.
|
||||
* npm run test:browser:colorpick (CHROMIUM_PATH / FIREFOX_PATH override binaries)
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await build({
|
||||
entryPoints: [path.join(root, 'src/utils/color-pick.ts')],
|
||||
bundle: true, write: false, format: 'iife', globalName: 'cp', platform: 'browser', logLevel: 'error',
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
|
||||
const design = {
|
||||
primaryColor: '#3b82f6', secondaryColor: '#64748b', accentColor: '#f59e0b', linkColor: '#2563eb',
|
||||
successColor: '#16a34a', warningColor: '#d97706', errorColor: '#dc2626',
|
||||
backgroundColor: '#ffffff', textColor: '#111827', mutedTextColor: '#6b7280', borderColor: '#e5e7eb',
|
||||
swatches: [
|
||||
{ id: 'b1', label: 'Logo orange', hex: '#FF6600', brand: true, slot: 3 },
|
||||
{ id: 'p1', label: 'Sand', hex: '#c8b08a', brand: false },
|
||||
],
|
||||
};
|
||||
|
||||
const html = `<!doctype html><html><head><style>
|
||||
body{margin:0;font:16px sans-serif}
|
||||
.canvas-device-frame{--wsb-primary:#3b82f6;background:#ffffff;color:#111827;padding:10px;width:700px}
|
||||
.box{height:60px;margin:6px 0;padding:4px}
|
||||
</style></head><body>
|
||||
<div class="canvas-device-frame">
|
||||
<div id="tok" class="box" style="background:var(--wsb-primary);color:#ffffff">token bg</div>
|
||||
<div id="brand" class="box" style="background:#ff6600;color:#111827">brand bg</div>
|
||||
<div id="sand" class="box" style="background:rgba(200,176,138,1);color:#111827">swatch bg</div>
|
||||
<div id="plain" class="box" style="background:#123456;color:#fedcba;border:3px solid #0a0b0c">plain + border</div>
|
||||
<div id="outer" class="box" style="background:#112233;color:#445566"><div id="nested" style="color:#778899"><span id="deep">nested transparent</span></div></div>
|
||||
<div id="alpha" class="box" style="background:rgba(18,52,86,.5);color:#111827">alpha</div>
|
||||
<div data-zone-preview="header" style="pointer-events:none;user-select:none"><div id="zone" class="box" style="background:#15202c;color:#ffffff">header zone preview (pointer-events:none, like the editor's header/footer preview)</div></div>
|
||||
<p id="txt" style="color:#6b7280;margin:6px 0">muted text on frame bg</p>
|
||||
</div>
|
||||
<div id="chrome" style="padding:10px">editor chrome</div>
|
||||
</body></html>`;
|
||||
|
||||
// Served over http://localhost (a secure context) so EyeDropper availability is reported truthfully.
|
||||
const server = http.createServer((_q, r) => { r.setHeader('content-type', 'text/html'); r.end(html); });
|
||||
await new Promise((res) => server.listen(0, '127.0.0.1', res));
|
||||
const url = `http://localhost:${server.address().port}/`;
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 900, height: 900 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
await page.goto(url);
|
||||
await page.addScriptTag({ content: js });
|
||||
await page.evaluate((d) => {
|
||||
window.__design = d;
|
||||
window.__leaks = [];
|
||||
for (const el of document.querySelectorAll('.canvas-device-frame, .canvas-device-frame *'))
|
||||
for (const t of ['click', 'mousedown', 'mouseup', 'pointerdown', 'pointerup'])
|
||||
el.addEventListener(t, () => window.__leaks.push(t + '#' + el.id));
|
||||
}, design);
|
||||
|
||||
let failed = 0;
|
||||
const check = (label, ok, detail) => {
|
||||
if (!ok) failed++;
|
||||
console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}${detail !== undefined ? ': ' + detail : ''}`);
|
||||
};
|
||||
const eq = (label, got, want) => check(label, JSON.stringify(got) === JSON.stringify(want), JSON.stringify(got) + (JSON.stringify(got) === JSON.stringify(want) ? '' : ' expected ' + JSON.stringify(want)));
|
||||
|
||||
async function pick(id, { hover } = {}) {
|
||||
await page.evaluate(() => { window.__res = null; cp.pickFromCanvas({ design: window.__design }).then((r) => { window.__res = r; }); });
|
||||
const box = await page.locator('#' + id).boundingBox();
|
||||
const x = box.x + 8, y = box.y + 8;
|
||||
await page.mouse.move(x, y);
|
||||
let tip = null;
|
||||
if (hover) tip = await page.evaluate(() => document.querySelector('[data-wsb-pick=tip]')?.textContent ?? null);
|
||||
await page.mouse.click(x, y);
|
||||
await page.waitForFunction(() => window.__res !== null, null, { timeout: 3000 });
|
||||
return { res: await page.evaluate(() => window.__res), tip };
|
||||
}
|
||||
const cand = (res, k) => res.candidates.find((c) => c.kind === k);
|
||||
|
||||
// 1. token-driven background (CSS variable)
|
||||
let { res, tip } = await pick('tok', { hover: true });
|
||||
eq('token bg: hex', res.hex, '#3b82f6');
|
||||
eq('token bg: background match', cand(res, 'background').match, { kind: 'token', ref: 'var(--wsb-primary)', label: 'Primary' });
|
||||
eq('token bg: text candidate', cand(res, 'text').hex, '#ffffff');
|
||||
check('token bg: hover tooltip shows live colour', tip === '#3b82f6', String(tip));
|
||||
eq('token bg: no border candidate', cand(res, 'border'), undefined);
|
||||
|
||||
// 2. brand swatch (case-insensitive hex)
|
||||
({ res } = await pick('brand'));
|
||||
eq('brand: hex', res.hex, '#ff6600');
|
||||
eq('brand: match', cand(res, 'background').match, { kind: 'swatch', ref: 'var(--wsb-brand-3)', label: 'Logo orange' });
|
||||
|
||||
// 3. plain saved swatch via rgba(...,1)
|
||||
({ res } = await pick('sand'));
|
||||
eq('swatch: hex', res.hex, '#c8b08a');
|
||||
eq('swatch: match', cand(res, 'background').match, { kind: 'swatch', ref: '#c8b08a', label: 'Sand' });
|
||||
|
||||
// 4. plain bg + text + border, no match
|
||||
({ res } = await pick('plain'));
|
||||
eq('plain: hex = bg', res.hex, '#123456');
|
||||
eq('plain: text', cand(res, 'text').hex, '#fedcba');
|
||||
eq('plain: border', cand(res, 'border').hex, '#0a0b0c');
|
||||
eq('plain: no matches', res.candidates.map((c) => c.match), [undefined, undefined, undefined]);
|
||||
|
||||
// 5. nested transparent child: text colour wins, background = painted ancestor
|
||||
({ res } = await pick('deep'));
|
||||
eq('nested: hex = inherited text colour', res.hex, '#778899');
|
||||
eq('nested: background = nearest painted ancestor', cand(res, 'background').hex, '#112233');
|
||||
eq('nested: no border', cand(res, 'border'), undefined);
|
||||
|
||||
// 6. alpha background -> 8-digit hex
|
||||
({ res } = await pick('alpha'));
|
||||
eq('alpha: hex', res.hex, '#12345680');
|
||||
|
||||
// 7. text on frame bg (frame background is the painted ancestor, matches Background token)
|
||||
({ res } = await pick('txt'));
|
||||
eq('text: hex', res.hex, '#6b7280');
|
||||
eq('text: text match', cand(res, 'text').match, { kind: 'token', ref: 'var(--wsb-muted)', label: 'Muted text' });
|
||||
eq('text: background match', cand(res, 'background').match, { kind: 'token', ref: 'var(--wsb-bg)', label: 'Background' });
|
||||
|
||||
// 7b. the editor's header/footer zone previews are pointer-events:none: they must still be pickable
|
||||
({ res } = await pick('zone'));
|
||||
eq('zone preview: hex', res.hex, '#15202c');
|
||||
eq('zone preview: text candidate', cand(res, 'text').hex, '#ffffff');
|
||||
|
||||
// 8. none of those pick clicks reached the elements (no node selection)
|
||||
eq('clicks never reached targets', await page.evaluate(() => window.__leaks), []);
|
||||
|
||||
// 9. Esc cancels; overlay cleaned up
|
||||
await page.evaluate(() => { window.__res = null; cp.pickFromCanvas({ design: window.__design }).then((r) => { window.__res = r; }); });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.waitForFunction(() => window.__res !== null, null, { timeout: 3000 });
|
||||
const esc = await page.evaluate(() => window.__res);
|
||||
check('Esc cancels', esc.ok === false && esc.reason === 'cancelled', JSON.stringify(esc));
|
||||
eq('overlay removed', await page.evaluate(() => document.querySelectorAll('[data-wsb-pick]').length), 0);
|
||||
|
||||
// 10. click outside the frame cancels
|
||||
await page.evaluate(() => { window.__res = null; cp.pickFromCanvas({ design: window.__design }).then((r) => { window.__res = r; }); });
|
||||
const cb = await page.locator('#chrome').boundingBox();
|
||||
await page.mouse.click(cb.x + 5, cb.y + 5);
|
||||
await page.waitForFunction(() => window.__res !== null, null, { timeout: 3000 });
|
||||
check('outside click cancels', (await page.evaluate(() => window.__res)).reason === 'cancelled');
|
||||
|
||||
// 11. after a pick finishes, normal clicks flow again
|
||||
await page.evaluate(() => { window.__leaks.length = 0; });
|
||||
await page.locator('#tok').click();
|
||||
check('clicks flow normally after picking', (await page.evaluate(() => window.__leaks)).includes('click#tok'));
|
||||
|
||||
// 12. EyeDropper availability (report)
|
||||
const eye = await page.evaluate(() => ({ present: 'EyeDropper' in window, available: cp.eyedropperAvailable(), kind: cp.screenPickKind() }));
|
||||
console.log(`[${name}] INFO EyeDropper: window.EyeDropper=${eye.present} eyedropperAvailable()=${eye.available} screenPickKind()=${eye.kind}`);
|
||||
check('secure context', await page.evaluate(() => isSecureContext));
|
||||
if (name === 'firefox') check('firefox: no screen pick (verdict C)', eye.kind === 'none');
|
||||
else check('chromium: screenPickKind matches window.EyeDropper', eye.kind === (eye.present ? 'eyedropper' : 'none'));
|
||||
|
||||
if (errors.length) { failed++; console.log('page errors:', errors.join('\n')); }
|
||||
await browser.close();
|
||||
return failed;
|
||||
}
|
||||
let total = 0;
|
||||
total += await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
total += await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
server.close();
|
||||
console.log(total ? `FAILED (${total})` : 'ALL PASS');
|
||||
process.exit(total ? 1 : 0);
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
/**
|
||||
* Used by scripts/e2e-color-system.mjs: reads {title,css,html,headCode,design} JSON on stdin and prints what the
|
||||
* BACKEND publishes (generateCompiledHTML in api/site-builder.php). Usage: php e2e-color-system-backend.php <backend repo dir>
|
||||
*/
|
||||
ob_start();
|
||||
define('SB_API_LIBRARY_ONLY', true);
|
||||
define('AUTH_USER', 'alice');
|
||||
define('HOME_DIR', '/docker/users/alice');
|
||||
require rtrim($argv[1], '/') . '/web-files/api/site-builder.php';
|
||||
ob_end_clean();
|
||||
$in = json_decode(stream_get_contents(STDIN), true);
|
||||
$U = 'https://example.com/';
|
||||
echo generateCompiledHTML($in['title'], $in['css'], $in['html'], $in['headCode'], [], '', $in['design'], $U, sb_canonical_url($U, 'index.html'));
|
||||
@@ -0,0 +1,25 @@
|
||||
// Bundled (esbuild) by scripts/e2e-color-system.mjs and run in Node: what a publish of a saved project.json
|
||||
// emits through the FRONTEND path (renderPublished = the editor Preview document), plus the pieces the
|
||||
// BACKEND path receives (the composed body HTML), so the two heads can be compared.
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
|
||||
function bodies(project: any, pageIdx: number) {
|
||||
const page = project.pages_craft_state[pageIdx];
|
||||
const hdr = project.header_craft_state ? exportBodyHtml(project.header_craft_state, 'header').html : '';
|
||||
const ftr = project.footer_craft_state ? exportBodyHtml(project.footer_craft_state, 'footer').html : '';
|
||||
const body = exportBodyHtml(page.craftState).html;
|
||||
return { page, composed: hdr + body + ftr };
|
||||
}
|
||||
|
||||
export function renderPublished(project: any, pageIdx: number): string {
|
||||
const { page, composed } = bodies(project, pageIdx);
|
||||
return exportComposedPreviewHtml(page.craftState, composed, {
|
||||
title: page.name, includeFonts: true, headCode: project.design?.headCode, design: project.design,
|
||||
});
|
||||
}
|
||||
|
||||
/** The inputs handlePublish feeds generateCompiledHTML for a page. */
|
||||
export function backendInputs(project: any, pageIdx: number) {
|
||||
const { page, composed } = bodies(project, pageIdx);
|
||||
return { title: page.name, css: '', html: composed, headCode: project.design?.headCode || '', design: project.design || {} };
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/** Project fixture for the colour-system e2e: an OLS-Digital-like dark header (#0f172a) with a logo box (#15202c) and a small page. */
|
||||
const node = (name, props, parent, nodes = [], isCanvas = false) => ({
|
||||
type: { resolvedName: name }, isCanvas, props, displayName: name, custom: {}, parent, hidden: false, nodes, linkedNodes: {},
|
||||
});
|
||||
const base = { anchorId: '', cssId: '', cssClass: '', animation: '', animationDelay: '0', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false };
|
||||
const box = (id, style, aiName) => ({ style: { padding: '20px', minHeight: '60px', ...style }, tag: 'div', fullWidth: false, contentWidth: 'full', ...base, aiName, node_id: id });
|
||||
|
||||
export function buildProject() {
|
||||
const header = {
|
||||
ROOT: node('Container', box('hdr-root', { backgroundColor: '#0f172a' }, 'Header'), null, ['logo-box'], true),
|
||||
'logo-box': node('Container', box('logo-box', { backgroundColor: '#15202c', minHeight: '50px' }, 'Logo box'), 'ROOT', [], true),
|
||||
};
|
||||
const page = {
|
||||
ROOT: node('Container', box('page-root', {}, 'Root'), null, ['target-box', 'copy'], true),
|
||||
// The element the brand colour is applied to.
|
||||
'target-box': node('Container', box('target-box', { backgroundColor: '#ffffff', minHeight: '80px' }, 'Target box'), 'ROOT', [], true),
|
||||
copy: node('TextBlock', { text: 'Hello colour system', html: '', style: { fontSize: '16px', color: '#111111' }, ...base, aiName: 'Copy', node_id: 'copy' }, 'ROOT'),
|
||||
};
|
||||
return {
|
||||
site_id: 1, name: 'Colours', html: '', css: '', pages: [], header_html: '', footer_html: '', head_code: '',
|
||||
craft_state: '', header_craft_state: JSON.stringify(header), footer_craft_state: '',
|
||||
pages_craft_state: [{ id: 'home', name: 'Home', slug: 'index', craftState: JSON.stringify(page) }],
|
||||
design: {
|
||||
primaryColor: '#3b82f6', secondaryColor: '#8b5cf6', accentColor: '#10b981', headingFont: 'Inter, sans-serif', bodyFont: 'Inter, sans-serif',
|
||||
linkColor: '#3b82f6', successColor: '#10b981', warningColor: '#f59e0b', errorColor: '#ef4444', backgroundColor: '#ffffff',
|
||||
textColor: '#1f2937', mutedTextColor: '#6b7280', borderColor: '#e5e7eb', borderRadius: '8px', buttonFont: 'Inter, sans-serif',
|
||||
buttonRadius: '8px', navStyle: 'light', headCode: '', favicon: '',
|
||||
},
|
||||
extras: {},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Mock WHP site-builder API + static server for the real-editor colour-system e2e
|
||||
* (scripts/e2e-color-system.mjs). Unlike the parity mock it STORES what the editor
|
||||
* saves (so a reload restores it), and serves a same-origin PNG through the
|
||||
* list_assets / upload_asset endpoints in the shape the real api/site-builder.php returns.
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
|
||||
function crc32(buf) {
|
||||
let c, crc = 0xffffffff;
|
||||
for (let n = 0; n < buf.length; n++) {
|
||||
c = (crc ^ buf[n]) & 0xff;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
crc = (crc >>> 8) ^ c;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
function chunk(type, data) {
|
||||
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
|
||||
const td = Buffer.concat([Buffer.from(type), data]);
|
||||
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td));
|
||||
return Buffer.concat([len, td, crc]);
|
||||
}
|
||||
/** w*h RGB PNG; px(x,y) -> [r,g,b]. */
|
||||
export function makePng(w, h, px) {
|
||||
const raw = Buffer.alloc((w * 3 + 1) * h);
|
||||
for (let y = 0; y < h; y++) {
|
||||
raw[y * (w * 3 + 1)] = 0;
|
||||
for (let x = 0; x < w; x++) {
|
||||
const [r, g, b] = px(x, y);
|
||||
const o = y * (w * 3 + 1) + 1 + x * 3;
|
||||
raw[o] = r; raw[o + 1] = g; raw[o + 2] = b;
|
||||
}
|
||||
}
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
|
||||
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
/** 100x100 test image: four flat quadrants + a few colour bands so palette extraction has >= 5 colours. */
|
||||
export const TEST_PNG_COLORS = {
|
||||
tl: [255, 0, 0], tr: [0, 0, 255], bl: [0, 160, 0], br: [255, 200, 0],
|
||||
band1: [128, 0, 128], band2: [0, 200, 200], band3: [40, 40, 40],
|
||||
};
|
||||
export function testPng() {
|
||||
const C = TEST_PNG_COLORS;
|
||||
return makePng(100, 100, (x, y) => {
|
||||
if (y >= 90) return x < 34 ? C.band1 : x < 67 ? C.band2 : C.band3;
|
||||
return y < 45 ? (x < 50 ? C.tl : C.tr) : (x < 50 ? C.bl : C.br);
|
||||
});
|
||||
}
|
||||
|
||||
export async function startServer({ buildDir, project, siteId = 1, extraAssets = [] }) {
|
||||
const state = { project, rev: 1, saves: 0, lastSaveBody: null, assets: [{ name: 'test.png', type: 'image/png', buf: testPng() }] };
|
||||
const mime = { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png', '.svg': 'image/svg+xml' };
|
||||
const json = (res, o, code = 200) => { res.statusCode = code; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(o)); };
|
||||
const server = http.createServer((req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (u.pathname === '/api/site-builder.php') {
|
||||
const a = u.searchParams.get('action');
|
||||
if (a === 'load') return json(res, { success: true, rev: 'r' + state.rev, limits: {}, project: state.project });
|
||||
if (a === 'list_assets') {
|
||||
return json(res, { success: true, assets: [...extraAssets, ...state.assets.map((s) => ({ name: s.name, url: `/api/assets-proxy/?site_id=${siteId}&filename=${encodeURIComponent(s.name)}`, type: s.type, size: s.buf.length, modified: 1 }))] });
|
||||
}
|
||||
if (a === 'save' && req.method === 'POST') {
|
||||
const chunks = [];
|
||||
req.on('data', (c) => chunks.push(c));
|
||||
req.on('end', () => {
|
||||
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
||||
const { base_rev, client_id, force_empty, force_overwrite, ...proj } = body;
|
||||
state.project = proj; state.lastSaveBody = body; state.saves++; state.rev++;
|
||||
json(res, { success: true, rev: 'r' + state.rev });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (a === 'upload_asset' && req.method === 'POST') {
|
||||
const chunks = [];
|
||||
req.on('data', (c) => chunks.push(c));
|
||||
req.on('end', () => json(res, { success: false, error: 'uploads not supported by the test mock' }, 400));
|
||||
return;
|
||||
}
|
||||
return json(res, { success: true });
|
||||
}
|
||||
if (u.pathname === '/api/assets-proxy/') {
|
||||
const a = state.assets.find((s) => s.name === u.searchParams.get('filename'));
|
||||
if (!a) { res.statusCode = 404; return res.end('nf'); }
|
||||
res.setHeader('content-type', a.type); return res.end(a.buf);
|
||||
}
|
||||
const p = u.pathname === '/' ? '/index.html' : u.pathname;
|
||||
if (p === '/index.html') {
|
||||
const cfg = { user: 't', apiUrl: '/api/site-builder.php', csrfToken: 'x', siteId, siteDomain: 'example.test', siteName: 'Colours', backUrl: '/', isRoot: false };
|
||||
const h = fs.readFileSync(path.join(buildDir, 'index.html'), 'utf8').replace('</head>', () => `<script>window.WHP_CONFIG=${JSON.stringify(cfg)};</script></head>`);
|
||||
res.setHeader('content-type', 'text/html'); return res.end(h);
|
||||
}
|
||||
const f = path.join(buildDir, p);
|
||||
if (f.startsWith(buildDir) && fs.existsSync(f) && fs.statSync(f).isFile()) {
|
||||
res.setHeader('content-type', mime[path.extname(f)] || 'application/octet-stream'); return res.end(fs.readFileSync(f));
|
||||
}
|
||||
res.statusCode = 404; res.end('nf');
|
||||
});
|
||||
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
||||
return { server, state, base: `http://localhost:${server.address().port}` };
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* REAL-EDITOR end-to-end test of the whole site colour system, headless Firefox AND Chromium.
|
||||
* Mounts the real editor (vite build + a mock WHP API that STORES saves, so reload restores them) and drives
|
||||
* the real UI: hex entry, pick from page / image, palette from image, persistence across reload, live brand
|
||||
* recolour (canvas == published by the frontend export == published by the backend generateCompiledHTML),
|
||||
* brand cap + guarded delete, contrast notes, and EyeDropper availability.
|
||||
*
|
||||
* npm run test:browser:colors
|
||||
*
|
||||
* Env: CHROMIUM_PATH / FIREFOX_PATH override the Playwright-pinned binaries
|
||||
* COLOR_SHOTS=<dir> write Firefox screenshots (shot-*.png) there
|
||||
* WHP_BACKEND_DIR backend worktree for the generateCompiledHTML leg (default /workspace/whp-wt-color-system)
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { startServer, testPng, TEST_PNG_COLORS } from './e2e-color-system-server.mjs';
|
||||
import { buildProject } from './e2e-color-system-fixture.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const BACKEND_DIR = process.env.WHP_BACKEND_DIR || '/workspace/whp-wt-color-system';
|
||||
// Pre-colour-feature baseline. 69fd34b = the first commit carrying the 2026.11.4 published head
|
||||
// (ColumnLayout stacking + Navbar wrap, fix/mobile-parity) and none of the colour feature, so "no brand
|
||||
// colours => published document unchanged" compares against the head that actually shipped before it.
|
||||
// (ab7a100, the old default, predates the 2026.11.4 head rules, so this check failed on main since then.)
|
||||
// Override with COLOR_BASE_COMMIT=<sha> on a branch with other deliberate head changes.
|
||||
const BASE_COMMIT = process.env.COLOR_BASE_COMMIT || '69fd34b';
|
||||
// Deliberate head changes made AFTER the base, folded back before the comparison so it still proves the
|
||||
// colour feature changed nothing else. Each `from` must occur exactly once (checked).
|
||||
const HEAD_FOLDS = [
|
||||
{
|
||||
why: 'legacy-grid: stored (pre-hook) card-grid signatures right after [data-wsb-grid] in the <=767px block',
|
||||
from: '[data-wsb-grid]{grid-template-columns:minmax(0,1fr)!important}[style^="max-width:1100px;margin:0 auto;display:grid;grid-template-columns:repeat("][style$=",1fr);gap:32px;text-align:center"]{grid-template-columns:minmax(0,1fr)!important}[style="max-width:1100px;margin:0 auto;display:grid;grid-template-columns:repeat(3,1fr);gap:32px"]:not(:has(>*>img[style^="width:100%;height:200px;object-fit:cover"])),[style^="max-width:1100px;margin:0 auto;display:grid;grid-template-columns:repeat("][style$=",1fr);gap:24px"]:not(:has(>*>img[style^="width:100%;height:200px;object-fit:cover"])){grid-template-columns:minmax(0,1fr)!important}',
|
||||
to: '[data-wsb-grid]{grid-template-columns:minmax(0,1fr)!important}',
|
||||
},
|
||||
{
|
||||
why: 'mobile-guard: card-grid / long-word / HtmlBlock media rules in the <=767px block; Navbar wrap moved to <=991px',
|
||||
from: '[class^="cols_"]{flex-direction:column!important;align-items:stretch!important}[data-wsb-grid]{grid-template-columns:minmax(0,1fr)!important}body{overflow-wrap:break-word}[data-wsb-html] :is(img,video,iframe,embed,object,svg,canvas){max-width:100%}[data-wsb-html] :is(img,video){height:auto}[data-wsb-html] pre{max-width:100%;overflow-x:auto}}@media(max-width:991px){nav[class^="nav_"],nav[class^="nav_"] .navbar-links{flex-wrap:wrap}}',
|
||||
to: '[class^="cols_"]{flex-direction:column!important;align-items:stretch!important}nav[class^="nav_"],nav[class^="nav_"] .navbar-links{flex-wrap:wrap}}',
|
||||
},
|
||||
];
|
||||
const foldHead = (html) => HEAD_FOLDS.reduce((h, f) => (h.split(f.from).length === 2 ? h.replace(f.from, () => f.to) : h), html);
|
||||
// Counted in order on the progressively folded document (a later fold's `from` may need an earlier fold applied).
|
||||
const foldsApplied = (html) => HEAD_FOLDS.map((f) => { const n = html.split(f.from).length - 1; if (n === 1) html = html.replace(f.from, () => f.to); return n; });
|
||||
const SHOTS = process.env.COLOR_SHOTS || '';
|
||||
if (SHOTS) fs.mkdirSync(SHOTS, { recursive: true });
|
||||
|
||||
// ---------------------------------------------------------------- frontend exporter (HEAD, and the pre-feature base commit)
|
||||
async function loadExporter(entryDir, tag) {
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(entryDir, 'scripts', tag === 'base' ? 'e2e-canvas-export-entry.ts' : 'e2e-color-system-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error', absWorkingDir: entryDir,
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const f = path.join(os.tmpdir(), `wsb-colors-export-${tag}-${process.pid}.mjs`);
|
||||
fs.writeFileSync(f, out.outputFiles[0].text);
|
||||
const m = await import(f);
|
||||
fs.rmSync(f, { force: true });
|
||||
return m;
|
||||
}
|
||||
const head = await loadExporter(root, 'head');
|
||||
let baseExporter = null;
|
||||
const baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wsb-colors-base-'));
|
||||
try {
|
||||
const top = execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd: root }).toString().trim();
|
||||
const prefix = path.relative(top, root); // 'craft'
|
||||
execFileSync('bash', ['-c', `git -C '${top}' archive ${BASE_COMMIT} ${prefix}/src ${prefix}/scripts/e2e-canvas-export-entry.ts ${prefix}/package.json ${prefix}/tsconfig.json | tar -x -C '${baseDir}'`]);
|
||||
fs.symlinkSync(path.join(root, 'node_modules'), path.join(baseDir, prefix, 'node_modules'));
|
||||
baseExporter = await loadExporter(path.join(baseDir, prefix), 'base');
|
||||
} catch (e) { console.log('NOTE base-commit exporter unavailable:', String(e.message).split('\n')[0]); }
|
||||
|
||||
function backendHtml(project, idx = 0) {
|
||||
const inp = head.backendInputs(project, idx);
|
||||
return execFileSync('php', [path.join(root, 'scripts/e2e-color-system-backend.php'), BACKEND_DIR], { input: JSON.stringify(inp), maxBuffer: 1 << 26 }).toString();
|
||||
}
|
||||
const haveBackend = fs.existsSync(path.join(BACKEND_DIR, 'web-files/api/site-builder.php'));
|
||||
const rootDecl = (html) => (html.match(/:root\{[^}]*\}/) || [''])[0];
|
||||
|
||||
// ---------------------------------------------------------------- build the real editor once
|
||||
const buildDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wsb-colors-'));
|
||||
execFileSync(path.join(root, 'node_modules/.bin/vite'), ['build', '--outDir', buildDir, '--emptyOutDir', '--logLevel', 'error'], { cwd: root, stdio: 'inherit' });
|
||||
|
||||
// A second origin serving the same PNG without CORS headers = "an image from another website".
|
||||
const remote = http.createServer((_q, r) => { r.setHeader('content-type', 'image/png'); r.end(testPng()); });
|
||||
await new Promise((r) => remote.listen(0, '127.0.0.1', r));
|
||||
const REMOTE_URL = `http://127.0.0.1:${remote.address().port}/remote.png`;
|
||||
|
||||
const toHex = (rgb) => {
|
||||
const m = /rgba?\(\s*(\d+),\s*(\d+),\s*(\d+)/.exec(rgb);
|
||||
return m ? '#' + [m[1], m[2], m[3]].map((n) => Number(n).toString(16).padStart(2, '0')).join('') : rgb;
|
||||
};
|
||||
const hx = (c) => '#' + c.map((n) => n.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
// ---------------------------------------------------------------- driver
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const ctx = await browser.newContext({ viewport: { width: 1500, height: 1000 } });
|
||||
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1|localhost)/, (r) => r.abort());
|
||||
const { server, state, base } = await startServer({
|
||||
buildDir, project: buildProject(),
|
||||
extraAssets: [{ name: 'remote.png', url: REMOTE_URL, type: 'image/png', size: 1, modified: 2 }],
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
const dialogs = [];
|
||||
page.on('dialog', (d) => { dialogs.push(d.message()); d.dismiss().catch(() => {}); });
|
||||
|
||||
let failed = 0;
|
||||
const check = (label, ok, detail) => {
|
||||
if (!ok) failed++;
|
||||
console.log(`[${name}] ${ok ? 'PASS' : 'FAIL'} ${label}${detail !== undefined ? ': ' + detail : ''}`);
|
||||
};
|
||||
const eq = (label, got, want) => {
|
||||
const ok = JSON.stringify(got) === JSON.stringify(want);
|
||||
check(label, ok, ok ? JSON.stringify(got) : `${JSON.stringify(got)} expected ${JSON.stringify(want)}`);
|
||||
};
|
||||
const shot = async (file) => { if (SHOTS && name === 'firefox') await page.screenshot({ path: path.join(SHOTS, file) }); };
|
||||
const settle = (ms = 250) => page.waitForTimeout(ms);
|
||||
|
||||
// ---- page helpers
|
||||
const frame = '.canvas-device-frame';
|
||||
const targetSel = `${frame} [data-craft-container][style*="min-height: 80px"]`;
|
||||
const logoSel = `${frame} [data-zone-preview=header] > div > div`;
|
||||
const sm = page.locator('[data-testid=swatch-manager]');
|
||||
const openSite = async () => { await page.click('#right-tab-site'); await sm.scrollIntoViewIfNeeded(); await settle(); };
|
||||
const openElement = async () => { await page.click('#right-tab-element'); await settle(); };
|
||||
const rows = () => sm.locator('[data-swatch-row]');
|
||||
const rowData = async () => rows().evaluateAll((els) => els.map((e) => ({
|
||||
id: e.getAttribute('data-swatch-row'),
|
||||
label: e.querySelector('[data-field=label]').value,
|
||||
hex: e.querySelector('[data-field=hex]').value,
|
||||
brand: e.querySelector('[data-action=brand]').getAttribute('aria-pressed') === 'true',
|
||||
live: !!e.querySelector('[data-testid=live-badge]'),
|
||||
})));
|
||||
const loadEditor = async () => {
|
||||
await page.goto(base + '/');
|
||||
await page.waitForSelector(`${frame} [data-craft-container]`, { timeout: 20000 });
|
||||
await settle(1200);
|
||||
};
|
||||
const selectTarget = async () => { await page.locator(targetSel).click({ position: { x: 30, y: 30 } }); await settle(400); await page.click('#right-tab-element'); await settle(300); };
|
||||
const fieldOf = (label) => page.locator('.panel-right .guided-section', { hasText: label }).first();
|
||||
const canvasBg = (sel) => page.locator(sel).evaluate((e) => getComputedStyle(e).backgroundColor);
|
||||
const save = async () => {
|
||||
const before = state.saves;
|
||||
await page.getByRole('button', { name: 'Save Draft' }).click();
|
||||
await page.waitForFunction(() => /Saved/.test(document.body.innerText), null, { timeout: 8000 }).catch(() => {});
|
||||
for (let i = 0; i < 40 && state.saves === before; i++) await settle(150);
|
||||
check('save went through the editor save path', state.saves > before, `saves=${state.saves}`);
|
||||
};
|
||||
const pageNodes = () => JSON.parse(state.project.pages_craft_state[0].craftState);
|
||||
|
||||
// ================================================================= 8 (first: needs only a loaded page) EyeDropper
|
||||
await loadEditor();
|
||||
const eye = await page.evaluate(() => ({ present: 'EyeDropper' in window, secure: isSecureContext }));
|
||||
await openSite();
|
||||
const screenBtnsSite = await sm.getByRole('button', { name: 'Pick from screen' }).count();
|
||||
console.log(`[${name}] INFO window.EyeDropper present=${eye.present} secureContext=${eye.secure}`);
|
||||
if (name === 'firefox') eq('8 Firefox: Pick from screen button ABSENT', screenBtnsSite, 0);
|
||||
else eq(`8 Chromium: Pick from screen present only if window.EyeDropper (EyeDropper=${eye.present})`, screenBtnsSite, eye.present ? 1 : 0);
|
||||
|
||||
// ================================================================= 1 Hex entry
|
||||
await sm.locator('[data-field=new-hex]').fill('zz');
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle();
|
||||
const hexErr = await sm.locator('[role=alert].color-hex-error').allInnerTexts();
|
||||
eq('1 invalid hex "zz" rejected with message', hexErr, ['Enter a hex colour like #3b82f6 (3, 4, 6 or 8 digits).']);
|
||||
eq('1 invalid hex added no row', (await rowData()).length, 0);
|
||||
await sm.locator('[data-field=new-hex]').fill('#15202C');
|
||||
await sm.locator('[data-field=new-label]').fill('Logo box');
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle();
|
||||
let rd = await rowData();
|
||||
eq('1 "#15202C" + label added, hex normalised', rd.map((r) => [r.label, r.hex]), [['Logo box', '#15202c']]);
|
||||
eq('1 error cleared after a valid add', await sm.locator('[role=alert].color-hex-error').count(), 0);
|
||||
for (const [typed, want] of [['#abc', '#abc'], ['#11223344', '#11223344'], ['f60', '#f60']]) {
|
||||
await sm.locator('[data-field=new-hex]').fill(typed);
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle(150);
|
||||
rd = await rowData();
|
||||
eq(`1 form "${typed}" accepted`, rd[rd.length - 1].hex, want);
|
||||
}
|
||||
// keep only Logo box
|
||||
for (let i = 0; i < 3; i++) { await rows().last().locator('[data-action=delete]').click(); await settle(150); }
|
||||
eq('1 cleanup leaves only Logo box', (await rowData()).map((r) => r.hex), ['#15202c']);
|
||||
|
||||
// ================================================================= 2 Pick from page
|
||||
const logoBox = await page.locator(logoSel).first().boundingBox();
|
||||
const hdrHex = await page.locator(`${frame} [data-zone-preview=header] > div`).first().evaluate((e) => getComputedStyle(e).backgroundColor);
|
||||
eq('2 fixture: header paints #0f172a', toHex(hdrHex), '#0f172a');
|
||||
const designBefore = JSON.stringify(await page.evaluate(() => null));
|
||||
const stylesBefore = await page.locator(targetSel).getAttribute('style');
|
||||
await sm.getByRole('button', { name: 'Pick from page' }).click();
|
||||
await settle(300);
|
||||
await page.mouse.move(logoBox.x + logoBox.width / 2, logoBox.y + logoBox.height / 2);
|
||||
await settle(200);
|
||||
const tipTxt = await page.evaluate(() => document.querySelector('[data-wsb-pick=tip]')?.textContent ?? null);
|
||||
check('2 pick mode shows a live tooltip while hovering the logo box', !!tipTxt && /#15202c/i.test(tipTxt), String(tipTxt));
|
||||
await shot('shot-canvas-pick-mode-tooltip.png');
|
||||
await page.mouse.click(logoBox.x + logoBox.width / 2, logoBox.y + logoBox.height / 2);
|
||||
await settle(400);
|
||||
const chooser = sm.locator('[data-testid=pick-chooser]');
|
||||
const chooserCount = await chooser.count();
|
||||
check('2 pick from page then offers the chooser (bg + text colours differ)', chooserCount === 1);
|
||||
const chooserBtns = chooserCount ? await chooser.locator('button').evaluateAll((bs) => bs.map((b) => b.innerText.replace(/\s+/g, ' ').trim())) : [];
|
||||
const logoComputed = toHex(await page.locator(logoSel).first().evaluate((e) => getComputedStyle(e).backgroundColor));
|
||||
const bgBtn = chooserBtns.find((t) => /^Background/.test(t)) || '';
|
||||
check('2 chooser background candidate equals the element computed colour', bgBtn.includes(logoComputed), `${logoComputed} :: ${JSON.stringify(chooserBtns)}`);
|
||||
check('2 chooser offers the match to the saved colour "Logo box"', /matches Logo box/.test(bgBtn), bgBtn);
|
||||
await shot('shot-canvas-pick-chooser.png');
|
||||
await chooser.getByRole('button', { name: /^Background/ }).click();
|
||||
await settle(300);
|
||||
rd = await rowData();
|
||||
eq('2 picking an already-saved colour adds no duplicate', rd.length, 1);
|
||||
check('2 note says it is already saved', /Already saved as "Logo box"/.test(await sm.locator('[role=status]').innerText()));
|
||||
await openElement();
|
||||
check('2 the pick click did NOT select a craft node', /Select something on the canvas/.test(await page.locator('.panel-right').innerText()));
|
||||
eq('2 target box untouched', await page.locator(targetSel).getAttribute('style'), stylesBefore);
|
||||
|
||||
// token match: the page's white target box == the Background token
|
||||
await openSite();
|
||||
const tb = await page.locator(targetSel).boundingBox();
|
||||
await sm.getByRole('button', { name: 'Pick from page' }).click();
|
||||
await settle(300);
|
||||
await page.mouse.click(tb.x + 30, tb.y + 30);
|
||||
await settle(400);
|
||||
// white bg + inherited text colour -> chooser; the Background candidate must report the token match
|
||||
const ch2 = await sm.locator('[data-testid=pick-chooser] button').evaluateAll((bs) => bs.map((b) => b.innerText.replace(/\s+/g, ' ').trim()));
|
||||
const tbComputed = toHex(await page.locator(targetSel).evaluate((e) => getComputedStyle(e).backgroundColor));
|
||||
check('2 token match offered when the picked colour equals a site colour', ch2.some((t) => t.includes(tbComputed) && /matches Background/.test(t)), JSON.stringify(ch2));
|
||||
await sm.locator('[data-testid=pick-chooser]').getByRole('button', { name: 'Cancel' }).click();
|
||||
await settle(200);
|
||||
eq('2 still no extra swatch after cancel', (await rowData()).length, 1);
|
||||
|
||||
// ================================================================= 3 Pick from image + palette
|
||||
await sm.getByRole('button', { name: 'Pick from image' }).click();
|
||||
await page.waitForSelector('[data-testid=image-pick-modal]');
|
||||
await page.locator('[data-testid=image-asset-test\\.png]').click();
|
||||
const cv = page.locator('[data-testid=image-pick-canvas]');
|
||||
await page.waitForFunction(() => { const c = document.querySelector('[data-testid=image-pick-canvas]'); return c && c.style.display !== 'none' && c.width > 0; });
|
||||
const cb = await cv.boundingBox();
|
||||
// known pixel: 75% across, 20% down = top-right quadrant (blue)
|
||||
const px = cb.x + cb.width * 0.75, py = cb.y + cb.height * 0.2;
|
||||
await page.mouse.move(px, py);
|
||||
await settle(200);
|
||||
eq('3 hover shows the exact pixel hex', (await page.locator('[data-testid=image-pick-hex]').innerText()), hx(TEST_PNG_COLORS.tr));
|
||||
await shot('shot-pick-from-image-modal.png');
|
||||
await page.mouse.click(px, py);
|
||||
await settle(300);
|
||||
rd = await rowData();
|
||||
eq('3 clicking the pixel saved exactly that colour', rd.map((r) => r.hex), ['#15202c', hx(TEST_PNG_COLORS.tr)]);
|
||||
check('3 modal closed after the pick', (await page.locator('[data-testid=image-pick-modal]').count()) === 0);
|
||||
// other quadrant for another exact value
|
||||
await sm.getByRole('button', { name: 'Pick from image' }).click();
|
||||
await page.locator('[data-testid=image-asset-test\\.png]').click();
|
||||
await page.waitForFunction(() => { const c = document.querySelector('[data-testid=image-pick-canvas]'); return c && c.style.display !== 'none' && c.width > 0; });
|
||||
const cb2 = await page.locator('[data-testid=image-pick-canvas]').boundingBox();
|
||||
await page.mouse.click(cb2.x + cb2.width * 0.25, cb2.y + cb2.height * 0.75);
|
||||
await settle(300);
|
||||
rd = await rowData();
|
||||
eq('3 bottom-left pixel exact', rd[rd.length - 1].hex, hx(TEST_PNG_COLORS.bl));
|
||||
// cross-origin error
|
||||
await sm.getByRole('button', { name: 'Pick from image' }).click();
|
||||
await page.locator('[data-testid=image-asset-remote\\.png]').click();
|
||||
await page.waitForSelector('[data-testid=image-pick-error]');
|
||||
const xo = await page.locator('[data-testid=image-pick-error]').innerText();
|
||||
check('3 cross-origin src shows the plain-English error', /comes from another website/.test(xo) && /Upload it to this site first/.test(xo), xo);
|
||||
await page.locator('[data-testid=image-pick-close]').click();
|
||||
// palette
|
||||
const swatchesBeforePalette = (await rowData()).map((r) => r.hex);
|
||||
await sm.getByRole('button', { name: 'Palette from image' }).click();
|
||||
await page.waitForSelector('[data-testid=palette-from-image-modal]');
|
||||
await page.locator('[data-testid=palette-from-image-modal] [data-testid=image-asset-test\\.png]').click();
|
||||
await page.waitForSelector('[data-testid^=palette-row-]');
|
||||
const palHexes = await page.locator('[data-testid^=palette-row-]').evaluateAll((els) => els.map((e) => e.getAttribute('data-testid').replace('palette-row-', '')));
|
||||
check('3 palette shows 5-8 swatches', palHexes.length >= 5 && palHexes.length <= 8, `${palHexes.length}: ${palHexes.join(' ')}`);
|
||||
eq('3 palette auto-applied nothing (design unchanged)', (await rowData()).map((r) => r.hex), swatchesBeforePalette);
|
||||
await shot('shot-palette-from-image-modal.png');
|
||||
const addHex = palHexes.find((h) => !swatchesBeforePalette.includes(h));
|
||||
await page.locator(`[data-testid="palette-add-${addHex}"]`).click();
|
||||
await settle(250);
|
||||
eq('3 Add adds exactly that swatch', (await rowData()).map((r) => r.hex), [...swatchesBeforePalette, addHex]);
|
||||
await page.locator('[data-testid=palette-close]').click();
|
||||
// drop everything except Logo box
|
||||
while ((await rows().count()) > 1) { await rows().last().locator('[data-action=delete]').click(); await settle(120); }
|
||||
|
||||
// ================================================================= 4 Persistence
|
||||
await sm.locator('[data-field=new-hex]').fill('#ff6600');
|
||||
await sm.locator('[data-field=new-label]').fill('Brand orange');
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle(200);
|
||||
await rows().last().locator('[data-action=brand]').click();
|
||||
await sm.locator('[data-field=new-hex]').fill('#c8b08a');
|
||||
await sm.locator('[data-field=new-label]').fill('Sand');
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle(250);
|
||||
const before = await rowData();
|
||||
eq('4 three swatches before save (one brand)', before.map((r) => [r.label, r.hex, r.brand]), [['Logo box', '#15202c', false], ['Brand orange', '#ff6600', true], ['Sand', '#c8b08a', false]]);
|
||||
// a low-contrast site colour so the Site panel shows a note in the screenshot (defaults already do)
|
||||
await sm.scrollIntoViewIfNeeded();
|
||||
await shot('shot-site-design-saved-colours.png');
|
||||
await save();
|
||||
const stored = state.project.design?.swatches;
|
||||
check('4 stored project.json contains design.swatches', Array.isArray(stored) && stored.length === 3, JSON.stringify(stored));
|
||||
const orangeStored = (stored || []).find((s) => s.label === 'Brand orange');
|
||||
eq('4 stored brand swatch (hex, brand, slot)', orangeStored && [orangeStored.hex, orangeStored.brand, orangeStored.slot], ['#ff6600', true, 1]);
|
||||
const sandStored = (stored || []).find((s) => s.label === 'Sand');
|
||||
eq('4 stored plain swatch', sandStored && [sandStored.hex, sandStored.brand, sandStored.slot], ['#c8b08a', false, undefined]);
|
||||
await loadEditor();
|
||||
await openSite();
|
||||
const after = await rowData();
|
||||
eq('4 reload: panel restores labels/hex/brand', after.map((r) => [r.label, r.hex, r.brand]), before.map((r) => [r.label, r.hex, r.brand]));
|
||||
eq('4 reload: brand swatch shows the live badge, others not', after.map((r) => r.live), [false, true, false]);
|
||||
await selectTarget();
|
||||
const bgField = fieldOf('Background Color');
|
||||
const savedBtns = await bgField.locator('[data-swatch]').evaluateAll((bs) => bs.map((b) => [b.getAttribute('aria-label'), b.getAttribute('data-live')]));
|
||||
eq('4 reload: saved swatch buttons present in the Background colour field', savedBtns, [['Logo box #15202c', null], ['Brand orange #ff6600 (live brand colour, var(--wsb-brand-1))', 'true'], ['Sand #c8b08a', null]]);
|
||||
await bgField.scrollIntoViewIfNeeded();
|
||||
await shot('shot-colour-field-saved-swatches-and-pick-tools.png');
|
||||
|
||||
// ================================================================= 5 Brand live recolour: canvas == frontend export == backend
|
||||
await bgField.locator('[data-live=true]').click();
|
||||
await settle(400);
|
||||
eq('5 canvas: element paints the brand colour', toHex(await canvasBg(targetSel)), '#ff6600');
|
||||
check('5 element stores the live token (inline style)', /background-color:\s*var\(--wsb-brand-1\)/.test(await page.locator(targetSel).getAttribute('style') || ''), await page.locator(targetSel).getAttribute('style'));
|
||||
await openSite();
|
||||
const orangeRow = rows().nth(1);
|
||||
await orangeRow.locator('[data-field=hex]').fill('#00aa55');
|
||||
await settle(500);
|
||||
eq('5 canvas element recoloured to the new brand hex', toHex(await canvasBg(targetSel)), '#00aa55');
|
||||
await save();
|
||||
const nodes = pageNodes();
|
||||
eq('5 stored value on the node is the token, not the hex', nodes['target-box'].props.style.backgroundColor, 'var(--wsb-brand-1)');
|
||||
eq('5 stored brand swatch hex updated', state.project.design.swatches.find((s) => s.slot === 1).hex, '#00aa55');
|
||||
const canvasRgb = await canvasBg(targetSel);
|
||||
|
||||
const publishedA = head.renderPublished(state.project, 0);
|
||||
const pub = await ctx.newPage();
|
||||
const bgOf = async (html) => {
|
||||
await pub.setContent(html, { waitUntil: 'domcontentloaded' });
|
||||
return pub.evaluate(() => {
|
||||
const e = [...document.querySelectorAll('div')].find((d) => d.style.minHeight === '80px');
|
||||
return e ? getComputedStyle(e).backgroundColor : null;
|
||||
});
|
||||
};
|
||||
eq('5 published (frontend export): identical to the canvas colour', await bgOf(publishedA), canvasRgb);
|
||||
eq('5 published (frontend export) is the new brand colour', toHex(await bgOf(publishedA)), '#00aa55');
|
||||
if (haveBackend) {
|
||||
const publishedB = backendHtml(state.project, 0);
|
||||
eq('5 published (backend generateCompiledHTML): identical to the canvas colour', await bgOf(publishedB), canvasRgb);
|
||||
const da = rootDecl(publishedA), db = rootDecl(publishedB);
|
||||
check('5 heads :root brand declaration byte-identical (frontend vs backend)', da === db && da.includes(';--wsb-brand-1:#00aa55'), da === db ? da.slice(-60) : `\n a=${da}\n b=${db}`);
|
||||
} else console.log(`[${name}] SKIP backend leg: ${BACKEND_DIR} not found`);
|
||||
|
||||
// site WITHOUT brand colours: heads identical to the pre-feature baseline
|
||||
const plain = buildProject();
|
||||
plain.design.swatches = [{ id: 'x', label: 'Plain', hex: '#c8b08a', brand: false }];
|
||||
const noDesign = buildProject();
|
||||
const pa = head.renderPublished(noDesign, 0);
|
||||
check('5 no-brand site: published head has no "brand" substring', !/brand/i.test(pa.split('</head>')[0]));
|
||||
const pplain = head.renderPublished(plain, 0);
|
||||
eq('5 non-brand swatches change nothing in the published document', pplain, pa);
|
||||
if (haveBackend) eq('5 no-brand site: frontend :root == backend :root', rootDecl(pa), rootDecl(backendHtml(noDesign, 0)));
|
||||
if (baseExporter) {
|
||||
eq(`5 no-brand site: each later deliberate head change found exactly once (${HEAD_FOLDS.map((f) => f.why.split(':')[0]).join(', ')})`, foldsApplied(pa), HEAD_FOLDS.map(() => 1));
|
||||
eq(`5 no-brand site: published document identical to the pre-feature baseline (${BASE_COMMIT}, later head changes folded back)`, foldHead(pa) === baseExporter.renderPublished(noDesign, 0), true);
|
||||
} else console.log(`[${name}] SKIP baseline comparison`);
|
||||
await pub.close();
|
||||
|
||||
// ================================================================= 6 Cap + guarded delete
|
||||
await openSite();
|
||||
// brand slots so far: 1 (orange). Mark Logo box + Sand brand => 3. Add three more => 6.
|
||||
await rows().nth(0).locator('[data-action=brand]').click();
|
||||
await rows().nth(2).locator('[data-action=brand]').click();
|
||||
for (const [h, l] of [['#111111', 'Ink'], ['#222222', 'Slate'], ['#333333', 'Coal']]) {
|
||||
await sm.locator('[data-field=new-hex]').fill(h);
|
||||
await sm.locator('[data-field=new-label]').fill(l);
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle(150);
|
||||
await rows().last().locator('[data-action=brand]').click();
|
||||
await settle(100);
|
||||
}
|
||||
rd = await rowData();
|
||||
eq('6 six brand colours', rd.filter((r) => r.brand).length, 6);
|
||||
await sm.locator('[data-field=new-hex]').fill('#444444');
|
||||
await sm.locator('[data-field=new-label]').fill('Seventh');
|
||||
await sm.getByRole('button', { name: 'Add colour' }).click();
|
||||
await settle(150);
|
||||
await rows().last().locator('[data-action=brand]').click();
|
||||
await settle(200);
|
||||
eq('6 7th brand colour refused with the message', await sm.locator('[role=status]').innerText(), 'You can have up to 6 brand colours');
|
||||
eq('6 the 7th stays a plain colour', (await rowData()).filter((r) => r.brand).length, 6);
|
||||
|
||||
// deleting a referenced brand colour asks first (orange row = index 1, used by the target box)
|
||||
await rows().nth(1).locator('[data-action=delete]').click();
|
||||
await settle(250);
|
||||
const dlg = sm.locator('[role=alertdialog]');
|
||||
check('6 deleting a referenced brand colour asks for confirmation', (await dlg.count()) === 1);
|
||||
const dlgText = (await dlg.innerText()).replace(/\s+/g, ' ');
|
||||
check('6 confirmation names the swatch, the use count and the fixed colour', /Brand orange is used in 1 place/.test(dlgText) && /#00aa55/.test(dlgText), dlgText);
|
||||
eq('6 nothing deleted before confirming', (await rowData()).length, 7);
|
||||
eq('6 canvas colour unchanged before confirming', toHex(await canvasBg(targetSel)), '#00aa55');
|
||||
await dlg.getByRole('button', { name: 'Cancel' }).click();
|
||||
await settle(150);
|
||||
eq('6 Cancel keeps the swatch', (await rowData()).length, 7);
|
||||
await rows().nth(1).locator('[data-action=delete]').click();
|
||||
await settle(150);
|
||||
await dlg.getByRole('button', { name: 'Replace and delete' }).click();
|
||||
await settle(500);
|
||||
eq('6 swatch removed after confirming', (await rowData()).some((r) => r.label === 'Brand orange'), false);
|
||||
eq('6 canvas element keeps its colour', toHex(await canvasBg(targetSel)), '#00aa55');
|
||||
const styleAfter = await page.locator(targetSel).getAttribute('style');
|
||||
check('6 canvas element now holds the literal hex (no brand var)', /background-color:\s*(#00aa55|rgb\(0, 170, 85\))/i.test(styleAfter || '') && !/wsb-brand-1/.test(styleAfter || ''), styleAfter);
|
||||
await save();
|
||||
eq('6 saved node holds the literal hex', pageNodes()['target-box'].props.style.backgroundColor, '#00aa55');
|
||||
eq('6 saved swatches no longer contain Brand orange', state.project.design.swatches.some((s) => s.label === 'Brand orange'), false);
|
||||
eq('6 published page (frontend) still paints the colour', toHex(await (async () => { const p2 = await ctx.newPage(); await p2.setContent(head.renderPublished(state.project, 0)); const v = await p2.evaluate(() => getComputedStyle([...document.querySelectorAll('div')].find((d) => d.style.minHeight === '80px')).backgroundColor); await p2.close(); return v; })()), '#00aa55');
|
||||
|
||||
// ================================================================= 7 Contrast
|
||||
await page.locator(`${frame} p`).click();
|
||||
await settle(400);
|
||||
await page.click('#right-tab-element');
|
||||
await settle(300);
|
||||
const tf = fieldOf('Text Color');
|
||||
await tf.locator('input[type=text]').first().fill('#ffffff');
|
||||
await tf.locator('input[type=text]').first().press('Enter');
|
||||
await settle(500);
|
||||
const note = await page.locator('.panel-right .contrast-note--fail').allInnerTexts();
|
||||
check('7 white text on a light background shows the inline warning with the ratio', note.length >= 1 && /Low contrast 1\.00:1 \(needs 4\.5:1\)/.test(note[0]), JSON.stringify(note));
|
||||
await page.locator('.panel-right').evaluate((e) => e.scrollTo?.(0, 0));
|
||||
await shot('shot-text-field-inline-contrast.png');
|
||||
await openSite();
|
||||
const siteNotes = await page.locator('.panel-right .contrast-note--fail').allInnerTexts();
|
||||
check('7 Site Design shows the site-level contrast notes', siteNotes.some((t) => /Button text on primary: Low contrast 3\.68:1/.test(t)), JSON.stringify(siteNotes.map((t) => t.replace(/\s+/g, ' '))));
|
||||
await shot('shot-site-design-contrast-notes.png');
|
||||
|
||||
if (errors.length) { failed++; console.log(`[${name}] FAIL page errors:\n` + errors.join('\n')); }
|
||||
await browser.close();
|
||||
server.close();
|
||||
return failed;
|
||||
}
|
||||
|
||||
let total = 0;
|
||||
try {
|
||||
total += await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
total += await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
} finally {
|
||||
remote.close();
|
||||
fs.rmSync(buildDir, { recursive: true, force: true });
|
||||
fs.rmSync(baseDir, { recursive: true, force: true });
|
||||
}
|
||||
console.log(total ? `FAILED (${total})` : 'ALL PASS');
|
||||
process.exit(total ? 1 : 0);
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser check (headless Firefox AND Chromium) for the colour picker's pixel reading:
|
||||
* src/utils/image-sample.ts + palette-extract.ts. jsdom has no canvas, so this bundles them with
|
||||
* esbuild, serves a generated PNG from one origin (the page's own) and from a second port
|
||||
* (cross-origin), and asserts exact pixel colours, the extracted palette, and the cross-origin
|
||||
* failure message.
|
||||
*
|
||||
* node scripts/e2e-image-sample.mjs (CHROMIUM_PATH / FIREFOX_PATH override binaries)
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import http from 'node:http';
|
||||
import zlib from 'node:zlib';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const W = 1024, H = 512;
|
||||
const RED = [200, 30, 30], BLUE = [20, 20, 200], GREEN = [0, 160, 0];
|
||||
|
||||
// ---- tiny PNG encoder (RGBA, filter 0)
|
||||
function crc32(buf) {
|
||||
let c, crc = ~0;
|
||||
for (let n = 0; n < buf.length; n++) { c = (crc ^ buf[n]) & 255; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; crc = (crc >>> 8) ^ c; }
|
||||
return ~crc >>> 0;
|
||||
}
|
||||
function chunk(type, data) {
|
||||
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
|
||||
const td = Buffer.concat([Buffer.from(type), data]);
|
||||
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td));
|
||||
return Buffer.concat([len, td, crc]);
|
||||
}
|
||||
function png() {
|
||||
const raw = Buffer.alloc((W * 4 + 1) * H);
|
||||
for (let y = 0; y < H; y++) {
|
||||
raw[y * (W * 4 + 1)] = 0;
|
||||
for (let x = 0; x < W; x++) {
|
||||
const c = x < W / 2 ? RED : y < H / 2 ? BLUE : GREEN;
|
||||
raw.set([...c, 255], y * (W * 4 + 1) + 1 + x * 4);
|
||||
}
|
||||
}
|
||||
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 6;
|
||||
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
const PNG = png();
|
||||
|
||||
// ---- bundle the units under test
|
||||
const bundle = await esbuild({
|
||||
stdin: {
|
||||
contents: "export * from './src/utils/image-sample'; export * from './src/utils/palette-extract';",
|
||||
resolveDir: root, loader: 'ts',
|
||||
},
|
||||
bundle: true, write: false, format: 'iife', globalName: 'T', platform: 'browser', logLevel: 'error',
|
||||
});
|
||||
const BUNDLE = bundle.outputFiles[0].text;
|
||||
|
||||
// ---- servers: page + same-origin image on A; image only on B (cross-origin)
|
||||
const serve = (withPage) => http.createServer((req, res) => {
|
||||
if (withPage && req.url === '/page.html') { res.setHeader('content-type', 'text/html'); return res.end('<!doctype html><title>t</title><body></body>'); }
|
||||
if (withPage && req.url === '/bundle.js') { res.setHeader('content-type', 'text/javascript'); return res.end(BUNDLE); }
|
||||
if (req.url.startsWith('/img.png')) { res.setHeader('content-type', 'image/png'); return res.end(PNG); }
|
||||
res.statusCode = 404; res.end();
|
||||
});
|
||||
const A = serve(true), B = serve(false);
|
||||
await Promise.all([new Promise((r) => A.listen(0, '127.0.0.1', r)), new Promise((r) => B.listen(0, '127.0.0.1', r))]);
|
||||
const pa = A.address().port, pb = B.address().port;
|
||||
|
||||
let failures = 0;
|
||||
const check = (name, ok, extra = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${extra ? ' ' + extra : ''}`); if (!ok) failures++; };
|
||||
const hex = (c) => '#' + c.map((n) => n.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
const targets = [
|
||||
['chromium', chromium, process.env.CHROMIUM_PATH],
|
||||
['firefox', firefox, process.env.FIREFOX_PATH],
|
||||
].filter(([n]) => !process.env.ONLY || process.env.ONLY === n);
|
||||
|
||||
for (const [name, type, exe] of targets) {
|
||||
console.log(`--- ${name}`);
|
||||
const browser = await type.launch({ headless: true, ...(exe ? { executablePath: exe } : {}) });
|
||||
const page = await browser.newPage();
|
||||
await page.goto(`http://127.0.0.1:${pa}/page.html`);
|
||||
await page.addScriptTag({ url: `/bundle.js` });
|
||||
const r = await page.evaluate(async ({ pa, pb }) => {
|
||||
const out = {};
|
||||
const same = await T.loadImageForSampling(`/img.png`);
|
||||
out.sameOk = same.ok;
|
||||
if (same.ok) {
|
||||
out.size = [same.width, same.height];
|
||||
const d = same.imageData;
|
||||
out.red = T.sampleAt(d, 10, 10);
|
||||
out.blue = T.sampleAt(d, 400, 10);
|
||||
out.green = T.sampleAt(d, 400, 200);
|
||||
out.palette = T.extractPalette(d.data);
|
||||
const c = document.createElement('canvas');
|
||||
same.draw(c);
|
||||
out.drawn = [c.width, c.height];
|
||||
} else out.sameMsg = same.message;
|
||||
const abs = await T.loadImageForSampling(`http://127.0.0.1:${pa}/img.png`);
|
||||
out.absSameOk = abs.ok;
|
||||
const cross = await T.loadImageForSampling(`http://127.0.0.1:${pb}/img.png`);
|
||||
out.cross = cross;
|
||||
const bad = await T.loadImageForSampling(`/missing.png`);
|
||||
out.bad = bad;
|
||||
return out;
|
||||
}, { pa, pb });
|
||||
check('same-origin image loads', r.sameOk, r.sameMsg || '');
|
||||
check('downscaled to 512x256', JSON.stringify(r.size) === '[512,256]', JSON.stringify(r.size));
|
||||
check('draw() sizes canvas', JSON.stringify(r.drawn) === '[512,256]');
|
||||
check('pixel red exact', r.red === hex(RED), r.red);
|
||||
check('pixel blue exact', r.blue === hex(BLUE), r.blue);
|
||||
check('pixel green exact', r.green === hex(GREEN), r.green);
|
||||
check('palette = red, blue, green in population order (red 50%, blue/green 25%)',
|
||||
r.palette[0] === hex(RED) && r.palette.length === 3 && r.palette.includes(hex(BLUE)) && r.palette.includes(hex(GREEN)), JSON.stringify(r.palette));
|
||||
check('absolute same-origin URL loads', r.absSameOk);
|
||||
check('cross-origin refused', r.cross.ok === false && r.cross.reason === 'cross-origin');
|
||||
check('cross-origin message exact', r.cross.message === 'That image comes from another website, so the browser will not let the builder read its colours. Upload it to this site first, then pick from the uploaded copy.');
|
||||
check('missing image -> error', r.bad.ok === false && r.bad.reason === 'error', r.bad.message);
|
||||
await browser.close();
|
||||
}
|
||||
A.close(); B.close();
|
||||
console.log(failures ? `\n${failures} FAILED` : '\nall passed');
|
||||
process.exit(failures ? 1 : 0);
|
||||
@@ -0,0 +1,51 @@
|
||||
// Bundled (browser IIFE) by scripts/e2e-legacy-grid.mjs. Builds published documents from LEGACY stored HTML
|
||||
// (pages saved before the data-wsb-grid hook existed) wrapped in the REAL Preview/publish head
|
||||
// (exportComposedPreviewHtml: header + page + footer, as WHP handlePublish composes them; the head is byte-identical
|
||||
// to WHP generateCompiledHTML, pinned on both sides by the head-parity tests).
|
||||
import { exportBodyHtml, exportComposedPreviewHtml, RESPONSIVE_CSS_MINIFIED } from '../src/utils/html-export';
|
||||
import { componentResolver } from '../src/components/resolver';
|
||||
import olsHeader from '../tests/fixtures/legacy-grid/ols.header.html';
|
||||
import olsIndex from '../tests/fixtures/legacy-grid/ols.index.html';
|
||||
import olsFooter from '../tests/fixtures/legacy-grid/ols.footer.html';
|
||||
import olsDesign from '../tests/fixtures/legacy-grid/ols.design.json';
|
||||
|
||||
type N = Record<string, any>;
|
||||
const EMPTY = JSON.stringify({ ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: { tag: 'div', style: {} }, displayName: 'Container', custom: {}, hidden: false, nodes: [], linkedNodes: {} } });
|
||||
const defaults = (type: string): Record<string, unknown> => {
|
||||
const c = (componentResolver as any)[type];
|
||||
return c?.craft?.props ? JSON.parse(JSON.stringify(c.craft.props)) : {};
|
||||
};
|
||||
const node = (type: string, props: Record<string, unknown>, extra: N = {}) => ({
|
||||
type: { resolvedName: type }, isCanvas: type === 'Container', props: { ...defaults(type), ...props }, displayName: type,
|
||||
custom: {}, hidden: false, nodes: [], linkedNodes: {}, ...extra,
|
||||
});
|
||||
const stripHook = (html: string) => html.replace(/ data-wsb-grid(="")?/g, '');
|
||||
const doc = (body: string, title: string) => exportComposedPreviewHtml(EMPTY, body, { title, design: olsDesign as any });
|
||||
|
||||
/** Every card-grid emitter in its stored (pre-hook) form, Galleries whose gap collides with a card-grid
|
||||
* signature, and an unwrapped customer grid (legacy HtmlBlock content has no data-wsb-html wrapper). */
|
||||
function synthetic(): string {
|
||||
const nodes: N = {};
|
||||
const kids: string[] = [];
|
||||
const add = (id: string, type: string, props: Record<string, unknown> = {}) => { nodes[id] = node(type, props, { parent: 'ROOT' }); kids.push(id); };
|
||||
add('features', 'FeaturesGrid');
|
||||
add('t2', 'Testimonials', { columns: 2 });
|
||||
add('t3', 'Testimonials');
|
||||
add('t4', 'Testimonials', { columns: 4 });
|
||||
add('counter', 'NumberCounter', { columns: 4 });
|
||||
add('gal', 'Gallery');
|
||||
add('gal32', 'Gallery', { columns: 3, gap: '32px', lightbox: true });
|
||||
add('gal24', 'Gallery', { columns: 4, gap: '24px' });
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, { nodes: kids });
|
||||
const body = stripHook(exportBodyHtml(JSON.stringify(nodes)).html);
|
||||
const customer = '<div id="customer" style="padding:16px"><div style="display:grid;grid-template-columns:repeat(3,1fr);gap:32px"><div>One</div><div>Two</div><div>Three</div></div></div>';
|
||||
return olsHeader + '\n' + body + customer + '\n' + olsFooter;
|
||||
}
|
||||
|
||||
(window as any).wsbLegacyGridDocs = (): Record<string, string> => ({
|
||||
ols: doc(olsHeader + '\n' + olsIndex + '\n' + olsFooter, 'Home'),
|
||||
// The same page as a re-save in 2026.11.5 would store it (hook added): phones must look identical.
|
||||
olsResaved: doc(olsHeader + '\n' + olsIndex.replace('<div style="max-width:1100px;margin:0 auto;display:grid;', '<div data-wsb-grid style="max-width:1100px;margin:0 auto;display:grid;') + '\n' + olsFooter, 'Home'),
|
||||
synthetic: doc(synthetic(), 'Legacy grids'),
|
||||
});
|
||||
(window as any).wsbResponsiveCss = RESPONSIVE_CSS_MINIFIED;
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Legacy card grids: real-browser (Chromium AND Firefox, headless) proof that the published head stacks card grids
|
||||
* stored BEFORE the data-wsb-grid hook existed (no re-save needed), and changes nothing else.
|
||||
*
|
||||
* npm run test:browser:legacy-grid
|
||||
*
|
||||
* Documents (scripts/e2e-legacy-grid-entry.ts, real exporter head):
|
||||
* ols - the OLS Digital home page exactly as stored on the site (tests/fixtures/legacy-grid: header +
|
||||
* page + footer, no data-wsb-* attributes; its FeaturesGrid is the legacy inline repeat(3,1fr))
|
||||
* olsResaved - the same page with the hook added, i.e. what a re-save stores today
|
||||
* synthetic - every card-grid emitter in its stored form (FeaturesGrid, Testimonials 2/3/4, NumberCounter 4),
|
||||
* Galleries whose gap collides with a card-grid signature (3 cols gap 32px + lightbox, 4 cols gap
|
||||
* 24px) plus a default one, and an unwrapped customer grid (legacy HtmlBlock content)
|
||||
* measured at 360 / 390 / 768 / 1280.
|
||||
*
|
||||
* Asserted (every doc, every width unless noted):
|
||||
* - no horizontal overflow: body.scrollWidth <= viewport and the right edge of every visible element box and text
|
||||
* line <= viewport (html,body{overflow-x:clip} hides overflow from documentElement.scrollWidth), and the page
|
||||
* cannot be scrolled sideways
|
||||
* - <=767px: every legacy card grid is one card per row; every Gallery keeps more than one column; the customer
|
||||
* grid keeps its 3 columns. Discriminating signal: with the legacy rules removed from the head, the same
|
||||
* legacy card grids are back to several per row (so the rules, not something else, stack them)
|
||||
* - <=767px: the legacy OLS page is pixel-identical to its re-saved (hooked) form
|
||||
* - 768 and 1280: every element box AND the full-page screenshot are identical with vs without the legacy rules
|
||||
*
|
||||
* Env: CHROMIUM_PATH / FIREFOX_PATH (when the Playwright-pinned builds are not installed), LEGACY_ONLY=chromium|firefox.
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-legacy-grid-entry.ts')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', jsx: 'automatic', logLevel: 'error',
|
||||
loader: { '.html': 'text' },
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
const WIDTHS = [360, 390, 768, 1280];
|
||||
const MOBILE_MAX = 767;
|
||||
|
||||
/** Runs in the page. */
|
||||
function measure() {
|
||||
const vw = window.innerWidth;
|
||||
const skip = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
|
||||
const contained = (el) => {
|
||||
for (let a = el.parentElement; a && a !== document.body && a !== document.documentElement; a = a.parentElement) {
|
||||
if (getComputedStyle(a).overflowX !== 'visible' && a.getBoundingClientRect().right <= vw + 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const label = (el) => `${el.tagName.toLowerCase()} "${(el.textContent || '').trim().slice(0, 24)}"`;
|
||||
let maxRight = 0; let worst = '';
|
||||
const bump = (right, el) => { if (right > maxRight) { maxRight = right; worst = label(el); } };
|
||||
for (const el of document.body.querySelectorAll('*')) {
|
||||
if (skip.has(el.tagName)) continue;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!(r.width || r.height) || getComputedStyle(el).visibility === 'hidden' || contained(el)) continue;
|
||||
bump(r.right, el);
|
||||
}
|
||||
const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||
for (let n = tw.nextNode(); n; n = tw.nextNode()) {
|
||||
const el = n.parentElement;
|
||||
if (!el || skip.has(el.tagName) || !n.textContent.trim() || contained(n)) continue;
|
||||
const range = document.createRange(); range.selectNodeContents(n);
|
||||
for (const r of range.getClientRects()) if (r.width) bump(r.right, el);
|
||||
}
|
||||
const grids = [...document.querySelectorAll('div')].filter((d) => getComputedStyle(d).display === 'grid').map((g) => {
|
||||
const kids = [...g.children].filter((k) => !skip.has(k.tagName) && k.getBoundingClientRect().height > 0);
|
||||
const firstTop = kids.length ? Math.round(kids[0].getBoundingClientRect().top) : 0;
|
||||
const kind = g.closest('#customer') ? 'customer'
|
||||
: g.querySelector(':scope > * > img[style^="width:100%;height:200px;object-fit:cover"]') ? 'gallery' : 'card';
|
||||
return { kind, hook: g.hasAttribute('data-wsb-grid'), n: kids.length, perRow: kids.filter((k) => Math.round(k.getBoundingClientRect().top) === firstTop).length };
|
||||
});
|
||||
return { vw, docSW: document.documentElement.scrollWidth, bodySW: document.body.scrollWidth, maxRight: Math.round(maxRight * 10) / 10, worst, grids };
|
||||
}
|
||||
|
||||
function sidewaysScroll() {
|
||||
const y = window.scrollY;
|
||||
window.scrollTo(5000, y);
|
||||
const x = window.scrollX;
|
||||
window.scrollTo(0, y);
|
||||
return x;
|
||||
}
|
||||
|
||||
function boxes() {
|
||||
return [...document.body.querySelectorAll('*')]
|
||||
.filter((e) => !['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(e.tagName))
|
||||
.map((e) => { const r = e.getBoundingClientRect(); return [e.tagName, ...[r.x, r.y, r.width, r.height].map((v) => Math.round(v * 10) / 10)].join(','); });
|
||||
}
|
||||
|
||||
let fail = 0;
|
||||
const ok = (c, m) => { if (!c) { fail++; console.log(' FAIL', m); } };
|
||||
const summary = [];
|
||||
|
||||
async function open(browser, html, w) {
|
||||
const page = await browser.newPage({ viewport: { width: w, height: 900 } });
|
||||
await page.route(/^https?:/, (r) => r.abort()); // deterministic: no fonts/CDN/images racing the layout
|
||||
await page.setContent(html, { waitUntil: 'load' });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await page.waitForTimeout(50);
|
||||
return page;
|
||||
}
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const gen = await browser.newPage();
|
||||
await gen.setContent('<!doctype html><html><body></body></html>');
|
||||
await gen.addScriptTag({ content: js });
|
||||
const docs = await gen.evaluate(() => window.wsbLegacyGridDocs());
|
||||
const css = await gen.evaluate(() => window.wsbResponsiveCss);
|
||||
await gen.close();
|
||||
// The legacy rules = everything between the [data-wsb-grid] rule and body{overflow-wrap...} in the head CSS.
|
||||
const HOOK = '[data-wsb-grid]{grid-template-columns:minmax(0,1fr)!important}';
|
||||
const legacy = css.slice(css.indexOf(HOOK) + HOOK.length, css.indexOf('body{overflow-wrap'));
|
||||
ok(legacy.includes('[style^=') && legacy.includes(':has('), `[${name}] could not isolate the legacy rules from the head CSS: ${legacy}`);
|
||||
const bodyOf = (h) => h.slice(h.indexOf('<body'));
|
||||
ok(bodyOf(docs.olsResaved).includes('data-wsb-grid') && !bodyOf(docs.ols).includes('data-wsb'), `[${name}] fixture: ols must be hook-free and olsResaved hooked`);
|
||||
const without = Object.fromEntries(Object.entries(docs).map(([k, v]) => {
|
||||
ok(v.split(legacy).length === 2, `[${name}] ${k}: the head does not carry the legacy rules exactly once`);
|
||||
return [k, v.replace(legacy, '')];
|
||||
}));
|
||||
|
||||
for (const [docName, html] of Object.entries(docs)) {
|
||||
for (const w of WIDTHS) {
|
||||
const tag = `[${name} ${w}] ${docName}`;
|
||||
const mobile = w <= MOBILE_MAX;
|
||||
const page = await open(browser, html, w);
|
||||
const m = await page.evaluate(measure);
|
||||
const sx = await page.evaluate(sidewaysScroll);
|
||||
ok(sx === 0, `${tag}: the page scrolls sideways (scrollX=${sx})`);
|
||||
ok(m.bodySW <= w, `${tag}: body.scrollWidth ${m.bodySW} > ${w}`);
|
||||
ok(m.maxRight <= w + 0.5, `${tag}: content reaches x=${m.maxRight}: ${m.worst}`);
|
||||
|
||||
const base = await open(browser, without[docName], w);
|
||||
const mb = await base.evaluate(measure);
|
||||
const fmt = (g) => g.map((x) => `${x.kind[0]}${x.perRow}/${x.n}`).join(',');
|
||||
summary.push(`${name.padEnd(8)} ${String(w).padEnd(4)} ${docName.padEnd(10)} bodySW=${m.bodySW} maxRight=${m.maxRight} grids=${fmt(m.grids)} | without rules: bodySW=${mb.bodySW} maxRight=${mb.maxRight}${mb.maxRight > w + 0.5 ? ' (' + mb.worst + ')' : ''} grids=${fmt(mb.grids)}`);
|
||||
|
||||
const cards = m.grids.filter((g) => g.kind === 'card' && g.n > 1);
|
||||
if (docName !== 'olsResaved') ok(cards.length > 0, `${tag}: no legacy card grid found (fixture broken)`);
|
||||
if (mobile) {
|
||||
for (const g of cards) ok(g.perRow === 1, `${tag}: a legacy card grid keeps ${g.perRow} per row on a phone`);
|
||||
for (const g of m.grids.filter((x) => x.kind === 'gallery')) ok(g.perRow > 1, `${tag}: a Gallery lost its columns (${g.perRow} per row)`);
|
||||
for (const g of m.grids.filter((x) => x.kind === 'customer')) ok(g.perRow === 3, `${tag}: the customer grid was reflowed (${g.perRow} per row)`);
|
||||
if (docName !== 'olsResaved') {
|
||||
const legacyCards = mb.grids.filter((g) => g.kind === 'card' && g.n > 1 && !g.hook);
|
||||
ok(legacyCards.length > 0 && legacyCards.every((g) => g.perRow > 1), `${tag}: without the legacy rules the card grids were expected to keep their columns (${fmt(legacyCards)})`);
|
||||
}
|
||||
} else {
|
||||
for (const g of cards) ok(g.perRow > 1, `${tag}: a card grid lost its columns at ${w} (${g.perRow} per row)`);
|
||||
const [b1, b2] = [await page.evaluate(boxes), await base.evaluate(boxes)];
|
||||
const diffs = b1.length !== b2.length ? Infinity : b1.filter((b, i) => b !== b2[i]).length;
|
||||
ok(diffs === 0, `${tag}: ${diffs} element boxes differ with vs without the legacy rules`);
|
||||
const [s1, s2] = [await page.screenshot({ fullPage: true }), await base.screenshot({ fullPage: true })];
|
||||
ok(s1.equals(s2), `${tag}: full-page pixels differ with vs without the legacy rules`);
|
||||
}
|
||||
if (mobile && docName === 'ols') {
|
||||
const resaved = await open(browser, docs.olsResaved, w);
|
||||
const [s1, s2] = [await page.screenshot({ fullPage: true }), await resaved.screenshot({ fullPage: true })];
|
||||
ok(s1.equals(s2), `${tag}: the legacy page differs from its re-saved (hooked) form on a phone`);
|
||||
await resaved.close();
|
||||
}
|
||||
await base.close();
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const only = process.env.LEGACY_ONLY;
|
||||
if (!only || only === 'chromium') await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (!only || only === 'firefox') await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
console.log('\n' + summary.join('\n'));
|
||||
console.log(fail ? `\n${fail} FAILED` : '\nall passed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,126 @@
|
||||
// Bundled (browser IIFE) by scripts/e2e-mobile-guard.mjs. Builds representative published documents
|
||||
// with the REAL exporter (exportBodyHtml + exportComposedPreviewHtml, the Preview/publish path) so the
|
||||
// real-browser suite measures exactly what customers get. HtmlBlock sanitising needs a DOM, which is
|
||||
// why this runs inside the browser rather than in node.
|
||||
// Uses only exports that exist before and after the mobile-guard change, so the SAME harness can record
|
||||
// a desktop baseline on the base commit (MOBILE_GUARD_RECORD).
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
import { componentResolver } from '../src/components/resolver';
|
||||
|
||||
type N = Record<string, any>;
|
||||
const defaults = (type: string): Record<string, unknown> => {
|
||||
const c = (componentResolver as any)[type];
|
||||
return c?.craft?.props ? JSON.parse(JSON.stringify(c.craft.props)) : {};
|
||||
};
|
||||
const node = (type: string, props: Record<string, unknown>, nodes: string[] = [], extra: N = {}) => ({
|
||||
type: { resolvedName: type }, isCanvas: type === 'Container', props: { ...defaults(type), ...props }, displayName: type,
|
||||
custom: {}, hidden: false, nodes, linkedNodes: {}, ...extra,
|
||||
});
|
||||
const LONG = 'Honest prices, straight answers and work that is finished when we say it will be, every time.';
|
||||
|
||||
function columns(nodes: N, id: string, split: string, n: number) {
|
||||
const linked: Record<string, string> = {};
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = `${id}-c${i}`; const t = `${id}-t${i}`;
|
||||
nodes[c] = node('Container', { tag: 'div', style: { padding: '8px' } }, [t], { parent: id });
|
||||
nodes[t] = node('TextBlock', { text: `${LONG} (${id} col ${i + 1})`, style: { fontSize: '16px' } }, [], { parent: c });
|
||||
linked[`col-${i}`] = c;
|
||||
}
|
||||
nodes[id] = node('ColumnLayout', { columns: n, gap: '16px', split }, [], { parent: 'ROOT', linkedNodes: linked });
|
||||
}
|
||||
|
||||
const NAV_LINKS = ['Home', 'About us', 'Services', 'Our work', 'Pricing', 'Testimonials', 'Blog', 'Contact us'].map((text, i, a) => ({
|
||||
text, href: '#' + text.toLowerCase().replace(/\s/g, '-'), ...(i === a.length - 1 ? { isCta: true } : {}),
|
||||
}));
|
||||
|
||||
/** showMobileMenu false = every Navbar saved before the hamburger existed (links must wrap);
|
||||
* true = the default for a newly dropped Navbar (hamburger). */
|
||||
function header(showMobileMenu: boolean): string {
|
||||
const nodes: N = { nav: node('Navbar', { logoText: 'Acme Plumbing & Heating Ltd', links: NAV_LINKS, padding: '16px 24px', showMobileMenu }, [], { parent: 'ROOT' }) };
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, ['nav']);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
/** First-party components only: every one of them must fit every width. */
|
||||
export function componentsState(): string {
|
||||
const nodes: N = {};
|
||||
const kids: string[] = [];
|
||||
const add = (id: string, type: string, props: Record<string, unknown> = {}) => { nodes[id] = node(type, props, [], { parent: 'ROOT' }); kids.push(id); };
|
||||
add('hero', 'HeroSimple', { title: 'Plumbing and heating you can actually rely on', subtitle: LONG });
|
||||
for (const [id, split, n] of [['c2', '50-50', 2], ['c3', '33-33-33', 3], ['c4', '25-25-25-25', 4], ['side', '30-70', 2]] as const) { columns(nodes, id, split, n); kids.push(id); }
|
||||
add('features', 'FeaturesGrid');
|
||||
add('testimonials', 'Testimonials');
|
||||
add('counter', 'NumberCounter');
|
||||
add('gallery', 'Gallery');
|
||||
add('pricing', 'PricingTable');
|
||||
add('reviews', 'ReviewsStrip');
|
||||
add('img', 'ImageBlock', { src: 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="600"><rect width="1600" height="600" fill="#888"/></svg>') });
|
||||
add('longword', 'TextBlock', { text: 'Supercalifragilisticexpialidociouslyunbreakablewordthatgoesonandonandonforeverandever and https://example.com/a/really/long/path/that/never/breaks/because/it/has/no/spaces/at/all?query=string&more=yes' });
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, kids);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
/** Customer raw HTML that fits a phone with the net: media shrink, <pre> scrolls on its own, long words wrap,
|
||||
* a full-width table keeps spanning the screen. */
|
||||
export const HTML_FITS: Record<string, string> = {
|
||||
hbIframe: '<iframe width="800" height="450" src="about:blank" title="video"></iframe>',
|
||||
hbImg: '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" width="1200" height="400" alt="">',
|
||||
hbTableFull: '<table id="full-table" style="width:100%;border-collapse:collapse" border="1"><tr><th>Plan</th><th>Price</th></tr><tr><td>Basic</td><td>$5</td></tr></table>',
|
||||
hbPre: '<pre>const reallyLongLine = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";</pre>',
|
||||
hbUrl: '<p>See https://example.com/a/really/long/path/that/never/breaks/because/it/has/no/spaces/at/all/ok</p>',
|
||||
// Deliberate horizontal scroller: must STILL scroll (the net must not flatten or clip it).
|
||||
hbScrollTable: '<div id="intentional-scroll" style="overflow-x:auto"><table style="width:1000px"><tr><td>a</td><td>b</td><td>c</td></tr></table></div>',
|
||||
// Phone probes: none of these may be clipped, unstuck or merged by the net.
|
||||
hbSticky: '<div id="sticky-box" style="height:1200px;background:#f5f5f5"><div id="sticky-probe" style="position:sticky;top:0;background:#ffeb3b;padding:8px">Sticky bar</div></div>',
|
||||
hbDropdown: '<div style="position:relative"><button type="button">Menu</button><ul id="dropdown-probe" style="position:absolute;top:100%;left:0;z-index:10;list-style:none;margin:0;padding:8px;background:#fff;box-shadow:0 4px 12px #0004"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li id="dropdown-last">Last item</li></ul></div>',
|
||||
};
|
||||
|
||||
/** Customer raw HTML wider than a phone by design (fixed widths / px grids): clipped as before, never a sideways page. */
|
||||
export const HTML_WIDE: Record<string, string> = {
|
||||
hbFixed: '<div style="width:1100px;background:#eee;padding:20px">A fixed 1100px banner</div>',
|
||||
hbGridPx: '<div style="display:grid;grid-template-columns:repeat(3,300px);gap:20px"><div style="padding:16px;border:1px solid #ccc">One</div><div style="padding:16px;border:1px solid #ccc">Two</div><div style="padding:16px;border:1px solid #ccc">Three</div></div>',
|
||||
hbGridFr: '<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:32px"><div style="padding:24px"><h3>Multi-Brand Portfolio</h3></div><div style="padding:24px"><h3>Hosting</h3></div><div style="padding:24px"><h3>StreamerTools</h3></div><div style="padding:24px"><h3>Consultancy</h3></div></div>',
|
||||
hbStyleFlex: '<style>.cards{display:flex;gap:16px}.card{flex:0 0 360px;padding:16px;border:1px solid #ccc}</style><div class="cards"><div class="card">A</div><div class="card">B</div><div class="card">C</div></div>',
|
||||
hbMinWidth: '<div style="min-width:900px">min-width 900px content</div>',
|
||||
// Tables are deliberately left alone by the net (scrolling one would shrink full-width tables): clipped as before.
|
||||
hbTableBare: '<table id="bare-table"><tr>' + Array.from({ length: 10 }, (_, i) => `<td>Column_heading_${i}</td>`).join('') + '</tr></table>',
|
||||
};
|
||||
|
||||
function htmlState(blocks: Record<string, string>, probes: boolean): string {
|
||||
const nodes: N = {};
|
||||
const kids: string[] = [];
|
||||
nodes.intro = node('TextBlock', { text: 'Before the custom HTML' }, [], { parent: 'ROOT' }); kids.push('intro');
|
||||
for (const [id, code] of Object.entries(blocks)) { nodes[id] = node('HtmlBlock', { code }, [], { parent: 'ROOT' }); kids.push(id); }
|
||||
if (probes) {
|
||||
// A multi-root HtmlBlock that is a direct flex / grid item: its roots must stay separate items/cells, at every
|
||||
// width (and a boxed wrapper would also move the margin and inline probes at desktop).
|
||||
nodes.flexRow = node('Container', { tag: 'div', style: { display: 'flex', flexDirection: 'row', gap: '12px' } }, ['hbRoots', 'rowText'], { parent: 'ROOT' });
|
||||
nodes.hbRoots = node('HtmlBlock', { code: '<div class="root-probe" style="flex:1;background:#eef">root one</div><div class="root-probe" style="flex:2;background:#fee">root two</div>' }, [], { parent: 'flexRow' });
|
||||
nodes.rowText = node('TextBlock', { text: 'flex sibling' }, [], { parent: 'flexRow' });
|
||||
kids.push('flexRow');
|
||||
nodes.gridBox = node('Container', { tag: 'div', style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' } }, ['hbCells'], { parent: 'ROOT' });
|
||||
nodes.hbCells = node('HtmlBlock', { code: '<div class="cell-probe" style="background:#efe">cell one</div><div class="cell-probe" style="background:#fef">cell two</div>' }, [], { parent: 'gridBox' });
|
||||
kids.push('gridBox');
|
||||
nodes.marginText = node('TextBlock', { text: 'margin neighbour', style: { marginBottom: '30px' } }, [], { parent: 'ROOT' }); kids.push('marginText');
|
||||
nodes.hbMargins = node('HtmlBlock', { code: '<h2 style="margin:40px 0">Collapsing margins</h2>' }, [], { parent: 'ROOT' }); kids.push('hbMargins');
|
||||
nodes.inlineRun = node('Container', { tag: 'div', style: {} }, ['hbInline', 'inlineBtn'], { parent: 'ROOT' });
|
||||
nodes.hbInline = node('HtmlBlock', { code: '<span>inline custom</span>' }, [], { parent: 'inlineRun' });
|
||||
nodes.inlineBtn = node('ButtonLink', { text: 'inline button' }, [], { parent: 'inlineRun' });
|
||||
kids.push('inlineRun');
|
||||
}
|
||||
nodes.outro = node('TextBlock', { text: 'After the custom HTML' }, [], { parent: 'ROOT' }); kids.push('outro');
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: { padding: '20px' } }, kids);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
function compose(state: string, title: string, showMobileMenu: boolean): string {
|
||||
const hdr = exportBodyHtml(header(showMobileMenu), 'header').html;
|
||||
const body = exportBodyHtml(state).html;
|
||||
return exportComposedPreviewHtml(state, hdr + body, { title, includeFonts: false });
|
||||
}
|
||||
|
||||
(window as any).wsbMobileGuardDocs = (): Record<string, string> => ({
|
||||
components: compose(componentsState(), 'Components', false),
|
||||
htmlblocks: compose(htmlState(HTML_FITS, true), 'Custom HTML', true),
|
||||
htmlwide: compose(htmlState(HTML_WIDE, false), 'Wide custom HTML', true),
|
||||
});
|
||||
@@ -0,0 +1,283 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Mobile guard: real-browser (Chromium AND Firefox, headless) regression suite for published pages.
|
||||
* jsdom has no layout engine, so none of this can be asserted in vitest.
|
||||
*
|
||||
* npm run test:browser:mobile-guard
|
||||
*
|
||||
* Builds three representative documents with the REAL exporter (scripts/e2e-mobile-guard-entry.ts):
|
||||
* components - Navbar with 8 links, hero, ColumnLayout 2/3/4/30-70, FeaturesGrid, Testimonials,
|
||||
* NumberCounter, Gallery, PricingTable, ReviewsStrip, a 1600px image, long word + URL
|
||||
* htmlblocks - customer HtmlBlocks that fit a phone with the net (iframe, img, width:100% table, pre, URL), an
|
||||
* intentional overflow-x:auto table, and probes: sticky bar, absolutely positioned dropdown,
|
||||
* multi-root blocks as direct flex items / grid cells, collapsing margins, an inline run
|
||||
* htmlwide - customer HtmlBlocks wider than a phone (fixed width, px grid, 4x1fr grid, <style> flex cards,
|
||||
* min-width, a 10-column bare table): clipped as before, the publish warning is their guard
|
||||
* and measures them at 360 / 390 / 768 / 1280.
|
||||
*
|
||||
* Asserted:
|
||||
* - documentElement.scrollWidth <= viewport and the page cannot be scrolled sideways (every doc, every width)
|
||||
* - body.scrollWidth <= viewport and the right edge of every visible element box and text line <= viewport,
|
||||
* unless it sits inside a scroll/clip container that itself fits (reachable / intentionally clipped):
|
||||
* components at every width, htmlblocks at <=767px (the HtmlBlock net is phone-only). htmlwide: the wide
|
||||
* content is still clipped (not reflowed) at <=767px.
|
||||
* - ColumnLayout rows stack (one column per row) at <=767px; component card grids are one column at
|
||||
* <=767px and keep more than one column at 768 (tablet).
|
||||
* - the Navbar fits the viewport and wraps its links onto more than one row at 360/390.
|
||||
* - the intentional overflow-x:auto table still scrolls; a width:100% table still spans the screen; a wide
|
||||
* table (htmlwide) is clipped and never makes the page scroll sideways.
|
||||
* - htmlblocks probes, every width: the HtmlBlock wrapper is display:contents, sticky still sticks, the
|
||||
* dropdown is visible on top, multi-root blocks stay separate flex items / grid cells.
|
||||
* - desktop (1280) is unchanged by the mobile hooks: every element box AND the full-page screenshot are
|
||||
* identical after removing them in the page (unwrap [data-wsb-html], drop data-wsb-grid).
|
||||
* Optional cross-commit proof of the same thing:
|
||||
* MOBILE_GUARD_RECORD=<file> write the 1280 boxes (run this on the base commit)
|
||||
* MOBILE_GUARD_BASELINE=<file> assert 1280 boxes equal that recording
|
||||
*
|
||||
* Env: CHROMIUM_PATH / FIREFOX_PATH (when the Playwright-pinned builds are not installed),
|
||||
* MOBILE_ONLY=chromium|firefox.
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-mobile-guard-entry.ts')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
const WIDTHS = [360, 390, 768, 1280];
|
||||
const MOBILE_MAX = 767;
|
||||
|
||||
/** Runs in the page. */
|
||||
function measure() {
|
||||
const vw = window.innerWidth;
|
||||
const skip = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
|
||||
// An ancestor (below body) that scrolls or clips horizontally and itself fits the viewport keeps its
|
||||
// content reachable (auto/scroll) or deliberately hidden (hidden/clip): not page overflow.
|
||||
const contained = (el) => {
|
||||
for (let a = el.parentElement; a && a !== document.body && a !== document.documentElement; a = a.parentElement) {
|
||||
if (getComputedStyle(a).overflowX !== 'visible' && a.getBoundingClientRect().right <= vw + 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const label = (el) => {
|
||||
const host = el.closest('[id]');
|
||||
return `${el.tagName.toLowerCase()}${host ? ' in #' + host.id : ''} "${(el.textContent || '').trim().slice(0, 24)}"`;
|
||||
};
|
||||
let maxRight = 0; let worst = '';
|
||||
const bump = (right, el) => { if (right > maxRight) { maxRight = right; worst = label(el); } };
|
||||
for (const el of document.body.querySelectorAll('*')) {
|
||||
if (skip.has(el.tagName)) continue;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!(r.width || r.height) || getComputedStyle(el).visibility === 'hidden' || contained(el)) continue;
|
||||
bump(r.right, el);
|
||||
}
|
||||
const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||
for (let n = tw.nextNode(); n; n = tw.nextNode()) {
|
||||
const el = n.parentElement;
|
||||
if (!el || skip.has(el.tagName) || !n.textContent.trim() || contained(n)) continue;
|
||||
const range = document.createRange(); range.selectNodeContents(n);
|
||||
for (const r of range.getClientRects()) if (r.width) bump(r.right, el);
|
||||
}
|
||||
// Distinct rows among boxes: a box starts a new row when its top is below the previous row's bottom.
|
||||
const rowsOf = (kids) => {
|
||||
const rs = kids.map((k) => k.getBoundingClientRect()).filter((r) => r.height > 0).sort((a, b) => a.top - b.top);
|
||||
let rows = 0; let bottom = -Infinity;
|
||||
for (const r of rs) { if (r.top >= bottom - 1) { rows++; bottom = r.bottom; } else bottom = Math.max(bottom, r.bottom); }
|
||||
return rows;
|
||||
};
|
||||
const realKids = (w) => [...w.children].filter((c) => !skip.has(c.tagName));
|
||||
const cols = [...document.querySelectorAll('[class^="cols_"]')].map((w) => ({ n: realKids(w).length, rows: rowsOf(realKids(w)) }));
|
||||
// Every CSS grid the first-party components emit (inline display:grid), keyed by its section.
|
||||
const grids = [...document.querySelectorAll('div')].filter((d) => getComputedStyle(d).display === 'grid' && !d.closest('[data-wsb-html]') && !d.closest('[id^="hb"]')).map((g) => {
|
||||
const kids = realKids(g).filter((k) => k.getBoundingClientRect().height > 0);
|
||||
const firstTop = kids.length ? Math.round(kids[0].getBoundingClientRect().top) : 0;
|
||||
return {
|
||||
where: (g.closest('section')?.textContent || '').trim().slice(0, 30),
|
||||
hook: g.hasAttribute('data-wsb-grid'),
|
||||
// A grid of images (Gallery) shrinks its thumbnails instead of overflowing; it may keep its columns.
|
||||
imagesOnly: kids.length > 0 && kids.every((k) => k.tagName === 'IMG' || k.querySelector('img')),
|
||||
n: kids.length, perRow: kids.filter((k) => Math.round(k.getBoundingClientRect().top) === firstTop).length,
|
||||
};
|
||||
});
|
||||
const nav = document.querySelector('nav');
|
||||
let navRight = 0; let linkRows = null;
|
||||
if (nav) {
|
||||
for (const el of [nav, ...nav.querySelectorAll('*')]) { const r = el.getBoundingClientRect(); if (r.width || r.height) navRight = Math.max(navRight, r.right); }
|
||||
const links = [...nav.querySelectorAll('.navbar-link, .navbar-cta')].filter((a) => a.getBoundingClientRect().height > 0);
|
||||
linkRows = links.length ? rowsOf(links) : null; // null: links collapsed behind the hamburger
|
||||
}
|
||||
const sc = document.getElementById('intentional-scroll');
|
||||
let scrolls = null;
|
||||
if (sc) { sc.scrollLeft = 50; scrolls = sc.scrollWidth > sc.clientWidth && sc.scrollLeft > 0; sc.scrollLeft = 0; }
|
||||
return {
|
||||
vw, docSW: document.documentElement.scrollWidth, bodySW: document.body.scrollWidth,
|
||||
maxRight: Math.round(maxRight * 10) / 10, worst, cols, grids, navRight: Math.round(navRight * 10) / 10, linkRows, scrolls,
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs in the page: can the page be scrolled sideways? (scrollX after asking for 5000px.) */
|
||||
function sidewaysScroll() {
|
||||
const y = window.scrollY;
|
||||
window.scrollTo(5000, y);
|
||||
const x = window.scrollX;
|
||||
window.scrollTo(0, y);
|
||||
return x;
|
||||
}
|
||||
|
||||
/** Runs in the page (htmlblocks doc): the net must not box, clip, unstick or merge customer HTML. */
|
||||
function probes() {
|
||||
const out = {};
|
||||
out.wrapperDisplays = [...new Set([...document.querySelectorAll('[data-wsb-html]')].map((w) => getComputedStyle(w).display))];
|
||||
// Multi-root block as direct grid items: two separate cells side by side.
|
||||
const cells = [...document.querySelectorAll('.cell-probe')].map((c) => c.getBoundingClientRect());
|
||||
out.cellsSeparate = cells.length === 2 && Math.abs(cells[0].top - cells[1].top) < 1 && cells[1].left > cells[0].right;
|
||||
// Multi-root block as direct flex items: no box between the roots and the flex container.
|
||||
const roots = [...document.querySelectorAll('.root-probe')];
|
||||
const flexBox = roots[0]?.closest('[style*="display:flex"]');
|
||||
out.rootsAreFlexItems = roots.length === 2 && roots.every((r) => {
|
||||
let p = r.parentElement;
|
||||
while (p && getComputedStyle(p).display === 'contents') p = p.parentElement;
|
||||
return p === flexBox;
|
||||
});
|
||||
// Sticky: scroll 300px into its tall container; the bar must stay pinned at the top of the viewport.
|
||||
const box = document.getElementById('sticky-box');
|
||||
const bar = document.getElementById('sticky-probe');
|
||||
if (box && bar) {
|
||||
window.scrollTo(0, window.scrollY + box.getBoundingClientRect().top + 300);
|
||||
out.stickyTop = Math.round(bar.getBoundingClientRect().top * 10) / 10;
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
// Absolutely positioned dropdown hanging below its block: its last item must be visible and on top.
|
||||
const last = document.getElementById('dropdown-last');
|
||||
if (last) {
|
||||
// window.scrollTo, not scrollIntoView: scrollIntoView would also scroll a clipping ancestor to reveal it.
|
||||
window.scrollTo(0, window.scrollY + last.getBoundingClientRect().top - 200);
|
||||
const r = last.getBoundingClientRect();
|
||||
const hit = document.elementFromPoint(r.left + Math.min(10, r.width / 2), r.top + r.height / 2);
|
||||
out.dropdownVisible = !!hit && (hit === last || last.contains(hit));
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
// A width:100% table still spans its container: its first row is as wide as the table's parent content box.
|
||||
const t = document.getElementById('full-table');
|
||||
if (t) {
|
||||
let host = t.parentElement;
|
||||
while (host && getComputedStyle(host).display === 'contents') host = host.parentElement;
|
||||
const cs = getComputedStyle(host);
|
||||
const inner = host.getBoundingClientRect().width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
|
||||
out.fullTableRow = Math.round(t.querySelector('tr').getBoundingClientRect().width);
|
||||
out.fullTableSpans = Math.abs(t.querySelector('tr').getBoundingClientRect().width - inner) <= 2;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Runs in the page. Element boxes, ignoring display:contents hook wrappers (they have no box). */
|
||||
function boxes() {
|
||||
return [...document.body.querySelectorAll('*')]
|
||||
.filter((e) => !['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(e.tagName) && !e.hasAttribute('data-wsb-html'))
|
||||
.map((e) => { const r = e.getBoundingClientRect(); return [e.tagName, ...[r.x, r.y, r.width, r.height].map((v) => Math.round(v * 10) / 10)].join(','); });
|
||||
}
|
||||
|
||||
/** Runs in the page: remove the mobile hooks (unwrap the HtmlBlock wrapper, drop the grid hook). */
|
||||
function stripHooks() {
|
||||
for (const w of [...document.querySelectorAll('[data-wsb-html]')]) w.replaceWith(...w.childNodes);
|
||||
for (const g of document.querySelectorAll('[data-wsb-grid]')) g.removeAttribute('data-wsb-grid');
|
||||
}
|
||||
|
||||
let fail = 0;
|
||||
const ok = (c, m) => { if (!c) { fail++; console.log(' FAIL', m); } };
|
||||
const baseline = process.env.MOBILE_GUARD_BASELINE ? JSON.parse(fs.readFileSync(process.env.MOBILE_GUARD_BASELINE, 'utf8')) : null;
|
||||
const record = {};
|
||||
const summary = [];
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const gen = await browser.newPage();
|
||||
await gen.setContent('<!doctype html><html><body></body></html>');
|
||||
await gen.addScriptTag({ content: js });
|
||||
const docs = await gen.evaluate(() => window.wsbMobileGuardDocs());
|
||||
await gen.close();
|
||||
record[name] = {};
|
||||
for (const [docName, html] of Object.entries(docs)) {
|
||||
for (const w of WIDTHS) {
|
||||
const page = await browser.newPage({ viewport: { width: w, height: 900 } });
|
||||
await page.route(/^https?:/, (r) => r.abort()); // deterministic: no fonts/CDN racing the layout
|
||||
await page.setContent(html, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(50);
|
||||
const m = await page.evaluate(measure);
|
||||
const tag = `[${name} ${w}] ${docName}`;
|
||||
const mobile = w <= MOBILE_MAX;
|
||||
summary.push(`${name.padEnd(8)} ${String(w).padEnd(4)} ${docName.padEnd(11)} docSW=${m.docSW} bodySW=${m.bodySW} maxRight=${m.maxRight}${m.maxRight > w + 0.5 ? ' (' + m.worst + ')' : ''} cols=${m.cols.map((c) => c.rows + '/' + c.n).join(',') || '-'} grids/row=${m.grids.map((g) => g.perRow + '/' + g.n + (g.hook ? 'h' : '')).join(',') || '-'} nav=${m.navRight}/${m.linkRows}rows${m.scrolls === null ? '' : ' scroller=' + m.scrolls}`);
|
||||
|
||||
ok(m.docSW <= w, `${tag}: documentElement.scrollWidth ${m.docSW} > ${w}`);
|
||||
const sx = await page.evaluate(sidewaysScroll);
|
||||
ok(sx === 0, `${tag}: the page scrolls sideways (scrollX=${sx})`);
|
||||
if (docName === 'htmlwide') {
|
||||
// Wider than a phone by design (fixed widths, px grids): the net does not reflow or box it, so it stays
|
||||
// clipped by html,body{overflow-x:clip} exactly as before (the publish warning is the guard for these),
|
||||
// and the page never scrolls sideways (asserted above).
|
||||
if (mobile) ok(m.maxRight > w + 0.5, `${tag}: the wide fixed block was expected to stay clipped (content ends at x=${m.maxRight})`);
|
||||
} else if (docName === 'components' || mobile) {
|
||||
// Customer HTML the net makes fit is held to the viewport only where the net applies (<=767px).
|
||||
ok(m.bodySW <= w, `${tag}: body.scrollWidth ${m.bodySW} > ${w}`);
|
||||
ok(m.maxRight <= w + 0.5, `${tag}: content reaches x=${m.maxRight} (clipped on a real device): ${m.worst}`);
|
||||
}
|
||||
ok(m.navRight <= w + 0.5, `${tag}: navbar reaches x=${m.navRight}`);
|
||||
if (docName === 'components' && w <= 390) ok(m.linkRows > 1, `${tag}: navbar links did not wrap (${m.linkRows} row)`);
|
||||
if (docName === 'htmlblocks' && mobile) ok(m.linkRows === null, `${tag}: hamburger navbar shows its links on a phone`);
|
||||
// The 1000px table only needs to scroll where it is wider than its box.
|
||||
if (m.scrolls !== null && w <= 768) ok(m.scrolls, `${tag}: the intentional overflow-x:auto table no longer scrolls`);
|
||||
if (docName === 'htmlblocks') {
|
||||
const pr = await page.evaluate(probes);
|
||||
summary.push(`${' '.repeat(26)}probes ${JSON.stringify(pr)}`);
|
||||
ok(pr.wrapperDisplays.length === 1 && pr.wrapperDisplays[0] === 'contents', `${tag}: HtmlBlock wrapper has a box (display ${pr.wrapperDisplays})`);
|
||||
ok(pr.cellsSeparate, `${tag}: a multi-root HtmlBlock in a grid no longer fills separate cells`);
|
||||
ok(pr.rootsAreFlexItems, `${tag}: a multi-root HtmlBlock in a flex row is no longer separate flex items`);
|
||||
ok(pr.stickyTop !== undefined && Math.abs(pr.stickyTop) <= 1, `${tag}: position:sticky inside an HtmlBlock stopped sticking (top=${pr.stickyTop})`);
|
||||
ok(pr.dropdownVisible, `${tag}: an absolutely positioned dropdown inside an HtmlBlock is clipped or covered`);
|
||||
ok(pr.fullTableSpans, `${tag}: a width:100% table no longer spans the screen (first row ${pr.fullTableRow}px)`);
|
||||
}
|
||||
if (docName === 'components') {
|
||||
for (const c of m.cols) ok(mobile ? c.rows === c.n : c.rows === 1, `${tag}: ColumnLayout ${mobile ? 'not stacked' : 'stacked'} (${c.rows} rows / ${c.n} cols)`);
|
||||
for (const g of m.grids) {
|
||||
if (g.n < 2) continue;
|
||||
if (mobile && !g.imagesOnly) ok(g.perRow === 1, `${tag}: grid "${g.where}" keeps ${g.perRow} columns on a phone`);
|
||||
if (!mobile && g.hook) ok(g.perRow > 1, `${tag}: grid "${g.where}" lost its columns (${g.perRow} per row)`);
|
||||
}
|
||||
}
|
||||
if (w === 1280) {
|
||||
const before = await page.evaluate(boxes);
|
||||
const shotBefore = await page.screenshot({ fullPage: true });
|
||||
await page.evaluate(stripHooks);
|
||||
await page.waitForTimeout(20);
|
||||
const after = await page.evaluate(boxes);
|
||||
const shotAfter = await page.screenshot({ fullPage: true });
|
||||
ok(shotBefore.equals(shotAfter), `${tag}: full-page pixels differ with vs without the mobile hooks`);
|
||||
const diffs = before.length !== after.length ? Infinity : before.filter((b, i) => b !== after[i]).length;
|
||||
ok(diffs === 0, `${tag}: ${diffs} element boxes differ with vs without the mobile hooks (${before.length}/${after.length} elements)`);
|
||||
record[name][docName] = after;
|
||||
const b = baseline?.[name]?.[docName];
|
||||
if (b) {
|
||||
const d = b.length !== before.length ? Infinity : b.filter((x, i) => x !== before[i]).length;
|
||||
if (d) for (let i = 0, shown = 0; i < Math.min(b.length, before.length) && shown < 3; i++) if (b[i] !== before[i]) { shown++; console.log(' diff', b[i], '->', before[i]); }
|
||||
ok(d === 0, `${tag}: ${d} element boxes differ from the recorded baseline (${b.length} -> ${before.length} elements)`);
|
||||
}
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const only = process.env.MOBILE_ONLY;
|
||||
if (!only || only === 'chromium') await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (!only || only === 'firefox') await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
if (process.env.MOBILE_GUARD_RECORD) fs.writeFileSync(process.env.MOBILE_GUARD_RECORD, JSON.stringify(record));
|
||||
console.log('\n' + summary.join('\n'));
|
||||
console.log(fail ? `\n${fail} FAILED` : '\nall passed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,73 @@
|
||||
// Bundled by scripts/e2e-mobile-parity.mjs. Builds the documents the real-browser mobile test measures.
|
||||
// Uses only exports that exist before and after the mobile-parity fix so the SAME harness can record a baseline.
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
|
||||
const node = (type: string, props: Record<string, unknown>, nodes: string[] = [], extra: Record<string, unknown> = {}) => ({
|
||||
type: { resolvedName: type }, isCanvas: type === 'Container', props, displayName: type, custom: {}, hidden: false, nodes, linkedNodes: {}, ...extra,
|
||||
});
|
||||
const LONG = 'Honest prices, straight answers and work that is finished when we say it will be, every time.';
|
||||
|
||||
/** ColumnLayout with `n` Container columns each holding one TextBlock. */
|
||||
function addColumns(nodes: Record<string, any>, id: string, props: Record<string, unknown>, n: number) {
|
||||
const linked: Record<string, string> = {};
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = `${id}-c${i}`;
|
||||
const t = `${id}-t${i}`;
|
||||
nodes[c] = node('Container', { tag: 'div', style: { padding: '8px' } }, [t], { parent: id });
|
||||
nodes[t] = node('TextBlock', { text: `${LONG} (${id} col ${i + 1})`, style: { fontSize: '16px' } }, [], { parent: c });
|
||||
linked[`col-${i}`] = c;
|
||||
}
|
||||
nodes[id] = node('ColumnLayout', { columns: n, gap: '16px', anchorId: id, ...props }, [], { parent: 'ROOT', linkedNodes: linked });
|
||||
}
|
||||
|
||||
export const NAV_LINKS = ['Home', 'About us', 'Services', 'Our work', 'Pricing', 'Blog', 'Contact'].map((text, i, a) => ({
|
||||
text, href: '#' + text.toLowerCase().replace(/\s/g, '-'), ...(i === a.length - 1 ? { isCta: true } : {}),
|
||||
}));
|
||||
|
||||
export function syntheticState(navShowMobileMenu: boolean | undefined): string {
|
||||
const nodes: Record<string, any> = {};
|
||||
const kids: string[] = ['nav'];
|
||||
const navProps: Record<string, unknown> = { logoText: 'Acme Plumbing & Heating', links: NAV_LINKS, padding: '16px 24px' };
|
||||
if (navShowMobileMenu !== undefined) navProps.showMobileMenu = navShowMobileMenu;
|
||||
nodes.nav = node('Navbar', navProps, [], { parent: 'ROOT' });
|
||||
const specs: Array<[string, Record<string, unknown>, number]> = [
|
||||
['c2', { split: '50-50' }, 2],
|
||||
['centered', { split: '50-50', gap: '48px', style: { alignItems: 'center' } }, 2],
|
||||
['c3', { split: '33-33-33' }, 3],
|
||||
['c4', { split: '25-25-25-25' }, 4],
|
||||
['c6', { split: '16-16-16-16-16-16' }, 6],
|
||||
['sideL', { split: '30-70' }, 2],
|
||||
['sideR', { split: '70-30' }, 2],
|
||||
['optout', { split: '50-50', styleMobile: { flexDirection: 'row' } }, 2],
|
||||
];
|
||||
for (const [id, p, n] of specs) { addColumns(nodes, id, p, n); kids.push(id); }
|
||||
// An existing author-built flex row (already stacks via the global rule) must be unaffected.
|
||||
nodes.row = node('Container', { tag: 'div', style: { display: 'flex', flexDirection: 'row', gap: '12px' } }, ['rt1', 'rt2'], { parent: 'ROOT' });
|
||||
nodes.rt1 = node('TextBlock', { text: 'Row item one', style: {} }, [], { parent: 'row' });
|
||||
nodes.rt2 = node('TextBlock', { text: 'Row item two', style: {} }, [], { parent: 'row' });
|
||||
kids.push('row');
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, kids);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
export function renderSynthetic(navShowMobileMenu: boolean | undefined): string {
|
||||
const state = syntheticState(navShowMobileMenu);
|
||||
const body = exportBodyHtml(state).html;
|
||||
return exportComposedPreviewHtml(state, body, { title: 'Synthetic', includeFonts: false });
|
||||
}
|
||||
|
||||
/** Stored OLS page rendered by the CURRENT frontend: regenerated body + current head. */
|
||||
export function renderStored(project: any, pageIdx: number): string {
|
||||
const page = project.pages_craft_state[pageIdx];
|
||||
const hdr = project.header_craft_state ? exportBodyHtml(project.header_craft_state, 'header').html : '';
|
||||
const ftr = project.footer_craft_state ? exportBodyHtml(project.footer_craft_state, 'footer').html : '';
|
||||
const body = exportBodyHtml(page.craftState).html;
|
||||
return exportComposedPreviewHtml(page.craftState, hdr + body + ftr, { title: page.name, includeFonts: true, headCode: project.design?.headCode, design: project.design });
|
||||
}
|
||||
|
||||
/** The checked-in (OLD) stored body under the CURRENT head: "existing site, next publish". */
|
||||
export function renderOldBodyNewHead(project: any, storedHtml: string): string {
|
||||
const m = storedHtml.match(/<body[^>]*>([\s\S]*)<\/body>/i);
|
||||
const body = m ? m[1] : storedHtml;
|
||||
return exportComposedPreviewHtml(project.pages_craft_state[0].craftState, body, { title: 'old', includeFonts: true, design: project.design });
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser regression test (Firefox AND Chromium, headless): published/Preview documents must
|
||||
* stack multi-column layouts at phone width, must not overflow horizontally at 390px, and must lay
|
||||
* out EXACTLY as before at desktop width.
|
||||
*
|
||||
* npm run test:browser:mobile
|
||||
* MOBILE_PARITY_RECORD=<file> write a layout snapshot (run on the base commit to get a baseline)
|
||||
* MOBILE_PARITY_BASELINE=<file> additionally assert desktop (1280) boxes equal that snapshot
|
||||
*
|
||||
* Env: CHROMIUM_PATH / FIREFOX_PATH, MOBILE_ONLY=chromium|firefox.
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const fixDir = path.join(root, 'tests/fixtures/canvas-parity');
|
||||
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-mobile-parity-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const tmp = path.join(os.tmpdir(), `wsb-mobile-${process.pid}.mjs`);
|
||||
fs.writeFileSync(tmp, out.outputFiles[0].text);
|
||||
const ent = await import(tmp);
|
||||
fs.rmSync(tmp, { force: true });
|
||||
|
||||
const project = JSON.parse(fs.readFileSync(path.join(fixDir, 'ols.project.json'), 'utf8'));
|
||||
const docs = {
|
||||
'synthetic (navbar showMobileMenu unset = existing)': ent.renderSynthetic(undefined),
|
||||
'synthetic (navbar showMobileMenu false)': ent.renderSynthetic(false),
|
||||
'synthetic (navbar showMobileMenu true)': ent.renderSynthetic(true),
|
||||
};
|
||||
project.pages_craft_state.forEach((pg, i) => { docs[`ols/${pg.slug} (regenerated)`] = ent.renderStored(project, i); });
|
||||
for (const slug of ['index', 'about', 'contact', 'brands']) {
|
||||
docs[`ols/${slug} (stored body, current head)`] = ent.renderOldBodyNewHead(project, fs.readFileSync(path.join(fixDir, `ols.${slug}.html`), 'utf8'));
|
||||
}
|
||||
|
||||
function measure() {
|
||||
const vis = (el) => { const r = el.getBoundingClientRect(); return getComputedStyle(el).display !== 'none' && (r.width > 0 || r.height > 0); };
|
||||
const els = [...document.body.querySelectorAll('*')].filter((e) => !['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(e.tagName));
|
||||
const boxes = els.map((el, i) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return [i, el.tagName, Math.round(r.x * 10) / 10, Math.round(r.y * 10) / 10, Math.round(r.width * 10) / 10, Math.round(r.height * 10) / 10, getComputedStyle(el).display];
|
||||
});
|
||||
let maxRight = 0; let worst = '';
|
||||
for (const el of els) { if (!vis(el)) continue; const r = el.getBoundingClientRect(); if (r.right > maxRight) { maxRight = r.right; worst = el.tagName + '.' + (el.className || '') + ':' + (el.textContent || '').slice(0, 20); } }
|
||||
// Multi-column layouts: ColumnLayout wrappers (class cols_*) -> do their column children share a row?
|
||||
const cols = [...document.querySelectorAll('[class^="cols_"]')].map((w) => {
|
||||
const kids = [...w.children].filter((c) => !['STYLE', 'SCRIPT'].includes(c.tagName));
|
||||
const tops = new Set(kids.map((k) => Math.round(k.getBoundingClientRect().top)));
|
||||
return { id: w.id, n: kids.length, rows: tops.size, dir: getComputedStyle(w).flexDirection, minW: Math.min(...kids.map((k) => k.getBoundingClientRect().width)) };
|
||||
});
|
||||
const rowEls = [...document.querySelectorAll('div')].filter((d) => /flex-direction:\s*row/.test(d.getAttribute('style') || '') && /display:\s*flex/.test(d.getAttribute('style') || '') && !/^cols_/.test(d.className));
|
||||
const rows = rowEls.map((d) => getComputedStyle(d).flexDirection);
|
||||
const nav = document.querySelector('nav');
|
||||
let navRight = 0;
|
||||
if (nav) for (const el of [nav, ...nav.querySelectorAll('*')]) { if (vis(el)) navRight = Math.max(navRight, el.getBoundingClientRect().right); }
|
||||
const navInfo = nav ? { w: nav.getBoundingClientRect().width, h: Math.round(nav.getBoundingClientRect().height), scrollW: nav.scrollWidth, hamburger: !!nav.querySelector('.navbar-hamburger') && getComputedStyle(nav.querySelector('.navbar-hamburger')).display } : null;
|
||||
return { innerW: window.innerWidth, maxRight: Math.round(maxRight * 10) / 10, navRight: Math.round(navRight * 10) / 10, worst, cols, rows, navInfo, boxes };
|
||||
}
|
||||
|
||||
const results = {};
|
||||
let fail = 0;
|
||||
const ok = (c, m) => { if (!c) { fail++; console.log(' FAIL', m); } };
|
||||
const baseline = process.env.MOBILE_PARITY_BASELINE ? JSON.parse(fs.readFileSync(process.env.MOBILE_PARITY_BASELINE, 'utf8')) : null;
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
results[name] = {};
|
||||
for (const [docName, html] of Object.entries(docs)) {
|
||||
results[name][docName] = {};
|
||||
for (const w of [390, 1280]) {
|
||||
const page = await browser.newPage({ viewport: { width: w, height: 900 } });
|
||||
// Deterministic: no network (web fonts / CDN icons would race the measurement).
|
||||
await page.route(/^https?:/, (r) => r.abort());
|
||||
await page.setContent(html, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(50);
|
||||
const m = await page.evaluate(measure);
|
||||
await page.close();
|
||||
results[name][docName][w] = m;
|
||||
const tag = `[${name} ${w}] ${docName}`;
|
||||
if (w === 390) {
|
||||
// ols/index's FeaturesGrid stacks via its data-wsb-grid hook, which a body stored before the hook
|
||||
// existed does not carry: only that stored body is exempt (it is fixed by republishing).
|
||||
ok(m.navRight <= 390.5, `${tag}: navbar overflows, reaches x=${m.navRight}`);
|
||||
if (docName !== 'ols/index (stored body, current head)') ok(m.maxRight <= 390.5, `${tag}: horizontal overflow, content reaches x=${m.maxRight} (${m.worst})`);
|
||||
for (const c of m.cols) {
|
||||
const optOut = c.id === 'optout';
|
||||
if (optOut) ok(c.rows === 1 || c.n === 1, `${tag}: opt-out columns should stay side by side (${JSON.stringify(c)})`);
|
||||
else ok(c.rows === c.n, `${tag}: columns not stacked (${JSON.stringify(c)})`);
|
||||
}
|
||||
}
|
||||
if (w === 1280 && baseline) {
|
||||
const b = baseline[name]?.[docName]?.[1280];
|
||||
if (b) {
|
||||
const sameCount = b.boxes.length === m.boxes.length;
|
||||
ok(sameCount, `${tag}: element count ${b.boxes.length} -> ${m.boxes.length}`);
|
||||
let diffs = 0;
|
||||
if (sameCount) for (let i = 0; i < b.boxes.length; i++) {
|
||||
const bb = b.boxes[i]; const mm = m.boxes[i];
|
||||
if (bb.slice(2, 6).some((v, j) => Math.abs(v - mm[2 + j]) > 0.5) || bb[6] !== mm[6]) { if (diffs++ < 3) console.log(' diff', JSON.stringify(bb), JSON.stringify(mm)); }
|
||||
}
|
||||
ok(diffs === 0, `${tag}: ${diffs} element boxes changed at desktop`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const only = process.env.MOBILE_ONLY;
|
||||
if (!only || only === 'chromium') await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (!only || only === 'firefox') await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
|
||||
if (process.env.MOBILE_PARITY_RECORD) fs.writeFileSync(process.env.MOBILE_PARITY_RECORD, JSON.stringify(results));
|
||||
// Human-readable summary at 390.
|
||||
for (const [b, per] of Object.entries(results)) {
|
||||
for (const [d, r] of Object.entries(per)) {
|
||||
const m = r[390];
|
||||
console.log(`${b.padEnd(8)} 390 ${d.padEnd(55)} maxRight=${String(m.maxRight).padEnd(7)} cols(rows/n)=${m.cols.map((c) => c.rows + '/' + c.n).join(',') || '-'} nav=${m.navInfo ? m.navInfo.h + 'h/' + m.navInfo.hamburger + '/right=' + m.navRight : '-'}`);
|
||||
}
|
||||
}
|
||||
console.log(fail ? `\n${fail} FAILED` : '\nall passed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,47 @@
|
||||
// Bundled (esbuild, node) by scripts/e2e-preview-assets.mjs: a version-history snapshot whose header, body and
|
||||
// design carry uploads exactly as the AssetPicker stores them (the same-origin panel proxy URL), turned into the
|
||||
// Preview document by the REAL buildSnapshotPreviewHtml (the same export + absolute-URL step as TopBar's Preview),
|
||||
// plus the published body for the backend publish check.
|
||||
import { editorProxyUrl } from '../src/sitesmith/editor-asset-urls';
|
||||
import { buildSnapshotPreviewHtml, type Snapshot } from '../src/utils/history-restore';
|
||||
import { exportBodyHtml } from '../src/utils/html-export';
|
||||
import { flattenTreeForCraft } from '../src/utils/craft-tree';
|
||||
import { inlinePreviewAssets, collectPreviewAssetUrls } from '../src/utils/preview-assets';
|
||||
|
||||
export const SITE_ID = 7;
|
||||
export const FILES = ['1700000000_aa11bb22_hero.png', '1700000001_bb22cc33_logo+v2.png', 'my photo.png', 'café.png', 'poster.png', 'fav.png'];
|
||||
export const OTHER_SITE_FILE = 'other-site.png';
|
||||
const U = (i: number) => editorProxyUrl(SITE_ID, FILES[i]);
|
||||
const n = (type: string, props: Record<string, unknown>, nodes?: any[]) => ({ type: { resolvedName: type }, props, ...(nodes ? { nodes } : {}) });
|
||||
const state = (tree: any) => JSON.stringify(flattenTreeForCraft(tree).nodes);
|
||||
|
||||
const header = state(n('Container', { node_id: 'ROOT', tag: 'div' }, [
|
||||
n('Navbar', { node_id: 'nav', logoType: 'image', logoImage: U(1), logoUrl: '/', links: [{ text: 'Home', href: '/' }] }),
|
||||
]));
|
||||
const page = state(n('Container', { node_id: 'ROOT', tag: 'div' }, [
|
||||
n('BackgroundSection', { node_id: 'bg', bgImage: U(0), overlayOpacity: 0.2 }, [n('Heading', { node_id: 'h', text: 'Hello', level: 'h1' })]),
|
||||
n('ImageBlock', { node_id: 'i1', src: U(0), alt: 'plain' }),
|
||||
n('ImageBlock', { node_id: 'i2', src: U(1), alt: 'plus' }),
|
||||
n('ImageBlock', { node_id: 'i3', src: U(2), alt: 'space' }),
|
||||
n('ImageBlock', { node_id: 'i4', src: U(3), alt: 'unicode' }),
|
||||
n('Container', { node_id: 'c', tag: 'div', style: { minHeight: '60px', backgroundImage: `url(${U(0)})` } }),
|
||||
n('HtmlBlock', { node_id: 'html', code:
|
||||
`<img id="rich" src="${U(0)}" alt="rich"><img id="srcset" alt="srcset" src="${U(2)}" srcset="${U(0)} 1x, ${U(3)} 2x">`
|
||||
+ `<video id="vid" poster="${U(4)}" width="40" height="30"></video>`
|
||||
+ `<a id="lnk" href="${U(0)}">full size</a>`
|
||||
+ `<img id="other" alt="other" src="${editorProxyUrl(8, OTHER_SITE_FILE)}">` }),
|
||||
n('ImageBlock', { node_id: 'i5', src: editorProxyUrl(SITE_ID, 'does-not-exist.png'), alt: 'missing' }),
|
||||
]));
|
||||
|
||||
export const SNAPSHOT: Snapshot = {
|
||||
pages_craft_state: [{ id: 'p1', name: 'Home', slug: 'index', craftState: page }],
|
||||
header_craft_state: header,
|
||||
footer_craft_state: null,
|
||||
design: { favicon: U(5) },
|
||||
} as unknown as Snapshot;
|
||||
|
||||
/** The Preview document as origin/main hands it to the sandboxed tab (proxy URLs made absolute on `origin`). */
|
||||
export function previewHtml(origin: string): string { return buildSnapshotPreviewHtml(SNAPSHOT, 0, origin); }
|
||||
/** The page body Save/Publish sends (no Preview step involved). */
|
||||
export function publishBody(): string { return exportBodyHtml(header).html + exportBodyHtml(page).html; }
|
||||
export { inlinePreviewAssets, collectPreviewAssetUrls };
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser check (Chromium AND Firefox, headless) that uploaded images render in PREVIEW, the way the editor
|
||||
* really opens it: a click opens a panel-origin tab (window.open('')), which holds an
|
||||
* <iframe sandbox="allow-scripts allow-popups allow-forms" srcdoc> -- an OPAQUE (null) origin
|
||||
* (utils/sandboxed-preview.ts). The asset stub is a real HTTP server sending the same headers as
|
||||
* whp libs/SiteBuilderAssetServe.php, above all `Cross-Origin-Resource-Policy: same-site`.
|
||||
* 1. control (origin/main behaviour, openSandboxedPreview on the exported HTML): every upload image is
|
||||
* blocked by CORP (naturalWidth 0) -- the canary bug (ERR_BLOCKED_BY_RESPONSE.NotSameSite);
|
||||
* 2. fixed (openPreviewWithInlinedAssets): the editor fetches this site's proxy assets and hands them over as
|
||||
* data: URLs; every upload image, srcset, poster, favicon and background loads; a missing file, another
|
||||
* site's file and an <a href> link keep their original URL; the frame is still null-origin;
|
||||
* 3. measured: a blob: URL made by the editor window or by the Preview tab does NOT load in that frame
|
||||
* (why data: is used);
|
||||
* 4. publish: the same page through the REAL backend sb_rewrite_asset_urls + generateCompiledHTML holds
|
||||
* `assets/<file>` only -- no data: URL, no proxy URL (Preview-only transformation).
|
||||
* Nothing leaves the machine: the server listens on 127.0.0.1 and every other request is aborted.
|
||||
* npm run test:browser:preview-assets Env: WHP_BACKEND_DIR (a whp worktree root), CHROMIUM_PATH / FIREFOX_PATH
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const BACKEND_DIR = process.env.WHP_BACKEND_DIR || '/workspace/whp';
|
||||
const define = { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' };
|
||||
|
||||
// node side: the Preview document from the real exporter
|
||||
const nodeOut = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-preview-assets-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error', define,
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const tmp = path.join(os.tmpdir(), `wsb-preview-assets-${process.pid}.mjs`);
|
||||
fs.writeFileSync(tmp, nodeOut.outputFiles[0].text);
|
||||
const { JSDOM } = await import('jsdom');
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>');
|
||||
globalThis.window = dom.window; globalThis.document = dom.window.document;
|
||||
const ent = await import(tmp);
|
||||
fs.rmSync(tmp, { force: true });
|
||||
|
||||
// browser side: the real Preview openers
|
||||
const browserJs = (await esbuild({
|
||||
stdin: {
|
||||
contents: "import { openSandboxedPreview } from './src/utils/sandboxed-preview';\n"
|
||||
+ "import { openPreviewWithInlinedAssets } from './src/utils/preview-assets';\n"
|
||||
+ 'window.WSB = { openSandboxedPreview, openPreviewWithInlinedAssets };',
|
||||
resolveDir: root, loader: 'ts',
|
||||
},
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', logLevel: 'error', define,
|
||||
})).outputFiles[0].text;
|
||||
|
||||
let pass = 0; let fail = 0; let skip = 0;
|
||||
const ok = (c, m, d = '') => { if (c) { pass++; console.log('PASS ', m); } else { fail++; console.log('FAIL ', m, d); } };
|
||||
|
||||
// An 8x8 PNG: a 1x1 image picked as a srcset 2x candidate has a density-corrected naturalWidth of 0.5 -> 0.
|
||||
const PNG = (() => {
|
||||
const crcT = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
|
||||
const crc = (b) => { let c = 0xffffffff; for (const x of b) c = crcT[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
||||
const chunk = (t, d) => { const l = Buffer.alloc(4); l.writeUInt32BE(d.length); const td = Buffer.concat([Buffer.from(t), d]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([l, td, c]); };
|
||||
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(8, 0); ihdr.writeUInt32BE(8, 4); ihdr[8] = 8; ihdr[9] = 2;
|
||||
const raw = Buffer.concat(Array.from({ length: 8 }, () => Buffer.from([0, ...Array(24).fill(200)])));
|
||||
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
||||
})();
|
||||
const ASSET_HEADERS = { // libs/SiteBuilderAssetServe.php sb_serve_asset()
|
||||
'Content-Type': 'image/png', 'Content-Length': String(PNG.length), 'X-Content-Type-Options': 'nosniff',
|
||||
'Cross-Origin-Resource-Policy': 'same-site', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
};
|
||||
const srv = http.createServer((req, res) => {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
if (u.pathname === '/site-builder/') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' });
|
||||
return res.end('<!doctype html><title>editor</title><script src="/wsb.js"></script><button id="old">old</button><button id="new">new</button>'
|
||||
+ '<script>const go=(m)=>{const win=window.open("","_blank");setTimeout(()=>{m==="old"?WSB.openSandboxedPreview(window.__html,{title:"Preview",win})'
|
||||
+ ':WSB.openPreviewWithInlinedAssets(window.__html,{title:"Preview",win,origin:location.origin,siteId:7})},50)};'
|
||||
+ 'document.getElementById("old").onclick=()=>go("old");document.getElementById("new").onclick=()=>go("new");</script>');
|
||||
}
|
||||
if (u.pathname === '/wsb.js') { res.writeHead(200, { 'Content-Type': 'text/javascript' }); return res.end(browserJs); }
|
||||
if (u.pathname === '/api/assets-proxy/') {
|
||||
const site = u.searchParams.get('site_id'); const f = u.searchParams.get('filename');
|
||||
if ((site === String(ent.SITE_ID) && ent.FILES.includes(f)) || (site === '8' && f === ent.OTHER_SITE_FILE)) { res.writeHead(200, ASSET_HEADERS); return res.end(PNG); }
|
||||
}
|
||||
res.writeHead(404); res.end();
|
||||
});
|
||||
await new Promise((r) => srv.listen(0, '127.0.0.1', r));
|
||||
const ORIGIN = `http://127.0.0.1:${srv.address().port}`;
|
||||
const html = ent.previewHtml(ORIGIN);
|
||||
|
||||
// ------------------------------------------------ static: the inliner only swaps this site's proxy URLs
|
||||
ok(html.includes(`src="${ORIGIN}/api/assets-proxy/?site_id=7&filename=`), 'control document carries absolute same-origin proxy URLs (as origin/main builds it)');
|
||||
const hits = ent.collectPreviewAssetUrls(html, { origin: ORIGIN, siteId: ent.SITE_ID });
|
||||
const names = [...new Set(hits.map((h) => new URL(h.key).searchParams.get('filename')))];
|
||||
ok(ent.FILES.every((f) => names.includes(f)), 'collector finds every upload: img, srcset, poster, logo, favicon, backgrounds', JSON.stringify(names));
|
||||
ok(!names.includes(ent.OTHER_SITE_FILE), "collector leaves another site's proxy URL alone");
|
||||
|
||||
// ------------------------------------------------ publish through the real backend (Preview-only transformation)
|
||||
if (fs.existsSync(path.join(BACKEND_DIR, 'web-files/api/site-builder.php'))) {
|
||||
const pub = JSON.parse(execFileSync('php', [path.join(root, 'scripts/e2e-sitesmith-editor-assets-backend.php'), BACKEND_DIR],
|
||||
{ input: JSON.stringify({ html: ent.publishBody(), css: '' }), maxBuffer: 1 << 26 }).toString());
|
||||
ok(!/data:image|assets-proxy|serve_asset/.test(pub.body + pub.doc), 'published body + document hold no data: URL and no proxy URL');
|
||||
ok(['assets/1700000000_aa11bb22_hero.png', 'assets/1700000001_bb22cc33_logo%2Bv2.png', 'assets/my%20photo.png', 'assets/caf%C3%A9.png', 'assets/poster.png'].every((r) => pub.body.includes(r)),
|
||||
'published body references the uploads as assets/<file>', pub.body.match(/assets\/[^"')\s]*/g)?.join(' '));
|
||||
} else { skip++; console.log(`SKIP published-output checks: no backend at WHP_BACKEND_DIR=${BACKEND_DIR}`); }
|
||||
|
||||
/** Open Preview with the given opener via a real click and read what the sandboxed frame shows. */
|
||||
async function preview(browser, mode) {
|
||||
const ctx = await browser.newContext();
|
||||
await ctx.route('**/*', (route) => (new URL(route.request().url()).origin === ORIGIN || route.request().url().startsWith('data:') ? route.continue() : route.abort()));
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(ORIGIN + '/site-builder/');
|
||||
await page.evaluate((h) => { window.__html = h; }, html);
|
||||
const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('#' + mode)]);
|
||||
const fh = await popup.waitForSelector('iframe', { timeout: 15000 });
|
||||
const frame = await fh.contentFrame();
|
||||
await frame.waitForSelector('img#rich', { timeout: 15000 });
|
||||
await frame.waitForFunction(() => [...document.images].every((i) => i.complete), null, { timeout: 15000 }).catch(() => {});
|
||||
await popup.waitForTimeout(300);
|
||||
const r = await frame.evaluate(async () => {
|
||||
const imgs = Object.fromEntries([...document.images].map((i) => [i.id || i.alt, { w: i.naturalWidth, src: i.currentSrc || i.src }]));
|
||||
const bgs = [...document.querySelectorAll('body *')].map((e) => getComputedStyle(e).backgroundImage).filter((b) => b && b !== 'none' && b.includes('url('));
|
||||
const bgLoads = await Promise.all(bgs.map((b) => new Promise((res) => { const m = /url\("?(.*?)"?\)$/.exec(b); const i = new Image(); i.onload = () => res(i.naturalWidth > 0); i.onerror = () => res(false); i.src = m ? m[1] : ''; })));
|
||||
return {
|
||||
origin: String(self.origin), imgs, bgs: bgs.map((b) => b.slice(0, 60)), bgLoads,
|
||||
poster: document.getElementById('vid')?.getAttribute('poster')?.slice(0, 30),
|
||||
link: document.getElementById('lnk')?.getAttribute('href'),
|
||||
icon: document.querySelector('link[rel="icon"]')?.getAttribute('href')?.slice(0, 30),
|
||||
};
|
||||
});
|
||||
const sandbox = await fh.getAttribute('sandbox');
|
||||
await ctx.close();
|
||||
return { ...r, sandbox };
|
||||
}
|
||||
|
||||
/** Blob URLs (editor window / Preview tab) inside the same kind of null-origin srcdoc frame: measured, not assumed. */
|
||||
async function blobProbe(browser) {
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(ORIGIN + '/site-builder/');
|
||||
const res = await page.evaluate(async () => {
|
||||
const win = window.open('', '_blank');
|
||||
const bytes = await (await fetch('/api/assets-proxy/?site_id=7&filename=fav.png')).arrayBuffer();
|
||||
const editorBlob = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
|
||||
const tabBlob = win.URL.createObjectURL(new win.Blob([bytes], { type: 'image/png' }));
|
||||
const data = 'data:image/png;base64,' + btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
||||
return await new Promise((resolve) => {
|
||||
win.addEventListener('message', (e) => resolve(e.data));
|
||||
const f = win.document.createElement('iframe');
|
||||
f.setAttribute('sandbox', 'allow-scripts allow-popups allow-forms');
|
||||
f.srcdoc = `<img id="editorBlob" src="${editorBlob}"><img id="tabBlob" src="${tabBlob}"><img id="data" src="${data}">`
|
||||
+ '<script>onload=()=>parent.postMessage(Object.fromEntries([...document.images].map(i=>[i.id,i.naturalWidth])),"*")<\/script>';
|
||||
win.document.body.appendChild(f);
|
||||
setTimeout(() => resolve(null), 8000);
|
||||
});
|
||||
});
|
||||
await ctx.close();
|
||||
return res;
|
||||
}
|
||||
|
||||
const UPLOADS = ['plain', 'plus', 'space', 'unicode', 'rich', 'srcset', 'Logo'];
|
||||
for (const [name, launcher, exe] of [['chromium', chromium, process.env.CHROMIUM_PATH], ['firefox', firefox, process.env.FIREFOX_PATH]]) {
|
||||
let browser;
|
||||
try { browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) }); }
|
||||
catch (e) { skip++; console.log(`SKIP [${name}] browser not available: ${String(e.message).split('\n')[0]}`); continue; }
|
||||
const up = (r) => Object.entries(r.imgs).filter(([k]) => UPLOADS.includes(k) || /logo/i.test(k));
|
||||
|
||||
const control = await preview(browser, 'old');
|
||||
ok(control.origin === 'null' && control.sandbox === 'allow-scripts allow-popups allow-forms', `[${name}] control: Preview frame is the sandboxed null-origin srcdoc`, `${control.origin} ${control.sandbox}`);
|
||||
ok(up(control).length >= 6 && up(control).every(([, v]) => v.w === 0), `[${name}] control (origin/main): every upload image is BLOCKED by CORP same-site (naturalWidth 0)`, JSON.stringify(control.imgs));
|
||||
ok(control.bgLoads.length >= 2 && control.bgLoads.every((b) => !b), `[${name}] control: the proxy backgrounds do not load either`, JSON.stringify(control.bgs));
|
||||
|
||||
const fixed = await preview(browser, 'new');
|
||||
ok(fixed.origin === 'null' && fixed.sandbox === 'allow-scripts allow-popups allow-forms', `[${name}] fixed: the frame is STILL the sandboxed null-origin srcdoc (sandbox unchanged)`, `${fixed.origin} ${fixed.sandbox}`);
|
||||
ok(up(fixed).length >= 6 && up(fixed).every(([, v]) => v.w > 0 && v.src.startsWith('data:image/png;base64,')), `[${name}] fixed: every upload image (plain, +, space, unicode, HtmlBlock, srcset, logo) loads from a data: URL`, JSON.stringify(Object.fromEntries(up(fixed).map(([k, v]) => [k, [v.w, v.src.slice(0, 22)]]))));
|
||||
ok(fixed.bgs.length >= 2 && fixed.bgs.every((b) => b.startsWith('url("data:image/png')) && fixed.bgLoads.every(Boolean), `[${name}] fixed: BackgroundSection and CSS url() backgrounds are data: and load`, JSON.stringify(fixed.bgs));
|
||||
ok(fixed.poster?.startsWith('data:image/png') && fixed.icon?.startsWith('data:image/png'), `[${name}] fixed: video poster and favicon are inlined`, `${fixed.poster} ${fixed.icon}`);
|
||||
ok(fixed.imgs.missing?.w === 0 && fixed.imgs.missing.src.includes('/api/assets-proxy/?site_id=7&filename=does-not-exist.png'), `[${name}] fixed: a missing file keeps its proxy URL (no worse than before)`, JSON.stringify(fixed.imgs.missing));
|
||||
ok(fixed.imgs.other?.src.includes('site_id=8') && fixed.imgs.other.w === 0, `[${name}] fixed: another site's proxy URL is not fetched or inlined`, JSON.stringify(fixed.imgs.other));
|
||||
ok(fixed.link?.startsWith(ORIGIN + '/api/assets-proxy/') || fixed.link?.startsWith('/api/assets-proxy/'), `[${name}] fixed: an <a href> to an upload stays a link`, fixed.link);
|
||||
|
||||
const probe = await blobProbe(browser);
|
||||
ok(probe && probe.editorBlob === 0 && probe.tabBlob === 0 && probe.data > 0, `[${name}] measured: blob: from the editor window and from the Preview tab do NOT load in the null-origin frame; data: does`, JSON.stringify(probe));
|
||||
await browser.close();
|
||||
}
|
||||
srv.close();
|
||||
console.log(`\n${pass} passed, ${fail} failed, ${skip} skipped`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,31 @@
|
||||
// Bundled (esbuild) by scripts/e2e-sitesmith-cleaned.mjs: turns one ordinary Sitesmith response into a
|
||||
// published-style page, with or without the apply-time cleaner, through the real exporter.
|
||||
import { cleanAiResponse } from '../src/sitesmith/clean-ai-response';
|
||||
import { flattenTreeForCraft } from '../src/utils/craft-tree';
|
||||
import { exportToHtml } from '../src/utils/html-export';
|
||||
import { DEFAULT_SITE_DESIGN } from '../src/state/SiteDesignContext';
|
||||
import type { SitesmithResponse } from '../src/types/sitesmith';
|
||||
|
||||
const n = (type: string, props: Record<string, unknown>, nodes?: any[]) => ({ type: { resolvedName: type }, props, ...(nodes ? { nodes } : {}) });
|
||||
|
||||
export const RESPONSE: SitesmithResponse = {
|
||||
type: 'replace', scope: 'page', message: 'Built a page.',
|
||||
pages: [{ name: 'Home', tree: n('Container', { node_id: 'ROOT', tag: 'div' }, [
|
||||
n('Navbar', { node_id: 'nav', logoType: 'text', logoText: 'Brand', logoUrl: '/', links: [{ text: 'Home', href: '/' }, { text: 'Old link', href: 'javascript:void(0)' }] }),
|
||||
n('Heading', { node_id: 'h', text: 'Fresh bread every morning', level: 'h1' }),
|
||||
n('ImageBlock', { node_id: 'i1', src: 'assets/hero.png', alt: 'Our bakery' }),
|
||||
n('ImageBlock', { node_id: 'i2', src: 'https://example.com/photo.png', alt: 'Off-list host' }),
|
||||
n('ImageBlock', { node_id: 'i3', src: 'https://placehold.co/600x400?text=Team', alt: 'Placeholder' }),
|
||||
n('Container', { node_id: 'c', tag: 'div', style: { backgroundImage: 'url(https://example.com/bg.png)', padding: '24px' } }, [
|
||||
n('ButtonLink', { node_id: 'b', text: 'Book a table', href: 'https://example.com/book' }),
|
||||
]),
|
||||
n('VideoBlock', { node_id: 'v', videoUrl: 'https://example.com/clip.mp4' }),
|
||||
]) }],
|
||||
};
|
||||
|
||||
export function render(clean: boolean): string {
|
||||
const resp = clean ? cleanAiResponse(RESPONSE) : RESPONSE;
|
||||
if (resp.type !== 'replace') throw new Error('unexpected');
|
||||
const flat = flattenTreeForCraft(resp.pages[0].tree);
|
||||
return exportToHtml(JSON.stringify(flat.nodes), { title: 'Home', includeFonts: true, design: DEFAULT_SITE_DESIGN }).html;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser check (Firefox AND Chromium, headless) for the Sitesmith apply-time cleaner (G8): a page
|
||||
* published from a CLEANED model response loads nothing outside the allow-listed hosts and carries no
|
||||
* inline event handlers or javascript: URLs. The same response UNCLEANED is loaded as a control, to
|
||||
* show the check can see an off-list request. Nothing leaves the machine: every request is answered
|
||||
* or aborted by page.route (off-site requests are only recorded).
|
||||
* npm run test:browser:sitesmith-cleaned Env: CHROMIUM_PATH / FIREFOX_PATH
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-sitesmith-cleaned-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const tmp = path.join(os.tmpdir(), `wsb-ss-cleaned-${process.pid}.mjs`);
|
||||
fs.writeFileSync(tmp, out.outputFiles[0].text);
|
||||
const ent = await import(tmp);
|
||||
fs.rmSync(tmp, { force: true });
|
||||
|
||||
const SITE = 'http://site.test';
|
||||
// The published page's own head resources (fonts, Font Awesome) + the cleaner's image hosts.
|
||||
const ALLOWED_HOSTS = new Set(['site.test', 'fonts.googleapis.com', 'fonts.gstatic.com', 'cdnjs.cloudflare.com', 'placehold.co']);
|
||||
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
|
||||
|
||||
let pass = 0; let fail = 0;
|
||||
const ok = (c, m, d = '') => { if (c) { pass++; console.log('PASS ', m); } else { fail++; console.log('FAIL ', m, d); } };
|
||||
|
||||
async function load(browser, html) {
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
const hosts = new Set();
|
||||
await page.route('**/*', async (route) => {
|
||||
const u = new URL(route.request().url());
|
||||
hosts.add(u.hostname);
|
||||
if (u.origin === SITE) {
|
||||
if (u.pathname === '/' || u.pathname === '/index.html') return route.fulfill({ status: 200, contentType: 'text/html', body: html });
|
||||
if (u.pathname.startsWith('/assets/')) return route.fulfill({ status: 200, contentType: 'image/png', body: PNG });
|
||||
return route.fulfill({ status: 404, body: '' });
|
||||
}
|
||||
return route.abort(); // never contact a real host
|
||||
});
|
||||
await page.goto(SITE + '/', { waitUntil: 'load' });
|
||||
await page.waitForTimeout(300);
|
||||
const dom = await page.evaluate(() => {
|
||||
const handlers = [];
|
||||
const jsUrls = [];
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
for (const a of el.attributes) {
|
||||
if (/^on/i.test(a.name)) handlers.push(`${el.tagName}.${a.name}`);
|
||||
if (['href', 'src', 'action', 'formaction', 'poster', 'data'].includes(a.name) && /^\s*(javascript|vbscript|data):/i.test(a.value)) jsUrls.push(`${el.tagName}.${a.name}`);
|
||||
}
|
||||
}
|
||||
return { handlers, jsUrls, text: document.body.innerText };
|
||||
});
|
||||
await ctx.close();
|
||||
return { hosts: [...hosts].sort(), dom };
|
||||
}
|
||||
|
||||
for (const [name, launcher, exe] of [['chromium', chromium, process.env.CHROMIUM_PATH], ['firefox', firefox, process.env.FIREFOX_PATH]]) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const control = await load(browser, ent.render(false));
|
||||
ok(control.hosts.includes('example.com'), `[${name}] control (uncleaned): the check sees the off-list request to example.com`, JSON.stringify(control.hosts));
|
||||
const cleaned = await load(browser, ent.render(true));
|
||||
const offList = cleaned.hosts.filter((h) => !ALLOWED_HOSTS.has(h));
|
||||
ok(offList.length === 0, `[${name}] cleaned: no request outside the allow-listed hosts`, JSON.stringify(cleaned.hosts));
|
||||
ok(cleaned.hosts.includes('site.test'), `[${name}] cleaned: the site's own asset was requested`, JSON.stringify(cleaned.hosts));
|
||||
ok(cleaned.dom.handlers.length === 0, `[${name}] cleaned: no inline event handlers`, JSON.stringify(cleaned.dom.handlers));
|
||||
ok(cleaned.dom.jsUrls.length === 0, `[${name}] cleaned: no javascript:/data: URLs in URL attributes`, JSON.stringify(cleaned.dom.jsUrls));
|
||||
ok(/Fresh bread every morning/.test(cleaned.dom.text) && /Book a table/.test(cleaned.dom.text), `[${name}] cleaned: the ordinary content is all there`);
|
||||
await browser.close();
|
||||
}
|
||||
console.log(fail ? `\nFAILED (${fail})` : `\nALL PASS (${pass})`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser (Chromium, headless) regression for "Sitesmith layout: containers cannot be deleted".
|
||||
*
|
||||
* Applies REAL captured Sitesmith page responses (src/utils/__fixtures__/sitesmith-*-response.json)
|
||||
* through the real modal (mock backend, scripts/e2e-sitesmith-mock-server.mjs), then tries to delete
|
||||
* every generated column Container (ColumnLayout linked columns) and every Section inner area by
|
||||
* the context menu and by the Delete key. Each delete must either remove something or show a
|
||||
* visible notice -- never a silent no-op.
|
||||
*
|
||||
* npm run test:browser:sitesmith-delete
|
||||
*
|
||||
* Env: CHROMIUM_PATH, SITESMITH_E2E_DIST, SITESMITH_E2E_SKIP_BUILD=1, SITESMITH_SHOTS=<dir>
|
||||
*/
|
||||
import { chromium } from '@playwright/test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createMockServer } from './e2e-sitesmith-mock-server.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const distDir = path.resolve(process.env.SITESMITH_E2E_DIST || fs.mkdtempSync(path.join(os.tmpdir(), 'sitesmith-del-')));
|
||||
const shotsDir = path.resolve(process.env.SITESMITH_SHOTS || path.join(os.tmpdir(), 'sitesmith-delete-shots'));
|
||||
fs.mkdirSync(shotsDir, { recursive: true });
|
||||
if (!(process.env.SITESMITH_E2E_SKIP_BUILD && fs.existsSync(path.join(distDir, 'index.html')))) {
|
||||
console.log(`building editor -> ${distDir}`);
|
||||
const b = spawnSync('npx', ['vite', 'build', '--outDir', distDir, '--emptyOutDir'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
|
||||
if (b.status !== 0) { console.error(b.stdout, b.stderr); process.exit(2); }
|
||||
}
|
||||
const srv = await createMockServer({ distDir });
|
||||
const fixtures = ['sitesmith-ols-home-response.json', 'sitesmith-ttm-likes-response.json'];
|
||||
|
||||
let failures = 0;
|
||||
const ok = (label, cond, detail) => { if (!cond) failures++; console.log(`${cond ? 'PASS' : 'FAIL'} ${label}${!cond && detail !== undefined ? ` -- ${detail}` : ''}`); };
|
||||
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}) });
|
||||
|
||||
async function loadFixture(fx) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
||||
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, (route) => {
|
||||
const u = route.request().url();
|
||||
if (/\.css(\?|$)|fonts\.googleapis/.test(u)) return route.fulfill({ status: 200, contentType: 'text/css', body: '/* offline */' });
|
||||
return route.abort();
|
||||
});
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem('sitesmith.selfReview', 'off'); } catch (e) {} });
|
||||
const page = await ctx.newPage();
|
||||
page.__errors = [];
|
||||
page.on('pageerror', (e) => page.__errors.push(String(e)));
|
||||
page.on('console', (m) => { if (m.type() === 'error') page.__errors.push(m.text()); });
|
||||
await page.goto(srv.url + '/');
|
||||
await page.waitForSelector('.canvas-device-frame [data-craft-container]', { timeout: 20000 });
|
||||
const resp = JSON.parse(fs.readFileSync(path.join(root, 'src/utils/__fixtures__', fx), 'utf8'));
|
||||
srv.setNextResult(resp);
|
||||
await page.click('button.sitesmith-btn');
|
||||
await page.waitForSelector('textarea.sitesmith-textarea:not([disabled])', { timeout: 10000 });
|
||||
await page.fill('textarea.sitesmith-textarea', 'Build me a home page');
|
||||
await page.click('[role=dialog] button:has-text("→")');
|
||||
await page.waitForSelector('[data-wsb-cols]', { timeout: 30000 });
|
||||
await page.waitForTimeout(800);
|
||||
// close the modal
|
||||
await page.click('[role=dialog] button[aria-label=Close]');
|
||||
await page.waitForSelector('[role=dialog]', { state: 'detached', timeout: 5000 }).catch(() => {});
|
||||
await page.waitForTimeout(300);
|
||||
return page;
|
||||
}
|
||||
|
||||
/** Ids of every generated column Container (ColumnLayout children) and Section inner area, read
|
||||
* from the fixture itself (the flattener keeps `node_id` as the Craft id; Section inner = `<id>__section-inner`). */
|
||||
function targetsOf(resp) {
|
||||
const cols = [], inners = [];
|
||||
const walk = (n) => {
|
||||
const t = n?.type?.resolvedName;
|
||||
const kids = n?.nodes || [];
|
||||
if (t === 'ColumnLayout') cols.push({ layout: n.props.node_id, cols: kids.map((k) => k.props.node_id) });
|
||||
if (t === 'Section' && kids.length) inners.push(`${n.props.node_id}__section-inner`);
|
||||
kids.forEach(walk);
|
||||
};
|
||||
resp.pages.forEach((p) => walk(p.tree));
|
||||
return { cols, inners };
|
||||
}
|
||||
|
||||
const exists = (page, id) => page.locator(`[data-layer-id="${id}"]`).count().then((c) => c > 0);
|
||||
const notices = (page) => page.evaluate(() => [...document.querySelectorAll('[role=status],[role=alert]')].map((n) => n.textContent.trim()).filter(Boolean).join(' | '));
|
||||
const layerCount = (page) => page.locator('[data-layer-id]').count();
|
||||
|
||||
async function selectViaLayers(page, id) {
|
||||
const row = page.locator(`[data-layer-id="${id}"]`);
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await row.click();
|
||||
await page.waitForTimeout(120);
|
||||
}
|
||||
async function deleteVia(page, route) {
|
||||
if (route === 'delete-key') {
|
||||
await page.keyboard.press('Delete');
|
||||
} else {
|
||||
// Right-click on the canvas without a mousedown (which would re-select whatever is under the cursor).
|
||||
const box = await page.locator('.canvas-device-frame').boundingBox();
|
||||
await page.dispatchEvent('.canvas-device-frame', 'contextmenu', { clientX: box.x + 40, clientY: box.y + 40, bubbles: true });
|
||||
await page.waitForSelector('button:has-text("Select Parent")', { timeout: 3000 });
|
||||
const del = page.locator('button', { has: page.locator('span', { hasText: /^Delete$/ }) }).last();
|
||||
if (await del.isDisabled()) { await page.keyboard.press('Escape'); return 'disabled'; }
|
||||
await del.click();
|
||||
}
|
||||
await page.waitForTimeout(300);
|
||||
return 'clicked';
|
||||
}
|
||||
|
||||
for (const fx of fixtures) {
|
||||
const resp = JSON.parse(fs.readFileSync(path.join(root, 'src/utils/__fixtures__', fx), 'utf8'));
|
||||
const { cols, inners } = targetsOf(resp);
|
||||
const short = fx.replace(/sitesmith-|-response\.json/g, '');
|
||||
for (const route of ['context-menu', 'delete-key']) {
|
||||
const page = await loadFixture(fx);
|
||||
await page.click('button:has-text("Layers")');
|
||||
await page.waitForSelector('[data-layer-id]', { timeout: 5000 });
|
||||
if (route === 'context-menu') await page.screenshot({ path: path.join(shotsDir, `${short}-applied.png`) });
|
||||
const tag = `${short} ${route}`;
|
||||
let attempts = 0, removed = 0, explained = 0, silent = 0;
|
||||
const rows = [];
|
||||
// Columns: delete the LAST column, then the FIRST, of every layout (each has content in the others).
|
||||
for (const { layout, cols: ids } of cols) {
|
||||
const order = ids.length > 1 ? [ids[ids.length - 1], ids[0]] : [ids[0]];
|
||||
for (const id of order) {
|
||||
if (!(await exists(page, id))) { console.log(` (skip ${id}: not on canvas)`); continue; }
|
||||
await selectViaLayers(page, id);
|
||||
const n0 = await notices(page);
|
||||
const r = await deleteVia(page, route);
|
||||
attempts++;
|
||||
const gone = !(await exists(page, id));
|
||||
const n1 = await notices(page);
|
||||
if (gone) removed++; else if (n1 && n1 !== n0) explained++; else silent++;
|
||||
if (gone && route === 'delete-key' && ids.length >= 3 && id === ids[ids.length - 1]) {
|
||||
await page.locator(`[data-layer-id="${ids[0]}"]`).click();
|
||||
await page.waitForTimeout(200);
|
||||
await page.screenshot({ path: path.join(shotsDir, `${short}-${ids.length}to${ids.length - 1}-cols.png`) });
|
||||
}
|
||||
rows.push(`${id} (${ids.length} cols in ${layout}): ${gone ? `DELETED (canvas column boxes now ${await page.evaluate(() => [...document.querySelectorAll('.canvas-device-frame [data-wsb-cols]')].map((c) => c.children.length).join(','))})` : r === 'disabled' ? 'menu item disabled' : n1 && n1 !== n0 ? `notice "${n1}"` : 'SILENT NO-OP'}`);
|
||||
}
|
||||
}
|
||||
for (const id of inners) {
|
||||
if (!(await exists(page, id))) continue;
|
||||
const owner = id.replace(/__section-inner$/, '');
|
||||
await selectViaLayers(page, id);
|
||||
const n0 = await notices(page);
|
||||
const before = await layerCount(page);
|
||||
const r = await deleteVia(page, route);
|
||||
attempts++;
|
||||
const gone = !(await exists(page, id));
|
||||
const n1 = await notices(page);
|
||||
if (gone) removed++; else if (n1 && n1 !== n0) explained++; else silent++;
|
||||
if (!gone) await page.screenshot({ path: path.join(shotsDir, `${short}-${route}-inner-notice.png`) });
|
||||
rows.push(`${id} (Section inner): ${gone ? `DELETED (section gone=${!(await exists(page, owner))}, layers ${before}->${await layerCount(page)})` : r === 'disabled' ? 'menu item disabled' : n1 && n1 !== n0 ? `notice "${n1}"` : 'SILENT NO-OP'}`);
|
||||
break; // one Section is enough
|
||||
}
|
||||
rows.forEach((r) => console.log(' ' + r));
|
||||
await page.screenshot({ path: path.join(shotsDir, `${short}-${route}-after.png`) });
|
||||
ok(`${tag}: no silent no-op deletes (${attempts} tries, ${removed} deleted, ${explained} explained, ${silent} silent)`, silent === 0);
|
||||
ok(`${tag}: every generated column Container could be deleted`, rows.filter((r) => /cols in/.test(r)).every((r) => /DELETED/.test(r)));
|
||||
// Undo brings a deleted column back (one history step per delete).
|
||||
if (removed) {
|
||||
const before = await layerCount(page);
|
||||
await page.click('.canvas-device-frame', { position: { x: 5, y: 5 } }).catch(() => {});
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForTimeout(300);
|
||||
ok(`${tag}: undo restores the last delete`, (await layerCount(page)) > before, `${before} -> ${await layerCount(page)}`);
|
||||
}
|
||||
const fatal = page.__errors.filter((e) => /Invariant|Cannot delete|top-level|Delete failed|does not exist in resolver/i.test(e));
|
||||
ok(`${tag}: no delete errors in console`, fatal.length === 0, fatal.slice(0, 3).join(' || '));
|
||||
await page.context().close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
srv.close?.();
|
||||
console.log(failures ? `\n${failures} FAILED` : '\nALL PASS');
|
||||
process.exit(failures ? 1 : 0);
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* Used by scripts/e2e-sitesmith-editor-assets.mjs: reads {html,css} JSON on stdin and prints what the publish handler
|
||||
* (api/site-builder.php) sends on to generateCompiledHTML: the body and CSS after sb_rewrite_asset_urls(), then the compiled
|
||||
* document. Usage: php e2e-sitesmith-editor-assets-backend.php <backend repo dir>
|
||||
*/
|
||||
ob_start();
|
||||
define('SB_API_LIBRARY_ONLY', true);
|
||||
define('AUTH_USER', 'alice');
|
||||
define('HOME_DIR', '/docker/users/alice');
|
||||
require rtrim($argv[1], '/') . '/web-files/api/site-builder.php';
|
||||
ob_end_clean();
|
||||
$in = json_decode(stream_get_contents(STDIN), true);
|
||||
$body = sb_rewrite_asset_urls((string)$in['html']);
|
||||
$css = sb_rewrite_asset_urls((string)$in['css']);
|
||||
$U = 'https://example.com/';
|
||||
echo json_encode(['body' => $body, 'doc' => generateCompiledHTML('Home', $css, $body, '', [], '', [], $U, sb_canonical_url($U, 'index.html'))]);
|
||||
@@ -0,0 +1,48 @@
|
||||
// Bundled (esbuild) by scripts/e2e-sitesmith-editor-assets.mjs: one Sitesmith response that places uploads as
|
||||
// `assets/<file>`, run through the apply-time order (cleaner, then the editor-URL conversion) and exported the way the
|
||||
// editor canvas / Preview and a publish do. Three variants: as the model wrote it (the bug), converted (the fix), and
|
||||
// the same page as a manual AssetPicker insertion (the reference the fix must equal).
|
||||
import { cleanAiResponse } from '../src/sitesmith/clean-ai-response';
|
||||
import { toEditorAssetUrls, editorProxyUrl } from '../src/sitesmith/editor-asset-urls';
|
||||
import { flattenTreeForCraft } from '../src/utils/craft-tree';
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
import { DEFAULT_SITE_DESIGN } from '../src/state/SiteDesignContext';
|
||||
import type { SitesmithResponse } from '../src/types/sitesmith';
|
||||
|
||||
export const SITE_ID = 7;
|
||||
/** Real upload names. Upload() sanitises to [A-Za-z0-9_.-]; the other two arrive via FTP / stock import. */
|
||||
export const FILES = ['1700000000_aa11bb22_hero.png', '1700000001_bb22cc33_logo+v2.png', 'my photo.png', 'café.png'];
|
||||
export const MISSING = 'assets/does-not-exist.png';
|
||||
export const ASSETS = FILES.map((f) => ({ filename: f, relUrl: `assets/${f}`, url: editorProxyUrl(SITE_ID, f), width: 800, height: 600 }));
|
||||
// what the model writes: relUrl verbatim, but the cleaner only accepts [A-Za-z0-9._%~+-], so a space / unicode name arrives %-encoded
|
||||
const rel = (i: number) => 'assets/' + FILES[i].split('').map((c) => (/[A-Za-z0-9._~+-]/.test(c) ? c : encodeURIComponent(c))).join('');
|
||||
const n = (type: string, props: Record<string, unknown>, nodes?: any[]) => ({ type: { resolvedName: type }, props, ...(nodes ? { nodes } : {}) });
|
||||
|
||||
function page(src: (i: number) => string): SitesmithResponse {
|
||||
return { type: 'replace', scope: 'page', message: 'm', pages: [{ name: 'Home', tree: n('Container', { node_id: 'ROOT', tag: 'div' }, [
|
||||
n('Navbar', { node_id: 'nav', logoType: 'image', logoImage: src(1), logoUrl: '/', links: [{ text: 'Home', href: '/' }] }),
|
||||
n('BackgroundSection', { node_id: 'bg', bgImage: src(0), overlayOpacity: 0.2 }, [n('Heading', { node_id: 'h', text: 'Hello', level: 'h1' })]),
|
||||
n('ImageBlock', { node_id: 'i1', src: src(0), alt: 'plain' }),
|
||||
n('ImageBlock', { node_id: 'i2', src: src(1), alt: 'plus' }),
|
||||
n('ImageBlock', { node_id: 'i3', src: src(2), alt: 'space' }),
|
||||
n('ImageBlock', { node_id: 'i4', src: src(3), alt: 'unicode' }),
|
||||
n('Container', { node_id: 'c', tag: 'div', style: { minHeight: '60px', backgroundImage: `url(${src(0)})` } }),
|
||||
n('HtmlBlock', { node_id: 'html', code: `<img id="rich" src="${src(0)}" alt="rich">` }),
|
||||
n('ImageBlock', { node_id: 'i5', src: MISSING, alt: 'missing' }),
|
||||
]) }] };
|
||||
}
|
||||
|
||||
type Variant = 'bug' | 'fix' | 'manual';
|
||||
function tree(v: Variant) {
|
||||
// manual: the proxy URL is what the picker stores (no cleaner in that path); bug / fix: the model's `assets/<file>`, cleaned
|
||||
let resp: SitesmithResponse = v === 'manual' ? page((i) => ASSETS[i].url) : cleanAiResponse(page(rel));
|
||||
if (v === 'fix') resp = toEditorAssetUrls(resp, ASSETS, { siteId: SITE_ID }).resp;
|
||||
if (resp.type !== 'replace') throw new Error('unexpected');
|
||||
return JSON.stringify(flattenTreeForCraft(resp.pages[0].tree).nodes);
|
||||
}
|
||||
export function body(v: Variant): string { return exportBodyHtml(tree(v)).html; }
|
||||
/** The editor Preview / canvas document. */
|
||||
export function editorDoc(v: Variant): string {
|
||||
const state = tree(v);
|
||||
return exportComposedPreviewHtml(state, exportBodyHtml(state).html, { title: 'Home', includeFonts: false, design: DEFAULT_SITE_DESIGN });
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser check (Chromium AND Firefox, headless) that uploads Sitesmith places as `assets/<file>` actually LOAD in the
|
||||
* editor canvas / Preview (a srcdoc iframe on the panel origin, like Canvas.tsx), and that publishing still yields only
|
||||
* `assets/<file>`:
|
||||
* 1. control (the model's page as written): every upload <img> is broken (naturalWidth 0) -- the bug this guards against;
|
||||
* 2. fixed (cleaner then toEditorAssetUrls, the apply order): every upload <img> loads from the stub proxy for THIS site,
|
||||
* the background and CSS url() uploads are requested, a file that does not exist is left alone;
|
||||
* 3. publish: the fixed page run through the REAL backend sb_rewrite_asset_urls + generateCompiledHTML contains
|
||||
* `assets/<file>` only (no proxy URL, no site_id), is byte-identical to the same page inserted manually with the
|
||||
* AssetPicker, and the published document's images load from the site's own /assets/.
|
||||
* Nothing leaves the machine (page.route answers or aborts every request).
|
||||
* npm run test:browser:sitesmith-editor-assets Env: WHP_BACKEND_DIR (a whp worktree root), CHROMIUM_PATH / FIREFOX_PATH
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const BACKEND_DIR = process.env.WHP_BACKEND_DIR || '/workspace/whp-wt-editor-asset-urls';
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-sitesmith-editor-assets-entry.ts')],
|
||||
bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },
|
||||
});
|
||||
const tmp = path.join(os.tmpdir(), `wsb-ss-editor-assets-${process.pid}.mjs`);
|
||||
fs.writeFileSync(tmp, out.outputFiles[0].text);
|
||||
// HtmlBlock sanitising (DOMPurify) needs a DOM; a bare jsdom window is enough for the exporter. Set before the bundle loads.
|
||||
const { JSDOM } = await import('jsdom');
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>');
|
||||
globalThis.window = dom.window; globalThis.document = dom.window.document;
|
||||
const ent = await import(tmp);
|
||||
fs.rmSync(tmp, { force: true });
|
||||
|
||||
let pass = 0; let fail = 0; let skip = 0;
|
||||
const ok = (c, m, d = '') => { if (c) { pass++; console.log('PASS ', m); } else { fail++; console.log('FAIL ', m, d); } };
|
||||
|
||||
const PANEL = 'http://panel.test';
|
||||
const SITE = 'http://site.test';
|
||||
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
|
||||
const known = new Set(ent.FILES);
|
||||
|
||||
/** Load `doc` inside a srcdoc iframe on the panel origin (as the canvas does); answer the proxy like api/assets-proxy. */
|
||||
async function loadEditor(browser, doc) {
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
const reqs = [];
|
||||
await page.route('**/*', async (route) => {
|
||||
const u = new URL(route.request().url());
|
||||
reqs.push(u.pathname + u.search);
|
||||
if (u.origin !== PANEL) return route.abort();
|
||||
if (u.pathname === '/site-builder/') return route.fulfill({ status: 200, contentType: 'text/html', body: '<!doctype html><iframe id="f" style="width:900px;height:900px"></iframe>' });
|
||||
if (u.pathname === '/api/assets-proxy/') {
|
||||
// URLSearchParams decodes '+' as a space, exactly like PHP's $_GET
|
||||
const name = u.searchParams.get('filename');
|
||||
if (u.searchParams.get('site_id') === String(ent.SITE_ID) && known.has(name)) return route.fulfill({ status: 200, contentType: 'image/png', body: PNG });
|
||||
}
|
||||
return route.fulfill({ status: 404, body: '' });
|
||||
});
|
||||
await page.goto(PANEL + '/site-builder/', { waitUntil: 'load' });
|
||||
await page.evaluate((d) => { document.getElementById('f').srcdoc = d; }, doc);
|
||||
const frame = await (await page.waitForSelector('#f')).contentFrame();
|
||||
await frame.waitForSelector('img');
|
||||
await page.waitForTimeout(500);
|
||||
const imgs = await frame.evaluate(() => [...document.images].map((i) => ({ alt: i.alt, id: i.id, ok: i.complete && i.naturalWidth > 0 })));
|
||||
const bgs = await frame.evaluate(() => [...document.querySelectorAll('body *')].map((e) => getComputedStyle(e).backgroundImage).filter((b) => b && b !== 'none'));
|
||||
await ctx.close();
|
||||
return { imgs, reqs, bgs };
|
||||
}
|
||||
|
||||
/** Load the PUBLISHED document at the site root; /assets/<file> is served by decoded path. */
|
||||
async function loadPublished(browser, doc) {
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
await page.route('**/*', async (route) => {
|
||||
const u = new URL(route.request().url());
|
||||
if (u.origin !== SITE) return route.abort();
|
||||
if (u.pathname === '/') return route.fulfill({ status: 200, contentType: 'text/html', body: doc });
|
||||
if (u.pathname.startsWith('/assets/') && known.has(decodeURIComponent(u.pathname.slice(8)))) return route.fulfill({ status: 200, contentType: 'image/png', body: PNG });
|
||||
return route.fulfill({ status: 404, body: '' });
|
||||
});
|
||||
await page.goto(SITE + '/', { waitUntil: 'load' });
|
||||
await page.waitForTimeout(500);
|
||||
const imgs = await page.evaluate(() => [...document.images].map((i) => ({ alt: i.alt, ok: i.complete && i.naturalWidth > 0 })));
|
||||
await ctx.close();
|
||||
return imgs;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- publish through the real backend
|
||||
const haveBackend = fs.existsSync(path.join(BACKEND_DIR, 'web-files/api/site-builder.php'));
|
||||
function publish(variant) {
|
||||
const raw = execFileSync('php', [path.join(root, 'scripts/e2e-sitesmith-editor-assets-backend.php'), BACKEND_DIR], { input: JSON.stringify({ html: ent.body(variant), css: '' }), maxBuffer: 1 << 26 }).toString();
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
const WANT_REL = ['assets/1700000000_aa11bb22_hero.png', 'assets/1700000001_bb22cc33_logo%2Bv2.png', 'assets/my%20photo.png', 'assets/caf%C3%A9.png'];
|
||||
|
||||
// static checks first (no browser needed)
|
||||
const fixedBody = ent.body('fix');
|
||||
ok(!/src="assets\//.test(fixedBody) || /does-not-exist/.test(fixedBody), 'fixed editor HTML has no upload left as a relative assets/ src');
|
||||
ok(fixedBody.includes('assets/does-not-exist.png'), 'a file that is not an upload is left as written (asset-repair owns it)');
|
||||
ok(ent.body('bug').includes('assets/1700000000_aa11bb22_hero.png'), 'control still carries the relative reference (the bug exists without the conversion)');
|
||||
|
||||
let pub = null;
|
||||
if (haveBackend) {
|
||||
pub = publish('fix');
|
||||
const man = publish('manual');
|
||||
ok(WANT_REL.every((r) => pub.body.includes(r)), 'published body references every upload as assets/<rawurlencoded file>', pub.body.match(/assets\/[^"')]*/g)?.join(' '));
|
||||
ok(!/assets-proxy|site_id|serve_asset/.test(pub.body) && !/assets-proxy|site_id|serve_asset/.test(pub.doc), 'no editor-only URL leaks into the published HTML (body or document)');
|
||||
ok(pub.body === man.body, 'published body is byte-identical to a manual AssetPicker insertion');
|
||||
ok(pub.doc === man.doc, 'published document is byte-identical to a manual AssetPicker insertion');
|
||||
ok(pub.body.includes('does-not-exist.png'), 'published page still has the non-upload reference untouched');
|
||||
} else {
|
||||
skip++; console.log(`SKIP published-output checks: no backend at WHP_BACKEND_DIR=${BACKEND_DIR}`);
|
||||
}
|
||||
|
||||
for (const [name, launcher, exe] of [['chromium', chromium, process.env.CHROMIUM_PATH], ['firefox', firefox, process.env.FIREFOX_PATH]]) {
|
||||
let browser;
|
||||
try { browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) }); }
|
||||
catch (e) { skip++; console.log(`SKIP [${name}] browser not available: ${String(e.message).split('\n')[0]}`); continue; }
|
||||
const control = await loadEditor(browser, ent.editorDoc('bug'));
|
||||
const upl = (r) => r.imgs.filter((i) => ['plain', 'plus', 'space', 'unicode', 'rich'].includes(i.alt));
|
||||
ok(upl(control).length === 5 && upl(control).every((i) => !i.ok), `[${name}] control (as the model wrote it): all 5 upload images are BROKEN in the editor`, JSON.stringify(control.imgs));
|
||||
const fixed = await loadEditor(browser, ent.editorDoc('fix'));
|
||||
ok(upl(fixed).length === 5 && upl(fixed).every((i) => i.ok), `[${name}] fixed: all 5 upload images (plain, + , space, unicode, HtmlBlock) load in the editor (naturalWidth>0)`, JSON.stringify(fixed.imgs));
|
||||
const reqs = fixed.reqs.filter((r) => r.startsWith('/api/assets-proxy/'));
|
||||
ok(reqs.length >= 4 && reqs.every((r) => r.includes('site_id=' + ent.SITE_ID)), `[${name}] fixed: the proxy is requested for the CURRENT site only`, JSON.stringify(reqs));
|
||||
const proxyBgs = fixed.bgs.filter((b) => b.includes('/api/assets-proxy/?site_id=' + ent.SITE_ID));
|
||||
ok(proxyBgs.length >= 2, `[${name}] fixed: BackgroundSection bgImage and a CSS url() background both resolve to the proxy`, JSON.stringify(fixed.bgs));
|
||||
ok(!control.bgs.some((b) => b.includes('assets-proxy')) && control.bgs.length >= 2, `[${name}] control: those backgrounds point at the broken relative path`, JSON.stringify(control.bgs));
|
||||
ok(!fixed.reqs.some((r) => r.startsWith('/site-builder/assets/') && !r.includes('does-not-exist')), `[${name}] fixed: nothing asks the panel for /site-builder/assets/<upload>`, JSON.stringify(fixed.reqs));
|
||||
if (pub) {
|
||||
const p = await loadPublished(browser, pub.doc);
|
||||
const u = p.filter((i) => ['plain', 'plus', 'space', 'unicode', 'rich'].includes(i.alt));
|
||||
ok(u.length === 5 && u.every((i) => i.ok), `[${name}] published document: every upload image loads from the site's own /assets/`, JSON.stringify(p));
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
console.log(`\n${pass} passed, ${fail} failed, ${skip} skipped`);
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* Mock editor + Sitesmith backend for real-browser tests.
|
||||
*
|
||||
* Serves a BUILT editor (vite dist), injects window.WHP_CONFIG into index.html, answers
|
||||
* /api/site-builder.php (load/save/list_assets stubs) and implements the Sitesmith backend contract
|
||||
* (web-files/api/sitesmith.php, docs/sitesmith-backend.md) at /api/sitesmith.php?action=NAME.
|
||||
* No network access beyond 127.0.0.1; deterministic; every request is recorded.
|
||||
*
|
||||
* const srv = await createMockServer({ distDir, project });
|
||||
* srv.setNextResult({ type: 'patch', ops: [], message: 'x' }); // queue a job result
|
||||
* srv.starts // recorded `start` bodies
|
||||
* await srv.close();
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const MIME = {
|
||||
'.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.png': 'image/png',
|
||||
'.svg': 'image/svg+xml', '.json': 'application/json', '.woff2': 'font/woff2', '.map': 'application/json',
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ PNG helpers (also used by the test)
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const t = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; }
|
||||
return t;
|
||||
})();
|
||||
const crc32 = (buf) => { let c = 0xffffffff; for (const b of buf) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
||||
function chunk(type, data) {
|
||||
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
|
||||
const td = Buffer.concat([Buffer.from(type, 'ascii'), data]);
|
||||
const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(td));
|
||||
return Buffer.concat([len, td, crc]);
|
||||
}
|
||||
/** A valid solid-colour RGB PNG. */
|
||||
export function makePng(w = 32, h = 32, [r, g, b] = [99, 102, 241]) {
|
||||
const row = Buffer.alloc(1 + w * 3);
|
||||
for (let x = 0; x < w; x++) { row[1 + x * 3] = r; row[2 + x * 3] = g; row[3 + x * 3] = b; }
|
||||
const raw = Buffer.concat(Array.from({ length: h }, () => row));
|
||||
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
|
||||
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
function sniff(buf) {
|
||||
if (buf.length > 24 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
|
||||
return { mime: 'image/png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
||||
}
|
||||
if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
|
||||
let i = 2, width = null, height = null;
|
||||
while (i + 9 < buf.length) {
|
||||
if (buf[i] !== 0xff) { i++; continue; }
|
||||
const m = buf[i + 1];
|
||||
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) { height = buf.readUInt16BE(i + 5); width = buf.readUInt16BE(i + 7); break; }
|
||||
i += 2 + buf.readUInt16BE(i + 2);
|
||||
}
|
||||
return { mime: 'image/jpeg', width, height };
|
||||
}
|
||||
if (buf.length > 6 && buf.subarray(0, 3).toString() === 'GIF') return { mime: 'image/gif', width: null, height: null };
|
||||
if (buf.length > 12 && buf.subarray(0, 4).toString() === 'RIFF' && buf.subarray(8, 12).toString() === 'WEBP') return { mime: 'image/webp', width: null, height: null };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Minimal multipart/form-data parser: scans the raw body for the boundary. */
|
||||
function parseMultipart(buf, contentType) {
|
||||
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || '');
|
||||
if (!m) return [];
|
||||
const delim = Buffer.from('--' + (m[1] || m[2]));
|
||||
const parts = [];
|
||||
let pos = buf.indexOf(delim);
|
||||
while (pos !== -1) {
|
||||
const next = buf.indexOf(delim, pos + delim.length);
|
||||
if (next === -1) break;
|
||||
// part = [pos+delim+CRLF, next-CRLF)
|
||||
const part = buf.subarray(pos + delim.length + 2, next - 2);
|
||||
const sep = part.indexOf('\r\n\r\n');
|
||||
if (sep !== -1) {
|
||||
const head = part.subarray(0, sep).toString('utf8');
|
||||
const nameM = /name="([^"]*)"/.exec(head);
|
||||
const fileM = /filename="([^"]*)"/.exec(head);
|
||||
parts.push({ name: nameM ? nameM[1] : '', filename: fileM ? fileM[1] : null, data: part.subarray(sep + 4) });
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
const PHASES = ['queued', 'preparing', 'captioning', 'generating', 'finalizing'];
|
||||
|
||||
export const DEFAULT_PROJECT = (() => {
|
||||
const node = (resolvedName, props, nodes = [], parent = null, isCanvas = false, extra = {}) =>
|
||||
({ type: { resolvedName }, isCanvas, props, displayName: resolvedName, custom: {}, hidden: false, parent, nodes, linkedNodes: {}, ...extra });
|
||||
const craft = {
|
||||
ROOT: node('Container', { style: { minHeight: '400px', backgroundColor: '#ffffff' }, tag: 'div' }, ['sec1'], null, true),
|
||||
sec1: node('Container', { style: { backgroundColor: '#1e3a8a', padding: '40px' }, tag: 'section', node_id: 'sec1' }, ['head1'], 'ROOT', true),
|
||||
head1: node('Heading', { text: 'Original heading', level: 'h1', style: { color: '#ffffff', fontSize: '36px' }, node_id: 'head1' }, [], 'sec1'),
|
||||
};
|
||||
return {
|
||||
pages_craft_state: [{ id: 'home', name: 'Home', slug: 'index', craftState: JSON.stringify(craft) }],
|
||||
design: {},
|
||||
extras: {},
|
||||
};
|
||||
})();
|
||||
|
||||
export const DEFAULT_ASSETS = [
|
||||
{ filename: 'hero.png', caption: 'A wide blue banner photo', alt: 'Banner', width: 64, height: 32, color: [30, 58, 138] },
|
||||
{ filename: 'team.png', caption: 'The team standing outside the shop', alt: null, width: 48, height: 48, color: [16, 185, 129] },
|
||||
{ filename: 'logo.png', caption: null, alt: null, width: 32, height: 32, color: [245, 158, 11] },
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {{distDir: string, port?: number, project?: object, host?: string}} o
|
||||
*/
|
||||
export async function createMockServer(o) {
|
||||
const distDir = o.distDir;
|
||||
const project = o.project ?? DEFAULT_PROJECT;
|
||||
const csrf = 'x';
|
||||
const siteId = 1;
|
||||
|
||||
const s = {
|
||||
requests: [], // every request: {method, path, action, body?}
|
||||
starts: [], // parsed `start` bodies
|
||||
cancels: [], // parsed `cancel` bodies
|
||||
uploads: [], // {fields, name, size, mime, id}
|
||||
imageDeletes: [], // ids
|
||||
refCalls: [], // {action, body}
|
||||
clearCalls: [], // clear_history bodies
|
||||
saves: 0,
|
||||
};
|
||||
|
||||
// ---- scriptable state
|
||||
let vision = true;
|
||||
let phaseDelayMs = 300;
|
||||
let slow = false; // jobs stay in `generating` until release()/cancel
|
||||
let uploadFailStatus = 0; // non-zero: ref_image_upload answers this status with a JSON error
|
||||
let enabled = true;
|
||||
const results = []; // queued results for upcoming jobs
|
||||
const jobs = new Map(); // job_id -> job
|
||||
const images = new Map(); // id -> {meta, bytes, mime}
|
||||
let refs = [];
|
||||
let refSeq = 1;
|
||||
let activeJobId = null;
|
||||
|
||||
const defaultResult = () => ({
|
||||
ok: true,
|
||||
response: {
|
||||
type: 'replace', scope: 'section', message: 'Default mock result',
|
||||
pages: [{ name: 'Home', tree: { type: { resolvedName: 'Container' }, props: { node_id: 'mock-default', style: { padding: '20px' } }, nodes: [{ type: { resolvedName: 'Heading' }, props: { node_id: 'mock-default-h', text: 'Default mock heading', style: { color: '#111111' } }, nodes: [] }] } }],
|
||||
},
|
||||
});
|
||||
|
||||
const toResult = (r) => (r && typeof r === 'object' && 'ok' in r ? r : { ok: true, response: r });
|
||||
|
||||
// Thread history as the server keeps it: the user turn at start, the answer when the job finishes.
|
||||
const history = [];
|
||||
const msg = (role, content, type = null) => ({ role, content, response_type: type, created_at: new Date().toISOString() });
|
||||
|
||||
function newJob(result) {
|
||||
const id = crypto.randomBytes(8).toString('hex');
|
||||
const job = { id, created: Math.floor(Date.now() / 1000), startedAt: Date.now(), step: 0, lastAdvance: 0, status: 'running', result: toResult(result ?? results.shift() ?? defaultResult()), polls: 0 };
|
||||
jobs.set(id, job);
|
||||
return job;
|
||||
}
|
||||
|
||||
function stepJob(job) {
|
||||
job.polls++;
|
||||
if (job.status !== 'running') return;
|
||||
if (slow) { job.step = Math.min(Math.max(job.step, 1), 3); if (job.step < 3) job.step++; return; }
|
||||
const now = Date.now();
|
||||
if (now - job.lastAdvance < phaseDelayMs * 0.8) return;
|
||||
job.lastAdvance = now;
|
||||
job.step++;
|
||||
if (job.step >= PHASES.length) job.status = 'done';
|
||||
}
|
||||
|
||||
const jobView = (job) => {
|
||||
const phase = job.status === 'done' ? 'done' : job.status === 'cancelled' ? 'done' : PHASES[Math.min(job.step, PHASES.length - 1)];
|
||||
return { job_id: job.id, status: job.status, phase, elapsed_s: Math.floor((Date.now() - job.startedAt) / 1000), created_at: job.created };
|
||||
};
|
||||
|
||||
const imageMeta = (im) => im.meta;
|
||||
|
||||
// ---- public controls
|
||||
Object.assign(s, {
|
||||
/** Queue the result of the next job (a bare response object, or a full {ok,...} result). */
|
||||
setNextResult(resp, notes) { const r = toResult(resp); if (notes) r.notes = notes; results.push(r); },
|
||||
clearResults() { results.length = 0; },
|
||||
/** Queue a function (start body) => result, for a job whose answer depends on what the editor sent. */
|
||||
setNextResultFn(fn) { results.push(fn); },
|
||||
setPhaseDelayMs(ms) { phaseDelayMs = ms; },
|
||||
setSlow(v) { slow = !!v; },
|
||||
setVision(v) { vision = !!v; },
|
||||
setUploadFail(status) { uploadFailStatus = status | 0; },
|
||||
setEnabled(v) { enabled = !!v; },
|
||||
/** Pretend a job is already running (as after a page reload). It advances with polls like any job. */
|
||||
setActiveJob(o2 = {}) {
|
||||
const job = newJob(o2.result);
|
||||
if (o2.phase) job.step = Math.max(0, PHASES.indexOf(o2.phase));
|
||||
if (o2.elapsed_s) job.startedAt = Date.now() - o2.elapsed_s * 1000;
|
||||
activeJobId = job.id;
|
||||
return job.id;
|
||||
},
|
||||
/** Let a `setSlow(true)` job finish on its next poll. */
|
||||
release() { slow = false; for (const j of jobs.values()) if (j.status === 'running') j.step = PHASES.length - 1; },
|
||||
/** Forget refs/images/jobs/recordings between scenarios (keeps knobs at their defaults). */
|
||||
reset() {
|
||||
for (const k of ['requests', 'starts', 'cancels', 'uploads', 'imageDeletes', 'refCalls', 'clearCalls']) s[k].length = 0;
|
||||
history.length = 0;
|
||||
results.length = 0; jobs.clear(); images.clear(); refs = []; refSeq = 1; activeJobId = null;
|
||||
vision = true; phaseDelayMs = 300; slow = false; uploadFailStatus = 0; enabled = true;
|
||||
},
|
||||
get imageCount() { return images.size; },
|
||||
get storedImages() { return [...images.values()].map((i) => ({ ...i.meta, mime: i.mime })); },
|
||||
requestsTo(pathPrefix) { return s.requests.filter((r) => r.path.startsWith(pathPrefix)); },
|
||||
});
|
||||
|
||||
// ---- handlers
|
||||
const json = (res, code, body) => { res.statusCode = code; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(body)); };
|
||||
const readBody = (req) => new Promise((resolve) => { const c = []; req.on('data', (d) => c.push(d)); req.on('end', () => resolve(Buffer.concat(c))); });
|
||||
|
||||
async function sitesmith(req, res, u, action) {
|
||||
const isPost = req.method === 'POST';
|
||||
const raw = isPost ? await readBody(req) : Buffer.alloc(0);
|
||||
const ct = req.headers['content-type'] || '';
|
||||
const rec = { method: req.method, path: u.pathname, action, query: Object.fromEntries(u.searchParams) };
|
||||
s.requests.push(rec);
|
||||
if (isPost && req.headers['x-csrf-token'] !== csrf) return json(res, 403, { ok: false, error: 'csrf', message: 'Your session has expired. Refresh the page.' });
|
||||
let body = {};
|
||||
if (isPost && !ct.startsWith('multipart/')) { try { body = JSON.parse(raw.toString('utf8') || '{}'); } catch { return json(res, 400, { ok: false, error: 'bad_json', message: 'Bad request.' }); } }
|
||||
rec.body = body;
|
||||
|
||||
switch (action) {
|
||||
case 'entitlement':
|
||||
return json(res, 200, { ok: true, summary: { enabled, status: enabled ? 'OK_MONTHLY' : 'DISABLED', monthly_used: 0, monthly_cap: 50, bonus_credits: 0, resets_on: '2026-12-01' }, profile_supported: true, vision });
|
||||
case 'capabilities':
|
||||
return json(res, 200, {
|
||||
ok: true,
|
||||
vision: { available: vision, source: vision ? 'primary' : 'none', message: vision ? '' : 'Image features are not available on this server, so Sitesmith cannot look at pictures yet. Describing what you want in words works as usual.' },
|
||||
features: { mockups: vision, reference_screenshots: vision, captions: vision, self_review: vision },
|
||||
limits: { max_ref_images: 12, max_site_refs: 20, max_upload_bytes: 8388608, max_attach_images: 4 },
|
||||
});
|
||||
case 'history': {
|
||||
const aj = activeJobId ? jobs.get(activeJobId) : null;
|
||||
const live = aj && aj.status === 'running' ? jobView(aj) : null;
|
||||
return json(res, 200, { ok: true, messages: history.slice(), active_job: live ? { job_id: live.job_id, status: live.status, phase: live.phase, elapsed_s: live.elapsed_s, created_at: live.created_at } : null });
|
||||
}
|
||||
case 'job_active': {
|
||||
const aj = activeJobId ? jobs.get(activeJobId) : null;
|
||||
return json(res, 200, { ok: true, job: aj && aj.status === 'running' ? jobView(aj) : null });
|
||||
}
|
||||
case 'start': {
|
||||
s.starts.push(body);
|
||||
for (const j of jobs.values()) if (j.status === 'running') return json(res, 409, { ok: false, error: 'job_in_progress', status: 'JOB_IN_PROGRESS', message: 'Sitesmith is already working on a request for this site.', job_id: j.id });
|
||||
// a queued function computes the result from the start body (scenario 8n: the real WHP review lockdown)
|
||||
const job = newJob(typeof results[0] === 'function' ? toResult(results.shift()(body)) : undefined);
|
||||
activeJobId = job.id;
|
||||
history.push(msg('user', String(body.message ?? '')));
|
||||
return json(res, 200, { ok: true, job_id: job.id, status: 'running', phase: 'queued', created_at: job.created });
|
||||
}
|
||||
case 'poll': {
|
||||
const job = jobs.get(u.searchParams.get('job_id') || '');
|
||||
if (!job) return json(res, 404, { ok: false, error: 'job_not_found', message: 'That job could not be found.' });
|
||||
stepJob(job);
|
||||
const v = jobView(job);
|
||||
if (job.status === 'cancelled') return json(res, 200, { ...v, ok: true, result: { ok: false, status: 'CANCELLED', message: 'The request was cancelled.' } });
|
||||
if (job.status === 'done') {
|
||||
if (activeJobId === job.id) activeJobId = null;
|
||||
if (!job.logged) { job.logged = true; history.push(msg('assistant', JSON.stringify(job.result.response ?? job.result), job.result.response?.type ?? 'error')); }
|
||||
return json(res, 200, { ...v, ok: true, result: job.result });
|
||||
}
|
||||
return json(res, 200, { ...v, ok: true, retry_after_ms: phaseDelayMs });
|
||||
}
|
||||
case 'cancel': {
|
||||
s.cancels.push(body);
|
||||
const job = jobs.get(body.job_id);
|
||||
if (!job) return json(res, 404, { ok: false, error: 'job_not_found', message: 'That job could not be found.' });
|
||||
if (job.status === 'running') job.status = 'cancelled';
|
||||
if (activeJobId === job.id) activeJobId = null;
|
||||
return json(res, 200, { ok: true, status: job.status });
|
||||
}
|
||||
case 'refs_list':
|
||||
return json(res, 200, { ok: true, references: refs, images: [...images.values()].map(imageMeta) });
|
||||
case 'refs_add': {
|
||||
s.refCalls.push({ action, body });
|
||||
const now = new Date().toISOString();
|
||||
const r = { id: refSeq++, url_label: String(body.url_label ?? ''), what_i_like: String(body.what_i_like ?? ''), screenshot_ids: body.screenshot_ids ?? [], created_at: now, updated_at: now };
|
||||
refs.push(r);
|
||||
return json(res, 200, { ok: true, reference: r });
|
||||
}
|
||||
case 'refs_update': {
|
||||
s.refCalls.push({ action, body });
|
||||
const r = refs.find((x) => x.id === body.id);
|
||||
if (!r) return json(res, 404, { ok: false, error: 'not_found', message: 'Reference not found.' });
|
||||
for (const k of ['url_label', 'what_i_like', 'screenshot_ids']) if (k in body) r[k] = body[k];
|
||||
r.updated_at = new Date().toISOString();
|
||||
return json(res, 200, { ok: true, reference: r });
|
||||
}
|
||||
case 'refs_delete':
|
||||
s.refCalls.push({ action, body });
|
||||
refs = refs.filter((x) => x.id !== body.id);
|
||||
return json(res, 200, { ok: true });
|
||||
case 'review_render_upload':
|
||||
case 'ref_image_upload': {
|
||||
const parts = parseMultipart(raw, ct);
|
||||
const fields = Object.fromEntries(parts.filter((p) => p.filename === null).map((p) => [p.name, p.data.toString('utf8')]));
|
||||
const file = parts.find((p) => p.name === 'file' && p.filename !== null);
|
||||
s.uploads.push({ fields, name: file?.filename ?? null, size: file?.data.length ?? 0, head: file ? file.data.subarray(0, 4).toString('hex') : '' });
|
||||
if (uploadFailStatus) return json(res, uploadFailStatus, { ok: false, error: 'server_error', message: 'The server had a problem saving that picture. Try again in a minute.' });
|
||||
if (!file) return json(res, 400, { ok: false, error: 'no_file', message: 'No file was uploaded.' });
|
||||
const info = sniff(file.data);
|
||||
if (!info) return json(res, 415, { ok: false, error: 'unsupported_type', message: 'That file is not a picture Sitesmith can use. Use a JPEG, PNG, WebP or GIF.' });
|
||||
const id = crypto.randomBytes(16).toString('hex');
|
||||
const meta = { id, kind: action === 'review_render_upload' ? 'review_render' : fields.kind === 'screenshot' ? 'screenshot' : 'mockup', name: file.filename || 'image', width: info.width, height: info.height, size: file.data.length, created_at: new Date().toISOString() };
|
||||
images.set(id, { meta, bytes: file.data, mime: info.mime });
|
||||
s.uploads[s.uploads.length - 1].id = id;
|
||||
s.uploads[s.uploads.length - 1].mime = info.mime;
|
||||
s.uploads[s.uploads.length - 1].kind = meta.kind;
|
||||
return json(res, 200, { ok: true, image: meta });
|
||||
}
|
||||
case 'ref_image_delete':
|
||||
s.imageDeletes.push(body.id);
|
||||
images.delete(body.id);
|
||||
return json(res, 200, { ok: true });
|
||||
case 'ref_image': {
|
||||
const im = images.get(u.searchParams.get('id') || '');
|
||||
if (!im) { res.statusCode = 404; return res.end('nf'); }
|
||||
res.statusCode = 200; res.setHeader('content-type', im.mime); res.setHeader('x-content-type-options', 'nosniff');
|
||||
return res.end(im.bytes);
|
||||
}
|
||||
case 'clear_history': {
|
||||
s.clearCalls.push(body);
|
||||
// the real endpoint refuses while a job is live (it would orphan the answer)
|
||||
for (const j of jobs.values()) if (j.status === 'running') return json(res, 409, { ok: false, error: 'job_in_progress', message: 'Sitesmith is still working on your previous request for this site. Please wait for it to finish.' });
|
||||
const n = history.length; history.length = 0;
|
||||
return json(res, 200, { ok: true, cleared: n });
|
||||
}
|
||||
case 'assets':
|
||||
return json(res, 200, { ok: true, assets: DEFAULT_ASSETS.map((a) => ({ filename: a.filename, relUrl: `assets/${a.filename}`, url: `/mock-assets/${a.filename}`, width: a.width, height: a.height, caption: a.caption, alt: a.alt })) });
|
||||
default:
|
||||
return json(res, 400, { ok: false, error: 'unknown_action', message: 'Unknown action.' });
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const u = new URL(req.url, 'http://x');
|
||||
const action = u.searchParams.get('action') || '';
|
||||
if (u.pathname === '/api/sitesmith.php') return await sitesmith(req, res, u, action);
|
||||
s.requests.push({ method: req.method, path: u.pathname, action });
|
||||
if (u.pathname === '/api/site-builder.php') {
|
||||
if (req.method === 'POST') await readBody(req);
|
||||
if (action === 'load') return json(res, 200, { success: true, rev: 'r1', limits: {}, project });
|
||||
if (action === 'save') { s.saves++; return json(res, 200, { success: true, rev: 'r' + (s.saves + 1) }); }
|
||||
if (action === 'list_assets') return json(res, 200, { success: true, assets: [] });
|
||||
return json(res, 200, { success: true });
|
||||
}
|
||||
if (u.pathname.startsWith('/mock-assets/')) {
|
||||
const a = DEFAULT_ASSETS.find((x) => x.filename === path.basename(u.pathname));
|
||||
if (a) { res.setHeader('content-type', 'image/png'); return res.end(makePng(a.width, a.height, a.color)); }
|
||||
}
|
||||
const p = u.pathname === '/' ? '/index.html' : u.pathname;
|
||||
if (p === '/index.html') {
|
||||
const cfg = { user: 't', apiUrl: '/api/site-builder.php', csrfToken: csrf, siteId, siteDomain: 'olsdigital.com', siteName: 'OLS', backUrl: '/', isRoot: false };
|
||||
const h = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8').replace('</head>', () => `<script>window.WHP_CONFIG=${JSON.stringify(cfg)};</script></head>`);
|
||||
res.setHeader('content-type', 'text/html'); return res.end(h);
|
||||
}
|
||||
const f = path.join(distDir, path.normalize(p));
|
||||
if (f.startsWith(distDir) && fs.existsSync(f) && fs.statSync(f).isFile()) {
|
||||
res.setHeader('content-type', MIME[path.extname(f)] || 'application/octet-stream');
|
||||
return res.end(fs.readFileSync(f));
|
||||
}
|
||||
res.statusCode = 404; res.end('nf');
|
||||
} catch (e) {
|
||||
res.statusCode = 500; res.end(String(e));
|
||||
}
|
||||
});
|
||||
|
||||
await new Promise((resolve) => server.listen(o.port ?? 0, o.host ?? '127.0.0.1', resolve));
|
||||
s.port = server.address().port;
|
||||
s.url = `http://127.0.0.1:${s.port}`;
|
||||
s.close = () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()); });
|
||||
return s;
|
||||
}
|
||||
|
||||
// Standalone: node scripts/e2e-sitesmith-mock-server.mjs <distDir> [port]
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
const srv = await createMockServer({ distDir: path.resolve(process.argv[2] || 'dist'), port: Number(process.argv[3] || 0) });
|
||||
console.log('mock sitesmith server up', srv.url);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
/**
|
||||
* Used by scripts/e2e-sitesmith.mjs (scenario 8n): runs the REAL WHP review lockdown on what the editor sent.
|
||||
* stdin {summary, proposed:[ops with alias ids]} -> stdout {summary: server-rebuilt summary | null, alias, ops, dropped}
|
||||
* (api/sitesmith.php sitesmith_review_rebuild_summary + Sitesmith::reviewFilterOps). Offline, no model call.
|
||||
* Usage: php e2e-sitesmith-review-backend.php <backend repo dir>
|
||||
*/
|
||||
ob_start();
|
||||
define('SITESMITH_API_LIBRARY_ONLY', true);
|
||||
$dir = rtrim($argv[1], '/');
|
||||
require_once $dir . '/web-files/libs/Sitesmith.php';
|
||||
require $dir . '/web-files/api/sitesmith.php';
|
||||
ob_end_clean();
|
||||
$in = json_decode(stream_get_contents(STDIN), true);
|
||||
$rb = sitesmith_review_rebuild_summary((string)($in['summary'] ?? ''));
|
||||
$f = $rb === null ? ['ops' => [], 'dropped' => []] : Sitesmith::reviewFilterOps((array)($in['proposed'] ?? []), $rb['alias']);
|
||||
echo json_encode(['summary' => $rb['summary'] ?? null, 'alias' => $rb['alias'] ?? null, 'ops' => $f['ops'], 'dropped' => (object)$f['dropped']], JSON_UNESCAPED_SLASHES);
|
||||
@@ -0,0 +1,493 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Real-browser (Firefox AND Chromium, headless) end-to-end test of the Sitesmith modal.
|
||||
*
|
||||
* Builds the editor to a scratch dir, serves it from a mock server that implements the Sitesmith
|
||||
* backend contract (scripts/e2e-sitesmith-mock-server.mjs), and drives the REAL modal: job
|
||||
* start/poll/cancel/resume, mockup + reference upload, "Sites I like", asset awareness, contrast
|
||||
* repair, vision-unavailable mode and the one-round self-review (real html-to-image capture).
|
||||
* No real host or AI provider is contacted: every non-127.0.0.1 request is answered locally.
|
||||
*
|
||||
* npm run test:browser:sitesmith
|
||||
*
|
||||
* Env:
|
||||
* CHROMIUM_PATH / FIREFOX_PATH override the Playwright-pinned binaries
|
||||
* SITESMITH_E2E_DIST=<dir> where to build (default: a fresh temp dir)
|
||||
* SITESMITH_E2E_SKIP_BUILD=1 reuse an existing build in SITESMITH_E2E_DIST
|
||||
* SITESMITH_SHOTS=<dir> Firefox screenshots go here (default: <tmp>/sitesmith-shots)
|
||||
* SITESMITH_ONLY=chromium|firefox run one browser
|
||||
* SITESMITH_SCENARIO=3,5b run only these scenario ids
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createMockServer, makePng } from './e2e-sitesmith-mock-server.mjs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const distDir = path.resolve(process.env.SITESMITH_E2E_DIST || fs.mkdtempSync(path.join(os.tmpdir(), 'sitesmith-e2e-')));
|
||||
const shotsDir = path.resolve(process.env.SITESMITH_SHOTS || path.join(os.tmpdir(), 'sitesmith-shots'));
|
||||
fs.mkdirSync(shotsDir, { recursive: true });
|
||||
|
||||
if (!(process.env.SITESMITH_E2E_SKIP_BUILD && fs.existsSync(path.join(distDir, 'index.html')))) {
|
||||
console.log(`building editor -> ${distDir}`);
|
||||
const b = spawnSync('npx', ['vite', 'build', '--outDir', distDir, '--emptyOutDir'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
|
||||
if (b.status !== 0) { console.error(b.stdout, b.stderr); process.exit(2); }
|
||||
}
|
||||
|
||||
const srv = await createMockServer({ distDir });
|
||||
|
||||
// ------------------------------------------------------------------ result builders
|
||||
|
||||
const el = (name, props, nodes = []) => ({ type: { resolvedName: name }, props, nodes });
|
||||
const pageResult = (headingText, { id = 'new-h', color = '#ffffff', bg = '#0f172a', size = '36px', weight = '700' } = {}) => ({
|
||||
type: 'replace', scope: 'page', message: 'Built it.',
|
||||
pages: [{ name: 'Home', tree: el('Container', { node_id: 'new-root', style: { minHeight: '300px', backgroundColor: '#ffffff' } }, [
|
||||
el('Container', { node_id: id + '-sec', tag: 'section', style: { backgroundColor: bg, padding: '40px' } }, [
|
||||
el('Heading', { node_id: id, text: headingText, level: 'h1', style: { color, fontSize: size, fontWeight: weight } }),
|
||||
]),
|
||||
]) }],
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ harness
|
||||
|
||||
let failures = 0;
|
||||
const log = (b, s, ok, label, detail) => {
|
||||
if (!ok) failures++;
|
||||
console.log(`[${b}] ${ok ? 'PASS' : 'FAIL'} ${s}: ${label}${!ok && detail !== undefined ? ` -- ${detail}` : ''}`);
|
||||
};
|
||||
|
||||
const INIT = `(() => {
|
||||
window.__phases = []; window.__bad = [];
|
||||
const BAD = /NetworkError|Failed to fetch/;
|
||||
const scan = () => {
|
||||
const st = document.querySelector('[data-testid=ss-job-status]');
|
||||
if (st) {
|
||||
const ph = st.getAttribute('data-phase') + '|' + (st.querySelector('[data-testid=ss-phase-label]')?.textContent || '');
|
||||
if (window.__phases[window.__phases.length - 1] !== ph) window.__phases.push(ph);
|
||||
}
|
||||
for (const d of document.querySelectorAll('[role=dialog]')) {
|
||||
const t = d.textContent || '';
|
||||
const m = BAD.exec(t);
|
||||
if (m && window.__bad.length < 5) window.__bad.push(t.slice(Math.max(0, m.index - 40), m.index + 60));
|
||||
}
|
||||
};
|
||||
new MutationObserver(scan).observe(document, { subtree: true, childList: true, characterData: true, attributes: true });
|
||||
try { if (!window.__keepSelfReview) localStorage.setItem('sitesmith.selfReview', 'off'); } catch (e) {}
|
||||
})();`;
|
||||
|
||||
async function newPage(browser, name, { selfReview = false } = {}) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
||||
const external = [];
|
||||
await ctx.route(/^https?:\/\/(?!127\.0\.0\.1)/, (route) => {
|
||||
const u = route.request().url();
|
||||
external.push(u);
|
||||
if (/\.css(\?|$)|fonts\.googleapis/.test(u)) return route.fulfill({ status: 200, contentType: 'text/css', headers: { 'access-control-allow-origin': '*' }, body: '/* offline */' });
|
||||
return route.abort();
|
||||
});
|
||||
await ctx.addInitScript(selfReview ? `window.__keepSelfReview = true;${INIT}` : INIT);
|
||||
const page = await ctx.newPage();
|
||||
const errors = [];
|
||||
const seenUrls = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
page.on('request', (r) => seenUrls.push(r.url()));
|
||||
page.__errors = errors; page.__urls = seenUrls; page.__external = external; page.__ctx = ctx;
|
||||
await page.goto(srv.url + '/');
|
||||
await page.waitForSelector('.canvas-device-frame [data-craft-container]', { timeout: 20000 });
|
||||
await page.waitForTimeout(500);
|
||||
return page;
|
||||
}
|
||||
|
||||
async function openModal(page, { waitInput = true } = {}) {
|
||||
await page.click('button.sitesmith-btn');
|
||||
await page.waitForSelector('[role=dialog]', { timeout: 10000 });
|
||||
if (!waitInput) return;
|
||||
await page.waitForSelector('textarea.sitesmith-textarea:not([disabled])', { timeout: 10000 });
|
||||
}
|
||||
const sendMsg = async (page, text) => { await page.fill('textarea.sitesmith-textarea', text); await page.click('[role=dialog] button:has-text("→")'); };
|
||||
const canvasText = (page) => page.evaluate(() => document.querySelector('.canvas-device-frame')?.innerText ?? '');
|
||||
const waitCanvas = (page, text, timeout = 20000) =>
|
||||
page.waitForFunction((t) => (document.querySelector('.canvas-device-frame')?.innerText ?? '').includes(t), text, { timeout });
|
||||
const expandSection = async (page, id) => {
|
||||
const btn = page.locator(`[data-testid=ss-section-${id}] > button`);
|
||||
if ((await btn.getAttribute('aria-expanded')) !== 'true') await btn.click();
|
||||
};
|
||||
const modalShot = async (page, name, file) => { if (name === 'firefox') await page.screenshot({ path: path.join(shotsDir, file) }); };
|
||||
const contrastIn = (page, text) => page.evaluate((t) => {
|
||||
const lum = ([r, g, b]) => { const f = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b); };
|
||||
const rgba = (s) => { const m = s.match(/[\d.]+/g).map(Number); return { c: m.slice(0, 3), a: m.length > 3 ? m[3] : 1 }; };
|
||||
const h = [...document.querySelectorAll('.canvas-device-frame h1,.canvas-device-frame h2')].find((e) => e.textContent.includes(t));
|
||||
if (!h) return null;
|
||||
const fg = rgba(getComputedStyle(h).color);
|
||||
let bg = null;
|
||||
for (let n = h; n; n = n.parentElement) { const b = rgba(getComputedStyle(n).backgroundColor); if (b.a > 0.99) { bg = b.c; break; } }
|
||||
bg = bg || [255, 255, 255];
|
||||
const [a, b] = [lum(fg.c), lum(bg)];
|
||||
return { color: getComputedStyle(h).color, bg: `rgb(${bg.join(', ')})`, ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05) };
|
||||
}, text);
|
||||
|
||||
// ------------------------------------------------------------------ scenarios
|
||||
|
||||
const scenarios = [];
|
||||
const scenario = (id, title, fn, opts) => scenarios.push({ id, title, fn, opts });
|
||||
|
||||
scenario('1', 'start -> poll progress -> result applied', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('Brand new heading'));
|
||||
await openModal(page);
|
||||
await modalShot(page, name, '01-idle.png');
|
||||
await sendMsg(page, 'Build me a home page');
|
||||
await page.waitForSelector('[data-testid=ss-job-status][data-phase=generating]', { timeout: 15000 });
|
||||
await modalShot(page, name, '02-progress.png');
|
||||
await waitCanvas(page, 'Brand new heading');
|
||||
ok('result applied to the canvas', true);
|
||||
const phases = await page.evaluate(() => window.__phases);
|
||||
const names = phases.map((p) => p.split('|')[0]);
|
||||
ok('successive phases seen', ['queued', 'preparing', 'captioning', 'generating', 'finalizing'].filter((p) => names.includes(p)).length >= 4, JSON.stringify(phases));
|
||||
ok('phase labels are shown as text', phases.some((p) => /Designing your page/.test(p)) && phases.some((p) => /Preparing/.test(p)), JSON.stringify(phases));
|
||||
const body = srv.starts[0] ?? {};
|
||||
ok('start body has site_id', body.site_id === 1, JSON.stringify(body.site_id));
|
||||
ok('start body has design.primaryColor', typeof body.design?.primaryColor === 'string', JSON.stringify(body.design));
|
||||
ok('exactly one start (self-review off)', srv.starts.length === 1, String(srv.starts.length));
|
||||
});
|
||||
|
||||
scenario('2', 'cancel a slow job', async ({ page, name, ok }) => {
|
||||
srv.setSlow(true);
|
||||
srv.setNextResult(pageResult('Should never appear'));
|
||||
await openModal(page);
|
||||
const before = await canvasText(page);
|
||||
await sendMsg(page, 'Something slow');
|
||||
await page.waitForSelector('[data-testid=ss-cancel]', { timeout: 10000 });
|
||||
await page.waitForSelector('[data-testid=ss-job-status][data-phase=generating]', { timeout: 10000 });
|
||||
ok('input replaced by status (no textarea while running)', (await page.locator('textarea.sitesmith-textarea').count()) === 0);
|
||||
await modalShot(page, name, '09-running-disabled.png');
|
||||
await page.click('[data-testid=ss-cancel]');
|
||||
await page.waitForSelector('[data-testid=ss-note]', { timeout: 15000 });
|
||||
ok('mock recorded the cancel', srv.cancels.length === 1 && typeof srv.cancels[0].job_id === 'string', JSON.stringify(srv.cancels));
|
||||
const note = await page.textContent('[data-testid=ss-note]');
|
||||
ok('UI shows a Cancelled note', /Cancelled/.test(note ?? ''), note);
|
||||
ok('canvas unchanged', (await canvasText(page)) === before && !(await canvasText(page)).includes('Should never appear'));
|
||||
});
|
||||
|
||||
scenario('3', 'reload with an active job resumes it', async ({ page, ok }) => {
|
||||
srv.setActiveJob({ phase: 'generating', elapsed_s: 4, result: { ok: true, response: pageResult('Resumed heading') } });
|
||||
await page.reload();
|
||||
await page.waitForSelector('.canvas-device-frame [data-craft-container]', { timeout: 20000 });
|
||||
await openModal(page, { waitInput: false }); // a resumed job replaces the input box
|
||||
await page.waitForSelector('[data-testid=ss-job-status]', { timeout: 15000 });
|
||||
const txt = await page.textContent('[data-testid=ss-job-status]');
|
||||
ok('status shows the picked-up text', /Picked up a request that was already running/.test(txt ?? ''), txt);
|
||||
await waitCanvas(page, 'Resumed heading');
|
||||
ok('result applied after completion', true);
|
||||
ok('no new start was made', srv.starts.length === 0, String(srv.starts.length));
|
||||
});
|
||||
|
||||
scenario('4', 'mockup upload + client-side rejections', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('Mockup based heading'));
|
||||
await openModal(page);
|
||||
await expandSection(page, 'mockups');
|
||||
const input = page.locator('input[data-testid=ss-mockup-input]');
|
||||
await input.setInputFiles({ name: 'mock.png', mimeType: 'image/png', buffer: makePng(64, 48) });
|
||||
await page.waitForSelector('[data-testid=ss-mockup-item] img', { timeout: 10000 });
|
||||
ok('one upload reached the server', srv.uploads.length === 1 && !!srv.uploads[0].id, JSON.stringify(srv.uploads));
|
||||
await page.waitForFunction(() => { const i = document.querySelector('[data-testid=ss-mockup-item] img'); return i && i.complete && i.naturalWidth > 0; }, null, { timeout: 10000 });
|
||||
ok('thumbnail rendered from the server', true);
|
||||
await modalShot(page, name, '03-mockup-attached.png');
|
||||
|
||||
const alertText = () => page.locator('[data-testid=ss-mockups] [role=alert]').first().textContent();
|
||||
await input.setInputFiles({ name: 'x.png', mimeType: 'image/png', buffer: Buffer.from('this is plain text, not a picture at all') });
|
||||
await page.waitForSelector('[data-testid=ss-mockups] [role=alert]', { timeout: 5000 });
|
||||
const a1 = await alertText();
|
||||
ok('non-image rejected client-side with a message', !!a1 && a1.length > 5, a1);
|
||||
await page.waitForTimeout(400);
|
||||
ok('non-image never reached the server', srv.uploads.length === 1, String(srv.uploads.length));
|
||||
|
||||
await input.setInputFiles({ name: 'big.png', mimeType: 'image/png', buffer: Buffer.concat([makePng(8, 8), Buffer.alloc(9 * 1024 * 1024)]) });
|
||||
await page.waitForFunction((prev) => { const a = document.querySelector('[data-testid=ss-mockups] [role=alert]'); return a && a.textContent !== prev; }, a1, { timeout: 8000 }).catch(() => {});
|
||||
const a2 = await alertText();
|
||||
ok('oversize file rejected client-side with a message', !!a2 && /limit|8\.0 MB|too (large|big)/i.test(a2), a2);
|
||||
await page.waitForTimeout(400);
|
||||
ok('oversize never reached the server', srv.uploads.length === 1, String(srv.uploads.length));
|
||||
|
||||
await sendMsg(page, 'Build toward my mockup');
|
||||
await waitCanvas(page, 'Mockup based heading');
|
||||
ok('start body mockup_ids has the uploaded id', Array.isArray(srv.starts[0]?.mockup_ids) && srv.starts[0].mockup_ids.includes(srv.uploads[0].id), JSON.stringify(srv.starts[0]?.mockup_ids));
|
||||
});
|
||||
|
||||
scenario('5', 'Sites I like CRUD, selection, never fetched', async ({ page, name, ok }) => {
|
||||
const label = `${srv.url}/should-never-be-fetched`;
|
||||
srv.setNextResult(pageResult('Reference based heading'));
|
||||
await openModal(page);
|
||||
await expandSection(page, 'sites');
|
||||
await page.click('[data-testid=ss-sites-i-like] button:has-text("Add a site I like")');
|
||||
await page.fill('#ss-ref-url', label);
|
||||
await page.fill('#ss-ref-likes', 'Big photo header');
|
||||
await page.click('[data-testid=ss-ref-form] button:has-text("Add site")');
|
||||
await page.waitForSelector('[data-testid=ss-ref-item]', { timeout: 8000 });
|
||||
ok('added entry listed', (await page.locator('[data-testid=ss-ref-item]').count()) === 1);
|
||||
// edit
|
||||
await page.click('[data-testid=ss-ref-item] button:has-text("Edit")');
|
||||
await page.fill('#ss-ref-likes', 'Simple menu and white space');
|
||||
await page.click('[data-testid=ss-ref-form] button:has-text("Save changes")');
|
||||
await page.waitForFunction(() => document.querySelector('[data-testid=ss-ref-item]')?.textContent.includes('Simple menu'), null, { timeout: 8000 });
|
||||
ok('edit saved (refs_update sent, text changed)', srv.refCalls.some((c) => c.action === 'refs_update'));
|
||||
// a second entry, then delete it with confirmation
|
||||
await page.click('[data-testid=ss-sites-i-like] button:has-text("Add a site I like")');
|
||||
await page.fill('#ss-ref-url', 'second-example.test');
|
||||
await page.fill('#ss-ref-likes', 'Nice footer');
|
||||
await page.click('[data-testid=ss-ref-form] button:has-text("Add site")');
|
||||
await page.waitForFunction(() => document.querySelectorAll('[data-testid=ss-ref-item]').length === 2, null, { timeout: 8000 });
|
||||
const second = page.locator('[data-testid=ss-ref-item]', { hasText: 'second-example.test' });
|
||||
await second.locator('button:has-text("Delete")').click();
|
||||
ok('delete asks for confirmation first', (await page.locator('button:has-text("Confirm delete")').count()) === 1 && !srv.refCalls.some((c) => c.action === 'refs_delete'));
|
||||
await page.click('button:has-text("Confirm delete")');
|
||||
await page.waitForFunction(() => document.querySelectorAll('[data-testid=ss-ref-item]').length === 1, null, { timeout: 8000 });
|
||||
ok('delete removed the entry (refs_delete sent)', srv.refCalls.some((c) => c.action === 'refs_delete'));
|
||||
// select + copy + send
|
||||
await page.locator('[data-testid=ss-ref-item] input[type=checkbox]').check();
|
||||
const copy = page.locator('[data-testid=ss-sites-copy]');
|
||||
const copyTxt = (await copy.textContent()) ?? '';
|
||||
ok('"does not open, visit or fetch it" copy visible', (await copy.isVisible()) && /does not open, visit or fetch it/.test(copyTxt), copyTxt);
|
||||
await modalShot(page, name, '04-sites-i-like.png');
|
||||
await sendMsg(page, 'Use the sites I like');
|
||||
await waitCanvas(page, 'Reference based heading');
|
||||
const refId = srv.refCalls.find((c) => c.action === 'refs_add');
|
||||
ok('start body reference_ids has the selected id', Array.isArray(srv.starts[0]?.reference_ids) && srv.starts[0].reference_ids.length === 1, JSON.stringify(srv.starts[0]?.reference_ids));
|
||||
ok('the label was stored as given', !!refId && refId.body.url_label.includes('should-never-be-fetched'), JSON.stringify(refId?.body));
|
||||
ok('mock never received a request for the label', !srv.requests.some((r) => r.path.includes('should-never-be-fetched')));
|
||||
ok('the browser never requested the label', !page.__urls.some((u) => u.includes('should-never-be-fetched')));
|
||||
});
|
||||
|
||||
scenario('5b', 'asset awareness', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('Asset aware heading'));
|
||||
await openModal(page);
|
||||
await expandSection(page, 'assets');
|
||||
await page.waitForSelector('[data-testid=ss-asset-item]', { timeout: 8000 });
|
||||
ok('three assets listed', (await page.locator('[data-testid=ss-asset-item]').count()) === 3);
|
||||
const txt = (await page.textContent('[data-testid=ss-assets]')) ?? '';
|
||||
ok('captions shown', txt.includes('A wide blue banner photo') && txt.includes('No description yet'), txt.slice(0, 200));
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('[data-testid=ss-asset-item] img')].every((i) => i.complete && i.naturalWidth > 0), null, { timeout: 8000 });
|
||||
ok('thumbnails loaded from same-origin URLs', true);
|
||||
await page.locator('[data-testid=ss-asset-item]').nth(2).locator('input[type=checkbox]').uncheck();
|
||||
await modalShot(page, name, '05-asset-awareness.png');
|
||||
await sendMsg(page, 'Use my pictures');
|
||||
await waitCanvas(page, 'Asset aware heading');
|
||||
const b = srv.starts[0] ?? {};
|
||||
ok('use_assets stays true and the excluded asset is left out', b.use_assets === true && Array.isArray(b.asset_filenames) && b.asset_filenames.length === 2 && !b.asset_filenames.includes('logo.png'), JSON.stringify([b.use_assets, b.asset_filenames]));
|
||||
});
|
||||
|
||||
scenario('6', 'contrast repair', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('Contrast heading', { id: 'c-h', color: '#334155', bg: '#1e3a8a', size: '16px', weight: '400' }));
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'Make a blue banner');
|
||||
await waitCanvas(page, 'Contrast heading');
|
||||
const c = await contrastIn(page, 'Contrast heading');
|
||||
ok('heading found in canvas', !!c);
|
||||
ok('heading colour was changed from #334155', !!c && c.color !== 'rgb(51, 65, 85)', c?.color);
|
||||
ok('heading now passes 4.5:1 on its background', !!c && c.ratio >= 4.5, JSON.stringify(c));
|
||||
const adj = page.locator('[data-testid=ss-adjust]');
|
||||
await adj.waitFor({ timeout: 5000 });
|
||||
const t = (await adj.textContent()) ?? '';
|
||||
ok('adjustment summary visible and about readability', (await adj.isVisible()) && /text colou?rs? .*(adjusted|readab)|readab/i.test(t), t.slice(0, 200));
|
||||
await modalShot(page, name, '06-contrast-summary.png');
|
||||
});
|
||||
|
||||
scenario('7', 'vision unavailable', async ({ page, name, ok }) => {
|
||||
srv.setVision(false);
|
||||
srv.setNextResult(pageResult('Text only heading'));
|
||||
await openModal(page);
|
||||
await expandSection(page, 'mockups');
|
||||
await page.waitForSelector('[data-testid=ss-vision-note]', { timeout: 8000 });
|
||||
ok('vision note shown', await page.locator('[data-testid=ss-vision-note]').isVisible());
|
||||
ok('file input disabled', await page.locator('input[data-testid=ss-mockup-input]').evaluate((e) => e.disabled));
|
||||
ok('self-review toggle disabled', await page.locator('[data-testid=ss-selfreview-toggle] input').evaluate((e) => e.disabled && !e.checked));
|
||||
await modalShot(page, name, '07-vision-unavailable.png');
|
||||
await sendMsg(page, 'Just words please');
|
||||
await waitCanvas(page, 'Text only heading');
|
||||
ok('text-only send works end to end', srv.starts.length === 1 && !srv.starts[0].mockup_ids, JSON.stringify(srv.starts[0]?.mockup_ids));
|
||||
});
|
||||
|
||||
scenario('9', 'Clear chat: confirm clears the history (and stays cleared after reopening)', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('Heading before clearing'));
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'Please remember this line');
|
||||
await waitCanvas(page, 'Heading before clearing');
|
||||
const dlg = page.locator('[role=dialog]');
|
||||
await page.waitForFunction(() => (document.querySelector('[role=dialog]')?.textContent ?? '').includes('Please remember this line'), null, { timeout: 15000 });
|
||||
await page.waitForSelector('[role=dialog] button:has-text("Clear chat")', { timeout: 10000 });
|
||||
await page.click('[role=dialog] button:has-text("Clear chat")');
|
||||
ok('first click asks for confirmation (no request yet)', (await dlg.locator('button:has-text("Clear for everyone on this site?")').count()) === 1 && srv.clearCalls.length === 0, String(srv.clearCalls.length));
|
||||
await page.click('[role=dialog] button:has-text("Clear for everyone on this site?")');
|
||||
await page.waitForFunction(() => !(document.querySelector('[role=dialog]')?.textContent ?? '').includes('Please remember this line'), null, { timeout: 10000 }).catch(() => {});
|
||||
const txt = (await dlg.textContent()) ?? '';
|
||||
ok('confirm sends exactly one clear_history', srv.clearCalls.length === 1, String(srv.clearCalls.length));
|
||||
ok('the history is gone from the modal after the confirm', !txt.includes('Please remember this line'), txt.slice(0, 200));
|
||||
ok('no error shown', (await page.locator('[data-testid=ss-error]').count()) === 0);
|
||||
await page.click('[role=dialog] button[aria-label=Close]');
|
||||
await openModal(page);
|
||||
await page.waitForTimeout(800);
|
||||
ok('still cleared after closing and reopening the modal', !(((await page.locator('[role=dialog]').textContent()) ?? '').includes('Please remember this line')));
|
||||
await modalShot(page, name, '09-cleared.png');
|
||||
});
|
||||
|
||||
scenario('9b', 'Clear chat while a job is running: a plain message, nothing lost', async ({ page, ok }) => {
|
||||
srv.setNextResult(pageResult('First heading'));
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'First request');
|
||||
await waitCanvas(page, 'First heading');
|
||||
await page.waitForSelector('[role=dialog] button:has-text("Clear chat")', { timeout: 10000 });
|
||||
srv.setActiveJob({ phase: 'generating' });
|
||||
srv.setSlow(true);
|
||||
await page.click('[role=dialog] button:has-text("Clear chat")');
|
||||
await page.click('[role=dialog] button:has-text("Clear for everyone on this site?")');
|
||||
await page.waitForSelector('[data-testid=ss-error]', { timeout: 10000 });
|
||||
const err = (await page.textContent('[data-testid=ss-error]')) ?? '';
|
||||
ok('the refusal is a readable sentence, not an error code', /still working/i.test(err) && !/job_in_progress/.test(err), err);
|
||||
srv.release();
|
||||
});
|
||||
|
||||
scenario('9c', 'Clear chat is disabled while Sitesmith is working', async ({ page, ok }) => {
|
||||
srv.setNextResult(pageResult('Done heading'));
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'One');
|
||||
await waitCanvas(page, 'Done heading');
|
||||
await page.waitForSelector('[data-testid=ss-clear-chat]:not([disabled])', { timeout: 10000 });
|
||||
srv.setSlow(true);
|
||||
srv.setNextResult(pageResult('Later heading'));
|
||||
await sendMsg(page, 'Two');
|
||||
await page.waitForSelector('[data-testid=ss-job-status]', { timeout: 10000 });
|
||||
ok('while a job runs the button is disabled', await page.locator('[data-testid=ss-clear-chat]').isDisabled());
|
||||
srv.release();
|
||||
await waitCanvas(page, 'Later heading');
|
||||
await page.waitForSelector('[data-testid=ss-clear-chat]:not([disabled])', { timeout: 10000 });
|
||||
ok('enabled again when the job has finished', true);
|
||||
});
|
||||
|
||||
scenario('8', 'self-review round trip (one round)', async ({ page, name, ok }) => {
|
||||
srv.setNextResult(pageResult('First pass heading', { id: 'fp-h' }));
|
||||
srv.setNextResult({ type: 'patch', message: 'Fixed spacing.', ops: [{ op: 'update_props', node_id: 'fp-h', props: { text: 'Reviewed heading' } }] });
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'Build and then check it');
|
||||
await page.waitForSelector('[data-testid=ss-review-note]', { timeout: 45000 });
|
||||
const note = (await page.textContent('[data-testid=ss-review-note]')) ?? '';
|
||||
ok('review note says it made fixes', /made fixes/.test(note), note);
|
||||
await waitCanvas(page, 'Reviewed heading');
|
||||
ok('patch from the second job applied', true);
|
||||
ok('two start jobs', srv.starts.length === 2, String(srv.starts.length));
|
||||
const up = srv.uploads[0];
|
||||
ok('render uploaded through review_render_upload (kind review_render) as a JPEG named self-review-render.jpg, > 2000 bytes',
|
||||
!!up && up.mime === 'image/jpeg' && up.kind === 'review_render' && up.name === 'self-review-render.jpg' && up.size > 2000, JSON.stringify(up));
|
||||
const s2 = srv.starts[1] ?? {};
|
||||
ok('second job message starts "Review the attached screenshot"', typeof s2.message === 'string' && s2.message.startsWith('Review the attached screenshot'), String(s2.message).slice(0, 60));
|
||||
ok('second job is intent "review" carrying the upload id in review_image_ids (not mockup_ids)', s2.intent === 'review' && Array.isArray(s2.review_image_ids) && s2.review_image_ids.includes(up?.id) && !s2.mockup_ids, JSON.stringify({ intent: s2.intent, review_image_ids: s2.review_image_ids, mockup_ids: s2.mockup_ids }));
|
||||
ok('second job has use_assets false', s2.use_assets === false, String(s2.use_assets));
|
||||
ok('render image deleted afterwards', srv.imageDeletes.includes(up?.id), JSON.stringify(srv.imageDeletes));
|
||||
await page.waitForTimeout(2500);
|
||||
ok('no third job', srv.starts.length === 2, String(srv.starts.length));
|
||||
await modalShot(page, name, '08-self-review-done.png');
|
||||
}, { selfReview: true });
|
||||
|
||||
// Round 6 (live 2026.11.10): the review summary listed only top-level sections (children of Section/ColumnLayout live
|
||||
// in Craft linkedNodes), so every proposal was stripped. A NESTED page is built in the real editor, the real
|
||||
// summarizeCanvas() output goes through the REAL WHP review lockdown (php: sitesmith_review_rebuild_summary +
|
||||
// Sitesmith::reviewFilterOps, WHP_BACKEND_DIR), the "model" patches the nested heading by its server alias, and the
|
||||
// edit must take effect on the canvas while a link/text edit, an unknown id and a delete are dropped with reasons.
|
||||
const WHP_BACKEND_DIR = process.env.WHP_BACKEND_DIR || '/workspace/whp-wt-sitesmith-r6';
|
||||
scenario('8n', 'self-review patches a NESTED node through the real WHP review lockdown', async ({ page, name, ok }) => {
|
||||
const info = [];
|
||||
// console values as JSON (Firefox prints an object argument as "JSHandle@object" in text())
|
||||
page.on('console', async (m) => { if (m.type() === 'info') info.push((await Promise.all(m.args().map((x) => x.jsonValue().catch(() => null)))).map((v) => (typeof v === 'string' ? v : JSON.stringify(v))).join(' ')); });
|
||||
srv.setNextResult({ type: 'replace', scope: 'page', message: 'Built it.', pages: [{ name: 'Home', tree: el('Container', { node_id: 'nr-root', style: { padding: '0px' } }, [
|
||||
el('Section', { node_id: 'nr-sec', aiName: 'Hero', style: { backgroundColor: '#0f172a', paddingTop: '48px', paddingBottom: '48px' } }, [
|
||||
el('Heading', { node_id: 'nr-h', text: 'Nested review heading', level: 'h1', style: { color: '#ffffff', fontSize: '40px' } }),
|
||||
el('ColumnLayout', { node_id: 'nr-cols', columns: 2 }, [
|
||||
el('Container', { node_id: 'nr-c1' }, [el('ButtonLink', { node_id: 'nr-btn', text: 'Nested button', href: '/contact', style: { backgroundColor: '#fde047', color: '#0f172a' } })]),
|
||||
el('Container', { node_id: 'nr-c2' }, [el('TextBlock', { node_id: 'nr-t', text: 'Second column', style: { color: '#ffffff' } })]),
|
||||
]),
|
||||
]),
|
||||
]) }] });
|
||||
let backend = null;
|
||||
srv.setNextResultFn((body) => {
|
||||
const alias = (real) => Object.entries(backend?.alias ?? {}).find(([, r]) => r === real)?.[0] ?? 'missing';
|
||||
backend = JSON.parse(execFileSync('php', [path.join(root, 'scripts/e2e-sitesmith-review-backend.php'), WHP_BACKEND_DIR], { input: JSON.stringify({ summary: body.canvas_summary, proposed: [] }) }).toString());
|
||||
const proposed = [
|
||||
{ op: 'update_props', node_id: alias('nr-h'), props: { style: { color: '#fde047' } } },
|
||||
{ op: 'update_props', node_id: alias('nr-btn'), props: { href: 'https://evil.example/x', text: 'Hacked' } },
|
||||
{ op: 'update_props', node_id: 'n999', props: { style: { color: '#ff0000' } } },
|
||||
{ op: 'delete_node', node_id: alias('nr-t') },
|
||||
];
|
||||
const f = JSON.parse(execFileSync('php', [path.join(root, 'scripts/e2e-sitesmith-review-backend.php'), WHP_BACKEND_DIR], { input: JSON.stringify({ summary: body.canvas_summary, proposed }) }).toString());
|
||||
backend = { ...backend, filtered: f };
|
||||
return { ok: true, response: { type: 'patch', message: 'Recoloured the hero heading.', ops: f.ops }, review_ops: { proposed: proposed.length, kept: f.ops.length, dropped: f.dropped } };
|
||||
});
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'Build my hero and check it');
|
||||
await page.waitForSelector('[data-testid=ss-review-note]', { timeout: 45000 });
|
||||
const note = (await page.textContent('[data-testid=ss-review-note]')) ?? '';
|
||||
const sent = srv.starts[1]?.canvas_summary ?? '';
|
||||
ok('the editor summary lists the NESTED nodes (heading, button, column text inside the Section)', /id=nr-h /.test(sent) && /id=nr-btn /.test(sent) && /id=nr-t /.test(sent), sent.slice(0, 600));
|
||||
const hLine = (backend?.summary ?? '').split('\n').find((l) => / id=n\d+ \{style\.color=#ffffff, style\.fontSize=40px, level=h1\}$/.test(l)) ?? '';
|
||||
ok('the WHP-rebuilt summary shows the heading indented under its Section, with its colour, without its text', /^ {4,}- Heading id=n\d+ /.test(hLine) && !/Nested review heading|Nested button|contact/.test(backend?.summary ?? ''), backend?.summary);
|
||||
ok('WHP kept exactly the nested heading edit, mapped back to its real id', JSON.stringify(backend?.filtered?.ops) === JSON.stringify([{ op: 'update_props', node_id: 'nr-h', props: { style: { color: '#fde047' } } }]), JSON.stringify(backend?.filtered));
|
||||
await page.waitForFunction(() => {
|
||||
const h = [...document.querySelectorAll('.canvas-device-frame h1')].find((e) => e.textContent.includes('Nested review heading'));
|
||||
return h && getComputedStyle(h).color === 'rgb(253, 224, 71)';
|
||||
}, null, { timeout: 10000 }).then(() => ok('the nested heading really changed colour on the canvas', true), (e) => ok('the nested heading really changed colour on the canvas', false, String(e).slice(0, 120)));
|
||||
const btn = await page.evaluate(() => { const a = [...document.querySelectorAll('.canvas-device-frame a')].find((e) => /Nested button|Hacked/.test(e.textContent)); return a ? { text: a.textContent.trim(), href: a.getAttribute('href') } : null; });
|
||||
ok('the button text and link were NOT changed (forbidden for a review)', btn?.text === 'Nested button' && btn?.href === '/contact', JSON.stringify(btn));
|
||||
ok('the column text was NOT deleted', (await canvasText(page)).includes('Second column'));
|
||||
ok('the note says it made fixes and why the rest were dropped', /made fixes/.test(note) && note.includes('3 did not pass the safety checks (1 named a part that is not on the page, 1 tried to change text, a link or an image, 1 tried to add, remove or replace a block)'), note);
|
||||
const logLine = info.find((t) => t.startsWith('[sitesmith] self-review dropped ops')) ?? '';
|
||||
ok('the console logs the drop counts, without any of the model\'s words', /unknown_id/.test(logLine) && !/evil|Hacked|Recoloured/.test(info.join(' ')), logLine);
|
||||
await modalShot(page, name, '08n-nested-review.png');
|
||||
}, { selfReview: true });
|
||||
|
||||
scenario('8b', 'self-review skipped when the upload fails', async ({ page, ok }) => {
|
||||
srv.setUploadFail(500);
|
||||
srv.setNextResult(pageResult('Kept first pass', { id: 'kp-h' }));
|
||||
await openModal(page);
|
||||
await sendMsg(page, 'Build it');
|
||||
await page.waitForSelector('[data-testid=ss-review-note]', { timeout: 45000 });
|
||||
const note = (await page.textContent('[data-testid=ss-review-note]')) ?? '';
|
||||
ok('non-blocking "Self-review skipped" note', /Self-review skipped/.test(note), note);
|
||||
ok('first job content still applied', (await canvasText(page)).includes('Kept first pass'));
|
||||
ok('no second job', srv.starts.length === 1, String(srv.starts.length));
|
||||
ok('no blocking error shown', (await page.locator('[data-testid=ss-error]').count()) === 0);
|
||||
}, { selfReview: true });
|
||||
|
||||
// ------------------------------------------------------------------ run
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
for (const sc of scenarios) {
|
||||
if (process.env.SITESMITH_SCENARIO && !process.env.SITESMITH_SCENARIO.split(',').includes(sc.id)) continue;
|
||||
srv.reset();
|
||||
const label = `${sc.id} ${sc.title}`;
|
||||
let page;
|
||||
try {
|
||||
page = await newPage(browser, name, sc.opts);
|
||||
await sc.fn({ page, name, ok: (l, c, d) => log(name, label, !!c, l, d) });
|
||||
await page.waitForTimeout(200);
|
||||
const bad = await page.evaluate(() => window.__bad);
|
||||
log(name, label, page.__errors.length === 0, 'no uncaught page errors', page.__errors.join(' | '));
|
||||
log(name, label, bad.length === 0, 'no NetworkError / Failed to fetch text in the modal', JSON.stringify(bad));
|
||||
const ext = page.__external.filter((u) => !/\.css(\?|$)|fonts\.(googleapis|gstatic)/.test(u));
|
||||
if (ext.length) console.log(`[${name}] note ${label}: ${ext.length} external request(s) aborted locally`);
|
||||
} catch (e) {
|
||||
log(name, label, false, 'scenario completed', String(e?.message ?? e).split('\n').slice(0, 3).join(' '));
|
||||
if (page && name === 'firefox') await page.screenshot({ path: path.join(shotsDir, `fail-${sc.id}.png`) }).catch(() => {});
|
||||
} finally {
|
||||
await page?.__ctx.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const only = process.env.SITESMITH_ONLY;
|
||||
if (only !== 'firefox') await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (only !== 'chromium') await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
await srv.close();
|
||||
console.log(failures ? `\n${failures} FAILURE(S)` : '\nALL PASS');
|
||||
process.exit(failures ? 1 : 0);
|
||||
@@ -0,0 +1,9 @@
|
||||
// Test helper: freeze the wall clock for a child process. FAKE_NOW=<ISO date> (node -r this).
|
||||
const RealDate = Date;
|
||||
const fixed = new RealDate(process.env.FAKE_NOW).getTime();
|
||||
if (!Number.isFinite(fixed)) throw new Error('FAKE_NOW must be a valid ISO date');
|
||||
class FakeDate extends RealDate {
|
||||
constructor(...a) { if (a.length === 0) super(fixed); else super(...a); }
|
||||
static now() { return fixed; }
|
||||
}
|
||||
globalThis.Date = FakeDate;
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Sitesmith catalog generator.
|
||||
*
|
||||
* Reads the editor's REAL definitions (component resolver + craft defaults, TS
|
||||
* prop types, section families, templates, palettes, design tokens, Font
|
||||
* Awesome helper, animation keyframes) and emits ONE compact, deterministic
|
||||
* JSON file the WHP panel's Sitesmith prompt builder loads.
|
||||
*
|
||||
* node scripts/gen-sitesmith-catalog.mjs --out ../../whp/web-files/libs/sitesmith-catalog.generated.json
|
||||
* node scripts/gen-sitesmith-catalog.mjs --stdout # print (used by the drift test)
|
||||
*
|
||||
* The drift test (src/sitesmith-catalog.drift.test.ts) regenerates and compares
|
||||
* to the committed file (path: $SITESMITH_CATALOG_FILE, default
|
||||
* ../../whp/web-files/libs/sitesmith-catalog.generated.json relative to craft/),
|
||||
* so a component/prop/section/template change that is not regenerated fails.
|
||||
*
|
||||
* Curated, human-written facts (one-line purpose, usage tips) live in
|
||||
* scripts/sitesmith-catalog/notes.mjs; a component with no note fails the build.
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import ts from 'typescript';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { NOTES, GLOBAL_NOTES } from './sitesmith-catalog/notes.mjs';
|
||||
|
||||
const craftRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const rel = (...p) => path.join(craftRoot, ...p);
|
||||
|
||||
/** Props every component shares; reported once in `common`, not per component. */
|
||||
const COMMON_PROPS = new Set(['style', 'animation', 'animationDelay', 'hideOnDesktop', 'hideOnTablet', 'hideOnMobile', 'aiName', 'node_id']);
|
||||
|
||||
async function loadRuntime() {
|
||||
const outfile = path.join(fs.mkdtempSync(path.join(process.env.TMPDIR || '/tmp', 'sscat-')), 'runtime.cjs');
|
||||
const res = await build({
|
||||
entryPoints: [rel('scripts/sitesmith-catalog/runtime-entry.ts')],
|
||||
bundle: true, write: false, format: 'cjs', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
});
|
||||
fs.writeFileSync(outfile, res.outputFiles[0].text);
|
||||
const data = createRequire(import.meta.url)(outfile).collect();
|
||||
fs.rmSync(path.dirname(outfile), { recursive: true, force: true });
|
||||
return data;
|
||||
}
|
||||
|
||||
function componentFiles() {
|
||||
const resolver = fs.readFileSync(rel('src/components/resolver.ts'), 'utf8');
|
||||
const map = {};
|
||||
for (const m of resolver.matchAll(/import \{ (\w+) \} from '\.\/([\w/]+)';/g)) map[m[1]] = rel('src/components', m[2] + '.tsx');
|
||||
return map;
|
||||
}
|
||||
|
||||
function typeInfo(checker, sym, decl) {
|
||||
const t = checker.getTypeOfSymbolAtLocation(sym, decl);
|
||||
const nn = checker.getNonNullableType(t);
|
||||
let text = checker.typeToString(nn, undefined, ts.TypeFormatFlags.NoTruncation);
|
||||
const parts = nn.isUnion() ? nn.types : [nn];
|
||||
const lits = parts.filter((p) => p.isStringLiteral()).map((p) => p.value);
|
||||
const out = {};
|
||||
if (lits.length && lits.length === parts.length) { out.type = 'enum'; out.enum = lits.sort(); return out; }
|
||||
if (lits.length && parts.every((p) => p.isStringLiteral() || (p.flags & ts.TypeFlags.String))) { out.type = 'string'; out.suggested = lits.sort(); return out; }
|
||||
if (nn.flags & ts.TypeFlags.String) out.type = 'string';
|
||||
else if (nn.flags & ts.TypeFlags.Number) out.type = 'number';
|
||||
else if (nn.flags & ts.TypeFlags.BooleanLike || text === 'boolean') out.type = 'boolean';
|
||||
else if (checker.isArrayType(nn)) {
|
||||
out.type = 'array';
|
||||
const el = checker.getTypeArguments(nn)[0];
|
||||
const props = el ? checker.getPropertiesOfType(el) : [];
|
||||
if (props.length) {
|
||||
out.item = {};
|
||||
for (const p of props) {
|
||||
const pt = checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(p, decl));
|
||||
const pu = pt.isUnion() ? pt.types : [pt];
|
||||
const pl = pu.filter((x) => x.isStringLiteral()).map((x) => x.value);
|
||||
let k = checker.typeToString(pt, undefined, ts.TypeFormatFlags.NoTruncation);
|
||||
if (pl.length && pl.length === pu.length) k = pl.sort().join('|');
|
||||
if (p.flags & ts.SymbolFlags.Optional) k += '?';
|
||||
out.item[p.name] = k;
|
||||
}
|
||||
} else out.item = checker.typeToString(el, undefined, ts.TypeFormatFlags.NoTruncation);
|
||||
} else if (nn.flags & ts.TypeFlags.Object) out.type = 'object';
|
||||
else out.type = text.length > 60 ? 'any' : text;
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractProps(program, file, name) {
|
||||
const checker = program.getTypeChecker();
|
||||
const sf = program.getSourceFile(file);
|
||||
if (!sf) throw new Error(`catalog: cannot read ${file}`);
|
||||
let propsType = null; let decl0 = null;
|
||||
sf.forEachChild((n) => {
|
||||
if (!ts.isVariableStatement(n)) return;
|
||||
for (const d of n.declarationList.declarations) {
|
||||
if (d.name.getText() !== name || !d.type || !ts.isTypeReferenceNode(d.type) || !d.type.typeArguments?.length) continue;
|
||||
propsType = checker.getTypeFromTypeNode(d.type.typeArguments[0]); decl0 = d;
|
||||
}
|
||||
});
|
||||
if (!propsType) throw new Error(`catalog: ${name}: expected "export const ${name}: UserComponent<Props>" in ${file}`);
|
||||
const out = {};
|
||||
for (const sym of checker.getPropertiesOfType(propsType)) {
|
||||
const optional = !!(sym.flags & ts.SymbolFlags.Optional);
|
||||
out[sym.name] = { ...typeInfo(checker, sym, decl0), optional };
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defaults computed from the wall clock when the editor module loads (Countdown.targetDate
|
||||
* = today + 30 days). Emitting them would make the generated catalog (and the drift test)
|
||||
* change every day and would teach the model a stale "default" date, so they are omitted
|
||||
* from the catalog entirely.
|
||||
*/
|
||||
const VOLATILE_DEFAULTS = new Set(['Countdown.targetDate']);
|
||||
|
||||
const COLOR_RE = /^(color|bg|bgValue|gradient)$|(colou?r|bg|background|gradientfrom|gradientto)$/i;
|
||||
const isTokenRef = (v) => typeof v === 'string' && /^var\(--wsb-[a-z-]+\)$/.test(v);
|
||||
|
||||
/** Trim a default so the file stays compact: long strings clipped, arrays cut to 1 item. */
|
||||
function slimDefault(v) {
|
||||
if (Array.isArray(v)) return v.slice(0, 1).map(slimDefault);
|
||||
if (v && typeof v === 'object') {
|
||||
const o = {};
|
||||
for (const k of Object.keys(v).sort()) o[k] = slimDefault(v[k]);
|
||||
return o;
|
||||
}
|
||||
if (typeof v === 'string' && v.length > 90) return v.slice(0, 87) + '...';
|
||||
return v;
|
||||
}
|
||||
|
||||
function sortKeys(o) {
|
||||
if (Array.isArray(o)) return o.map(sortKeys);
|
||||
if (o && typeof o === 'object') return Object.fromEntries(Object.keys(o).sort().map((k) => [k, sortKeys(o[k])]));
|
||||
return o;
|
||||
}
|
||||
|
||||
export async function buildCatalog() {
|
||||
const rt = await loadRuntime();
|
||||
const files = componentFiles();
|
||||
const cfg = ts.readConfigFile(rel('tsconfig.json'), ts.sys.readFile);
|
||||
const parsed = ts.parseJsonConfigFileContent(cfg.config, ts.sys, craftRoot);
|
||||
const program = ts.createProgram(Object.values(files), { ...parsed.options, noEmit: true });
|
||||
|
||||
const names = Object.keys(rt.components);
|
||||
for (const n of names) if (!NOTES[n]) throw new Error(`catalog: component "${n}" has no entry in scripts/sitesmith-catalog/notes.mjs (add a one-line purpose)`);
|
||||
for (const n of Object.keys(NOTES)) if (!rt.components[n]) throw new Error(`catalog: notes.mjs mentions "${n}" which is not in the editor's component resolver`);
|
||||
|
||||
const components = {};
|
||||
for (const name of names.sort()) {
|
||||
const src = fs.readFileSync(files[name], 'utf8');
|
||||
const all = extractProps(program, files[name], name);
|
||||
const defaults = rt.components[name].defaults;
|
||||
const props = {};
|
||||
for (const [p, info] of Object.entries(all)) {
|
||||
if (COMMON_PROPS.has(p) || p === 'children') continue;
|
||||
const e = { ...info };
|
||||
delete e.optional;
|
||||
if (p in defaults && !VOLATILE_DEFAULTS.has(`${name}.${p}`) && !(typeof defaults[p] === 'string' && defaults[p].startsWith('data:'))) e.default = slimDefault(defaults[p]);
|
||||
if (info.type !== 'boolean' && info.type !== 'number' && COLOR_RE.test(p)) {
|
||||
e.color = true;
|
||||
if (isTokenRef(defaults[p])) e.tokenDefault = true;
|
||||
}
|
||||
props[p] = e;
|
||||
}
|
||||
const note = NOTES[name];
|
||||
const kind = rt.components[name].isCanvas || rt.components[name].shellInner ? "any" : name === "ColumnLayout" ? "columns" : "none";
|
||||
// icon support is read from the component SOURCE: faClass() => Font Awesome class, else plain text/emoji.
|
||||
let icon = null;
|
||||
if (/\bicon\b/.test(Object.keys(all).join(' ')) || /icon/i.test(JSON.stringify(Object.values(all).map((a) => a.item || '')))) {
|
||||
icon = /faClass\(/.test(src) ? 'fontawesome' : 'text';
|
||||
}
|
||||
components[name] = {
|
||||
category: path.basename(path.dirname(files[name])),
|
||||
purpose: note.purpose,
|
||||
children: kind,
|
||||
...(note.tips ? { tips: note.tips } : {}),
|
||||
props,
|
||||
...(all.animation ? { animation: true } : {}),
|
||||
...(icon ? { icon } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const htmlExport = fs.readFileSync(rel('src/utils/html-export.ts'), 'utf8');
|
||||
const animations = [...new Set([...htmlExport.matchAll(/\[data-animation="([\w-]+)"\]\.animated/g)].map((m) => m[1]))].sort();
|
||||
const faSrc = fs.readFileSync(rel('src/utils/fa-icon.ts'), 'utf8');
|
||||
const brands = [...(faSrc.match(/const BRANDS = new Set\(\[([\s\S]*?)\]\)/)?.[1] ?? '').matchAll(/'([\w-]+)'/g)].map((m) => m[1]).sort();
|
||||
|
||||
const catalog = {
|
||||
generatedBy: 'craft/scripts/gen-sitesmith-catalog.mjs (do not edit; regenerate)',
|
||||
version: 1,
|
||||
common: {
|
||||
props: { style: 'object of CSS properties (camelCase); never an array', animation: animations, animationDelay: 'seconds as a bare string, e.g. "0.2"', hideOnDesktop: 'boolean', hideOnTablet: 'boolean', hideOnMobile: 'boolean' },
|
||||
...GLOBAL_NOTES.common,
|
||||
},
|
||||
tokens: {
|
||||
vars: rt.tokenVars,
|
||||
colorTokens: rt.colorTokens.map((k) => `var(--wsb-${k})`),
|
||||
},
|
||||
icons: { library: 'Font Awesome Free 7.3.1', classForm: 'fa-solid fa-<name> | fa-regular fa-<name> | fa-brands fa-<name>', brands, ...GLOBAL_NOTES.icons },
|
||||
palettes: rt.palettes,
|
||||
sectionFamilies: rt.families,
|
||||
sections: rt.sections,
|
||||
templates: rt.templates,
|
||||
components,
|
||||
};
|
||||
return sortKeysKeepArrays(catalog);
|
||||
}
|
||||
|
||||
/** Deterministic key order for objects; array order is preserved (it is meaningful). */
|
||||
function sortKeysKeepArrays(o) {
|
||||
if (Array.isArray(o)) return o.map(sortKeysKeepArrays);
|
||||
if (o && typeof o === 'object') return Object.fromEntries(Object.keys(o).sort().map((k) => [k, sortKeysKeepArrays(o[k])]));
|
||||
return o;
|
||||
}
|
||||
|
||||
export function serialize(catalog) {
|
||||
return JSON.stringify(catalog, null, 1) + '\n';
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2);
|
||||
const catalog = await buildCatalog();
|
||||
const text = serialize(catalog);
|
||||
const oi = args.indexOf('--out');
|
||||
if (oi >= 0) {
|
||||
const out = path.resolve(process.cwd(), args[oi + 1]);
|
||||
fs.writeFileSync(out, text);
|
||||
console.error(`wrote ${out} (${text.length} bytes, ${Object.keys(catalog.components).length} components, ${catalog.sections.length} sections, ${catalog.templates.length} templates)`);
|
||||
} else {
|
||||
process.stdout.write(text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Render a Sitesmith JSON response (a recorded fixture, or a live one saved to a file) through the
|
||||
* repo's own exporter into HTML, then take Firefox screenshots so a human can compare runs.
|
||||
*
|
||||
* node scripts/render-sitesmith-response.mjs --response resp.json --out outdir [--design design.json]
|
||||
* [--page 0] [--assets dir] [--width 1280] [--mobile 390] [--no-shots]
|
||||
*
|
||||
* --design JSON of SiteDesign overrides (primaryColor, headingFont, ...), i.e. the values the
|
||||
* SITE DESIGN prompt block carried. Defaults to the editor's default design.
|
||||
* --assets directory to expose as ./assets/ next to the HTML (symlinked) so relUrl images load.
|
||||
* Screenshots: Playwright module and Firefox binary come from $SITESMITH_PLAYWRIGHT / $SITESMITH_FIREFOX
|
||||
* (defaults below). Only type=replace responses render (patches need a canvas).
|
||||
*/
|
||||
import { build } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const craftRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (name, def) => { const i = args.indexOf('--' + name); return i >= 0 ? args[i + 1] : def; };
|
||||
const flag = (name) => args.includes('--' + name);
|
||||
const respPath = opt('response'), outDir = opt('out');
|
||||
if (!respPath || !outDir) { console.error('usage: render-sitesmith-response.mjs --response resp.json --out dir [--design design.json] [--assets dir]'); process.exit(2); }
|
||||
|
||||
const PLAYWRIGHT = process.env.SITESMITH_PLAYWRIGHT || '/tmp/claude-1000/-workspace/edbe144d-d5fe-40a1-88a3-fb8ed9709df9/scratchpad/repro/node_modules/playwright/index.mjs';
|
||||
const FIREFOX = process.env.SITESMITH_FIREFOX || '/home/claude/.cache/ms-playwright/firefox-1538/firefox/firefox';
|
||||
|
||||
const bundle = await build({
|
||||
entryPoints: [path.join(craftRoot, 'scripts/sitesmith-catalog/render-entry.ts')],
|
||||
bundle: true, write: false, format: 'cjs', platform: 'node', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"' },
|
||||
});
|
||||
const tmp = fs.mkdtempSync(path.join(process.env.TMPDIR || '/tmp', 'ssrender-'));
|
||||
fs.writeFileSync(path.join(tmp, 'r.cjs'), bundle.outputFiles[0].text);
|
||||
const { renderResponse } = createRequire(import.meta.url)(path.join(tmp, 'r.cjs'));
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
|
||||
const resp = JSON.parse(fs.readFileSync(respPath, 'utf8'));
|
||||
const design = opt('design') ? JSON.parse(fs.readFileSync(opt('design'), 'utf8')) : {};
|
||||
const html = renderResponse(resp, design, Number(opt('page', 0)));
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const htmlPath = path.join(outDir, 'page.html');
|
||||
fs.writeFileSync(htmlPath, html);
|
||||
if (opt('assets')) {
|
||||
const link = path.join(outDir, 'assets');
|
||||
fs.rmSync(link, { recursive: true, force: true });
|
||||
fs.symlinkSync(path.resolve(opt('assets')), link);
|
||||
}
|
||||
console.log(`html: ${htmlPath} (${html.length} bytes)`);
|
||||
|
||||
if (!flag('no-shots')) {
|
||||
const { firefox } = await import(pathToFileURL(PLAYWRIGHT).href);
|
||||
const browser = await firefox.launch({ executablePath: FIREFOX, headless: true });
|
||||
for (const [label, width, height] of [['desktop', Number(opt('width', 1280)), 900], ['mobile', Number(opt('mobile', 390)), 844]]) {
|
||||
const page = await browser.newPage({ viewport: { width, height } });
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
await page.goto(pathToFileURL(htmlPath).href, { waitUntil: 'networkidle', timeout: 60000 }).catch((e) => errors.push(String(e)));
|
||||
await page.evaluate(() => document.fonts && document.fonts.ready);
|
||||
// reveal entrance animations deterministically for the capture
|
||||
await page.addStyleTag({ content: '[data-animation]{opacity:1!important;animation:none!important}' });
|
||||
const shot = path.join(outDir, `${label}.png`);
|
||||
await page.screenshot({ path: shot, fullPage: true });
|
||||
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
||||
console.log(`${label}: ${shot} horizontal-overflow-px=${overflow}${errors.length ? ' errors=' + JSON.stringify(errors) : ''}`);
|
||||
await page.close();
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Curated, human-written facts the editor's code cannot express: a one-line
|
||||
* purpose per component, and short usage tips where the real behaviour is
|
||||
* surprising. Everything else in the catalog (props, types, enums, defaults,
|
||||
* animation, icon support, child rules) is derived from the code. Adding a
|
||||
* component to the resolver without an entry here fails the generator.
|
||||
*/
|
||||
export const NOTES = {
|
||||
Accordion: { purpose: 'Expand/collapse FAQ list (items: title + content, isOpen)' },
|
||||
BackgroundSection: { purpose: 'Full-width section over a bg image/colour with a dark overlay; children sit inside', tips: 'Text over bgImage needs overlayColor+overlayOpacity (>=0.45) for contrast.' },
|
||||
BookingEmbed: { purpose: 'Embedded booking widget (calendly|square|custom url)', tips: 'Only if the user supplied a booking URL.' },
|
||||
ButtonLink: { purpose: 'Link styled as a button; look comes from style (backgroundColor, color, padding, borderRadius, fontWeight)', tips: 'No variant prop: set style yourself, e.g. primary = {backgroundColor:"var(--wsb-primary)",color:"var(--wsb-bg)",padding:"14px 28px",borderRadius:"var(--wsb-button-radius)",fontWeight:"600"}; secondary = transparent bg + border.' },
|
||||
CTASection: { purpose: 'Centered call-to-action band on a gradient (prop gradient = CSS gradient string); ctas[] buttons', tips: 'Use ctas[], not buttonText/buttonHref.' },
|
||||
CallToAction: { purpose: 'Call-to-action band on colour/gradient/image (bgType+bgValue, overlay); ctas[] buttons', tips: 'Use ctas[], not buttonText/secondaryButton*.' },
|
||||
ColumnLayout: { purpose: 'Row of columns; each direct child becomes one column and stacks on mobile', tips: 'ALWAYS set style display:"flex" and flexDirection:"row": published pages stack columns on phones ONLY via that inline pair (measured; without it columns stay side by side, squeezed). columns follows the child count; split must be an allowed string; style.alignItems:"center" centres vertically.' },
|
||||
ContactForm: { purpose: 'Complete contact form with fields[], submit button, spam captcha option (no children)', tips: 'Delivery is configured by the owner (recipientEmail / webhook): never invent an address; leave recipientEmail empty.' },
|
||||
Container: { purpose: 'Generic block (flow layout). Children stack vertically; use style for padding/background/maxWidth/flex', tips: 'tag is one of div|section|article|header|footer|main. The page root is a Container.' },
|
||||
ContentSlider: { purpose: 'Auto-playing slider of content/image slides', tips: 'Use sparingly; a static hero is almost always better.' },
|
||||
Countdown: { purpose: 'Countdown to targetDate (YYYY-MM-DD)', tips: 'Only for a real, user-given date.' },
|
||||
Divider: { purpose: 'Horizontal rule' },
|
||||
FeaturesGrid: { purpose: 'Responsive grid of cards {icon,title,description,image?,buttonText?,buttonUrl?}', tips: 'icon is PLAIN TEXT (a single glyph/emoji), NOT Font Awesome: never put fa-* there. For Font Awesome icon cards build ColumnLayout > Container > Icon + Heading + TextBlock instead. An image per feature (image,imageAlt) replaces the icon.' },
|
||||
Footer: { purpose: 'Simple footer text line (copyright). For richer footers compose Container/ColumnLayout/SocialLinks/Menu', tips: 'Colour comes from style.color (default is dark text: set a light color on a dark footer). Emit in the top-level "footer" slot for scope=site.' },
|
||||
FormButton: { purpose: 'Submit button inside a FormContainer' },
|
||||
FormContainer: { purpose: 'Wrapper for hand-built forms (InputField/TextareaField/FormButton children)', tips: 'Prefer ContactForm.' },
|
||||
Gallery: { purpose: 'Image grid (images[] {src,alt,caption?}), columns, optional lightbox', tips: 'Use the user\'s uploaded images only; no placeholders in galleries.' },
|
||||
Heading: { purpose: 'Heading h1-h6; size/weight/colour/letterSpacing via style', tips: 'One h1 per page. Set fontFamily:"var(--wsb-heading-font)" and a size from the type scale; leave html empty.' },
|
||||
HeroSimple: { purpose: 'Pre-built hero: heading, subtitle, ctas[], bg colour/gradient/image/video with overlay, minHeight', tips: 'With bgType=image set overlayColor+overlayOpacity (>=0.45) so light text passes contrast. No entrance animation support.' },
|
||||
HtmlBlock: { purpose: 'Sanitised raw HTML. Last resort only', tips: 'Scripts/handlers are stripped.' },
|
||||
Icon: { purpose: 'One Font Awesome icon (icon="fa-solid fa-<name>" or bare "fa-<name>"), optional circle/rounded background', tips: 'The ONLY real-icon component. size/color/bgColor/bgShape/bgSize; link optional.' },
|
||||
ImageBlock: { purpose: 'Image. Crop/size/radius via style (width, maxWidth, aspectRatio, objectFit, borderRadius)', tips: 'Always set alt. Use style.aspectRatio with objectFit:"cover" (e.g. "4 / 3", "16 / 9", "1 / 1") and a consistent borderRadius. src: "assets/<file>" for uploaded images.' },
|
||||
InputField: { purpose: 'Single-line form input inside FormContainer' },
|
||||
Logo: { purpose: 'Text or image logo linking home' },
|
||||
MapEmbed: { purpose: 'Embedded map for an address', tips: 'Only with a real address from the user.' },
|
||||
Menu: { purpose: 'Link list (horizontal/vertical) with optional CTA-styled link' },
|
||||
Navbar: { purpose: 'Top navigation bar: logo (text|image), links[] {text,href,isCta?}, sticky option', tips: 'Set showMobileMenu:true or the links overflow on phones. Emit in the top-level "header" slot. In-page links use href "#anchor"; other pages "/page-slug".' },
|
||||
NumberCounter: { purpose: 'Row of animated stats (counters[] {number,suffix,label})', tips: 'Only real figures supplied by the user.' },
|
||||
OpeningHours: { purpose: 'Opening hours table (rows[] {day,hours,closed})', tips: 'Only real hours supplied by the user.' },
|
||||
PricingTable: { purpose: 'Pricing cards (plans[] {name,price,period,features[],buttonText,buttonHref,isFeatured})', tips: 'Only real prices supplied by the user; otherwise use a "Request a quote" CTA.' },
|
||||
ReviewsStrip: { purpose: 'Strip of customer reviews (reviews[] {name,rating,text,source,url}) with link to all reviews', tips: 'Only real reviews supplied by the user.' },
|
||||
SearchBar: { purpose: 'Search form' },
|
||||
Section: { purpose: 'Full-width section band with a centred inner column (innerMaxWidth); optional top/bottom divider shapes', tips: 'Backgrounds and vertical padding go in style (backgroundColor, paddingTop/paddingBottom).' },
|
||||
SocialLinks: { purpose: 'Row of social icons (links[] {platform,url})', tips: 'Only profiles the user gave.' },
|
||||
Spacer: { purpose: 'Vertical gap' },
|
||||
StarRating: { purpose: 'Star rating glyphs (rating 0-5)', tips: 'Only real ratings.' },
|
||||
StickyCallBar: { purpose: 'Mobile-only sticky call/directions bar', tips: 'Only with a real phone number.' },
|
||||
SubscribeForm: { purpose: 'Email newsletter signup' },
|
||||
Tabs: { purpose: 'Tabbed content (tabs[] {label,content})' },
|
||||
Testimonials: { purpose: 'Testimonial cards (testimonials[] {quote,name,title,rating}) in a grid or single layout', tips: 'Only real quotes supplied by the user.' },
|
||||
TextBlock: { purpose: 'Paragraph text; size/colour/lineHeight/maxWidth via style', tips: 'Set fontFamily:"var(--wsb-body-font)", lineHeight 1.6-1.75, maxWidth about 65ch for long copy; leave html empty.' },
|
||||
TextareaField: { purpose: 'Multi-line form input inside FormContainer' },
|
||||
VideoBlock: { purpose: 'Video (file/youtube/vimeo) or background video', tips: 'Only with a URL the user gave.' },
|
||||
};
|
||||
|
||||
export const GLOBAL_NOTES = {
|
||||
common: {
|
||||
rules: [
|
||||
'Every prop below that is a colour accepts a hex, rgb()/hsl(), a gradient (where noted) or a design token var(--wsb-<name>).',
|
||||
'Entrance animation (animation, animationDelay) exists only on components marked animation:true; HeroSimple, Divider, Spacer, HtmlBlock do not support it.',
|
||||
],
|
||||
},
|
||||
icons: {
|
||||
components: 'Icon renders Font Awesome. FeaturesGrid.icon is plain text, not Font Awesome.',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
// Bundled by scripts/render-sitesmith-response.mjs (esbuild, platform node).
|
||||
// Turns a Sitesmith JSON response into the HTML the REPO EXPORTER produces:
|
||||
// the same sanitize -> flatten -> exportBodyHtml path the editor uses.
|
||||
import { sanitizeAiTree, flattenTreeForCraft } from '../../src/utils/craft-tree';
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../../src/utils/html-export';
|
||||
import { DEFAULT_SITE_DESIGN } from '../../src/state/SiteDesignContext';
|
||||
|
||||
function stateFor(tree: any): string {
|
||||
const clean = sanitizeAiTree(tree, new Set(), { n: 0 });
|
||||
if (!clean) throw new Error('response tree root is not a known component');
|
||||
const flat = flattenTreeForCraft(clean);
|
||||
const root = {
|
||||
type: { resolvedName: 'Container' }, isCanvas: true, props: { tag: 'div', style: {} }, displayName: 'Container',
|
||||
custom: {}, hidden: false, parent: null, nodes: [flat.rootNodeId], linkedNodes: {},
|
||||
};
|
||||
flat.nodes[flat.rootNodeId].parent = 'ROOT';
|
||||
return JSON.stringify({ ROOT: root, ...flat.nodes });
|
||||
}
|
||||
|
||||
/** Mirrors SiteBuilderHead.php sb_font_awesome_link(): the backend adds this to published pages. */
|
||||
const FA_LINK = '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.3.1/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer">';
|
||||
|
||||
export function renderResponse(resp: any, designOverrides: Record<string, any> = {}, pageIndex = 0) {
|
||||
if (resp?.type !== 'replace') throw new Error(`only type=replace responses can be rendered (got ${resp?.type})`);
|
||||
const design = { ...DEFAULT_SITE_DESIGN, ...designOverrides };
|
||||
const page = resp.pages[pageIndex];
|
||||
const pageState = stateFor(page.tree);
|
||||
const hdr = resp.header ? exportBodyHtml(stateFor(resp.header.tree), 'header').html : '';
|
||||
const ftr = resp.footer ? exportBodyHtml(stateFor(resp.footer.tree), 'footer').html : '';
|
||||
const body = exportBodyHtml(pageState).html;
|
||||
let html = exportComposedPreviewHtml(pageState, hdr + body + ftr, { title: page.name, includeFonts: true, design } as any);
|
||||
if (/class="[^"]*\bfa-/.test(html) && !html.includes('font-awesome')) html = html.replace('</head>', () => `${FA_LINK}\n</head>`);
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Bundled by scripts/gen-sitesmith-catalog.mjs (esbuild, platform node) and run
|
||||
// in Node. Collects everything that only exists at RUNTIME in the editor's real
|
||||
// definitions: component craft defaults/rules, token vocabulary, palettes,
|
||||
// section families and templates. The TypeScript prop TYPES come from the
|
||||
// compiler API in the .mjs (types are erased at runtime).
|
||||
import { componentResolver } from '../../src/components/resolver';
|
||||
import { TOKEN_VARS, COLOR_TOKENS } from '../../src/utils/tokens';
|
||||
import { PALETTES } from '../../src/constants/palettes';
|
||||
import { BUILTIN_SECTIONS } from '../../src/sections/families';
|
||||
import { SECTION_FAMILIES } from '../../src/sections/catalog';
|
||||
import { allTemplates } from '../../src/templates/definitions';
|
||||
import { CANVAS_TYPES, SHELL_INNER } from '../../src/utils/craft-tree';
|
||||
import { DEFAULT_SITE_DESIGN } from '../../src/state/SiteDesignContext';
|
||||
|
||||
type Tpl = { type: string; props: Record<string, any>; children?: Tpl[] };
|
||||
|
||||
/** "Section[Heading,TextBlock,ButtonLink]": the structural skeleton of a tree. */
|
||||
function recipe(n: Tpl): string {
|
||||
const kids = (n.children ?? []).map(recipe);
|
||||
// collapse runs of identical siblings: Container*3
|
||||
const out: string[] = [];
|
||||
for (const k of kids) {
|
||||
const last = out[out.length - 1];
|
||||
const m = last && last.match(/^(.*)\*(\d+)$/);
|
||||
if (last === k) out[out.length - 1] = `${k}*2`;
|
||||
else if (m && m[1] === k) out[out.length - 1] = `${k}*${Number(m[2]) + 1}`;
|
||||
else out.push(k);
|
||||
}
|
||||
return out.length ? `${n.type}[${out.join(',')}]` : n.type;
|
||||
}
|
||||
|
||||
export function collect() {
|
||||
const components: Record<string, any> = {};
|
||||
for (const [name, comp] of Object.entries(componentResolver) as [string, any][]) {
|
||||
components[name] = {
|
||||
defaults: comp.craft?.props ?? {},
|
||||
displayName: comp.craft?.displayName ?? name,
|
||||
isCanvas: CANVAS_TYPES.has(name),
|
||||
shellInner: SHELL_INNER[name] ?? null,
|
||||
canMoveInFalse: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
components,
|
||||
tokenVars: TOKEN_VARS.map(([v, k]) => ({ var: v, designKey: k, default: (DEFAULT_SITE_DESIGN as any)[k] })),
|
||||
colorTokens: COLOR_TOKENS.map((t) => t.key),
|
||||
palettes: PALETTES.map((p) => ({ id: p.id, name: p.name, ...p.design, fonts: p.fonts ?? null })),
|
||||
families: SECTION_FAMILIES.filter((f) => f.id !== 'custom'),
|
||||
sections: BUILTIN_SECTIONS.map((s) => ({ id: s.id, name: s.name, family: s.family, keywords: s.keywords, recipe: recipe(s.tree as Tpl) })),
|
||||
templates: allTemplates.map((t) => ({
|
||||
id: t.id, name: t.name, category: t.category, description: t.description, multiPage: t.isMultiPage,
|
||||
design: t.design,
|
||||
pages: t.pages.map((p) => ({ name: p.name, slug: p.slug, recipe: p.content.components.map((c) => recipe(c as Tpl)) })),
|
||||
header: t.header.components.map((c) => recipe(c as Tpl)),
|
||||
footer: t.footer.components.map((c) => recipe(c as Tpl)),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, test, expect, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { Frame, Element, useEditor } from '@craftjs/core';
|
||||
import { SaveAwareEditor } from './App';
|
||||
import { Container } from './components/layout/Container';
|
||||
import { ensureJsdomShims } from './test-utils/editorHarness';
|
||||
import { EditorConfigProvider } from './state/EditorConfigContext';
|
||||
import { SaveGuardProvider, useSaveGuard } from './state/SaveGuardContext';
|
||||
import { WhpConfig } from './types';
|
||||
|
||||
/**
|
||||
* Against a REAL Craft editor: onNodesChange (what App wires to markDirty)
|
||||
* must fire for content edits and must NOT fire for selection or for the
|
||||
* load's own deserialize -- otherwise a freshly opened site would warn
|
||||
* "unsaved changes" on close.
|
||||
*/
|
||||
const whpConfig: WhpConfig = {
|
||||
user: 'u', apiUrl: '/api', csrfToken: 't', siteId: 1,
|
||||
siteDomain: 'example.com', siteName: 'Example', backUrl: '/', isRoot: false,
|
||||
};
|
||||
|
||||
let api: { actions: any; query: any; guard: ReturnType<typeof useSaveGuard> };
|
||||
const Capture: React.FC = () => {
|
||||
const { actions, query } = useEditor();
|
||||
const guard = useSaveGuard();
|
||||
api = { actions, query, guard };
|
||||
return null;
|
||||
};
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => { root.unmount(); });
|
||||
container.remove();
|
||||
});
|
||||
|
||||
const STATE = JSON.stringify({
|
||||
ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: {}, displayName: 'Container', custom: {}, hidden: false, nodes: [], linkedNodes: {} },
|
||||
});
|
||||
|
||||
describe('canvas dirty tracking on a real Craft editor', () => {
|
||||
test('load deserialize and selection stay clean; a prop edit makes it dirty', async () => {
|
||||
ensureJsdomShims();
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => {
|
||||
root = createRoot(container);
|
||||
root.render(
|
||||
<EditorConfigProvider config={whpConfig}>
|
||||
<SaveGuardProvider>
|
||||
<SaveAwareEditor>
|
||||
<Frame><Element is={Container} canvas style={{}} /></Frame>
|
||||
<Capture />
|
||||
</SaveAwareEditor>
|
||||
</SaveGuardProvider>
|
||||
</EditorConfigProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
// What LoadGate does: deserialize while loading, then flip to loaded.
|
||||
act(() => { api.actions.deserialize(STATE); });
|
||||
act(() => { api.guard.setLoadState('loaded'); });
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(api.guard.dirty).toBe(false);
|
||||
|
||||
act(() => { api.actions.selectNode('ROOT'); });
|
||||
expect(api.guard.dirty).toBe(false);
|
||||
|
||||
act(() => { api.actions.setProp('ROOT', (p: any) => { p.tag = 'section'; }); });
|
||||
expect(api.guard.dirty).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, test, expect, vi, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
import { useMobileChrome } from './state/MobileChromeContext';
|
||||
import { ensureJsdomShims } from './test-utils/editorHarness';
|
||||
|
||||
/**
|
||||
* The overlays (section library, command palette) mount NEXT TO the shell in
|
||||
* App, so the mobile chrome state (open sheet) must be provided above both:
|
||||
* otherwise the section library's closeSheet() after an insert hits the
|
||||
* default no-op and the Blocks sheet stays open over the canvas.
|
||||
*/
|
||||
const seen: { shell?: ReturnType<typeof useMobileChrome>; overlays?: ReturnType<typeof useMobileChrome> } = {};
|
||||
vi.mock('./editor/EditorShell', () => ({
|
||||
EditorShell: () => { seen.shell = useMobileChrome(); return null; },
|
||||
}));
|
||||
vi.mock('./editor/CanvasOverlays', () => ({
|
||||
CanvasOverlays: () => { seen.overlays = useMobileChrome(); return null; },
|
||||
}));
|
||||
|
||||
import { App } from './App';
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
afterEach(() => { act(() => { root.unmount(); }); container.remove(); });
|
||||
|
||||
describe('App mobile chrome wiring', () => {
|
||||
test('the shell and the overlays share one MobileChromeContext', () => {
|
||||
ensureJsdomShims();
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => { root = createRoot(container); root.render(<App whpConfig={null as any} />); });
|
||||
act(() => seen.shell!.openSheet('blocks'));
|
||||
expect(seen.shell!.activeSheet).toBe('blocks');
|
||||
expect(seen.overlays!.activeSheet).toBe('blocks');
|
||||
act(() => seen.overlays!.closeSheet());
|
||||
expect(seen.shell!.activeSheet).toBeNull();
|
||||
});
|
||||
});
|
||||
+65
-11
@@ -1,14 +1,21 @@
|
||||
import React from 'react';
|
||||
import { Editor } from '@craftjs/core';
|
||||
import { Editor, DefaultEventHandlers } from '@craftjs/core';
|
||||
import { EditorShell } from './editor/EditorShell';
|
||||
import { RenderNode } from './editor/RenderNode';
|
||||
import { componentResolver } from './components/resolver';
|
||||
import { WhpConfig } from './types';
|
||||
import { EditorConfigProvider } from './state/EditorConfigContext';
|
||||
import { SiteDesignProvider } from './state/SiteDesignContext';
|
||||
import { CanvasTokenStyle } from './editor/CanvasTokenStyle';
|
||||
import { SaveGuardProvider, useSaveGuard } from './state/SaveGuardContext';
|
||||
import { NoticeProvider } from './state/NoticeContext';
|
||||
import { ProjectExtrasProvider } from './state/ProjectExtrasContext';
|
||||
import { CanvasOverlays } from './editor/CanvasOverlays';
|
||||
import { PageProvider } from './state/PageContext';
|
||||
import { GlobalSectionsProvider } from './state/GlobalSectionsContext';
|
||||
import { SitesmithProvider, useSitesmithModal } from './state/SitesmithContext';
|
||||
import { SitesmithModal } from './panels/sitesmith/SitesmithModal';
|
||||
import { MobileChromeProvider } from './state/MobileChromeContext';
|
||||
|
||||
interface AppProps {
|
||||
whpConfig: WhpConfig | null;
|
||||
@@ -20,19 +27,66 @@ const SitesmithModalMount: React.FC = () => {
|
||||
return <SitesmithModal target={target} onClose={close} />;
|
||||
};
|
||||
|
||||
// #50: shift / cmd / ctrl-click adds to the selection (Craft's default is cmd only).
|
||||
// In Craft 0.2.12 `isMultiSelectEnabled` is an option of DefaultEventHandlers, not
|
||||
// of <Editor>, so it is set by supplying the handlers; the other options keep
|
||||
// Craft's own defaults.
|
||||
export const isMultiSelectClick = (e: MouseEvent) => e.shiftKey || e.metaKey || e.ctrlKey;
|
||||
export const craftHandlers = (store: any) =>
|
||||
new DefaultEventHandlers({ store, removeHoverOnMouseleave: false, isMultiSelectEnabled: isMultiSelectClick });
|
||||
|
||||
// Craft fires onNodesChange only when the serialized node tree changes (not on
|
||||
// selection, hover or DOM registration), which is exactly "the canvas was edited".
|
||||
export const SaveAwareEditor: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const { markDirty } = useSaveGuard();
|
||||
return (
|
||||
<Editor
|
||||
resolver={componentResolver}
|
||||
enabled={true}
|
||||
onRender={RenderNode}
|
||||
handlers={craftHandlers}
|
||||
onNodesChange={markDirty}
|
||||
indicator={{
|
||||
className: 'wsb-drop-line',
|
||||
thickness: 3,
|
||||
success: 'var(--color-accent)',
|
||||
error: 'var(--color-danger)',
|
||||
transition: '0.08s ease-out',
|
||||
style: { borderRadius: 2, boxShadow: '0 0 0 1px rgba(0,0,0,.25)' },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Editor>
|
||||
);
|
||||
};
|
||||
|
||||
export const App: React.FC<AppProps> = ({ whpConfig }) => {
|
||||
return (
|
||||
<EditorConfigProvider config={whpConfig}>
|
||||
<SiteDesignProvider>
|
||||
<Editor resolver={componentResolver} enabled={true} onRender={RenderNode}>
|
||||
<PageProvider>
|
||||
<SitesmithProvider>
|
||||
<EditorShell />
|
||||
<SitesmithModalMount />
|
||||
</SitesmithProvider>
|
||||
</PageProvider>
|
||||
</Editor>
|
||||
</SiteDesignProvider>
|
||||
<SaveGuardProvider>
|
||||
<NoticeProvider>
|
||||
<ProjectExtrasProvider>
|
||||
<SiteDesignProvider>
|
||||
<CanvasTokenStyle />
|
||||
<SaveAwareEditor>
|
||||
<PageProvider>
|
||||
<GlobalSectionsProvider>
|
||||
<SitesmithProvider>
|
||||
{/* Shared by the shell and the overlays (e.g. the section
|
||||
library closes the mobile Blocks sheet after an insert). */}
|
||||
<MobileChromeProvider>
|
||||
<EditorShell />
|
||||
<CanvasOverlays />
|
||||
<SitesmithModalMount />
|
||||
</MobileChromeProvider>
|
||||
</SitesmithProvider>
|
||||
</GlobalSectionsProvider>
|
||||
</PageProvider>
|
||||
</SaveAwareEditor>
|
||||
</SiteDesignProvider>
|
||||
</ProjectExtrasProvider>
|
||||
</NoticeProvider>
|
||||
</SaveGuardProvider>
|
||||
</EditorConfigProvider>
|
||||
);
|
||||
};
|
||||
@@ -118,3 +118,20 @@ describe('ButtonLink.craft.props exposes target + hover + box-model + animation/
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ButtonLink.toHtml palette token default (Refs #44)', () => {
|
||||
test('a new button (craft default props) paints the primary token', () => {
|
||||
const { html } = toHtml({ ...(ButtonLink as any).craft.props }, '');
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ButtonLink.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ ...(ButtonLink as any).craft.props }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "primary"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl, cssValue, scopeId } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
interface ButtonLinkProps {
|
||||
text?: string;
|
||||
@@ -75,8 +76,8 @@ ButtonLink.craft = {
|
||||
hoverBg: '',
|
||||
hoverColor: '',
|
||||
style: {
|
||||
backgroundColor: '#3b82f6',
|
||||
color: '#ffffff',
|
||||
backgroundColor: tokenRef('primary'),
|
||||
color: tokenRef('bg'),
|
||||
padding: '12px 24px',
|
||||
borderRadius: '8px',
|
||||
fontWeight: '600',
|
||||
|
||||
@@ -32,3 +32,12 @@ describe('Divider.toHtml XSS hardening (thickness/color into style=)', () => {
|
||||
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Divider.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["border"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#e4e4e7"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
|
||||
@@ -9,7 +10,7 @@ interface DividerProps {
|
||||
}
|
||||
|
||||
export const Divider: UserComponent<DividerProps> = ({
|
||||
color = '#e4e4e7',
|
||||
color = tokenRef('border'),
|
||||
thickness = '1px',
|
||||
style = {},
|
||||
}) => {
|
||||
@@ -39,7 +40,7 @@ export const Divider: UserComponent<DividerProps> = ({
|
||||
Divider.craft = {
|
||||
displayName: 'Divider',
|
||||
props: {
|
||||
color: '#e4e4e7',
|
||||
color: tokenRef('border'),
|
||||
thickness: '1px',
|
||||
style: {},
|
||||
},
|
||||
@@ -55,7 +56,7 @@ Divider.craft = {
|
||||
(Divider as any).toHtml = (props: DividerProps, _childrenHtml: string) => {
|
||||
const styleStr = cssPropsToString({
|
||||
border: 'none',
|
||||
borderTop: `${props.thickness || '1px'} solid ${props.color || '#e4e4e7'}`,
|
||||
borderTop: `${props.thickness || '1px'} solid ${props.color || tokenRef('border')}`,
|
||||
margin: '16px 0',
|
||||
...props.style,
|
||||
});
|
||||
|
||||
@@ -31,3 +31,13 @@ describe('Footer (F4: box-model + animation + visibility props on craft.props)',
|
||||
expect(craftProps).toHaveProperty('hideOnMobile', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Footer.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((Footer as any).craft.props as object) };
|
||||
const { html } = (((Footer) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['text', 'bg']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ['#18181b', '#a1a1aa']) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
|
||||
interface FooterProps {
|
||||
@@ -92,8 +93,9 @@ Footer.craft = {
|
||||
props: {
|
||||
text: '© 2026 MySite. All rights reserved.',
|
||||
style: {
|
||||
backgroundColor: '#18181b',
|
||||
color: '#a1a1aa',
|
||||
// Dark band: text token as the band, bg token as its (contrast-safe) text.
|
||||
backgroundColor: tokenRef('text'),
|
||||
color: tokenRef('bg'),
|
||||
fontSize: '14px',
|
||||
padding: '24px 20px',
|
||||
},
|
||||
|
||||
@@ -107,3 +107,57 @@ describe('Heading.craft.props exposes the box-model + animation/visibility rollo
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Heading.toHtml inline rich text (#46)', () => {
|
||||
test('legacy plain text with html="" is escaped', () => {
|
||||
expect(toHtml({ level: 'h2', text: 'a<b', html: '' }, '').html).toBe('<h2>a<b</h2>');
|
||||
});
|
||||
|
||||
test('marked html is emitted (html-only props)', () => {
|
||||
expect(toHtml({ level: 'h2', html: '<b>Hi</b> there' }, '').html).toBe('<h2><b>Hi</b> there</h2>');
|
||||
});
|
||||
|
||||
test('html whose text mirror matches text is emitted', () => {
|
||||
expect(toHtml({ level: 'h2', text: 'Hi there', html: '<b>Hi</b> there' }, '').html).toBe('<h2><b>Hi</b> there</h2>');
|
||||
});
|
||||
|
||||
test('text changed without html (e.g. AI update_props) wins over stale html', () => {
|
||||
expect(toHtml({ level: 'h2', text: 'New <copy>', html: '<b>Old</b> copy' }, '').html).toBe('<h2>New <copy></h2>');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['<img src=x onerror=alert(1)>', '<img'],
|
||||
['<script>alert(1)</script>', '<script'],
|
||||
['<a href="javascript:alert(1)">x</a>', 'javascript:'],
|
||||
['<a href="javascript:alert(1)">x</a>', 'href'],
|
||||
['<b onclick="alert(1)">x</b>', 'onclick'],
|
||||
['<span style="position:fixed;inset:0">x</span>', 'position'],
|
||||
['</h2><iframe src="https://evil"></iframe><h2>', 'iframe'],
|
||||
['<svg onload=alert(1)>', 'onload'],
|
||||
])('malicious stored html is sanitised at export: %s', (html, banned) => {
|
||||
const out = toHtml({ level: 'h2', html }, '').html as string;
|
||||
expect(out.toLowerCase()).not.toContain(banned);
|
||||
expect(out.startsWith('<h2')).toBe(true);
|
||||
expect(out.endsWith('</h2>')).toBe(true);
|
||||
});
|
||||
|
||||
test('external _blank link gets rel=noopener at export', () => {
|
||||
expect(toHtml({ level: 'h2', html: '<a href="https://e.com" target="_blank">x</a>' }, '').html)
|
||||
.toBe('<h2><a href="https://e.com" target="_blank" rel="noopener">x</a></h2>');
|
||||
});
|
||||
|
||||
test('craft.props carries a blank html default', () => {
|
||||
expect((Heading as any).craft.props.html).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
test('Heading default colour is the text token', () => {
|
||||
expect((Heading as any).craft.props.style.color).toBe('var(--wsb-text)');
|
||||
});
|
||||
|
||||
describe('Heading.toHtml newlines (canvas parity)', () => {
|
||||
test('plain text newlines become <br>, like the editor canvas', () => {
|
||||
const { html } = (Heading as any).toHtml({ text: 'a\nb', level: 'h2' }, '');
|
||||
expect(html).toContain('a<br>b');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
import { resolveInlineHtml, textToInlineHtml } from '../../utils/inline-html';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useInlineEditable } from './useInlineEditable';
|
||||
|
||||
type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
||||
|
||||
@@ -17,6 +19,8 @@ const sanitizeHeadingLevel = (level: unknown): HeadingLevel =>
|
||||
|
||||
interface HeadingProps {
|
||||
text?: string;
|
||||
/** Sanitised inline rich text (#46); '' = plain `text` only. */
|
||||
html?: string;
|
||||
level?: HeadingLevel;
|
||||
style?: CSSProperties;
|
||||
cssId?: string;
|
||||
@@ -30,6 +34,7 @@ interface HeadingProps {
|
||||
|
||||
export const Heading: UserComponent<HeadingProps> = ({
|
||||
text = 'Heading',
|
||||
html = '',
|
||||
level = 'h2',
|
||||
style = {},
|
||||
}) => {
|
||||
@@ -42,34 +47,7 @@ export const Heading: UserComponent<HeadingProps> = ({
|
||||
}));
|
||||
|
||||
const safeLevel = sanitizeHeadingLevel(level);
|
||||
const elRef = useRef<HTMLElement | null>(null);
|
||||
const editedTextRef = useRef<string | null>(null);
|
||||
|
||||
const commitText = useCallback(() => {
|
||||
if (elRef.current) {
|
||||
const newText = elRef.current.innerText;
|
||||
editedTextRef.current = newText;
|
||||
setProp((p: HeadingProps) => { p.text = newText; });
|
||||
}
|
||||
}, [setProp]);
|
||||
|
||||
// Commit on blur
|
||||
const handleBlur = useCallback(() => { commitText(); }, [commitText]);
|
||||
|
||||
// Also commit on deselect via effect
|
||||
useEffect(() => {
|
||||
if (!selected && editedTextRef.current !== null) {
|
||||
setProp((p: HeadingProps) => { p.text = editedTextRef.current!; });
|
||||
editedTextRef.current = null;
|
||||
}
|
||||
}, [selected, setProp]);
|
||||
|
||||
// Set DOM text on mount and when text prop changes externally (not during editing)
|
||||
useEffect(() => {
|
||||
if (elRef.current && !selected && editedTextRef.current === null) {
|
||||
elRef.current.innerText = text || '';
|
||||
}
|
||||
}, [text, selected]);
|
||||
const { elRef, onBlur, onInput, onKeyDown } = useInlineEditable(text, html, selected, setProp);
|
||||
|
||||
return React.createElement(safeLevel, {
|
||||
ref: (ref: HTMLElement | null): void => {
|
||||
@@ -78,13 +56,9 @@ export const Heading: UserComponent<HeadingProps> = ({
|
||||
},
|
||||
contentEditable: selected,
|
||||
suppressContentEditableWarning: true,
|
||||
onBlur: handleBlur,
|
||||
onInput: () => {
|
||||
// Track that we have unsaved edits
|
||||
if (elRef.current) {
|
||||
editedTextRef.current = elRef.current.innerText;
|
||||
}
|
||||
},
|
||||
onBlur,
|
||||
onInput,
|
||||
onKeyDown,
|
||||
style: { outline: 'none', cursor: selected ? 'text' : 'pointer', minHeight: '1em', ...style },
|
||||
});
|
||||
};
|
||||
@@ -93,12 +67,13 @@ Heading.craft = {
|
||||
displayName: 'Heading',
|
||||
props: {
|
||||
text: 'Your Heading',
|
||||
html: '',
|
||||
level: 'h2' as HeadingLevel,
|
||||
style: {
|
||||
fontSize: '36px',
|
||||
fontWeight: '700',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#1f2937',
|
||||
color: tokenRef('text'),
|
||||
marginBottom: '16px',
|
||||
lineHeight: '',
|
||||
letterSpacing: '',
|
||||
@@ -126,7 +101,7 @@ Heading.craft = {
|
||||
|
||||
(Heading as any).toHtml = (props: HeadingProps, _childrenHtml: string) => {
|
||||
const tag = sanitizeHeadingLevel(props.level);
|
||||
const safeText = escapeHtml(props.text || '');
|
||||
const safeText = resolveInlineHtml(props.text, props.html) ?? textToInlineHtml(props.text || '');
|
||||
const styleStr = cssPropsToString(props.style);
|
||||
return { html: `<${tag}${styleStr ? ` style="${styleStr}"` : ''}>${safeText}</${tag}>` };
|
||||
};
|
||||
@@ -375,6 +375,8 @@ export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '' }) => {
|
||||
// already-saved sites keep deserializing cleanly.
|
||||
return React.createElement('div', {
|
||||
ref: setRef,
|
||||
// Hook for the editor's mobile-frame mirror of the published HtmlBlock net (editor.css).
|
||||
'data-wsb-html': '',
|
||||
style: {
|
||||
minHeight: '40px',
|
||||
outline: selected ? '2px solid #3b82f6' : 'none',
|
||||
@@ -400,8 +402,17 @@ HtmlBlock.craft = {
|
||||
|
||||
/* ---------- HTML export ---------- */
|
||||
|
||||
/**
|
||||
* Mobile safety net hook: the exporter wraps the block's output in this element
|
||||
* (after injecting the node's data attrs, so `html` itself stays byte-identical
|
||||
* to every earlier release). Inline `display:contents` = no box, on every
|
||||
* viewport: layout is unchanged everywhere. It only scopes the head's <=767px
|
||||
* media/table rules (RESPONSIVE_CSS in utils/html-export.ts).
|
||||
*/
|
||||
export const HTML_BLOCK_WRAP: [string, string] = ['<div data-wsb-html style="display:contents">', '</div>'];
|
||||
|
||||
(HtmlBlock as any).toHtml = (props: HtmlBlockProps, _childrenHtml: string) => {
|
||||
// Run through the same DOMPurify config used for the live editor preview
|
||||
// so exported pages can't carry <script>/on*= payloads either.
|
||||
return { html: purifyHtml(props.code || '') };
|
||||
return { html: purifyHtml(props.code || ''), wrap: HTML_BLOCK_WRAP };
|
||||
};
|
||||
@@ -6,7 +6,7 @@ const toHtml = (Icon as any).toHtml;
|
||||
describe('Icon.toHtml normal rendering', () => {
|
||||
test('renders icon class, size/color style, and link href', () => {
|
||||
const { html } = toHtml({ icon: 'fa-star', size: '32px', color: '#3b82f6', link: 'https://example.com' }, '');
|
||||
expect(html).toContain('class="fa fa-star"');
|
||||
expect(html).toContain('class="fa-solid fa-star"');
|
||||
expect(html).toContain('font-size:32px');
|
||||
expect(html).toContain('color:#3b82f6');
|
||||
expect(html).toContain('href="https://example.com"');
|
||||
@@ -70,3 +70,15 @@ describe('Icon.craft.props includes the box-model/animation/visibility rollout p
|
||||
expect(props).toHaveProperty('hideOnMobile', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Icon.toHtml palette token fallback (Refs #44)', () => {
|
||||
test('colour absent -> primary token', () => {
|
||||
const { html } = toHtml({ icon: 'fa-star', size: '32px' }, '');
|
||||
expect(html).toContain('color:var(--wsb-primary)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
});
|
||||
test('an explicit colour still wins', () => {
|
||||
const { html } = toHtml({ icon: 'fa-star', size: '32px', color: '#ff0000' }, '');
|
||||
expect(html).toContain('color:#ff0000');
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { faClass } from '../../utils/fa-icon';
|
||||
|
||||
interface IconProps {
|
||||
icon?: string;
|
||||
@@ -29,7 +31,7 @@ function getBgBorderRadius(shape: string): string {
|
||||
export const Icon: UserComponent<IconProps> = ({
|
||||
icon = 'fa-star',
|
||||
size = '32px',
|
||||
color = '#3b82f6',
|
||||
color = tokenRef('primary'),
|
||||
bgColor = 'transparent',
|
||||
bgShape = 'none',
|
||||
bgSize = '56px',
|
||||
@@ -45,7 +47,7 @@ export const Icon: UserComponent<IconProps> = ({
|
||||
|
||||
const iconEl = (
|
||||
<i
|
||||
className={`fa ${icon}`}
|
||||
className={faClass(icon)}
|
||||
style={{ fontSize: size, color, lineHeight: 1 }}
|
||||
/>
|
||||
);
|
||||
@@ -95,7 +97,7 @@ Icon.craft = {
|
||||
props: {
|
||||
icon: 'fa-star',
|
||||
size: '32px',
|
||||
color: '#3b82f6',
|
||||
color: tokenRef('primary'),
|
||||
bgColor: 'transparent',
|
||||
bgShape: 'none',
|
||||
bgSize: '56px',
|
||||
@@ -120,7 +122,7 @@ Icon.craft = {
|
||||
const {
|
||||
icon = 'fa-star',
|
||||
size = '32px',
|
||||
color = '#3b82f6',
|
||||
color = tokenRef('primary'),
|
||||
bgColor = 'transparent',
|
||||
bgShape = 'none',
|
||||
bgSize = '56px',
|
||||
@@ -129,7 +131,7 @@ Icon.craft = {
|
||||
} = props;
|
||||
|
||||
const iconStyle = cssPropsToString({ fontSize: size, color, lineHeight: '1' });
|
||||
let iconHtml = `<i class="fa ${escapeAttr(icon)}"${iconStyle ? ` style="${iconStyle}"` : ''}></i>`;
|
||||
let iconHtml = `<i class="${escapeAttr(faClass(icon))}"${iconStyle ? ` style="${iconStyle}"` : ''}></i>`;
|
||||
|
||||
const hasBg = bgShape !== 'none' && bgColor !== 'transparent';
|
||||
if (hasBg) {
|
||||
|
||||
@@ -83,3 +83,12 @@ describe('Logo.toHtml text-logo styling sanitization', () => {
|
||||
expect(html).toContain('MySite');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Logo.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ text: "Acme" }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["text"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#1f2937"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
@@ -125,7 +126,7 @@ Logo.craft = {
|
||||
fontWeight: props.fontWeight || '700',
|
||||
fontSize: props.fontSize || '20px',
|
||||
fontFamily: props.fontFamily || 'Inter, sans-serif',
|
||||
color: props.color || '#1f2937',
|
||||
color: props.color || tokenRef('text'),
|
||||
});
|
||||
innerHtml = `<span${spanStyle ? ` style="${spanStyle}"` : ''}>${escapeHtml(props.text || 'MySite')}</span>`;
|
||||
}
|
||||
|
||||
@@ -67,3 +67,53 @@ describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
|
||||
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Menu.toHtml dropdowns (#53)', () => {
|
||||
const nested = [
|
||||
{ text: 'Home', href: '/' },
|
||||
{ text: 'Services', href: '/services', children: [
|
||||
{ text: 'Web', href: '/web' },
|
||||
{ text: 'Bad', href: 'javascript:alert(1)' },
|
||||
] },
|
||||
{ text: 'Go', href: '#go', isCta: true },
|
||||
];
|
||||
|
||||
test('a link with children emits the dropdown wrapper, aria-* toggle, inline script and submenu', () => {
|
||||
const { html } = toHtml({ links: nested }, '', 'node-dd');
|
||||
expect(html).toMatch(/<div class="[a-z0-9_-]+-dd"><a href="\/services"[^>]*>Services<\/a><button type="button" class="[a-z0-9_-]+-dd-toggle" aria-haspopup="true" aria-expanded="false" aria-label="Services submenu" onclick="[^"]*aria-expanded[^"]*">/);
|
||||
expect(html).toMatch(/<ul class="[a-z0-9_-]+-sub"><li><a href="\/web"[^>]*>Web<\/a><\/li>/);
|
||||
expect(html).toMatch(/-dd:focus-within > \.[a-z0-9_-]+-sub/);
|
||||
expect(html).toMatch(/-dd:hover > \.[a-z0-9_-]+-sub/);
|
||||
});
|
||||
|
||||
test('safeUrl is applied to child hrefs', () => {
|
||||
const { html } = toHtml({ links: nested }, '', 'node-dd');
|
||||
expect(html).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
test('no children -> no dropdown markup, CSS or script (legacy output unchanged)', () => {
|
||||
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }, { text: 'About', href: '/about' }] }, '', 'node-flat');
|
||||
expect(html).not.toContain('aria-haspopup');
|
||||
expect(html).not.toContain('onclick');
|
||||
expect(html).not.toContain('-sub');
|
||||
});
|
||||
|
||||
test('default hover + CTA colours are the primary token', () => {
|
||||
const { html } = toHtml({}, '', 'node-tok');
|
||||
expect(html).toMatch(/:hover\s*\{\s*color:\s*var\(--wsb-primary\)/);
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect((Menu as any).craft.props.linkHoverColor).toBe('var(--wsb-primary)');
|
||||
expect((Menu as any).craft.props.ctaBgColor).toBe('var(--wsb-primary)');
|
||||
expect((Menu as any).craft.props.followPages).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Menu.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((Menu as any).craft.props as object) };
|
||||
const { html } = (((Menu) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['text', 'bg']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ['#3f3f46']) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
@@ -2,20 +2,17 @@ import React, { CSSProperties, useState } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { NavLink, DROPDOWN_TOGGLE_ONCLICK, hasDropdown } from '../../utils/nav-links';
|
||||
|
||||
/* ---------- Types ---------- */
|
||||
|
||||
interface MenuLink {
|
||||
text: string;
|
||||
href: string;
|
||||
isExternal?: boolean;
|
||||
isCta?: boolean;
|
||||
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
|
||||
download?: boolean;
|
||||
}
|
||||
type MenuLink = NavLink;
|
||||
|
||||
interface MenuProps {
|
||||
links?: MenuLink[];
|
||||
/** #53: links follow the site's pages (materialised by PageContext). */
|
||||
followPages?: boolean;
|
||||
alignment?: 'left' | 'center' | 'right';
|
||||
linkColor?: string;
|
||||
linkHoverColor?: string;
|
||||
@@ -46,10 +43,10 @@ const defaultLinks: MenuLink[] = [
|
||||
export const Menu: UserComponent<MenuProps> = ({
|
||||
links = defaultLinks,
|
||||
alignment = 'right',
|
||||
linkColor = '#3f3f46',
|
||||
linkHoverColor = '#3b82f6',
|
||||
ctaBgColor = '#3b82f6',
|
||||
ctaTextColor = '#ffffff',
|
||||
linkColor = tokenRef('text'),
|
||||
linkHoverColor = tokenRef('primary'),
|
||||
ctaBgColor = tokenRef('primary'),
|
||||
ctaTextColor = tokenRef('bg'),
|
||||
gap = '24px',
|
||||
orientation = 'horizontal',
|
||||
fontSize = '14px',
|
||||
@@ -60,6 +57,7 @@ export const Menu: UserComponent<MenuProps> = ({
|
||||
} = useNode();
|
||||
|
||||
const [hoveredLink, setHoveredLink] = useState<number | null>(null);
|
||||
const [openDropdown, setOpenDropdown] = useState<number | null>(null);
|
||||
|
||||
const justifyMap = { left: 'flex-start', center: 'center', right: 'flex-end' };
|
||||
|
||||
@@ -76,7 +74,9 @@ export const Menu: UserComponent<MenuProps> = ({
|
||||
...style,
|
||||
}}
|
||||
>
|
||||
{links.map((link, i) => (
|
||||
{links.map((link, i) => {
|
||||
const kids = !link.isCta && link.children?.length ? link.children : null;
|
||||
const anchor = (
|
||||
<a
|
||||
key={i}
|
||||
href={link.href}
|
||||
@@ -102,22 +102,59 @@ export const Menu: UserComponent<MenuProps> = ({
|
||||
>
|
||||
{link.text}
|
||||
</a>
|
||||
))}
|
||||
);
|
||||
if (!kids) return anchor;
|
||||
// #53: one-level dropdown, opened on hover in the editor (export: hover,
|
||||
// focus-within and a click toggle -- see toHtml).
|
||||
return (
|
||||
<span
|
||||
key={i}
|
||||
style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 4 }}
|
||||
onMouseEnter={() => setOpenDropdown(i)}
|
||||
onMouseLeave={() => setOpenDropdown(null)}
|
||||
>
|
||||
{anchor}
|
||||
<span aria-hidden="true" style={{ fontSize, color: linkColor }}>▾</span>
|
||||
{(openDropdown === i || orientation === 'vertical') && (
|
||||
<ul style={orientation === 'vertical' ? SUB_STATIC_STYLE : SUB_STYLE}>
|
||||
{kids.map((child, j) => (
|
||||
<li key={j}>
|
||||
<a
|
||||
href={child.href}
|
||||
onClick={(e) => e.preventDefault()}
|
||||
style={{ display: 'block', padding: '6px 16px', whiteSpace: 'nowrap', textDecoration: 'none', fontSize, color: linkColor }}
|
||||
>
|
||||
{child.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
|
||||
const SUB_STYLE: CSSProperties = {
|
||||
position: 'absolute', top: '100%', left: 0, zIndex: 1001, minWidth: 180, margin: 0, padding: '8px 0',
|
||||
listStyle: 'none', background: tokenRef('bg'), borderRadius: 6, boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
|
||||
};
|
||||
const SUB_STATIC_STYLE: CSSProperties = { margin: 0, padding: '4px 0 0 12px', listStyle: 'none' };
|
||||
|
||||
/* ---------- Craft config ---------- */
|
||||
|
||||
Menu.craft = {
|
||||
displayName: 'Menu',
|
||||
props: {
|
||||
links: defaultLinks,
|
||||
followPages: false,
|
||||
alignment: 'right',
|
||||
linkColor: '#3f3f46',
|
||||
linkHoverColor: '#3b82f6',
|
||||
ctaBgColor: '#3b82f6',
|
||||
ctaTextColor: '#ffffff',
|
||||
linkColor: tokenRef('text'),
|
||||
linkHoverColor: tokenRef('primary'),
|
||||
ctaBgColor: tokenRef('primary'),
|
||||
ctaTextColor: tokenRef('bg'),
|
||||
gap: '24px',
|
||||
orientation: 'horizontal',
|
||||
fontSize: '14px',
|
||||
@@ -142,10 +179,10 @@ Menu.craft = {
|
||||
// string-interpolation sinks below (hoverCol goes into a <style> block,
|
||||
// the worst case: </style> breakout -> arbitrary <script>), see
|
||||
// task-cssxss-brief.md.
|
||||
const linkCol = cssValue(props.linkColor) || '#3f3f46';
|
||||
const hoverCol = cssValue(props.linkHoverColor) || '#3b82f6';
|
||||
const ctaBg = cssValue(props.ctaBgColor) || '#3b82f6';
|
||||
const ctaText = cssValue(props.ctaTextColor) || '#ffffff';
|
||||
const linkCol = cssValue(props.linkColor) || tokenRef('text');
|
||||
const hoverCol = cssValue(props.linkHoverColor) || tokenRef('primary');
|
||||
const ctaBg = cssValue(props.ctaBgColor) || tokenRef('primary');
|
||||
const ctaText = cssValue(props.ctaTextColor) || tokenRef('bg');
|
||||
const gap = cssValue(props.gap) || '24px';
|
||||
const orientation = props.orientation || 'horizontal';
|
||||
const alignment = props.alignment || 'right';
|
||||
@@ -173,7 +210,7 @@ Menu.craft = {
|
||||
// would let one instance's hover styling bleed into the other's).
|
||||
const scope = scopeId(nodeId, JSON.stringify(links) + orientation + alignment, 'menu');
|
||||
|
||||
const linksHtml = links.map((link) => {
|
||||
const anchorHtml = (link: MenuLink) => {
|
||||
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||
const downloadAttr = link.download ? ' download' : '';
|
||||
const cls = link.isCta ? `${scope}-cta` : `${scope}-link`;
|
||||
@@ -188,11 +225,30 @@ Menu.craft = {
|
||||
transition: 'color 0.15s, background-color 0.15s',
|
||||
});
|
||||
return `<a href="${escapeAttr(safeUrl(link.href || '#'))}" class="${cls}"${target}${downloadAttr}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
|
||||
};
|
||||
|
||||
// #53: a (non-CTA) link with children becomes a dropdown: the parent link
|
||||
// still navigates; a separate toggle button opens the submenu on touch /
|
||||
// click (hover and focus-within open it on desktop, see dropdownCss).
|
||||
const linksHtml = links.map((link) => {
|
||||
if (link.isCta || !link.children?.length) return anchorHtml(link);
|
||||
const kids = link.children.map((child) => `<li>${anchorHtml({ ...child, isCta: false })}</li>`).join('');
|
||||
return `<div class="${scope}-dd">${anchorHtml(link)}<button type="button" class="${scope}-dd-toggle" aria-haspopup="true" aria-expanded="false" aria-label="${escapeAttr(`${link.text} submenu`)}" onclick="${DROPDOWN_TOGGLE_ONCLICK}">▾</button><ul class="${scope}-sub">${kids}</ul></div>`;
|
||||
}).join('\n ');
|
||||
|
||||
const dropdownCss = hasDropdown(links) ? `
|
||||
.${scope}-dd { position: relative; display: inline-flex; align-items: center; gap: 2px; }
|
||||
.${scope}-dd-toggle { background: none; border: 0; margin: 0; padding: 2px 4px; cursor: pointer; color: ${linkCol}; font-size: ${fSize}; line-height: 1; }
|
||||
.${scope}-sub { display: none; position: absolute; top: 100%; left: 0; z-index: 1001; min-width: 180px; margin: 0; padding: 8px 0; list-style: none; background: ${tokenRef('bg')}; border-radius: 6px; box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
|
||||
.${scope}-dd:hover > .${scope}-sub, .${scope}-dd:focus-within > .${scope}-sub, .${scope}-dd.is-open > .${scope}-sub { display: block; }
|
||||
.${scope}-sub a { display: block !important; padding: 6px 16px !important; white-space: nowrap; }${orientation === 'vertical' ? `
|
||||
.${scope}-dd { flex-wrap: wrap; }
|
||||
.${scope}-sub { display: block; position: static; box-shadow: none; background: transparent; min-width: 0; padding: 4px 0 0 12px; flex-basis: 100%; }
|
||||
.${scope}-dd-toggle { display: none; }` : ''}` : '';
|
||||
|
||||
const hoverCss = `<style>
|
||||
.${scope}-link:hover { color: ${hoverCol} !important; }
|
||||
.${scope}-cta:hover { filter: brightness(1.1); }
|
||||
.${scope}-cta:hover { filter: brightness(1.1); }${dropdownCss}
|
||||
</style>`;
|
||||
|
||||
return {
|
||||
|
||||
@@ -140,3 +140,68 @@ describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into
|
||||
expect(html).toContain('background-color:#123456');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navbar.toHtml dropdowns (#53)', () => {
|
||||
const nested = [
|
||||
{ text: 'Home', href: '/' },
|
||||
{ text: 'Services', href: '/services', source: 'page', pageId: 's', children: [
|
||||
{ text: 'Web', href: '/web', source: 'page', pageId: 'w' },
|
||||
{ text: 'Bad', href: 'javascript:alert(1)' },
|
||||
] },
|
||||
{ text: 'Go', href: '#go', isCta: true },
|
||||
];
|
||||
|
||||
test('a link with children emits the dropdown wrapper, aria-* toggle, inline script and submenu', () => {
|
||||
const { html } = toHtml({ links: nested }, '', 'node-dd');
|
||||
expect(html).toMatch(/<div class="navbar-dd"><a href="\/services" class="navbar-link"[^>]*>Services<\/a><button type="button" class="navbar-dd-toggle" aria-haspopup="true" aria-expanded="false" aria-label="Services submenu" onclick="[^"]*is-open[^"]*aria-expanded[^"]*">/);
|
||||
expect(html).toMatch(/<ul class="navbar-sub"><li><a href="\/web" class="navbar-link"[^>]*>Web<\/a><\/li>/);
|
||||
expect(html).toContain('.navbar-dd:focus-within > .navbar-sub');
|
||||
});
|
||||
|
||||
test('safeUrl is applied to child hrefs', () => {
|
||||
const { html } = toHtml({ links: nested }, '', 'node-dd');
|
||||
expect(html).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
test('hamburger layout lists children indented (static submenu in the mobile media query)', () => {
|
||||
const { html } = toHtml({ links: nested, showMobileMenu: true }, '', 'node-dd-m');
|
||||
const media = html.slice(html.indexOf('@media'));
|
||||
expect(media).toMatch(/\.navbar-sub \{ display: block; position: static;[^}]*padding: 4px 0 0 16px/);
|
||||
});
|
||||
|
||||
test('no children -> no dropdown markup, CSS or script', () => {
|
||||
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }] }, '', 'node-flat');
|
||||
expect(html).not.toContain('aria-haspopup');
|
||||
expect(html).not.toContain('navbar-dd');
|
||||
expect(html).not.toContain('onclick');
|
||||
});
|
||||
|
||||
test('default hover + CTA colours are the primary token', () => {
|
||||
const { html } = toHtml({}, '', 'node-tok');
|
||||
expect(html).toMatch(/\.navbar-link:hover \{ color: var\(--wsb-primary\)/);
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect((Navbar as any).craft.props.hoverColor).toBe('var(--wsb-primary)');
|
||||
expect((Navbar as any).craft.props.ctaColor).toBe('var(--wsb-primary)');
|
||||
expect((Navbar as any).craft.props.followPages).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navbar.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((Navbar as any).craft.props as object) };
|
||||
const { html } = (((Navbar) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['text', 'bg', 'border']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ['#3f3f46', '#e4e4e7']) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navbar mobile menu default', () => {
|
||||
test('NEW Navbars (craft defaults) get the hamburger; a stored Navbar without the prop keeps its output', async () => {
|
||||
const { Navbar } = await import('./Navbar');
|
||||
expect((Navbar as any).craft.props.showMobileMenu).toBe(true);
|
||||
const toHtml = (Navbar as any).toHtml;
|
||||
expect(toHtml({}, '', 'n1').html).not.toContain('navbar-hamburger"');
|
||||
expect(toHtml({ showMobileMenu: true }, '', 'n1').html).toContain('class="navbar-hamburger"');
|
||||
});
|
||||
});
|
||||
@@ -3,18 +3,12 @@ import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, cssValue, scopeId } from '../../utils/escape';
|
||||
import { isLightColor } from '../../utils/color';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { NavLink, DROPDOWN_TOGGLE_ONCLICK, hasDropdown } from '../../utils/nav-links';
|
||||
|
||||
/* ---------- Types ---------- */
|
||||
|
||||
interface NavLink {
|
||||
text: string;
|
||||
href: string;
|
||||
isExternal?: boolean;
|
||||
isCta?: boolean;
|
||||
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
|
||||
download?: boolean;
|
||||
}
|
||||
|
||||
interface NavbarProps {
|
||||
logoType?: 'text' | 'image';
|
||||
logoText?: string;
|
||||
@@ -25,6 +19,8 @@ interface NavbarProps {
|
||||
logoFontSize?: string;
|
||||
logoColor?: string;
|
||||
links?: NavLink[];
|
||||
/** #53: links follow the site's pages (materialised by PageContext). */
|
||||
followPages?: boolean;
|
||||
backgroundColor?: string;
|
||||
textColor?: string;
|
||||
hoverColor?: string;
|
||||
@@ -58,6 +54,11 @@ const PADDING_PRESETS = [
|
||||
{ label: 'Spacious', value: '24px 48px' },
|
||||
];
|
||||
|
||||
function isLightNavBg(bg: string): boolean {
|
||||
const v = (bg || '').trim().toLowerCase();
|
||||
return v === tokenRef('bg') || isLightColor(v);
|
||||
}
|
||||
|
||||
/* ---------- Component ---------- */
|
||||
|
||||
export const Navbar: UserComponent<NavbarProps> = ({
|
||||
@@ -70,11 +71,11 @@ export const Navbar: UserComponent<NavbarProps> = ({
|
||||
logoFontSize = '20px',
|
||||
logoColor,
|
||||
links = defaultLinks,
|
||||
backgroundColor = '#ffffff',
|
||||
textColor = '#3f3f46',
|
||||
hoverColor = '#3b82f6',
|
||||
ctaColor = '#3b82f6',
|
||||
ctaTextColor = '#ffffff',
|
||||
backgroundColor = tokenRef('bg'),
|
||||
textColor = tokenRef('text'),
|
||||
hoverColor = tokenRef('primary'),
|
||||
ctaColor = tokenRef('primary'),
|
||||
ctaTextColor = tokenRef('bg'),
|
||||
padding = '16px 24px',
|
||||
navAlignment = 'space-between',
|
||||
isSticky = false,
|
||||
@@ -89,10 +90,18 @@ export const Navbar: UserComponent<NavbarProps> = ({
|
||||
}));
|
||||
|
||||
const { design } = useSiteDesign();
|
||||
const resolvedLogoColor = logoColor || (backgroundColor === '#ffffff' || backgroundColor === '#f8fafc' || backgroundColor === '#f9fafb' ? design.textColor : '#ffffff');
|
||||
const resolvedTextColor = textColor || (backgroundColor === '#ffffff' || backgroundColor === '#f8fafc' || backgroundColor === '#f9fafb' ? '#3f3f46' : '#e4e4e7');
|
||||
// Light-background heuristic: the bg token counts as light (it is the page
|
||||
// background); legacy stored hex values keep the old hex test. White/zinc on
|
||||
// an explicitly dark bar is "text on a dark custom colour" -- no token fits.
|
||||
const lightBg = isLightNavBg(backgroundColor);
|
||||
const resolvedTextColor = textColor || (lightBg ? tokenRef('text') : '#e4e4e7');
|
||||
// A STORED light hex bar (legacy nodes: '#ffffff' + textColor '#3f3f46') must not
|
||||
// take the logo colour from the Site Design text, which is light on a dark design;
|
||||
// follow the link text, exactly as toHtml does (`logoColor || textCol`).
|
||||
const resolvedLogoColor = logoColor || (isLightColor(backgroundColor) ? resolvedTextColor : lightBg ? design.textColor : '#ffffff');
|
||||
|
||||
const [hoveredLink, setHoveredLink] = useState<number | null>(null);
|
||||
const [openDropdown, setOpenDropdown] = useState<number | null>(null);
|
||||
|
||||
return (
|
||||
<nav
|
||||
@@ -150,7 +159,9 @@ export const Navbar: UserComponent<NavbarProps> = ({
|
||||
<span style={{ display: 'block', width: '24px', height: '2px', backgroundColor: resolvedTextColor }} />
|
||||
</div>
|
||||
)}
|
||||
{links.map((link, i) => (
|
||||
{links.map((link, i) => {
|
||||
const kids = !link.isCta && link.children?.length ? link.children : null;
|
||||
const anchor = (
|
||||
<a
|
||||
key={i}
|
||||
href={link.href}
|
||||
@@ -176,7 +187,37 @@ export const Navbar: UserComponent<NavbarProps> = ({
|
||||
>
|
||||
{link.text}
|
||||
</a>
|
||||
))}
|
||||
);
|
||||
if (!kids) return anchor;
|
||||
// #53: one-level dropdown, opened on hover in the editor (export:
|
||||
// hover, focus-within and a click toggle -- see toHtml).
|
||||
return (
|
||||
<span
|
||||
key={i}
|
||||
style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 4 }}
|
||||
onMouseEnter={() => setOpenDropdown(i)}
|
||||
onMouseLeave={() => setOpenDropdown(null)}
|
||||
>
|
||||
{anchor}
|
||||
<span aria-hidden="true" style={{ fontSize: '14px', color: resolvedTextColor }}>▾</span>
|
||||
{openDropdown === i && (
|
||||
<ul style={{ position: 'absolute', top: '100%', left: 0, zIndex: 1001, minWidth: 180, margin: 0, padding: '8px 0', listStyle: 'none', background: backgroundColor, borderRadius: 6, boxShadow: '0 8px 24px rgba(0,0,0,0.12)' }}>
|
||||
{kids.map((child, j) => (
|
||||
<li key={j}>
|
||||
<a
|
||||
href={child.href}
|
||||
onClick={(e) => e.preventDefault()}
|
||||
style={{ display: 'block', padding: '6px 16px', whiteSpace: 'nowrap', textDecoration: 'none', fontSize: '14px', color: resolvedTextColor }}
|
||||
>
|
||||
{child.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
@@ -196,17 +237,20 @@ Navbar.craft = {
|
||||
logoFontSize: '20px',
|
||||
logoColor: undefined,
|
||||
links: defaultLinks,
|
||||
backgroundColor: '#ffffff',
|
||||
textColor: '#3f3f46',
|
||||
hoverColor: '#3b82f6',
|
||||
ctaColor: '#3b82f6',
|
||||
ctaTextColor: '#ffffff',
|
||||
followPages: false,
|
||||
backgroundColor: tokenRef('bg'),
|
||||
textColor: tokenRef('text'),
|
||||
hoverColor: tokenRef('primary'),
|
||||
ctaColor: tokenRef('primary'),
|
||||
ctaTextColor: tokenRef('bg'),
|
||||
padding: '16px 24px',
|
||||
navAlignment: 'space-between',
|
||||
isSticky: false,
|
||||
showMobileMenu: false,
|
||||
// On for NEW Navbars (links overflow a phone otherwise). The component's render default and toHtml
|
||||
// stay falsy so a stored Navbar that never had the prop keeps its exact output.
|
||||
showMobileMenu: true,
|
||||
style: {
|
||||
borderBottom: '1px solid #e4e4e7',
|
||||
borderBottom: `1px solid ${tokenRef('border')}`,
|
||||
},
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
@@ -227,11 +271,11 @@ Navbar.craft = {
|
||||
// Sanitized once here -- these are raw string-interpolation sinks below
|
||||
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||
const bgColor = cssValue(props.backgroundColor) || '#ffffff';
|
||||
const textCol = cssValue(props.textColor) || '#3f3f46';
|
||||
const hoverCol = cssValue(props.hoverColor) || '#3b82f6';
|
||||
const ctaCol = cssValue(props.ctaColor) || '#3b82f6';
|
||||
const ctaTextCol = cssValue(props.ctaTextColor) || '#ffffff';
|
||||
const bgColor = cssValue(props.backgroundColor) || tokenRef('bg');
|
||||
const textCol = cssValue(props.textColor) || tokenRef('text');
|
||||
const hoverCol = cssValue(props.hoverColor) || tokenRef('primary');
|
||||
const ctaCol = cssValue(props.ctaColor) || tokenRef('primary');
|
||||
const ctaTextCol = cssValue(props.ctaTextColor) || tokenRef('bg');
|
||||
const pad = cssValue(props.padding) || '16px 24px';
|
||||
const alignment = props.navAlignment || 'space-between';
|
||||
const sticky = props.isSticky;
|
||||
@@ -276,22 +320,8 @@ Navbar.craft = {
|
||||
logoHtml = `<a href="${escapeAttr(safeUrl(logoUrl))}" style="text-decoration:none;display:flex;align-items:center;flex-shrink:0"><span${logoStyle ? ` style="${logoStyle}"` : ''}>${escapeHtml(props.logoText || 'MySite')}</span></a>`;
|
||||
}
|
||||
|
||||
// Links HTML
|
||||
const links = props.links || defaultLinks;
|
||||
const linksHtml = links.map((link) => {
|
||||
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||
const linkStyle = cssPropsToString({
|
||||
textDecoration: 'none',
|
||||
fontSize: '14px',
|
||||
fontWeight: link.isCta ? '600' : '400',
|
||||
color: link.isCta ? ctaTextCol : textCol,
|
||||
backgroundColor: link.isCta ? ctaCol : 'transparent',
|
||||
padding: link.isCta ? '8px 20px' : '0',
|
||||
borderRadius: link.isCta ? '6px' : '0',
|
||||
transition: 'color 0.15s, background-color 0.15s',
|
||||
});
|
||||
return `<a href="${escapeAttr(safeUrl(link.href || "#"))}"${target}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
|
||||
}).join('\n ');
|
||||
const links = links0;
|
||||
const dropdown = hasDropdown(links);
|
||||
|
||||
// Hamburger HTML for mobile. The toggle needs an accessible name (there's
|
||||
// no visible text, just three bars) and must report its open/closed state
|
||||
@@ -310,16 +340,24 @@ Navbar.craft = {
|
||||
// into or get overridden by another Navbar instance's rules.
|
||||
const hoverCss = `<style>
|
||||
.${scope} .navbar-link:hover { color: ${hoverCol} !important; }
|
||||
.${scope} .navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
||||
.${scope} .navbar-cta:hover { filter: brightness(1.1); }${dropdown ? `
|
||||
.${scope} .navbar-dd { position: relative; display: inline-flex; align-items: center; gap: 2px; }
|
||||
.${scope} .navbar-dd-toggle { background: none; border: 0; margin: 0; padding: 2px 4px; cursor: pointer; color: ${textCol}; font-size: 14px; line-height: 1; }
|
||||
.${scope} .navbar-sub { display: none; position: absolute; top: 100%; left: 0; z-index: 1001; min-width: 180px; margin: 0; padding: 8px 0; list-style: none; background-color: ${bgColor}; border-radius: 6px; box-shadow: 0 8px 24px rgba(0,0,0,0.12); }
|
||||
.${scope} .navbar-dd:hover > .navbar-sub, .${scope} .navbar-dd:focus-within > .navbar-sub, .${scope} .navbar-dd.is-open > .navbar-sub { display: block; }
|
||||
.${scope} .navbar-sub a { display: block; padding: 6px 16px !important; white-space: nowrap; }` : ''}${mobile ? `
|
||||
@media (max-width: 768px) {
|
||||
.${scope} .navbar-hamburger { display: flex !important; }
|
||||
.${scope} .navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
||||
.${scope} .navbar-links.navbar-open { display: flex !important; }
|
||||
.${scope} .navbar-links.navbar-open { display: flex !important; }${dropdown ? `
|
||||
.${scope} .navbar-dd { flex-direction: column; align-items: flex-start; }
|
||||
.${scope} .navbar-dd-toggle { display: none; }
|
||||
.${scope} .navbar-sub { display: block; position: static; box-shadow: none; min-width: 0; padding: 4px 0 0 16px; }` : ''}
|
||||
}` : ''}
|
||||
</style>`;
|
||||
|
||||
// Add CSS class to each link for hover
|
||||
const linksHtmlWithClass = links.map((link) => {
|
||||
const anchorHtml = (link: NavLink) => {
|
||||
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||
const downloadAttr = link.download ? ' download' : '';
|
||||
const cls = link.isCta ? 'navbar-cta' : 'navbar-link';
|
||||
@@ -334,6 +372,16 @@ Navbar.craft = {
|
||||
transition: 'color 0.15s, background-color 0.15s',
|
||||
});
|
||||
return `<a href="${escapeAttr(safeUrl(link.href || "#"))}" class="${cls}"${target}${downloadAttr}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
|
||||
};
|
||||
|
||||
// #53: a (non-CTA) link with children becomes a dropdown: the parent link
|
||||
// still navigates; a separate toggle button opens the submenu on touch /
|
||||
// click (hover and focus-within open it on desktop). In the hamburger
|
||||
// layout the children are listed indented (see the media query above).
|
||||
const linksHtmlWithClass = links.map((link) => {
|
||||
if (link.isCta || !link.children?.length) return anchorHtml(link);
|
||||
const kids = link.children.map((child) => `<li>${anchorHtml({ ...child, isCta: false })}</li>`).join('');
|
||||
return `<div class="navbar-dd">${anchorHtml(link)}<button type="button" class="navbar-dd-toggle" aria-haspopup="true" aria-expanded="false" aria-label="${escapeAttr(`${link.text} submenu`)}" onclick="${DROPDOWN_TOGGLE_ONCLICK}">▾</button><ul class="navbar-sub">${kids}</ul></div>`;
|
||||
}).join('\n ');
|
||||
|
||||
return {
|
||||
|
||||
@@ -6,7 +6,7 @@ const toHtml = (SearchBar as any).toHtml;
|
||||
describe('SearchBar.toHtml decorative icons (F2.5)', () => {
|
||||
test('the input-adjacent search icon is aria-hidden', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
const icons = html.match(/<i class="fa fa-search"[^>]*>/g) || [];
|
||||
const icons = html.match(/<i class="fa-solid fa-magnifying-glass"[^>]*>/g) || [];
|
||||
expect(icons.length).toBeGreaterThan(0);
|
||||
icons.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||
});
|
||||
@@ -73,3 +73,22 @@ describe('SearchBar.craft.props includes animation/visibility defaults', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SearchBar.toHtml palette token fallbacks (Refs #44)', () => {
|
||||
test('button background is the primary token and input text is the text token', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect(html).toContain('color:var(--wsb-text)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
expect(html).not.toContain('#1f2937');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SearchBar.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border", "muted", "primary"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#d1d5db", "#9ca3af", "#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
interface SearchBarProps {
|
||||
placeholder?: string;
|
||||
@@ -50,13 +51,13 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
>
|
||||
<div style={{ position: 'relative', flex: 1 }}>
|
||||
<i
|
||||
className="fa fa-search"
|
||||
className="fa-solid fa-magnifying-glass"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: '14px',
|
||||
top: '50%',
|
||||
transform: 'translateY(-50%)',
|
||||
color: '#9ca3af',
|
||||
color: tokenRef('muted'),
|
||||
fontSize: '14px',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
@@ -70,10 +71,10 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
padding: '12px 16px 12px 40px',
|
||||
fontSize: '15px',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
border: '1px solid #d1d5db',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
borderRadius: showButton ? '8px 0 0 8px' : '8px',
|
||||
backgroundColor: '#ffffff',
|
||||
color: '#1f2937',
|
||||
backgroundColor: tokenRef('bg'),
|
||||
color: tokenRef('text'),
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
@@ -87,8 +88,8 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
fontSize: '15px',
|
||||
fontWeight: '600',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#ffffff',
|
||||
backgroundColor: '#3b82f6',
|
||||
color: tokenRef('bg'),
|
||||
backgroundColor: tokenRef('primary'),
|
||||
border: 'none',
|
||||
borderRadius: '0 8px 8px 0',
|
||||
cursor: 'pointer',
|
||||
@@ -98,7 +99,7 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
|
||||
gap: '6px',
|
||||
}}
|
||||
>
|
||||
<i className="fa fa-search" style={{ fontSize: '13px' }} />
|
||||
<i className="fa-solid fa-magnifying-glass" style={{ fontSize: '13px' }} />
|
||||
{buttonText}
|
||||
</button>
|
||||
)}
|
||||
@@ -147,10 +148,10 @@ SearchBar.craft = {
|
||||
...style,
|
||||
});
|
||||
|
||||
const inputStyleStr = `width:100%;padding:12px 16px 12px 40px;font-size:15px;font-family:Inter,sans-serif;border:1px solid #d1d5db;border-radius:${showButton ? '8px 0 0 8px' : '8px'};background-color:#ffffff;color:#1f2937;outline:none;box-sizing:border-box`;
|
||||
const inputStyleStr = `width:100%;padding:12px 16px 12px 40px;font-size:15px;font-family:Inter,sans-serif;border:1px solid ${tokenRef('border')};border-radius:${showButton ? '8px 0 0 8px' : '8px'};background-color:${tokenRef('bg')};color:${tokenRef('text')};outline:none;box-sizing:border-box`;
|
||||
|
||||
const btnHtml = showButton
|
||||
? `<button type="submit" style="padding:12px 20px;font-size:15px;font-weight:600;font-family:Inter,sans-serif;color:#ffffff;background-color:#3b82f6;border:none;border-radius:0 8px 8px 0;cursor:pointer;white-space:nowrap;display:flex;align-items:center;gap:6px"><i class="fa fa-search" style="font-size:13px" aria-hidden="true"></i>${escapeHtml(buttonText)}</button>`
|
||||
? `<button type="submit" style="padding:12px 20px;font-size:15px;font-weight:600;font-family:Inter,sans-serif;color:${tokenRef('bg')};background-color:${tokenRef('primary')};border:none;border-radius:0 8px 8px 0;cursor:pointer;white-space:nowrap;display:flex;align-items:center;gap:6px"><i class="fa-solid fa-magnifying-glass" style="font-size:13px" aria-hidden="true"></i>${escapeHtml(buttonText)}</button>`
|
||||
: '';
|
||||
|
||||
// F2: previously a purely decorative <form> -- no action/method/input
|
||||
@@ -164,7 +165,7 @@ SearchBar.craft = {
|
||||
return {
|
||||
html: `<form role="search" action="${actionAttr}" method="GET"${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
<div style="position:relative;flex:1">
|
||||
<i class="fa fa-search" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#9ca3af;font-size:14px;pointer-events:none" aria-hidden="true"></i>
|
||||
<i class="fa-solid fa-magnifying-glass" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);color:${tokenRef('muted')};font-size:14px;pointer-events:none" aria-hidden="true"></i>
|
||||
<input type="search" name="q" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
|
||||
</div>
|
||||
${btnHtml}
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('SocialLinks.toHtml accessibility (F2.5)', () => {
|
||||
|
||||
test('the icon glyph itself is aria-hidden', () => {
|
||||
const { html } = toHtml({ links: [{ platform: 'twitter', url: '#' }] }, '');
|
||||
expect(html).toMatch(/<i class="fa fa-twitter"[^>]*aria-hidden="true"/);
|
||||
expect(html).toMatch(/<i class="fa-brands fa-x-twitter"[^>]*aria-hidden="true"/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -91,3 +91,13 @@ describe('SocialLinks.craft.props includes the box-model/animation/visibility ro
|
||||
expect(props).toHaveProperty('hideOnMobile', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SocialLinks.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((SocialLinks as any).craft.props as object) };
|
||||
const { html } = (((SocialLinks) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['text', 'bg']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ['#374151']) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
||||
|
||||
interface SocialLink {
|
||||
@@ -25,18 +26,24 @@ interface SocialLinksProps {
|
||||
}
|
||||
|
||||
const platformIcons: Record<string, string> = {
|
||||
facebook: 'fa-facebook',
|
||||
twitter: 'fa-twitter',
|
||||
instagram: 'fa-instagram',
|
||||
linkedin: 'fa-linkedin',
|
||||
youtube: 'fa-youtube',
|
||||
github: 'fa-github',
|
||||
tiktok: 'fa-music',
|
||||
pinterest: 'fa-pinterest',
|
||||
snapchat: 'fa-snapchat',
|
||||
whatsapp: 'fa-whatsapp',
|
||||
spotify: 'fa-spotify',
|
||||
twitch: 'fa-twitch',
|
||||
facebook: 'fa-brands fa-facebook',
|
||||
twitter: 'fa-brands fa-x-twitter',
|
||||
instagram: 'fa-brands fa-instagram',
|
||||
linkedin: 'fa-brands fa-linkedin',
|
||||
youtube: 'fa-brands fa-youtube',
|
||||
github: 'fa-brands fa-github',
|
||||
tiktok: 'fa-brands fa-tiktok',
|
||||
pinterest: 'fa-brands fa-pinterest',
|
||||
snapchat: 'fa-brands fa-snapchat',
|
||||
whatsapp: 'fa-brands fa-whatsapp',
|
||||
spotify: 'fa-brands fa-spotify',
|
||||
bluesky: 'fa-brands fa-bluesky',
|
||||
threads: 'fa-brands fa-threads',
|
||||
discord: 'fa-brands fa-discord',
|
||||
mastodon: 'fa-brands fa-mastodon',
|
||||
reddit: 'fa-brands fa-reddit',
|
||||
telegram: 'fa-brands fa-telegram',
|
||||
twitch: 'fa-brands fa-twitch',
|
||||
};
|
||||
|
||||
const platformLabels: Record<string, string> = {
|
||||
@@ -52,6 +59,12 @@ const platformLabels: Record<string, string> = {
|
||||
whatsapp: 'WhatsApp',
|
||||
spotify: 'Spotify',
|
||||
twitch: 'Twitch',
|
||||
bluesky: 'Bluesky',
|
||||
threads: 'Threads',
|
||||
discord: 'Discord',
|
||||
mastodon: 'Mastodon',
|
||||
reddit: 'Reddit',
|
||||
telegram: 'Telegram',
|
||||
};
|
||||
|
||||
const defaultLinks: SocialLink[] = [
|
||||
@@ -87,8 +100,8 @@ const alignMap: Record<string, string> = {
|
||||
export const SocialLinks: UserComponent<SocialLinksProps> = ({
|
||||
links = defaultLinks,
|
||||
iconSize = '20px',
|
||||
iconColor = '#ffffff',
|
||||
iconBgColor = '#374151',
|
||||
iconColor = tokenRef('bg'),
|
||||
iconBgColor = tokenRef('text'),
|
||||
iconShape = 'circle',
|
||||
gap = '10px',
|
||||
alignment = 'center',
|
||||
@@ -115,7 +128,7 @@ export const SocialLinks: UserComponent<SocialLinksProps> = ({
|
||||
}}
|
||||
>
|
||||
{links.map((link, i) => {
|
||||
const iconClass = platformIcons[link.platform] || 'fa-link';
|
||||
const iconClass = platformIcons[link.platform] || 'fa-solid fa-link';
|
||||
const shapeStyle = getShapeStyle(iconShape, iconSize);
|
||||
const hasBg = iconShape !== 'none';
|
||||
|
||||
@@ -135,7 +148,7 @@ export const SocialLinks: UserComponent<SocialLinksProps> = ({
|
||||
...shapeStyle,
|
||||
}}
|
||||
>
|
||||
<i className={`fa ${iconClass}`} style={{ fontSize: iconSize }} />
|
||||
<i className={iconClass} style={{ fontSize: iconSize }} />
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
@@ -150,8 +163,8 @@ SocialLinks.craft = {
|
||||
props: {
|
||||
links: defaultLinks,
|
||||
iconSize: '20px',
|
||||
iconColor: '#ffffff',
|
||||
iconBgColor: '#374151',
|
||||
iconColor: tokenRef('bg'),
|
||||
iconBgColor: tokenRef('text'),
|
||||
iconShape: 'circle',
|
||||
gap: '10px',
|
||||
alignment: 'center',
|
||||
@@ -175,8 +188,8 @@ SocialLinks.craft = {
|
||||
const links = props.links || defaultLinks;
|
||||
// Sanitized -- raw string-interpolation sinks in aStyle/getShapeStr below.
|
||||
const iconSize = cssValue(props.iconSize) || '20px';
|
||||
const iconColor = cssValue(props.iconColor) || '#ffffff';
|
||||
const iconBgColor = cssValue(props.iconBgColor) || '#374151';
|
||||
const iconColor = cssValue(props.iconColor) || tokenRef('bg');
|
||||
const iconBgColor = cssValue(props.iconBgColor) || tokenRef('text');
|
||||
const iconShape = props.iconShape || 'circle';
|
||||
const gap = props.gap || '10px';
|
||||
const alignment = props.alignment || 'center';
|
||||
@@ -209,7 +222,7 @@ SocialLinks.craft = {
|
||||
};
|
||||
|
||||
const linksHtml = links.map((link) => {
|
||||
const iconClass = platformIcons[link.platform] || 'fa-link';
|
||||
const iconClass = platformIcons[link.platform] || 'fa-solid fa-link';
|
||||
const title = platformLabels[link.platform] || link.platform;
|
||||
let aStyle = `text-decoration:none;color:${iconColor};background-color:${hasBg ? iconBgColor : 'transparent'}`;
|
||||
if (hasBg) {
|
||||
@@ -219,7 +232,7 @@ SocialLinks.craft = {
|
||||
// aria-hidden and the accessible name lives on the link (aria-label,
|
||||
// mirroring the existing `title` tooltip since title support in
|
||||
// screen readers is inconsistent).
|
||||
return `<a href="${escapeAttr(safeUrl(link.url || '#'))}" target="_blank" rel="noopener noreferrer" title="${escapeAttr(title)}" aria-label="${escapeAttr(title)}" style="${aStyle}"><i class="fa ${escapeAttr(iconClass)}" style="font-size:${iconSize}" aria-hidden="true"></i></a>`;
|
||||
return `<a href="${escapeAttr(safeUrl(link.url || '#'))}" target="_blank" rel="noopener noreferrer" title="${escapeAttr(title)}" aria-label="${escapeAttr(title)}" style="${aStyle}"><i class="${escapeAttr(iconClass)}" style="font-size:${iconSize}" aria-hidden="true"></i></a>`;
|
||||
}).join('\n ');
|
||||
|
||||
return {
|
||||
|
||||
@@ -11,7 +11,7 @@ describe('StarRating.toHtml accessibility (F2.2)', () => {
|
||||
|
||||
test('individual star glyphs are aria-hidden', () => {
|
||||
const { html } = toHtml({ rating: 3, maxStars: 5 }, '');
|
||||
const glyphs = html.match(/<i class="fa fa-star"[^>]*>/g) || [];
|
||||
const glyphs = html.match(/<i class="fa-solid fa-star"[^>]*>/g) || [];
|
||||
expect(glyphs.length).toBeGreaterThan(0);
|
||||
glyphs.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||
});
|
||||
@@ -58,7 +58,7 @@ describe('StarRating.toHtml XSS hardening (rating/maxStars into aria-label, F2.2
|
||||
test('a non-numeric maxStars does not blow up the star loop (no NaN glyph count, no huge output)', () => {
|
||||
const malicious = '5" onmouseover="alert(1)';
|
||||
const { html } = toHtml({ rating: 3, maxStars: malicious as any }, '');
|
||||
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||
const glyphs = html.match(/<i class="fa-solid fa-star"/g) || [];
|
||||
// Falls back to a sane default star count rather than looping 0 or NaN times.
|
||||
expect(glyphs.length).toBeGreaterThan(0);
|
||||
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||
@@ -66,7 +66,7 @@ describe('StarRating.toHtml XSS hardening (rating/maxStars into aria-label, F2.2
|
||||
|
||||
test('an absurdly large maxStars is clamped to a sane maximum instead of looping unboundedly', () => {
|
||||
const { html } = toHtml({ rating: 3, maxStars: 1e9 as any }, '');
|
||||
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||
const glyphs = html.match(/<i class="fa-solid fa-star"/g) || [];
|
||||
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||
});
|
||||
|
||||
@@ -86,3 +86,12 @@ describe('StarRating.craft.props includes the box-model/animation/visibility rol
|
||||
expect(props).toHaveProperty('hideOnMobile', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('StarRating.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["warning", "border"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#f59e0b", "#d1d5db"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { cssValue, escapeAttr } from '../../utils/escape';
|
||||
@@ -21,8 +22,8 @@ export const StarRating: UserComponent<StarRatingProps> = ({
|
||||
rating = 4.5,
|
||||
maxStars = 5,
|
||||
size = '24px',
|
||||
filledColor = '#f59e0b',
|
||||
emptyColor = '#d1d5db',
|
||||
filledColor = tokenRef('warning'),
|
||||
emptyColor = tokenRef('border'),
|
||||
style = {},
|
||||
}) => {
|
||||
const {
|
||||
@@ -39,7 +40,7 @@ export const StarRating: UserComponent<StarRatingProps> = ({
|
||||
stars.push(
|
||||
<i
|
||||
key={i}
|
||||
className="fa fa-star"
|
||||
className="fa-solid fa-star"
|
||||
style={{ color: filledColor, fontSize: size }}
|
||||
/>
|
||||
);
|
||||
@@ -47,9 +48,9 @@ export const StarRating: UserComponent<StarRatingProps> = ({
|
||||
// Half star
|
||||
stars.push(
|
||||
<span key={i} style={{ position: 'relative', display: 'inline-block', fontSize: size }}>
|
||||
<i className="fa fa-star" style={{ color: emptyColor }} />
|
||||
<i className="fa-solid fa-star" style={{ color: emptyColor }} />
|
||||
<span style={{ position: 'absolute', left: 0, top: 0, overflow: 'hidden', width: '50%' }}>
|
||||
<i className="fa fa-star" style={{ color: filledColor }} />
|
||||
<i className="fa-solid fa-star" style={{ color: filledColor }} />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
@@ -58,7 +59,7 @@ export const StarRating: UserComponent<StarRatingProps> = ({
|
||||
stars.push(
|
||||
<i
|
||||
key={i}
|
||||
className="fa fa-star"
|
||||
className="fa-solid fa-star"
|
||||
style={{ color: emptyColor, fontSize: size }}
|
||||
/>
|
||||
);
|
||||
@@ -89,8 +90,8 @@ StarRating.craft = {
|
||||
rating: 4.5,
|
||||
maxStars: 5,
|
||||
size: '24px',
|
||||
filledColor: '#f59e0b',
|
||||
emptyColor: '#d1d5db',
|
||||
filledColor: tokenRef('warning'),
|
||||
emptyColor: tokenRef('border'),
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
@@ -123,8 +124,8 @@ StarRating.craft = {
|
||||
: 5;
|
||||
// Sanitized -- raw string-interpolation sinks in the star glyphs below.
|
||||
const size = cssValue(props.size) || '24px';
|
||||
const filledColor = cssValue(props.filledColor) || '#f59e0b';
|
||||
const emptyColor = cssValue(props.emptyColor) || '#d1d5db';
|
||||
const filledColor = cssValue(props.filledColor) || tokenRef('warning');
|
||||
const emptyColor = cssValue(props.emptyColor) || tokenRef('border');
|
||||
const wrapperStyle = cssPropsToString({
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
@@ -135,11 +136,11 @@ StarRating.craft = {
|
||||
let starsHtml = '';
|
||||
for (let i = 1; i <= maxStars; i++) {
|
||||
if (i <= Math.floor(rating)) {
|
||||
starsHtml += `<i class="fa fa-star" style="color:${filledColor};font-size:${size}" aria-hidden="true"></i>`;
|
||||
starsHtml += `<i class="fa-solid fa-star" style="color:${filledColor};font-size:${size}" aria-hidden="true"></i>`;
|
||||
} else if (i === Math.ceil(rating) && rating % 1 !== 0) {
|
||||
starsHtml += `<span style="position:relative;display:inline-block;font-size:${size}" aria-hidden="true"><i class="fa fa-star" style="color:${emptyColor}"></i><span style="position:absolute;left:0;top:0;overflow:hidden;width:50%"><i class="fa fa-star" style="color:${filledColor}"></i></span></span>`;
|
||||
starsHtml += `<span style="position:relative;display:inline-block;font-size:${size}" aria-hidden="true"><i class="fa-solid fa-star" style="color:${emptyColor}"></i><span style="position:absolute;left:0;top:0;overflow:hidden;width:50%"><i class="fa-solid fa-star" style="color:${filledColor}"></i></span></span>`;
|
||||
} else {
|
||||
starsHtml += `<i class="fa fa-star" style="color:${emptyColor};font-size:${size}" aria-hidden="true"></i>`;
|
||||
starsHtml += `<i class="fa-solid fa-star" style="color:${emptyColor};font-size:${size}" aria-hidden="true"></i>`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,3 +65,62 @@ describe('TextBlock.craft.props exposes the box-model + animation/visibility rol
|
||||
expect(style.opacity).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TextBlock.toHtml inline rich text (#46)', () => {
|
||||
test('legacy plain text with html="" is escaped', () => {
|
||||
expect(toHtml({ text: 'a<b', html: '' }, '').html).toBe('<p>a<b</p>');
|
||||
});
|
||||
|
||||
test('marked html is emitted (html-only props)', () => {
|
||||
expect(toHtml({ html: '<b>Hi</b> there' }, '').html).toBe('<p><b>Hi</b> there</p>');
|
||||
});
|
||||
|
||||
test('html whose text mirror matches text is emitted', () => {
|
||||
expect(toHtml({ text: 'Hi there', html: '<b>Hi</b> there' }, '').html).toBe('<p><b>Hi</b> there</p>');
|
||||
});
|
||||
|
||||
test('text changed without html (e.g. AI update_props) wins over stale html', () => {
|
||||
expect(toHtml({ text: 'New <copy>', html: '<b>Old</b> copy' }, '').html).toBe('<p>New <copy></p>');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['<img src=x onerror=alert(1)>', '<img'],
|
||||
['<script>alert(1)</script>', '<script'],
|
||||
['<a href="javascript:alert(1)">x</a>', 'javascript:'],
|
||||
['<a href="javascript:alert(1)">x</a>', 'href'],
|
||||
['<b onclick="alert(1)">x</b>', 'onclick'],
|
||||
['<span style="position:fixed;inset:0">x</span>', 'position'],
|
||||
['</p><iframe src="https://evil"></iframe><p>', 'iframe'],
|
||||
['<svg onload=alert(1)>', 'onload'],
|
||||
])('malicious stored html is sanitised at export: %s', (html, banned) => {
|
||||
const out = toHtml({ html }, '').html as string;
|
||||
expect(out.toLowerCase()).not.toContain(banned);
|
||||
expect(out.startsWith('<p')).toBe(true);
|
||||
expect(out.endsWith('</p>')).toBe(true);
|
||||
});
|
||||
|
||||
test('external _blank link gets rel=noopener at export', () => {
|
||||
expect(toHtml({ html: '<a href="https://e.com" target="_blank">x</a>' }, '').html)
|
||||
.toBe('<p><a href="https://e.com" target="_blank" rel="noopener">x</a></p>');
|
||||
});
|
||||
|
||||
test('craft.props carries a blank html default', () => {
|
||||
expect((TextBlock as any).craft.props.html).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TextBlock.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ ...(TextBlock as any).craft.props }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["text"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#3f3f46"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TextBlock.toHtml newlines (canvas parity)', () => {
|
||||
test('plain text newlines become <br>, like the editor canvas (textToInlineHtml)', () => {
|
||||
const { html } = toHtml({ text: 'a\n\nb <i>' }, '');
|
||||
expect(html).toBe('<p>a<br><br>b <i></p>');
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,14 @@
|
||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
import { resolveInlineHtml, textToInlineHtml } from '../../utils/inline-html';
|
||||
import { useInlineEditable } from './useInlineEditable';
|
||||
|
||||
interface TextBlockProps {
|
||||
text?: string;
|
||||
/** Sanitised inline rich text (#46); '' = plain `text` only. */
|
||||
html?: string;
|
||||
style?: CSSProperties;
|
||||
cssId?: string;
|
||||
cssClass?: string;
|
||||
@@ -17,6 +21,7 @@ interface TextBlockProps {
|
||||
|
||||
export const TextBlock: UserComponent<TextBlockProps> = ({
|
||||
text = 'Start typing here...',
|
||||
html = '',
|
||||
style = {},
|
||||
}) => {
|
||||
const {
|
||||
@@ -27,31 +32,7 @@ export const TextBlock: UserComponent<TextBlockProps> = ({
|
||||
selected: node.events.selected,
|
||||
}));
|
||||
|
||||
const elRef = useRef<HTMLParagraphElement | null>(null);
|
||||
const editedTextRef = useRef<string | null>(null);
|
||||
|
||||
const commitText = useCallback(() => {
|
||||
if (elRef.current) {
|
||||
const newText = elRef.current.innerText;
|
||||
editedTextRef.current = newText;
|
||||
setProp((p: TextBlockProps) => { p.text = newText; });
|
||||
}
|
||||
}, [setProp]);
|
||||
|
||||
const handleBlur = useCallback(() => { commitText(); }, [commitText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected && editedTextRef.current !== null) {
|
||||
setProp((p: TextBlockProps) => { p.text = editedTextRef.current!; });
|
||||
editedTextRef.current = null;
|
||||
}
|
||||
}, [selected, setProp]);
|
||||
|
||||
useEffect(() => {
|
||||
if (elRef.current && !selected && editedTextRef.current === null) {
|
||||
elRef.current.innerText = text || '';
|
||||
}
|
||||
}, [text, selected]);
|
||||
const { elRef, onBlur, onInput, onKeyDown } = useInlineEditable(text, html, selected, setProp);
|
||||
|
||||
return (
|
||||
<p
|
||||
@@ -61,8 +42,9 @@ export const TextBlock: UserComponent<TextBlockProps> = ({
|
||||
}}
|
||||
contentEditable={selected}
|
||||
suppressContentEditableWarning
|
||||
onBlur={handleBlur}
|
||||
onInput={() => { if (elRef.current) editedTextRef.current = elRef.current.innerText; }}
|
||||
onBlur={onBlur}
|
||||
onInput={onInput}
|
||||
onKeyDown={onKeyDown}
|
||||
style={{
|
||||
outline: 'none',
|
||||
cursor: selected ? 'text' : 'pointer',
|
||||
@@ -79,10 +61,11 @@ TextBlock.craft = {
|
||||
displayName: 'Text',
|
||||
props: {
|
||||
text: 'Start typing here...',
|
||||
html: '',
|
||||
style: {
|
||||
fontSize: '16px',
|
||||
lineHeight: '1.6',
|
||||
color: '#3f3f46',
|
||||
color: tokenRef('text'),
|
||||
letterSpacing: '',
|
||||
textTransform: '' as CSSProperties['textTransform'],
|
||||
fontStyle: '' as CSSProperties['fontStyle'],
|
||||
@@ -110,6 +93,6 @@ TextBlock.craft = {
|
||||
|
||||
(TextBlock as any).toHtml = (props: TextBlockProps, _childrenHtml: string) => {
|
||||
const styleStr = cssPropsToString(props.style);
|
||||
const escapedText = escapeHtml(props.text || '');
|
||||
const escapedText = resolveInlineHtml(props.text, props.html) ?? textToInlineHtml(props.text || '');
|
||||
return { html: `<p${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</p>` };
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, test, expect, afterEach, vi } from 'vitest';
|
||||
import { renderEditorHarness, EditorHarness } from '../../test-utils/editorHarness';
|
||||
|
||||
/**
|
||||
* #46 inline rich text against a REAL Craft.js editor: contentEditable
|
||||
* commits store sanitised `html` + plain `text` as ONE undo step, a deselect
|
||||
* after blur adds no second step, and load (deserialize + history.clear)
|
||||
* leaves nothing to undo.
|
||||
*/
|
||||
function stateWith(nodeType: 'Heading' | 'TextBlock', props: Record<string, unknown>) {
|
||||
return JSON.stringify({
|
||||
ROOT: {
|
||||
type: { resolvedName: 'Container' }, isCanvas: true, props: { style: {}, tag: 'div' },
|
||||
displayName: 'Container', custom: {}, hidden: false, nodes: ['n-1'], linkedNodes: {},
|
||||
},
|
||||
'n-1': {
|
||||
type: { resolvedName: nodeType }, isCanvas: false,
|
||||
props: nodeType === 'Heading' ? { level: 'h2', style: {}, ...props } : { style: {}, ...props },
|
||||
displayName: nodeType === 'Heading' ? 'Heading' : 'Text', custom: {}, hidden: false,
|
||||
parent: 'ROOT', nodes: [], linkedNodes: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let harness: EditorHarness | null = null;
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
delete (document as any).execCommand;
|
||||
harness?.unmount();
|
||||
harness = null;
|
||||
});
|
||||
|
||||
function mount(nodeType: 'Heading' | 'TextBlock', props: Record<string, unknown>) {
|
||||
harness = renderEditorHarness({ initialState: stateWith(nodeType, props) });
|
||||
harness.act(() => { harness!.actions.history.clear(); });
|
||||
return harness;
|
||||
}
|
||||
|
||||
const el = () => harness!.query.node('n-1').get().dom as HTMLElement;
|
||||
const nodeProps = () => JSON.parse(harness!.getSerialized())['n-1'].props;
|
||||
const select = () => harness!.act(() => { harness!.actions.selectNode('n-1'); });
|
||||
const deselect = () => harness!.act(() => { harness!.actions.selectNode(); });
|
||||
const typeHtml = (html: string) => harness!.act(() => {
|
||||
el().innerHTML = html;
|
||||
el().dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
const blur = () => harness!.act(() => { el().dispatchEvent(new FocusEvent('focusout', { bubbles: true })); });
|
||||
|
||||
function undoDepth(): number {
|
||||
let n = 0;
|
||||
while (harness!.query.history.canUndo() && n < 50) {
|
||||
harness!.act(() => { harness!.actions.history.undo(); });
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
describe.each(['Heading', 'TextBlock'] as const)('%s inline editing (#46)', (type) => {
|
||||
test('a marked edit stores sanitised html + plain text mirror', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
expect(el().getAttribute('contenteditable')).toBe('true');
|
||||
typeHtml('Hello <b>World</b>');
|
||||
blur();
|
||||
expect(nodeProps().html).toBe('Hello <b>World</b>');
|
||||
expect(nodeProps().text).toBe('Hello World');
|
||||
});
|
||||
|
||||
test('blur then deselect is ONE undo step (no double commit)', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
typeHtml('Hello <b>World</b>');
|
||||
blur();
|
||||
deselect();
|
||||
expect(undoDepth()).toBe(1);
|
||||
expect(nodeProps().text).toBe('Hello');
|
||||
expect(nodeProps().html).toBe('');
|
||||
// Undo of a deselected node re-renders the DOM from props.
|
||||
expect(el().innerHTML).toBe('Hello');
|
||||
});
|
||||
|
||||
test('deselect without blur commits exactly once', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
typeHtml('Hi <i>there</i>');
|
||||
deselect();
|
||||
expect(nodeProps().html).toBe('Hi <i>there</i>');
|
||||
expect(undoDepth()).toBe(1);
|
||||
});
|
||||
|
||||
test('a plain edit leaves html empty (legacy shape)', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
typeHtml('Fish & chips');
|
||||
blur();
|
||||
expect(nodeProps().html).toBe('');
|
||||
expect(nodeProps().text).toBe('Fish & chips');
|
||||
});
|
||||
|
||||
test('Enter-created block lines survive as newlines in text', () => {
|
||||
mount(type, { text: 'a', html: '' });
|
||||
select();
|
||||
typeHtml('a<div>b</div>');
|
||||
blur();
|
||||
expect(nodeProps().text).toBe('a\nb');
|
||||
expect(nodeProps().html).toBe('');
|
||||
});
|
||||
|
||||
test('hostile markup typed/pasted into the editable is sanitised on commit', () => {
|
||||
mount(type, { text: 'x', html: '' });
|
||||
select();
|
||||
typeHtml('<img src=x onerror="alert(1)"><a href="javascript:alert(1)" onclick="x()">click</a> <b style="position:fixed">ok</b>');
|
||||
blur();
|
||||
expect(nodeProps().html).toBe('click <b>ok</b>');
|
||||
expect(nodeProps().text).toBe('click ok');
|
||||
});
|
||||
|
||||
test('external links created by createLink get target=_blank + rel=noopener on commit', () => {
|
||||
mount(type, { text: 'x', html: '' });
|
||||
select();
|
||||
typeHtml('<a href="https://example.org/">x</a>');
|
||||
blur();
|
||||
expect(nodeProps().html).toBe('<a href="https://example.org/" target="_blank" rel="noopener">x</a>');
|
||||
});
|
||||
|
||||
test('blur with no edit commits nothing', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
blur();
|
||||
deselect();
|
||||
expect(harness!.query.history.canUndo()).toBe(false);
|
||||
});
|
||||
|
||||
test('load (deserialize + history.clear) renders stored html and leaves nothing to undo', () => {
|
||||
mount(type, { text: 'Hi there', html: '<b>Hi</b> there' });
|
||||
expect(el().innerHTML).toBe('<b>Hi</b> there');
|
||||
harness!.act(() => {
|
||||
harness!.actions.deserialize(stateWith(type, { text: 'Page two', html: '<i>Page</i> two' }));
|
||||
});
|
||||
harness!.act(() => { harness!.actions.history.clear(); });
|
||||
expect(el().innerHTML).toBe('<i>Page</i> two');
|
||||
expect(harness!.query.history.canUndo()).toBe(false);
|
||||
});
|
||||
|
||||
test('hostile stored html never reaches the canvas DOM', () => {
|
||||
mount(type, { text: '', html: '<img src=x onerror="alert(1)">safe<script>alert(1)</script>' });
|
||||
expect(el().innerHTML).toBe('safe');
|
||||
});
|
||||
|
||||
test('stale html is ignored when text was changed without it (AI update_props)', () => {
|
||||
mount(type, { text: 'Hi there', html: '<b>Hi</b> there' });
|
||||
harness!.act(() => { harness!.actions.setProp('n-1', (p: any) => { p.text = 'Brand <new>'; }); });
|
||||
expect(el().innerHTML).toBe('Brand <new>');
|
||||
});
|
||||
|
||||
test('mod+b while typing runs execCommand(bold) and marks the edit pending', () => {
|
||||
mount(type, { text: 'Hello', html: '' });
|
||||
select();
|
||||
// jsdom has no execCommand at all -- install a stub for this test.
|
||||
const exec = vi.fn(() => { el().innerHTML = '<b>Hello</b>'; return true; });
|
||||
(document as any).execCommand = exec;
|
||||
harness!.act(() => {
|
||||
el().dispatchEvent(new KeyboardEvent('keydown', { key: 'b', ctrlKey: true, bubbles: true }));
|
||||
});
|
||||
expect(exec).toHaveBeenCalledWith('bold');
|
||||
blur();
|
||||
expect(nodeProps().html).toBe('<b>Hello</b>');
|
||||
expect(undoDepth()).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import React, { useCallback, useEffect, useRef } from 'react';
|
||||
import {
|
||||
sanitizeInlineHtml,
|
||||
inlineHtmlToText,
|
||||
isPlainInlineHtml,
|
||||
textToInlineHtml,
|
||||
resolveInlineHtml,
|
||||
markExternalLinks,
|
||||
} from '../../utils/inline-html';
|
||||
import { useGlobalOverrideCommit } from '../../state/GlobalInstanceContext';
|
||||
|
||||
interface InlineTextProps {
|
||||
text?: string;
|
||||
html?: string;
|
||||
}
|
||||
|
||||
const SHORTCUTS: Record<string, string> = { b: 'bold', i: 'italic', u: 'underline' };
|
||||
|
||||
/**
|
||||
* contentEditable wiring shared by Heading and TextBlock (#46).
|
||||
*
|
||||
* - The DOM is written imperatively (innerHTML) only while the node is NOT
|
||||
* selected and has no pending edit, so the caret is never reset mid-typing.
|
||||
* - An edit is committed ONCE -- on blur, or on deselect if no blur came
|
||||
* first -- as a single `setProp` (= one undo step) that stores BOTH the
|
||||
* sanitised `html` and its plain `text` mirror. Unmarked content stores
|
||||
* `html: ''` so legacy nodes keep their legacy shape.
|
||||
* - mod+b/i/u is handled locally: the global shortcut dispatcher skips
|
||||
* contentEditable targets.
|
||||
*/
|
||||
export function useInlineEditable(
|
||||
text: string,
|
||||
html: string,
|
||||
selected: boolean,
|
||||
setProp: (cb: (p: InlineTextProps) => void) => void,
|
||||
) {
|
||||
const elRef = useRef<HTMLElement | null>(null);
|
||||
const pendingRef = useRef(false);
|
||||
const commitProps = useGlobalOverrideCommit(setProp); // #57: inside a global instance -> override
|
||||
|
||||
const commit = useCallback(() => {
|
||||
if (!pendingRef.current) return;
|
||||
pendingRef.current = false;
|
||||
const el = elRef.current;
|
||||
if (!el) return;
|
||||
markExternalLinks(el);
|
||||
const clean = sanitizeInlineHtml(el.innerHTML);
|
||||
const nextText = inlineHtmlToText(clean);
|
||||
const nextHtml = isPlainInlineHtml(clean) ? '' : clean;
|
||||
commitProps((p) => { p.html = nextHtml; p.text = nextText; });
|
||||
}, [commitProps]);
|
||||
|
||||
// Deselect without a blur (e.g. Escape, programmatic selection change).
|
||||
useEffect(() => {
|
||||
if (!selected) commit();
|
||||
}, [selected, commit]);
|
||||
|
||||
useEffect(() => {
|
||||
if (elRef.current && !selected && !pendingRef.current) {
|
||||
elRef.current.innerHTML = resolveInlineHtml(text, html) ?? textToInlineHtml(text || '');
|
||||
}
|
||||
}, [text, html, selected]);
|
||||
|
||||
const onInput = useCallback(() => { pendingRef.current = true; }, []);
|
||||
|
||||
const onKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return;
|
||||
const cmd = SHORTCUTS[e.key.toLowerCase()];
|
||||
if (!cmd) return;
|
||||
if (typeof document.execCommand !== 'function') return;
|
||||
e.preventDefault();
|
||||
document.execCommand(cmd);
|
||||
pendingRef.current = true;
|
||||
}, []);
|
||||
|
||||
return { elRef, onBlur: commit, onInput, onKeyDown };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { BookingEmbed, bookingEmbedUrl } from './BookingEmbed';
|
||||
|
||||
const toHtml = (BookingEmbed as any).toHtml;
|
||||
const defaults = () => ({ ...(BookingEmbed as any).craft.props });
|
||||
const run = (url: string, extra: any = {}) => toHtml({ ...defaults(), url, ...extra }, '').html as string;
|
||||
|
||||
describe('BookingEmbed.toHtml host allowlist', () => {
|
||||
test.each([
|
||||
'https://calendly.com/acme/30min',
|
||||
'https://app.calendly.com/x',
|
||||
'https://squareup.com/appointments/book/abc',
|
||||
'https://app.squareup.com/appointments/book/abc/L1/start',
|
||||
'https://acme.square.site/appointments',
|
||||
])('allows %s', (u) => {
|
||||
const html = run(u);
|
||||
expect(html).toContain('<iframe src="');
|
||||
expect(html).toContain('sandbox="allow-scripts allow-forms allow-same-origin allow-popups"');
|
||||
expect(html).toContain('referrerpolicy="strict-origin-when-cross-origin"');
|
||||
expect(html).toContain('loading="lazy"');
|
||||
expect(html).toContain('height:700px');
|
||||
});
|
||||
|
||||
test.each([
|
||||
'https://evil.com',
|
||||
'javascript:alert(1)',
|
||||
' JaVaScRiPt:alert(1)',
|
||||
'data:text/html,<script>alert(1)</script>',
|
||||
'http://calendly.com/acme',
|
||||
'https://calendly.com.evil.com/x',
|
||||
'https://evilcalendly.com/x',
|
||||
'https://evil.com/calendly.com',
|
||||
'https://evil.com?u=https://calendly.com',
|
||||
'https://calendly.com@evil.com/x',
|
||||
'https://user:pw@calendly.com/x',
|
||||
'https://square.site/x',
|
||||
'//evil.com',
|
||||
'',
|
||||
])('never iframes %s', (u) => {
|
||||
expect(bookingEmbedUrl(u)).toBe('');
|
||||
const html = run(u);
|
||||
expect(html).not.toContain('<iframe');
|
||||
expect(html).not.toMatch(/javascript:/i);
|
||||
expect(html).not.toContain('<script');
|
||||
});
|
||||
|
||||
test("provider 'custom' is not an escape hatch", () => {
|
||||
expect(run('https://evil.com', { provider: 'custom' })).not.toContain('<iframe');
|
||||
});
|
||||
|
||||
test('refused https URL degrades to an escaped link, never an iframe', () => {
|
||||
const html = run('https://evil.com/a?x=1&y="><script>', { title: '<b>Book</b>' });
|
||||
expect(html).toContain('<a href="https://evil.com/a?x=1&y="><script>"');
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).toContain('<b>Book</b>');
|
||||
expect(html).not.toContain('<iframe');
|
||||
});
|
||||
|
||||
test('title and height are escaped / sanitised', () => {
|
||||
const html = run('https://calendly.com/a', { title: '"><script>x</script>', height: '700px;position:fixed" onload="x' });
|
||||
expect(html).not.toContain('<script>');
|
||||
// quotes/semicolons are stripped from height: the payload stays inside style="".
|
||||
expect(html).toMatch(/style="width:100%;height:[^";]*;border:none;display:block"><\/iframe>/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, cssValue, safeUrl } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
interface BookingEmbedProps {
|
||||
provider?: 'calendly' | 'square' | 'custom';
|
||||
url?: string;
|
||||
height?: string;
|
||||
title?: string;
|
||||
style?: CSSProperties;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
// Exact hosts, plus subdomains of the *.suffix entries. Everything else is
|
||||
// refused, whatever the `provider` says ('custom' is NOT an escape hatch).
|
||||
const EXACT_HOSTS = ['calendly.com', 'squareup.com', 'app.squareup.com'];
|
||||
const SUFFIX_HOSTS = ['.calendly.com', '.square.site'];
|
||||
|
||||
/** Returns the normalised https URL when its host is allow-listed, else ''. */
|
||||
export function bookingEmbedUrl(raw: unknown): string {
|
||||
const s = safeUrl(typeof raw === 'string' ? raw : '');
|
||||
if (!s) return '';
|
||||
let u: URL;
|
||||
try { u = new URL(s); } catch { return ''; }
|
||||
if (u.protocol !== 'https:') return '';
|
||||
if (u.username || u.password) return '';
|
||||
const host = u.hostname.toLowerCase();
|
||||
const ok = EXACT_HOSTS.includes(host) || SUFFIX_HOSTS.some((suf) => host.endsWith(suf) && host.length > suf.length);
|
||||
return ok ? u.toString() : '';
|
||||
}
|
||||
|
||||
const PROVIDER_LABEL: Record<string, string> = { calendly: 'Calendly', square: 'Square Appointments', custom: 'Booking' };
|
||||
|
||||
export const BookingEmbed: UserComponent<BookingEmbedProps> = ({
|
||||
provider = 'calendly',
|
||||
url = '',
|
||||
height = '700px',
|
||||
title = 'Book an appointment',
|
||||
style = {},
|
||||
}) => {
|
||||
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
|
||||
const ok = !!bookingEmbedUrl(url);
|
||||
// No live iframe in the canvas: a placeholder card keeps the editor offline-safe.
|
||||
return (
|
||||
<div
|
||||
ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
style={{ padding: 24, outline: selected ? '2px solid #3b82f6' : 'none', ...style }}
|
||||
>
|
||||
<div style={{ border: `2px dashed ${tokenRef('border')}`, borderRadius: 12, padding: 32, textAlign: 'center', color: tokenRef('muted'), minHeight: 160 }}>
|
||||
<div style={{ fontWeight: 600, color: tokenRef('text') }}>{title}</div>
|
||||
<div style={{ marginTop: 8, fontSize: 14 }}>
|
||||
{PROVIDER_LABEL[provider] || 'Booking'} embed{ok ? `: ${url}` : url ? ': this address is not an allowed booking host' : ': paste your booking URL in the panel'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
BookingEmbed.craft = {
|
||||
displayName: 'Booking',
|
||||
props: {
|
||||
provider: 'calendly',
|
||||
url: '',
|
||||
height: '700px',
|
||||
title: 'Book an appointment',
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||
};
|
||||
|
||||
(BookingEmbed as any).toHtml = (props: BookingEmbedProps, _childrenHtml: string) => {
|
||||
const title = typeof props.title === 'string' && props.title ? props.title : 'Book an appointment';
|
||||
const wrapStyle = cssPropsToString({ width: '100%', ...(props.style || {}) });
|
||||
const wrap = (inner: string) => `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>${inner}</div>`;
|
||||
|
||||
const src = bookingEmbedUrl(props.url);
|
||||
if (src) {
|
||||
const height = cssValue(props.height) || '700px';
|
||||
return {
|
||||
html: wrap(`<iframe src="${escapeAttr(src)}" title="${escapeAttr(title)}" loading="lazy" sandbox="allow-scripts allow-forms allow-same-origin allow-popups" referrerpolicy="strict-origin-when-cross-origin" style="width:100%;height:${height};border:none;display:block"></iframe>`),
|
||||
};
|
||||
}
|
||||
|
||||
// Not allow-listed: never an iframe. A plain http(s) link at most.
|
||||
const raw = safeUrl(typeof props.url === 'string' ? props.url : '');
|
||||
const link = /^https?:\/\//i.test(raw) ? raw : '';
|
||||
return {
|
||||
html: wrap(link
|
||||
? `<p><a href="${escapeAttr(link)}" target="_blank" rel="noopener noreferrer nofollow">${escapeHtml(title)}</a></p>`
|
||||
: ''),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { OpeningHours } from './OpeningHours';
|
||||
|
||||
const toHtml = (OpeningHours as any).toHtml;
|
||||
|
||||
describe('OpeningHours.toHtml', () => {
|
||||
test('default: 7 rows, th scope=row, hidden caption, token colours', () => {
|
||||
const { html } = toHtml({ ...(OpeningHours as any).craft.props }, '', 'n1');
|
||||
expect(html.match(/<th scope="row"/g)).toHaveLength(7);
|
||||
expect(html).toContain('<caption');
|
||||
expect(html).toContain('clip:rect(0,0,0,0)');
|
||||
expect(html).toContain('var(--wsb-text)');
|
||||
expect(html).toContain('Sunday');
|
||||
expect(html).toMatch(/Sunday<\/th><td[^>]*>Closed</);
|
||||
});
|
||||
|
||||
test('closed overrides stale hours text', () => {
|
||||
const { html } = toHtml({ rows: [{ day: 'Mon', hours: '9-5', closed: true }] }, '', 'n1');
|
||||
expect(html).toContain('>Closed<');
|
||||
expect(html).not.toContain('9-5');
|
||||
});
|
||||
|
||||
test('escapes day, hours, note and title; sanitises colours', () => {
|
||||
const { html } = toHtml({
|
||||
title: '<img src=x onerror=1>',
|
||||
note: '"><script>alert(1)</script>',
|
||||
rows: [{ day: '<b>Mon</b>', hours: '<script>x</script>', closed: false }],
|
||||
labelColor: 'red;background:url(javascript:alert(1))"',
|
||||
}, '', 'n1');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(html).not.toContain('<img');
|
||||
expect(html).not.toContain('<b>');
|
||||
expect(html).toContain('<b>Mon</b>');
|
||||
// cssValue strips ( ) ; " so no url()/extra declaration can form.
|
||||
expect(html).not.toContain('url(');
|
||||
expect(html).not.toMatch(/color:red[^"]*;background/);
|
||||
});
|
||||
|
||||
test('tolerates non-array rows', () => {
|
||||
expect(() => toHtml({ rows: 'nope' }, '', 'n1')).not.toThrow();
|
||||
});
|
||||
|
||||
test('two instances get distinct heading ids', () => {
|
||||
const a = toHtml({ title: 'T' }, '', 'a').html.match(/id="(hours_[a-z0-9]+)"/)[1];
|
||||
const b = toHtml({ title: 'T' }, '', 'b').html.match(/id="(hours_[a-z0-9]+)"/)[1];
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, cssValue, scopeId } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
export interface HoursRow {
|
||||
day: string;
|
||||
hours: string;
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
interface OpeningHoursProps {
|
||||
title?: string;
|
||||
rows?: HoursRow[];
|
||||
note?: string;
|
||||
style?: CSSProperties;
|
||||
labelColor?: string;
|
||||
valueColor?: string;
|
||||
anchorId?: string;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
// Every key is present on every default row: the generic array editor derives
|
||||
// its per-item fields from Object.keys(items[0]).
|
||||
export const defaultHoursRows = (): HoursRow[] => [
|
||||
{ day: 'Monday', hours: '9:00 AM - 5:00 PM', closed: false },
|
||||
{ day: 'Tuesday', hours: '9:00 AM - 5:00 PM', closed: false },
|
||||
{ day: 'Wednesday', hours: '9:00 AM - 5:00 PM', closed: false },
|
||||
{ day: 'Thursday', hours: '9:00 AM - 5:00 PM', closed: false },
|
||||
{ day: 'Friday', hours: '9:00 AM - 5:00 PM', closed: false },
|
||||
{ day: 'Saturday', hours: '10:00 AM - 2:00 PM', closed: false },
|
||||
{ day: 'Sunday', hours: '', closed: true },
|
||||
];
|
||||
|
||||
// "Open now" is deliberately NOT computed: the published page is a static
|
||||
// snapshot, so this is a plain table.
|
||||
function cellText(r: HoursRow): string {
|
||||
return r.closed ? 'Closed' : (r.hours || '');
|
||||
}
|
||||
|
||||
const VISUALLY_HIDDEN = 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0';
|
||||
|
||||
export const OpeningHours: UserComponent<OpeningHoursProps> = ({
|
||||
title = 'Opening Hours',
|
||||
rows = defaultHoursRows(),
|
||||
note = '',
|
||||
style = {},
|
||||
labelColor = tokenRef('text'),
|
||||
valueColor = tokenRef('muted'),
|
||||
anchorId,
|
||||
}) => {
|
||||
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
|
||||
const items = Array.isArray(rows) ? rows : [];
|
||||
|
||||
return (
|
||||
<section
|
||||
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
id={anchorId || undefined}
|
||||
style={{ padding: '48px 20px', outline: selected ? '2px solid #3b82f6' : 'none', ...style }}
|
||||
>
|
||||
<div style={{ maxWidth: '480px', margin: '0 auto' }}>
|
||||
{title && <h2 style={{ margin: '0 0 16px', fontSize: '28px', color: labelColor }}>{title}</h2>}
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<caption style={{ position: 'absolute', width: 1, height: 1, overflow: 'hidden', clip: 'rect(0,0,0,0)' }}>{title || 'Opening hours'}</caption>
|
||||
<tbody>
|
||||
{items.map((r, i) => (
|
||||
<tr key={i} style={{ borderBottom: `1px solid ${tokenRef('border')}` }}>
|
||||
<th scope="row" style={{ textAlign: 'left', padding: '10px 0', fontWeight: 600, color: labelColor }}>{r.day}</th>
|
||||
<td style={{ textAlign: 'right', padding: '10px 0', color: valueColor }}>{cellText(r)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{note && <p style={{ margin: '12px 0 0', fontSize: '14px', color: valueColor }}>{note}</p>}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
OpeningHours.craft = {
|
||||
displayName: 'Opening Hours',
|
||||
props: {
|
||||
title: 'Opening Hours',
|
||||
rows: defaultHoursRows(),
|
||||
note: '',
|
||||
style: { backgroundColor: 'transparent' },
|
||||
labelColor: tokenRef('text'),
|
||||
valueColor: tokenRef('muted'),
|
||||
anchorId: '',
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||
};
|
||||
|
||||
(OpeningHours as any).toHtml = (props: OpeningHoursProps, _childrenHtml: string, nodeId?: string) => {
|
||||
const rows = Array.isArray(props.rows) ? props.rows : [];
|
||||
const title = typeof props.title === 'string' ? props.title : 'Opening Hours';
|
||||
const note = typeof props.note === 'string' ? props.note : '';
|
||||
const labelColor = cssValue(props.labelColor) || tokenRef('text');
|
||||
const valueColor = cssValue(props.valueColor) || tokenRef('muted');
|
||||
const sectionStyle = cssPropsToString({ padding: '48px 20px', ...(props.style || {}) });
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const hid = scopeId(nodeId, title, 'hours');
|
||||
|
||||
const body = rows.map((r) =>
|
||||
`<tr style="border-bottom:1px solid ${tokenRef('border')}"><th scope="row" style="text-align:left;padding:10px 0;font-weight:600;color:${labelColor}">${escapeHtml(r.day)}</th><td style="text-align:right;padding:10px 0;color:${valueColor}">${escapeHtml(cellText(r))}</td></tr>`
|
||||
).join('');
|
||||
|
||||
return {
|
||||
html: `<section${idAttr}${title ? ` aria-labelledby="${hid}"` : ''}${sectionStyle ? ` style="${sectionStyle}"` : ''}><div style="max-width:480px;margin:0 auto">${title ? `<h2 id="${hid}" style="margin:0 0 16px;font-size:28px;color:${labelColor}">${escapeHtml(title)}</h2>` : ''}<table style="width:100%;border-collapse:collapse"><caption style="${VISUALLY_HIDDEN}">${escapeHtml(title || 'Opening hours')}</caption><tbody>${body}</tbody></table>${note ? `<p style="margin:12px 0 0;font-size:14px;color:${valueColor}">${escapeHtml(note)}</p>` : ''}</div></section>`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { ReviewsStrip, clampRating } from './ReviewsStrip';
|
||||
|
||||
const toHtml = (ReviewsStrip as any).toHtml;
|
||||
const defaults = () => ({ ...(ReviewsStrip as any).craft.props });
|
||||
|
||||
describe('ReviewsStrip.toHtml', () => {
|
||||
test('default: 3 cards, token colours, aria-label stars, no aggregate markup', () => {
|
||||
const { html } = toHtml(defaults(), '', 'n1');
|
||||
expect(html.match(/<figure/g)).toHaveLength(3);
|
||||
expect(html).toContain('var(--wsb-bg)');
|
||||
expect(html).toContain('aria-label="5 out of 5 stars"');
|
||||
expect(html).toContain('aria-label="4 out of 5 stars"');
|
||||
expect(html).not.toContain('itemtype');
|
||||
expect(html).not.toContain('application/ld+json');
|
||||
});
|
||||
|
||||
test('escapes names, text and source label', () => {
|
||||
const { html } = toHtml({ ...defaults(), reviews: [{ name: '<i>Eve</i>', rating: 5, text: '"><script>alert(1)</script>', source: '<b>G</b>', url: '' }] }, '', 'n1');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(html).not.toContain('<i>');
|
||||
expect(html).not.toContain('<b>');
|
||||
expect(html).toContain('<i>Eve</i>');
|
||||
});
|
||||
|
||||
test('hostile review and all-reviews URLs are dropped; https kept', () => {
|
||||
const hostile = toHtml({ ...defaults(), allReviewsUrl: 'javascript:alert(1)', reviews: [{ name: 'A', rating: 5, text: 't', source: 'G', url: ' JaVa\tScript:alert(1)' }] }, '', 'n1').html;
|
||||
expect(hostile).not.toMatch(/javascript/i);
|
||||
expect(hostile).not.toContain('<a ');
|
||||
const ok = toHtml({ ...defaults(), allReviewsUrl: 'https://g.page/r/abc?x=1&y=2', reviews: [{ name: 'A', rating: 5, text: 't', source: 'G', url: 'https://yelp.com/biz/x' }] }, '', 'n1').html;
|
||||
expect(ok).toContain('href="https://g.page/r/abc?x=1&y=2"');
|
||||
expect(ok).toContain('href="https://yelp.com/biz/x"');
|
||||
expect(ok).toContain('rel="noopener noreferrer nofollow"');
|
||||
});
|
||||
|
||||
test('rating is clamped to 1-5 and garbage is safe; max 6 cards', () => {
|
||||
expect(clampRating(99)).toBe(5);
|
||||
expect(clampRating(0)).toBe(1);
|
||||
expect(clampRating('"><x')).toBe(5);
|
||||
const many = Array.from({ length: 9 }, (_, i) => ({ name: `n${i}`, rating: 'x"', text: 't', source: '', url: '' }));
|
||||
const { html } = toHtml({ ...defaults(), reviews: many }, '', 'n1');
|
||||
expect(html.match(/<figure/g)).toHaveLength(6);
|
||||
expect(html.match(/aria-label="5 out of 5 stars"/g)).toHaveLength(6);
|
||||
});
|
||||
|
||||
test('cardBg is sanitised', () => {
|
||||
const { html } = toHtml({ ...defaults(), cardBg: 'red"onmouseover="x' }, '', 'n1');
|
||||
// cssValue strips the quotes, so the payload stays inert text inside style="".
|
||||
expect(html).not.toMatch(/onmouseover\s*=\s*"/);
|
||||
expect((html.match(/<figure style="[^"]*"/g) || [])).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, cssValue, scopeId } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { httpUrl } from './StickyCallBar';
|
||||
|
||||
export interface ReviewItem {
|
||||
name: string;
|
||||
rating: number;
|
||||
text: string;
|
||||
source: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface ReviewsStripProps {
|
||||
title?: string;
|
||||
reviews?: ReviewItem[];
|
||||
allReviewsUrl?: string;
|
||||
allReviewsLabel?: string;
|
||||
cardBg?: string;
|
||||
style?: CSSProperties;
|
||||
anchorId?: string;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
// v1: reviews are entered by hand. The `source` is a plain-text label
|
||||
// (e.g. "Google"), never an official integration.
|
||||
export const defaultReviews = (): ReviewItem[] => [
|
||||
{ name: 'Alex P.', rating: 5, text: 'Friendly, fast and great value. Highly recommend.', source: 'Google', url: '' },
|
||||
{ name: 'Jordan M.', rating: 5, text: 'Exactly what we needed, and the team was a pleasure to deal with.', source: 'Google', url: '' },
|
||||
{ name: 'Sam R.', rating: 4, text: 'Professional service from start to finish.', source: 'Yelp', url: '' },
|
||||
];
|
||||
|
||||
export function clampRating(r: unknown): number {
|
||||
const n = Math.round(Number(r));
|
||||
if (!Number.isFinite(n)) return 5;
|
||||
return Math.min(5, Math.max(1, n));
|
||||
}
|
||||
|
||||
const stars = (n: number) => '★'.repeat(n) + '☆'.repeat(5 - n);
|
||||
|
||||
const CARD_CSS = (bg: string) =>
|
||||
`background-color:${bg};border:1px solid ${tokenRef('border')};border-radius:12px;padding:24px;display:flex;flex-direction:column;gap:8px`;
|
||||
|
||||
export const ReviewsStrip: UserComponent<ReviewsStripProps> = ({
|
||||
title = 'What our customers say',
|
||||
reviews = defaultReviews(),
|
||||
allReviewsUrl = '',
|
||||
allReviewsLabel = 'Read all reviews',
|
||||
cardBg = tokenRef('bg'),
|
||||
style = {},
|
||||
anchorId,
|
||||
}) => {
|
||||
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
|
||||
const items = (Array.isArray(reviews) ? reviews : []).slice(0, 6);
|
||||
return (
|
||||
<section
|
||||
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
id={anchorId || undefined}
|
||||
style={{ padding: '56px 20px', outline: selected ? '2px solid #3b82f6' : 'none', ...style }}
|
||||
>
|
||||
<div style={{ maxWidth: '1100px', margin: '0 auto' }}>
|
||||
{title && <h2 style={{ margin: '0 0 24px', textAlign: 'center', color: tokenRef('text') }}>{title}</h2>}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(260px,1fr))', gap: '20px' }}>
|
||||
{items.map((r, i) => (
|
||||
<figure key={i} style={{ margin: 0, backgroundColor: cardBg, border: `1px solid ${tokenRef('border')}`, borderRadius: 12, padding: 24, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<div role="img" aria-label={`${clampRating(r.rating)} out of 5 stars`} style={{ color: tokenRef('warning'), letterSpacing: 2 }}>{stars(clampRating(r.rating))}</div>
|
||||
<blockquote style={{ margin: 0, color: tokenRef('text') }}>{r.text}</blockquote>
|
||||
<figcaption style={{ fontSize: 14, color: tokenRef('muted') }}>{r.name}{r.source ? ` · ${r.source}` : ''}</figcaption>
|
||||
</figure>
|
||||
))}
|
||||
</div>
|
||||
{allReviewsUrl && <p style={{ textAlign: 'center', marginTop: 24 }}><span style={{ color: tokenRef('link'), fontWeight: 600 }}>{allReviewsLabel}</span></p>}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
ReviewsStrip.craft = {
|
||||
displayName: 'Reviews',
|
||||
props: {
|
||||
title: 'What our customers say',
|
||||
reviews: defaultReviews(),
|
||||
allReviewsUrl: '',
|
||||
allReviewsLabel: 'Read all reviews',
|
||||
cardBg: tokenRef('bg'),
|
||||
style: { backgroundColor: 'transparent' },
|
||||
anchorId: '',
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
hideOnDesktop: false,
|
||||
hideOnTablet: false,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||
};
|
||||
|
||||
(ReviewsStrip as any).toHtml = (props: ReviewsStripProps, _childrenHtml: string, nodeId?: string) => {
|
||||
const title = typeof props.title === 'string' ? props.title : '';
|
||||
const items = (Array.isArray(props.reviews) ? props.reviews : []).slice(0, 6);
|
||||
const cardBg = cssValue(props.cardBg) || tokenRef('bg');
|
||||
const sectionStyle = cssPropsToString({ padding: '56px 20px', ...(props.style || {}) });
|
||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||
const hid = scopeId(nodeId, title, 'reviews');
|
||||
|
||||
const cards = items.map((r) => {
|
||||
const n = clampRating(r.rating);
|
||||
const link = httpUrl(r.url);
|
||||
const who = `${escapeHtml(r.name)}${r.source ? ` · ${escapeHtml(r.source)}` : ''}`;
|
||||
const cap = link ? `<a href="${escapeAttr(link)}" target="_blank" rel="noopener noreferrer nofollow" style="color:inherit">${who}</a>` : who;
|
||||
return `<figure style="margin:0;${CARD_CSS(cardBg)}"><div role="img" aria-label="${n} out of 5 stars" style="color:${tokenRef('warning')};letter-spacing:2px">${stars(n)}</div><blockquote style="margin:0;color:${tokenRef('text')}">${escapeHtml(r.text)}</blockquote><figcaption style="font-size:14px;color:${tokenRef('muted')}">${cap}</figcaption></figure>`;
|
||||
}).join('');
|
||||
|
||||
const all = httpUrl(props.allReviewsUrl);
|
||||
const allHtml = all
|
||||
? `<p style="text-align:center;margin-top:24px"><a href="${escapeAttr(all)}" target="_blank" rel="noopener noreferrer nofollow" style="color:${tokenRef('link')};font-weight:600">${escapeHtml(props.allReviewsLabel ?? 'Read all reviews')}</a></p>`
|
||||
: '';
|
||||
|
||||
return {
|
||||
html: `<section${idAttr}${title ? ` aria-labelledby="${hid}"` : ''}${sectionStyle ? ` style="${sectionStyle}"` : ''}><div style="max-width:1100px;margin:0 auto">${title ? `<h2 id="${hid}" style="margin:0 0 24px;text-align:center;color:${tokenRef('text')}">${escapeHtml(title)}</h2>` : ''}<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:20px">${cards}</div>${allHtml}</div></section>`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { StickyCallBar, telHref } from './StickyCallBar';
|
||||
import { exportBodyHtml } from '../../utils/html-export';
|
||||
|
||||
const toHtml = (StickyCallBar as any).toHtml;
|
||||
const defaults = () => ({ ...(StickyCallBar as any).craft.props });
|
||||
|
||||
describe('StickyCallBar.toHtml', () => {
|
||||
test('default: fixed bar, primary token, tel: preserved, two links', () => {
|
||||
const { html } = toHtml(defaults(), '');
|
||||
expect(html).toContain('position:fixed;bottom:0;left:0;right:0;z-index:999');
|
||||
expect(html).toContain('var(--wsb-primary)');
|
||||
expect(html).toContain('href="tel:+15551234567"');
|
||||
expect(html.match(/<a /g)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('formats free-text phone into a dialable tel: href', () => {
|
||||
expect(telHref('(555) 123-4567')).toBe('tel:5551234567');
|
||||
expect(telHref('+1 555 123 4567')).toBe('tel:+15551234567');
|
||||
expect(telHref('javascript:alert(1)')).toBe('tel:1');
|
||||
expect(telHref('call me')).toBe('');
|
||||
});
|
||||
|
||||
test('hostile directions URL and labels', () => {
|
||||
const { html } = toHtml({ ...defaults(), directionsUrl: 'javascript:alert(1)', callLabel: '<script>x</script>', phone: '+1555' }, '');
|
||||
expect(html).not.toContain('javascript:');
|
||||
expect(html).not.toContain('<script>');
|
||||
expect(html).toContain('<script>');
|
||||
expect(html.match(/<a /g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('no dialable phone and no directions renders nothing', () => {
|
||||
expect((toHtml({ ...defaults(), phone: '', directionsUrl: '' }, '')).html).toBe('');
|
||||
});
|
||||
|
||||
test('exportBodyHtml emits data-hide-desktop data-hide-tablet (mobile-only)', () => {
|
||||
const state = JSON.stringify({
|
||||
ROOT: { type: 'div', isCanvas: true, props: {}, displayName: 'div', custom: {}, hidden: false, nodes: ['bar'], linkedNodes: {} },
|
||||
bar: { type: { resolvedName: 'StickyCallBar' }, isCanvas: false, props: defaults(), displayName: 'Call Bar', custom: {}, parent: 'ROOT', hidden: false, nodes: [], linkedNodes: {} },
|
||||
});
|
||||
const out = exportBodyHtml(state);
|
||||
const body = typeof out === 'string' ? out : (out as any).html ?? JSON.stringify(out);
|
||||
expect(body).toContain('data-hide-desktop');
|
||||
expect(body).toContain('data-hide-tablet');
|
||||
expect(body).not.toContain('data-hide-mobile');
|
||||
expect(body).toContain('href="tel:+15551234567"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('StickyCallBar.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((StickyCallBar as any).craft.props as object) };
|
||||
const { html } = (((StickyCallBar) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['bg']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of [] as string[]) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { escapeHtml, escapeAttr, cssValue, safeUrl } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
interface StickyCallBarProps {
|
||||
phone?: string;
|
||||
callLabel?: string;
|
||||
directionsUrl?: string;
|
||||
directionsLabel?: string;
|
||||
bgColor?: string;
|
||||
textColor?: string;
|
||||
position?: 'bottom';
|
||||
style?: CSSProperties;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
hideOnTablet?: boolean;
|
||||
hideOnMobile?: boolean;
|
||||
}
|
||||
|
||||
/** tel: href from free text: keep only digits and a leading +. '' when nothing dialable remains. */
|
||||
export function telHref(phone: unknown): string {
|
||||
const raw = typeof phone === 'string' ? phone.trim() : '';
|
||||
const digits = raw.replace(/[^0-9]/g, '');
|
||||
if (!digits) return '';
|
||||
return `tel:${raw.startsWith('+') ? '+' : ''}${digits}`;
|
||||
}
|
||||
|
||||
/** Directions link: http(s) only (Maps / Apple Maps / OSM), never other schemes. */
|
||||
export function httpUrl(url: unknown): string {
|
||||
const u = safeUrl(typeof url === 'string' ? url : '');
|
||||
return /^https?:\/\//i.test(u) ? u : '';
|
||||
}
|
||||
|
||||
const linkCss = (textColor: string, sep: boolean) =>
|
||||
`flex:1;display:block;text-align:center;padding:14px 8px;font-weight:600;font-size:16px;text-decoration:none;color:${textColor}${sep ? ';border-left:1px solid rgba(255,255,255,0.35)' : ''}`;
|
||||
|
||||
export const StickyCallBar: UserComponent<StickyCallBarProps> = ({
|
||||
phone = '+15551234567',
|
||||
callLabel = 'Call us',
|
||||
directionsUrl = 'https://maps.google.com/?q=Your+Business',
|
||||
directionsLabel = 'Directions',
|
||||
bgColor = tokenRef('primary'),
|
||||
textColor = tokenRef('bg'),
|
||||
style = {},
|
||||
}) => {
|
||||
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
|
||||
// The editor shows the bar in-flow (not position:fixed) so it never covers the canvas.
|
||||
return (
|
||||
<div
|
||||
ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
style={{ display: 'flex', backgroundColor: bgColor, outline: selected ? '2px solid #3b82f6' : 'none', ...style }}
|
||||
>
|
||||
{phone && <span style={{ flex: 1, textAlign: 'center', padding: '14px 8px', fontWeight: 600, color: textColor }}>{callLabel}</span>}
|
||||
{directionsUrl && <span style={{ flex: 1, textAlign: 'center', padding: '14px 8px', fontWeight: 600, color: textColor, borderLeft: '1px solid rgba(255,255,255,0.35)' }}>{directionsLabel}</span>}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
StickyCallBar.craft = {
|
||||
displayName: 'Call Bar',
|
||||
props: {
|
||||
phone: '+15551234567',
|
||||
callLabel: 'Call us',
|
||||
directionsUrl: 'https://maps.google.com/?q=Your+Business',
|
||||
directionsLabel: 'Directions',
|
||||
bgColor: tokenRef('primary'),
|
||||
textColor: tokenRef('bg'),
|
||||
position: 'bottom',
|
||||
style: {},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
// Mobile-only: the export's VISIBILITY_CSS hides it on desktop and tablet.
|
||||
hideOnDesktop: true,
|
||||
hideOnTablet: true,
|
||||
hideOnMobile: false,
|
||||
},
|
||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||
};
|
||||
|
||||
// The fixed bar can cover page content at the bottom edge; add a Spacer at the
|
||||
// end of the page to compensate (documented, not automatic).
|
||||
(StickyCallBar as any).toHtml = (props: StickyCallBarProps, _childrenHtml: string) => {
|
||||
const bg = cssValue(props.bgColor) || tokenRef('primary');
|
||||
const fg = cssValue(props.textColor) || tokenRef('bg');
|
||||
const tel = telHref(props.phone);
|
||||
const dir = httpUrl(props.directionsUrl);
|
||||
const links: string[] = [];
|
||||
if (tel) links.push(`<a href="${escapeAttr(tel)}" style="${linkCss(fg, false)}">${escapeHtml(props.callLabel ?? 'Call us')}</a>`);
|
||||
if (dir) links.push(`<a href="${escapeAttr(dir)}" target="_blank" rel="noopener noreferrer" style="${linkCss(fg, links.length > 0)}">${escapeHtml(props.directionsLabel ?? 'Directions')}</a>`);
|
||||
if (links.length === 0) return { html: '' };
|
||||
return {
|
||||
html: `<nav aria-label="Quick contact" style="position:fixed;bottom:0;left:0;right:0;z-index:999;display:flex;background-color:${bg}">${links.join('')}</nav>`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, test, expect, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { renderEditorHarness, EditorHarness } from '../../test-utils/editorHarness';
|
||||
import { insertBlock } from '../../panels/left/blocks-registry';
|
||||
import { BusinessStylePanel } from '../../panels/right/styles/BusinessStylePanel';
|
||||
import { GenericPropsEditor } from '../../panels/right/styles/GenericPropsEditor';
|
||||
import { deriveVirtualRows } from '../../panels/left/layers-virtual-rows';
|
||||
import { exportBodyHtml } from '../../utils/html-export';
|
||||
|
||||
let h: EditorHarness | null = null;
|
||||
afterEach(() => { h?.unmount(); h = null; });
|
||||
|
||||
const BLOCKS_UNDER_TEST: Array<[string, string, string | null]> = [
|
||||
['opening-hours', 'OpeningHours', 'rows'],
|
||||
['call-bar', 'StickyCallBar', null],
|
||||
['reviews-strip', 'ReviewsStrip', 'reviews'],
|
||||
['booking-embed', 'BookingEmbed', null],
|
||||
];
|
||||
|
||||
const Probe: React.FC<{ id: string; which: 'business' | 'generic' }> = ({ id, which }) => {
|
||||
const { props, name } = useEditor((state) => ({ props: state.nodes[id]?.data.props, name: state.nodes[id]?.data.displayName }));
|
||||
const Panel = which === 'business' ? BusinessStylePanel : GenericPropsEditor;
|
||||
return <div data-testid="panel" data-name={name}><Panel selectedId={id} nodeProps={props || {}} typeName={name} /></div>;
|
||||
};
|
||||
|
||||
describe('local-business blocks in the real editor', () => {
|
||||
test.each(BLOCKS_UNDER_TEST)('insertBlock(%s) creates a %s node and exports', (blockId, resolvedName) => {
|
||||
h = renderEditorHarness();
|
||||
let id: string | null = null;
|
||||
h.act(() => { id = insertBlock(h!.query, h!.actions, blockId); });
|
||||
expect(id).toBeTruthy();
|
||||
expect(JSON.parse(h.getSerialized())[id!].type.resolvedName).toBe(resolvedName);
|
||||
const out: any = exportBodyHtml(h.getSerialized());
|
||||
expect(typeof out === 'string' ? out : out.html).toBeTruthy();
|
||||
});
|
||||
|
||||
test.each(['business', 'generic'] as const)('%s panel renders per-item fields for rows / reviews', (which) => {
|
||||
const check = (blockId: string, fields: string[]) => {
|
||||
h = renderEditorHarness();
|
||||
let id: string | null = null;
|
||||
h.act(() => { id = insertBlock(h!.query, h!.actions, blockId); });
|
||||
h.mountChild(<Probe id={id!} which={which} />);
|
||||
const text = (h.container.querySelector('[data-testid="panel"]')?.textContent || '').toLowerCase();
|
||||
for (const f of fields) expect(text, `${blockId}:${f}`).toContain(f);
|
||||
h.unmount(); h = null;
|
||||
};
|
||||
check('opening-hours', ['day', 'hours', 'closed']);
|
||||
check('reviews-strip', ['name', 'rating', 'text', 'source', 'url']);
|
||||
});
|
||||
|
||||
test('layers virtual rows are derived for hours and reviews', () => {
|
||||
h = renderEditorHarness();
|
||||
let id: string | null = null;
|
||||
h.act(() => { id = insertBlock(h!.query, h!.actions, 'opening-hours'); });
|
||||
const n = JSON.parse(h.getSerialized())[id!];
|
||||
const rows = deriveVirtualRows(n.displayName, n.props);
|
||||
expect(rows.map((r) => r.label)).toEqual(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']);
|
||||
let rid: string | null = null;
|
||||
h.act(() => { rid = insertBlock(h!.query, h!.actions, 'reviews-strip'); });
|
||||
const r = JSON.parse(h.getSerialized())[rid!];
|
||||
expect(deriveVirtualRows(r.displayName, r.props).map((x) => x.label)).toEqual(['Alex P.', 'Jordan M.', 'Sam R.']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
/**
|
||||
* INERT editor-only stand-in for the ALTCHA widget. It makes no network request and loads
|
||||
* no script: the real widget is injected at PUBLISH time by the WHP panel
|
||||
* (FormRelayRewrite.php) once the relay token is known. Never emitted by toHtml.
|
||||
*/
|
||||
export const CaptchaMock = ({ style }: { style?: CSSProperties }) => (
|
||||
<div
|
||||
data-testid="captcha-mock"
|
||||
aria-hidden="true"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', maxWidth: 260,
|
||||
border: '1px solid rgba(128,128,128,0.4)', borderRadius: 6, fontSize: 13,
|
||||
fontFamily: 'Inter, sans-serif', opacity: 0.85, pointerEvents: 'none', ...style,
|
||||
}}
|
||||
>
|
||||
<span style={{ width: 16, height: 16, border: '2px solid currentColor', borderRadius: 3, display: 'inline-block' }} />
|
||||
I'm not a robot <span style={{ marginLeft: 'auto', fontSize: 10, opacity: 0.6 }}>ALTCHA</span>
|
||||
</div>
|
||||
);
|
||||
@@ -6,7 +6,7 @@ const toHtml = (ContactForm as any).toHtml;
|
||||
describe('ContactForm.toHtml relay wiring', () => {
|
||||
test('with recipientEmail: emits marker, placeholder action, honeypot', () => {
|
||||
const { html } = toHtml({ recipientEmail: 'a@b.com', thankYouUrl: '/thx', fields: [] }, '');
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" recipient="a@b.com" thankyou="\/thx"-->/);
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" captcha="1" recipient="a@b.com" thankyou="\/thx"-->/);
|
||||
expect(html).toMatch(/action="__WHP_FORM_ACTION__F_[0-9a-z]+__"/);
|
||||
expect(html).toContain('method="POST"');
|
||||
expect(html).toContain('name="_gotcha"');
|
||||
@@ -244,7 +244,9 @@ describe('ContactForm.toHtml destination marker', () => {
|
||||
// if it has to be edited, every already-published site's forms have changed
|
||||
// shape and that is the thing to stop, not the test.
|
||||
const FROZEN_LEGACY_MARKER =
|
||||
'<!--WHP-FORM id="F_3hodg" recipient="a@example.com" thankyou="/thx"-->';
|
||||
'<!--WHP-FORM id="F_3hodg" captcha="1" recipient="a@example.com" thankyou="/thx"-->';
|
||||
// (captcha="1" was added when captcha became mandatory on every relay form: that is the one deliberate
|
||||
// shape change since 071f3447; the fid and everything else is unchanged.)
|
||||
|
||||
const legacy = toHtml({ ...defaultProps, recipientEmail: 'a@example.com', thankYouUrl: '/thx' }, '', 'n1');
|
||||
expect(legacy.html.startsWith(`${FROZEN_LEGACY_MARKER}<form `)).toBe(true);
|
||||
@@ -286,3 +288,50 @@ describe('ContactForm.toHtml destination marker', () => {
|
||||
expect(out.html).toContain('name="_gotcha"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm.toHtml palette token fallbacks (Refs #44)', () => {
|
||||
test('submitColor empty -> primary token; input text -> text token', () => {
|
||||
const { html } = toHtml({ recipientEmail: 'a@b.com', fields: [{ type: 'text', label: 'Name', name: 'name' }], submitColor: '' }, '');
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect(html).toContain('color:var(--wsb-text)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
expect(html).not.toContain('#1f2937');
|
||||
});
|
||||
test('explicit submitColor wins', () => {
|
||||
const { html } = toHtml({ recipientEmail: 'a@b.com', fields: [], submitColor: '#ff0000' }, '');
|
||||
expect(html).toContain('background-color:#ff0000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ fields: [{ label: 'N', name: 'n', type: 'text', required: true }] }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border", "text", "error"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#ef4444", "#374151", "#d1d5db", "#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm.toHtml dark-aware inputs (eval 2026-11-01)', () => {
|
||||
const fields = [{ type: 'text', label: 'Name', name: 'name', placeholder: 'Your name', required: true }];
|
||||
test('inputTextColor sets the typed text colour; placeholders follow it (currentColor) via a scoped rule', () => {
|
||||
const { html } = toHtml({ fields, inputBg: '#1b1530', inputTextColor: '#f5f3ff' }, '', 'n1');
|
||||
expect(html).toMatch(/<input[^>]*style="[^"]*color:#f5f3ff/);
|
||||
expect(html).toMatch(/<form[^>]*data-wsb-form/);
|
||||
expect(html).toContain('<style>form[data-wsb-form] ::placeholder{color:currentColor;opacity:.7}</style>');
|
||||
});
|
||||
test('without inputTextColor the old derivation stays (light stored surface -> legacy dark text)', () => {
|
||||
expect(toHtml({ fields, inputBg: '#ffffff' }, '').html).toMatch(/<input[^>]*color:#1f2937/);
|
||||
expect(toHtml({ fields }, '').html).toMatch(/<input[^>]*color:var\(--wsb-text\)/);
|
||||
});
|
||||
test('an inputBorder written as a whole border ("1px solid X") is used as-is, not doubled into "1px solid 1px solid X"', () => {
|
||||
const { html } = toHtml({ fields, inputBorder: '1px solid color-mix(in srgb, var(--wsb-secondary) 45%, transparent)' }, '');
|
||||
expect(html).not.toContain('1px solid 1px solid');
|
||||
expect(html).toContain('border:1px solid color-mix(in srgb, var(--wsb-secondary) 45%, transparent)');
|
||||
expect(toHtml({ fields, inputBorder: '#334155' }, '').html).toContain('border:1px solid #334155');
|
||||
});
|
||||
test('a hostile inputTextColor cannot break out of the style attribute', () => {
|
||||
const { html } = toHtml({ fields, inputTextColor: 'red;}"><script>alert(1)</script>' }, '');
|
||||
expect(html).not.toContain('<script>');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,27 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { CaptchaMock } from './CaptchaMock';
|
||||
import { relayFormWiring, isRelayWired } from '../../utils/form-relay-wiring';
|
||||
import { escapeHtml, escapeAttr, slugId, cssValue, sanitizeInputType } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { textOnSurface } from '../../utils/color';
|
||||
|
||||
/* Legacy-surface text (finding 8): nodes saved before the component-tokens
|
||||
work store inputBg '#ffffff'. The typed text on a stored LIGHT input keeps
|
||||
the pre-token dark hex so it stays readable on a dark Site Design palette;
|
||||
absent / token / dark inputs keep the token. Stored props are never
|
||||
rewritten. (Labels need no rule: labelColor has been a stored prop since
|
||||
ContactForm was introduced, so legacy nodes carry their own '#374151'.) */
|
||||
const LEGACY_INPUT_TEXT = '#1f2937';
|
||||
|
||||
/** Placeholders follow the input's own text colour, so they stay readable on dark inputs too (the UA grey did
|
||||
* not). Scoped to these forms; emitted once per form in export, once globally in the editor canvas. */
|
||||
export const FORM_PLACEHOLDER_CSS = 'form[data-wsb-form] ::placeholder{color:currentColor;opacity:.7}';
|
||||
|
||||
/** `inputBorder` is a colour; a model sometimes writes a whole border ("1px solid X"): use that as-is. */
|
||||
export const inputBorderCss = (v: string): string =>
|
||||
/\b(?:solid|dashed|dotted|double|groove|ridge|inset|outset|none|hidden)\b/i.test(v) ? v : `1px solid ${v}`;
|
||||
|
||||
// The allowlist enforced at export time lives in `sanitizeInputType`
|
||||
// (utils/escape.ts) -- this union is a superset (it also covers 'textarea'
|
||||
@@ -31,6 +50,8 @@ interface ContactFormProps {
|
||||
style?: CSSProperties;
|
||||
labelColor?: string;
|
||||
inputBg?: string;
|
||||
/** Typed text (and, via currentColor, placeholder) colour in the inputs. Absent = derived from inputBg (legacy rule). */
|
||||
inputTextColor?: string;
|
||||
inputBorder?: string;
|
||||
recipientEmail?: string;
|
||||
thankYouUrl?: string;
|
||||
@@ -44,6 +65,8 @@ interface ContactFormProps {
|
||||
webhookUrl?: string;
|
||||
webhookSecretId?: string;
|
||||
webhookAuthMode?: 'signature' | 'bearer';
|
||||
/** @deprecated Captcha is mandatory on relay forms. Old saved designs may still hold true/false here; it is ignored. */
|
||||
captcha?: boolean;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
hideOnDesktop?: boolean;
|
||||
@@ -61,13 +84,16 @@ const defaultFields: ContactFormField[] = [
|
||||
export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
fields = defaultFields,
|
||||
submitText = 'Send Message',
|
||||
submitColor = '#3b82f6',
|
||||
submitColor = tokenRef('primary'),
|
||||
formAction = '#',
|
||||
recipientEmail,
|
||||
destinationType,
|
||||
successMessage = 'Thank you! We\'ll get back to you soon.',
|
||||
style = {},
|
||||
labelColor = '#374151',
|
||||
inputBg = '#ffffff',
|
||||
inputBorder = '#d1d5db',
|
||||
labelColor = tokenRef('text'),
|
||||
inputBg = tokenRef('bg'),
|
||||
inputTextColor,
|
||||
inputBorder = tokenRef('border'),
|
||||
}) => {
|
||||
const {
|
||||
connectors: { connect, drag },
|
||||
@@ -81,10 +107,10 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
padding: '10px 14px',
|
||||
fontSize: '14px',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
border: `1px solid ${inputBorder}`,
|
||||
border: inputBorderCss(inputBorder),
|
||||
borderRadius: '6px',
|
||||
backgroundColor: inputBg,
|
||||
color: '#1f2937',
|
||||
color: inputTextColor || textOnSurface(inputBg, LEGACY_INPUT_TEXT, tokenRef('text')),
|
||||
boxSizing: 'border-box',
|
||||
outline: 'none',
|
||||
};
|
||||
@@ -94,6 +120,7 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
action={formAction}
|
||||
method="POST"
|
||||
data-wsb-form=""
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
style={{
|
||||
padding: '32px',
|
||||
@@ -108,7 +135,7 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
<div key={i} style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
|
||||
<label style={{ fontSize: '14px', fontWeight: '500', color: labelColor }}>
|
||||
{field.label}
|
||||
{field.required && <span style={{ color: '#ef4444', marginLeft: '2px' }}>*</span>}
|
||||
{field.required && <span style={{ color: tokenRef('error'), marginLeft: '2px' }}>*</span>}
|
||||
</label>
|
||||
{field.type === 'textarea' ? (
|
||||
<textarea
|
||||
@@ -140,6 +167,7 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{isRelayWired(recipientEmail, destinationType) && <CaptchaMock />}
|
||||
<button
|
||||
type="submit"
|
||||
style={{
|
||||
@@ -147,7 +175,7 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
|
||||
fontSize: '16px',
|
||||
fontWeight: '600',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#ffffff',
|
||||
color: tokenRef('bg'),
|
||||
backgroundColor: submitColor,
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
@@ -168,17 +196,17 @@ ContactForm.craft = {
|
||||
props: {
|
||||
fields: defaultFields,
|
||||
submitText: 'Send Message',
|
||||
submitColor: '#3b82f6',
|
||||
submitColor: tokenRef('primary'),
|
||||
formAction: '#',
|
||||
successMessage: 'Thank you! We\'ll get back to you soon.',
|
||||
style: {
|
||||
backgroundColor: '#ffffff',
|
||||
backgroundColor: tokenRef('bg'),
|
||||
borderRadius: '12px',
|
||||
border: '1px solid #e5e7eb',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
},
|
||||
labelColor: '#374151',
|
||||
inputBg: '#ffffff',
|
||||
inputBorder: '#d1d5db',
|
||||
labelColor: tokenRef('text'),
|
||||
inputBg: tokenRef('bg'),
|
||||
inputBorder: tokenRef('border'),
|
||||
recipientEmail: '',
|
||||
thankYouUrl: '',
|
||||
// Present (not omitted) so FormStylePanel's `nodeProps.X !== undefined`
|
||||
@@ -212,13 +240,14 @@ ContactForm.craft = {
|
||||
});
|
||||
// Sanitized -- raw string-interpolation sinks in inputStyleStr/labelHtml
|
||||
// below.
|
||||
const labelColor = cssValue(props.labelColor) || '#374151';
|
||||
const inputBg = cssValue(props.inputBg) || '#ffffff';
|
||||
const inputBorder = cssValue(props.inputBorder) || '#d1d5db';
|
||||
const inputStyleStr = `width:100%;padding:10px 14px;font-size:14px;font-family:Inter,sans-serif;border:1px solid ${inputBorder};border-radius:6px;background-color:${inputBg};color:#1f2937;box-sizing:border-box;outline:none`;
|
||||
const labelColor = cssValue(props.labelColor) || tokenRef('text');
|
||||
const inputBg = cssValue(props.inputBg) || tokenRef('bg');
|
||||
const inputBorder = cssValue(props.inputBorder) || tokenRef('border');
|
||||
const inputText = cssValue(props.inputTextColor) || textOnSurface(inputBg, LEGACY_INPUT_TEXT, tokenRef('text'));
|
||||
const inputStyleStr = `width:100%;padding:10px 14px;font-size:14px;font-family:Inter,sans-serif;border:${inputBorderCss(inputBorder)};border-radius:6px;background-color:${inputBg};color:${inputText};box-sizing:border-box;outline:none`;
|
||||
|
||||
const fieldsHtml = (props.fields || defaultFields).map((field, i) => {
|
||||
const reqStar = field.required ? '<span style="color:#ef4444;margin-left:2px">*</span>' : '';
|
||||
const reqStar = field.required ? `<span style="color:${tokenRef('error')};margin-left:2px">*</span>` : '';
|
||||
// Deterministic id: index + slugified name, so repeated fields with the
|
||||
// same name (or no name) still get unique, stable ids -- no Math.random.
|
||||
const fieldId = `field-${i}-${slugId(field.name)}`;
|
||||
@@ -241,8 +270,8 @@ ContactForm.craft = {
|
||||
fontSize: '16px',
|
||||
fontWeight: '600',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#ffffff',
|
||||
backgroundColor: props.submitColor || '#3b82f6',
|
||||
color: tokenRef('bg'),
|
||||
backgroundColor: cssValue(props.submitColor) || tokenRef('primary'),
|
||||
border: 'none',
|
||||
borderRadius: '8px',
|
||||
cursor: 'pointer',
|
||||
@@ -269,8 +298,8 @@ ContactForm.craft = {
|
||||
const successAttr = props.successMessage ? ` data-whp-success-message="${escapeAttr(props.successMessage)}"` : '';
|
||||
|
||||
return {
|
||||
html: `${marker}<form action="${actionAttr}" method="POST"${successAttr}${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
html: `${marker}<form action="${actionAttr}" method="POST" data-wsb-form${successAttr}${formStyle ? ` style="${formStyle}"` : ''}>
|
||||
${honeypot ? ` ${honeypot}\n` : ''}${fieldsHtml ? ` ${fieldsHtml}\n` : ''} <button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${escapeHtml(props.submitText || 'Send Message')}</button>
|
||||
</form>`,
|
||||
</form><style>${FORM_PLACEHOLDER_CSS}</style>`,
|
||||
};
|
||||
};
|
||||
@@ -38,3 +38,20 @@ describe('FormButton.craft.props includes animation/visibility defaults', () =>
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FormButton.toHtml palette token default (Refs #44)', () => {
|
||||
test('a new form button (craft default props) paints the primary token', () => {
|
||||
const { html } = toHtml({ ...(FormButton as any).craft.props }, '');
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
});
|
||||
});
|
||||
|
||||
describe('FormButton.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ ...(FormButton as any).craft.props }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "primary"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
|
||||
interface FormButtonProps {
|
||||
text?: string;
|
||||
@@ -31,8 +32,8 @@ export const FormButton: UserComponent<FormButtonProps> = ({
|
||||
onClick={(e) => e.preventDefault()}
|
||||
style={{
|
||||
padding: '12px 32px',
|
||||
backgroundColor: '#3b82f6',
|
||||
color: '#ffffff',
|
||||
backgroundColor: tokenRef('primary'),
|
||||
color: tokenRef('bg'),
|
||||
border: 'none',
|
||||
borderRadius: '6px',
|
||||
fontSize: '16px',
|
||||
@@ -55,8 +56,8 @@ FormButton.craft = {
|
||||
props: {
|
||||
text: 'Submit',
|
||||
style: {
|
||||
backgroundColor: '#3b82f6',
|
||||
color: '#ffffff',
|
||||
backgroundColor: tokenRef('primary'),
|
||||
color: tokenRef('bg'),
|
||||
padding: '12px 32px',
|
||||
borderRadius: '6px',
|
||||
fontWeight: '600',
|
||||
|
||||
@@ -6,7 +6,7 @@ const toHtml = (FormContainer as any).toHtml;
|
||||
describe('FormContainer.toHtml relay wiring', () => {
|
||||
test('with recipientEmail: marker + placeholder action + honeypot, forces POST', () => {
|
||||
const { html } = toHtml({ recipientEmail: 'a@b.com', thankYouUrl: '/thx', method: 'GET' }, '<input name="email">');
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" recipient="a@b.com" thankyou="\/thx"-->/);
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" captcha="1" recipient="a@b.com" thankyou="\/thx"-->/);
|
||||
expect(html).toMatch(/action="__WHP_FORM_ACTION__F_[0-9a-z]+__"/);
|
||||
expect(html).toContain('method="POST"'); // relay forces POST even though method=GET
|
||||
expect(html).toContain('name="_gotcha"');
|
||||
@@ -69,3 +69,12 @@ describe('FormContainer.craft.props includes animation/visibility defaults', ()
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('FormContainer.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ ...(FormContainer as any).craft.props }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#ffffff", "#e4e4e7"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,18 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||
import { Container } from '../layout/Container';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { CaptchaMock } from './CaptchaMock';
|
||||
import { relayFormWiring, isRelayWired } from '../../utils/form-relay-wiring';
|
||||
import { sanitizeFormMethod } from '../../utils/escape';
|
||||
|
||||
interface FormContainerProps {
|
||||
action?: string;
|
||||
method?: 'GET' | 'POST';
|
||||
recipientEmail?: string;
|
||||
/** @deprecated Captcha is mandatory on relay forms. Old saved designs may still hold true/false here; it is ignored. */
|
||||
captcha?: boolean;
|
||||
thankYouUrl?: string;
|
||||
style?: CSSProperties;
|
||||
children?: React.ReactNode;
|
||||
@@ -23,6 +27,7 @@ export const FormContainer: UserComponent<FormContainerProps> = ({
|
||||
action = '#',
|
||||
method = 'POST',
|
||||
style = {},
|
||||
recipientEmail,
|
||||
}) => {
|
||||
const { connectors: { connect, drag } } = useNode();
|
||||
|
||||
@@ -45,6 +50,7 @@ export const FormContainer: UserComponent<FormContainerProps> = ({
|
||||
style={{ display: 'flex', flexDirection: 'column', gap: '16px', padding: '0' }}
|
||||
tag="div"
|
||||
/>
|
||||
{isRelayWired(recipientEmail) && <CaptchaMock style={{ marginTop: 12 }} />}
|
||||
</form>
|
||||
);
|
||||
};
|
||||
@@ -60,9 +66,9 @@ FormContainer.craft = {
|
||||
thankYouUrl: '',
|
||||
style: {
|
||||
padding: '24px',
|
||||
backgroundColor: '#ffffff',
|
||||
backgroundColor: tokenRef('bg'),
|
||||
borderRadius: '8px',
|
||||
border: '1px solid #e4e4e7',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
},
|
||||
animation: '',
|
||||
animationDelay: '',
|
||||
|
||||
@@ -89,3 +89,12 @@ describe('InputField.craft.props includes animation/visibility defaults', () =>
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('InputField.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ label: 'L', required: true }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border", "text", "error"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#18181b", "#ef4444", "#d4d4d8", "#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId, sanitizeInputType } from '../../utils/escape';
|
||||
@@ -45,8 +46,8 @@ export const InputField: UserComponent<InputFieldProps> = ({
|
||||
}}
|
||||
>
|
||||
{label && (
|
||||
<label style={{ fontSize: '14px', fontWeight: '500', color: '#18181b' }}>
|
||||
{label}{required && <span style={{ color: '#ef4444' }}> *</span>}
|
||||
<label style={{ fontSize: '14px', fontWeight: '500', color: tokenRef('text') }}>
|
||||
{label}{required && <span style={{ color: tokenRef('error') }}> *</span>}
|
||||
</label>
|
||||
)}
|
||||
<input
|
||||
@@ -56,11 +57,11 @@ export const InputField: UserComponent<InputFieldProps> = ({
|
||||
required={required}
|
||||
style={{
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #d4d4d8',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
borderRadius: '6px',
|
||||
fontSize: '14px',
|
||||
color: '#18181b',
|
||||
backgroundColor: '#ffffff',
|
||||
color: tokenRef('text'),
|
||||
backgroundColor: tokenRef('bg'),
|
||||
outline: 'none',
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
@@ -113,7 +114,7 @@ InputField.craft = {
|
||||
// hash for legacy 2-arg call sites without a node id.
|
||||
const fieldId = scopeId(nodeId, props.name || 'field', 'field');
|
||||
const labelHtml = props.label
|
||||
? `<label for="${escapeAttr(fieldId)}" style="font-size:14px;font-weight:500;color:#18181b">${escapeHtml(props.label)}${props.required ? '<span style="color:#ef4444"> *</span>' : ''}</label>`
|
||||
? `<label for="${escapeAttr(fieldId)}" style="font-size:14px;font-weight:500;color:${tokenRef('text')}">${escapeHtml(props.label)}${props.required ? `<span style="color:${tokenRef('error')}"> *</span>` : ''}</label>`
|
||||
: '';
|
||||
const ariaLabelAttr = !props.label
|
||||
? ` aria-label="${escapeAttr(props.placeholder || props.name || 'Input field')}"`
|
||||
@@ -121,7 +122,7 @@ InputField.craft = {
|
||||
return {
|
||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||
${labelHtml}
|
||||
<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(props.type)}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
|
||||
<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(props.type)}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid ${tokenRef('border')};border-radius:6px;font-size:14px;color:${tokenRef('text')};background-color:${tokenRef('bg')};width:100%;box-sizing:border-box" />
|
||||
</div>`,
|
||||
};
|
||||
};
|
||||
@@ -50,7 +50,7 @@ describe('SubscribeForm.toHtml is functional (not a dead POST)', () => {
|
||||
|
||||
test('with recipientEmail: emits the relay marker, placeholder action, and honeypot -- a working submission path', () => {
|
||||
const { html } = toHtml({ recipientEmail: 'news@example.com', thankYouUrl: '/thanks' }, '', 'node-sub1');
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" recipient="news@example.com" thankyou="\/thanks"-->/);
|
||||
expect(html).toMatch(/<!--WHP-FORM id="F_[0-9a-z]+" captcha="1" recipient="news@example.com" thankyou="\/thanks"-->/);
|
||||
expect(html).toMatch(/action="__WHP_FORM_ACTION__F_[0-9a-z]+__"/);
|
||||
expect(html).toContain('name="_gotcha"');
|
||||
const mid = html.match(/id="(F_[0-9a-z]+)"/)![1];
|
||||
@@ -79,3 +79,26 @@ describe('SubscribeForm.craft.props includes animation/visibility defaults', ()
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SubscribeForm.toHtml palette token fallbacks (Refs #44)', () => {
|
||||
test('buttonColor absent -> primary token; heading/input text -> text token', () => {
|
||||
const { html } = toHtml({ heading: 'Join us' }, '');
|
||||
expect(html).toContain('background-color:var(--wsb-primary)');
|
||||
expect(html).toContain('color:var(--wsb-text)');
|
||||
expect(html).not.toContain('#3b82f6');
|
||||
expect(html).not.toContain('#1f2937');
|
||||
});
|
||||
test('explicit buttonColor wins', () => {
|
||||
const { html } = toHtml({ buttonColor: '#ff0000' }, '');
|
||||
expect(html).toContain('background-color:#ff0000');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SubscribeForm.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({}, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border", "text"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#d1d5db", "#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,18 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
import { CaptchaMock } from './CaptchaMock';
|
||||
import { relayFormWiring, isRelayWired } from '../../utils/form-relay-wiring';
|
||||
import { escapeHtml, escapeAttr } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { textOnSurface } from '../../utils/color';
|
||||
|
||||
/* Legacy-surface text (finding 8): nodes saved before the component-tokens
|
||||
work store style.backgroundColor '#f8fafc'. The heading on a stored LIGHT
|
||||
wrapper keeps the pre-token dark hex (readable on a dark Site Design
|
||||
palette); absent / token / dark wrappers keep the token. The email input
|
||||
has its own token surface + token text, so it is unaffected. */
|
||||
const LEGACY_HEADING_TEXT = '#1f2937';
|
||||
|
||||
interface SubscribeFormProps {
|
||||
heading?: string;
|
||||
@@ -16,6 +26,8 @@ interface SubscribeFormProps {
|
||||
* published form then has no working action at all, which is the bug
|
||||
* this prop exists to fix. */
|
||||
recipientEmail?: string;
|
||||
/** @deprecated Captcha is mandatory on relay forms. Old saved designs may still hold true/false here; it is ignored. */
|
||||
captcha?: boolean;
|
||||
thankYouUrl?: string;
|
||||
animation?: string;
|
||||
animationDelay?: string;
|
||||
@@ -28,9 +40,10 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||
heading = 'Subscribe to our newsletter',
|
||||
placeholder = 'Enter your email',
|
||||
buttonText = 'Subscribe',
|
||||
buttonColor = '#3b82f6',
|
||||
buttonColor = tokenRef('primary'),
|
||||
layout = 'inline',
|
||||
style = {},
|
||||
recipientEmail,
|
||||
}) => {
|
||||
const {
|
||||
connectors: { connect, drag },
|
||||
@@ -55,7 +68,7 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||
<h3 style={{
|
||||
fontSize: '22px',
|
||||
fontWeight: '600',
|
||||
color: '#1f2937',
|
||||
color: textOnSurface(style.backgroundColor, LEGACY_HEADING_TEXT, tokenRef('text')),
|
||||
marginBottom: '20px',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
}}>
|
||||
@@ -81,10 +94,10 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||
padding: '12px 16px',
|
||||
fontSize: '15px',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
border: '1px solid #d1d5db',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
borderRadius: isInline ? '8px 0 0 8px' : '8px',
|
||||
backgroundColor: '#ffffff',
|
||||
color: '#1f2937',
|
||||
backgroundColor: tokenRef('bg'),
|
||||
color: tokenRef('text'),
|
||||
outline: 'none',
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
@@ -96,7 +109,7 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||
fontSize: '15px',
|
||||
fontWeight: '600',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#ffffff',
|
||||
color: tokenRef('bg'),
|
||||
backgroundColor: buttonColor,
|
||||
border: 'none',
|
||||
borderRadius: isInline ? '0 8px 8px 0' : '8px',
|
||||
@@ -107,6 +120,7 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
|
||||
{buttonText}
|
||||
</button>
|
||||
</form>
|
||||
{isRelayWired(recipientEmail) && <CaptchaMock style={{ margin: '12px auto 0' }} />}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -119,9 +133,9 @@ SubscribeForm.craft = {
|
||||
heading: 'Subscribe to our newsletter',
|
||||
placeholder: 'Enter your email',
|
||||
buttonText: 'Subscribe',
|
||||
buttonColor: '#3b82f6',
|
||||
buttonColor: tokenRef('primary'),
|
||||
layout: 'inline',
|
||||
style: { backgroundColor: '#f8fafc' },
|
||||
style: { backgroundColor: tokenRef('bg') },
|
||||
recipientEmail: '',
|
||||
thankYouUrl: '',
|
||||
animation: '',
|
||||
@@ -144,7 +158,7 @@ SubscribeForm.craft = {
|
||||
heading = 'Subscribe to our newsletter',
|
||||
placeholder = 'Enter your email',
|
||||
buttonText = 'Subscribe',
|
||||
buttonColor = '#3b82f6',
|
||||
buttonColor = tokenRef('primary'),
|
||||
layout = 'inline',
|
||||
style = {},
|
||||
} = props;
|
||||
@@ -158,7 +172,7 @@ SubscribeForm.craft = {
|
||||
});
|
||||
|
||||
const headingHtml = heading
|
||||
? `<h3 style="font-size:22px;font-weight:600;color:#1f2937;margin-bottom:20px;font-family:Inter,sans-serif">${escapeHtml(heading)}</h3>`
|
||||
? `<h3 style="font-size:22px;font-weight:600;color:${textOnSurface(style.backgroundColor, LEGACY_HEADING_TEXT, tokenRef('text'))};margin-bottom:20px;font-family:Inter,sans-serif">${escapeHtml(heading)}</h3>`
|
||||
: '';
|
||||
|
||||
const formStyle = cssPropsToString({
|
||||
@@ -170,14 +184,14 @@ SubscribeForm.craft = {
|
||||
alignItems: 'stretch',
|
||||
});
|
||||
|
||||
const inputStyleStr = `flex:1;padding:12px 16px;font-size:15px;font-family:Inter,sans-serif;border:1px solid #d1d5db;border-radius:${isInline ? '8px 0 0 8px' : '8px'};background-color:#ffffff;color:#1f2937;outline:none;box-sizing:border-box`;
|
||||
const inputStyleStr = `flex:1;padding:12px 16px;font-size:15px;font-family:Inter,sans-serif;border:1px solid ${tokenRef('border')};border-radius:${isInline ? '8px 0 0 8px' : '8px'};background-color:${tokenRef('bg')};color:${tokenRef('text')};outline:none;box-sizing:border-box`;
|
||||
|
||||
const btnStyle = cssPropsToString({
|
||||
padding: '12px 24px',
|
||||
fontSize: '15px',
|
||||
fontWeight: '600',
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
color: '#ffffff',
|
||||
color: tokenRef('bg'),
|
||||
backgroundColor: buttonColor,
|
||||
border: 'none',
|
||||
borderRadius: isInline ? '0 8px 8px 0' : '8px',
|
||||
|
||||
@@ -80,3 +80,12 @@ describe('TextareaField.craft.props includes animation/visibility defaults', ()
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('TextareaField.toHtml design tokens (#44)', () => {
|
||||
test('default export references var(--wsb-*) and no longer carries the old hard-coded hex', () => {
|
||||
const { html } = toHtml({ label: 'L', required: true }, '');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ["bg", "border", "text", "error"]) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ["#18181b", "#ef4444", "#d4d4d8", "#ffffff"]) expect(lower, `old ${hex}`).not.toContain(hex);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { CSSProperties } from 'react';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { useNode, UserComponent } from '@craftjs/core';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
||||
@@ -45,8 +46,8 @@ export const TextareaField: UserComponent<TextareaFieldProps> = ({
|
||||
}}
|
||||
>
|
||||
{label && (
|
||||
<label style={{ fontSize: '14px', fontWeight: '500', color: '#18181b' }}>
|
||||
{label}{required && <span style={{ color: '#ef4444' }}> *</span>}
|
||||
<label style={{ fontSize: '14px', fontWeight: '500', color: tokenRef('text') }}>
|
||||
{label}{required && <span style={{ color: tokenRef('error') }}> *</span>}
|
||||
</label>
|
||||
)}
|
||||
<textarea
|
||||
@@ -57,11 +58,11 @@ export const TextareaField: UserComponent<TextareaFieldProps> = ({
|
||||
readOnly
|
||||
style={{
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #d4d4d8',
|
||||
border: `1px solid ${tokenRef('border')}`,
|
||||
borderRadius: '6px',
|
||||
fontSize: '14px',
|
||||
color: '#18181b',
|
||||
backgroundColor: '#ffffff',
|
||||
color: tokenRef('text'),
|
||||
backgroundColor: tokenRef('bg'),
|
||||
outline: 'none',
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
@@ -120,7 +121,7 @@ TextareaField.craft = {
|
||||
// 2-arg call sites without a node id.
|
||||
const fieldId = scopeId(nodeId, props.name || 'message', 'field');
|
||||
const labelHtml = props.label
|
||||
? `<label for="${escapeAttr(fieldId)}" style="font-size:14px;font-weight:500;color:#18181b">${escapeHtml(props.label)}${props.required ? '<span style="color:#ef4444"> *</span>' : ''}</label>`
|
||||
? `<label for="${escapeAttr(fieldId)}" style="font-size:14px;font-weight:500;color:${tokenRef('text')}">${escapeHtml(props.label)}${props.required ? `<span style="color:${tokenRef('error')}"> *</span>` : ''}</label>`
|
||||
: '';
|
||||
const ariaLabelAttr = !props.label
|
||||
? ` aria-label="${escapeAttr(props.placeholder || props.name || 'Textarea field')}"`
|
||||
@@ -128,7 +129,7 @@ TextareaField.craft = {
|
||||
return {
|
||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||
${labelHtml}
|
||||
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${escapeAttr(String(rows))}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
||||
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${escapeAttr(String(rows))}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid ${tokenRef('border')};border-radius:6px;font-size:14px;color:${tokenRef('text')};background-color:${tokenRef('bg')};width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
||||
</div>`,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { ContactForm } from './ContactForm';
|
||||
import { SubscribeForm } from './SubscribeForm';
|
||||
import { FormContainer } from './FormContainer';
|
||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||
|
||||
const cases: [string, any, any][] = [
|
||||
['ContactForm', (ContactForm as any).toHtml, { fields: [] }],
|
||||
['SubscribeForm', (SubscribeForm as any).toHtml, {}],
|
||||
['FormContainer', (FormContainer as any).toHtml, {}],
|
||||
];
|
||||
const base = { recipientEmail: 'a@b.com', thankYouUrl: '/thx' };
|
||||
|
||||
describe.each(cases)('%s captcha marker attribute', (_n, toHtml, extra) => {
|
||||
const run = (p: any) => toHtml({ ...extra, ...base, ...p }, '', 'node1').html as string;
|
||||
const MARK = /<!--WHP-FORM id="F_[0-9a-z]+" captcha="1" recipient="a@b.com" thankyou="\/thx"-->/;
|
||||
test('relay form always emits captcha="1" between id and recipient', () => {
|
||||
expect(run({ captcha: true })).toMatch(MARK);
|
||||
});
|
||||
test.each([[false], [undefined], ['yes'], [1], [0], [null]])('mandatory: legacy prop %p still emits captcha="1" (no opt-out)', (v) => {
|
||||
const html = run({ captcha: v });
|
||||
expect(html).toMatch(MARK);
|
||||
expect(html).not.toContain('captcha="0"');
|
||||
expect(html).toBe(run({ captcha: true }));
|
||||
});
|
||||
test('no captcha prop at all (new design) emits captcha="1"', () => {
|
||||
expect(run({})).toMatch(MARK);
|
||||
});
|
||||
test('no relay (no recipient): no marker at all, even with captcha true', () => {
|
||||
expect(toHtml({ ...extra, captcha: true }, '', 'n').html).not.toContain('WHP-FORM');
|
||||
expect(toHtml({ ...extra, captcha: false }, '', 'n').html).not.toContain('captcha');
|
||||
});
|
||||
test('never emits widget markup (injected at publish)', () => {
|
||||
expect(run({ captcha: true })).not.toMatch(/altcha-widget|challenge\.php|widget\.php/);
|
||||
});
|
||||
});
|
||||
|
||||
test('webhook marker keeps captcha attr inside the strict-regex attribute zone', () => {
|
||||
const m = relayFormWiring('', '', undefined, 'n', { type: 'webhook', url: 'https://x.y/h' }, true).marker;
|
||||
expect(m).toMatch(/^<!--WHP-FORM id="[^"]+"(?: [a-z]+="[^"]*")* captcha="1" recipient=/);
|
||||
});
|
||||
|
||||
describe('captcha is not a configurable prop any more', () => {
|
||||
test.each([ContactForm, SubscribeForm, FormContainer])('%#: no captcha default in craft.props', (C: any) => {
|
||||
expect(C.craft.props.captcha).toBeUndefined();
|
||||
});
|
||||
test('relayFormWiring ignores the legacy 6th argument', () => {
|
||||
const on = relayFormWiring('a@b.com', '', undefined, 'n', undefined).marker;
|
||||
expect(relayFormWiring('a@b.com', '', undefined, 'n', undefined, false).marker).toBe(on);
|
||||
expect(on).toContain(' captcha="1"');
|
||||
});
|
||||
test('a form with an old captcha:false still renders its HTML without error', () => {
|
||||
for (const [, toHtml, extra] of cases) {
|
||||
expect(() => toHtml({ ...extra, ...base, captcha: false }, '', 'n1')).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -56,3 +56,29 @@ describe('BackgroundSection.toHtml style-value XSS hardening', () => {
|
||||
expect(html).toContain('child');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BackgroundSection.toHtml bgPosition focal point (#55)', () => {
|
||||
test('bgPosition is emitted as background-position', () => {
|
||||
const { html } = toHtml({ bgImage: 'assets/a.jpg', bgPosition: 'left top' }, 'child');
|
||||
expect(html).toContain('background-position:left top');
|
||||
expect(html).not.toContain('background-position:center');
|
||||
});
|
||||
test('blank or missing bgPosition keeps center', () => {
|
||||
expect(toHtml({ bgImage: 'assets/a.jpg', bgPosition: '' }, '').html).toContain('background-position:center');
|
||||
expect(toHtml({ bgImage: 'assets/a.jpg' }, '').html).toContain('background-position:center');
|
||||
});
|
||||
test('a malicious bgPosition cannot break out of the style attribute', () => {
|
||||
const { html } = toHtml({ bgImage: 'x', bgPosition: 'left";}</style><script>alert(1)</script>' }, '');
|
||||
expect(html).not.toContain('<script>alert(1)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BackgroundSection.toHtml design tokens (#44)', () => {
|
||||
test('default craft props export var(--wsb-*) and none of the old design hex', () => {
|
||||
const props = { ...((BackgroundSection as any).craft.props as object) };
|
||||
const { html } = (((BackgroundSection) as any).toHtml)(props, '', 'node-tok');
|
||||
const lower = html.toLowerCase();
|
||||
for (const t of ['text']) expect(html, `token ${t}`).toContain(`var(--wsb-${t})`);
|
||||
for (const hex of ['#1e293b']) expect(lower, `old ${hex}`).not.toContain(hex.toLowerCase());
|
||||
});
|
||||
});
|
||||
@@ -2,10 +2,14 @@ import React, { CSSProperties } from 'react';
|
||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
||||
import { Container } from './Container';
|
||||
import { cssPropsToString } from '../../utils/style-helpers';
|
||||
import { escapeAttr } from '../../utils/escape';
|
||||
import { tokenRef } from '../../utils/tokens';
|
||||
import { PlaceholderHint } from './PlaceholderHint';
|
||||
import { escapeAttr, cssValue } from '../../utils/escape';
|
||||
|
||||
interface BackgroundSectionProps {
|
||||
bgImage?: string;
|
||||
/** CSS background-position (focal point); blank = center. */
|
||||
bgPosition?: string;
|
||||
bgColor?: string;
|
||||
overlayColor?: string;
|
||||
overlayOpacity?: number;
|
||||
@@ -17,7 +21,8 @@ interface BackgroundSectionProps {
|
||||
|
||||
export const BackgroundSection: UserComponent<BackgroundSectionProps> = ({
|
||||
bgImage = '',
|
||||
bgColor = '#1e293b',
|
||||
bgPosition = '',
|
||||
bgColor = tokenRef('text'),
|
||||
overlayColor = '#000000',
|
||||
overlayOpacity = 0.4,
|
||||
innerMaxWidth = '1200px',
|
||||
@@ -37,7 +42,7 @@ export const BackgroundSection: UserComponent<BackgroundSectionProps> = ({
|
||||
backgroundColor: bgColor,
|
||||
backgroundImage: bgImage ? `url(${bgImage})` : undefined,
|
||||
backgroundSize: 'cover',
|
||||
backgroundPosition: 'center',
|
||||
backgroundPosition: cssValue(bgPosition) || 'center',
|
||||
...style,
|
||||
}}
|
||||
>
|
||||
@@ -51,6 +56,7 @@ export const BackgroundSection: UserComponent<BackgroundSectionProps> = ({
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
/>
|
||||
<PlaceholderHint url={bgImage} />
|
||||
{/* Content */}
|
||||
<Element
|
||||
id="bg-section-inner"
|
||||
@@ -75,7 +81,8 @@ BackgroundSection.craft = {
|
||||
displayName: 'Background Section',
|
||||
props: {
|
||||
bgImage: '',
|
||||
bgColor: '#1e293b',
|
||||
bgPosition: '',
|
||||
bgColor: tokenRef('text'),
|
||||
overlayColor: '#000000',
|
||||
overlayOpacity: 0.4,
|
||||
innerMaxWidth: '1200px',
|
||||
@@ -96,10 +103,10 @@ BackgroundSection.craft = {
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
minHeight: '200px',
|
||||
backgroundColor: props.bgColor || '#1e293b',
|
||||
backgroundColor: props.bgColor || tokenRef('text'),
|
||||
backgroundImage: props.bgImage ? `url(${props.bgImage})` : undefined,
|
||||
backgroundSize: 'cover',
|
||||
backgroundPosition: 'center',
|
||||
backgroundPosition: cssValue(props.bgPosition) || 'center',
|
||||
...props.style,
|
||||
});
|
||||
const overlayStyle = cssPropsToString({
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, test, expect, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { exportBodyHtml, RESPONSIVE_CSS_MINIFIED } from '../../utils/html-export';
|
||||
import { renderEditorHarness, EditorHarness } from '../../test-utils/editorHarness';
|
||||
import { DeviceProvider } from '../../state/DeviceContext';
|
||||
import { RenderNode } from '../../editor/RenderNode';
|
||||
import type { DeviceMode } from '../../types';
|
||||
// Vitest stubs CSS imports (`?raw` reads back empty); read the real file (same as DropIndicator.test).
|
||||
const nodeFs = (globalThis as any).process.getBuiltinModule('node:fs');
|
||||
const EDITOR_CSS: string = nodeFs.readFileSync(`${(globalThis as any).process.cwd()}/src/styles/editor.css`, 'utf8');
|
||||
|
||||
/**
|
||||
* Minor finding: un-stacking Columns on mobile (styleMobile.flexDirection 'row'
|
||||
* under a stacked tablet) rendered STACKED in the editor but UN-stacked when
|
||||
* published. Published mobile stacking is the global RESPONSIVE_CSS rule, which
|
||||
* matches the DESKTOP inline style; the editor's device-emulation copy of that
|
||||
* rule matched the device-RESOLVED inline style instead.
|
||||
*/
|
||||
|
||||
|
||||
/** Selector list of every editor.css rule that stacks (flex-direction:column) on the mobile frame. */
|
||||
function editorMobileStackSelectors(): string {
|
||||
const out: string[] = [];
|
||||
const re = /([^{}]+)\{([^{}]*)\}/g;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = re.exec(EDITOR_CSS))) {
|
||||
const sel = m[1].replace(/\/\*[\s\S]*?\*\//g, '').trim();
|
||||
if (sel.includes('[data-device="mobile"]') && /flex-direction:\s*column\s*!important/.test(m[2])) out.push(sel);
|
||||
}
|
||||
return out.join(',');
|
||||
}
|
||||
|
||||
/** The published global mobile stacking selector (from RESPONSIVE_CSS). */
|
||||
const PUBLISHED_STACK_SELECTOR = /\{([^{}]+)\{flex-direction:column!important\}/.exec(RESPONSIVE_CSS_MINIFIED)![1];
|
||||
|
||||
const node = (type: string, props: Record<string, unknown>, nodes: string[] = [], extra: Record<string, unknown> = {}) => ({
|
||||
type: { resolvedName: type }, isCanvas: type === 'Container', props, displayName: type,
|
||||
custom: {}, hidden: false, nodes, linkedNodes: {}, ...extra,
|
||||
});
|
||||
const colsState = (props: Record<string, unknown>) =>
|
||||
JSON.stringify({
|
||||
ROOT: node('Container', { tag: 'div', style: {} }, ['cl']),
|
||||
cl: node('ColumnLayout', { columns: 2, split: '50-50', gap: '16px', anchorId: 'cl', ...props }, [], {
|
||||
parent: 'ROOT', isCanvas: false, linkedNodes: { 'col-0': 'c0', 'col-1': 'c1' },
|
||||
}),
|
||||
c0: node('Container', { tag: 'div', style: {} }, [], { parent: 'cl' }),
|
||||
c1: node('Container', { tag: 'div', style: {} }, [], { parent: 'cl' }),
|
||||
});
|
||||
|
||||
let h: EditorHarness | null = null;
|
||||
afterEach(() => { h?.unmount(); h = null; });
|
||||
|
||||
function editorStacksOnMobile(state: string, device: DeviceMode = 'mobile'): boolean {
|
||||
h = renderEditorHarness({
|
||||
initialState: state,
|
||||
onRender: RenderNode,
|
||||
wrap: (tree) => <DeviceProvider initialDevice={device}><div className="canvas-device-frame" data-device={device}>{tree}</div></DeviceProvider>,
|
||||
});
|
||||
const el = h.container.querySelector('#cl') as HTMLElement;
|
||||
return el.matches(editorMobileStackSelectors());
|
||||
}
|
||||
|
||||
function publishedBaseStacks(state: string): boolean {
|
||||
const doc = document.createElement('div');
|
||||
doc.innerHTML = exportBodyHtml(state).html;
|
||||
return (doc.querySelector('#cl') as HTMLElement).matches(PUBLISHED_STACK_SELECTOR);
|
||||
}
|
||||
|
||||
describe('Columns mobile stacking: editor matches published', () => {
|
||||
test('un-stack on mobile under a stacked tablet -> NOT stacked in the editor (published is not)', () => {
|
||||
const state = colsState({ style: {}, styleTablet: { flexDirection: 'column' }, styleMobile: { flexDirection: 'row' } });
|
||||
expect(publishedBaseStacks(state)).toBe(false);
|
||||
expect(exportBodyHtml(state).html).toMatch(/@media \(max-width:767px\)\{\[data-wsb-r="b-cl"\]\{flex-direction:row!important/);
|
||||
expect(editorStacksOnMobile(state)).toBe(false);
|
||||
});
|
||||
|
||||
test('desktop row, no override -> stacked in both', () => {
|
||||
const state = colsState({ style: { flexDirection: 'row' } });
|
||||
expect(publishedBaseStacks(state)).toBe(true);
|
||||
expect(editorStacksOnMobile(state)).toBe(true);
|
||||
});
|
||||
|
||||
test('desktop row + mobile row override -> stacked in both (global rule wins published)', () => {
|
||||
const state = colsState({ style: { flexDirection: 'row' }, styleMobile: { flexDirection: 'row' } });
|
||||
expect(publishedBaseStacks(state)).toBe(true);
|
||||
expect(editorStacksOnMobile(state)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Columns stack on phones BY DEFAULT (no flex-direction in the props)', () => {
|
||||
test('published: wrapper carries the cols_ class the global head rule targets; mobile row override is the opt-out', () => {
|
||||
const html = exportBodyHtml(colsState({ style: {} })).html;
|
||||
expect(html).toMatch(/<div class="cols_[a-z0-9]+" id="cl"/);
|
||||
expect(RESPONSIVE_CSS_MINIFIED).toContain('[class^="cols_"]{flex-direction:column!important;align-items:stretch!important}');
|
||||
const optOut = exportBodyHtml(colsState({ styleMobile: { flexDirection: 'row' } })).html;
|
||||
expect(optOut).toMatch(/@media \(max-width:767px\)\{\[data-wsb-r="b-cl"\]\{flex-direction:row!important/);
|
||||
});
|
||||
test('editor mobile frame stacks default Columns, and a mobile row override un-stacks them', () => {
|
||||
const stacksDefault = () => {
|
||||
h = renderEditorHarness({
|
||||
initialState: colsState({ style: {} }),
|
||||
onRender: RenderNode,
|
||||
wrap: (tree) => <DeviceProvider initialDevice="mobile"><div className="canvas-device-frame" data-device="mobile">{tree}</div></DeviceProvider>,
|
||||
});
|
||||
const el = h.container.querySelector('#cl') as HTMLElement;
|
||||
return el.matches(editorMobileStackSelectors());
|
||||
};
|
||||
expect(stacksDefault()).toBe(true);
|
||||
h?.unmount(); h = null;
|
||||
expect(editorStacksOnMobile(colsState({ styleMobile: { flexDirection: 'row' } }))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,7 @@ const splitToWidths: Record<string, string[]> = {
|
||||
'16-16-16-16-16-16': ['16.666%', '16.666%', '16.666%', '16.666%', '16.666%', '16.666%'],
|
||||
};
|
||||
|
||||
function getWidths(split: SplitOption, columns: number): string[] {
|
||||
export function getWidths(split: SplitOption, columns: number): string[] {
|
||||
// Check predefined splits first
|
||||
if (split !== 'equal') {
|
||||
const defined = splitToWidths[split];
|
||||
@@ -75,6 +75,7 @@ export const ColumnLayout: UserComponent<ColumnLayoutProps> = ({
|
||||
<div
|
||||
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
|
||||
id={anchorId || undefined}
|
||||
data-wsb-cols=""
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
|
||||
Loaded 100 of 505 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user