Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Opus 5.5 11cd967c90 fix(editor): generated columns/cards can be deleted; a refused delete says why
Sitesmith layouts put their cards/columns as Container children of a
ColumnLayout, which the flattener turns into Craft LINKED nodes (col-N).
Craft never deletes a linked node (isDeletable() is false), and
findDeletableTarget returned null for a populated column, so the context
menu, Delete/Backspace, command palette and mobile toolbar all silently did
nothing -- 100% of generated column containers in both captured Sitesmith
responses were undeletable.

- planDelete/runDelete (craft-helpers): one rule set for every delete route.
  A column of a Columns layout is removed by rebuilding the layout (minus the
  column subtree, slots renumbered col-0.., columns decremented, split
  rescaled) in one undo step; the rebuilt layout gets a new id so Craft's
  <Element> remounts. Last column -> the layout goes (as before).
- A Section/BackgroundSection/Form content area is still protected but now
  shows a notice explaining why with a "Delete <Section>" action; ROOT stays
  protected. No delete is a silent no-op any more.
- Sitesmith patch delete_node uses the same path (a card delete no longer
  fails with only a console warning).
- Tests: src/utils/sitesmith-delete.test.ts (real Craft editor + the two
  captured Sitesmith responses), updated core-commands test, and a
  real-browser check: npm run test:browser:sitesmith-delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXjXyosSkunDsdWz3mb
2026-11-08 06:54:00 -08:00
shadowdaoandClaude Opus 5.5 8ff0e01c45 preview: inline uploaded assets as data: URLs so they render in the sandboxed Preview
Preview (and version-history Preview) renders the page in an
<iframe sandbox srcdoc> without allow-same-origin, i.e. an opaque origin.
Every site-builder asset response carries Cross-Origin-Resource-Policy:
same-site (whp libs/SiteBuilderAssetServe.php), so each upload requested
from that frame is cross-site and blocked (ERR_BLOCKED_BY_RESPONSE.NotSameSite,
naturalWidth 0). The canvas was fine; Preview images were broken for everyone.

CORP and the sandbox stay as they are. Before the HTML is handed to the
sandboxed frame, the editor (panel origin, same-origin to the proxy) fetches
this site's proxy assets and swaps each URL for a data: URL in the HTML text
(utils/preview-assets.ts): img src/srcset, poster, video src, <link> icon,
inline-style and <style> url(), &quot;/&amp; forms, both proxy URL forms.
<a href>, <meta content>, other sites, other origins are left alone. Per-asset
(8 MiB), total (40 MiB), count (200) and timeout (15 s) caps; any per-asset
failure keeps the original URL. Save/Publish/export are untouched.

blob: was measured and rejected: in Chromium and Firefox a blob: URL made by
the editor window or by the Preview tab does not load inside the null-origin
frame; data: does.

Tests: vitest for the collector/rewriter; new real-browser suite
test:browser:preview-assets (real HTTP stub with the backend's CORP header,
Preview opened by a click through the real openers) reproduces the block with
the old opener and passes with the new one in Chromium and Firefox, measures
blob vs data, and checks the real backend publish holds only assets/<file>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 20:29:36 -08:00
shadowdaoandClaude Sonnet 5.5 c6809293c4 sitesmith: show uploaded images in the editor canvas and Preview
Sitesmith writes uploads as assets/<file>, which the editor (panel origin) cannot load.
After the repair + allow-list cleaner, apply now converts every real-upload reference to the
same panel proxy URL the AssetPicker stores (publish rewrites it back to assets/<file>);
canvas summaries sent to the model show assets/<file> again. Covers apply, self-review
patches and regenerate-section. Adds unit, Craft integration and a Chromium+Firefox
browser suite (test:browser:sitesmith-editor-assets) incl. the real PHP publish rewrite.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 17:43:06 -08:00
shadowdaoandClaude Sonnet 5.5 bf12520d01 docs: round 9 image-use findings update and Pixabay design hook
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 14:18:13 -08:00
shadowdaoandClaude Sonnet 5.5 03569c5120 sitesmith: verify uploaded-image references, enforce home hero photo, rotate heroes, low-res guard
New sitesmith/asset-repair.ts, run by apply() before the allow-list cleaner when the editor passes the
site's fresh upload list: unknown assets/ (and assets-proxy) references are swapped for the nearest real
upload or a labelled placeholder; the home hero takes the best landscape upload when it has a placeholder
or no image; a whole-site build does not repeat a hero photo; a photo under 1200px wide is never kept as a
full-bleed hero background. Notes appear in the modal note area.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 14:17:52 -08:00
shadowdaoandClaude Sonnet 5.5 a20e728824 stock photos: short Pixabay licence reminder in the Stock tab
One line (no standalone resale; recognisable people / trademark limits) with a
link to the Pixabay licence summary, shown with the "Images by Pixabay" credit
in every Stock tab state. Craft unit test added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 10:37:33 -08:00
shadowdaoandClaude Sonnet 5.5 8a503c4267 stock photos: Pixabay with the user's own API key (Add-key prompt, attribution)
useStockPhotos gains key status/save/test/remove (key only ever sent in a POST
body; the backend returns configured + last4). The Stock tab shows an Add your
Pixabay key prompt when no key is saved or Pixabay rejects it, a masked
change/remove row, 'Images by Pixabay' attribution link, contributor and
photo-page links. Provider is pixabay; Pexels references removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 10:15:04 -08:00
shadowdaoandClaude Sonnet 5.5 da860e2dae sitesmith cleaner: drop images.pexels.com from the AI image host allow-list
Stock photos are imported into the site's assets, never hotlinked, so the
only external image host model output may use is placehold.co.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 10:15:04 -08:00
shadowdaoandClaude Sonnet 5.5 94bbfd3ec9 docs: r8 image-use findings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 07:49:39 -08:00
shadowdaoandClaude Sonnet 5.5 93f0a72f2a sitesmith: label-free background placeholders get a contrast-safe box colour and an editor-only 'Add a photo here' hint
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 07:48:36 -08:00
shadowdaoandClaude Sonnet 5.5 6604ff4674 fix(sitesmith): partial-build CTA bands get a mailto link or a visible note; review fix ops map hex to design tokens
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-02 07:31:07 -08:00
shadowdaoandClaude Opus 5.5 4177e5015a fix(sitesmith): summarize nested (linkedNodes) nodes, explain dropped review ops, truly label-free bg placeholders
1. summarizeCanvas() walked only node.nodes, so everything inside Section/ColumnLayout/forms
   (linkedNodes) was missing and live self-reviews could only name top-level sections. It now
   walks nodes + linked slots (stable key order) and lists id, type and key props (text first,
   links, main style values as style.<key>, colour-like props) as key="value", within a
   documented budget (150 nodes, 6000 chars, 300 chars of props per line; detail is dropped
   before nodes; cuts happen at line boundaries -- a mid-line cut used to make the server
   refuse the whole review). HtmlBlock code is no longer summarised.
   applyPatch no longer counts an op with nothing left to set as a change; ops that did nothing
   are counted per reason. The self-review note and console say why ops were dropped (server
   and editor reasons, counts only). Real-browser test 8n builds a nested page, sends the real
   summary through the real WHP review lockdown (php) and checks the nested edit takes effect
   while link/text edits, unknown ids and deletes are dropped.
3. Background placeholders use ?text=%E2%80%8B (measured: placehold.co then draws no glyphs;
   the same-colour label left a 4-colour ghost in its PNG); the capture draws no <text> for a
   zero-width or same-colour label. Pixel test on the case-4 hero markup in both browsers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgk6UunFCKyXqLe2Cq
2026-11-01 20:40:09 -08:00
shadowdaoandClaude Opus 5.5 615a20e25b fix(sitesmith): footer page menus follow "Add these pages"; round 5 statuses; dialog wording
Live run of 2026.11.9:
- After "Add these pages" the footer's Explore menu listed only Home although the dialog said
  the header and footer link to every page. addPagesResponse() now also repairs the footer's
  PAGE menus (repairFooterLinks: a Navbar/Menu that already links a page of the site gets
  followPages + every shown page); a legal/social footer menu is left alone.
- Dialog: "keeps your other 1 page" -> "keeps your other page (name)" / "keeps your other N
  pages (names)"; "with menus that link to every page you will have".
- New server statuses PROVIDER_BUDGET, PROVIDER_AUTH (the provider refused this server's
  key) and SITE_OVER_LIMIT (whole-site pre-flight) with specific messages; the server text
  is preferred (fixed wording + derived reason).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 19:09:27 -08:00
shadowdaoandClaude Opus 5.5 52b453eecc fix(sitesmith): honest self-review wording when changes were dropped or not applied
Live 2026.11.8: the server's review lockdown stripped every op, and the editor said
"made no changes. Sitesmith said: Image band narrowed..." (a fix that never happened). With
the backend's review_ops {proposed, kept}:
- all dropped -> new status "dropped": "Sitesmith proposed N changes, but none passed the
  safety checks, so nothing on your page was changed. What it proposed (not applied): ..."
- some dropped -> the "made fixes" note says how many were dropped and labels the quote as
  possibly describing them;
- not-applied / claimed-no-ops quotes are labelled as not applied instead of "Sitesmith said".
"Sitesmith said" is kept only where the quote describes what actually happened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:33:02 -08:00
shadowdaoandClaude Opus 5.5 274ae9fc33 fix(sitesmith): placehold.co backgrounds lose their label (it covered the hero headline)
Live case 5 (2026.11.8): BackgroundSection.bgImage =
placehold.co/1920x1080/101a2b/fbfaf7?text=Team+collaborating+... printed the label across
the hero headline on the published page and in the review render. The allow-list cleaner now
rewrites a placehold.co URL used as a background (bgImage, backgroundImageUrl, CallToAction
bgValue, ContentSlider slide imageSrc) to https://placehold.co/WxH/BG/BG (no query, text colour
= box colour, so neither the label nor the "W x H" fallback shows). Runs after the host
allow-list; ordinary image placeholders keep their label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:31:12 -08:00
shadowdaoandClaude Opus 5.5 2dcf8b7feb fix(sitesmith): a partial whole-site build never offers a bare destructive "Replace site"
Live case 2 (2026.11.8): the daily limit stopped a site build after page 1, the dialog still
said "Replace your entire site?" and accepting deleted the owner's other page. The server now
reports site_build {planned, built, missing}; when pages are missing the confirm becomes
"Sitesmith built only N of M pages" with:
- "Add these pages" (default focus): each built page replaces the page at the same address,
  new ones are appended, every other page is kept (PageContext mergeAiPages / addAiPages), and
  the new header is repaired to link the kept pages too;
- "Replace site and delete K pages" with the names it deletes (only when K > 0);
- Cancel.
A complete site build keeps "Replace your entire site?" and now names the pages it deletes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:29:56 -08:00
shadowdaoandClaude Opus 5.5 37935abad8 fix(sitesmith): judge ContactForm labels against the form's own card, not the section
The ContactForm component paints its own card (default style.backgroundColor = bg token).
Contrast repair judged labelColor against the section behind it, so white labels on the
white default card (inside a dark section) went unrepaired (eval r3 case 6, ttm-likes).
A ContactForm with no style prop now resolves to the bg token; an explicit style without
a background stays transparent and is still judged against the section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:20:58 -08:00
shadowdaoandClaude Opus 5.5 69568e5979 docs: Sitesmith design spec (was untracked) with the amended per-send call cap for page-by-page site builds
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:31:16 -08:00
shadowdaoandClaude Opus 5.5 04c0b0a08a sitesmith capture: show the whole page as side-by-side strips (max 9000 px)
The capture stopped at 3000 CSS px, so the reviewer never saw the bottom or footer. Now the full page
height H is rendered at its normal width (1280). H <= 3000: one image, as before. Otherwise
N = min(3, ceil(H/3000)) equal-height strips (each <= 3000 px) are laid out side by side, left to
right (strip 1 = page top), with 24 px #808080 gutters, in one JPEG; H > 9000 shows the top 9000 px
(cropped). Geometry is the pure stripGeometry() (unit-tested); JPEG quality steps 0.8 -> 0.5 before
"too large" (3 MB cap, server limit 8 MB). CaptureResult gains strips/pageHeight; runSelfReview
returns them and says when only the top of a long page was reviewed. Real eval pages: 2 strips,
~0.8-1.1 s, 150-270 KB in Chromium and Firefox; e2e checks strip order/alignment/gutters/cropping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:27:56 -08:00
shadowdaoandClaude Opus 5.5 41d0721028 sitesmith capture: draw placehold.co images locally as labelled boxes
The capture never fetches external images, so placehold.co placeholders came out as a blank grey box
(Chromium) or alt text (Firefox) and the reviewer reported a false "screenshot mismatch". checkUrl now
maps a strictly parsed placehold.co URL (https, host exactly placehold.co, /WxH with 1-4 digits, up to
two 3/6-digit hex colours, optional image extension) to a locally generated SVG data URL of the same
intrinsic size: URL bg colour (default #cccccc), ?text= label (default "W x H") in the fg colour
(default #969696), XML-escaped. Off-spec placehold.co URLs become a plain #cccccc box (no label), or
the old 1x1 grey image when the size is unknown. Works for <img> (own CSS: width, aspect-ratio,
object-fit) and CSS url() backgrounds. Only an SVG byte-identical to our generator passes the
second sanitiser pass. makePolicy/allow-list, sandbox and CSP unchanged; fetchBounded refuses
placehold.co outright. e2e: fidelity samples the boxes/labels, security asserts zero placehold.co
requests (incl. hostile ?text=) in Chromium and Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:24:06 -08:00
shadowdaoandClaude Opus 5.5 9781e02043 sitesmith: report-only check that the primary CTA uses the accent colour; modal wiring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:21:14 -08:00
shadowdaoandClaude Opus 5.5 65d388ff89 sitesmith: a replacing header keeps links to existing pages; accurate chrome dialog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:21:14 -08:00
shadowdaoandClaude Opus 5.5 201486f357 sitesmith: site_pages in requests, per-page build phases, 10 minute cap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:21:14 -08:00
shadowdaoandClaude Opus 5.5 28119f0666 sitesmith capture: keep a var() border shorthand that a border-top overrides
`border:1px solid var(--x); border-top:4px solid ...` (the AI's accent-top card) lost its left/right/
bottom sides in the self-review capture in Chromium AND Firefox: once a later declaration overrides
one longhand, the CSSOM can no longer serialise the var() shorthand (it and its remaining longhands
read back as ""), so the 4c1c8db recovery had nothing to emit. Recover such shorthands from the
declaration block's source text (inline value; innermost blocks of a sheet, matched to rules by
cssText), re-parse each ALONE through the CSSOM and judge it with the unchanged value/URL gate.
e2e-capture-fidelity gains the card (var/var, var/literal, stylesheet) sampled on all four sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:19:07 -08:00
shadowdaoandClaude Opus 5.5 6e48cb82b7 sitesmith: form text repairs pick neutrals; note when uploads were not used
- contrast repair: ContactForm labelColor / inputTextColor are repaired to a
  neutral (text/bg/muted token, black, white), never the accent. Measured on
  the ttm-likes eval response in Chromium: before, dark typed text, UA-grey
  placeholders and an invalid border on the dark inputs; after, white text,
  placeholders at 70% of it, visible border.
- a page/site build that shows none of the owner's offered uploads gets an
  honest note (the brief now requires one in the hero or a feature).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:43:01 -08:00
shadowdaoandClaude Opus 5.5 ed50732d58 sitesmith: readable form inputs on dark sections + sRGB color-mix() in contrast repair
Eval 2026-11-01 (ttm-likes): a ContactForm on a dark band had dark typed text
and UA-grey placeholders on a color-mix() input surface, and its inputBorder
"1px solid X" came out as the invalid "1px solid 1px solid X".

- ContactForm: new inputTextColor prop (typed text); placeholders now follow
  the input's own text colour via a scoped form[data-wsb-form] ::placeholder
  rule (export + editor canvas); an inputBorder that is a whole border is used
  as-is. Without inputTextColor the legacy derivation is unchanged.
- contrast repair: resolves opaque color-mix(in srgb, A p%, B) surfaces (the
  brief prescribes these tints; translucent / other spaces stay unchecked),
  checks ContactForm labelColor against its section and the derived input text
  colour against an explicitly set inputBg, writing inputTextColor on failure.
- catalog generator: (rebased onto main 01a78c9, which already omits the
  clock-derived Countdown.targetDate default via VOLATILE_DEFAULTS + the
  date-frozen drift test; this commit's duplicate inline check was dropped.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:43:01 -08:00
shadowdaoandClaude Opus 5.5 0c9faf0495 sitesmith: AI-built pages render full-bleed (page root padding 0)
The page root Container's default 20px padding framed every AI-built section
in a white margin (visible in every eval screenshot). New AI page/site
replaces now set padding 0 on the page root unless the model set padding
itself. Saved pages, section inserts, patches and the Container default are
unchanged, so existing sites do not move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:42:49 -08:00
shadowdaoandClaude Opus 5.5 0fe7f07162 sitesmith: a page request replaces the page, never the whole site
Eval 2026-11-01: "Build my home page following the layout of the attached
mockup" came back as scope "site", and confirming replaced every page. The
editor now decides from what the owner asked (sitesmith/replace-plan.ts):

- scope "site" is honoured (with the existing confirm) only for an explicit
  whole-site request ("build me a website", "the whole site", "every page",
  "a 4 page site"); otherwise the first page replaces the current page and a
  note says so.
- the shared header/footer are replaced with a page only when they are still
  the untouched starter ones ("MySite" + "Get Started") AND the owner says yes
  in a new dialog mode ("Use the new header and footer" / "Keep my header and
  footer"); customised chrome is always kept, with a note.
- the editor sends chrome_default:true so the backend can let the model
  restyle the starter chrome on a page request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:42:49 -08:00
shadowdaoandClaude Opus 5.5 648d6a3a51 sitesmith self-review: never present a claimed fix that sent no ops
An empty patch whose message claims a change ("Fixed the hero ...") is now
status 'claimed-no-ops' with a warning note: "Sitesmith's reply describes a fix,
but it sent no changes, so nothing on your page was changed." The structured
render_mismatch flag from newer backends is read first; the existing wording
check still covers older replies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:42:49 -08:00
shadowdaoandClaude Opus 5.5 4c1c8db97e sitesmith self-review: keep var() shorthands (background/border) in the capture
Measured in Chromium and Firefox: the CSSOM exposes `background: var(--x)` and
`border: 1px solid var(--x)` only as pending-substitution longhands whose values
read back as "", so the capture sanitiser (which re-serialises the parsed
declarations) dropped them. The self-review screenshot then showed dark heroes,
image placeholders and card borders as white, and the model "fixed" things that
were fine on the real page.

The sanitiser now emits the declared shorthand once, at its first longhand,
through the same value/URL gate as every other declaration. Sandbox, CSP and
the single URL allow-list are unchanged.

- scripts/e2e-capture-fidelity.mjs: real-browser test through the whole capture
  path (sanitise -> inline -> sandboxed frame -> html-to-image), decodes the
  JPEG and samples pixels. Failed 9/12 checks per browser before, passes after.
- e2e-capture-security: hostile var() shorthand / var() fallback url() probes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:42:49 -08:00
shadowdaoandClaude Sonnet 5.5 01a78c9b3d catalog: omit the wall-clock-derived Countdown.targetDate default so the generated catalog (and drift test) no longer flip daily
Add a date-independence test (freezes Date at two different days via a preload).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 16:28:48 -08:00
shadowdaoandClaude Opus 5.5 96670b94f8 Legacy grids: published head stacks pre-hook card grids on phones (no re-save)
Stored pages (generated at editor-save time) from before release 2026.11.5 carry
FeaturesGrid / Testimonials / NumberCounter grids without data-wsb-grid, so a
republish kept repeat(N,1fr) on phones (OLS home: body 594px wide at 360).
The <=767px block now matches the exact inline styles those emitters stored
(whole-attribute signatures; no spaces, as in git history and every stored
OLS/TTM page). Gallery shares the prefix with a free gap and keeps its columns:
the two colliding signatures carry :not(:has(> * > Gallery thumbnail)) in their
own rule (a browser without :has drops only that rule). Customer grids never
match. Mirrored byte-for-byte by WHP generateCompiledHTML (fix/legacy-grid-backend).

Tests: vitest selector contract (legacy shapes match, == current emitters minus
the hook, Gallery and customer grids never match, pretty == minified); head
parity pins updated; new real-browser suite test:browser:legacy-grid (Chromium +
Firefox, 360/390/768/1280) on the stored OLS home page + synthetic legacy grids;
colors suite folds the new rules back like the mobile-guard ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:26:11 -08:00
shadowdaoandClaude Opus 5.5 322742aa81 e2e-sitesmith: follow the honest Clear chat confirm label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:38:54 -08:00
shadowdaoandClaude Opus 5.5 96274a6aa8 fix(sitesmith): contrast repair resolves the real background (gradients, shorthand, section props)
Contrast auto-repair read only style.backgroundColor / bgColor, so white text on a
gradient hero (style.background) was "repaired" against the white page colour.

- Resolve style.background (solid shorthand, gradient, url), HeroSimple bgGradient*/
  bgColor defaults, CallToAction bgValue, BackgroundSection bgColor, opaque image overlay.
- Gradients: every stop is checked, worst stop decides; unparseable stops (color-mix,
  unresolved token, translucent, layered) = not checked. An unresolvable background no
  longer falls through to an outer/page colour.
- A repair is applied only if it reaches the target and strictly beats the old colour
  against the worst stop.
- clamp() font sizes use their minimum for the large-text test.
- Patch path: ancestor background now comes from effectiveBackgroundOf (which learns
  style.background shorthand and section props) instead of a private walker.
- Tests: real ttm-likes and ols-home responses as fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:31:34 -08:00
shadowdaoandClaude Opus 5.5 c71a6b64a6 Fix ImageBlock (any non-Container) directly inside ColumnLayout exporting an empty div
Craft's <Element id=col-N is={Container}> only adopts an existing linkedNode whose
type is Container; otherwise it creates a fresh empty Container and orphans ours.
flattenTreeForCraft now wraps a non-Container column child in a pre-created Container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:31:34 -08:00
shadowdaoandClaude Opus 5.5 2b82424d7f Sitesmith: self-review sees the page it just built, reports honestly; per-message pictures
A. A page/site replace lands on the canvas in loadState's deferred
   deserialize, so apply() returned before the canvas changed and the
   self-review composed, captured and summarised the PREVIOUS page (the live
   eval: every review said "the render doesn't match the page I built").
   PageContext.whenCanvasSettled() resolves when the requested load really
   ran; apply() awaits it (bounded, 5 s) and returns the applied fingerprint
   (from the response tree for replaces). The review checks the live canvas
   against it right before composing and skips with a plain note otherwise.
   Header/footer/title come from latestChrome() (refs updated in the same
   tick), not the modal's one-render-old context.
B. Review outcomes are fixed / fine / mismatch / not-applied / skipped and
   quote the model. An empty patch where the model says the render was not
   its page is "did not work this time", never "found nothing to fix"; an
   ask is not a review; ops naming missing nodes are "none could be
   applied" (applyPatch now counts ops that took effect).
E. Pictures from earlier sessions are labelled "saved earlier" and never
   preselected; a line above the box lists what goes with THIS message;
   multi-file uploads select every file. Clear chat says it deletes the
   site's whole conversation for everyone (one thread per site, backend).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:31:34 -08:00
shadowdaoandClaude Opus 5.5 99d5855f6a Sitesmith: RESPONSE_TOO_LONG status gets its own message
The backend now ends a job with RESPONSE_TOO_LONG when the model answer is
cut off at the output cap twice. Without the status in the union it fell
back to the generic ERROR text; now it says nothing was changed and to ask
for one page or section at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:31:34 -08:00
shadowdaoandClaude Opus 5.5 542f5efc78 Mobile guard: drop the HtmlBlock table rule; colour e2e baseline = first 2026.11.4-head commit
- Tables inside HtmlBlocks are left alone on phones: display:block (the only way to make one scroll)
  shrank a fitting width:100% table's rows from 349px to 77px at 390. Wide tables stay clipped as before.
  The <pre> rule (max-width:100%;overflow-x:auto, no display change) and the media rules stay.
- Browser suite: width:100% table still spans the screen (fails on cfeeef3's rule: first row 78px); the
  10-column bare table moved to htmlwide (clipped, page never scrolls sideways).
- e2e-color-system: default COLOR_BASE_COMMIT ab7a100 -> 69fd34b, the first commit with the 2026.11.4
  published head (ColumnLayout stacking + Navbar wrap) and none of the colour feature. ab7a100 predates
  that head, so check 5 failed on main itself. This branch's own head change (mobile guard) is folded back
  by exact string, asserted present once, before comparing, so the check still proves the colour feature
  changed nothing else. Passes on 69fd34b; fails (as it should) against ab7a100.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:16:53 -08:00
shadowdaoandClaude Opus 5.5 cfeeef37ce Mobile guard: HtmlBlock wrapper never gets a box; phone net is media + per-table/pre scroll only
Review of bb4fb75: overflow-x:auto on [data-wsb-html] forced overflow-y:auto (clipped dropdowns/shadows),
broke position:sticky inside customer HTML, and display:block!important merged multi-root blocks that are
direct flex/grid items. Now the wrapper stays display:contents on every viewport and no rule targets it;
at <=767px only its descendants are touched: media max-width:100% (img/video height:auto), and a table or
<pre> becomes its own sideways scroller (not when already inside an inline overflow wrapper). No
overflow-wrap:anywhere (it shrank min-content); body{overflow-wrap:break-word} inherits through the wrapper.
Deliberately wide customer markup (fixed widths, px grids) is clipped as before; the publish warning is
its guard, and its wording now says the excess is cut off. width= attributes are no longer flagged (they
size only media and tables, which the net handles). stripMediaBlocks lowercases once.

Browser suite: htmlblocks probes at every width (wrapper display:contents, sticky sticks, absolutely
positioned dropdown visible on top, multi-root block = separate flex items / grid cells, bare table
scrolls on its own); new htmlwide doc asserts wide blocks stay clipped and the page never scrolls sideways.
All probes fail on bb4fb75's net and pass now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 15:09:22 -08:00
shadowdaoandClaude Opus 5.5 bb4fb7548b Mobile guard: real-browser overflow suite, card-grid + HtmlBlock mobile hooks, wide custom HTML publish warning
- scripts/e2e-mobile-guard.mjs (npm run test:browser:mobile-guard): Chromium + Firefox at 360/390/768/1280 over
  exporter-built pages (navbar, columns, FeaturesGrid/Testimonials/NumberCounter/Gallery/Pricing/Reviews, big
  image, long word/URL, wide customer HtmlBlocks). Asserts body.scrollWidth and every visible box/text right edge
  (html,body{overflow-x:clip} hides overflow from documentElement.scrollWidth), stacking on phones, columns kept
  on tablet, navbar wrap, intentional overflow-x:auto still scrolls, and 1280 box + pixel identity with the hooks
  removed (optional cross-commit baseline).
- OLS home overflow was FeaturesGrid (inline repeat(3,1fr)), not an HtmlBlock. FeaturesGrid, Testimonials and
  NumberCounter grids carry data-wsb-grid; the <=767px head block makes them one column.
- HtmlBlock output is exported inside <div data-wsb-html style="display:contents"> (applied after attr
  injection, toHtml().html unchanged); on phones it becomes a max-width:100% sideways-scrolling box, media
  shrink, long words break. body{overflow-wrap:break-word} on phones. Navbar link wrap now up to 991px
  (8 links + long logo overflowed at 768).
- Head parity pins updated (mirror in WHP generateCompiledHTML); editor.css mirrors for the mobile frame.
- publish-checks: warn when an HtmlBlock's inline/<style> CSS sets widths, flex sizes or grids over 390px or a
  3+ column grid with no phone @media rule; says what is not checked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:58:39 -08:00
shadowdaoandClaude Opus 5.5 9f9be5f41a Sitesmith modal: Clear chat explains a refusal and is disabled while a job runs
Reproduced in the e2e mock (now stateful: history + clear_history with the
server's 409 while a job is live): the normal two-step clear works (first
click arms the confirm by design), but a confirm while a job is live -- e.g.
the self-review follow-up that starts right after a send -- was refused by the
server and the modal showed the raw code 'job_in_progress', so the chat looked
like it would not clear on the first try. Now the server's sentence is shown,
and the button is disabled (with a tooltip) while a send, resume or self-review
is running. e2e scenarios 9, 9b (failed before), 9c (Firefox + Chromium).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:16:59 -08:00
shadowdaoandClaude Opus 5.5 465cf17bb0 Sitesmith: self-review render via review_render_upload; one-line-per-node summaries; real-browser check of cleaned output
- The render is uploaded with the new review_render_upload action (backend kind
  review_render, the only image a review job accepts); mocks follow.
- summarizeCanvas() never lets a newline or a quote into a node line (the server
  validates review summaries line by line); test.
- test:browser:sitesmith-cleaned (Firefox + Chromium): a page published from a
  cleaned ordinary Sitesmith response requests nothing outside the allow-listed
  hosts (own assets, fonts, Font Awesome CDN, images.pexels.com, placehold.co)
  and has no inline handlers or javascript:/data: URL attributes; the same
  response uncleaned is the control (requests example.com). All requests are
  answered or aborted locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:47:04 -08:00
shadowdaoandClaude Opus 5.5 4a34781ab6 Sitesmith cleaner: patches use the target component's rules; CSS values checked against a positive grammar
Review findings on clean-ai-response.ts:
1. update_props is now cleaned with the TARGET node's component (resolved on the
   live canvas by apply()); an unresolvable target gets the strictest rules
   (no code, url/src only assets/). code is kept only on an HtmlBlock.
2. cssValueAllowed() is a positive grammar: numbers/lengths/hex/keywords, an
   allow-list of functions (gradients, colour functions, calc/clamp, var(--*),
   transforms, filters), url() only of assets/<file>, quoted strings only plain
   font names; image-set(, src(, cross-fade(, element(, paint(, attr(, env(,
   ':' or '//' outside url(assets/..), backslashes and control chars rejected.
   Regression: every style/colour value in the templates, section families and
   palettes passes (clean-ai-response.ordinary.test.ts).
Also: tricky link forms (//host, backslashes, whitespace/control chars,
mixed-case schemes, > 2048) rejected; comments state the server-side mirror is
not implemented (deferred).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:38:14 -08:00
shadowdaoandClaude Opus 5.5 2b8b0557b2 Sitesmith: allow-list cleaner for model responses before they reach the canvas; export strips attack-only CSS (G8)
clean-ai-response.ts runs first in useApplyAiResponse().apply() and in
applyRegeneratedSection(): link props allow ''|#anchor|relative|mailto:|tel:|
https:|http: (never //host, backslash, whitespace/control chars, > 2048);
images only assets/<file> or https on images.pexels.com / placehold.co;
videos assets/ or YouTube/Vimeo; the model can never set form destinations,
relay settings or head code (patches keep the user's values); style names
must be CSS identifiers and values may not carry url() (except assets/),
@import, expression(, behavior, -moz-binding, javascript:, < > { } ; \;
anchor ids [A-Za-z0-9_-]. HtmlBlock code keeps its existing sanitisers.
Export boundary: stripLegacyCssVectors() in cssValue/cssPropsToString
(byte-identical for ordinary content: OLS fixture + default design measured).
Server-side mirror not implemented (deferred).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:31:42 -08:00
shadowdaoandClaude Opus 5.5 93b3cc35af Colour e2e: baseline commit overridable (COLOR_BASE_COMMIT)
On the release branch mobile-parity's <=767px head rules land before the
colour merge, so 'identical to ab7a100' cannot hold; run with
COLOR_BASE_COMMIT=<commit before the colour merge> there. Measured: vs ab7a100
the only difference is those two documented rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:23:17 -08:00
shadowdaoandClaude Opus 5.5 a113f25a62 Guard test: the capture-frame exception now fails on allow-scripts, a skipped or ignored sanitiser, or src= (G7)
captureFileViolations() pins the one allow-same-origin srcdoc frame: sandbox set
once to exactly allow-same-origin, no script/form/popup/navigation tokens,
srcdoc only from inlineResources(clean.html), sanitizeCaptureHtml called and its
verdict checked before srcdoc. Eight mutated copies of the real source prove
each rule fails. Plus a behavioural jsdom test of the real captureHtml frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:10:30 -08:00
shadowdaoandClaude Opus 5.5 6c406ca99b Sitesmith: self-review is intent 'review' (not a mockup); typed statuses with specific messages (G3, G6)
- The self-review follow-up sends intent:'review' + review_image_ids instead of
  putting the render in mockup_ids, so the backend builds a critique+patch
  instruction instead of 'build toward this mockup'. Render still deleted after.
- types/sitesmith.ts: SitesmithStatus = server statuses (adds IMAGES_BUSY,
  TOO_MANY_JOBS, SERVER_BUSY, ...) + client statuses (TIMEOUT, ABORTED, ...);
  network status strings are narrowed with a type guard (unknown -> ERROR);
  the hook builds SendResultErr without casts.
- statusMessages.ts: one specific message per status (a Record over the union,
  so a new status without a message fails tsc), used by the modal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:10:30 -08:00
shadowdaoandClaude Opus 5.5 7a58921ba3 Sitesmith design payload: brand colours carry their published slot (G1)
buildDesignPayload numbered brand colours by list position while the page
publishes them as --wsb-brand-<slot>, so the prompt could name a different
colour than the page renders. It now uses publishedBrandSwatches (same rule as
the publisher) and sends {name?, hex, slot}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 11:10:30 -08:00
shadowdaoandClaude Opus 5.5 3413c7816d Head parity: re-pin E_brand_swatches after the mobile-parity merge
The colour branch pinned the brand head before the <=767px stacking/nav-wrap
rules existed; the bytes are now copied from the merged WHP
generateCompiledHTML output (WHP release/sitesmith-colors).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:56:02 -08:00
shadowdaoandClaude Opus 5.5 9f48b8b134 Merge feat/sitesmith-catalog into release/sitesmith-colors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:55:05 -08:00
shadowdaoandClaude Opus 5.5 ae092990ca Merge feat/sitesmith-ui into release/sitesmith-colors
Conflict: craft/package.json scripts (kept mobile, colour and sitesmith e2e entries).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:55:05 -08:00
shadowdaoandClaude Opus 5.5 57734fbe51 Merge feat/sitesmith-hook into release/sitesmith-colors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:54:46 -08:00
shadowdaoandClaude Opus 5.5 6decf8cdb0 Merge feat/color-system into release/sitesmith-colors
Conflicts: package.json (kept both test:browser:mobile and the colour scripts);
head-parity test (kept E_icons from mobile-parity/main AND the E_brand_swatches /
F_swatches_no_brand cases from color-system; pinned bytes re-derived later
against the merged WHP script).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 10:54:46 -08:00
shadowdao f6b90d393f Merge fix/mobile-parity into release/sitesmith-colors 2026-11-01 10:54:16 -08:00
shadowdaoandClaude Sonnet 5.5 cfa8ab2e40 Sitesmith modal: load assets once; clearer oversize-image message
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:52:56 -08:00
shadowdaoandClaude Sonnet 5.5 304850fcd3 Sitesmith e2e: Firefox + Chromium end-to-end test of the modal (npm run test:browser:sitesmith)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:48:12 -08:00
shadowdaoandClaude Sonnet 5.5 a406daae1e Sitesmith e2e: reusable mock editor + Sitesmith backend server for real-browser tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:48:12 -08:00
shadowdaoandClaude Sonnet 5.5 8a481a87d8 Sitesmith modal: flow tests (phases, cancel, resume, errors, vision off, sites/assets payload, self-review round trip)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:43:23 -08:00
shadowdaoandClaude Sonnet 5.5 784d85346e Sitesmith: tests for payload, design, attachments, panels, self-review runner
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:40:55 -08:00
shadowdaoandClaude Sonnet 5.5 79159dcb28 Sitesmith modal: live job status, cancel, resume, attachments, Sites I like, asset awareness, self-review toggle, design in the request
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:39:47 -08:00
shadowdaoandClaude Sonnet 5.5 f0b3dd1dba Sitesmith capture: CSS judged via CSSOM (no regex), single URL gate (no % / dot segments / backslash), all resources inlined through a bounded no-credentials fetch, CSP img-src data: only; bypass-class proof tests (unit + Firefox/Chromium)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:37:56 -08:00
shadowdaoandClaude Sonnet 5.5 c4f45541a3 Sitesmith: contrast repair wired into apply-ai-response; scoped guard exception for the script-less capture frame
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:32:50 -08:00
shadowdaoandClaude Sonnet 5.5 197b9c46ab Sitesmith self-review capture: sanitise page HTML before it reaches the frame (inert DOMParser allow-list, fixed-point guard), CSP + script-less sandbox, real-browser hostile-page proof; UI building blocks (attachments, sites I like, asset awareness, design payload)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:31:29 -08:00
shadowdaoandClaude Sonnet 5.5 0fde4dc22f Sitesmith: contrast auto-repair for model responses; capture module (html-to-image) for self-review
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:23:26 -08:00
shadowdaoandClaude Sonnet 5.5 7627be78dc SwatchManager chooser: readable text colour and a visible chip border on dark colours
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:12:58 -08:00
shadowdaoandClaude Sonnet 5.5 75bd5921da Real-editor colour-system e2e (Firefox + Chromium): hex entry, pick from page/image, palette, persistence, brand recolour canvas==frontend==backend, caps, contrast
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:12:38 -08:00
shadowdaoandClaude Sonnet 5.5 c4b6802cab Add real-browser mobile parity test (Firefox + Chromium, 390/1280)
npm run test:browser:mobile; MOBILE_PARITY_RECORD/BASELINE compare desktop boxes against a base-commit snapshot.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:10:15 -08:00
shadowdaoandClaude Sonnet 5.5 2e5492600e Editor: mirror default mobile column stacking (canvas emulation + Stack toggle)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:10:15 -08:00
shadowdaoandClaude Sonnet 5.5 69fd34bd7c Preview/Published head: stack ColumnLayout on phones, wrap Navbar links, emit Font Awesome
- <=767px: [class^=cols_] wrappers (every ColumnLayout split) stack; a mobile flexDirection:row override still opts out.
- <=767px: navbars without a hamburger wrap instead of overflowing.
- wrapInDocument emits the same Font Awesome links as the backend sb_font_awesome_link (Preview is a sandboxed srcdoc iframe).
- head-parity pins updated (+ E_icons case).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:10:15 -08:00
shadowdaoandClaude Sonnet 5.5 79cdd593d9 Navbar: showMobileMenu defaults to true for new Navbars and the seeded header
Existing Navbars (prop absent/false) are untouched: render default and toHtml stay falsy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:10:15 -08:00
shadowdaoandClaude Sonnet 5.5 501f276746 Colour pick mode: header/footer zone previews (pointer-events:none) are now pickable
Found by the real-editor e2e: picking over the header or its logo box returned the page colour behind it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:09:39 -08:00
shadowdaoandClaude Sonnet 5.5 ba5611c3e3 Inline contrast in Text, Button, Pricing and Nav/Footer panels (effective background from node parents)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:02:57 -08:00
shadowdaoandClaude Sonnet 5.5 dcf9c92fee Site Design panel: Saved colours section + inline contrast on text/muted/link/primary-button
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:01:21 -08:00
shadowdaoandClaude Sonnet 5.5 d83919b89a feat(sitesmith): renderer for Sitesmith responses (repo exporter + Firefox shots); catalog tips for ColumnLayout stacking, Navbar, Footer
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:01:04 -08:00
shadowdaoandClaude Sonnet 5.5 faaa8a87a0 Site Design: SwatchManager (saved colours, brand toggle, guarded delete/un-brand, use-as-site-colour, pick + palette)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 10:00:51 -08:00
shadowdaoandClaude Sonnet 5.5 c34690d08b Colour fields: hex validation, brand chips, pick tools, save colour, inline contrast prop; gradient parse accepts brand refs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:58:55 -08:00
shadowdaoandClaude Sonnet 5.5 150c84065b TokenSwatchRow: saved colours after the site tokens (brand = live ring + token ref)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:57:17 -08:00
shadowdaoandClaude Sonnet 5.5 9c61f41079 Site colours: replaceBrandRef + PageContext siteStateStrings/rewriteSiteStates for brand-ref rewriting
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:56:55 -08:00
shadowdaoandClaude Sonnet 5.5 2f5c311118 Sitesmith hook: start+poll transport, failure-safe results, refs/assets wrappers
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:54:55 -08:00
shadowdaoandClaude Sonnet 5.5 179aaebe49 Colour picking: native EyeDropper + in-canvas pick mode with brand/token matching, real-browser e2e
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:54:33 -08:00
shadowdaoandClaude Sonnet 5.5 54920dff08 Site colours: pick-from-image and palette-from-image modals
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:53:13 -08:00
shadowdaoandClaude Sonnet 5.5 e4ba07b47e ContrastNote: inline low-contrast hint with suggestion
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:53:05 -08:00
shadowdaoandClaude Sonnet 5.5 de240eee75 feat(sitesmith): catalog generator from real component/section/template definitions + drift test
craft/scripts/gen-sitesmith-catalog.mjs emits a compact JSON catalog (props with
TS types/enums/defaults, token-aware colour props, animation + icon support,
child rules, section recipes, templates, palettes) for the WHP panel prompt.
src/sitesmith/catalog.drift.test.ts regenerates and compares to the committed
whp file so drift fails.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:52:49 -08:00
shadowdaoandClaude Sonnet 5.5 453268a31c Publish checks: button + site-level contrast via checkContrast, unchecked info line
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:52:44 -08:00
shadowdaoandClaude Sonnet 5.5 fb9ac0e6c4 Site colours: real-browser check for image sampling + palette (Firefox + Chromium)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:52:40 -08:00
shadowdaoandClaude Sonnet 5.5 39e954bd77 Contrast: pure WCAG checkContrast/suggestFix/siteColorPairs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:51:57 -08:00
shadowdaoandClaude Sonnet 5.5 e09a87d2a6 Site colours: palette extraction + same-origin image sampling utils
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:51:47 -08:00
shadowdaoandClaude Sonnet 5.5 1190a98265 tokens: isTokenRef accepts brand token names (digits)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:51:32 -08:00
shadowdaoandClaude Sonnet 5.5 c388be7fe7 Head parity: pin brand-colour swatch cases (E, F) from the WHP script
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:50:25 -08:00
shadowdaoandClaude Sonnet 5.5 faecc76384 Site colours: saved swatches + live brand-colour tokens in design model
design.swatches [{id,label,hex,brand,slot}]; brand ones are published as
--wsb-brand-N appended inside :root (canvas and export share buildTokenVarDecls).
Sites without brand colours emit identical bytes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:49:53 -08:00
shadowdao ab7a10073b Merge fix/editor-parity into release/editor-parity (on top of captcha + Font Awesome) 2026-11-01 09:26:21 -08:00
shadowdaoandClaude Sonnet 5.5 ae02eb7d0d test(site-builder): parity harness neutralises documented editor-only differences (empty drop zone, empty-image placeholder)
Container marks the applied drop zone with data-wsb-dropzone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:18:29 -08:00
shadowdaoandClaude Sonnet 5.5 d75f9d90ca fix(site-builder): published Text/Heading keep plain-text newlines as <br> like the canvas
Canvas renders plain text via textToInlineHtml (newline -> <br>); toHtml used escapeHtml,
so line breaks typed in the editor vanished on publish (TTM about page: ~100px shorter).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:16:26 -08:00
shadowdaoandClaude Sonnet 5.5 7d77201e5a fix(site-builder): Container 40px drop-zone min-height only when empty
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:14:28 -08:00
shadowdaoandClaude Sonnet 5.5 01d5ba5496 fix(site-builder): HeroSimple canvas render uses the exporter's declaration order (style wins over minHeight prop)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:13:54 -08:00
shadowdaoandClaude Sonnet 5.5 7a1ab36e63 fix(site-builder): editor canvas drops blank style values like the exporter
React assigns '' for a blank style value and a blank longhand after a shorthand
({padding:'20px', paddingTop:''}) wipes the shorthand in the canvas; the exporter
drops blanks. ResolvedRender is the one place node style reaches React, so
normalise there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:12:35 -08:00
shadowdaoandClaude Sonnet 5.5 64fc21866c test(site-builder): canvas parity harness loads stored state verbatim (no blank-style stripping)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:11:52 -08:00
shadowdaoandClaude Sonnet 5.5 d6bfc51ae3 Merge fix/canvas-reset into fix/editor-parity
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 09:10:23 -08:00
shadowdaoandClaude Sonnet 5.5 dc415db2d3 fix(site-builder): editor canvas renders content with the published base reset
Published pages/Preview ship a head reset (*{margin:0;padding:0}, img block,
a inherit, body line-height 1.6 / #1f2937 / 16px); the editor canvas had none,
so h1-h6/p margins, line-height and inherited size/colour differed.

- editor.css: one commented block scoping the reset to .canvas-device-frame,
  every selector zero-specificity (:where) so inline styles / class rules win
  exactly as when published; editor chrome untouched (snapshot identical).
- tokens.ts: canvas heading/link token rules made zero-specificity too.
- utils/css-reset.ts: single source for the reset declarations (html-export
  imports it; test asserts byte-identity with the backend head and that the
  editor.css block carries the same declarations).
- scripts/e2e-canvas-parity.mjs (npm run test:browser:canvas): real editor vs
  published HTML in Firefox + Chromium, boxes within 1px + computed styles.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 08:23:19 -08:00
shadowdaoandClaude Sonnet 5.5 dbf3dda3e4 fix(site-builder): hero gradient blank on editor canvas - shorthand + undefined longhands
HeroSimple emitted 'background' together with backgroundImage/Size/Position
that were undefined. React assigns '' for those on first render and Chromium
and Firefox then wipe the shorthand's gradient (background-image: none), so
the canvas hero rendered white. Build the style with only the relevant keys
(shared by render and toHtml); exported HTML is byte-identical.

Adds a real-browser (Chromium+Firefox) regression test: npm run test:browser:bg,
and toHtml byte-identity assertions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 07:52:34 -08:00
shadowdaoandClaude Sonnet 5.5 7b3baa815c feat(site-builder): Font Awesome 7.3.1 icons (per-network brands) in editor and exports
Exporters emit fa-solid/fa-brands/fa-regular classes through utils/fa-icon.ts;
SocialLinks gets X/TikTok/Bluesky/Threads/Discord/Mastodon/Reddit/Telegram;
the editor loads all.min.css + v4-shims (SRI) so editor chrome FA4 names work.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgKV8v9BUrQWXSUW4P
2026-10-31 11:59:46 -07:00
shadowdaoandClaude Sonnet 5.5 bb97e5b396 feat(forms): captcha is mandatory on every relay form; remove the toggle
relayFormWiring always emits captcha="1" for relay-wired forms (legacy captcha prop ignored,
old projects with captcha:false load fine). CaptchaMock always shown for relay-wired forms;
FormStylePanel toggle replaced by a read-only note.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgKV8v9BUrQWXSUW4P
2026-10-31 11:29:07 -07:00
shadowdaoandClaude Sonnet 5.5 92da689e62 feat(forms): captcha prop + panel toggle + marker attribute for relay forms
captcha=true emits captcha="1", explicit false emits captcha="0", undefined emits
nothing (legacy designs byte-identical). New forms default true. Editor shows an inert mock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXgKV8v9BUrQWXSUW4P
2026-10-31 08:25:12 -07:00
shadowdaoandClaude Opus 5.5 76f0ba9ca1 fix(site-builder): navbar logo image never shown — no logoType control
The Navbar renders logoImage only when logoType === 'image', but the
Logo/Text toggle lived in the settings UI removed in 65a10a1 (2026-07-12);
NavStylePanel kept the image picker and never gained the toggle. A picked
logo was stored and silently ignored (editor and published site showed the
text fallback "MySite"; seen on olsdigital.com).

- Logo Type Text/Image toggle in the Navbar Logo section
- picking an image sets logoImage + logoType:'image' in one undo step

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 05:50:33 -07:00
shadowdao bdb4789903 Merge fe-after-backend: client_id, warnings, limits, head parity 2026-10-07 13:52:24 -07:00
shadowdaoandClaude Sonnet 5.5 9d425afa29 feat(editor): adopt backend final-fix contract (client_id, warnings, limits, head parity)
client_id per editor load (memory only), already_saved, save warnings via notices,
upload_max_bytes enforced client-side with the server error text on 413,
project_max_bytes warning, headCode in the Preview font scan, pinned backend heads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:49:53 -07:00
shadowdaoandClaude Opus 5.5 eb401cd979 fix(sections): inserting from the section library closes the mobile Blocks sheet
The section library now calls closeSheet() after inserting a section (or a
global section). It mounts in CanvasOverlays, beside EditorShell, so it could
not reach the MobileChromeProvider inside the shell; the provider moves up to
App around the shell and the overlays so both share one sheet state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:22 -07:00
shadowdaoandClaude Opus 5.5 472e5e4d81 fix(selection): Esc clears a multi-selection; context menu acts on all selected
Esc was only claimed by select.parent for a single node, so a multi-selection
could not be dropped from the keyboard. Add select.clear (Esc, >1 selected)
through the existing dispatcher, which already skips text fields and open
dialogs. The context menu's Duplicate/Delete now run the multi-selection core
commands (edit.duplicate / edit.delete) when the clicked node is part of a
multi-selection, instead of acting on the first node only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:22 -07:00
shadowdaoandClaude Opus 5.5 84bc626ed0 fix(sitesmith): first-run wizard only for users who can use Sitesmith
The business-profile wizard was forced on an empty canvas even when
Sitesmith was locked (paid addon), capped or switched off. The decision now
waits for the entitlement and skips the wizard unless the user can chat
(OK_MONTHLY / OK_BONUS); a failed entitlement falls back to the modal.
useSitesmith reports an ok:false entitlement as an error so it cannot hang.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:22 -07:00
shadowdaoandClaude Opus 5.5 92c88496a7 fix(publish-checklist): Fix on SEO checks opens the page's SEO settings
Title-length, missing meta description and noindex-landing checks carry
fix: 'page-settings', but Fix only closed the list. It now shows that page's
PageSettingsModal in place of the checklist; closing it finishes the Fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:22 -07:00
shadowdaoandClaude Opus 5.5 49ed687c3b fix(topbar): mobile overflow menu reaches Version history and the command palette
On mobile the collapsed topbar had no route to Version history, Export ZIP,
Business profile or the command palette. Add a 'Version history' item (only
when the site.history command is registered, run through the registry) and a
'More commands…' item that opens the command palette.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:41:22 -07:00
shadowdaoandClaude Opus 5.5 c62a333257 fix(editor): header/footer zone previews show the active device's overrides
The zone previews render the exported HTML, whose <style data-wsb-responsive>
@media rules evaluate against the browser viewport, so tablet/mobile modes
showed desktop styling for header/footer. ZonePreview now applies the active
device's override rules unconditionally (applyResponsiveCssForDevice) and
drops the rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:40:54 -07:00
shadowdaoandClaude Opus 5.5 e20c604413 fix(editor): mobile column stacking follows the desktop style, as published
Published mobile stacking is the global RESPONSIVE_CSS rule matching the
DESKTOP inline style, so un-stacking Columns on mobile under a stacked tablet
(styleMobile.flexDirection 'row') publishes un-stacked. The editor's
device-emulation copy matched the resolved inline style and showed it stacked.
RenderNode now marks nodes with a flexDirection/display override with
data-wsb-base-stack (baseStacksOnMobile) and editor.css keys off it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:40:54 -07:00
shadowdaoandClaude Opus 5.5 579ea5370c fix(tokens): canvas token CSS falls back to defaults for blank tokens
Export/published :root token CSS replaced a blank/whitespace token with its
default; the editor canvas emitted an empty custom property, invalidating
every var() that read it. Share one buildTokenVarDecls between the canvas
and the export so both apply the same fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:40:54 -07:00
shadowdaoandClaude Opus 5.5 faf129c509 fix(preview): gate head animation CSS/noscript on composed header+body+footer
Preview (TopBar handlePreview + history snapshot preview) gated the
animation CSS and no-JS fallback on the page body only, while the published
head (generateCompiledHTML) gates on the composed header+body+footer. Add
exportComposedPreviewHtml (head scanned over composed content for fonts and
animation; body replaced with composed HTML + one reveal script) and use it
from both Preview paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:40:54 -07:00
shadowdaoandClaude Opus 5.5 a2d18b7f4b fix(save): a save during a page/zone switch persists the target page, not the old canvas
PageContext.loadState deserializes on setTimeout(0); a save landing in that
window serialized the previous page's still-mounted canvas into the new active
page's slot. loadState now records the pending state and sendSave uses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:33:58 -07:00
shadowdaoandClaude Opus 5.5 6d22aabdc0 fix(global-sections): block structural edits inside a global-section instance
syncInstances rebuilds an instance's subtree from the master, so a node
dropped, pasted, duplicated or moved into an instance vanished from every page
on the next master edit. Chosen approach: BLOCK (not preserve-on-sync):
- every resolver component's Craft canMoveIn/canMoveOut refuses a canvas inside
  an instance (canvas DnD, Layers DnD, actions.move); synthetic shell-inner
  nodes now carry the component's rules instead of hardcoded allow-all
- insertBlock (BlocksPanel / EmptyContainerAdd / palette), paste (menu +
  shortcut), duplicate (menu + shortcut) and Sitesmith patch/section replace
  redirect to after the instance or refuse; no empty-container '+' inside one
The instance root still moves/duplicates as a whole; content overrides are
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:32:34 -07:00
shadowdaoandClaude Opus 5.5 ca500d36a9 fix(global-sections): Templates, Sitesmith site, Reset site and history Restore refused while a master is open
Each replaced site content under an open master zone: Templates cleared the zone
and committed the template's first section as the new master (rewriting every
instance); replaceAllPages left the zone without committing; history Restore
loaded page content around it. Templates button/command/overflow item and the
history Restore buttons are disabled with a 'Click Done first' notice, and the
handlers (TemplateModal.handleLoad, replaceAllPages -> false, Sitesmith site,
Reset site, restoreSite/restorePage) refuse as a hard guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:26:37 -07:00
shadowdaoandClaude Opus 5.5 996c9e92ec fix(global-sections): save/autosave/publish inside a master zone persist the live master
The zone's live master was neither in extras nor in the stored pages until
Done, so a save from inside the zone succeeded without it and cleared dirty;
closing the tab lost the edit (publish shipped stale instances). The save
payload now carries the master committed into the library and every stored
page/header/footer synced, computed exactly as Done would without touching the
editor (PageContext.globalZoneSaveView).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:23:46 -07:00
shadowdaoandClaude Opus 5.5 37ed85bf42 fix(navbar): logo on a stored light bar follows the link text in the editor
Legacy Navbar nodes store backgroundColor '#ffffff' + textColor '#3f3f46'; the
editor took the logo colour from the Site Design text (light on a dark design)
while the export already uses logoColor || textCol. Same dark-palette class as
finding 8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:22:22 -07:00
shadowdaoandClaude Opus 5.5 4b18d68389 fix(history): restore each page's menu settings (nav)
snapshotToPages mapped only id/name/slug/craftState/seo and
planPageRestore built/replaced pages without nav, so 'Restore site' and
'Restore one page' dropped every page's nav (show/parentId/label). The
NavSync effect then rewrote the follow-pages header: hidden pages
reappeared, dropdown nesting flattened, custom labels reverted.

SnapshotPage now carries `nav?: PageNav`, accepted only when it is a
plain non-null, non-array object (shallow-copied), else omitted.
planPageRestore restores it in id/slug replace mode (like seo) and on
append. HistoryModal already passes these rows straight to
setPagesCraftState, which keeps nav, so no wiring change was needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:20:24 -07:00
shadowdaoandClaude Opus 5.5 c00985a3a1 fix(responsive): derive Container/Section flex layout from the resolved per-device style in export
Tablet/mobile Alignment and Vertical-alignment overrides published only the
raw text-align/justify-content declarations, while the editor (which renders
from the device-resolved style) also applied the derived flex layout
(display:flex;flex-direction:column;align-items). Desktop-centred containers
stayed centred on mobile, mobile-only centring/vertical-align did nothing, and
in boxed mode the flex sits on the inner div which had no scope at all.

- Container/Section: single containerLayout()/sectionLayout() helper used by
  render, toHtml and a new static responsiveLayout hook.
- responsiveCssForNode takes an optional DerivedLayoutFn: per device it diffs
  the layout derived from the resolved style against what already applies
  (desktop for tablet, tablet for mobile), emits changes (and resets for
  dropped keys), and scopes boxed-mode inner rules as [data-wsb-r=x]>div.
- html-export passes the component's responsiveLayout hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:20:24 -07:00
shadowdaoandClaude Opus 5.5 6afb1c9b22 fix(site-builder): keep legacy light-surface text readable on dark palettes
Nodes saved before the component-tokens work (9ab0102) store light surface
hexes -- ContactForm inputBg '#ffffff', SubscribeForm style.backgroundColor
'#f8fafc', Testimonials cardBg '#f8fafc' -- while the text on those surfaces
became var(--wsb-text)/var(--wsb-muted). On a dark Site Design palette (light
text token, e.g. Agency #fafafa) that rendered white-on-white.

Text on a STORED light surface (hex #rgb/#rrggbb or rgb()) now keeps the
pre-token dark hex (input #1f2937, subscribe heading #1f2937, testimonial
quote #374151 / name #18181b / title #64748b); absent, token or dark surfaces
keep the token text. Stored props are never rewritten. Applied in both the
editor render and toHtml export.

Generalises Navbar's isLightNavBg into utils/color.ts (isLightColor /
textOnSurface, plus parseColor moved out of publish-checks and re-exported);
Navbar and autoTextColor now share it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:20:24 -07:00
shadowdaoandClaude Opus 5.5 7fe47160e9 fix(export): keep injected attrs out of the WHP-FORM marker comment
injectAttrs() skipped leading <style> blocks and then inserted the
responsive/visibility/animation attrs before the first '>'. Relay forms
(ContactForm, SubscribeForm, FormContainer with a recipient) start their
toHtml with `<!--WHP-FORM ...-->`, so the attrs landed inside the marker
(`thankyou=""-- data-wsb-r="...">`): the comment was left unterminated,
Preview swallowed the form, and the publish step refused the whole site.

injectAttrs now skips any leading run of whitespace, <style> blocks and
<!--...--> comments (any order, repeated) and targets the first real
element; a string that is only such a run is returned unchanged. The
marker wire format is untouched.

Tests port the backend's strict marker regex from FormRelayRewrite.php
and export each relay form with a recipient + styleMobile/styleTablet +
hideOnMobile + animation through exportBodyHtml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:20:24 -07:00
shadowdaoandClaude Opus 5.5 ff826a03c4 fix(api): 180s publish timeout, "Still publishing..." after 30s
Save/load keep 30s; publish of a large site legitimately runs longer and was
reported as failed at 30s while the server kept going.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:19:11 -07:00
shadowdaoandClaude Opus 5.5 6d6994f009 fix(preview): render customer head code only in a sandboxed srcdoc iframe
Preview and history Preview opened the composed page (raw site head code
included) as a panel-origin blob: tab, so a customer's <script> ran with the
viewer's panel session and CSRF token (root included). Both now open an empty
shell tab inside the click and render the page in an <iframe srcdoc> with
sandbox="allow-scripts allow-popups allow-forms" (no allow-same-origin):
an opaque origin, no opener. Tests assert the sandbox attribute and scan the
source for any remaining text/html blob / document.write / blob tab path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 13:18:11 -07:00
shadowdao d4400e49ad Merge component-tokens 2026-10-07 13:01:14 -07:00
shadowdao c35a73bb12 Merge integration-followups 2026-10-07 13:01:14 -07:00
shadowdaoandClaude Opus 5.5 bbae73c132 fix(styles): box-model and shadow presets are discrete undo steps
Preset buttons in BoxModelSection / BorderEffectsSection now write through
the discrete setters (setPropStyles / setPropStyle), so a keyboard-activated
preset (no pointerup or focusout to close the burst) never merges into the
previous edit of the same key. SpacingControl gains an optional onPreset
for this; margin/padding presets are also one undo step for all four sides
in the media panels.

Refs #7

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:54:13 -07:00
shadowdaoandClaude Opus 5.5 7d25bf181c fix(api): time out hung save/publish/load; show PHP error text
- save, publish and load run under a 30s AbortController timeout (raced,
  so a stalled body read can't hang either); save/publish resolve to
  { success:false, error:'timeout', message } and load rejects with a
  readable Error, so a hung request no longer blocks the save queue
- readApiResult falls back to obj.error when obj.message is absent, so
  PHP texts like 'Another save of this site is still in progress...' are
  shown instead of 'server returned HTTP 503'

Refs #4
Refs #47

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:51:48 -07:00
shadowdaoandClaude Sonnet 5.5 e347a4334d feat(site-builder): tokenise remaining component design colours (Navbar, Menu, Footer, SocialLinks, StickyCallBar, BackgroundSection, ContentSlider, Countdown, HeroSimple)
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:50:47 -07:00
shadowdaoandClaude Opus 5.5 25de75c34f fix(shortcuts): bare-key shortcuts never fire while a dialog is open
Single-key shortcuts (1/2/3 device switch) are skipped while any editor
dialog or modal is open (role=dialog/alertdialog, aria-modal, dialog[open],
.modal-backdrop) or focus is inside one. Dialog-like page content inside
the canvas frame does not count.

Refs #39

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:49:46 -07:00
shadowdaoandClaude Opus 5.5 aae94b1da2 fix(canvas): keep the empty-container block popover inside the viewport
The popover is measured once open and clamped to the viewport with an
8px margin; near the bottom edge it flips above the '+'.

Refs #41

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:48:49 -07:00
shadowdaoandClaude Opus 5.5 822d43cf61 fix(stock): stale searches can't overwrite newer results; scope 404
- A cache-hit search aborts any older in-flight stock_search and clears
  loading; StockPhotoTab only applies the newest request's result
- A bare 404 means 'stock unavailable' only for the stock_search probe;
  on stock_import it is an ordinary error (an explicit invalid/unknown
  action error still disables the tab)

Refs #55

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:48:18 -07:00
shadowdaoandClaude Opus 5.5 4bae531339 fix(templates): explain what the apply-design checkbox now means
Templates reference the site tokens, so with the checkbox off a template
follows the site's own palette. Label and a state-dependent help line now
say so.

Refs #44

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:47:04 -07:00
shadowdaoandClaude Opus 5.5 d5bfb02911 fix(styles): NavStylePanel reads the per-device resolved style
Switches NavStylePanel from nodeProps.style to useResolvedStyle(nodeProps)
and adds OverrideDots on Margin and Padding, the conversion #45 applied
to the other panels. NavStylePanel has no style-based text-alignment
control (Menu alignment is a top-level prop), so no dot there.

Refs #45

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:46:16 -07:00
shadowdaoandClaude Opus 5.5 9697dc95a3 feat(editor): wire business panel, section commands and Layers follow-ups
- GuidedStyles classifies Opening Hours / Call Bar / Reviews / Booking to
  BusinessStylePanel (#60) and shows a Regenerate button in the type
  header, hidden when edit.regenerate-section's when() is false (#58)
- LayersPanel TYPE_ICONS for the four business blocks (FA 4.7) (#60)
- Context menu entries 'Save as section…' and 'Regenerate this section'
  invoke site.save-as-section / edit.regenerate-section (#52, #58)
- commands: useCommandState(id) hook (registered/enabled/run)
- Layers: keep dropEffect 'move' on refused targets so drop fires and the
  refusal notice shows; renaming to the default name stores no
  custom.label (#47)

Refs #60
Refs #58
Refs #52
Refs #47

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:45:16 -07:00
shadowdaoandClaude Sonnet 5.5 2877bc06fa feat(site-builder): tokenise colours hard-coded inside components
Component render/toHtml now use var(--wsb-*) instead of hex so Site Design
palette changes reach FeaturesGrid, Testimonials, Accordion, PricingTable,
CTA/CallToAction, forms, Gallery, Tabs and others. Exemption lists removed.

Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:44:39 -07:00
shadowdaoandClaude Opus 5.5 ebf75ebfe0 feat(topbar): search button opens the command palette; Preview head parity
- Icon button with tooltip 'Search (Ctrl/Cmd+K)' calls openCommandPalette()
- Preview passes fontScanHtml: composedBody and trims metaTitle so the
  Preview head matches the published head

Refs #49

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:41:36 -07:00
shadowdaoandClaude Opus 5.5 db54341006 fix(export): Preview head parity with the published head
Frontend half of the backend-followups head parity work:
- CSS reset gains html,body{overflow-x:clip} (no phantom h-scroll, sticky
  navbar still works)
- buildFontsLink adds per-element preset fonts found in the page HTML
  (fontScanHtml option, defaults to the body); own-key preset lookup so
  names like 'constructor' behave like the backend's isset
- blank/whitespace design tokens fall back to the defaults
- description/ogTitle/twitterCard are trimmed
- history snapshot preview scans header+body+footer and trims metaTitle

Re-baselines the two TOKEN_VARS-move document hashes (the clip rule is
proven to be the only change) and pins the four complete heads from WHP
scripts/test-site-builder-head-parity.php.

Refs #54

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:41:36 -07:00
shadowdao 8227d768e6 Merge issue-57 (Refs #57) 2026-10-07 12:37:19 -07:00
shadowdao 07eba1ba69 Merge issue-52-content-C (Refs #52) 2026-10-07 12:37:19 -07:00
shadowdao 7fb5215571 Merge issue-52-content-B (Refs #52) 2026-10-07 12:37:19 -07:00
shadowdao cb887bc02f Merge issue-52-content-A (Refs #52) 2026-10-07 12:37:19 -07:00
shadowdaoandClaude Opus 5.5 dcc7e27be4 fix(site-builder): refuse Sitesmith page replace while editing a global master
A page-scope Sitesmith replace with a master zone open loaded the AI page
onto the zone canvas. On Done, its first section became the new master and
the sync rewrote every instance on every page with it, orphaning all
overrides. replaceCurrentPage now returns false inside a master zone and
the apply path reports an error asking the user to click Done first.

Refs #57

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:35:56 -07:00
shadowdaoandClaude Opus 5.5 dd8b99be06 feat(site-builder): reusable global sections with per-page overrides
Make a top-level section global (context menu), place instances from the
Section library's new Global tab, edit the master once in its own zone
("Editing global section" banner, Done - update N instances) and every
instance on every page/header/footer is rebuilt from it. Instances are real
inlined subtrees (custom.global on the root, custom.gkey on every node), so
export and published output are unchanged static HTML.

- utils/global-sections.ts: pure model (createMaster, instantiate,
  syncInstances, collectOverridesFromInstance, applyOverrides, detach,
  findInstanceRoot, master zone round trip). Unchanged input returns the
  identical string; sync keeps the instance root id and the instance's own
  inner ids per gkey.
- PageContext: __global__:<id> zone (editGlobal / finishGlobal); leaving it
  commits the master (rev + 1 only when it changed), syncs every stored
  slot and applies the sync to the returned-to canvas as ONE undo step.
- GlobalSectionsContext: makeGlobal / insertInstance / detach / setOverride
  / resetOverride / remove (refused while used), one undo step each.
- Inline text edits inside an instance record an override (text + html)
  via useGlobalOverrideCommit; GuidedStyles shows a Global section panel
  (Edit master, Detach, content override fields) instead of style panels.
- RenderNode: Global badge, dashed outline, lock icon on inner nodes.
- buildSavePayload: a master zone on the canvas is never saved into a page.

Refs #57

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:28:53 -07:00
shadowdao e0c48fc9b6 Merge whp-zip-export frontend (Refs #42)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
2026-10-07 12:24:38 -07:00
shadowdaoandClaude Opus 5.5 97469dbabf feat(site-builder): "Download site (.zip)" command
Registers site.download-zip (WHP mode only; shows in the ⋯ menu and the
palette) via ExportCommand, mounted in CanvasOverlays. useSiteExport POSTs
?action=export_zip with the CSRF header: a zip answer is saved through a
Blob + anchor click, anything else (JSON error, older backend, network
failure, a stream cut short) becomes an error notice.

Refs #42

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:15:44 -07:00
shadowdao 74dcbb003b feat(site-builder): add hero, services, about and cta sections to the library
Token-based sections (21 total across four families) with tests covering
insert, export (no stray hex, alt on images, relative links) and tree shape.

Refs #52
2026-10-07 12:15:12 -07:00
shadowdao 761d2255f8 feat(site-builder): add social-proof, FAQ, pricing and team sections
Refs #52
2026-10-07 12:14:30 -07:00
shadowdaoandClaude Sonnet 5.5 a16a724048 feat(site-builder): contact, hours, gallery and local-business sections
Adds 17 token-based sections across contact, hours, gallery and local strips,
with a real-editor test covering insert, hex-free export, alt text and links.

Refs #52

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:13:05 -07:00
shadowdao 48061d37ae Merge issue-60 (Refs #60) 2026-10-07 12:09:09 -07:00
shadowdao edae0d6107 Merge issue-58-fe (Refs #58)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
#	craft/src/styles/editor.css
2026-10-07 12:09:09 -07:00
shadowdao 0ac420a23c Merge issue-55-fe (Refs #55)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 12:09:09 -07:00
shadowdao 05c39961ce Merge issue-52-fe (Refs #52)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
#	craft/src/styles/editor.css
2026-10-07 12:09:09 -07:00
shadowdao 1d34d1b3b1 Merge issue-53 (Refs #53)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 12:09:09 -07:00
shadowdaoandClaude Opus 5.5 4379ffac64 fix(site-builder): nav link href typing is one undo burst again
URL/anchor/tel/mailto edits from LinkPicker now go through
continuousSetProp (key link:<i>:href); a page pick stays a discrete
step via discreteSetProp. source/pageId stripping and the followPages
mergeLinks re-merge remain inside the updater.

Refs #53

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:07:58 -07:00
shadowdao d39e1ecc31 Merge issue-56 (Refs #56)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
#	craft/src/styles/editor.css
2026-10-07 12:06:59 -07:00
shadowdao 0a59294fee Merge issue-54-fe (Refs #54)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 12:06:59 -07:00
shadowdao 4a81d0b89f Merge issue-51-fe (Refs #51)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
#	craft/src/styles/editor.css
2026-10-07 12:06:59 -07:00
shadowdao 1eaf8e39fb Merge issue-49 (Refs #49)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 12:06:59 -07:00
shadowdao eb87a39619 Merge issue-48 (Refs #48)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 12:06:59 -07:00
shadowdao f75958caea Merge issue-50 (Refs #50) 2026-10-07 12:06:59 -07:00
shadowdao c0fd183c11 feat(site-builder): pre-publish checklist and canonical link
Publish now runs client-side checks (image alt, meta description, title
length, H1, empty links, contrast, noindex landing, empty page) over the
current state and shows a grouped checklist with Fix links and
"Publish anyway". Adds ExportOptions.canonicalUrl -> <link rel="canonical">
after the favicon line in both Preview and export.

Refs #54
2026-10-07 12:05:28 -07:00
shadowdaoandClaude Sonnet 5.5 a9c8f4d65a feat(site-builder): version history modal with preview and restore
Adds a site.history command (WHP mode, only when history_list answers) opening
a modal of saves/publishes by day. Preview opens the snapshot re-exported with
its own design; Restore site / Restore one page load the snapshot as unsaved
state (history cleared, dirty marked) so the user still clicks Save.

Refs #51

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:04:17 -07:00
shadowdaoandClaude Sonnet 5.5 0bd6b74ba5 feat(site-builder): copy/paste style and saved style presets
Refs #48

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:03:27 -07:00
shadowdaoandClaude Sonnet 5.5 a80667dfe6 feat(site-builder): multi-select with bulk styling and mixed-type actions
Shift/cmd/ctrl-click multi-select via DefaultEventHandlers, same-type bulk
styling as one undo step, mixed-type Delete/Duplicate/Move block, grouped
undo for array-aware edit.* commands.

Refs #50

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:03:26 -07:00
shadowdaoandClaude Opus 5.5 52477bff45 feat(site-builder): menus that follow pages, with dropdowns
- utils/nav-links.ts: shared NavLink type (source/pageId/children),
  pageHref, buildPageLinks, mergeLinks, adoptPageLinks, rewriteHeaderLinks
- PageData.nav {show, parentId, label} + updatePageNav; a nav-sync effect in
  PageProvider materialises page-following links into the stored header
  (or the live header nodes while it is being edited); string/identity
  guards keep it a no-op when nothing changed
- Navbar/Menu: followPages prop (default false; the default header seed is
  true), one-level dropdowns (hover/focus-within + inline click toggle,
  indented in the hamburger layout), hover/CTA colours default to the
  primary token
- NavStylePanel: Follow pages toggle (adopts matching manual links, keeps
  custom text as the page's menu label), read-only page rows with Hide from
  menu, sub-link editor for manual links, LinkPicker records pageId
- Page Settings: Show in menu / Menu label / Nest under; Pages panel badge
- useWhpApi: nav passes through pages_craft_state on save and load

Legacy navs (no followPages) are never rewritten.

Refs #53

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:03:16 -07:00
shadowdaoandClaude Sonnet 5.5 1512cb7645 feat(site-builder): Cmd+K command palette
Refs #49

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 12:03:07 -07:00
shadowdao 092c8f6747 feat(site-builder): drag padding handles on the canvas
Edge handles on a selected Section/Container/Columns write padding via the
per-device setter as one undo burst; Alt = opposite side, Shift = all four,
Ctrl/Cmd snaps to 8px, Escape cancels.

Refs #56
2026-10-07 12:02:32 -07:00
shadowdao 5430f13877 Merge issue-45 (Refs #45)
# Conflicts:
#	craft/src/panels/right/styles/ButtonStylePanel.tsx
#	craft/src/panels/right/styles/shared.tsx
#	craft/src/styles/editor.css
2026-10-07 11:58:40 -07:00
shadowdao 68a3734eaf Merge issue-47 (Refs #47)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 11:58:26 -07:00
shadowdao 2b41cd46ba Merge issue-39 (Refs #39)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 11:58:26 -07:00
shadowdaoandClaude Opus 5.5 c472560fb5 fix(site-builder): remaining style panels show per-device values and dots
SectionType, Social, Pricing, Form and the generic props editor already
wrote tablet/mobile overrides through the device-aware useNodeProp setters
but still read nodeProps.style, so a mobile padding/margin/alignment edit
looked like a no-op and had no reset dot. They now read useResolvedStyle()
and show OverrideDots on Padding, Margin and Text Alignment.

NavStylePanel has the same gap but is outside this task's files.

Refs #45

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:57:17 -07:00
shadowdaoandClaude Sonnet 5.5 220f560972 feat(site-builder): Sitesmith business profile wizard and one-click section regenerate
5-step profile wizard (name/type, services, area, tone, palette preview) saved to
extras.sitesmithProfile and sent with every Sitesmith request. Regenerate this
section rewrites the selected block for the business as a single undo step.

Refs #58

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:55:33 -07:00
shadowdaoandClaude Sonnet 5.5 7d24ca52fa fix(site-builder): re-read saved sections when the library opens
Refs #52

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:54:53 -07:00
shadowdao 2cb04d2537 feat(site-builder): local-business block pack (hours, call bar, reviews, booking)
Refs #60
2026-10-07 11:53:44 -07:00
shadowdao c0e0003460 feat(site-builder): asset search/filter, stock photo tab and background focal point
Search + type chips in the Assets panel and picker library; Stock photos
entry in the picker (feature-detected, hidden when stock_disabled/absent);
bgPosition focal point for Hero and Background Section.

Refs #55
2026-10-07 11:52:32 -07:00
shadowdaoandClaude Sonnet 5.5 6e819f1ef2 feat(site-builder): section library catalog, modal and insertion
Catalog skeleton with per-family files (one seed each for hero, services,
contact), live token-styled thumbnails, insert-after-selection, and
save-as-section into project extras.

Refs #52

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:52:25 -07:00
shadowdao c2a90cd7a7 feat(site-builder): tablet/mobile style overrides that never touch desktop
On tablet/mobile the useNodeProp style setters now route responsive keys
(spacing, font size, line height, letter spacing, alignment, size, flex
layout) into styleTablet/styleMobile; colours and other keys still write
style. An empty value removes the override. Continuous-burst keys include
the device so a desktop drag and a mobile drag never merge.

- shared.tsx: device-aware setters, new setResponsiveStyleProp /
  clearResponsiveStyleProp exports, setPropStylesContinuous
- responsive-panel.tsx: useResolvedStyle, useOverrideState, DeviceBanner
- OverrideDot: filled dot resets the override (one undo step), hollow dot
  marks an inherited value; wired into Text/Button/Container/Image/Media/
  BackgroundSection panels and both box-model sections
- Columns: "Stack on this device" toggle (flexDirection override)
- GuidedStyles: device banner under the type header
- RenderNode: every component node renders through one stable
  ResolvedRender so gaining/losing an override or switching device no
  longer remounts the node (the remount dropped inline-edit focus/caret
  and blanked a selected Heading)

Refs #45
2026-10-07 11:51:53 -07:00
shadowdao 8860349c9b Merge issue-44-templates-D (Refs #44) 2026-10-07 11:47:58 -07:00
shadowdao 6dac754602 Merge issue-44-templates-C (Refs #44) 2026-10-07 11:47:58 -07:00
shadowdao 82f8fecb77 Merge issue-44-templates-B (Refs #44) 2026-10-07 11:47:58 -07:00
shadowdao 2e51371a67 Merge issue-44-templates-A (Refs #44) 2026-10-07 11:47:58 -07:00
shadowdao 2dd362e858 Merge issue-44 (Refs #44)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 11:47:58 -07:00
shadowdao c68e459430 feat(site-builder): complete shortcut set on the command registry with a cheat sheet
Core editor shortcuts become registry commands run by the single
useCommandShortcuts dispatcher: undo/redo, delete, duplicate (after +
select), copy/paste, Alt+arrow move, 1/2/3 device, Cmd+S/Shift+P/P site
commands and Cmd+/ cheat sheet. Tab/Esc no longer fire from buttons or
dialogs. Context menu labels come from formatShortcut.

Refs #39
2026-10-07 11:47:55 -07:00
shadowdao 98e32a68b9 Merge issue-46 (Refs #44 #46)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
#	craft/src/styles/editor.css
2026-10-07 11:47:54 -07:00
shadowdaoandClaude Sonnet 5.5 8edc426986 feat(site-builder): layers drag reorder, rename, hide/show, collapse
Refs #47

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:47:10 -07:00
shadowdao d8ff295093 fix(site-builder): rebuild editor.css after union merge interleaved #41/#34 regions 2026-10-07 11:42:32 -07:00
shadowdaoandClaude Opus 5.5 7e8812a752 feat(site-builder): inline bold/italic/underline/links on Heading and Text
Select text inside a selected Heading or Text block and a floating
toolbar offers B / I / U / Link / Unlink (execCommand; mousedown is
prevented so the selection survives; mod+b/i/u handled on the editable).

Storage: new `html` prop holding sanitised inline HTML, with `text` kept
as the plain mirror for AI summaries, search and legacy content.
Unmarked edits store html '' so legacy nodes keep their shape. The
allowlist (b strong i em u a br span; style=color only, hex/rgb/
var(--wsb-*); href via DOMPurify URI check AND safeUrl, unsafe links
unwrapped; target only _blank with forced rel=noopener) runs on commit,
on canvas render and again at export. If `text` was changed without
`html` (Sitesmith update_props), the stale html is ignored.

Each edit commits once (blur, or deselect if no blur came first) as one
setProp = one undo step; the old blur+deselect double commit is gone.
Heading colour default now tokenRef('text'). Sitesmith canvas summary
skips `html`.

Refs #46

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:41:56 -07:00
shadowdao 74df8a3b70 Merge issue-34 (Refs #34) 2026-10-07 11:41:22 -07:00
shadowdao d756a723de Merge issue-43 (Refs #43)
# Conflicts:
#	craft/src/editor/CanvasOverlays.tsx
2026-10-07 11:41:22 -07:00
shadowdao 817028df89 Merge issue-41 (Refs #41) 2026-10-07 11:40:54 -07:00
shadowdao 4fbe109bac Merge issue-37 (Refs #37) 2026-10-07 11:40:54 -07:00
shadowdaoandClaude Sonnet 5.5 fad34f3e71 feat(site-builder): actionable empty canvas and inline add for empty containers
Refs #41

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:39:34 -07:00
shadowdao 22c59eb970 feat(site-builder): tablet/mobile canvas emulates published hide, stacking and full-width
Frame gets data-device; RenderNode mirrors hide flags and selection onto the
dom; editor.css emulates the exported breakpoints inside the narrowed frame.
Also: data-wsb-overridden counts only set values, responsive scope ids are
zone-prefixed (h-/b-/f-) so ROOT no longer collides, and comment delimiters
are stripped from responsive declarations.

Refs #37
2026-10-07 11:39:25 -07:00
shadowdaoandClaude Sonnet 5.5 e94bec8d58 feat(site-builder): re-author medical/portfolio/photography/content-creator templates onto design tokens
Palette and heading fonts become var(--wsb-*) refs; mutedTextColor added to
each template's design. Gradient companion stops stay hex.

Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:38:22 -07:00
shadowdaoandClaude Sonnet 5.5 af460f23e6 feat(site-builder): precise drop indicator with target glow and empty-container label
Restyle Craft's insertion bar via the Editor indicator prop and mirror the
live placement onto the DOM (data-drop-target/-error/-empty, is-dragging).

Refs #43

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:38:22 -07:00
shadowdao dd7a50cf3d feat(site-builder): token-aware colour controls and Try a palette
Colour controls offer the site palette first, show the resolved colour for
var(--wsb-*) values with a token chip, and keep the stored reference.
autoTextColor resolves tokens. Site Design gains six one-click palettes.

Refs #44
2026-10-07 11:38:17 -07:00
shadowdaoandClaude Sonnet 5.5 dff17b0917 feat(site-builder): re-author restaurant, small-business, saas-landing, agency templates onto design tokens
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:37:31 -07:00
shadowdaoandClaude Sonnet 5.5 99457c5a63 feat(site-builder): re-author templates group D onto design tokens
coming-soon, church, non-profit and fitness-gym now reference var(--wsb-*)
for their own palette and fonts instead of hard-coded copies, so changing
Site Design after applying restyles them. Adds mutedTextColor to each design.

Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:37:08 -07:00
shadowdaoandClaude Sonnet 5.5 9869db8514 feat(site-builder): re-author templates group C onto design tokens
event-conference, resume-cv, blog and wedding now reference var(--wsb-*)
tokens instead of repeating their design palette/fonts in component props.

Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:36:41 -07:00
shadowdaoandClaude Sonnet 5.5 2a6055d863 feat(site-builder): selection breadcrumb, Esc selects parent, Tab cycles siblings
Refs #34

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:36:40 -07:00
shadowdao ce3db23506 Merge W0-tokens-defaults (Refs #45 #37 #44) 2026-10-07 11:33:02 -07:00
shadowdao 8216248107 Merge W0-breakpoints (Refs #45 #37 #44) 2026-10-07 11:33:02 -07:00
shadowdaoandClaude Sonnet 5.5 705c602a67 test: flush #40 debounce in Container padding seed test (still one undo step)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:31:51 -07:00
shadowdao 136e3ce6ea fix(site-builder): restore closing brace lost in #36/#38 editor.css merge 2026-10-07 11:31:10 -07:00
shadowdao 1f5cac2cca Merge issue-38 (Refs #38)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 11:30:20 -07:00
shadowdao 536b6c6b8c Merge issue-36 (Refs #36) 2026-10-07 11:30:16 -07:00
shadowdao bee052833c Merge issue-35 (Refs #35) 2026-10-07 11:30:16 -07:00
shadowdao 5db1879c63 Merge issue-40 (Refs #40) 2026-10-07 11:30:16 -07:00
shadowdao ec071c4c39 feat(site-builder): debounce style inputs and stop Layers recomputing on hover
Text/number/hex inputs keep local state and commit on 150ms idle, blur or
Enter through the continuous setters; native colour pickers get an
onContinuous path; ButtonStylePanel colour routes through the shared
setters. LayersPanel collectors return structural signatures/primitives
so hover and unrelated prop edits no longer rebuild the tree.

Refs #40
2026-10-07 11:28:47 -07:00
shadowdaoandClaude Opus 5.5 5f99df23a7 feat(site-builder): per-breakpoint style model, device context and responsive export
- utils/breakpoints.ts: single source for 767/768/991/992; head
  VISIBILITY/RESPONSIVE CSS built from it (flex-stacking rule moved from
  768 to the 767 mobile boundary).
- utils/responsive-style.ts: styleTablet/styleMobile partial overrides,
  cascade resolution, pure setters, scoped @media CSS per node.
- state/DeviceContext.tsx: real DeviceProvider (owns the one-time mobile
  forcing from EditorShell); TopBar, overflow menu, ReportIssueModal and
  Canvas read useDevice() instead of props.
- editor/RenderNode.tsx: resolves the effective style for the current
  device in one place and marks overridden nodes with data-wsb-overridden.
  Craft passes an opaque <DefaultRender/> to onRender, so the component
  element is rebuilt with the resolved style (cloneElement cannot work).
- utils/html-export.ts: hidden nodes skipped; overrides emitted as one
  body-level <style data-wsb-responsive> block + data-wsb-r scope attr;
  injectAttrs skips leading <style> elements.
- test-utils/editorHarness.tsx: optional onRender/wrap options.

Refs #45
Refs #37

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:28:44 -07:00
shadowdaoandClaude Sonnet 5.5 4a11a9e344 feat(site-builder): open Spacing/Colours by default, remember collapse state, single container padding control
CollapsibleSection persists open/closed per section title via local-prefs.
Container/Section/Columns drop the shorthand padding preset grid; the
per-side Padding control expands a legacy shorthand and writes all four
longhands in one undo step (new SpacingControl onChangeAll).

Refs #35

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:25:30 -07:00
shadowdao e5119174e7 feat(site-builder): Element/Site tabs in the right panel
Refs #36
2026-10-07 11:25:28 -07:00
shadowdaoandClaude Sonnet 5.5 5006089a4a test(site-builder): real-editor test that new blocks serialize token defaults
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:24:52 -07:00
shadowdaoandClaude Sonnet 5.5 045643d570 feat(site-builder): Section background and dividers default to bg token
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:24:52 -07:00
shadowdaoandClaude Sonnet 5.5 488f208262 feat(site-builder): section blocks default to palette tokens
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:24:52 -07:00
shadowdaoandClaude Sonnet 5.5 af43af7dc1 feat(site-builder): form blocks default to palette tokens
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:24:52 -07:00
shadowdaoandClaude Sonnet 5.5 d70f4933af feat(site-builder): basic blocks default to palette tokens
Refs #44

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:24:52 -07:00
shadowdao 7b082c8d2e feat(site-builder): searchable blocks panel, remembered collapse state and left tab
Refs #38
2026-10-07 11:23:00 -07:00
shadowdao 2180f9a776 Merge W0-registry-notices (Refs #38 #41 #49 #48 #57 #58)
# Conflicts:
#	craft/src/state/NoticeContext.tsx
#	craft/src/styles/editor.css
2026-10-07 11:20:30 -07:00
shadowdao ae871c9cdc Merge W0-commands (Refs #39 #49 #34)
# Conflicts:
#	craft/src/styles/editor.css
2026-10-07 11:20:25 -07:00
shadowdao 42700f911f Merge W0-tokens-core (Refs #44) 2026-10-07 11:20:21 -07:00
shadowdaoandClaude Opus 5.5 f8ac1fbe42 feat(site-builder): token module, canvas token variables, palette swatch row
Make var(--wsb-*) a first-class style value in the editor:

- utils/tokens.ts: TokenKey, TOKEN_VARS (moved from html-export.ts, same
  order/content as the backend), COLOR_TOKENS palette order, tokenRef,
  isTokenRef, tokenKeyOf, resolveTokenValue and buildCanvasTokenCss, which
  defines the 16 vars + token base CSS scoped to .canvas-device-frame
  (never :root) with every value through cssValue().
- editor/CanvasTokenStyle.tsx: <style data-wsb-canvas-tokens> driven by
  useSiteDesign(), mounted in App inside SiteDesignProvider, so design
  edits recolour token-backed values on the canvas instantly.
- panels/right/styles/TokenSwatchRow.tsx: palette-first swatch row that
  emits token references; .token-swatch styles appended to editor.css.
- html-export.ts imports TOKEN_VARS; export output pinned byte-identical
  to the pre-move baseline by hash in html-export.test.ts.

Refs #44

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:16:29 -07:00
shadowdaoandClaude Sonnet 5.5 73aa35ac96 feat(site-builder): command registry, shortcut matcher, tree walkers and top-bar command menu
Library only; nothing is mounted. Adds minimal DeviceContext/NoticeContext
stubs (owned by W0-breakpoints / W0-registry-notices) that expose the
agreed interfaces.

Refs #39 #49 #34

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:14:52 -07:00
shadowdaoandClaude Sonnet 5.5 21c2776c88 feat(site-builder): block registry, notices, local prefs, project extras, overlay slot
Add an exported block registry (keywords, search, insertBlock) consumed by
BlocksPanel, a NoticeProvider/NoticeHost toast stack, a guarded localStorage
prefs helper, a ProjectExtras store persisted as project.json 'extras', and a
CanvasOverlays mount point.

Refs #38
Refs #41
Refs #49
Refs #48
Refs #57
Refs #58

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 11:14:51 -07:00
shadowdaoandClaude Opus 5.5 97ccbee461 fix(site-builder): serialise all saves; honest pill for conflicts and new sites
A manual Save during Publish sent a second save with the same base_rev; the
loser 409'd against its own tab (and could abort the publish).

- useWhpApi: every save runs through one in-flight promise (SaveGuard
  saveInFlight). A save requested while one is out waits, then sends only
  if still dirty, with the rev the first returned; payload is read from the
  editor at send time. Forced (empty/overwrite) saves always send.
- Save buttons are disabled while publishing.
- Pill: a conflict reads 'Unsaved changes' (modal open) from Save and from
  Publish alike; a never-saved site (load rev null) reads 'Not saved yet'.
- Autosave interval reads runSave through a ref, so editing can't keep
  restarting it and starve autosave.
- Fix stale 'Throws like exportBodyHtml' comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:35:11 -07:00
shadowdaoandClaude Opus 5.5 572e736f1f fix(site-builder): Undo can no longer cross the load or a page switch
Craft records actions.deserialize as an undoable step and nothing cleared
history, so Undo right after load returned the canvas to the blank pre-load
Frame (autosave would then save it), and Undo after a page switch put the
previous page's content into the current slot.

- clear history after the load-time deserialize and after every page/
  header/footer switch (in-place AI replacement of the same slot keeps it)
- continuousSetProp opens a burst only when its first call actually
  changed something, so it never merges into an entry it did not create
- the empty-save banner's Undo is disabled when there is nothing to undo

Real-editor tests: load, page/header switch, no-op-first burst, banner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:32:15 -07:00
shadowdao eb134a4743 Merge polish/save-pipeline: load gate, honest save state, idle autosave, conflict handling (Refs #28 #30 #31 #33) 2026-10-07 10:21:51 -07:00
shadowdaoandClaude Sonnet 5.5 34c932fc67 fix(site-builder): disarm Keep mine on empty-banner Undo; autosaveDue honours conflict
Refs #31

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:20:45 -07:00
shadowdaoandClaude Sonnet 5.5 a6db5438b2 feat(site-builder): detect two-tab save conflicts; Reload latest / Keep mine modal
Refs #31

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:19:07 -07:00
shadowdaoandClaude Sonnet 5.5 a20c9bae28 fix(site-builder): don't cache swallowed export failures; load-bearing autosave gate test
Refs #33

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:15:24 -07:00
shadowdaoandClaude Sonnet 5.5 c863767283 fix(site-builder): autosave only when dirty; memoise per-state page export
Refs #33

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:12:31 -07:00
shadowdaoandClaude Sonnet 5.5 86b82ed154 fix(site-builder): publish racing an edit stays a draft; no autosave during publish
Refs #30

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:09:26 -07:00
shadowdaoandClaude Sonnet 5.5 9418444916 fix(site-builder): honest save state (dirty tracking, status pill, beforeunload, error notice)
Track dirty from Craft node changes and page/design/header/footer state, cleared
only by a successful save. Persistent Unsaved/Saving/Saved/Published/Save failed
pill, beforeunload prompt while dirty or saving, one persistent error notice,
resp.ok/non-JSON handling for save and publish, and publish refuses to run
after a failed save. Draft badge no longer flips on a no-op autosave.

Refs #30

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:07:03 -07:00
shadowdao 8537cacd01 Merge polish/undo-merging: one undo step per edit (Refs #32) 2026-10-07 10:01:59 -07:00
shadowdaoandClaude Sonnet 5.5 2c85e33b38 fix(site-builder): continuous-edit bursts via history.merge; plain setters are single steps
Refs #32

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 10:00:29 -07:00
shadowdao a406ff8548 fix(site-builder): fail load on unreadable page state; disable editing controls until loaded
Refs #28
2026-10-07 10:00:11 -07:00
shadowdao 66e669fa01 fix(site-builder): never save before a successful load; guard empty overwrites
Refs #28
2026-10-07 09:57:11 -07:00
shadowdaoandClaude Sonnet 5.5 ac490215ce fix(site-builder): one undo step per edit (throttle continuous inputs, single setProp for multi-prop toggles)
Refs #32

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 09:56:12 -07:00
shadowdaoandClaude Opus 5 9ab01021be chore: pin the shared-memory project key
Ties every collaborator's Claude Code to the same shared-memory project
automatically, instead of each machine inferring a key from the directory
name. Read by project.identify at session start.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-23 08:09:04 -07:00
jknapp a684d51996 Merge PR #27: webhook destination controls for contact forms
Adds the webhook destination option to the contact form. Legacy markers stay byte-identical; the raw secret never reaches a Craft prop.

Pairs with the whp-side branch of the same name.
2026-08-11 00:42:02 +00:00
shadowdaoandClaude Opus 5 422697acec fix(site-builder): review findings on the webhook destination controls
I-1: WebhookSecretField now mounts with key={selectedId}. GuidedStyles renders
FormStylePanel with no key, so a selection change re-rendered rather than
remounted it and React kept `draft`/`status`. Since a failed store deliberately
retains the draft, clicking a second contact form showed node A's raw secret in
node B's field, and the next blur assigned the returned secret_id to the wrong
form (burning a slot against the per-site cap). The status banner leaked the
same way. Both pinned by the reviewer's repro sequence.

I-2: the button is "Clear", not "Remove", and says so -- nothing deletes a
stored key file, so the 50-per-site cap counts stores-ever. Labelling it Remove
told the customer they had reclaimed a slot right up until the 429 that said
otherwise. Actually deleting the file is Task 8's territory.

M-1: inline warning when the webhook URL is blank or not absolute https. The
publish step does refuse these, but into an error_log the customer never reads.
Warning only -- isHttpsWebhookUrl never edits the value or blocks the publish,
since either would trade a loud server-side refusal for a silently inert form.

M-2: the BYTE-IDENTITY test now compares against a literal marker captured by
executing the emitter at 071f3447, not against another head-revision output. The
self-comparison could only catch a drift affecting one side; a uniform one
passed it. Verified: a uniform `<!-- WHP-FORM` drift now fails this assertion.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 15:57:38 -07:00
shadowdaoandClaude Opus 5 d1c57db967 feat(site-builder): webhook destination controls on the contact form
ContactForm gains four craft props (destinationType, webhookUrl,
webhookSecretId, webhookAuthMode), all present in craft.props defaults so
FormStylePanel's `nodeProps.X !== undefined` gates actually render their
controls. The controls live in FormStylePanel (RightPanel renders only
GuidedStyles, so related.settings would be dead UI).

relayFormWiring widens the marker to optionally carry type/url/secret/
authmode BETWEEN `id` and `recipient`, which is where FormRelayRewrite.php's
parser looks. A marker with no type is byte-identical to what shipped before
-- pinned by a test that diffs an explicit-email form against one with no
destination props at all, since every already-published site depends on that
shape continuing to provision an email endpoint.

Every optional attribute value goes through one escaping site (markerAttr ->
escapeAttr); type and authmode are additionally allowlisted, so a case-drifted
"Bearer" reaches the relay as the exact literal it compares against instead of
being silently downgraded to unsigned.

The raw shared secret is never a prop: it is held in WebhookSecretField's
local state, POSTed to /api/form-webhook-secret.php on blur, and only the
returned opaque id is persisted. The field is write-only (set / replace /
remove, never view) because the endpoint has no read route, and the endpoint's
429 cap message is surfaced verbatim so a customer can act on it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 15:45:05 -07:00
shadowdaoandClaude Opus 5 071f3447fd Add static security advisory to HTML block style panel
Custom HTML block renders arbitrary markup on the published site.
Scripts and event handlers are stripped, but forms, iframes, and
images survive and can send data elsewhere. Add a plain, always-shown
advisory (no content detection) alongside the existing wrapper-styling
note.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 08:37:42 -07:00
shadowdaoandClaude Opus 5 98f2ebf118 Fix: HtmlBlock sanitizer strips select/meter presentation attrs
size, low, high, and optimum were missing from PURIFY_CONFIG.ALLOWED_ATTR
even though <select> and <meter> are already in ALLOWED_TAGS, so
<select size="4"> rendered at default height and <meter low/high/optimum>
lost its threshold-based gauge colouring. All four are pure
presentation/semantic attributes with no URL/script/event-handler
surface, so no security implication.

Also regenerates the pinned pre-Task-25 output fixture: its source
(html-block-test-body.html) already exercises size/low/high/optimum, so
the byte-identity test's expected output legitimately changes to include
them; verified the regenerated fixture's only diff from the prior one is
those four attributes now surviving.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 07:23:36 -07:00
shadowdaoandClaude Opus 5 916a568e9f fix(site-builder): address Task 25 review findings on <style> scoping
Four issues from adversarial review of the block-scoped <style> feature:

1. (Critical) transformBlock() recursed once per @media/@supports/@container
   nesting level with no cap -- ~7000 nested rules blew the call stack, and
   nothing between a Custom HTML block's toHtml() and the publish pipeline
   catches exceptions, so this took down the whole page's publish and
   crashed the live editor on every keystroke. Added MAX_NESTING_DEPTH=20
   (pass the body through unscoped beyond it) and wrapped scopeCss() so it
   never throws on any input, matching repairOrphanNodes's existing
   contract. Caught and fixed a variable-shadowing bug in my own first pass
   at this: the new depth parameter was silently shadowed by a pre-existing
   `let depth` used for brace-matching in the same block, which would have
   defeated the cap with no type error.

2. (Important) FORCE_BODY: true was unconditional, but it isn't a no-op for
   style-free input: it also changes how the parser preserves whitespace
   after a LEADING html comment, which this repo's own fixture starts with.
   Verified via a raw byte-diff against HtmlBlock.tsx@6a9b227 (extracted
   verbatim, run standalone against real dompurify+jsdom) that the fixture
   gained bytes. Fixed by applying FORCE_BODY only when the input has a
   real (non-comment) <style> tag to rescue -- confirmed empirically that
   this is a true no-op for every other input. Pinned the old output as a
   checked-in regression fixture and added a raw toBe() diff test.

3. (Important) scopeStyleBlocks() wasn't idempotent -- pasting previously
   published/exported output into a fresh block nested a second wrapper
   and re-prefixed every selector. Added isAlreadyScoped(), which detects
   a lone root wrapper whose <style> content is already a no-op under
   scopeCss for that wrapper's own class (reusing scopeCss's own
   idempotency guarantee) and leaves it untouched.

4. (Minor) Documented, not fixed: the 32-bit scope-id hash is
   brute-forceable (CSS-only impact, same trust tier as other accepted
   risks here), and DOMPurify's SAFE_FOR_XML silently drops an entire
   <style> block when its content merely looks tag-like (e.g.
   content: "<Read More>").

1155/1155 tests passing (was 1141), tsc clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 17:36:12 -07:00
shadowdaoandClaude Opus 5 32f4092156 feat(site-builder): add block-scoped <style> support to Custom HTML block
<style> was previously in FORBID_TAGS and stripped entirely. It's now
allowed, but its CSS is rewritten by a new hand-rolled scoper
(src/utils/scope-css.ts) so a customer's rules only match inside their own
block's wrapper -- never leak out and restyle the rest of the page. The
wrapper div (class="whp-html-<hash>") is only emitted when a block actually
has surviving <style> content, so blocks that don't use it stay
byte-identical to before this change.

Key findings, both covered by tests:
- DOMPurify's body-only serialization silently drops a <style> tag that
  appears before any other content in a block (the HTML5 parser implicitly
  places it in <head>, which DOMPurify never looks at). Fixed with
  FORCE_BODY: true.
- DOMPurify does not sanitize CSS declaration values at all (expression(),
  behavior:, url() to any host all pass through verbatim) -- @import is
  stripped explicitly by scopeCss() since it's the one CSS-level
  exfiltration/fetch vector in scope here.

Scope identifier reuses the existing djb2 stableHash() from utils/escape.ts
(already used for this exact class of problem) over the block's own `code`
string -- deterministic, no node id, no Math.random/Date.now.

1141/1141 tests passing (was 1077), tsc clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 17:10:57 -07:00
shadowdaoandClaude Opus 5 6a9b227dda fix(site-builder): repair dead-code data:image clause in HTML block URI regex
Review follow-up on the Task 24 sanitiser widening (approved, no bypass
found). Two Important findings to close:

1. ALLOWED_URI_REGEXP's data:image/...;base64, arm sat inside the group
   that appends a trailing `:` to every alternative, so it required a
   second colon no real data URI has -- the clause could never match.
   Confirmed dead before the fix (poster/cite/href all stripped a valid
   base64 PNG data URI) and working after (all three now survive), while
   javascript:/data:text/html stay blocked. Pulled the arm out into its
   own top-level alternative.

2. Corrected an inaccurate comment/report claim that every allowed
   attribute value goes through this regex -- `src` on
   img/video/audio/source/image/track is additionally covered by
   DOMPurify's own DATA_URI_TAGS allow-list, which is mimetype-blind and
   bypasses the regex entirely (acceptable: none of those tags execute
   src as a document; iframe is correctly excluded from that list).

Adds two regression tests: the regex fix actually working, and the
DATA_URI_TAGS bypass pinned so a future DOMPurify change surfaces as a
failing test rather than a surprise. Fixture byte figures unchanged
(15,815 -> 14,899; fixture has no data:image URIs).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 16:50:32 -07:00
shadowdaoandClaude Opus 5 156c5bae35 fix(site-builder): widen Custom HTML block sanitiser allow-list
A customer's broad HTML fixture showed 38% of it silently deleted by
the shipped DOMPurify config: colspan/rowspan/scope, <dl>, <sub>/<sup>,
<details>/<summary>, inline <svg>, <video>/<audio>, lang/dir/role, and
<ol start/reversed> were all stripped. The site owner's call: be
generous, this block is an explicit escape hatch, allow forms too.

Widens PURIFY_CONFIG in HtmlBlock.tsx (45->119 tags, 16->108 attrs;
form/input/button/select/textarea removed from FORBID_TAGS) while
keeping the four non-negotiables intact: no <script>, no on*, no
javascript: URLs, iframes stay sandboxed. <style> stays blocked
(separate task adds scoped support later), including inside the newly
allowed inline SVG. SVG support is an explicit tag list mirroring
DOMPurify's own SVG vocabulary rather than USE_PROFILES, which turned
out to silently discard ALLOWED_ATTR entirely and pull in unaudited
tags (dialog, template, marquee, ...) not in scope here.

Fixture survival goes from 61.6% (9,739/15,815 bytes) to 94.2%
(14,899/15,815 bytes). Adds a fixture-driven regression + security
test file (HtmlBlock.security.test.ts) plus a checked-in copy of the
reference fixture, loaded via Vite's ?raw import so tests need no new
dependencies and can't silently drift from the thing being tested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 16:36:01 -07:00
shadowdaoandClaude Opus 5 69e61ab4b2 fix(site-builder): final whole-branch review fixes
C1: HtmlBlock's PURIFY_CONFIG omitted 'style' from ALLOWED_ATTR, so the
toolbar colour picker added in this branch was silently deleted by
DOMPurify -- issue #2 was regressed, not fixed. Adds style/id plus table
tags, with tests pinning the markup path in both render and toHtml.

I3: PagesPanel's three confirmation states were not mutually exclusive;
cancelling delete revealed an unbidden reset prompt on a destructive action.

I5: orphan repair logged at console.warn, which the new console buffer
cannot see -- the reporter would never capture the most diagnostic signal
for the still-unreproduced drop bug. Also aligns useWhpApi's initial-load
failure handling with loadState's fallback.

I7: corrects comments (and the design spec) that asserted an orphan
"renders somewhere on the canvas", which a mid-plan audit disproved.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 12:47:23 -07:00
shadowdaoandClaude Opus 5 3dd6b54a35 fix(site-builder): address Task 19 review — onChange convention, opt-out copy
Review findings on the Report an Issue modal:

1. Revert the description textarea from onInput back to onChange. The
   onInput swap sidestepped a real React value-tracker dedup gotcha (a
   test harness's raw `el.value = x` assignment looks like a no-op change
   to a controlled onChange input), but this codebase already has the
   correct fix for exactly that gotcha: bypass the tracker's patched
   setter via the native prototype descriptor, as HeadCodeModal.test.tsx,
   SiteDesignPanel.reset.test.tsx, shared-controls.test.tsx, and both
   MediaStylePanel.*.test.tsx already do. Rewrote typeDescription() in
   ReportIssueModal.test.tsx to use that idiom instead of bending the
   component to fit the test.

2. The include-contents opt-out copy said unchecking it still sends "your
   description, the page name and your browser details" but omitted
   console errors, which buildReportPayload always includes regardless of
   the checkbox and which can incidentally echo page content. Copy now
   lists console errors explicitly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:39:22 -07:00
shadowdaoandClaude Opus 5 d7eeff3a68 feat(site-builder): add in-builder Report an Issue modal
Wires the Task 18 payload builder and Task 16/17 diagnostics into a
user-facing modal, reachable from the topbar bug icon (desktop) and
overflow menu (mobile). Two gaps in the task brief's draft, not called
out there, are handled explicitly: buildReportPayload() can throw when
the payload is still oversized after canvas_state is dropped, so
submission is wrapped in try/catch with an actionable "too large" error
that preserves the user's typed text; and the textarea maxLength is
sourced from MAX_DESCRIPTION_CHARS (with a proximity character count)
instead of a hardcoded number, so the UI limit can't drift from the
payload limit.

Also portals the modal to document.body for the same stacking-context
reasons TemplateModal/HeadCodeModal already do, and guards the
useEditor() selection collector with optional chaining so it degrades
gracefully under TopBar's existing test harness (a minimal @craftjs/core
stub with no events/nodes on its collector state).

The textarea uses onInput rather than onChange: React's onChange dedup
(via its DOM value-tracker) treats a test harness's raw `el.value = x`
assignment as a no-op change, matching this repo's existing pattern
(HeadCodeModal.test.tsx, shared-controls.test.tsx, etc. all work around
the same gotcha) -- onInput is a plain passthrough with no such check,
and is behaviorally identical for real typing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:29:26 -07:00
shadowdaoandClaude Opus 5 f43a1ef872 fix(site-builder): enforce the payload cap unconditionally, bound description
Review found the 512KB cap on buildReportPayload only ever measured on the
includeCanvas+canvasState branch -- opt-out and null-canvas paths returned
early without checking size at all, and an oversized non-canvas field
(description straight from a user's textarea) could slip through with a
canvas_state_omitted: 'size' marker that falsely claimed the drop had fixed
things.

- Truncate description to 5000 chars (matches the server-side validator's
  future limit), silently: unlike canvas_state, a truncated free-text
  description is exactly what it looks like, not a misleadingly-plausible
  partial structure.
- Route every return path through finalize(), which measures the actual
  candidate payload and throws rather than returning an oversized body --
  so 'size' can never be attached to a payload that's still over cap.
- Keep the opt-out early return structurally separate so canvas_state is
  never populated from input on that path, regardless of the cap check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:14:12 -07:00
shadowdaoandClaude Opus 5 fd7f883d6a feat(site-builder): add pure issue-report payload builder
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:08:46 -07:00
shadowdaoandClaude Opus 5 4cfcccd272 fix(site-builder): swap build-stamp console.log for a window global, add test
Review found two real issues in the initial build-stamp commit:

- A permanent, unconditional console.log on every editor load for every
  customer is production noise. Replaced with a window.__WHP_EDITOR_BUILD__
  assignment -- same load-bearing effect (keeps build-stamp.ts from being
  tree-shaken out before Task 19 wires in the real call site), but prints
  nothing. Support can ask a user to type __WHP_EDITOR_BUILD__ in the
  console on request. Commented as load-bearing so it isn't later "cleaned
  up" as a stray global.
- editorBuild()'s 'dev' fallback was never actually exercised by any test
  in the suite, despite the previous report claiming otherwise. Added
  build-stamp.test.ts asserting editorBuild() === 'dev' under vitest.

Also silences the expected-failure stderr git prints on the successful
'nogit' fallback path (stdio: ['ignore', 'pipe', 'ignore']), so a
release-tarball build log doesn't show a misleading fatal: line for an
intentional, handled case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:05:01 -07:00
shadowdaoandClaude Opus 5 024f9fdd46 feat(site-builder): stamp git sha + date into the editor bundle
package.json's version is hand-maintained and never changes between
builds, so a bug report can't identify which bundle produced it.
Vite's `define` injects __EDITOR_BUILD__ (short git SHA + build date)
at compile time; editorBuild() in build-stamp.ts is the only safe way
to read it, falling back to 'dev' since vitest does not apply Vite's
`define` and the identifier is otherwise undeclared. The execSync
call falls back to 'nogit' when building outside a git checkout
(release tarballs), verified by building from a directory with no
git ancestry at all.

Also wires editorBuild() into a startup console.log in main.tsx --
without any reference to it, Vite tree-shakes the unused module out
of the bundle entirely and __EDITOR_BUILD__ never gets substituted,
silently leaving every bug report saying 'dev'. Task 19 will add the
real call site when it assembles the report payload.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:59:38 -07:00
shadowdaoandClaude Opus 5 fc8918c1f9 fix(site-builder): stop the console-error marker from re-deriving "original" from a live wrapper
Review found a gap in the idempotency marker added for Task 16: if
external code wraps our patched console.error between two of our own
installs, the marker sees an unmarked function and treats it as
virgin, capturing the external wrapper itself as "the original".
That both double-records (the old patch is still reachable inside the
wrapper's closure) and makes __resetConsoleErrorBuffer() restore to
the wrapper instead of the real original.

Fix: stash the true original exactly once, directly on the `console`
object (not module scope, so it survives HMR too), and always
re-wrap that stashed reference rather than whatever console.error
currently is. Reinstalling after an external wrap now discards that
wrapper instead of guessing whether it still chains to us -- a
deliberate, documented trade-off, since there is no safe way to tell
those two cases apart from the outside.

Also: window error/rejection listeners now catch exceptions from a
hostile e.reason the same way the console.error patch already did,
and the module doc comment now notes the known HMR buffer-orphan
wrinkle. Adds two tests covering the external-wrapper and
module-re-execution scenarios; both were mutation-verified to fail
against the prior implementation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:51:08 -07:00
shadowdaoandClaude Opus 5 9be71e8fd1 feat(site-builder): capture recent console errors for issue reports
Ring buffer of the most recent console.error/window-error messages
(20 max, 500 chars each, message text only) for Task 19's report
payload. installConsoleErrorBuffer() is idempotent via a marker
stamped on the patched console.error itself (not just a module-scoped
flag), so React 18 StrictMode double-invocation or HMR re-running this
module's top level can't wrap an already-patched console.error and
build a growing chain. The patch always chains to the original.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:37:32 -07:00
shadowdaoandClaude Opus 5 aba0d187d7 fix(site-builder): make Reset Entire Site's guard load-bearing in the handler
Two Important review findings on the previous commit (1a01834):

1. handleResetSite ran unconditionally -- the confirm button's `disabled`
   attribute was the only thing standing between a mismatched/empty typed
   value and a full site wipe. Extracted the match check into a single
   exported pure predicate, siteResetConfirmMatches(typed, domain), used
   for the button's disabled/cursor/opacity (previously three duplicated
   inline comparisons) AND as the first line of handleResetSite itself,
   which now returns early if it doesn't hold. An empty domain is rejected
   outright (`!!domain &&` short-circuits) so the guard holds even if the
   handler were ever reached with no configured domain, independent of the
   entry point being hidden.

2. The dialog said "design tokens" but resetToDefaults() also wipes
   headCode (analytics/search-console/third-party scripts) and favicon --
   neither is one of the 17 documented design properties, so a user had no
   reason to read them as included. Copy now names both explicitly.
   Re-verified every remaining claim in the paragraph against what the
   handler actually does (page/header/footer replacement, no undo, no
   publish call, images untouched, 30000ms auto-save) -- all still hold.

Verified load-bearing by temporarily reverting each guard in place (no git
stash -- shared across worktrees/sessions per review feedback) and
confirming the corresponding test fails: dropping the !!domain check broke
the empty-domain unit test; removing the handleResetSite check broke a new
test that invokes the confirm button's React onClick directly (bypassing
both the disabled attribute and react-dom's own disabled-click suppression,
which independent investigation confirmed blocks a plain DOM `.disabled =
false; .click()`/dispatchEvent bypass -- pulling onClick off the element's
stashed __reactProps$ key was the only way to actually exercise the
handler's own guard).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:30:20 -07:00
shadowdaoandClaude Opus 5 1a01834068 feat(site-builder): add domain-confirmed Reset Entire Site
Adds a danger-zone escape hatch below SiteDesignPanel's existing "Reset to
Defaults": blanks every page down to one empty Home, blanks the header and
footer, and resets all design tokens. Guarded by typing the exact site
domain to arm the confirm button.

The brief's setHeader('')/setFooter('') calls were wrong -- both take a
SerializedTreeNode (same tree shape as replaceAllPages), not a craft-state
string; passing '' would have hit treeToCraftState's sanitizeAiTree and
silently fallen back to a generic div-shaped empty canvas instead of a
proper header/footer. Built BLANK_HEADER_TREE/BLANK_FOOTER_TREE (tagged
header/footer) alongside the brief's page tree, and dropped the brief's
literal's extraneous flat-state fields (isCanvas/displayName/custom/hidden/
linkedNodes) that made it need an `as any` cast -- sanitizeAiTree/
flattenTreeForCraft only ever read type/props/nodes.

In standalone mode (no WHP_CONFIG) siteDomain is '', so the entire danger
zone -- not just the button -- is hidden behind `siteDomain &&`, closing off
the empty-string-trivially-matches guard bypass.

Dialog copy states the reset is undoable... is NOT undoable, and that
auto-save (confirmed exactly 30s via TopBar.tsx's setInterval) turns the
blank canvas into the saved draft shortly after, so no false safety-net
claim is made.

Verified load-bearing: reverted the implementation via git stash and
confirmed 3 of 4 new tests fail (the 4th, an absence-only standalone-mode
check, passed vacuously on first draft -- rewritten into a same-test
contrast against the non-standalone case, which does fail on revert).
Split into a second mock-free integration test file
(SiteDesignPanel.reset.integration.test.tsx) after vi.mock's file-scoped
hoisting made a same-file vi.doUnmock silently keep using the mocks --
it exercises the real PageProvider/SiteDesignProvider/treeToCraftState
pipeline end to end via the real editorHarness.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:17:53 -07:00
shadowdaoandClaude Opus 5 bfcf6278e9 feat(site-builder): add Reset Page to the Pages panel
Adds a "Reset to blank" control to each page row in PagesPanel, behind an
inline confirmation matching the existing delete-confirmation UI. Blanks
the target page's canvas to EMPTY_CANVAS (Task 8) via actions.deserialize.

Since deserialize() acts on the live Frame, resetting a page that isn't
on screen switches to it first (switchPage), then defers the blank via
its own setTimeout(0) -- same-delay setTimeout callbacks fire in
registration order, so switchPage's own deferred load (also setTimeout(0),
registered first) always resolves before the blank does. Verified this
ordering empirically by injecting the reversed-order regression and
confirming the new ordering-sensitive integration test catches it.

Ran the brief's undo-characterization test first: actions.deserialize() IS
recorded in this @craftjs/core version's undo stack, so the confirmation
dialog's "Ctrl+Z undoes this." claim is accurate and was kept.

The reset button lives only in the per-page action row (not the separate
Header/Footer zone-row block), verified structurally and by test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:02:59 -07:00
shadowdaoandClaude Opus 5 e5fd74d63d fix(site-builder): repair orphan nodes on initial page load too
useWhpApi's load() called actions.deserialize() directly on the first
page's stored craftState, bypassing repairOrphanNodes -- unlike
PageContext.loadState, which runs it on every subsequent page switch.
An orphaned node (unreachable from ROOT, invisible to Layers/selection)
in a saved project would get silently repaired on the next page switch
but not on the load that actually renders it first. Route the initial
deserialize through the same repair call, with the same console.warn,
so both paths behave identically.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 09:53:36 -07:00
shadowdaoandClaude Opus 5 cf38fdb245 feat(site-builder): array editors scroll to the item picked in Layers
Wires ArrayItemFieldsEditor and FeaturesEditor up to useLayerFocus() so
clicking a virtual row in the Layers tree scrolls the matching item's
card into view in the right-hand array editor. scrollIntoView is
optional-chained on both the queried element and the method itself so
a miss or an environment without it degrades silently.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 07:21:27 -07:00
shadowdaoandClaude Opus 5 2438777462 feat(site-builder): Layers shows array-prop items, unplaced nodes, and scrolls
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 07:15:17 -07:00
shadowdaoandClaude Opus 5 f9561c8c54 feat(site-builder): add LayerFocusContext for layers-to-array-editor focus
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 07:08:26 -07:00
shadowdaoandClaude Opus 5 f30fc6efec fix(site-builder): add Hero/CTA components to Layers virtual-rows registry
A grep across every component under src/components/ (not just the 12
files the original registry hardcoded) turns up three more leaf
components with the identical array-prop-as-content pattern: Hero
(HeroSimple.tsx), Call to Action (CallToAction.tsx) and CTA Section
(CTASection.tsx) all render a shared `ctas?: CtaButton[]` prop whose
items are `{ text, href, variant?, target? }`. Without this, a Hero's
CTA buttons still wouldn't appear in the Layers tree.

Verified displayName, prop name and label field against each
component's craft.props defaults and the shared CtaButton type in
sections/_cta-helpers.tsx -- all three matched exactly, no corrections
needed. A follow-up sweep for any further array-prop leaf components
found none: the only other array fields in the tree are nested one
level inside already-covered items (ContactFormField.options,
PricingPlan.features), not top-level component props.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 07:04:54 -07:00
shadowdaoandClaude Opus 5 eb4290a45e feat(site-builder): derive Layers rows from array-prop composites
FeaturesGrid, Tabs, Accordion, PricingTable, Testimonials, Gallery,
ContentSlider, NumberCounter, Menu, SocialLinks, Navbar and ContactForm
store their content in array props rather than Craft child nodes, so
the Layers tree showed nothing underneath them. This adds the pure
deriveVirtualRows() function and VIRTUAL_CHILD_PROPS registry the
Layers panel will consume in a later task.

Verified the registry against each component's actual item interface:
corrected Tabs (label field is `label`, not `title` -- TabItem has no
`title`) and Content Slider (label field is `heading`, not `title` --
Slide has no `title`). Both would have silently fallen back to
"Tab N" / "Slide N" for every existing site.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:59:23 -07:00
shadowdaoandClaude Opus 5 38c8d22e5d test(site-builder): cover loadState's orphan-repair wiring via PageProvider
Review found Task 8's prescribed test never mounts PageProvider, so it
never exercises loadState -- deleting the repairOrphanNodes call would
still leave that suite green. Adds a PageProvider-mounted test driving
switchPage into a page with a stored orphaned node, asserting on what
loadState hands to actions.deserialize and that console.warn fires.
Verified load-bearing: temporarily neutering the repair call fails the
new test (ROOT.nodes missing 'stray'), then restored.

Also documents the fallback-branch invariant that `fallback` must
always be a known-safe constant, per review.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:53:55 -07:00
shadowdaoandClaude Opus 5 9885b37af5 fix(site-builder): reattach unreachable nodes when loading a page
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:48:19 -07:00
shadowdaoandClaude Opus 5 86aacbe1a8 fix(site-builder): repair cyclic orphan clusters in repairOrphanNodes
Review found that a cluster of orphan nodes referencing only each other
(no member's parent points outside the orphan set) made the reattach
loop find zero tops and silently no-op, leaving the cluster unreachable
while reporting repaired: []. Replaced the single-pass reattach with a
loop that re-derives the unreachable set each round and force-reattaches
one representative when no ordinary top exists, guaranteeing
findUnreachableNodeIds is empty after repair. Adds 2-node/3-node cycle
and mixed ordinary-subtree-plus-cycle tests; the original 11 tests are
unchanged and still pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:43:46 -07:00
shadowdaoandClaude Opus 5 f0a1508acd feat(site-builder): add pure orphan-node detection and repair
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:36:39 -07:00
shadowdaoandClaude Opus 5 66db1db507 feat(site-builder): add insert/colour/format toolbar to the Edit HTML modal
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:31:55 -07:00
shadowdaoandClaude Opus 5 b670b436c3 fix(site-builder): stop CodeEditor fallback insert from being lost on CodeMirror mount
insertAtCursor's textarea-fallback branch advanced lastEmittedRef to the
post-insertion value. The mount effect's dynamic import() closes over
`value` as of initial render, so if CodeMirror finishes loading after a
fallback-mode insertion, it mounts with the pre-insertion doc. The only
repair mechanism -- the value-sync effect -- is gated on `value !==
lastEmittedRef.current`, so advancing that ref made the gate see them as
already equal and skip the repair, silently dropping the insertion.

Also clamps caretOffset to [0, text.length] defensively, and adds coverage
for a non-empty-selection replace and for the fallback-to-CodeMirror-mount
transition itself (using the real @codemirror/* packages, no mocks).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 06:26:27 -07:00
shadowdaoandClaude Opus 5 d89930e218 feat(site-builder): expose insertAtCursor/getValue handle on CodeEditor
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 19:24:29 -07:00
shadowdaoandClaude Opus 5 45ee004672 fix(site-builder): discriminate formatHtml whitespace by block/inline boundary, not newline
Round 3 fixed a phantom-space idempotency bug by dropping any boundary
whitespace containing a newline, but that also stripped ordinary
hand-wrapped text like "hello\n<strong>", merging words on a single pass --
directly contradicting this formatter's own "does not reflow text"
contract. The correct discriminator is what the whitespace borders, not
whether it contains a newline: a run between two inline-level things (text,
<strong>, <a>, ...) is always significant and must survive regardless of
newlines, while a run touching a block-tag boundary carries no rendered
meaning and is always dropped. Since this formatter's own emitted
indentation is only ever inserted next to a block tag, that rule also
resolves the original phantom-space bug without any newline special-casing.
tokenize() now peeks each upcoming tag's name once (reused for both the
preceding text run's decision and the tag's own processing) so pushTextToken
can see what's on both sides of a whitespace run.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 19:19:32 -07:00
shadowdaoandClaude Opus 5 536e4e9f86 fix(site-builder): make formatHtml close-tag mismatch recovery self-draining
Round 2's tag-name check on close popping fixed misattribution but could
wedge the stack permanently: a mismatch with a real, still-open ancestor
(e.g. an unclosed <p> before a later </div>, a normal optional-end-tag
slip) never drained, so everything after it inherited the stuck depth and
could print out of source order. Close handling now searches the whole
stack for a matching tag, not just the top; frames above a found match are
popped and implicitly closed (no fabricated close tag, just ending their
indentation) before the match itself closes normally. A close with no
match anywhere is still left in place untouched, since it has nothing to
pair with. Also fixes a related idempotency bug in text-run whitespace
collapsing surfaced while verifying this: boundary whitespace containing a
newline (formatter-introduced structural gap) is now dropped entirely
instead of being collapsed to a preserved space like same-line boundary
spaces are.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 19:10:25 -07:00
shadowdaoandClaude Opus 5 51f3fe81b6 fix(site-builder): make formatHtml quote- and raw-text-aware
Code review found two Important bugs from only <pre> being exempted from
the naive </> tag-boundary scan: a > inside a quoted attribute value split
tags and broke idempotency, and <script>/<style> (declared BLOCK_TAGS but
never given raw-text treatment) let JS/CSS < and > desync sibling nesting.
Adds a quote-aware tag-end scanner, generalizes verbatim handling to
<script>/<style>, and makes close-tag stack popping verify the tag name
before popping instead of blindly popping by position.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:59:57 -07:00
shadowdaoandClaude Opus 5 321a193b83 feat(site-builder): add dependency-free formatHtml prettifier
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:48:41 -07:00
shadowdaoandClaude Opus 5 4ac57e1c4c feat(site-builder): HTML blocks get a code-only style panel
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:42:28 -07:00
shadowdaoandClaude Opus 5 0d0d722dd7 refactor(site-builder): extract HtmlCodeField out of GenericPropsEditor
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:38:38 -07:00
shadowdaoandClaude Opus 5 a30e82accf fix(site-builder): HtmlBlock render stops applying style so editor matches published output
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:35:12 -07:00
shadowdaoandClaude Opus 5 6791345f77 docs: implementation plan for the five user-reported site-builder issues
23 TDD tasks across five phases: HTML block (render/export mismatch, code-only
panel, editor toolbar), tree integrity (orphan repair + Unplaced recovery),
reset page/site, Layers virtual rows for array-prop composites, and in-builder
issue reporting (endpoint, table, root-only admin page). Off-canvas drop
prevention is scoped as an investigation whose acceptance criterion is a
written mechanism, not a guessed fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:27:02 -07:00
shadowdaoandClaude Opus 5 fb68fa6485 docs: design spec for five user-reported site-builder issues
Covers off-canvas drops (reachability invariant: prevent, repair on load,
recover via Layers), the HTML block's dead style props (render/export
mismatch plus a code-editor toolbar), page/site reset, Layers virtual rows
for array-prop composites, and in-builder issue reporting backed by a new
whp.site_builder_reports table and a root-only admin page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 10:39:00 -07:00
shadowdaoandClaude Opus 5 c6840db0bb chore(branding): rename "Web Hosting Panel" to "Web Hosting Platform"
Matches the rename in the whp repo now that the Web Hosting Platform
domain is registered. Doc line and a JS comment; no behaviour change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 14:17:27 -07:00
jknapp f5d2a23a5f Merge PR #26: surface publish warnings in the editor 2026-07-16 12:34:32 +00:00
shadowdaoandClaude Opus 4.8 c712a69c4a test(topbar): cover publish() warnings wiring into PublishWarnings banner
PublishWarnings.tsx had unit tests for the presentational banner, but
nothing asserted that result.warnings from publish() actually flows
through TopBar's handlePublish into it. That 3-line seam is exactly what
this feature exists to fix -- the backend always returned warnings, and
TopBar discarded them by only checking result.success, so the
contact-form-relay warning was dead code for its entire life.

Adds TopBar.test.tsx asserting: warnings render after a successful
publish with warnings, no banner renders when warnings is absent, a
warning doesn't present as a publish failure, warnings survive the 3s
"Published" flash (fake timers, advanced past 3000ms), and a fresh
publish clears stale warnings from the previous one.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 22:12:31 -07:00
shadowdaoandClaude Opus 4.8 d460e8ac33 topbar: surface publish warnings instead of discarding them
handlePublish's JSON response has always included a `warnings` array
(e.g. the contact-form relay's "submissions will not be delivered"
notice), but nothing in the editor ever read it. Adds a PublishWarnings
banner, held in its own state independent of the 3s publishStatus
flash so the customer has time to read it, rendered in both the
desktop and mobile TopBar branches.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 21:52:11 -07:00
jknapp 2b1569202a Merge PR #25: bounce + image crop/resize fix 2026-07-14 23:07:58 +00:00
shadowdaoandClaude Opus 4.8 5c44dd545c fix(site-builder): bounce stays visible + springier; image/video crop fills (cover) + resize shrinks footprint
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 16:04:50 -07:00
jknapp 2ac62c4e9e Merge PR #24: fix animation delay unit 2026-07-14 19:36:51 +00:00
shadowdaoandClaude Opus 4.8 25dfcbb725 fix(site-builder): coerce bare-number animation delay to a valid CSS time (2 -> 2s)
data-animation-delay is stored as a plain seconds string (e.g. '2'); the reveal
script assigned it raw to el.style.animationDelay, which is invalid CSS and no-ops.
Suffix 's' onto bare numbers (leaving '2s'/'200ms' alone) so entrance-animation
delays actually apply. Backend generateCompiledHTML gets the byte-identical change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 12:34:51 -07:00
jknapp 9bf78fd72d Merge PR #23: fix entrance-animation output 2026-07-14 19:16:59 +00:00
shadowdaoandClaude Opus 4.8 2dcc2b4d21 fix(site-builder): entrance-animation reveal script survives Preview + well-formed void-tag attrs + no-JS fallback
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 12:12:01 -07:00
jknapp 4e0fc78a30 Merge PR #22: enh pages productivity + cross-page clipboard 2026-07-14 14:48:25 +00:00
shadowdaoandClaude Opus 4.8 85dfe181aa fix(pages): duplicatePage must save outgoing active canvas before teardown (avoid dropping live edits)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:47:44 -07:00
shadowdaoandClaude Opus 4.8 a698f014b0 feat(site-builder): page duplicate/reorder/set-landing + fix cross-page node copy/paste
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:36:00 -07:00
jknapp 204ea5e078 Merge PR #21: enh output/seo/tokens (frontend) 2026-07-14 14:21:10 +00:00
shadowdaoandClaude Opus 4.8 0291ddce9a feat(site-builder): per-page SEO meta + favicon + design-token CSS-var wiring + published-output a11y/perf
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 07:14:56 -07:00
jknapp f7da654c11 Merge PR #20: enh nav 2026-07-14 13:58:11 +00:00
jknapp d6666f6f79 Merge PR #19: enh containers 2026-07-14 13:56:11 +00:00
jknapp 6e628d68dd Merge PR #18: enh sections 2026-07-14 13:54:52 +00:00
jknapp 8f17b74e2b Merge PR #17: enh forms 2026-07-14 13:49:57 +00:00
shadowdaoandClaude Opus 4.8 54572f648a feat(builder): nav/menu link-to-page picker, page sync, download attr, box-model rollout
NavStylePanel (Navbar/Menu/Logo/Footer):
- LinkPicker: dropdown of the site's pages (read-only via usePages()) plus
  manual URL / #anchor / tel: / mailto: entry, wired into every link-href
  field (standalone Logo href, Navbar logoUrl, Navbar/Menu link items).
- "Sync links with Pages" button in the Links section: repopulates the
  links array from the current pages list (label = page name, href = '/'
  for the landing page else '/{slug}'), preserving any existing CTA link.
  Regression-fix vs the legacy GrapesJS builder, which had this.
- `download` checkbox per link (Navbar/Menu links, standalone Logo href)
  emits the `download` attribute on export for links to files.
- Links/Colors sections now gate on the component actually carrying a
  `links`/color prop, so Footer (no links array) no longer shows a dead
  "Add Link" editor.
- Box-model (Margin/Padding via SpacingControl, Border & Effects via
  BorderControl + box-shadow presets + opacity), AnimationControl, and
  VisibilityControl added for all four owned components, backed by new
  animation/animationDelay/hideOnDesktop/hideOnTablet/hideOnMobile props
  (with blank/default values in each component's .craft.props).

Tests: NavStylePanel.test.tsx (new, 17 tests: LinkPicker modes, sync
preserves CTA, download toggle, box-model/animation/visibility wiring) +
extended Navbar/Menu/Logo/Footer .toHtml.test.ts (download attribute,
craft.props defaults). Full suite: 683/683 passing. `npm run build` green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:47:59 -07:00
shadowdaoandClaude Opus 4.8 8bf525c600 feat(builder): surface hidden section/pricing/social props + box-model rollout
SectionTypePanel (Accordion/Tabs/Testimonials/Countdown/NumberCounter/
CTASection/CallToAction/FeaturesGrid), PricingStylePanel, and
SocialStylePanel all gain a Spacing & Border section (margin/padding
per-side, border, box-shadow, opacity), an Animation section, and a
Visibility section, wired to the shared SpacingControl/BorderControl/
AnimationControl/VisibilityControl.

PricingTable's per-card colors (cardBg/textColor/subColor/featColor/
checkColor/btnBg/btnColor) were previously hard-coded literals computed
from featuredBg inside toHtml -- promoted to real optional props (each
falling back to the exact prior literal when unset) and exposed via
ColorPickerField in PricingStylePanel.

SocialStylePanel now exposes SocialLinks' iconShape/gap (already-built
props with no control), plus Icon's bgColor/bgShape/bgSize/link and
StarRating's filledColor/emptyColor, which the panel's generic
iconBgColor/starColor checks never matched since those aren't Icon's or
StarRating's real prop names.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:47:58 -07:00
jknapp d07bc7789d Merge PR #16: enh code editor 2026-07-14 13:47:46 +00:00
jknapp b03425ac39 Merge PR #15: enh text+button 2026-07-14 13:46:08 +00:00
shadowdaoandClaude Opus 4.8 5b19ae97af feat(builder): FORMS package -- field editor, functional Subscribe/Search, box-model+anim rollout
- FormStylePanel: ContactForm field editor (add/remove/reorder via
  ArrayPropEditor + manual move up/down) covering label/name/placeholder/
  type (full sanitizeInputType allowlist + textarea/select)/required/
  options.
- SubscribeForm.toHtml: was a dead `<form method="POST">` with no action at
  all -- wired through the same relayFormWiring contract as ContactForm/
  FormContainer so a recipientEmail makes it actually submit (marker +
  placeholder action + honeypot), falling back to action="#" otherwise.
- SearchBar: was purely decorative (no action/method/input name) -- now a
  real GET form (configurable target, default "/") with input name="q",
  safeUrl-guarded against javascript:/vbscript: breakout.
- Box-model (margin/padding per-side, border, shadow, opacity), entrance
  animation, and hide-on-device controls added to FormStylePanel and
  rolled out (blank/false craft.props defaults) across ContactForm,
  FormContainer, InputField, TextareaField, FormButton, SubscribeForm,
  SearchBar. No toHtml changes needed for animation/visibility --
  html-export.ts's buildDataAttrs() already emits data-animation/
  data-hide-* generically from these prop names.
- Extended toHtml tests for all 7 components: field-type rendering
  (incl. textarea/select), type-attribute XSS sanitization, relay/GET
  functional wiring, box-model style passthrough, craft.props defaults.

npx vitest run: 689/689 passed. npm run build: green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:44:21 -07:00
shadowdaoandClaude Opus 4.8 88df4f2888 feat(builder): CodeMirror 6 code editor for HTML/CSS/JS with lazy loading
Replaces the plain single-line input (HtmlBlock's `code` prop, via
GenericPropsEditor) and the plain <textarea> (HeadCodeModal's site-wide
head code) with a proper syntax-highlighted, tab-completing code editor.

- New src/ui/CodeEditor.tsx: reusable CodeMirror 6 editor (state/view/
  commands/autocomplete/language/lang-html/lang-css/lang-javascript/
  theme-one-dark). All @codemirror/* packages are pulled in via a single
  dynamic import() inside the component so they land in separate lazy
  chunks instead of the main bundle -- confirmed via `npm run build`:
  main editor.js grew by only ~5.5KB (657KB -> 663KB raw) while ~570KB of
  CodeMirror source split into index*.js chunks that only load when a
  code editor modal is actually opened. While that import is in flight,
  or if it ever fails, the component renders a plain <textarea> so typing
  never breaks.
- GenericPropsEditor.tsx: special-cases the `code` prop (used only by
  HtmlBlock today) into an "Edit HTML" button that opens the CodeEditor
  in a modal (language="html"), instead of rendering it as a single-line
  text input alongside the component's other string props.
- HeadCodeModal.tsx: swaps its <textarea> for CodeEditor (language="html"
  -- head code is HTML with embedded <script>/<style>), keeping the
  existing SiteDesignContext.updateDesign({ headCode }) wiring.

GuidedStyles.tsx untouched: HtmlBlock's displayName ("HTML") already
matches GuidedStyles' `isUtility` regex and routes to GenericPropsEditor,
so no dispatcher change was needed.

HtmlBlock.tsx untouched: purifyHtml/toHtml sanitization is unchanged, as
specified. Skipped the optional AnimationControl/VisibilityControl
addition -- HtmlBlock has no dedicated StylePanel (it shares
GenericPropsEditor with Divider/Spacer/every unmatched type), and doing
it well would mean adding real Animation/Visibility widgets to that
shared editor for every consumer, which is a bigger change than "trivial"
for this package's scope.

Tests: CodeEditor.test.tsx and HeadCodeModal.test.tsx both exploit the
fact that dynamic import() always resolves on a later microtask, so
asserting against the DOM immediately after the initial synchronous
render deterministically exercises the <textarea> fallback path (value
display, onChange wiring, language prop plumbing) without needing to
mock @codemirror/*.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:42:59 -07:00
shadowdaoandClaude Opus 4.8 e1b4ab735c feat(builder): text+button package -- typography depth, button target/hover, box-model+anim/vis rollout
- TextStylePanel (Heading/TextBlock): line-height/letter-spacing presets,
  text-transform (none/uppercase/lowercase/capitalize), italic + underline
  toggles (fontStyle/textDecoration), and a custom NumericUnitInput
  font-size alongside the existing preset row. All write to component
  `style`; no toHtml changes needed (style already flows through
  cssPropsToString for both components).
- ButtonStylePanel/ButtonLink: "Open in new tab" checkbox writes the
  existing `target` prop ('_self'/'_blank' -- toHtml already emitted
  rel="noopener noreferrer" for _blank). New Hover State section
  (hoverBg/hoverColor via ColorPickerField) renders a scoped
  `<style>.btn_<hash>:hover{...}</style>` block before the `<a>` in
  toHtml, scoped per-node via scopeId (same pattern as Navbar/Menu) so
  two buttons on one page don't collide; both values sanitized through
  cssValue against <style>-element breakout. Editor canvas gets a live
  hover preview via onMouseEnter/onMouseLeave local state (mirrors Menu's
  approach), since there's no way to preview a CSS :hover rule directly
  on an inline-styled React element.
- Heading/TextBlock/ButtonLink: added margin(per-side)/padding(per-side,
  Text only)/border/box-shadow/opacity style defaults + AnimationControl/
  VisibilityControl-backed animation/animationDelay/hideOnDesktop/
  hideOnTablet/hideOnMobile props, each panel gaining collapsible
  Spacing / Border & Effects / Animation & Visibility sections. Button
  keeps its existing padding-shorthand preset row rather than adding a
  redundant per-side padding control; only margin got the new
  per-side SpacingControl.
- Tests: extended all three *.toHtml.test.ts files -- typography style
  emission (line-height/letter-spacing/text-transform/font-style/
  text-decoration/custom font-size), button target+rel, scoped hover
  style emission + two adversarial style-breakout cases (</style><script>
  and rule-injection via `;}selector{`), and craft.props assertions for
  every new prop on all three components. 674 tests green, tsc + vite
  build clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:41:53 -07:00
jknapp ff1e8fc096 Merge PR #14: enh media package 2026-07-14 13:37:55 +00:00
shadowdaoandClaude Opus 4.8 0419291259 feat(builder): media package -- image crop/perf, video size+picker, gallery cols/lightbox, box-model+anim/vis rollout
- ImageBlock/ImageStylePanel: SizeControl width(absorbs old maxWidth
  presets)/height, AspectRatioControl + OBJECT_FIT grid + FocalPointGrid for
  CSS framing crop (aspect-ratio/object-fit/object-position on the <img>).
  Exported <img> always gets loading="lazy" decoding="async", plus width/
  height attrs when the style has a plain px length (pxAttr helper).
- VideoBlock/MediaStylePanel: Video URL text input replaced with
  AssetPicker(mediaType="video") writing videoUrl (paste-URL still handles
  YouTube/Vimeo, upload/browse handle files). Added SizeControl(width) +
  AspectRatioControl so the video frame honors real size/aspect instead of
  a hardcoded 16:9 (padding-bottom hack replaced with CSS aspect-ratio).
  New optional `poster` prop (image AssetPicker) + preload="metadata" on
  file-type <video>.
- Gallery: surfaced the existing-but-unexposed `columns` and `lightbox`
  props with panel controls.
- All 5 owned components (ImageBlock, VideoBlock, Gallery, ContentSlider,
  MapEmbed): added margin/padding (per-side)/border/box-shadow/opacity style
  defaults + AnimationControl/VisibilityControl-backed animation/
  animationDelay/hideOnDesktop/hideOnTablet/hideOnMobile props. New shared
  mediaBoxModel.tsx (package-local, not shared.tsx) DRYs the box-model +
  border/effects + animation/visibility panel sections across
  ImageStylePanel and MediaStylePanel.
- Tests: extended *.toHtml.test.ts for all 5 components (crop/perf attrs,
  video size/aspect/poster/preload, gallery columns/lightbox, box-model
  style emission, craft.props presence) + new MediaStylePanel.video.test.tsx
  verifying the AssetPicker wiring writes videoUrl/poster and the video-only
  size controls are gated on videoUrl. 694 tests green, tsc + vite build
  clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:30:50 -07:00
558 changed files with 74527 additions and 2716 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
cloud-hosting-platform/site-builder
+1 -1
View File
@@ -2,7 +2,7 @@
## Overview
This site builder integrates with WHP (Web Hosting Panel) to provide users with a visual site building interface. Users can create HTML pages using a drag-and-drop editor and save them directly to their web hosting account.
This site builder integrates with WHP (Web Hosting Platform) to provide users with a visual site building interface. Users can create HTML pages using a drag-and-drop editor and save them directly to their web hosting account.
## Architecture
+25
View File
@@ -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
View File
@@ -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>
+7
View File
@@ -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",
+15
View File
@@ -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"
},
+24
View File
@@ -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>,
);
};
+63
View File
@@ -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);
+15
View File
@@ -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,
});
}
+317
View File
@@ -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))) };
};
+171
View File
@@ -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);
});
+119
View File
@@ -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);
+175
View File
@@ -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'));
+25
View File
@@ -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: {},
};
}
+106
View File
@@ -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}` };
}
+460
View File
@@ -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);
+123
View File
@@ -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);
+51
View File
@@ -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;
+179
View File
@@ -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);
+126
View File
@@ -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),
});
+283
View File
@@ -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);
+73
View File
@@ -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 });
}
+131
View File
@@ -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);
+47
View File
@@ -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 };
+193
View File
@@ -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&amp;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;
}
+82
View File
@@ -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);
+177
View File
@@ -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);
+392
View File
@@ -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);
+493
View File
@@ -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);
+9
View File
@@ -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;
+233
View File
@@ -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();
}
+64
View File
@@ -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)),
})),
};
}
+75
View File
@@ -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);
});
});
+40
View File
@@ -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
View File
@@ -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>
);
};
@@ -52,3 +52,86 @@ describe('ButtonLink.toHtml text escaping (attacker-controlled `text` prop)', ()
expect(html).toContain('>Click Me</a>');
});
});
describe('ButtonLink.toHtml hover state (scoped <style> block)', () => {
test('no hover props -- no <style> block, no class added', () => {
const { html } = toHtml({ href: '#', text: 'x' }, '', 'node-1');
expect(html).not.toContain('<style>');
expect(html).not.toContain('class=');
});
test('hoverBg/hoverColor emit a scoped :hover rule scoped to the node id', () => {
const { html } = toHtml({ href: '#', text: 'x', hoverBg: '#111111', hoverColor: '#eeeeee' }, '', 'node-42');
expect(html).toMatch(/<style>\.btn_[a-z0-9]+:hover\{background-color:#111111;color:#eeeeee\}<\/style>/);
expect(html).toMatch(/class="btn_[a-z0-9]+"/);
});
test('two different node ids produce different scope classes (no collision)', () => {
const a = toHtml({ href: '#', text: 'x', hoverBg: '#111111' }, '', 'node-a').html;
const b = toHtml({ href: '#', text: 'x', hoverBg: '#111111' }, '', 'node-b').html;
const scopeOf = (html: string) => html.match(/btn_[a-z0-9]+/)?.[0];
expect(scopeOf(a)).toBeTruthy();
expect(scopeOf(a)).not.toBe(scopeOf(b));
});
test('an XSS breakout attempt in hoverBg cannot close the <style> element', () => {
const malicious = '</style><script>alert(1)</script>';
const { html } = toHtml({ href: '#', text: 'x', hoverBg: malicious }, '', 'node-1');
expect(html).not.toContain('</style><script>');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a rule-breakout attempt in hoverColor cannot inject a second selector/rule', () => {
const malicious = 'red;}body{background:red';
const { html } = toHtml({ href: '#', text: 'x', hoverColor: malicious }, '', 'node-1');
expect(html).not.toContain('}body{');
expect(html).not.toContain(';}');
// The whole export is still exactly one <style> element -- no new rule
// or element was opened by the malicious value.
expect((html.match(/<style>/g) || []).length).toBe(1);
expect((html.match(/<\/style>/g) || []).length).toBe(1);
});
});
describe('ButtonLink.craft.props exposes target + hover + box-model + animation/visibility', () => {
test('target defaults to _self, hoverBg/hoverColor blank', () => {
const props = (ButtonLink as any).craft.props;
expect(props.target).toBe('_self');
expect(props.hoverBg).toBe('');
expect(props.hoverColor).toBe('');
});
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
const props = (ButtonLink as any).craft.props;
expect(props.animation).toBe('');
expect(props.animationDelay).toBe('0');
expect(props.hideOnDesktop).toBe(false);
expect(props.hideOnTablet).toBe(false);
expect(props.hideOnMobile).toBe(false);
});
test('style carries blank/default box-model keys', () => {
const style = (ButtonLink as any).craft.props.style;
expect(style).toHaveProperty('marginTop');
expect(style.border).toBe('none');
expect(style.boxShadow).toBe('none');
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);
});
});
+56 -5
View File
@@ -1,13 +1,25 @@
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 { escapeHtml, escapeAttr, safeUrl, cssValue, scopeId } from '../../utils/escape';
import { tokenRef } from '../../utils/tokens';
interface ButtonLinkProps {
text?: string;
href?: string;
target?: '_self' | '_blank';
style?: CSSProperties;
/** Background color applied on `:hover` via a scoped `<style>` block
* (editor preview does not show hover state -- only the published
* export). Blank means "no hover background override". */
hoverBg?: string;
/** Text color applied on `:hover`, same scoped `<style>` block. */
hoverColor?: string;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const ButtonLink: UserComponent<ButtonLinkProps> = ({
@@ -15,6 +27,8 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
href = '#',
target = '_self',
style = {},
hoverBg = '',
hoverColor = '',
}) => {
const {
connectors: { connect, drag },
@@ -23,6 +37,8 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
selected: node.events.selected,
}));
const [hovered, setHovered] = React.useState(false);
return (
<a
ref={(ref: HTMLAnchorElement | null) => { if (ref) connect(drag(ref)); }}
@@ -32,12 +48,16 @@ export const ButtonLink: UserComponent<ButtonLinkProps> = ({
// Prevent navigation inside editor
e.preventDefault();
}}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
style={{
display: 'inline-block',
textDecoration: 'none',
cursor: 'pointer',
outline: selected ? '2px solid #3b82f6' : 'none',
...style,
...(hovered && hoverBg ? { backgroundColor: hoverBg } : {}),
...(hovered && hoverColor ? { color: hoverColor } : {}),
}}
>
{text}
@@ -53,15 +73,25 @@ ButtonLink.craft = {
text: 'Click Me',
href: '#',
target: '_self',
hoverBg: '',
hoverColor: '',
style: {
backgroundColor: '#3b82f6',
color: '#ffffff',
backgroundColor: tokenRef('primary'),
color: tokenRef('bg'),
padding: '12px 24px',
borderRadius: '8px',
fontWeight: '600',
fontSize: '16px',
border: 'none',
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
boxShadow: 'none',
opacity: '1',
},
animation: '',
animationDelay: '0',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -72,7 +102,7 @@ ButtonLink.craft = {
/* ---------- HTML export ---------- */
(ButtonLink as any).toHtml = (props: ButtonLinkProps, _childrenHtml: string) => {
(ButtonLink as any).toHtml = (props: ButtonLinkProps, _childrenHtml: string, nodeId?: string) => {
const styleStr = cssPropsToString({
display: 'inline-block',
textDecoration: 'none',
@@ -80,7 +110,28 @@ ButtonLink.craft = {
});
const escapedText = escapeHtml(props.text || '');
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
// Scoped hover style -- same pattern as Navbar/Menu: a deterministic,
// per-node class (via scopeId) avoids two ButtonLink instances on the
// same page colliding on a shared `.btn-link:hover` rule. hoverBg/
// hoverColor are sanitized through cssValue -- they land inside a
// `<style>` element, the worst-case XSS sink (an unescaped `<`/`>` or
// `{`/`}` could close the rule/element and open a `<script>`).
const hoverBg = cssValue(props.hoverBg);
const hoverColor = cssValue(props.hoverColor);
let hoverCss = '';
let cls = '';
if (hoverBg || hoverColor) {
const scope = scopeId(nodeId, (props.href || '') + (props.text || ''), 'btn');
cls = ` class="${scope}"`;
const decls = [
hoverBg ? `background-color:${hoverBg}` : '',
hoverColor ? `color:${hoverColor}` : '',
].filter(Boolean).join(';');
hoverCss = `<style>.${scope}:hover{${decls}}</style>`;
}
return {
html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
html: `${hoverCss}<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${cls}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
};
};
@@ -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);
});
});
+4 -3
View File
@@ -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,
});
@@ -20,3 +20,24 @@ describe('Footer.toHtml text escaping (attacker-controlled `text` prop)', () =>
expect(html).toContain('© 2026 MySite. All rights reserved.');
});
});
describe('Footer (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Footer as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
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());
});
});
+14 -2
View File
@@ -1,11 +1,17 @@
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 {
text?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
export const Footer: UserComponent<FooterProps> = ({
@@ -87,11 +93,17 @@ 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',
},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
},
rules: {
canDrag: () => true,
@@ -56,3 +56,108 @@ describe('Heading.toHtml text escaping (attacker-controlled `text` prop)', () =>
expect(html).toBe('<h2>Hello world</h2>');
});
});
describe('Heading.toHtml typography depth (line-height/letter-spacing/transform/style/decoration)', () => {
test('line-height, letter-spacing, text-transform all flow into the style attribute', () => {
const { html } = toHtml({
text: 'x',
level: 'h2',
style: { lineHeight: '1.25', letterSpacing: '0.05em', textTransform: 'uppercase' },
}, '');
expect(html).toContain('line-height:1.25');
expect(html).toContain('letter-spacing:0.05em');
expect(html).toContain('text-transform:uppercase');
});
test('italic + underline toggles emit font-style and text-decoration', () => {
const { html } = toHtml({
text: 'x',
level: 'h2',
style: { fontStyle: 'italic', textDecoration: 'underline' },
}, '');
expect(html).toContain('font-style:italic');
expect(html).toContain('text-decoration:underline');
});
test('a custom font-size (not one of the presets) still flows through', () => {
const { html } = toHtml({ text: 'x', level: 'h2', style: { fontSize: '42px' } }, '');
expect(html).toContain('font-size:42px');
});
});
describe('Heading.craft.props exposes the box-model + animation/visibility rollout', () => {
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
const props = (Heading as any).craft.props;
expect(props.animation).toBe('');
expect(props.animationDelay).toBe('0');
expect(props.hideOnDesktop).toBe(false);
expect(props.hideOnTablet).toBe(false);
expect(props.hideOnMobile).toBe(false);
});
test('style carries blank/default box-model + typography-depth keys', () => {
const style = (Heading as any).craft.props.style;
expect(style).toHaveProperty('marginTop');
expect(style).toHaveProperty('paddingTop');
expect(style).toHaveProperty('lineHeight');
expect(style).toHaveProperty('letterSpacing');
expect(style).toHaveProperty('textTransform');
expect(style.border).toBe('none');
expect(style.boxShadow).toBe('none');
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&lt;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 &lt;copy&gt;</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="jav&#x61;script: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');
});
});
+29 -39
View File
@@ -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,14 +67,30 @@ 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: '',
textTransform: '' as CSSProperties['textTransform'],
fontStyle: '' as CSSProperties['fontStyle'],
textDecoration: '',
marginTop: '', marginRight: '', marginLeft: '',
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
border: 'none',
boxShadow: 'none',
opacity: '1',
},
animation: '',
animationDelay: '0',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -111,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}>` };
};
@@ -0,0 +1,51 @@
import { describe, test, expect, vi } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
vi.mock('@craftjs/core', () => ({
useNode: (collect?: (node: any) => any) => {
const node = { events: { selected: false } };
return {
connectors: { connect: (el: any) => el, drag: (el: any) => el },
actions: { setProp: vi.fn() },
...(collect ? collect(node) : {}),
};
},
}));
import { HtmlBlock } from './HtmlBlock';
let container: HTMLDivElement;
let root: Root;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
describe('HtmlBlock render ignores the style prop (matches toHtml)', () => {
test('a stored backgroundColor/color/padding is NOT applied to the wrapper', () => {
render(
React.createElement(HtmlBlock as any, {
code: '<p>hello</p>',
style: { backgroundColor: 'rgb(255, 0, 0)', color: 'rgb(0, 0, 255)', padding: '40px' },
}),
);
const wrapper = container.firstElementChild as HTMLElement;
expect(wrapper.style.backgroundColor).toBe('');
expect(wrapper.style.color).toBe('');
expect(wrapper.style.padding).toBe('');
});
test('the editor affordances survive: minHeight is kept, content still renders', () => {
render(React.createElement(HtmlBlock as any, { code: '<p>hello</p>', style: {} }));
const wrapper = container.firstElementChild as HTMLElement;
expect(wrapper.style.minHeight).toBe('40px');
expect(wrapper.innerHTML).toContain('hello');
});
});
@@ -0,0 +1,332 @@
import { describe, test, expect } from 'vitest';
import { purifyHtml } from './HtmlBlock';
// Vite/Vitest `?raw` import -- ships the exact bytes of the file as a
// string, declared by node_modules/vite/client.d.ts. This is a checked-in
// copy of the reference acceptance fixture used for Task 24 (widening the
// Custom HTML block's sanitiser allow-list); keep it byte-identical to the
// external fixture used to drive this task so these tests cannot silently
// drift from the thing they are supposed to be testing against.
import fixtureHtml from './__fixtures__/html-block-test-body.html?raw';
/**
* Task 24: the site owner tested a broad HTML fixture against the shipped
* sanitiser config and found 38% of it silently deleted -- merged table
* cells collapsing (colspan/rowspan/scope stripped), <dl>/<sub>/<details>/
* inline <svg>/<video>/<audio> dropped wholesale, lang/dir/role stripped
* (breaking RTL rendering), <ol start/reversed> flattened. The fix widens
* ALLOWED_TAGS/ALLOWED_ATTR in HtmlBlock.tsx. These tests run the *actual*
* reference fixture through the *actual* purifyHtml() and assert the
* previously-broken constructs now survive with their meaningful
* attributes intact, while re-confirming (with attack payloads spliced
* into the newly-widened surface -- forms, media, inline svg) that the
* four non-negotiable security properties still hold.
*/
describe('purifyHtml -- Task 24 fixture regression (formerly-dropped constructs survive)', () => {
const out = purifyHtml(fixtureHtml);
test('table merged cells keep colspan/rowspan/scope', () => {
expect(out).toContain('<td colspan="2">');
expect(out).toContain('<td rowspan="2">');
expect(out).toContain('<th scope="col">');
expect(out).toContain('<th scope="row">');
});
test('definition list keeps its dl/dt/dd structure (was flattened to "TermDef")', () => {
expect(out).toMatch(/<dl>[\s\S]*<dt>Term one<\/dt>[\s\S]*<dd>Definition of the first term\.<\/dd>[\s\S]*<\/dl>/);
});
test('menu list survives with nested buttons', () => {
expect(out).toMatch(/<menu>[\s\S]*<button type="button">Copy<\/button>[\s\S]*<\/menu>/);
});
test('sub/sup survive (was flattened to "H2O")', () => {
expect(out).toContain('H<sub>2</sub>O');
expect(out).toContain('x<sup>2</sup>');
});
test('details/summary survive with the open attribute (was flattened)', () => {
expect(out).toContain('<summary>Collapsed disclosure</summary>');
expect(out).toContain('<details open="">');
});
test('hgroup survives', () => {
expect(out).toMatch(/<hgroup>[\s\S]*<h2>Grouped heading<\/h2>/);
});
test('inline svg survives with its shape children and role/aria-label (was deleted entirely)', () => {
expect(out).toMatch(/<svg[^>]*role="img"[^>]*aria-label="Two shapes"[^>]*>/);
expect(out).toMatch(/<rect[^>]*fill="none"[^>]*stroke="currentColor"[^>]*>/);
expect(out).toMatch(/<circle[^>]*cx="135"[^>]*cy="45"[^>]*r="40"[^>]*>/);
expect(out).toMatch(/<text[^>]*text-anchor="middle"[^>]*>svg<\/text>/);
});
test('picture/source with media+srcset survive', () => {
expect(out).toContain('<source media="(min-width: 800px)" srcset="wide.png">');
expect(out).toContain('<source media="(min-width: 400px)" srcset="medium.png">');
});
test('video/audio survive with source/track children (was deleted entirely)', () => {
expect(out).toMatch(/<video[^>]*controls=""[^>]*poster="poster\.jpg"[^>]*>/);
expect(out).toContain('<source src="clip.webm" type="video/webm">');
expect(out).toContain('<track kind="captions" src="captions.vtt" srclang="en" label="English">');
expect(out).toMatch(/<audio[^>]*controls=""[^>]*>/);
});
test('canvas survives with its fallback text', () => {
expect(out).toContain('<canvas width="200" height="60">Canvas fallback text</canvas>');
});
test('mark/small/del/ins survive as distinct elements (was flattened to "msdi")', () => {
expect(out).toContain('<mark>mark</mark>');
expect(out).toContain('<small>small</small>');
expect(out).toContain('<del>del</del>');
expect(out).toContain('<ins>ins</ins>');
});
test('lang/dir preserved for RTL text (was stripped, breaking Arabic/Hebrew rendering)', () => {
expect(out).toContain('lang="ar" dir="rtl"');
expect(out).toContain('lang="he" dir="rtl"');
});
test('role attribute preserved alongside aria-* (role was stripped)', () => {
expect(out).toMatch(/<nav aria-label="Primary">/);
expect(out).toMatch(/role="img"/);
});
test('ol start/reversed preserved (was flattened to plain <ol>)', () => {
expect(out).toContain('<ol start="5" reversed="">');
});
test('text semantics survive: abbr/cite/q/time/data/kbd/samp/var/dfn/address/bdi/bdo/ruby', () => {
expect(out).toContain('<abbr title="HyperText Markup Language">HTML</abbr>');
expect(out).toContain('<kbd>Ctrl</kbd>');
expect(out).toContain('<samp>output text</samp>');
expect(out).toContain('<var>variable</var>');
expect(out).toContain('<dfn>definition term</dfn>');
expect(out).toContain('<address>');
expect(out).toContain('<bdi>');
expect(out).toContain('<bdo dir="rtl">');
expect(out).toContain('<ruby>');
expect(out).toContain('<rt>kan</rt>');
expect(out).toContain('<time datetime="2026-08-09">');
expect(out).toContain('<data value="42">');
});
test('wbr survives (word-break opportunity)', () => {
expect(out).toContain('super<wbr>cali<wbr>fragilistic');
});
test('hidden attribute survives', () => {
expect(out).toContain('<p hidden="">');
});
test('forms survive end-to-end: fieldset/legend/label/select/optgroup/option/textarea/datalist/output/progress/meter', () => {
expect(out).toContain('<form action="#" method="get">');
expect(out).toContain('<fieldset>');
expect(out).toContain('<legend>Text inputs</legend>');
expect(out).toContain('<label for="f-text">Text</label>');
expect(out).toContain('<input id="f-text" name="text" type="text" placeholder="Placeholder" value="Prefilled">');
expect(out).toContain('<input id="f-email" type="email" required="">');
expect(out).toContain('<input id="f-num" type="number" min="0" max="100" step="5" value="25">');
expect(out).toContain('<input id="f-ro" type="text" value="read only" readonly="">');
expect(out).toContain('<input id="f-dis" type="text" value="disabled" disabled="">');
expect(out).toContain('<input type="checkbox" name="c" value="1" checked="">');
expect(out).toContain('<select id="f-select" name="select">');
expect(out).toContain('<optgroup label="Group one">');
expect(out).toContain('<option value="1" selected="">One</option>');
expect(out).toContain('<select id="f-multi" multiple="" size="4">');
expect(out).toContain('<datalist id="suggestions">');
expect(out).toContain('<textarea id="f-area" rows="4" cols="40">');
expect(out).toContain('<output name="result" for="f-num f-range">');
expect(out).toContain('<progress id="f-prog" value="0.6">');
expect(out).toContain('<meter id="f-meter" min="0" max="100" low="30" high="80" optimum="90" value="72">');
expect(out).toContain('<button type="submit">Submit</button>');
});
test('bug fix: <select size> and <meter low/high/optimum> survive (both tags were already allowed, only these four attrs were missing)', () => {
expect(out).toContain('<select id="f-multi" multiple="" size="4">');
expect(out).toContain('low="30" high="80" optimum="90"');
});
test('fixture byte survival crosses 90% (was 61.6% -- 9739/15815 -- before Task 24)', () => {
expect(out.length).toBeGreaterThan(fixtureHtml.length * 0.9);
});
});
describe('purifyHtml -- Task 24: things in the fixture that must still be dropped', () => {
const out = purifyHtml(fixtureHtml);
test('style tag never survives', () => {
expect(out).not.toMatch(/<style[\s>]/i);
});
test('script tag never survives', () => {
expect(out).not.toMatch(/<script[\s>]/i);
});
test('dialog/template stay excluded (not in the widened allow-list)', () => {
expect(out).not.toContain('<dialog');
expect(out).not.toContain('<template');
});
test('no on* handler survives anywhere in the widened output, including inside the dialog fallback content', () => {
expect(out).not.toMatch(/\son[a-z]+\s*=/i);
// The fixture's dialog/close buttons carry onclick specifically to
// prove this; their text content should still come through once the
// handler is stripped and (for dialog) the wrapping tag is dropped.
expect(out).toContain('Open dialog');
});
});
describe('purifyHtml -- Task 24: security properties on newly-allowed elements', () => {
test('script inside a newly-allowed <form> still never survives', () => {
const out = purifyHtml('<form><script>alert(1)</script></form>');
expect(out).not.toContain('<script');
});
test('on* handlers never survive on newly-allowed form controls', () => {
const out = purifyHtml('<input onfocus="alert(1)" value="x">');
expect(out).not.toMatch(/onfocus/i);
const out2 = purifyHtml('<select onchange="alert(1)"><option>x</option></select>');
expect(out2).not.toMatch(/onchange/i);
});
test('javascript: blocked in <form action>', () => {
const out = purifyHtml('<form action="javascript:alert(1)"><button type="submit">go</button></form>');
expect(out).not.toContain('javascript:');
});
test('formaction is not in the allow-list at all -- dropped regardless of value', () => {
const out = purifyHtml('<button formaction="javascript:alert(1)">go</button>');
expect(out).not.toContain('formaction');
expect(out).not.toContain('javascript:');
});
test('javascript: blocked on svg <a xlink:href> (xlink:href is not allow-listed at all)', () => {
const out = purifyHtml('<svg><a xlink:href="javascript:alert(1)">click</a></svg>');
expect(out).not.toContain('javascript:');
expect(out).not.toContain('xlink:href');
});
test('javascript: blocked in newly-allowed media URL attributes (poster, source src)', () => {
const out = purifyHtml('<video poster="javascript:alert(1)"><source src="javascript:alert(2)"></video>');
expect(out).not.toContain('javascript:');
});
test('javascript: still blocked in plain href alongside the widened surface', () => {
const out = purifyHtml('<a href="javascript:alert(1)"><svg><text>x</text></svg></a>');
expect(out).not.toContain('javascript:');
});
test('iframe still gets the forced restrictive sandbox + referrerpolicy alongside the widened surface', () => {
const out = purifyHtml('<form><input></form><iframe src="https://example.com/"></iframe>');
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
const sandbox = out.match(/sandbox="([^"]*)"/)![1];
expect(sandbox).not.toMatch(/allow-top-navigation/);
expect(out).toContain('referrerpolicy="no-referrer"');
});
test('on* on an iframe is still stripped even though iframe now sits among many more allowed siblings', () => {
const out = purifyHtml('<iframe src="https://example.com/" onload="alert(1)"></iframe>');
expect(out).not.toMatch(/onload/i);
});
test('Task 25: style tag nested inside the newly-allowed inline svg now survives, scoped', () => {
// Was "style tag stays blocked" pre-Task-25 -- <style> is now a
// deliberate escape hatch (see HtmlBlock.tsx's ALLOWED_TAGS/Task 25
// comment), including copies nested inside inline SVG:
// querySelectorAll('style') in scopeStyleBlocks() doesn't care about
// namespace/nesting depth, because CSS itself doesn't respect SVG
// subtree boundaries -- an unscoped <style> inside <svg> would still
// apply page-wide, so it needs the same scoping as a top-level one.
const out = purifyHtml('<svg><style>svg{color:red}</style><rect width="1" height="1"></rect></svg>');
expect(out).toMatch(/<style/i);
expect(out).not.toContain('<style>svg{color:red}</style>'); // rewritten, not verbatim
expect(out).toMatch(/\.whp-html-\w+ svg\{color:red\}/);
expect(out).toContain('<rect');
});
test('contenteditable does not smuggle an event handler in alongside it', () => {
const out = purifyHtml('<div contenteditable="true" onblur="alert(1)">x</div>');
expect(out).not.toMatch(/onblur/i);
expect(out).toContain('contenteditable="true"');
});
test('dialog stays excluded even with an attack payload; its inert children still render', () => {
const out = purifyHtml('<dialog onclick="alert(1)"><p>hi</p></dialog>');
expect(out).not.toContain('<dialog');
expect(out).not.toMatch(/onclick/i);
expect(out).toContain('<p>hi</p>');
});
test('javascript: blocked via data: smuggling on newly-allowed poster/cite/action attributes', () => {
// data: is only allow-listed for data:image/*;base64, -- confirm the
// regex is not accidentally satisfied by a text/html or bare data:
// payload on any of the newly URI-checked attributes.
const out = purifyHtml(
'<video poster="data:text/html,<script>alert(1)</script>"></video>' +
'<blockquote cite="data:text/html,x">q</blockquote>' +
'<form action="data:text/html,x"></form>',
);
expect(out).not.toContain('data:text/html');
});
test('review fix: data:image/*;base64, URIs now actually survive on poster/cite/href (dead-code regex bug)', () => {
// ALLOWED_URI_REGEXP used to put the data:image arm inside the group
// that gets a trailing `:` appended to every alternative, requiring a
// second colon after the one already in "base64," -- which no real
// data URI has, so the clause could never match anything. Confirm the
// fixed regex actually allows a real base64 image data URI through on
// ordinary URI-checked attributes (not just the DATA_URI_TAGS-covered
// src ones tested below).
const b64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
const out = purifyHtml(
`<video poster="data:image/png;base64,${b64}"></video>` +
`<blockquote cite="data:image/png;base64,${b64}">q</blockquote>` +
`<a href="data:image/png;base64,${b64}">img</a>`,
);
expect(out).toContain(`poster="data:image/png;base64,${b64}"`);
expect(out).toContain(`cite="data:image/png;base64,${b64}"`);
expect(out).toContain(`href="data:image/png;base64,${b64}"`);
});
test('documented reality: data: on img/video/audio/source src is mimetype-blind (DOMPurify DATA_URI_TAGS bypasses ALLOWED_URI_REGEXP)', () => {
// This is NOT gated by ALLOWED_URI_REGEXP at all -- DOMPurify has its
// own internal DATA_URI_TAGS allow-list (img, video, audio, source,
// image, track) that accepts ANY data: URI on the `src` attribute of
// those tags regardless of declared mimetype, before our regex is ever
// consulted. Acceptable because none of those tags execute their src
// as a document/script context in mainstream browsers -- the sink
// doesn't execute. Pinned here so a future DOMPurify version change to
// DATA_URI_TAGS shows up as a failing test, not a surprise in
// production. <iframe> -- the one tag where this WOULD be dangerous --
// is correctly not in DOMPurify's DATA_URI_TAGS list, so its src still
// goes through the normal ALLOWED_URI_REGEXP check and gets stripped.
const b64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
const imgOut = purifyHtml(`<img src="data:text/html;base64,${b64}">`);
expect(imgOut).toContain(`src="data:text/html;base64,${b64}"`);
const iframeOut = purifyHtml(`<iframe src="data:text/html;base64,${b64}"></iframe>`);
expect(iframeOut).not.toContain('data:');
});
});
describe('purifyHtml -- bug fix: size/low/high/optimum were stripped despite select/meter being allowed tags', () => {
test('<select size> survives with its value intact (multi-select row count)', () => {
const out = purifyHtml('<select size="4"><option>a</option></select>');
expect(out).toContain('size="4"');
});
test('<input size> survives with its value intact', () => {
const out = purifyHtml('<input type="text" size="10">');
expect(out).toContain('size="10"');
});
test('<meter low/high/optimum> survive with their values intact (threshold-based gauge colouring)', () => {
const out = purifyHtml('<meter low="1" high="9" optimum="5" value="4" min="0" max="10"></meter>');
expect(out).toContain('low="1"');
expect(out).toContain('high="9"');
expect(out).toContain('optimum="5"');
});
});
+336 -2
View File
@@ -1,5 +1,17 @@
import { describe, test, expect } from 'vitest';
import { purifyHtml } from './HtmlBlock';
import { stableHash } from '../../utils/escape';
import fixtureHtml from './__fixtures__/html-block-test-body.html?raw';
// Ground truth "before" output: purifyHtml(fixtureHtml) computed with the
// EXACT HtmlBlock.tsx code as it stood at commit 6a9b227 (the commit
// immediately before Task 25 -- `git show
// 6a9b227:craft/src/components/basic/HtmlBlock.tsx`), run against the real
// dompurify+jsdom, not guessed at or re-derived from reading the code. See
// the "byte-diff against 6a9b227" describe block below -- this is the
// literal regression check the Task 25 review asked for, after the first
// round of `.not.toContain(...)`-style tests passed while FORCE_BODY was
// silently changing output for a comment-led, style-free fixture.
import preTask25FixtureOutput from './__fixtures__/html-block-test-body.pre-task25-output.html?raw';
describe('purifyHtml', () => {
test('strips script tags', () => {
@@ -17,8 +29,47 @@ describe('purifyHtml', () => {
const out = purifyHtml('<iframe src="https://www.youtube.com/embed/abc" allowfullscreen></iframe>');
expect(out).toContain('youtube.com/embed/abc');
});
test('strips form/input', () => {
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
test('allows form/input (Task 24: forms are a deliberate escape-hatch addition) but still strips on*/script inside them', () => {
const out = purifyHtml('<form><input name="x" onfocus="bad()"><script>alert(1)</script></form>');
expect(out).toContain('<form');
expect(out).toContain('<input name="x">');
expect(out).not.toContain('onfocus');
expect(out).not.toContain('<script');
});
});
describe('purifyHtml markup path (C1 review finding)', () => {
test('a style attribute survives sanitization (colour picker output must not be silently dropped)', () => {
const out = purifyHtml('<p style="color: #ff0000">red text</p>');
expect(out).toBe('<p style="color: #ff0000">red text</p>');
});
test('an id attribute survives sanitization (anchor targets)', () => {
const out = purifyHtml('<a href="#section" id="section">link</a>');
expect(out).toContain('id="section"');
});
test('a pasted table survives sanitization', () => {
const input = '<table><thead><tr><th>Head</th></tr></thead><tbody><tr><td>Cell</td></tr></tbody></table>';
expect(purifyHtml(input)).toBe(input);
});
test('script tags still do not survive alongside a style attribute', () => {
const out = purifyHtml('<p style="color:#ff0000">ok</p><script>alert(1)</script>');
expect(out).not.toContain('<script');
expect(out).toContain('style="color:#ff0000"');
});
test('on* handlers still do not survive on an element that also carries style', () => {
const out = purifyHtml('<p style="color:#ff0000" onclick="bad()">x</p>');
expect(out).not.toContain('onclick');
expect(out).toContain('style="color:#ff0000"');
});
test('javascript: URLs still do not survive on an element that also carries style', () => {
const out = purifyHtml('<a style="color:#ff0000" href="javascript:void(0)">x</a>');
expect(out).not.toContain('javascript:');
expect(out).toContain('style="color:#ff0000"');
});
});
@@ -64,3 +115,286 @@ describe('purifyHtml iframe sandboxing (M-6)', () => {
expect(out).toContain('<p>hi</p>');
});
});
describe('purifyHtml -- Task 25: block-scoped <style> support', () => {
test('a block with no <style> at all is untouched: no wrapper div added', () => {
const out = purifyHtml('<p>hello</p>');
expect(out).toBe('<p>hello</p>');
expect(out).not.toContain('<div');
});
test('blocks WITHOUT <style> are byte-identical to pre-Task-25 output (no wrapper regression)', () => {
// Same representative inputs the Task 24 suite already pins to an exact
// string -- re-asserted here under the Task 25 name so a future change
// that starts wrapping every block (not just style-bearing ones) fails
// loudly and obviously, not just as a Task 24 side-effect.
expect(purifyHtml('<p style="color: #ff0000">red text</p>')).toBe('<p style="color: #ff0000">red text</p>');
const table = '<table><thead><tr><th>Head</th></tr></thead><tbody><tr><td>Cell</td></tr></tbody></table>';
expect(purifyHtml(table)).toBe(table);
expect(purifyHtml('<a href="/x">x</a>')).toBe('<a href="/x">x</a>');
});
test('the full Task 24 fixture (no <style> in it) produces no wrapper and is unaffected', () => {
// The fixture is the broadest real-world stand-in this repo has for
// "a customer's actual pasted block". It contains no <style>, so this
// is the closest thing to a real before/after diff over a large,
// realistic input: the only lever Task 25 pulled (allowing <style> +
// FORCE_BODY) must produce PRECISELY the same output as before for
// content that never touches that lever.
const out = purifyHtml(fixtureHtml);
expect(out).not.toContain('<div class="whp-html-');
expect(out).not.toMatch(/<style[\s>]/i); // still no bare <style> in this fixture
});
test('an empty <style></style> (no CSS content) does not trigger a wrapper', () => {
const out = purifyHtml('<p>hi</p><style></style>');
expect(out).not.toContain('<div class="whp-html-');
});
test('a whitespace-only <style> does not trigger a wrapper', () => {
const out = purifyHtml('<p>hi</p><style> \n </style>');
expect(out).not.toContain('<div class="whp-html-');
});
test('a block WITH real <style> content gets wrapped in a scope-class div', () => {
const out = purifyHtml('<style>h1 { color: red; }</style><h1>Hi</h1>');
expect(out).toMatch(/^<div class="whp-html-[0-9a-z]+">/);
expect(out).toContain('<h1>Hi</h1>');
});
test('the style content is rewritten to only match inside the wrapper (the actual leak-prevention property)', () => {
const out = purifyHtml('<style>h1 { color: red; }</style><h1>Hi</h1>');
const scopeClass = out.match(/class="(whp-html-[0-9a-z]+)"/)![1];
expect(out).toContain(`.${scopeClass} h1 { color: red; }`);
// The bare, unscoped rule must not appear anywhere in the output --
// that's exactly the leak this feature exists to close.
expect(out).not.toContain('<style>h1 { color: red; }</style>');
});
test('scope class is deterministic: the SAME code produces the SAME class across repeated calls', () => {
const code = '<style>p { color: blue; }</style><p>x</p>';
const out1 = purifyHtml(code);
const out2 = purifyHtml(code);
expect(out1).toBe(out2);
const class1 = out1.match(/class="(whp-html-[0-9a-z]+)"/)![1];
const class2 = out2.match(/class="(whp-html-[0-9a-z]+)"/)![1];
expect(class1).toBe(class2);
});
test('pinned scope class for a known input -- guards against silent hash-function drift', () => {
// If this ever needs to change, it means the hash function itself
// changed -- which would silently churn every stored site's HTML on
// next save and desync already-published pages from a fresh Preview.
// That should be a loud, deliberate decision, not a side-effect of an
// unrelated refactor -- hence pinning the literal output here.
const code = '<style>h1{color:red}</style>';
expect(stableHash(code)).toBe('5fwbyn');
const out = purifyHtml(code);
expect(out).toContain('class="whp-html-5fwbyn"');
});
test('scope class is a pure function of `code` -- does not depend on Craft node id or call order', () => {
// purifyHtml's signature only ever takes the code string -- there is no
// node id parameter it could even reach for. This test documents that
// invariant so a future refactor threading a node id through here (as
// html-export.ts's renderNode already does for OTHER components, see
// its `scopeId` comment) doesn't silently get wired into this path too.
const codeA = '<style>h1 { color: red; }</style><h1>same content</h1>';
const codeB = '<style>h1 { color: red; }</style><h1>same content</h1>';
expect(codeA).toBe(codeB); // sanity: truly identical strings
const outA = purifyHtml(codeA);
const outB = purifyHtml(codeB);
expect(outA).toBe(outB);
});
test('FORCE_BODY regression: a block whose ENTIRE code is a leading <style> (nothing before it) still survives', () => {
// Without FORCE_BODY, DOMPurify parses `code` via DOMParser as a mini
// HTML document and serializes only <body>. Per the HTML5 parsing
// algorithm, a <style> tag with nothing before it is implicitly placed
// in the parser's <head>, which DOMPurify's body-only serialization
// never looks at -- the whole block would silently vanish. Confirmed
// empirically against dompurify+jsdom directly before this fix existed.
const out = purifyHtml('<style>h1{color:red}</style>');
expect(out).toContain('<style>');
expect(out).toContain('color:red');
});
test('FORCE_BODY regression: leading <style> immediately followed by markup, both survive', () => {
const out = purifyHtml('<style>h1{color:red}</style><h1>Hi</h1>');
expect(out).toContain('<h1>Hi</h1>');
expect(out).toMatch(/<style>[\s\S]*color:\s*red/);
});
test(':root / html / body inside a block map to the block wrapper itself (end-to-end through purifyHtml)', () => {
const out = purifyHtml('<style>:root { --brand: red; } body { margin: 0; }</style><p>x</p>');
const scopeClass = out.match(/class="(whp-html-[0-9a-z]+)"/)![1];
expect(out).toContain(`.${scopeClass} { --brand: red; }`);
expect(out).toContain(`.${scopeClass} { margin: 0; }`);
});
test('@import is stripped end-to-end (network-fetch/exfiltration channel)', () => {
const out = purifyHtml('<style>@import url("https://evil.example/x.css"); h1{color:red}</style><h1>x</h1>');
expect(out).not.toContain('@import');
expect(out).not.toContain('evil.example');
expect(out).toContain('color:red');
});
test('@keyframes body is not scoped (animation would otherwise break) -- end-to-end through purifyHtml', () => {
const out = purifyHtml(
'<style>@keyframes spin { from { opacity: 0; } to { opacity: 1; } }</style><h1>x</h1>',
);
expect(out).toContain('@keyframes spin');
expect(out).toMatch(/@keyframes spin\s*\{\s*from\s*\{\s*opacity:\s*0;?\s*\}\s*to\s*\{\s*opacity:\s*1;?\s*\}\s*\}/);
});
test('multiple <style> blocks in one Custom HTML block are each scoped under the SAME class', () => {
const out = purifyHtml('<style>h1{color:red}</style><h1>A</h1><style>p{color:blue}</style><p>B</p>');
const classes = [...out.matchAll(/class="(whp-html-[0-9a-z]+)"/g)].map((m) => m[1]);
expect(classes.length).toBeGreaterThanOrEqual(1);
expect(new Set(classes).size).toBe(1); // same block -> same scope class everywhere
});
});
describe('purifyHtml -- Task 25: security properties of the newly-allowed <style>', () => {
test('</style> inside a CSS comment cannot break out into executable markup', () => {
const out = purifyHtml(
'<style>/* </style><script>alert(1)</script> */ h1{color:red}</style><p>hi</p>',
);
expect(out).not.toContain('<script');
expect(out).not.toMatch(/on[a-z]+\s*=/i);
});
test('</style> inside a CSS string cannot break out into executable markup', () => {
const out = purifyHtml(
'<style>h1::before{content:"</style><script>alert(1)</script>"}</style><p>hi</p>',
);
expect(out).not.toContain('<script');
});
test('script/on*/javascript: are still stripped from markup sitting alongside a styled block', () => {
const out = purifyHtml(
'<style>h1{color:red}</style><p onclick="alert(1)">x</p><script>alert(2)</script><a href="javascript:alert(3)">y</a>',
);
expect(out).not.toMatch(/onclick/i);
expect(out).not.toContain('<script');
expect(out).not.toContain('javascript:');
});
test('iframe sandboxing still applies alongside a styled block', () => {
const out = purifyHtml('<style>h1{color:red}</style><iframe src="https://example.com/"></iframe>');
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
});
test(
'documented reality: DOMPurify does not sanitize CSS declaration values -- ' +
'expression()/behavior/-moz-binding pass through untouched (dead in modern browsers, ' +
'not exploitable there, but not filtered by this pipeline either)',
() => {
const out = purifyHtml(
'<style>div{width:expression(alert(1));behavior:url(evil.htc);-moz-binding:url(evil.xml#x)}</style><div>x</div>',
);
expect(out).toContain('expression(alert(1))');
expect(out).toContain('behavior:url(evil.htc)');
expect(out).toContain('-moz-binding:url(evil.xml#x)');
},
);
test('documented reality: url() to a remote host survives (legitimate for background-image, but a known CSS-exfiltration channel already accepted elsewhere in this config)', () => {
const out = purifyHtml('<style>div{background:url(https://tracker.example/pixel.png)}</style><div>x</div>');
expect(out).toContain('tracker.example');
});
});
describe('purifyHtml -- review finding: raw byte-diff against HtmlBlock.tsx@6a9b227 (the commit before Task 25)', () => {
// Round 1 of this task's tests used `.not.toContain(...)`/`.toContain(...)`
// assertions for the "no <style> => unchanged" guarantee. Those all
// passed while FORCE_BODY: true (applied unconditionally at the time)
// was silently changing the ACTUAL bytes for any style-free block that
// starts with a multi-line HTML comment -- including this repo's own
// fixture, which is exactly that shape. `.not.toContain` can't catch an
// extra leading newline; only a raw diff against the real old output
// can. These tests do that: `preTask25FixtureOutput` is
// `purifyHtml(fixtureHtml)` computed with the UNMODIFIED HtmlBlock.tsx
// source at 6a9b227 (via `git show 6a9b227:...`), run against the real
// dompurify+jsdom, not re-derived from reading the code -- see that
// fixture file's own header comment.
test('the fixture (comment-led, no <style>) is byte-identical to the pre-Task-25 output', () => {
expect(fixtureHtml.startsWith('<!--')).toBe(true); // sanity: this IS the comment-led shape
expect(purifyHtml(fixtureHtml)).toBe(preTask25FixtureOutput);
});
test('a short comment-led, style-free block matches pre-Task-25 output exactly (including the dropped leading whitespace quirk)', () => {
// Confirmed independently against 6a9b227's exact code: a multi-line
// leading comment followed by blank-line whitespace, with no <style>
// anywhere, produces "<p>hi</p>" -- both the comment AND the
// whitespace between it and <p> are dropped by the parser's
// "before head" insertion-mode rules (unrelated to this task; that's
// the pre-existing, unconditional behavior with FORCE_BODY off). The
// point of this test is that the NEW code must reproduce that exact
// old quirk byte-for-byte for style-free input, not "improve" on it.
const commentLed =
'<!-- ============================================================\n' +
' HTML test fixture header\n' +
' ============================================================ -->\n' +
'\n<p>hi</p>';
expect(purifyHtml(commentLed)).toBe('<p>hi</p>');
});
test('plain style-free inputs (no comment involved) still match pre-Task-25 output', () => {
expect(purifyHtml('<p>hello</p>')).toBe('<p>hello</p>');
expect(purifyHtml('<p style="color: #ff0000">red text</p>')).toBe('<p style="color: #ff0000">red text</p>');
});
});
describe('purifyHtml -- review finding: never throws, even on pathological deeply-nested @media input', () => {
function buildDeeplyNestedMedia(count: number): string {
// ~7000 nested @media blocks (the review's exact repro shape) reproduced
// through the REAL purifyHtml() call, not just scopeCss() in isolation
// -- proving the fix holds end-to-end through DOMPurify + scopeStyleBlocks,
// not merely in the unit-tested function.
let css = 'h1{color:red}';
for (let i = 0; i < count; i++) css = `@media (min-width: 1px) {${css}}`;
return `<style>${css}</style><h1>x</h1>`;
}
test('~7000 levels of nested @media does not crash purifyHtml (was: RangeError: Maximum call stack size exceeded)', () => {
const code = buildDeeplyNestedMedia(7000);
expect(() => purifyHtml(code)).not.toThrow();
const out = purifyHtml(code);
expect(out).toContain('<h1>x</h1>');
expect(out).toContain('@media');
});
test('a scope class + wrapper is still produced for the pathological input (best-effort, not a silent no-op)', () => {
const code = buildDeeplyNestedMedia(7000);
const out = purifyHtml(code);
expect(out).toMatch(/^<div class="whp-html-[0-9a-z]+">/);
});
});
describe('purifyHtml -- review finding: idempotent over its own prior output', () => {
test('running purifyHtml() twice (customer pastes previously-published output into a fresh block) does not nest a second wrapper', () => {
const code = '<style>h1 { color: red; }</style><h1>Hi</h1>';
const once = purifyHtml(code);
const twice = purifyHtml(once);
expect(twice).toBe(once);
// Specifically: no second wrapper div, no double-prefixed selector.
expect((twice.match(/<div class="whp-html-/g) || []).length).toBe(1);
});
test('idempotent for a block using :root/media too', () => {
const code = '<style>:root{--x:1} @media (min-width: 600px) { h1, p { color: red; } }</style><h1>Hi</h1><p>x</p>';
const once = purifyHtml(code);
const twice = purifyHtml(once);
expect(twice).toBe(once);
expect((twice.match(/<div class="whp-html-/g) || []).length).toBe(1);
});
test('three generations (paste published output into a block, publish again, paste THAT) stay stable', () => {
const code = '<style>h1{color:red}</style><h1>Hi</h1>';
const gen1 = purifyHtml(code);
const gen2 = purifyHtml(gen1);
const gen3 = purifyHtml(gen2);
expect(gen3).toBe(gen1);
});
});
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest';
import { HtmlBlock } from './HtmlBlock';
import { HtmlBlock, purifyHtml } from './HtmlBlock';
const toHtml = (HtmlBlock as any).toHtml;
@@ -23,3 +23,47 @@ describe('HtmlBlock.toHtml sanitizes raw code (A4.1)', () => {
expect(html).toBe('<p>hi</p>');
});
});
test('toHtml never emits the style prop (the other half of the render/export contract)', () => {
const out = (HtmlBlock as any).toHtml(
{ code: '<p>hi</p>', style: { backgroundColor: '#ff0000', padding: '40px' } },
'',
);
expect(out.html).toBe('<p>hi</p>');
expect(out.html).not.toContain('background');
expect(out.html).not.toContain('40px');
});
describe('HtmlBlock.toHtml markup path (C1 review finding)', () => {
test('a style attribute inside `code` (e.g. from the toolbar colour picker) reaches exported output', () => {
const { html } = toHtml({ code: '<p style="color: #ff0000">red text</p>' }, '');
expect(html).toBe('<p style="color: #ff0000">red text</p>');
});
test('a table inside `code` reaches exported output', () => {
const code = '<table><tbody><tr><td>Cell</td></tr></tbody></table>';
const { html } = toHtml({ code }, '');
expect(html).toBe(code);
});
});
describe('HtmlBlock.toHtml -- Task 25: block-scoped <style>, and editor/export byte-parity', () => {
test('a <style>-bearing block exports the same scoped wrapper purifyHtml() would produce in the editor canvas', () => {
// The editor canvas (HtmlBlock component) and toHtml() (Preview +
// Published export) both call the exact same purifyHtml(code) -- this
// is the byte-parity invariant this project treats as a hard
// requirement. Proven here by calling purifyHtml directly (as the
// canvas's useMemo does) and toHtml (as export does) on the identical
// code string and asserting the two never diverge.
const code = '<style>h1 { color: red; }</style><h1>Hi</h1>';
const { html } = toHtml({ code }, '');
expect(html).toBe(purifyHtml(code));
});
test('a <style>-free block still exports byte-identical to pre-Task-25 output (no wrapper regression) via toHtml', () => {
const code = '<p>hello</p>';
const { html } = toHtml({ code }, '');
expect(html).toBe('<p>hello</p>');
expect(html).not.toContain('<div');
});
});
+325 -8
View File
@@ -1,6 +1,8 @@
import React, { CSSProperties, useMemo } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import DOMPurify from 'dompurify';
import { stableHash } from '../../utils/escape';
import { scopeCss } from '../../utils/scope-css';
interface HtmlBlockProps {
code: string;
@@ -9,28 +11,207 @@ interface HtmlBlockProps {
node_id?: string;
}
// Task 24: widening the allow-list after a customer's broad HTML fixture
// showed 38% of it silently deleted (tables losing colspan/rowspan/scope,
// <dl>/<sub>/<details>/inline <svg>/<video>/<audio> dropped wholesale,
// lang/dir/role stripped, <ol start/reversed> flattened). The owner's call:
// be generous -- this block is an explicit escape hatch and customers
// reasonably expect it to render ordinary HTML, including forms. The four
// non-negotiables (no <script>, no on*, no javascript: URLs, iframes stay
// sandboxed) are unaffected by the widening and are covered by dedicated
// tests in HtmlBlock.test.ts / HtmlBlock.security.test.ts.
const PURIFY_CONFIG = {
ALLOWED_TAGS: [
'a','p','br','hr','div','span','section','article',
'header','footer','main','aside','nav',
'ul','ol','li',
'h1','h2','h3','h4','h5','h6',
'h1','h2','h3','h4','h5','h6','hgroup',
'em','strong','b','i','u','s',
'blockquote','code','pre',
'img','figure','figcaption',
'iframe',
// Tables: pasted content commonly includes these; dropping them
// silently ate customer-pasted tables (see C1 review finding).
'table','thead','tbody','tfoot','tr','td','th','caption','colgroup','col',
// Text semantics (Task 24).
'sub','sup','small','mark','del','ins','abbr','cite','q','time','data',
'kbd','samp','var','dfn','address','bdi','bdo','ruby','rt','rp','wbr',
// Lists (Task 24).
'dl','dt','dd','menu',
// Disclosure widget (Task 24). Note: <dialog> and <template> are
// deliberately NOT added -- the fixture exercises them wrapped in
// on*= handlers specifically to prove they still get neutralized/
// dropped by staying outside the allow-list.
'details','summary',
// Media (Task 24). URL-bearing attributes on these (poster, srcset,
// action, cite...) go through the ALLOWED_URI_REGEXP gate like
// everything else -- see _isValidAttribute in dompurify, which
// URI-checks every allowed attribute value except a small fixed
// "inert" list (alt, class, id, style, title, ...) that never includes
// src/poster/srcset. The one exception: `src` itself on img/video/
// audio/source/image/track is additionally covered by DOMPurify's own
// `DATA_URI_TAGS` allow-list, which accepts any data: URI on those
// tag/attribute pairs regardless of mimetype, bypassing this regex --
// see the ALLOWED_URI_REGEXP comment below and
// HtmlBlock.security.test.ts. Not a gap in the four non-negotiables:
// none of those tags execute their src as a document.
'picture','source','video','audio','track','canvas',
// Forms (Task 24). Site owner's explicit decision: allow the full
// ordinary form surface. No on*= survives (FORBID_ATTR below), and
// action/formaction-style URLs are gated by ALLOWED_URI_REGEXP the
// same as href/src, so `javascript:` still cannot survive here either.
'form','input','button','select','option','optgroup','textarea',
'label','fieldset','legend','datalist','output','progress','meter',
// Inline SVG (Task 24) -- see the block comment on IFRAME_SANDBOX_HOOK's
// neighbor below for why this is an explicit tag list rather than
// DOMPurify's USE_PROFILES svg profile. Deliberately excludes <use> and
// <image> (both need xlink:href, an external-reference vector DOMPurify
// itself excludes from its own SVG defaults) and <a>/<foreignObject>
// (not needed by the fixture; foreignObject can embed arbitrary HTML).
'svg','g','defs','symbol','title','desc','rect','circle','ellipse',
'line','polyline','polygon','path','text','tspan',
'lineargradient','radialgradient','stop','clippath','mask','marker',
'pattern','switch','view',
// Task 25: block-scoped <style> support. Formerly in FORBID_TAGS
// (stripped entirely). Now allowed through sanitisation -- its CSS is
// rewritten by scopeStyleBlocks()/scopeCss() below, immediately after
// DOMPurify runs, so it can only match inside this block's own wrapper
// element. See the FORCE_BODY comment below and scopeStyleBlocks() for
// why allowing the tag alone is not sufficient.
//
// Review note (Task 25 follow-up, documented not fixed): DOMPurify's
// SAFE_FOR_XML default (on unless a caller explicitly disables it,
// which PURIFY_CONFIG does not) silently drops an ENTIRE <style>
// element -- not just the offending part -- if its text content
// contains anything that merely LOOKS tag-like (a `<` followed by a
// word character, `/`, or `!`), as an mXSS-namespace-confusion defense
// that isn't specific to <style>. So `.x::after{content:"<Read
// More>"}` -- a plausible, entirely benign real-world CSS content
// string -- makes the whole style block vanish with no error, the same
// way a `<script>` would. This is a GOOD security property (better
// paranoid than exploitable), but it's an undocumented interaction
// with this newly-widened surface that will otherwise confuse whoever
// debugs the inevitable "my CSS just disappeared" report -- confirmed
// empirically against dompurify+jsdom directly, not guessed at.
'style',
],
// NOTE: supplying ALLOWED_ATTR replaces DOMPurify's own default attribute
// allowlist rather than extending it, so anything the product needs
// (style, id, ...) must be listed explicitly here even though DOMPurify
// would allow it by default.
ALLOWED_ATTR: [
'href','src','alt','title','target','rel',
'width','height','class',
'width','height','class','id','style',
'allowfullscreen','allow','frameborder',
'sandbox','referrerpolicy',
// Task 24 additions.
'colspan','rowspan','scope','headers','span','start','reversed',
'type','value','name','placeholder','required','disabled','readonly',
'checked','selected','multiple','size','min','max','step','minlength',
'maxlength','pattern','rows','cols','accept','action','method','for',
'list','label','datetime','cite','lang','dir','role','srcset','media',
'sizes','loading','controls','poster','loop','muted','autoplay',
'preload','playsinline','kind','srclang','default','open','download',
'hidden','contenteditable',
// Bug fix: <select size="4">/<input size> and <meter low/high/optimum>
// were still being stripped even though <select>/<meter> are already in
// ALLOWED_TAGS -- only these four attribute names were missing here.
// Effect: a multi-select rendered at default height instead of the
// requested row count, and <meter> lost its threshold-based gauge
// colouring. Pure presentation/semantic attributes -- no URL, no
// script, no event-handler surface -- so no security weight added.
'low','high','optimum',
// SVG presentation attributes (explicit route -- see ALLOWED_TAGS
// comment on the SVG tag list). Covers the fixture's <svg viewBox
// role>/<rect>/<circle>/<text> block plus the common presentation
// attributes for the shapes/gradients allowed above. Deliberately
// excludes xlink:href (no <use>/<image> allowed, so it has nothing
// legitimate to attach to) and the SMIL/animation attributes (begin,
// dur, repeatCount, ...) which DOMPurify's own SVG defaults exclude
// for the same reason on* handlers are excluded.
'viewbox','cx','cy','r','rx','ry','x','y','x1','y1','x2','y2',
'points','d','fill','stroke','stroke-width','stroke-linecap',
'stroke-linejoin','stroke-dasharray','fill-rule','clip-rule','opacity',
'fill-opacity','stroke-opacity','text-anchor','dominant-baseline',
'font-family','font-size','font-weight','transform','offset',
'stop-color','stop-opacity','gradientunits','gradienttransform',
'preserveaspectratio',
],
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
// Review fix (Task 24 follow-up): the data:image arm used to sit inside
// the group that gets a trailing `:` appended for every alternative
// (`(?:https?|mailto|tel|data:image\/[a-z]+;base64,):`), so it required
// a SECOND colon after the one already in "base64,figure" -- no real
// data URI has that, so the clause could never match. It is now its own
// top-level alternative. NOTE: this regex is not the only thing gating
// data: URIs -- DOMPurify has its own internal `DATA_URI_TAGS` allow-list
// (img/video/audio/source/image/track) that accepts ANY data: URI on
// those tag/attribute pairs regardless of declared mimetype, bypassing
// this regex entirely. See HtmlBlock.security.test.ts for a regression
// test documenting that (acceptable: none of those tags execute their
// src as a document in mainstream browsers, and <iframe> -- which would
// be dangerous -- is correctly not in that DOMPurify list).
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel):|data:image\/[a-z]+;base64,|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
// form/input/button/select/textarea removed from FORBID_TAGS (Task 24) --
// they are now deliberately allowed above. script/object/embed/link/meta
// stay forbidden. <style> (Task 25) is now allowed too -- see ALLOWED_TAGS
// comment above and scopeStyleBlocks() below; it survives sanitisation
// here but its CSS gets scoped afterwards, including copies nested inside
// the newly-allowed inline <svg> (querySelectorAll('style') in
// scopeStyleBlocks() doesn't care about namespace/nesting depth).
FORBID_TAGS: ['script','object','embed','link','meta'],
FORBID_ATTR: [/^on/i],
// NOTE: FORCE_BODY is deliberately NOT set here -- see
// needsForceBody()/purifyHtml() below. It's applied conditionally, per
// call, only when the input actually has a real <style> tag to rescue.
};
// Task 25: without FORCE_BODY, DOMPurify parses `input` as a full (mini)
// HTML document via DOMParser and only serializes <body>'s contents. Per
// the HTML5 parsing algorithm, a tag that can only legally appear in
// <head> -- and now that <style> is allowed, that includes <style> --
// gets implicitly placed in <head> when it appears before any other real
// content, and is silently lost (DOMPurify never looks at <head>). A block
// whose entire `code` is `<style>h1{color:red}</style>` -- a very
// plausible paste, style-before-markup is a common snippet shape -- would
// vanish with no error anywhere, despite <style> sitting right there in
// ALLOWED_TAGS. FORCE_BODY prepends an internal element before parsing so
// the parser is already in body-insertion-mode by the time it reaches the
// customer's first tag, keeping a leading <style> (or anything else) in
// <body> where DOMPurify's body-only serialization actually looks.
// Confirmed empirically against dompurify+jsdom directly (not just this
// app's behavior) -- see the "leading <style> with nothing before it" test
// in HtmlBlock.test.ts.
//
// Review finding (Task 25 follow-up): FORCE_BODY is NOT a no-op for input
// that has no <style> tag at all. It also changes how the HTML parser
// treats character content sitting between a LEADING comment and the next
// real tag -- normal parsing (before <body> is established) silently drops
// pure-whitespace text runs there per the HTML5 "before head" insertion
// mode rules, while FORCE_BODY (already in body-insertion-mode from the
// first token) preserves that whitespace as a real text node. Concretely:
// a block starting with a multi-line HTML comment -- this repo's own
// ~16KB fixture does exactly that -- gained 2 extra leading bytes (a
// preserved newline) once FORCE_BODY was unconditionally on, which
// silently broke the "blocks without <style> are byte-identical to
// pre-Task-25 output" guarantee (confirmed with a raw diff against
// HtmlBlock.tsx@6a9b227 -- the commit immediately before this task -- over
// the fixture and a comment-led block; see HtmlBlock.test.ts). Fix: only
// ever set FORCE_BODY when the input has a real <style> tag to rescue --
// the one and only case that needs it -- so every other input takes
// exactly the pre-Task-25 code path, unchanged.
//
// "Real" deliberately excludes a `<style` substring that only appears
// inside an HTML comment (e.g. a customer's own code-sample text
// mentioning `<style>`) -- that text can never become an actual <style>
// element, but naively substring-matching it would still flip FORCE_BODY
// on and reintroduce the exact same whitespace-preservation side effect
// for a block that never had, and never needed, real style scoping.
const STYLE_TAG_RE = /<style[\s>/]/i;
const HTML_COMMENT_RE = /<!--[\s\S]*?-->/g;
function needsForceBody(input: string): boolean {
return STYLE_TAG_RE.test(input.replace(HTML_COMMENT_RE, ''));
}
// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
// phishing vector (DOMPurify already strips <script>/on*=, but an
@@ -48,6 +229,120 @@ const IFRAME_SANDBOX_HOOK = (node: Element): void => {
}
};
/**
* Task 25: rewrite any surviving `<style>` element(s) in `sanitized` (the
* DOMPurify output) so their CSS only matches inside this block's own
* wrapper element, then wrap the whole thing in that wrapper.
*
* Deliberately does the LEAST work possible when there's nothing to scope:
* a cheap substring check bails out before touching the DOM at all, so a
* block that doesn't use <style> -- i.e. every block saved before this task
* -- gets `sanitized` back completely unchanged (same string, no wrapper,
* no re-serialization round-trip that could subtly reformat attributes).
* That byte-for-byte identity is a hard requirement: published pages
* already contain `toHtml()` output with NO wrapper element, and adding one
* unconditionally would silently change the DOM/box-model of every
* existing customer block. See HtmlBlock.test.ts's
* "blocks without <style> are byte-identical" tests, which run this
* against real fixture content and diff the exact string.
*
* Scope identifier: `whp-html-${stableHash(rawCode)}` -- `stableHash` is
* the existing djb2 hash from utils/escape.ts (already used for this exact
* class of problem, see `scopeId` in that file), applied to `rawCode` --
* the block's own `code` prop, nothing else. Pure function of the block's
* own content: no Math.random, no Date.now, no counter, and deliberately
* NOT the Craft node id (unlike `scopeId`), because a scope identifier that
* depends on anything outside `code` would make the editor canvas preview
* (which calls purifyHtml(code) on render) and the published output (which
* calls the same purifyHtml(code) at publish time) diverge whenever that
* outside thing differs between the two call sites, and would make the
* stored HTML churn on every save even when the block's own content didn't
* change. Hashing `code` guarantees purifyHtml(code) is fully deterministic
* on its own -- same code in, byte-identical output out, every time, in
* both places it's called.
*/
const SCOPE_CLASS_RE = /^whp-html-[0-9a-z]+$/;
/**
* Idempotency (review finding, Task 25 follow-up): `purifyHtml()` is not
* reachable-with-its-own-output through any CURRENT code path, but nothing
* stops a customer from pasting previously-published or exported HTML from
* this exact feature into a fresh Custom HTML block -- at which point
* `code` already contains our own `<div class="whp-html-OLD">...<style>
* .whp-html-OLD h1{...}</style>...</div>` wrapper. Without this check,
* `scopeStyleBlocks` would hash the NEW `code` to a NEW scope class, fail
* to recognise the embedded selectors as already scoped (they're prefixed
* for the OLD class, not the new one `scopeCss`'s own idempotency guard
* checks against), and nest a second wrapper div around the first while
* re-prefixing every selector under the new class on top of the old one.
*
* Detects "the sanitized content IS ALREADY exactly one of our own scoped
* wrappers": a single root element, a <div>, whose class matches our own
* naming convention, and whose `<style>` descendant(s) are each already a
* no-op under `scopeCss` for that div's own class -- i.e. re-scoping would
* change nothing. That last check reuses `scopeCss`'s own idempotency
* guarantee (`scopeCss(scopeCss(x, S), S) === scopeCss(x, S)`, proved in
* scope-css.test.ts) rather than re-implementing "is this CSS already
* scoped" as a second parser: if scoping again under the div's own class
* is a no-op, the CSS is already confined to that div, regardless of
* whether this app was the one that put it there -- which is the actual
* safety property this function exists to guarantee, not merely a proxy
* for it.
*/
function isAlreadyScoped(container: HTMLElement): boolean {
if (container.children.length !== 1) return false;
const root = container.children[0];
if (root.tagName !== 'DIV') return false;
const cls = root.getAttribute('class') || '';
if (!SCOPE_CLASS_RE.test(cls)) return false;
const scopeSelector = `.${cls}`;
const styleEls = Array.from(root.querySelectorAll('style'));
if (styleEls.length === 0) return false; // matches our naming by coincidence but scopes nothing -- not ours to protect
return styleEls.every((el) => {
const text = el.textContent || '';
if (text.trim() === '') return true;
return scopeCss(text, scopeSelector) === text;
});
}
function scopeStyleBlocks(sanitized: string, rawCode: string): string {
if (!sanitized.includes('<style')) return sanitized;
const container = document.createElement('div');
container.innerHTML = sanitized;
if (isAlreadyScoped(container)) return sanitized;
const styleEls = Array.from(container.querySelectorAll('style'));
const nonEmpty = styleEls.filter((el) => (el.textContent || '').trim() !== '');
if (nonEmpty.length === 0) return sanitized;
// Review note (Task 25 follow-up, documented not fixed): `stableHash` is
// a 32-bit djb2 hash, so it's brute-forceable in principle -- a customer
// could deliberately craft a second block's `code` to collide onto the
// same `whp-html-<hash>` class as an existing block on the same page, at
// which point the two blocks' <style> rules apply to (and override) each
// other, since they'd share one wrapper class. Impact is CSS-only --
// visual breakage, never script execution or data exposure -- the same
// trust tier as other accepted risks in this file (e.g. remote url() in
// style content, or the pre-existing DATA_URI_TAGS mimetype-blindness
// documented in HtmlBlock.security.test.ts). Not fixed here: closing it
// would mean either a wider hash (cheap, but every existing scope class
// set with THIS Task 25 code would silently reshuffle -- a similar
// "changing the hash function reshuffles stored HTML" cost the pinned
// hash test above already guards against happening BY ACCIDENT) or a
// collision-checked/salted scheme, either of which is a bigger design
// decision than a follow-up-review fix.
const scopeClass = `whp-html-${stableHash(rawCode)}`;
for (const el of nonEmpty) {
el.textContent = scopeCss(el.textContent || '', `.${scopeClass}`);
}
return `<div class="${scopeClass}">${container.innerHTML}</div>`;
}
export function purifyHtml(input: string): string {
// Hook is added immediately before sanitize() and removed immediately
// after, scoped tightly to this single call -- so it can never leak onto
@@ -56,22 +351,35 @@ export function purifyHtml(input: string): string {
// multiple copies of the same hook.
DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
try {
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
const raw = input || '';
// See needsForceBody()/the FORCE_BODY comment above PURIFY_CONFIG:
// applied only when there's a real <style> tag to rescue, so every
// other input takes the exact pre-Task-25 sanitize() call, unchanged.
const config = needsForceBody(raw) ? { ...PURIFY_CONFIG, FORCE_BODY: true } : PURIFY_CONFIG;
const sanitized = DOMPurify.sanitize(raw, config as any) as unknown as string;
return scopeStyleBlocks(sanitized, raw);
} finally {
DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
}
}
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '' }) => {
const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
const clean = useMemo(() => purifyHtml(code), [code]);
const setRef = (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); };
// The `style` prop is deliberately NOT applied. `toHtml()` emits only the
// purified `code`, so anything styled here would show in the editor and
// vanish on the live page -- the exact bug this block was reported for.
// Wrapper styling belongs in the user's own markup (see the Edit HTML
// toolbar's colour control). `style` stays on the props interface so
// 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',
...style,
},
dangerouslySetInnerHTML: { __html: clean },
});
@@ -94,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 };
};
+39 -1
View File
@@ -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"');
@@ -44,3 +44,41 @@ describe('Icon.toHtml XSS hardening', () => {
expect(html).not.toMatch(/"\s+onclick="/);
});
});
describe('Icon.toHtml bgShape/bgColor/bgSize rendering (built but, until this panel update, unexposed)', () => {
test('bgShape="circle" + bgColor render a colored 50%-radius background box', () => {
const { html } = toHtml({ icon: 'fa-star', bgShape: 'circle', bgColor: '#3b82f6', bgSize: '64px' }, '');
expect(html).toContain('background-color:#3b82f6');
expect(html).toContain('border-radius:50%');
expect(html).toContain('width:64px');
expect(html).toContain('height:64px');
});
test('bgShape="none" (default) renders the bare icon with no background wrapper', () => {
const { html } = toHtml({ icon: 'fa-star' }, '');
expect(html).not.toContain('background-color');
});
});
describe('Icon.craft.props includes the box-model/animation/visibility rollout props', () => {
test('animation, animationDelay, and all 3 hideOn* flags are declared (blank/false defaults)', () => {
const props = (Icon as any).craft.props;
expect(props).toHaveProperty('animation', '');
expect(props).toHaveProperty('animationDelay', '');
expect(props).toHaveProperty('hideOnDesktop', false);
expect(props).toHaveProperty('hideOnTablet', false);
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');
});
});
+17 -5
View File
@@ -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;
@@ -12,6 +14,11 @@ interface IconProps {
bgSize?: string;
link?: string;
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
function getBgBorderRadius(shape: string): string {
@@ -24,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',
@@ -40,7 +47,7 @@ export const Icon: UserComponent<IconProps> = ({
const iconEl = (
<i
className={`fa ${icon}`}
className={faClass(icon)}
style={{ fontSize: size, color, lineHeight: 1 }}
/>
);
@@ -90,12 +97,17 @@ Icon.craft = {
props: {
icon: 'fa-star',
size: '32px',
color: '#3b82f6',
color: tokenRef('primary'),
bgColor: 'transparent',
bgShape: 'none',
bgSize: '56px',
link: '',
style: {},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -110,7 +122,7 @@ Icon.craft = {
const {
icon = 'fa-star',
size = '32px',
color = '#3b82f6',
color = tokenRef('primary'),
bgColor = 'transparent',
bgShape = 'none',
bgSize = '56px',
@@ -119,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) {
@@ -43,6 +43,29 @@ describe('Logo.toHtml image src/alt sanitization (type="image")', () => {
});
});
describe('Logo.toHtml download attribute (F3: link-to-file toggle)', () => {
test('download:true emits the download attribute', () => {
const { html } = toHtml({ href: '/resume.pdf', download: true, text: 'Resume' }, '');
expect(html).toMatch(/<a href="\/resume\.pdf" download/);
});
test('no download prop -> no download attribute emitted', () => {
const { html } = toHtml({ href: '/', text: 'MySite' }, '');
expect(html).not.toContain('download');
});
});
describe('Logo (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Logo as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Logo.toHtml text-logo styling sanitization', () => {
test('a quote-breakout color does not escape the span style attribute', () => {
const malicious = 'red" onmouseover="alert(1)';
@@ -60,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);
});
});
+19 -2
View File
@@ -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';
@@ -12,11 +13,18 @@ interface LogoProps {
imageSrc?: string;
imageWidth?: string;
href?: string;
/** Adds the `download` attribute to the exported anchor (F3: link to a file). */
download?: boolean;
fontFamily?: string;
fontSize?: string;
fontWeight?: string;
color?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Component ---------- */
@@ -27,6 +35,7 @@ export const Logo: UserComponent<LogoProps> = ({
imageSrc = '',
imageWidth = '120px',
href = '/',
download = false,
fontFamily = 'Inter, sans-serif',
fontSize = '20px',
fontWeight = '700',
@@ -44,6 +53,7 @@ export const Logo: UserComponent<LogoProps> = ({
<a
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
href={href}
download={download || undefined}
onClick={(e) => e.preventDefault()}
style={{
textDecoration: 'none',
@@ -87,7 +97,13 @@ Logo.craft = {
fontSize: '20px',
fontWeight: '700',
color: undefined,
download: false,
style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as LogoProps,
rules: {
canDrag: () => true,
@@ -110,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>`;
}
@@ -122,8 +138,9 @@ Logo.craft = {
flexShrink: '0',
...props.style,
});
const downloadAttr = props.download ? ' download' : '';
return {
html: `<a href="${escapeAttr(safeUrl(href))}"${aStyle ? ` style="${aStyle}"` : ''}>${innerHtml}</a>`,
html: `<a href="${escapeAttr(safeUrl(href))}"${downloadAttr}${aStyle ? ` style="${aStyle}"` : ''}>${innerHtml}</a>`,
};
};
@@ -31,6 +31,29 @@ describe('Menu.toHtml deterministic + unique scope ids (thread node id, no Math.
});
});
describe('Menu.toHtml download attribute (F3: link-to-file toggle)', () => {
test('a link with download:true emits the download attribute', () => {
const { html } = toHtml({ links: [{ text: 'Brochure', href: '/brochure.pdf', download: true }] }, '', 'node-dl1');
expect(html).toMatch(/<a href="\/brochure\.pdf"[^>]* download[^>]*>Brochure<\/a>/);
});
test('a link without download does not emit the attribute', () => {
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }] }, '', 'node-dl2');
expect(html).not.toContain(' download');
});
});
describe('Menu (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Menu as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
test('a linkHoverColor value containing </style><script> is neutralized', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
@@ -44,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());
});
});
+93 -23
View File
@@ -2,18 +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;
}
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;
@@ -23,6 +22,11 @@ interface MenuProps {
orientation?: 'horizontal' | 'vertical';
fontSize?: string;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Defaults ---------- */
@@ -39,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',
@@ -53,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' };
@@ -69,12 +74,15 @@ 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}
target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)}
@@ -94,26 +102,68 @@ 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',
style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as MenuProps,
rules: {
canDrag: () => true,
@@ -129,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';
@@ -160,8 +210,9 @@ 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`;
const linkStyle = cssPropsToString({
textDecoration: 'none',
@@ -173,12 +224,31 @@ Menu.craft = {
borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s',
});
return `<a href="${escapeAttr(safeUrl(link.href || '#'))}" class="${cls}"${target}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
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}">&#9662;</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 {
@@ -83,6 +83,29 @@ describe('Navbar.toHtml node-scoped ids/hover styles (M-1: two navbars must not
});
});
describe('Navbar.toHtml download attribute (F3: link-to-file toggle)', () => {
test('a link with download:true emits the download attribute', () => {
const { html } = toHtml({ links: [{ text: 'Brochure', href: '/brochure.pdf', download: true }] }, '', 'node-dl1');
expect(html).toMatch(/<a href="\/brochure\.pdf"[^>]* download[^>]*>Brochure<\/a>/);
});
test('a link without download does not emit the attribute', () => {
const { html } = toHtml({ links: [{ text: 'Home', href: '/' }] }, '', 'node-dl2');
expect(html).not.toContain(' download');
});
});
describe('Navbar (F4: box-model + animation + visibility props on craft.props)', () => {
test('craft.props includes animation/visibility defaults so the panel controls always render', () => {
const craftProps = (Navbar as any).craft.props;
expect(craftProps).toHaveProperty('animation', 'none');
expect(craftProps).toHaveProperty('animationDelay', '0');
expect(craftProps).toHaveProperty('hideOnDesktop', false);
expect(craftProps).toHaveProperty('hideOnTablet', false);
expect(craftProps).toHaveProperty('hideOnMobile', false);
});
});
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
@@ -117,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"');
});
});
+110 -48
View File
@@ -3,16 +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;
}
interface NavbarProps {
logoType?: 'text' | 'image';
logoText?: string;
@@ -23,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;
@@ -33,6 +31,11 @@ interface NavbarProps {
isSticky?: boolean;
showMobileMenu?: boolean;
style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
}
/* ---------- Defaults ---------- */
@@ -51,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> = ({
@@ -63,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,
@@ -82,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
@@ -143,12 +159,15 @@ 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}
target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)}
@@ -168,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>
);
@@ -188,18 +237,26 @@ 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,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as NavbarProps,
rules: {
canDrag: () => true,
@@ -214,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;
@@ -263,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
@@ -297,17 +340,26 @@ 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';
const linkStyle = cssPropsToString({
textDecoration: 'none',
@@ -319,7 +371,17 @@ Navbar.craft = {
borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s',
});
return `<a href="${escapeAttr(safeUrl(link.href || "#"))}" class="${cls}"${target}${linkStyle ? ` style="${linkStyle}"` : ''}>${escapeHtml(link.text)}</a>`;
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}">&#9662;</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"'));
});
@@ -30,3 +30,65 @@ describe('SearchBar.toHtml XSS hardening (placeholder/buttonText/showButton)', (
expect(html).toMatch(/border-radius:(8px 0 0 8px|8px)/);
});
});
// F2: SearchBar was purely decorative -- no action/method/input name, so
// submitting did nothing. It now emits a real GET form.
describe('SearchBar.toHtml is a functional GET search form (not decorative)', () => {
test('defaults to a GET form action="/" with the query input named "q"', () => {
const { html } = toHtml({}, '');
expect(html).toMatch(/<form role="search" action="\/" method="GET"/);
expect(html).toContain('<input type="search" name="q"');
});
test('a configured action (real search-results page) is used verbatim', () => {
const { html } = toHtml({ action: '/search' }, '');
expect(html).toContain('action="/search"');
});
test('a javascript: action is blocked via safeUrl and falls back to "/"', () => {
const { html } = toHtml({ action: 'javascript:alert(1)' }, '');
expect(html).toContain('action="/"');
expect(html).not.toContain('javascript:');
});
test('an empty/whitespace action falls back to "/"', () => {
const { html } = toHtml({ action: ' ' }, '');
expect(html).toContain('action="/"');
});
});
describe('SearchBar.toHtml box-model style passthrough', () => {
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
const { html } = toHtml({ style: { marginBottom: '14px', border: '1px solid #aaa', boxShadow: '0 1px 4px rgba(0,0,0,.1)', opacity: '0.9' } }, '');
expect(html).toContain('margin-bottom:14px');
expect(html).toContain('border:1px solid #aaa');
expect(html).toContain('opacity:0.9');
});
});
describe('SearchBar.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults', () => {
expect(SearchBar.craft!.props).toMatchObject({
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
});
});
});
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);
});
});
+43 -14
View File
@@ -1,19 +1,30 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
import { tokenRef } from '../../utils/tokens';
interface SearchBarProps {
placeholder?: string;
buttonText?: string;
showButton?: boolean;
/** Where the search GET request is submitted -- a real search-results page
* if the site has one, or '/' (site root) by default. The query is sent
* as `?q=...`, the conventional param name search-results pages look for. */
action?: string;
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const SearchBar: UserComponent<SearchBarProps> = ({
placeholder = 'Search...',
buttonText = 'Search',
showButton = true,
action = '/',
style = {},
}) => {
const {
@@ -27,6 +38,8 @@ export const SearchBar: UserComponent<SearchBarProps> = ({
<form
ref={(ref: HTMLFormElement | null): void => { if (ref) connect(drag(ref)); }}
role="search"
action={action}
method="GET"
onSubmit={(e) => e.preventDefault()}
style={{
display: 'flex',
@@ -38,29 +51,30 @@ 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',
}}
/>
<input
type="search"
name="q"
placeholder={placeholder}
style={{
width: '100%',
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',
}}
@@ -74,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',
@@ -85,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>
)}
@@ -101,7 +115,13 @@ SearchBar.craft = {
placeholder: 'Search...',
buttonText: 'Search',
showButton: true,
action: '/',
style: {},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -117,6 +137,7 @@ SearchBar.craft = {
placeholder = 'Search...',
buttonText = 'Search',
showButton = true,
action = '/',
style = {},
} = props;
@@ -127,17 +148,25 @@ 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
// name at all, so submitting did nothing. A real GET to `action` with the
// query in the conventional `q` param makes this a functioning search
// form on publish (routes to a real search-results page if the site has
// one, or reloads '/' with ?q=... by default). `safeUrl` blocks
// javascript:/vbscript:/data:text/html breakout via the action attribute.
const actionAttr = escapeAttr(safeUrl(action) || '/');
return {
html: `<form role="search"${formStyle ? ` style="${formStyle}"` : ''}>
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>
<input type="search" placeholder="${escapeAttr(placeholder)}" style="${inputStyleStr}" />
<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}
</form>`,
@@ -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"/);
});
});
@@ -51,3 +51,53 @@ describe('SocialLinks.toHtml XSS hardening (iconSize/iconColor/iconBgColor/gap i
expect(html).not.toContain('javascript:alert(1)');
});
});
describe('SocialLinks.toHtml iconShape/gap emission (previously built but unexposed in SocialStylePanel)', () => {
test('iconShape="circle" emits a 50% border-radius on the wrapping <a>', () => {
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'circle' }, '');
expect(html).toMatch(/<a[^>]*style="[^"]*border-radius:50%[^"]*"/);
});
test('iconShape="square" emits border-radius:0', () => {
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'square' }, '');
expect(html).toMatch(/<a[^>]*style="[^"]*border-radius:0[^"]*"/);
});
test('iconShape="rounded" emits a 6px border-radius', () => {
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'rounded' }, '');
expect(html).toMatch(/<a[^>]*style="[^"]*border-radius:6px[^"]*"/);
});
test('iconShape="none" omits the background box entirely (transparent bg, no fixed box size)', () => {
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'none' }, '');
const aTag = html.match(/<a[^>]*>/)![0];
expect(aTag).toContain('background-color:transparent');
expect(aTag).not.toContain('border-radius');
});
test('gap emits on the wrapper <div> style', () => {
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], gap: '24px' }, '');
expect(html).toMatch(/<div[^>]*style="[^"]*gap:24px[^"]*"/);
});
});
describe('SocialLinks.craft.props includes the box-model/animation/visibility rollout props', () => {
test('animation, animationDelay, and all 3 hideOn* flags are declared (blank/false defaults)', () => {
const props = (SocialLinks as any).craft.props;
expect(props).toHaveProperty('animation', '');
expect(props).toHaveProperty('animationDelay', '');
expect(props).toHaveProperty('hideOnDesktop', false);
expect(props).toHaveProperty('hideOnTablet', false);
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());
});
});
+45 -22
View File
@@ -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 {
@@ -17,21 +18,32 @@ interface SocialLinksProps {
gap?: string;
alignment?: 'left' | 'center' | 'right';
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
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> = {
@@ -47,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[] = [
@@ -82,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',
@@ -110,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';
@@ -130,7 +148,7 @@ export const SocialLinks: UserComponent<SocialLinksProps> = ({
...shapeStyle,
}}
>
<i className={`fa ${iconClass}`} style={{ fontSize: iconSize }} />
<i className={iconClass} style={{ fontSize: iconSize }} />
</a>
);
})}
@@ -145,12 +163,17 @@ SocialLinks.craft = {
props: {
links: defaultLinks,
iconSize: '20px',
iconColor: '#ffffff',
iconBgColor: '#374151',
iconColor: tokenRef('bg'),
iconBgColor: tokenRef('text'),
iconShape: 'circle',
gap: '10px',
alignment: 'center',
style: {},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -165,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';
@@ -199,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) {
@@ -209,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);
});
@@ -75,3 +75,23 @@ describe('StarRating.toHtml XSS hardening (rating/maxStars into aria-label, F2.2
expect(html).toMatch(/<span role="img" aria-label="Rating: 4\.5 out of 5"/);
});
});
describe('StarRating.craft.props includes the box-model/animation/visibility rollout props', () => {
test('animation, animationDelay, and all 3 hideOn* flags are declared (blank/false defaults)', () => {
const props = (StarRating as any).craft.props;
expect(props).toHaveProperty('animation', '');
expect(props).toHaveProperty('animationDelay', '');
expect(props).toHaveProperty('hideOnDesktop', false);
expect(props).toHaveProperty('hideOnTablet', false);
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);
});
});
+24 -13
View File
@@ -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';
@@ -10,14 +11,19 @@ interface StarRatingProps {
filledColor?: string;
emptyColor?: string;
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const StarRating: UserComponent<StarRatingProps> = ({
rating = 4.5,
maxStars = 5,
size = '24px',
filledColor = '#f59e0b',
emptyColor = '#d1d5db',
filledColor = tokenRef('warning'),
emptyColor = tokenRef('border'),
style = {},
}) => {
const {
@@ -34,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 }}
/>
);
@@ -42,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>
);
@@ -53,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 }}
/>
);
@@ -84,9 +90,14 @@ StarRating.craft = {
rating: 4.5,
maxStars: 5,
size: '24px',
filledColor: '#f59e0b',
emptyColor: '#d1d5db',
filledColor: tokenRef('warning'),
emptyColor: tokenRef('border'),
style: {},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -113,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',
@@ -125,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>`;
}
}
@@ -20,3 +20,107 @@ describe('TextBlock.toHtml text escaping (attacker-controlled `text` prop)', ()
expect(html).toBe('<p>Hello world</p>');
});
});
describe('TextBlock.toHtml typography depth (line-height/letter-spacing/transform/style/decoration)', () => {
test('line-height, letter-spacing, text-transform all flow into the style attribute', () => {
const { html } = toHtml({
text: 'x',
style: { lineHeight: '1.75', letterSpacing: '-0.02em', textTransform: 'capitalize' },
}, '');
expect(html).toContain('line-height:1.75');
expect(html).toContain('letter-spacing:-0.02em');
expect(html).toContain('text-transform:capitalize');
});
test('italic + underline toggles emit font-style and text-decoration', () => {
const { html } = toHtml({ text: 'x', style: { fontStyle: 'italic', textDecoration: 'underline' } }, '');
expect(html).toContain('font-style:italic');
expect(html).toContain('text-decoration:underline');
});
test('a custom font-size (not one of the presets) still flows through', () => {
const { html } = toHtml({ text: 'x', style: { fontSize: '19px' } }, '');
expect(html).toContain('font-size:19px');
});
});
describe('TextBlock.craft.props exposes the box-model + animation/visibility rollout', () => {
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
const props = (TextBlock as any).craft.props;
expect(props.animation).toBe('');
expect(props.animationDelay).toBe('0');
expect(props.hideOnDesktop).toBe(false);
expect(props.hideOnTablet).toBe(false);
expect(props.hideOnMobile).toBe(false);
});
test('style carries blank/default box-model + typography-depth keys', () => {
const style = (TextBlock as any).craft.props.style;
expect(style).toHaveProperty('marginTop');
expect(style).toHaveProperty('paddingTop');
expect(style).toHaveProperty('letterSpacing');
expect(style).toHaveProperty('textTransform');
expect(style.border).toBe('none');
expect(style.boxShadow).toBe('none');
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&lt;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 &lt;copy&gt;</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="jav&#x61;script: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 &lt;i&gt;</p>');
});
});
+28 -31
View File
@@ -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,11 +61,26 @@ 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'],
textDecoration: '',
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
border: 'none',
boxShadow: 'none',
opacity: '1',
},
animation: '',
animationDelay: '0',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -96,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,426 @@
<!-- ============================================================
HTML test fixture — everything below goes inside <body>
Unstyled on purpose. No external assets (SVG/data URIs only)
except the media/iframe block, which is intentionally broken
so you can see fallback behavior.
============================================================ -->
<a href="#main">Skip to content</a>
<header>
<h1>HTML Test Fixture</h1>
<p><small>A wide sample of elements for rendering, sanitizing, and parsing tests.</small></p>
<nav aria-label="Primary">
<ul>
<li><a href="#text">Text</a></li>
<li><a href="#lists">Lists</a></li>
<li><a href="#tables">Tables</a></li>
<li><a href="#forms">Forms</a></li>
<li><a href="#media">Media</a></li>
<li><a href="#edge">Edge cases</a></li>
</ul>
</nav>
</header>
<main id="main">
<!-- ========== HEADINGS ========== -->
<section id="headings">
<h2>Headings</h2>
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>
<hgroup>
<h2>Grouped heading</h2>
<p>Subtitle paragraph inside hgroup</p>
</hgroup>
</section>
<hr>
<!-- ========== TEXT & INLINE ========== -->
<section id="text">
<h2>Text and inline elements</h2>
<p>A normal paragraph with a fair amount of text so you can check line height, wrapping, and measure. It runs long enough to break across several lines in most containers, which is the whole point of including it here at all.</p>
<p>
<strong>strong</strong>, <b>b</b>, <em>em</em>, <i>i</i>, <u>u</u>,
<s>s</s>, <del>del</del>, <ins>ins</ins>, <mark>mark</mark>,
<small>small</small>, H<sub>2</sub>O, x<sup>2</sup>,
<code>inline code</code>, <kbd>Ctrl</kbd>+<kbd>C</kbd>,
<samp>output text</samp>, <var>variable</var>,
<abbr title="HyperText Markup Language">HTML</abbr>,
<dfn>definition term</dfn>,
<time datetime="2026-08-09">August 9, 2026</time>,
<data value="42">forty-two</data>,
<q>short inline quote</q>,
<cite>Cited Work</cite>,
<bdi>إسم</bdi>,
<bdo dir="rtl">reversed direction</bdo>,
<ruby>漢<rt>kan</rt>字<rt>ji</rt></ruby>
</p>
<p>
Links:
<a href="#top">internal anchor</a> ·
<a href="https://example.com">absolute</a> ·
<a href="/relative/path">relative</a> ·
<a href="mailto:test@example.com">mailto</a> ·
<a href="tel:+15555550123">tel</a> ·
<a href="https://example.com" target="_blank" rel="noopener noreferrer">new tab</a> ·
<a href="#" download>download attr</a>
</p>
<blockquote cite="https://example.com/source">
<p>A block quotation. It contains its own paragraph and a nested quote so you can check indentation stacking.</p>
<blockquote><p>Nested block quotation.</p></blockquote>
<footer>— <cite>Someone, Somewhere</cite></footer>
</blockquote>
<pre><code>#!/usr/bin/env bash
set -euo pipefail
for i in {1..3}; do
printf 'iteration %d\n' "$i"
done
# a deliberately long line to force horizontal overflow: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</code></pre>
<p>Line break here,<br>after the break.</p>
<p>Word break opportunity: super<wbr>cali<wbr>fragilistic<wbr>expiali<wbr>docious</p>
<address>
Contact: <a href="mailto:admin@example.com">admin@example.com</a><br>
123 Nowhere St, Somewhere
</address>
<p>Entities: &amp; &lt; &gt; &quot; &apos; &copy; &reg; &trade; &nbsp; &mdash; &hellip; &#8364; &#x1F600;</p>
</section>
<hr>
<!-- ========== LISTS ========== -->
<section id="lists">
<h2>Lists</h2>
<h3>Unordered, nested</h3>
<ul>
<li>First item</li>
<li>Second item
<ul>
<li>Nested item
<ul><li>Deeply nested item</li></ul>
</li>
<li>Another nested item</li>
</ul>
</li>
<li>Third item with a longer body of text so that it wraps onto more than one line and you can confirm the hanging indent behaves.</li>
</ul>
<h3>Ordered variants</h3>
<ol>
<li>Default numbering</li>
<li>Second
<ol type="a"><li>Lower alpha</li><li>Second alpha</li></ol>
</li>
</ol>
<ol start="5" reversed>
<li>Reversed, starting at 5</li>
<li>Next</li>
<li>Next</li>
</ol>
<h3>Description list</h3>
<dl>
<dt>Term one</dt>
<dd>Definition of the first term.</dd>
<dt>Term two</dt>
<dt>Term two, alias</dt>
<dd>Definition covering both terms above.</dd>
</dl>
<h3>Menu</h3>
<menu>
<li><button type="button">Copy</button></li>
<li><button type="button">Paste</button></li>
</menu>
</section>
<hr>
<!-- ========== TABLES ========== -->
<section id="tables">
<h2>Tables</h2>
<table>
<caption>Quarterly figures with spans and a footer</caption>
<colgroup>
<col span="1">
<col span="2">
<col>
</colgroup>
<thead>
<tr>
<th scope="col">Region</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">North</th>
<td>1,204</td>
<td>1,391</td>
<td rowspan="2">Shared note spanning two rows</td>
</tr>
<tr>
<th scope="row">South</th>
<td>988</td>
<td>1,022</td>
</tr>
<tr>
<th scope="row">East</th>
<td colspan="2">Merged across two quarters</td>
<td>—</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Total</th>
<td>2,192</td>
<td>2,413</td>
<td></td>
</tr>
</tfoot>
</table>
<h3>Wide table (horizontal overflow)</h3>
<table>
<tr><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th><th>H</th><th>I</th><th>J</th><th>K</th><th>L</th></tr>
<tr><td>value-1</td><td>value-2</td><td>value-3</td><td>value-4</td><td>value-5</td><td>value-6</td><td>value-7</td><td>value-8</td><td>value-9</td><td>value-10</td><td>value-11</td><td>value-12</td></tr>
</table>
</section>
<hr>
<!-- ========== FORMS ========== -->
<section id="forms">
<h2>Forms</h2>
<form action="#" method="get">
<fieldset>
<legend>Text inputs</legend>
<p><label for="f-text">Text</label> <input id="f-text" name="text" type="text" placeholder="Placeholder" value="Prefilled"></p>
<p><label for="f-search">Search</label> <input id="f-search" type="search" list="suggestions"></p>
<datalist id="suggestions">
<option value="alpha"></option>
<option value="beta"></option>
<option value="gamma"></option>
</datalist>
<p><label for="f-email">Email</label> <input id="f-email" type="email" required></p>
<p><label for="f-url">URL</label> <input id="f-url" type="url"></p>
<p><label for="f-tel">Tel</label> <input id="f-tel" type="tel" pattern="[0-9-+ ]+"></p>
<p><label for="f-pass">Password</label> <input id="f-pass" type="password" minlength="8"></p>
<p><label for="f-num">Number</label> <input id="f-num" type="number" min="0" max="100" step="5" value="25"></p>
<p><label for="f-area">Textarea</label><br><textarea id="f-area" rows="4" cols="40">Multiline
content
here</textarea></p>
<p><label for="f-ro">Readonly</label> <input id="f-ro" type="text" value="read only" readonly></p>
<p><label for="f-dis">Disabled</label> <input id="f-dis" type="text" value="disabled" disabled></p>
</fieldset>
<fieldset>
<legend>Date, time, color, range, file</legend>
<p><label for="f-date">Date</label> <input id="f-date" type="date" value="2026-08-09"></p>
<p><label for="f-time">Time</label> <input id="f-time" type="time" value="13:45"></p>
<p><label for="f-dtl">Datetime-local</label> <input id="f-dtl" type="datetime-local"></p>
<p><label for="f-month">Month</label> <input id="f-month" type="month"></p>
<p><label for="f-week">Week</label> <input id="f-week" type="week"></p>
<p><label for="f-color">Color</label> <input id="f-color" type="color" value="#336699"></p>
<p><label for="f-range">Range</label> <input id="f-range" type="range" min="0" max="10" value="7"></p>
<p><label for="f-file">File</label> <input id="f-file" type="file" multiple accept=".txt,.md"></p>
</fieldset>
<fieldset>
<legend>Choices</legend>
<p>
<label><input type="checkbox" name="c" value="1" checked> Checked</label>
<label><input type="checkbox" name="c" value="2"> Unchecked</label>
<label><input type="checkbox" name="c" value="3" disabled> Disabled</label>
</p>
<p>
<label><input type="radio" name="r" value="a" checked> Option A</label>
<label><input type="radio" name="r" value="b"> Option B</label>
</p>
<p>
<label for="f-select">Select</label>
<select id="f-select" name="select">
<option value="">— choose —</option>
<optgroup label="Group one">
<option value="1" selected>One</option>
<option value="2">Two</option>
</optgroup>
<optgroup label="Group two" disabled>
<option value="3">Three</option>
</optgroup>
</select>
</p>
<p>
<label for="f-multi">Multi-select</label><br>
<select id="f-multi" multiple size="4">
<option>Red</option><option selected>Green</option><option>Blue</option><option>Violet</option>
</select>
</p>
</fieldset>
<fieldset>
<legend>Output and buttons</legend>
<p><label for="f-prog">Progress</label> <progress id="f-prog" value="0.6">60%</progress></p>
<p><label for="f-meter">Meter</label> <meter id="f-meter" min="0" max="100" low="30" high="80" optimum="90" value="72">72</meter></p>
<p><output name="result" for="f-num f-range">Computed output</output></p>
<p>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button">Plain button</button>
<button type="button" disabled>Disabled button</button>
<input type="submit" value="Input submit">
<input type="button" value="Input button">
</p>
<input type="hidden" name="csrf" value="hidden-value">
</fieldset>
</form>
</section>
<hr>
<!-- ========== MEDIA & EMBEDS ========== -->
<section id="media">
<h2>Media and embeds</h2>
<h3>Inline SVG</h3>
<svg width="180" height="90" viewBox="0 0 180 90" role="img" aria-label="Two shapes">
<rect x="5" y="5" width="80" height="80" fill="none" stroke="currentColor" stroke-width="3"></rect>
<circle cx="135" cy="45" r="40" fill="none" stroke="currentColor" stroke-width="3"></circle>
<text x="45" y="50" text-anchor="middle" font-size="14" fill="currentColor">svg</text>
</svg>
<h3>Figure with data-URI image</h3>
<figure>
<img alt="Small red square"
width="64" height="64"
src="data:image/svg+xml;utf8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20width%3D'64'%20height%3D'64'%3E%3Crect%20width%3D'64'%20height%3D'64'%20fill%3D'%23c0392b'%2F%3E%3C%2Fsvg%3E">
<figcaption>Figure caption describing the image above.</figcaption>
</figure>
<h3>Broken image (alt-text fallback test)</h3>
<img src="does-not-exist.png" alt="This alt text should render because the source is missing" width="200" height="100">
<h3>Picture element</h3>
<picture>
<source media="(min-width: 800px)" srcset="wide.png">
<source media="(min-width: 400px)" srcset="medium.png">
<img src="narrow.png" alt="Responsive image fallback" width="150" height="80">
</picture>
<h3>Video and audio (sources intentionally missing)</h3>
<video controls width="320" poster="poster.jpg">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<track kind="captions" src="captions.vtt" srclang="en" label="English">
Your browser does not support the video element.
</video>
<audio controls>
<source src="tone.ogg" type="audio/ogg">
<source src="tone.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<h3>Canvas and iframe</h3>
<canvas width="200" height="60">Canvas fallback text</canvas>
<iframe title="Sandboxed iframe" src="about:blank" width="300" height="120" sandbox loading="lazy"></iframe>
</section>
<hr>
<!-- ========== INTERACTIVE / SEMANTIC ========== -->
<section id="interactive">
<h2>Interactive and semantic containers</h2>
<details>
<summary>Collapsed disclosure</summary>
<p>Hidden content revealed on toggle.</p>
</details>
<details open>
<summary>Open disclosure</summary>
<ul><li>With a list inside</li><li>Second item</li></ul>
</details>
<dialog id="test-dialog">
<p>Non-modal dialog content.</p>
<button type="button" onclick="this.closest('dialog').close()">Close</button>
</dialog>
<button type="button" onclick="document.getElementById('test-dialog').show()">Open dialog</button>
<article>
<header><h3>Article header</h3></header>
<p>Article body content.</p>
<aside><p>An aside nested inside the article.</p></aside>
<footer><p>Article footer.</p></footer>
</article>
<p><span contenteditable="true">Editable inline region</span></p>
<p hidden>This paragraph has the hidden attribute and should not render.</p>
<template id="tpl">
<p>Template content — must not render until cloned.</p>
</template>
</section>
<hr>
<!-- ========== EDGE CASES ========== -->
<section id="edge">
<h2>Edge cases</h2>
<p>Very long unbroken token (overflow test):</p>
<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
<p>Long URL: https://example.com/a/very/long/path/segment/that/keeps/going/and/going?query=1&amp;another=2&amp;third=3#fragment-identifier</p>
<p lang="ar" dir="rtl">هذا نص عربي لاختبار الاتجاه من اليمين إلى اليسار.</p>
<p lang="he" dir="rtl">זהו טקסט עברי לבדיקה.</p>
<p lang="ja">日本語のテキストです。改行と折り返しの確認用。</p>
<p lang="de">Straßenverkehrsordnung — Grüße aus München</p>
<p>Emoji &amp; combining: 👋🏽 👨‍👩‍👧‍👦 🇺🇸 é vs é (precomposed vs combining)</p>
<p>Zero-width chars between letters: a&#8203;b&#8203;c</p>
<p>Escaped tag text: &lt;script&gt;alert(1)&lt;/script&gt;</p>
<p>Attribute with quotes: <span title='He said "hello"'>hover me</span></p>
<p>Empty elements follow:</p>
<div></div>
<p></p>
<ul></ul>
<table></table>
<p>Deep nesting:</p>
<div><div><div><div><div><div><div><p>Seven levels deep.</p></div></div></div></div></div></div></div>
<p>Inline element stress:
<strong><em><u><s><mark>all five at once</mark></s></u></em></strong>
</p>
<p style="color: teal;">Inline style attribute (teal).</p>
<p class="custom-class another-class" data-test-id="edge-1" data-value="42">Element with classes and data attributes.</p>
</section>
</main>
<footer>
<p><small>End of fixture — <time datetime="2026-08-09">2026-08-09</time></small></p>
</footer>
@@ -0,0 +1,415 @@
<a href="#main">Skip to content</a>
<header>
<h1>HTML Test Fixture</h1>
<p><small>A wide sample of elements for rendering, sanitizing, and parsing tests.</small></p>
<nav aria-label="Primary">
<ul>
<li><a href="#text">Text</a></li>
<li><a href="#lists">Lists</a></li>
<li><a href="#tables">Tables</a></li>
<li><a href="#forms">Forms</a></li>
<li><a href="#media">Media</a></li>
<li><a href="#edge">Edge cases</a></li>
</ul>
</nav>
</header>
<main id="main">
<section id="headings">
<h2>Headings</h2>
<h1>Heading level 1</h1>
<h2>Heading level 2</h2>
<h3>Heading level 3</h3>
<h4>Heading level 4</h4>
<h5>Heading level 5</h5>
<h6>Heading level 6</h6>
<hgroup>
<h2>Grouped heading</h2>
<p>Subtitle paragraph inside hgroup</p>
</hgroup>
</section>
<hr>
<section id="text">
<h2>Text and inline elements</h2>
<p>A normal paragraph with a fair amount of text so you can check line height, wrapping, and measure. It runs long enough to break across several lines in most containers, which is the whole point of including it here at all.</p>
<p>
<strong>strong</strong>, <b>b</b>, <em>em</em>, <i>i</i>, <u>u</u>,
<s>s</s>, <del>del</del>, <ins>ins</ins>, <mark>mark</mark>,
<small>small</small>, H<sub>2</sub>O, x<sup>2</sup>,
<code>inline code</code>, <kbd>Ctrl</kbd>+<kbd>C</kbd>,
<samp>output text</samp>, <var>variable</var>,
<abbr title="HyperText Markup Language">HTML</abbr>,
<dfn>definition term</dfn>,
<time datetime="2026-08-09">August 9, 2026</time>,
<data value="42">forty-two</data>,
<q>short inline quote</q>,
<cite>Cited Work</cite>,
<bdi>إسم</bdi>,
<bdo dir="rtl">reversed direction</bdo>,
<ruby>漢<rt>kan</rt>字<rt>ji</rt></ruby>
</p>
<p>
Links:
<a href="#top">internal anchor</a> ·
<a href="https://example.com">absolute</a> ·
<a href="/relative/path">relative</a> ·
<a href="mailto:test@example.com">mailto</a> ·
<a href="tel:+15555550123">tel</a> ·
<a href="https://example.com" target="_blank" rel="noopener noreferrer">new tab</a> ·
<a href="#" download="">download attr</a>
</p>
<blockquote cite="https://example.com/source">
<p>A block quotation. It contains its own paragraph and a nested quote so you can check indentation stacking.</p>
<blockquote><p>Nested block quotation.</p></blockquote>
<footer>— <cite>Someone, Somewhere</cite></footer>
</blockquote>
<pre><code>#!/usr/bin/env bash
set -euo pipefail
for i in {1..3}; do
printf 'iteration %d\n' "$i"
done
# a deliberately long line to force horizontal overflow: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
</code></pre>
<p>Line break here,<br>after the break.</p>
<p>Word break opportunity: super<wbr>cali<wbr>fragilistic<wbr>expiali<wbr>docious</p>
<address>
Contact: <a href="mailto:admin@example.com">admin@example.com</a><br>
123 Nowhere St, Somewhere
</address>
<p>Entities: &amp; &lt; &gt; " ' © ® ™ &nbsp; — … € 😀</p>
</section>
<hr>
<section id="lists">
<h2>Lists</h2>
<h3>Unordered, nested</h3>
<ul>
<li>First item</li>
<li>Second item
<ul>
<li>Nested item
<ul><li>Deeply nested item</li></ul>
</li>
<li>Another nested item</li>
</ul>
</li>
<li>Third item with a longer body of text so that it wraps onto more than one line and you can confirm the hanging indent behaves.</li>
</ul>
<h3>Ordered variants</h3>
<ol>
<li>Default numbering</li>
<li>Second
<ol type="a"><li>Lower alpha</li><li>Second alpha</li></ol>
</li>
</ol>
<ol start="5" reversed="">
<li>Reversed, starting at 5</li>
<li>Next</li>
<li>Next</li>
</ol>
<h3>Description list</h3>
<dl>
<dt>Term one</dt>
<dd>Definition of the first term.</dd>
<dt>Term two</dt>
<dt>Term two, alias</dt>
<dd>Definition covering both terms above.</dd>
</dl>
<h3>Menu</h3>
<menu>
<li><button type="button">Copy</button></li>
<li><button type="button">Paste</button></li>
</menu>
</section>
<hr>
<section id="tables">
<h2>Tables</h2>
<table>
<caption>Quarterly figures with spans and a footer</caption>
<colgroup>
<col span="1">
<col span="2">
<col>
</colgroup>
<thead>
<tr>
<th scope="col">Region</th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">North</th>
<td>1,204</td>
<td>1,391</td>
<td rowspan="2">Shared note spanning two rows</td>
</tr>
<tr>
<th scope="row">South</th>
<td>988</td>
<td>1,022</td>
</tr>
<tr>
<th scope="row">East</th>
<td colspan="2">Merged across two quarters</td>
<td>—</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row">Total</th>
<td>2,192</td>
<td>2,413</td>
<td></td>
</tr>
</tfoot>
</table>
<h3>Wide table (horizontal overflow)</h3>
<table>
<tbody><tr><th>A</th><th>B</th><th>C</th><th>D</th><th>E</th><th>F</th><th>G</th><th>H</th><th>I</th><th>J</th><th>K</th><th>L</th></tr>
<tr><td>value-1</td><td>value-2</td><td>value-3</td><td>value-4</td><td>value-5</td><td>value-6</td><td>value-7</td><td>value-8</td><td>value-9</td><td>value-10</td><td>value-11</td><td>value-12</td></tr>
</tbody></table>
</section>
<hr>
<section>
<h2>Forms</h2>
<form action="#" method="get">
<fieldset>
<legend>Text inputs</legend>
<p><label for="f-text">Text</label> <input id="f-text" name="text" type="text" placeholder="Placeholder" value="Prefilled"></p>
<p><label for="f-search">Search</label> <input id="f-search" type="search" list="suggestions"></p>
<datalist id="suggestions">
<option value="alpha"></option>
<option value="beta"></option>
<option value="gamma"></option>
</datalist>
<p><label for="f-email">Email</label> <input id="f-email" type="email" required=""></p>
<p><label for="f-url">URL</label> <input id="f-url" type="url"></p>
<p><label for="f-tel">Tel</label> <input id="f-tel" type="tel" pattern="[0-9-+ ]+"></p>
<p><label for="f-pass">Password</label> <input id="f-pass" type="password" minlength="8"></p>
<p><label for="f-num">Number</label> <input id="f-num" type="number" min="0" max="100" step="5" value="25"></p>
<p><label for="f-area">Textarea</label><br><textarea id="f-area" rows="4" cols="40">Multiline
content
here</textarea></p>
<p><label for="f-ro">Readonly</label> <input id="f-ro" type="text" value="read only" readonly=""></p>
<p><label for="f-dis">Disabled</label> <input id="f-dis" type="text" value="disabled" disabled=""></p>
</fieldset>
<fieldset>
<legend>Date, time, color, range, file</legend>
<p><label for="f-date">Date</label> <input id="f-date" type="date" value="2026-08-09"></p>
<p><label for="f-time">Time</label> <input id="f-time" type="time" value="13:45"></p>
<p><label for="f-dtl">Datetime-local</label> <input id="f-dtl" type="datetime-local"></p>
<p><label for="f-month">Month</label> <input id="f-month" type="month"></p>
<p><label for="f-week">Week</label> <input id="f-week" type="week"></p>
<p><label for="f-color">Color</label> <input id="f-color" type="color" value="#336699"></p>
<p><label for="f-range">Range</label> <input id="f-range" type="range" min="0" max="10" value="7"></p>
<p><label for="f-file">File</label> <input id="f-file" type="file" multiple="" accept=".txt,.md"></p>
</fieldset>
<fieldset>
<legend>Choices</legend>
<p>
<label><input type="checkbox" name="c" value="1" checked=""> Checked</label>
<label><input type="checkbox" name="c" value="2"> Unchecked</label>
<label><input type="checkbox" name="c" value="3" disabled=""> Disabled</label>
</p>
<p>
<label><input type="radio" name="r" value="a" checked=""> Option A</label>
<label><input type="radio" name="r" value="b"> Option B</label>
</p>
<p>
<label for="f-select">Select</label>
<select id="f-select" name="select">
<option value="">— choose —</option>
<optgroup label="Group one">
<option value="1" selected="">One</option>
<option value="2">Two</option>
</optgroup>
<optgroup label="Group two" disabled="">
<option value="3">Three</option>
</optgroup>
</select>
</p>
<p>
<label for="f-multi">Multi-select</label><br>
<select id="f-multi" multiple="" size="4">
<option>Red</option><option selected="">Green</option><option>Blue</option><option>Violet</option>
</select>
</p>
</fieldset>
<fieldset>
<legend>Output and buttons</legend>
<p><label for="f-prog">Progress</label> <progress id="f-prog" value="0.6">60%</progress></p>
<p><label for="f-meter">Meter</label> <meter id="f-meter" min="0" max="100" low="30" high="80" optimum="90" value="72">72</meter></p>
<p><output name="result" for="f-num f-range">Computed output</output></p>
<p>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button">Plain button</button>
<button type="button" disabled="">Disabled button</button>
<input type="submit" value="Input submit">
<input type="button" value="Input button">
</p>
<input type="hidden" name="csrf" value="hidden-value">
</fieldset>
</form>
</section>
<hr>
<section id="media">
<h2>Media and embeds</h2>
<h3>Inline SVG</h3>
<svg width="180" height="90" viewBox="0 0 180 90" role="img" aria-label="Two shapes">
<rect x="5" y="5" width="80" height="80" fill="none" stroke="currentColor" stroke-width="3"></rect>
<circle cx="135" cy="45" r="40" fill="none" stroke="currentColor" stroke-width="3"></circle>
<text x="45" y="50" text-anchor="middle" font-size="14" fill="currentColor">svg</text>
</svg>
<h3>Figure with data-URI image</h3>
<figure>
<img alt="Small red square" width="64" height="64" src="data:image/svg+xml;utf8,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20width%3D'64'%20height%3D'64'%3E%3Crect%20width%3D'64'%20height%3D'64'%20fill%3D'%23c0392b'%2F%3E%3C%2Fsvg%3E">
<figcaption>Figure caption describing the image above.</figcaption>
</figure>
<h3>Broken image (alt-text fallback test)</h3>
<img src="does-not-exist.png" alt="This alt text should render because the source is missing" width="200" height="100">
<h3>Picture element</h3>
<picture>
<source media="(min-width: 800px)" srcset="wide.png">
<source media="(min-width: 400px)" srcset="medium.png">
<img src="narrow.png" alt="Responsive image fallback" width="150" height="80">
</picture>
<h3>Video and audio (sources intentionally missing)</h3>
<video controls="" width="320" poster="poster.jpg">
<source src="clip.webm" type="video/webm">
<source src="clip.mp4" type="video/mp4">
<track kind="captions" src="captions.vtt" srclang="en" label="English">
Your browser does not support the video element.
</video>
<audio controls="">
<source src="tone.ogg" type="audio/ogg">
<source src="tone.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<h3>Canvas and iframe</h3>
<canvas width="200" height="60">Canvas fallback text</canvas>
<iframe title="Sandboxed iframe" width="300" height="120" sandbox="allow-scripts allow-same-origin allow-popups allow-forms" loading="lazy" referrerpolicy="no-referrer"></iframe>
</section>
<hr>
<section id="interactive">
<h2>Interactive and semantic containers</h2>
<details>
<summary>Collapsed disclosure</summary>
<p>Hidden content revealed on toggle.</p>
</details>
<details open="">
<summary>Open disclosure</summary>
<ul><li>With a list inside</li><li>Second item</li></ul>
</details>
<p>Non-modal dialog content.</p>
<button type="button">Close</button>
<button type="button">Open dialog</button>
<article>
<header><h3>Article header</h3></header>
<p>Article body content.</p>
<aside><p>An aside nested inside the article.</p></aside>
<footer><p>Article footer.</p></footer>
</article>
<p><span contenteditable="true">Editable inline region</span></p>
<p hidden="">This paragraph has the hidden attribute and should not render.</p>
</section>
<hr>
<section id="edge">
<h2>Edge cases</h2>
<p>Very long unbroken token (overflow test):</p>
<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
<p>Long URL: https://example.com/a/very/long/path/segment/that/keeps/going/and/going?query=1&amp;another=2&amp;third=3#fragment-identifier</p>
<p lang="ar" dir="rtl">هذا نص عربي لاختبار الاتجاه من اليمين إلى اليسار.</p>
<p lang="he" dir="rtl">זהו טקסט עברי לבדיקה.</p>
<p lang="ja">日本語のテキストです。改行と折り返しの確認用。</p>
<p lang="de">Straßenverkehrsordnung — Grüße aus München</p>
<p>Emoji &amp; combining: 👋🏽 👨‍👩‍👧‍👦 🇺🇸 é vs é (precomposed vs combining)</p>
<p>Zero-width chars between letters: a​b​c</p>
<p>Escaped tag text: &lt;script&gt;alert(1)&lt;/script&gt;</p>
<p>Attribute with quotes: <span title="He said &quot;hello&quot;">hover me</span></p>
<p>Empty elements follow:</p>
<div></div>
<p></p>
<ul></ul>
<table></table>
<p>Deep nesting:</p>
<div><div><div><div><div><div><div><p>Seven levels deep.</p></div></div></div></div></div></div></div>
<p>Inline element stress:
<strong><em><u><s><mark>all five at once</mark></s></u></em></strong>
</p>
<p style="color: teal;">Inline style attribute (teal).</p>
<p class="custom-class another-class" data-test-id="edge-1" data-value="42">Element with classes and data attributes.</p>
</section>
</main>
<footer>
<p><small>End of fixture — <time datetime="2026-08-09">2026-08-09</time></small></p>
</footer>
@@ -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 &amp; 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 &lt;new&gt;');
});
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&amp;y=&quot;&gt;&lt;script&gt;"');
expect(html).not.toContain('<script');
expect(html).toContain('&lt;b&gt;Book&lt;/b&gt;');
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('&lt;b&gt;Mon&lt;/b&gt;');
// 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('&lt;i&gt;Eve&lt;/i&gt;');
});
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&amp;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 ? ` &middot; ${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('&lt;script&gt;');
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&apos;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"');
@@ -126,3 +126,212 @@ describe('ContactForm.toHtml field type attribute sanitization', () => {
expect(html).toContain('type="email"');
});
});
// F1: the field editor (FormStylePanel) can now create fields of every type
// in sanitizeInputType's allowlist, plus textarea/select. Verify each
// renders with the right control, label/for association, and required flag.
describe('ContactForm.toHtml renders every configured field type/label/required', () => {
const cases: { type: string; tag: string }[] = [
{ type: 'text', tag: 'input' },
{ type: 'email', tag: 'input' },
{ type: 'tel', tag: 'input' },
{ type: 'number', tag: 'input' },
{ type: 'password', tag: 'input' },
{ type: 'url', tag: 'input' },
{ type: 'search', tag: 'input' },
{ type: 'date', tag: 'input' },
{ type: 'checkbox', tag: 'input' },
{ type: 'radio', tag: 'input' },
];
test.each(cases)('type=$type renders a sanitized <$tag type="$type"> with label + for/id wiring', ({ type, tag }) => {
const fields = [{ type: type as any, label: `Field ${type}`, name: `f_${type}`, placeholder: '', required: true }];
const { html } = toHtml({ fields }, '');
expect(html).toContain(`<${tag}`);
expect(html).toContain(`type="${type}"`);
expect(html).toContain(`Field ${type}`);
// required renders the input attribute AND the visual asterisk
expect(html).toMatch(/ required/);
expect(html).toContain('*</span>');
const labelFor = html.match(/<label for="([^"]+)"/)![1];
expect(html).toContain(`id="${labelFor}"`);
});
test('type=textarea renders a <textarea>, not an <input>', () => {
const fields = [{ type: 'textarea' as const, label: 'Message', name: 'message', placeholder: '', required: false }];
const { html } = toHtml({ fields }, '');
expect(html).toMatch(/<textarea[^>]*name="message"/);
expect(html).not.toMatch(/<input[^>]*name="message"/);
});
test('type=select renders a <select> with escaped <option> values from field.options', () => {
const fields = [{ type: 'select' as const, label: 'Plan', name: 'plan', placeholder: 'Choose one', required: false, options: ['Basic', 'Pro', '"><script>alert(1)</script>'] }];
const { html } = toHtml({ fields }, '');
expect(html).toMatch(/<select[^>]*name="plan"/);
expect(html).toContain('<option value="Basic">Basic</option>');
expect(html).toContain('<option value="Pro">Pro</option>');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a non-required field omits both the required attribute and the asterisk', () => {
const fields = [{ type: 'text' as const, label: 'Nickname', name: 'nickname', placeholder: '', required: false }];
const { html } = toHtml({ fields }, '');
expect(html).not.toMatch(/ required/);
expect(html).not.toContain('*</span>');
});
});
// Box-model / animation / visibility rollout (common enh-batch pattern):
// these are top-level props consumed generically by the export's
// buildDataAttrs() -- this just confirms the defaults are present on
// craft.props so the panel controls render and the props survive save/load.
describe('ContactForm.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults for animation, animationDelay, hideOnDesktop/Tablet/Mobile', () => {
expect(ContactForm.craft!.props).toMatchObject({
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
});
});
});
/* ---------- Webhook destination (Task 10) ----------
This file builds props inline rather than spreading a shared object, so
`defaultProps` is introduced here for the destination cases only; every
pre-existing test above is untouched. */
const defaultProps = { fields: [] as any[], formAction: '#' };
describe('ContactForm.craft.props includes the destination defaults', () => {
// The trap this pins: FormStylePanel renders each destination control behind
// `nodeProps.X !== undefined`, so a prop omitted from these defaults yields an
// invisible control and the whole feature looks like it does nothing.
test('destinationType/webhookUrl/webhookSecretId/webhookAuthMode are all present', () => {
expect(ContactForm.craft!.props).toMatchObject({
destinationType: 'email',
webhookUrl: '',
webhookSecretId: '',
webhookAuthMode: 'signature',
});
});
test('no craft prop holds a raw secret -- only an id', () => {
const keys = Object.keys(ContactForm.craft!.props as object);
expect(keys).toContain('webhookSecretId');
expect(keys.filter((k) => /secret/i.test(k))).toEqual(['webhookSecretId']);
});
});
describe('ContactForm.toHtml destination marker', () => {
test('email destination emits the legacy marker unchanged', () => {
const out = toHtml(
{ ...defaultProps, destinationType: 'email', recipientEmail: 'a@example.com', thankYouUrl: '' }, '');
expect(out.html).toContain('<!--WHP-FORM');
expect(out.html).toContain('recipient="a@example.com"');
expect(out.html).not.toContain('type="webhook"');
});
test('BYTE-IDENTITY: an email destination emits exactly what a pre-feature form emits', () => {
// The guarantee every already-published site depends on: a marker with no
// `type` still provisions an email endpoint, so its bytes must not drift by
// so much as a space.
//
// FROZEN LITERAL, not a self-comparison. Comparing two head-revision outputs
// to each other only catches a drift that affects ONE of them -- a uniform
// change passes it. This string was captured from `071f3447` (the revision
// deployed to production before this feature) and is the actual reference:
// 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" 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);
// ...and the new props, set to their defaults, change nothing about it.
const explicit = toHtml(
{ ...defaultProps, destinationType: 'email', webhookUrl: '', webhookSecretId: '',
webhookAuthMode: 'signature', recipientEmail: 'a@example.com', thankYouUrl: '/thx' }, '', 'n1');
expect(explicit.html).toBe(legacy.html);
});
test('webhook destination emits type, url, secret id and auth mode', () => {
const out = toHtml(
{ ...defaultProps, destinationType: 'webhook', webhookUrl: 'https://hooks.example.com/x',
webhookSecretId: 'sec-1', webhookAuthMode: 'bearer', recipientEmail: 'fb@example.com' }, '');
expect(out.html).toContain('type="webhook"');
expect(out.html).toContain('url="https://hooks.example.com/x"');
expect(out.html).toContain('secret="sec-1"');
expect(out.html).toContain('authmode="bearer"');
expect(out.html).toContain('recipient="fb@example.com"');
});
test('a raw secret value is never emitted, only its id', () => {
const out = toHtml(
{ ...defaultProps, destinationType: 'webhook', webhookUrl: 'https://hooks.example.com/x',
webhookSecretId: 'sec-1', webhookSecret: 'SUPERSECRET' } as any, '');
// Non-vacuous: the marker IS emitted (so there is something that could have
// carried the secret) and carries the id, but not the value.
expect(out.html).toContain('secret="sec-1"');
expect(out.html).not.toContain('SUPERSECRET');
});
test('a webhook form with no fallback email still emits a marker (never a bare formAction)', () => {
const out = toHtml(
{ ...defaultProps, destinationType: 'webhook', webhookUrl: 'https://hooks.example.com/x' }, '');
expect(out.html).toContain('type="webhook"');
expect(out.html).toContain('recipient=""');
expect(out.html).toMatch(/action="__WHP_FORM_ACTION__F_[0-9a-z]+__"/);
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>');
});
});
+100 -26
View File
@@ -1,11 +1,39 @@
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'
// and 'select', which take their own render branches instead of an
// `<input type>`), kept in sync by hand since TS unions can't import a
// runtime array.
export type ContactFormFieldType =
| 'text' | 'email' | 'tel' | 'number' | 'password' | 'url' | 'search' | 'date'
| 'checkbox' | 'radio' | 'textarea' | 'select';
interface ContactFormField {
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
type: ContactFormFieldType;
label: string;
name: string;
placeholder: string;
@@ -22,9 +50,28 @@ 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;
/* ---- Submission destination (see utils/form-relay-wiring.ts) ----
'email' (default) reproduces the legacy marker exactly. 'webhook' widens it
with the url / secret id / auth mode below.
There is deliberately NO raw-secret prop: craft props are serialised into
the saved project and into published output, so the secret is POSTed to
/api/form-webhook-secret.php and only the returned opaque id is kept. */
destinationType?: 'email' | 'webhook';
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;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
const defaultFields: ContactFormField[] = [
@@ -37,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 },
@@ -57,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',
};
@@ -70,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',
@@ -84,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
@@ -116,6 +167,7 @@ export const ContactForm: UserComponent<ContactFormProps> = ({
)}
</div>
))}
{isRelayWired(recipientEmail, destinationType) && <CaptchaMock />}
<button
type="submit"
style={{
@@ -123,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',
@@ -144,19 +196,30 @@ 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`
// gates actually render the destination controls.
destinationType: 'email',
webhookUrl: '',
webhookSecretId: '',
webhookAuthMode: 'signature',
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -177,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)}`;
@@ -206,15 +270,25 @@ 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',
alignSelf: 'flex-start',
});
const { marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, props.formAction, nodeId);
// Only the webhook SECRET ID travels here -- there is no prop holding the raw
// secret, by construction (see ContactFormProps).
const { marker, actionAttr, honeypot } = relayFormWiring(
props.recipientEmail, props.thankYouUrl, props.formAction, nodeId,
{
type: props.destinationType,
url: props.webhookUrl,
secretId: props.webhookSecretId,
authMode: props.webhookAuthMode,
},
);
// The form-sender relay delivers success via a full-page 303 redirect
// (to thankYouUrl or a hosted thanks.php page) -- there is no in-page JS
@@ -224,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>`,
};
};
@@ -22,4 +22,36 @@ describe('FormButton.toHtml', () => {
expect(html).toContain('&amp;');
expect(html).toContain('&quot;quoted&quot;');
});
test('box-model style (margin/border/box-shadow/opacity) flows through via the style prop', () => {
const { html } = toHtml({ text: 'Submit', style: { marginTop: '12px', border: '2px solid #000', boxShadow: '0 2px 4px rgba(0,0,0,.2)', opacity: '0.8' } }, '');
expect(html).toContain('margin-top:12px');
expect(html).toContain('border:2px solid #000');
expect(html).toContain('opacity:0.8');
});
});
describe('FormButton.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults', () => {
expect(FormButton.craft!.props).toMatchObject({
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
});
});
});
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);
});
});
+15 -4
View File
@@ -2,10 +2,16 @@ 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;
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const FormButton: UserComponent<FormButtonProps> = ({
@@ -26,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',
@@ -50,14 +56,19 @@ FormButton.craft = {
props: {
text: 'Submit',
style: {
backgroundColor: '#3b82f6',
color: '#ffffff',
backgroundColor: tokenRef('primary'),
color: tokenRef('bg'),
padding: '12px 32px',
borderRadius: '6px',
fontWeight: '600',
fontSize: '16px',
border: 'none',
},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -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"');
@@ -52,3 +52,29 @@ describe('FormContainer.toHtml method attribute sanitization', () => {
expect(html).toContain('method="GET"');
});
});
describe('FormContainer.toHtml box-model style passthrough', () => {
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
const { html } = toHtml({ action: '/legacy', style: { marginTop: '20px', border: '3px dashed #ccc', boxShadow: '0 4px 8px rgba(0,0,0,.2)', opacity: '0.95' } }, '');
expect(html).toContain('margin-top:20px');
expect(html).toContain('border:3px dashed #ccc');
expect(html).toContain('opacity:0.95');
});
});
describe('FormContainer.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults', () => {
expect(FormContainer.craft!.props).toMatchObject({
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
});
});
});
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);
});
});
+19 -3
View File
@@ -1,23 +1,33 @@
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;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const FormContainer: UserComponent<FormContainerProps> = ({
action = '#',
method = 'POST',
style = {},
recipientEmail,
}) => {
const { connectors: { connect, drag } } = useNode();
@@ -40,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>
);
};
@@ -55,10 +66,15 @@ FormContainer.craft = {
thankYouUrl: '',
style: {
padding: '24px',
backgroundColor: '#ffffff',
backgroundColor: tokenRef('bg'),
borderRadius: '8px',
border: '1px solid #e4e4e7',
border: `1px solid ${tokenRef('border')}`,
},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -72,3 +72,29 @@ describe('InputField.toHtml type attribute sanitization', () => {
expect(html).toContain('type="number"');
});
});
describe('InputField.toHtml box-model style passthrough', () => {
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
const { html } = toHtml({ label: 'Name', name: 'name', style: { marginBottom: '8px', border: '1px solid #333', boxShadow: '0 1px 2px rgba(0,0,0,.1)', opacity: '0.9' } }, '');
expect(html).toContain('margin-bottom:8px');
expect(html).toContain('border:1px solid #333');
expect(html).toContain('opacity:0.9');
});
});
describe('InputField.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults', () => {
expect(InputField.craft!.props).toMatchObject({
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
});
});
});
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);
});
});
+18 -7
View File
@@ -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';
@@ -10,6 +11,11 @@ interface InputFieldProps {
placeholder?: string;
required?: boolean;
style?: CSSProperties;
animation?: string;
animationDelay?: string;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
export const InputField: UserComponent<InputFieldProps> = ({
@@ -40,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
@@ -51,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',
@@ -77,6 +83,11 @@ InputField.craft = {
placeholder: 'Enter your name',
required: false,
style: {},
animation: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -103,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')}"`
@@ -111,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>`,
};
};
@@ -6,7 +6,7 @@ const toHtml = (SubscribeForm as any).toHtml;
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
test('form method is always POST regardless of any injected props', () => {
const { html } = toHtml({ heading: 'Join us', method: 'GET"><script>alert(1)</script>' } as any, '');
expect(html).toContain('<form method="POST"');
expect(html).toMatch(/<form action="[^"]*" method="POST"/);
expect(html).not.toContain('<script');
});
@@ -37,3 +37,68 @@ describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop
expect(html).toContain('>Go<');
});
});
// F1: SubscribeForm previously emitted `<form method="POST">` with no action
// at all -- a published subscribe form silently did nothing on submit.
// Wired through the same relay contract as ContactForm/FormContainer
// (utils/form-relay-wiring.ts) so setting a recipient makes it functional.
describe('SubscribeForm.toHtml is functional (not a dead POST)', () => {
test('without a recipient: still has a real (non-empty) action -- "#" fallback, not a bare method="POST"', () => {
const { html } = toHtml({}, '');
expect(html).toMatch(/<form action="#" method="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]+" 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];
expect(html).toContain(`__WHP_FORM_ACTION__${mid}__`);
});
test('the email input keeps its name="email" so the relay receives it', () => {
const { html } = toHtml({ recipientEmail: 'news@example.com' }, '', 'node-sub2');
expect(html).toContain('name="email"');
});
});
describe('SubscribeForm.toHtml box-model style passthrough', () => {
test('margin/border/box-shadow/opacity flow through via the style prop', () => {
const { html } = toHtml({ style: { marginTop: '16px', border: '1px solid #ddd', boxShadow: '0 2px 6px rgba(0,0,0,.15)', opacity: '0.85' } }, '');
expect(html).toContain('margin-top:16px');
expect(html).toContain('border:1px solid #ddd');
expect(html).toContain('opacity:0.85');
});
});
describe('SubscribeForm.craft.props includes animation/visibility defaults', () => {
test('has blank/false defaults', () => {
expect(SubscribeForm.craft!.props).toMatchObject({
animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false,
});
});
});
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);
});
});
+59 -16
View File
@@ -1,7 +1,18 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
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;
@@ -10,15 +21,29 @@ interface SubscribeFormProps {
buttonColor?: string;
layout?: 'inline' | 'stacked';
style?: CSSProperties;
/** "Send submissions to" address -- same relay contract as ContactForm/
* FormContainer (see utils/form-relay-wiring.ts). Blank = no relay; the
* 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;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
}
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 },
@@ -43,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',
}}>
@@ -69,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',
}}
@@ -84,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',
@@ -95,6 +120,7 @@ export const SubscribeForm: UserComponent<SubscribeFormProps> = ({
{buttonText}
</button>
</form>
{isRelayWired(recipientEmail) && <CaptchaMock style={{ margin: '12px auto 0' }} />}
</div>
);
};
@@ -107,9 +133,16 @@ 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: '',
animationDelay: '',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
},
rules: {
canDrag: () => true,
@@ -120,12 +153,12 @@ SubscribeForm.craft = {
/* ---------- HTML export ---------- */
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string) => {
(SubscribeForm as any).toHtml = (props: SubscribeFormProps, _childrenHtml: string, nodeId?: string) => {
const {
heading = 'Subscribe to our newsletter',
placeholder = 'Enter your email',
buttonText = 'Subscribe',
buttonColor = '#3b82f6',
buttonColor = tokenRef('primary'),
layout = 'inline',
style = {},
} = props;
@@ -139,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({
@@ -151,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',
@@ -166,11 +199,21 @@ SubscribeForm.craft = {
whiteSpace: 'nowrap',
});
// Same relay contract as ContactForm/FormContainer: a recipientEmail wires
// the form through the WHP form-sender relay (marker + placeholder action
// + honeypot, provisioned/rewritten at publish time). Previously this form
// always emitted `<form method="POST">` with NO action at all -- a
// published subscribe form silently did nothing on submit. Falling back to
// `formAction`-less relay wiring (fallbackAction undefined -> '#') keeps
// the old no-recipient case visually identical (action="#") while making
// the relay path actually functional once an admin sets an email.
const { marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, undefined, nodeId);
return {
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
html: `${marker}<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
${headingHtml}
<form method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
<input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
<form action="${actionAttr}" method="POST"${formStyle ? ` style="${formStyle}"` : ''}>
${honeypot ? ` ${honeypot}\n` : ''} <input type="email" name="email" placeholder="${escapeAttr(placeholder)}" required style="${inputStyleStr}" />
<button type="submit"${btnStyle ? ` style="${btnStyle}"` : ''}>${escapeHtml(buttonText)}</button>
</form>
</div>`,
Loaded 100 of 558 files, more files were not shown because too many files have changed in this diff. Show more