Compare commits

...
13 Commits
Author SHA1 Message Date
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
jknapp 1d9460c173 Merge PR #13: enhancement foundation 2026-07-14 13:12:22 +00:00
shadowdaoandClaude Opus 4.8 8d69982a0b chore(builder): install CodeMirror deps for the upcoming code-editor feature
Adds @codemirror/state, view, commands, autocomplete, language,
lang-html, lang-javascript, lang-css, and theme-one-dark to package.json
now (unused for now, tree-shaken out of the build) so the code-editor
feature branch doesn't need to touch package.json/package-lock.json itself
and conflict with other enh-batch branches doing the same.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:07:25 -07:00
shadowdaoandClaude Opus 4.8 fb40e3ece4 feat(builder): add reusable StylePanel controls (foundation for enh batch)
Adds NumericUnitInput, SizeControl, AspectRatioControl, FocalPointGrid,
SpacingControl, BorderControl, AnimationControl, and VisibilityControl to
src/panels/right/styles/shared.tsx -- presentational value/onChange controls
that upcoming feature panels will import instead of reinventing size,
spacing, border, and animation/visibility UI per panel.

AnimationControl/VisibilityControl emit the exact prop names
(animation/animationDelay, hideOnDesktop/hideOnTablet/hideOnMobile) already
consumed by html-export.ts's buildDataAttrs(), verified by reading that file
directly. ANIMATIONS matches the export's actual data-animation set
(fade-in/slide-up/slide-left/slide-right/zoom-in/bounce) rather than the
slide-down variant that doesn't exist in the export.

No existing shared.tsx exports were touched, and nothing is wired into any
feature panel yet -- that's the downstream feature branches' job.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:07:20 -07:00
shadowdaoandClaude Opus 4.8 9591fcb8a7 feat(builder): add shared style presets for size/aspect-ratio/shadow/typography rollout
ASPECT_RATIOS, SHADOW_PRESETS, LINE_HEIGHTS, LETTER_SPACINGS, OBJECT_FIT,
BORDER_STYLES, and SIZE_PRESETS -- foundation for the new shared StylePanel
controls (SizeControl, AspectRatioControl, BorderControl) so upcoming
feature panels share one preset source instead of each defining their own.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 06:07:14 -07:00
jknapp f80811318b Merge PR #12: real-Editor integration test harness 2026-07-14 00:12:49 +00:00
shadowdaoandClaude Opus 4.8 cb9fea6656 test(builder): real-@craftjs/core integration test harness (duplicate/paste, template load, AI apply-response)
Mocked unit tests for regenerateTreeIds, TemplateModal.addTemplateComponents,
and buildNodeTree each let a real bug ship (DataCloneError on duplicate/paste,
dropped template children, no-op AI section-replace/insert) because their
fake @craftjs/core query/actions never exercised Craft's real node shape
(data.type as a live component reference) or real parseFreshNode validation.

Adds src/test-utils/editorHarness.tsx, which mounts a REAL <Editor>+<Frame>
(no vi.mock('@craftjs/core') anywhere) via react-dom/client + act, plus the
jsdom shims Craft/this component library actually needs (ResizeObserver,
matchMedia, and an HTMLElement.prototype.innerText polyfill -- jsdom has no
native innerText, which Heading/TextBlock rely on to paint their text).

Adds 3 integration suites under src/test-utils/integration/ driving the real
useNodeActions/useKeyboardShortcuts, TemplateModal's real tree-build pipeline,
and the real useApplyAiResponse hook against a live EditorStore, asserting on
both the real rendered DOM and query.serialize()/exportBodyHtml output.

Red-proofed the duplicate/paste suite: temporarily reverted
regenerateTreeIds to structuredClone(oldNode.data) and confirmed both tests
fail with the historical DataCloneError before restoring the fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 17:11:40 -07:00
jknapp b1afdcb585 Merge PR #11: mobile fast-follows 2026-07-13 16:19:53 +00:00
shadowdaoandClaude Opus 4.8 f00e4db3dc test(builder): cover useVisualViewport; fix: disable Select-Parent at ROOT in desktop context menu
- useVisualViewport.test.tsx: covers the visualViewport-undefined fallback,
  the keyboardInset math on a mocked visualViewport resize, and
  listener add/remove (resize + scroll) across mount/unmount.
- ContextMenu.tsx: Select Parent was only disabled at isRoot, so selecting
  a top-level section and choosing Select Parent silently landed on the
  un-editable ROOT (no outline, no toolbar) -- a dead end. Switched the
  guard to useNodeActions' canSelectParent (false whenever the node's
  parent is ROOT or missing), matching the mobile selection toolbar's
  existing identical guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 09:19:00 -07:00
jknapp b9552faa30 Merge PR #10: Mobile Phase B (touch editing) 2026-07-13 15:43:29 +00:00
shadowdaoandClaude Opus 4.8 77f35c4e9e fix(builder): duplicate inserts+selects after source; select-parent/styles-sheet/canvas-pad mobile fixes
Ship-blocking fix (Fable consult): useNodeActions.duplicate() appended the
regenerated tree at the end of the parent while leaving the ORIGINAL
selected, so duplicating a top-level section landed the copy off-screen at
the bottom of the page with no visible change -- shared by both the mobile
selection toolbar and the desktop right-click ContextMenu. Now inserts the
copy immediately after the source (actions.addNodeTree(tree, parentId,
sourceIndex + 1)) and selects it (actions.selectNode(tree.rootNodeId)),
falling back to append-at-end if the source's index can't be resolved.
Mobile also scrolls the new node into view.

Three cheap fast-follows:
- canSelectParent on useNodeActions (false when the node's parent is ROOT
  or missing); MobileSelectionToolbar disables "Select Parent" instead of
  dead-ending on a page-wide ROOT outline with no toolbar of its own.
- Opening the Styles sheet on mobile now scrolls the selected node above
  the 65dvh sheet; a temporary generous bottom-padding class handles the
  case where the node is the last thing on the page and there'd otherwise
  be no room left to scroll it into view.
- Canvas gets bottom padding equal to the fixed selection toolbar's height
  while it's visible, so the last section of a short page isn't stuck
  permanently underneath it.

Desktop duplicate behavior improves (inserts after + selects) via the
shared hook; no toHtml changes. Verified live via Playwright at 375px and
1280px (screenshots in craft/scratchpad/mobileB2/).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 08:41:33 -07:00
shadowdaoandClaude Opus 4.8 2c8425ffb0 feat(builder): mobile-B touch editing -- selection toolbar, tap-to-add, swipe-dismiss
Phase B makes the Craft.js editor genuinely usable by touch on top of Phase
A's responsive shell, gated entirely behind useIsMobile()/<=768px:

- Extract useNodeActions(nodeId) out of ContextMenu.tsx (move/duplicate/
  delete/select-parent), shared by the desktop right-click menu (behavior
  unchanged) and the new mobile MobileSelectionToolbar.
- MobileSelectionToolbar: bottom-fixed selection toolbar (Move Up/Down,
  Duplicate, Select Parent, Edit Styles, two-tap Delete confirm), hidden
  while a sheet is open.
- BlocksPanel: tap-to-add on mobile (insert after selection, close sheet,
  select + scroll the new node into view); desktop drag/double-click
  unchanged.
- LayersPanel rows >=44px on mobile; HeadCodeModal portaled to document.body
  (same fix TemplateModal already had); BottomSheet gets swipe-to-dismiss
  and on-screen-keyboard clearance via a new useVisualViewportInsets hook.

Also fixes two pre-existing bugs surfaced only by driving a real Craft.js
document with Playwright touch input (masked by tests that mock
@craftjs/core): regenerateTreeIds structuredClone'd a live node's whole
data object, including the component function reference in data.type,
throwing DataCloneError and silently breaking Duplicate/Paste for every
node type; and an earlier useNodeActions draft cached canMoveUp/canMoveDown
inside a useEditor collector closed over nodeId, which goes stale for one
render whenever the selection changes without an unrelated store event.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 08:07:51 -07:00
jknapp 2a071bc7ab Merge PR #9: Mobile Phase A 2026-07-13 14:31:23 +00:00
34 changed files with 3781 additions and 113 deletions
+217
View File
@@ -8,6 +8,15 @@
"name": "whp-site-builder", "name": "whp-site-builder",
"version": "2.0.0", "version": "2.0.0",
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.10.4",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/language": "^6.12.4",
"@codemirror/state": "^6.7.1",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.6",
"@craftjs/core": "^0.2.10", "@craftjs/core": "^0.2.10",
"@craftjs/layers": "^0.2.7", "@craftjs/layers": "^0.2.7",
"dompurify": "^3.4.5", "dompurify": "^3.4.5",
@@ -373,6 +382,133 @@
"specificity": "bin/cli.js" "specificity": "bin/cli.js"
} }
}, },
"node_modules/@codemirror/autocomplete": {
"version": "6.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/commands": {
"version": "6.10.4",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.4.tgz",
"integrity": "sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.7.0",
"@codemirror/view": "^6.27.0",
"@lezer/common": "^1.1.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.5",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.12.4",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
"integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.5.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.42.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/state": {
"version": "6.7.1",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.1.tgz",
"integrity": "sha512-9QzNDgE4EYDnAHfrTlR2lwiPciiOymLtwKK+8yHQzCc7GXhAP9xdEbEJFy2IWB1j9UGUl9BsgMmTo/ImA02T7A==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/theme-one-dark": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
"integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.43.6",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.6.tgz",
"integrity": "sha512-EVunGSYN1wz1p75WY1s3Xg7t3i8Yol0kGZGizNdX9BUFgMFILYVe8/u6EVpo7Ff5PwbZuILb4QAq7IZoKzIEQA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.7.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@craftjs/core": { "node_modules/@craftjs/core": {
"version": "0.2.12", "version": "0.2.12",
"resolved": "https://registry.npmjs.org/@craftjs/core/-/core-0.2.12.tgz", "resolved": "https://registry.npmjs.org/@craftjs/core/-/core-0.2.12.tgz",
@@ -1093,6 +1229,69 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@lezer/common": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.4.tgz",
"integrity": "sha512-N+tn9tej2hPvyKgHEApMOQfHczDJCwxrRFS3SPn9QjYN+uwHvEDnCgKRrb3mxDYxRS8sKMM8fhC3+lc04Abz5Q==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.13",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.10",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",
"integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",
"license": "MIT"
},
"node_modules/@playwright/test": { "node_modules/@playwright/test": {
"version": "1.59.1", "version": "1.59.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",
@@ -1873,6 +2072,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/crelt": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
"license": "MIT"
},
"node_modules/css-color-keywords": { "node_modules/css-color-keywords": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz", "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz",
@@ -2686,6 +2891,12 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/style-mod": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
"license": "MIT"
},
"node_modules/styled-components": { "node_modules/styled-components": {
"version": "6.3.12", "version": "6.3.12",
"resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.3.12.tgz", "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.3.12.tgz",
@@ -3096,6 +3307,12 @@
} }
} }
}, },
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
},
"node_modules/w3c-xmlserializer": { "node_modules/w3c-xmlserializer": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+9
View File
@@ -14,6 +14,15 @@
"test:unit:watch": "vitest" "test:unit:watch": "vitest"
}, },
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.10.4",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.11",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/language": "^6.12.4",
"@codemirror/state": "^6.7.1",
"@codemirror/theme-one-dark": "^6.1.3",
"@codemirror/view": "^6.43.6",
"@craftjs/core": "^0.2.10", "@craftjs/core": "^0.2.10",
"@craftjs/layers": "^0.2.7", "@craftjs/layers": "^0.2.7",
"dompurify": "^3.4.5", "dompurify": "^3.4.5",
@@ -20,3 +20,14 @@ describe('Footer.toHtml text escaping (attacker-controlled `text` prop)', () =>
expect(html).toContain('© 2026 MySite. All rights reserved.'); 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);
});
});
+10
View File
@@ -6,6 +6,11 @@ import { escapeHtml } from '../../utils/escape';
interface FooterProps { interface FooterProps {
text?: string; text?: string;
style?: CSSProperties; style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
} }
export const Footer: UserComponent<FooterProps> = ({ export const Footer: UserComponent<FooterProps> = ({
@@ -92,6 +97,11 @@ Footer.craft = {
fontSize: '14px', fontSize: '14px',
padding: '24px 20px', padding: '24px 20px',
}, },
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
}, },
rules: { rules: {
canDrag: () => true, canDrag: () => true,
@@ -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', () => { describe('Logo.toHtml text-logo styling sanitization', () => {
test('a quote-breakout color does not escape the span style attribute', () => { test('a quote-breakout color does not escape the span style attribute', () => {
const malicious = 'red" onmouseover="alert(1)'; const malicious = 'red" onmouseover="alert(1)';
+17 -1
View File
@@ -12,11 +12,18 @@ interface LogoProps {
imageSrc?: string; imageSrc?: string;
imageWidth?: string; imageWidth?: string;
href?: string; href?: string;
/** Adds the `download` attribute to the exported anchor (F3: link to a file). */
download?: boolean;
fontFamily?: string; fontFamily?: string;
fontSize?: string; fontSize?: string;
fontWeight?: string; fontWeight?: string;
color?: string; color?: string;
style?: CSSProperties; style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
} }
/* ---------- Component ---------- */ /* ---------- Component ---------- */
@@ -27,6 +34,7 @@ export const Logo: UserComponent<LogoProps> = ({
imageSrc = '', imageSrc = '',
imageWidth = '120px', imageWidth = '120px',
href = '/', href = '/',
download = false,
fontFamily = 'Inter, sans-serif', fontFamily = 'Inter, sans-serif',
fontSize = '20px', fontSize = '20px',
fontWeight = '700', fontWeight = '700',
@@ -44,6 +52,7 @@ export const Logo: UserComponent<LogoProps> = ({
<a <a
ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }} ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
href={href} href={href}
download={download || undefined}
onClick={(e) => e.preventDefault()} onClick={(e) => e.preventDefault()}
style={{ style={{
textDecoration: 'none', textDecoration: 'none',
@@ -87,7 +96,13 @@ Logo.craft = {
fontSize: '20px', fontSize: '20px',
fontWeight: '700', fontWeight: '700',
color: undefined, color: undefined,
download: false,
style: {}, style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as LogoProps, } as LogoProps,
rules: { rules: {
canDrag: () => true, canDrag: () => true,
@@ -122,8 +137,9 @@ Logo.craft = {
flexShrink: '0', flexShrink: '0',
...props.style, ...props.style,
}); });
const downloadAttr = props.download ? ' download' : '';
return { 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>)', () => { describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
test('a linkHoverColor value containing </style><script> is neutralized', () => { test('a linkHoverColor value containing </style><script> is neutralized', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{'; const malicious = '#fff}</style><script>alert(1)</script><style>{';
+15 -1
View File
@@ -10,6 +10,8 @@ interface MenuLink {
href: string; href: string;
isExternal?: boolean; isExternal?: boolean;
isCta?: boolean; isCta?: boolean;
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
download?: boolean;
} }
interface MenuProps { interface MenuProps {
@@ -23,6 +25,11 @@ interface MenuProps {
orientation?: 'horizontal' | 'vertical'; orientation?: 'horizontal' | 'vertical';
fontSize?: string; fontSize?: string;
style?: CSSProperties; style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
} }
/* ---------- Defaults ---------- */ /* ---------- Defaults ---------- */
@@ -75,6 +82,7 @@ export const Menu: UserComponent<MenuProps> = ({
href={link.href} href={link.href}
target={link.isExternal ? '_blank' : undefined} target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined} rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()} onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)} onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)} onMouseLeave={() => setHoveredLink(null)}
@@ -114,6 +122,11 @@ Menu.craft = {
orientation: 'horizontal', orientation: 'horizontal',
fontSize: '14px', fontSize: '14px',
style: {}, style: {},
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as MenuProps, } as MenuProps,
rules: { rules: {
canDrag: () => true, canDrag: () => true,
@@ -162,6 +175,7 @@ Menu.craft = {
const linksHtml = links.map((link) => { const linksHtml = links.map((link) => {
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : ''; const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
const downloadAttr = link.download ? ' download' : '';
const cls = link.isCta ? `${scope}-cta` : `${scope}-link`; const cls = link.isCta ? `${scope}-cta` : `${scope}-link`;
const linkStyle = cssPropsToString({ const linkStyle = cssPropsToString({
textDecoration: 'none', textDecoration: 'none',
@@ -173,7 +187,7 @@ Menu.craft = {
borderRadius: link.isCta ? '6px' : '0', borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s', 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>`;
}).join('\n '); }).join('\n ');
const hoverCss = `<style> const hoverCss = `<style>
@@ -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>)', () => { describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => { test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{'; const malicious = '#fff}</style><script>alert(1)</script><style>{';
+15 -1
View File
@@ -11,6 +11,8 @@ interface NavLink {
href: string; href: string;
isExternal?: boolean; isExternal?: boolean;
isCta?: boolean; isCta?: boolean;
/** Adds the `download` attribute to the exported anchor (F3: links to files). */
download?: boolean;
} }
interface NavbarProps { interface NavbarProps {
@@ -33,6 +35,11 @@ interface NavbarProps {
isSticky?: boolean; isSticky?: boolean;
showMobileMenu?: boolean; showMobileMenu?: boolean;
style?: CSSProperties; style?: CSSProperties;
hideOnDesktop?: boolean;
hideOnTablet?: boolean;
hideOnMobile?: boolean;
animation?: string;
animationDelay?: string;
} }
/* ---------- Defaults ---------- */ /* ---------- Defaults ---------- */
@@ -149,6 +156,7 @@ export const Navbar: UserComponent<NavbarProps> = ({
href={link.href} href={link.href}
target={link.isExternal ? '_blank' : undefined} target={link.isExternal ? '_blank' : undefined}
rel={link.isExternal ? 'noopener noreferrer' : undefined} rel={link.isExternal ? 'noopener noreferrer' : undefined}
download={link.download || undefined}
onClick={(e) => e.preventDefault()} onClick={(e) => e.preventDefault()}
onMouseEnter={() => setHoveredLink(i)} onMouseEnter={() => setHoveredLink(i)}
onMouseLeave={() => setHoveredLink(null)} onMouseLeave={() => setHoveredLink(null)}
@@ -200,6 +208,11 @@ Navbar.craft = {
style: { style: {
borderBottom: '1px solid #e4e4e7', borderBottom: '1px solid #e4e4e7',
}, },
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
animation: 'none',
animationDelay: '0',
} as NavbarProps, } as NavbarProps,
rules: { rules: {
canDrag: () => true, canDrag: () => true,
@@ -308,6 +321,7 @@ Navbar.craft = {
// Add CSS class to each link for hover // Add CSS class to each link for hover
const linksHtmlWithClass = links.map((link) => { const linksHtmlWithClass = links.map((link) => {
const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : ''; const target = link.isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
const downloadAttr = link.download ? ' download' : '';
const cls = link.isCta ? 'navbar-cta' : 'navbar-link'; const cls = link.isCta ? 'navbar-cta' : 'navbar-link';
const linkStyle = cssPropsToString({ const linkStyle = cssPropsToString({
textDecoration: 'none', textDecoration: 'none',
@@ -319,7 +333,7 @@ Navbar.craft = {
borderRadius: link.isCta ? '6px' : '0', borderRadius: link.isCta ? '6px' : '0',
transition: 'color 0.15s, background-color 0.15s', 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>`;
}).join('\n '); }).join('\n ');
return { return {
+65
View File
@@ -94,3 +94,68 @@ export const DEVICE_WIDTHS: Record<string, string> = {
tablet: '768px', tablet: '768px',
mobile: '375px', mobile: '375px',
}; };
/* ---------- ENH-Foundation shared presets ----------
Consumed by the reusable StylePanel controls in
src/panels/right/styles/shared.tsx (SizeControl, AspectRatioControl,
BorderControl, etc). Kept in the `{ label, value }` shape used throughout
this file so they drop straight into PresetButtonGrid / ColorSwatchGrid. */
// Width/height preset row used by SizeControl (image + video sizing).
export const SIZE_PRESETS = [
{ label: '25%', value: '25%' },
{ label: '50%', value: '50%' },
{ label: '75%', value: '75%' },
{ label: '100%', value: '100%' },
{ label: 'Auto', value: 'auto' },
{ label: 'Full', value: '100vw' },
];
// CSS `aspect-ratio` values. 'Original' (empty string) clears the property.
export const ASPECT_RATIOS = [
{ label: 'Original', value: '' },
{ label: '1:1', value: '1 / 1' },
{ label: '4:3', value: '4 / 3' },
{ label: '3:2', value: '3 / 2' },
{ label: '16:9', value: '16 / 9' },
{ label: '4:5', value: '4 / 5' },
{ label: '9:16', value: '9 / 16' },
];
// box-shadow presets; 'Colored' is the color-aware option (accent-tinted).
export const SHADOW_PRESETS = [
{ label: 'None', value: 'none' },
{ label: 'S', value: '0 1px 2px rgba(0,0,0,0.08)' },
{ label: 'M', value: '0 4px 8px rgba(0,0,0,0.12)' },
{ label: 'L', value: '0 10px 24px rgba(0,0,0,0.18)' },
{ label: 'Colored', value: '0 8px 20px rgba(59,130,246,0.35)' },
];
export const LINE_HEIGHTS = [
{ label: 'Tight', value: '1.1' },
{ label: 'Snug', value: '1.25' },
{ label: 'Normal', value: '1.5' },
{ label: 'Relaxed', value: '1.75' },
{ label: 'Loose', value: '2' },
];
export const LETTER_SPACINGS = [
{ label: 'Tight', value: '-0.02em' },
{ label: 'Normal', value: 'normal' },
{ label: 'Wide', value: '0.05em' },
{ label: 'Wider', value: '0.1em' },
];
export const OBJECT_FIT = [
{ label: 'Cover', value: 'cover' },
{ label: 'Contain', value: 'contain' },
{ label: 'Fill', value: 'fill' },
{ label: 'None', value: 'none' },
];
export const BORDER_STYLES = [
{ label: 'None', value: 'none' },
{ label: 'Solid', value: 'solid' },
{ label: 'Dashed', value: 'dashed' },
{ label: 'Dotted', value: 'dotted' },
];
+42 -1
View File
@@ -6,6 +6,7 @@ import { DeviceMode } from '../types';
import { DEVICE_WIDTHS } from '../constants/presets'; import { DEVICE_WIDTHS } from '../constants/presets';
import { exportBodyHtml } from '../utils/html-export'; import { exportBodyHtml } from '../utils/html-export';
import { useIsMobile } from '../hooks/useIsMobile'; import { useIsMobile } from '../hooks/useIsMobile';
import { useMobileChrome } from '../state/MobileChromeContext';
interface CanvasProps { interface CanvasProps {
device: DeviceMode; device: DeviceMode;
@@ -135,6 +136,42 @@ export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
const isEditingRegularPage = !isEditingHeader && !isEditingFooter; const isEditingRegularPage = !isEditingHeader && !isEditingFooter;
// Fast-follow item 4: while `MobileSelectionToolbar` is up (fixed, ~53px
// tall, just above the tab bar), it covers whatever content was at the
// very bottom of the canvas's own scroll area -- on a short page, the
// last section could sit permanently under the toolbar with no way to
// scroll past it. Mirrors that toolbar's own visibility condition
// (`selectedId && activeSheet === null`) exactly, computed independently
// here since Canvas has no other reason to depend on the toolbar
// component itself.
const isMobile = useIsMobile();
const { activeSheet } = useMobileChrome();
const { selectedId } = useEditor((state) => {
const selected = state.events.selected;
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
return { selectedId: id && id !== 'ROOT' ? id : null };
});
const mobileToolbarVisible = isMobile && !!selectedId && activeSheet === null;
// Fast-follow item 3: `MobileSelectionToolbar`'s "Style" tap scrolls the
// selected node up towards the top of the canvas so it stays visible
// above the Styles sheet (~65dvh tall) -- but that scroll is still bound
// by the canvas's own natural scroll range. For a selected node near the
// END of the content (very plausibly the last section on the page --
// exactly the kind of node someone just added/duplicated and wants to
// style), there may not be enough scrollable distance below it to bring
// its top all the way up to the visible band above the sheet; the browser
// simply clamps at its existing max scrollTop, leaving the node's top
// stuck behind the sheet with nothing anyone can do about it (verified
// live: the last section of a page landed under the sheet even after the
// scroll-into-view ran). Pad the canvas with a full extra viewport's
// worth of scroll room while the sheet is open with a selection, exactly
// as `has-mobile-selection-toolbar` (item 4) already pads it for the
// fixed toolbar -- generous enough that ANY node, including the very
// last one, can always be scrolled with its top reaching the very top of
// the canvas (comfortably within the "top ~30%" target).
const mobileStylesSheetPad = isMobile && !!selectedId && activeSheet === 'styles';
const frameStyle = isEditingHeader const frameStyle = isEditingHeader
? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' } ? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' }
: isEditingFooter : isEditingFooter
@@ -144,7 +181,11 @@ export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div'; const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div';
return ( return (
<div className="editor-canvas"> <div
className={`editor-canvas${mobileToolbarVisible ? ' has-mobile-selection-toolbar' : ''}${
mobileStylesSheetPad ? ' has-mobile-styles-sheet' : ''
}`}
>
<div <div
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`} className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
style={{ style={{
+2
View File
@@ -4,6 +4,7 @@ import { TopBar } from '../panels/topbar/TopBar';
import { LeftPanel } from '../panels/left/LeftPanel'; import { LeftPanel } from '../panels/left/LeftPanel';
import { RightPanel } from '../panels/right/RightPanel'; import { RightPanel } from '../panels/right/RightPanel';
import { MobilePanelBar } from '../panels/mobile/MobilePanelBar'; import { MobilePanelBar } from '../panels/mobile/MobilePanelBar';
import { MobileSelectionToolbar } from '../panels/mobile/MobileSelectionToolbar';
import { Canvas } from './Canvas'; import { Canvas } from './Canvas';
import { ContextMenu } from '../panels/context-menu/ContextMenu'; import { ContextMenu } from '../panels/context-menu/ContextMenu';
import { useContextMenu } from '../hooks/useContextMenu'; import { useContextMenu } from '../hooks/useContextMenu';
@@ -97,6 +98,7 @@ export const EditorShell: React.FC = () => {
{!isMobile && <RightPanel />} {!isMobile && <RightPanel />}
</div> </div>
{isMobile && <MobilePanelBar />} {isMobile && <MobilePanelBar />}
{isMobile && <MobileSelectionToolbar />}
<ContextMenu <ContextMenu
visible={menuState.visible} visible={menuState.visible}
x={menuState.x} x={menuState.x}
+258
View File
@@ -0,0 +1,258 @@
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import type { NodeTree, Node } from '@craftjs/core';
import { useNodeActions, type NodeActions } from './useNodeActions';
/**
* Phase B, item 1: `useNodeActions` was extracted out of `ContextMenu.tsx` so
* the desktop right-click menu and the mobile selection toolbar
* (`MobileSelectionToolbar`) share one implementation. This suite exercises
* the hook directly (mocking `@craftjs/core`'s `useEditor`, mirroring the
* pattern in `useKeyboardShortcuts.test.tsx`), covering:
* - moveUp/moveDown call `actions.move` with the right target index, and
* are no-ops at the respective boundary
* - canMoveUp/canMoveDown reflect the node's position among its siblings
* - duplicate regenerates ids, inserts the copy IMMEDIATELY AFTER the
* source node (`actions.addNodeTree(tree, parentId, sourceIndex + 1)`),
* and selects the new copy (`actions.selectNode(tree.rootNodeId)`) --
* Phase B fast-follow: the previous append-at-end behavior left the copy
* off-screen with the ORIGINAL still selected, so users couldn't see
* what "Duplicate" had just done.
* - selectParent calls `actions.selectNode` with the parent id
* - canSelectParent reflects whether the node's parent is itself real
* (not ROOT/missing) -- false at a top-level section, true one level in
* - deleteNode routes through `findDeletableTarget` (also covering the
* "no deletable target" no-op)
* - ROOT/null nodeId disables every action safely (no-ops, all
* canMoveUp/canMoveDown/canDelete/canSelectParent false)
*/
const moveMock = vi.fn();
const addNodeTreeMock = vi.fn();
const selectNodeMock = vi.fn();
const deleteMock = vi.fn();
interface FakeNodeData {
parent: string | null;
nodes: string[];
}
let fakeNodes: Record<string, { data: FakeNodeData }> = {};
const COPIED_TREE: NodeTree = {
rootNodeId: 'child-1',
nodes: {
'child-1': {
id: 'child-1',
data: { props: {}, type: { resolvedName: 'Container' }, name: 'Container', displayName: 'Container', isCanvas: false, parent: 'parent-1', linkedNodes: {}, nodes: [], hidden: false },
info: {},
events: { selected: false, dragged: false, hovered: false },
dom: null,
related: {},
rules: {},
_hydrationTimestamp: 0,
} as unknown as Node,
},
};
function makeQuery() {
return {
node: (id: string) => ({
get: () => fakeNodes[id] ?? null,
toNodeTree: () => {
if (id !== 'child-1') throw new Error(`unexpected toNodeTree() for "${id}"`);
return COPIED_TREE;
},
}),
};
}
vi.mock('@craftjs/core', () => ({
useEditor: (collector?: (state: any, query: any) => any) => {
const state = {
nodes: Object.fromEntries(Object.entries(fakeNodes).map(([id, n]) => [id, n])),
};
const query = makeQuery();
const collected = collector ? collector(state, query) : {};
return {
...collected,
actions: {
move: moveMock,
addNodeTree: addNodeTreeMock,
selectNode: selectNodeMock,
delete: deleteMock,
},
query,
};
},
}));
vi.mock('../utils/craft-tree', async (importOriginal) => {
const actual = await importOriginal<typeof import('../utils/craft-tree')>();
return { ...actual, regenerateTreeIds: vi.fn(actual.regenerateTreeIds) };
});
import { regenerateTreeIds } from '../utils/craft-tree';
const regenerateTreeIdsMock = vi.mocked(regenerateTreeIds);
let container: HTMLDivElement;
let root: Root;
let captured: NodeActions | null = null;
const Probe: React.FC<{ nodeId: string | null }> = ({ nodeId }) => {
captured = useNodeActions(nodeId);
return null;
};
function render(nodeId: string | null) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(<Probe nodeId={nodeId} />);
});
}
function rerender(nodeId: string | null) {
act(() => {
root.render(<Probe nodeId={nodeId} />);
});
}
function unmount() {
act(() => {
root.unmount();
});
container.remove();
}
beforeEach(() => {
moveMock.mockClear();
addNodeTreeMock.mockClear();
selectNodeMock.mockClear();
deleteMock.mockClear();
regenerateTreeIdsMock.mockClear();
captured = null;
fakeNodes = {
ROOT: { data: { parent: null, nodes: ['parent-1'] } },
'parent-1': { data: { parent: 'ROOT', nodes: ['child-0', 'child-1', 'child-2'] } },
'child-0': { data: { parent: 'parent-1', nodes: [] } },
'child-1': { data: { parent: 'parent-1', nodes: [] } },
'child-2': { data: { parent: 'parent-1', nodes: [] } },
};
});
afterEach(() => {
if (root) unmount();
});
describe('useNodeActions', () => {
test('a middle child can move both up and down', () => {
render('child-1');
expect(captured!.canMoveUp).toBe(true);
expect(captured!.canMoveDown).toBe(true);
});
test('the first child cannot move up, but can move down', () => {
render('child-0');
expect(captured!.canMoveUp).toBe(false);
expect(captured!.canMoveDown).toBe(true);
});
test('the last child can move up, but not down', () => {
render('child-2');
expect(captured!.canMoveUp).toBe(true);
expect(captured!.canMoveDown).toBe(false);
});
test('moveUp calls actions.move with idx - 1, moveDown with idx + 2 (Craft.js index semantics)', () => {
render('child-1');
act(() => captured!.moveUp());
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 0);
moveMock.mockClear();
act(() => captured!.moveDown());
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 3);
});
test('moveUp/moveDown at a boundary are no-ops', () => {
render('child-0');
act(() => captured!.moveUp());
expect(moveMock).not.toHaveBeenCalled();
rerender('child-2');
act(() => captured!.moveDown());
expect(moveMock).not.toHaveBeenCalled();
});
test('duplicate inserts the copy immediately after the source (parentId, sourceIndex + 1) and selects it', () => {
render('child-1');
let returned: string | null | undefined;
act(() => {
returned = captured!.duplicate();
});
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [tree, parentId, index] = addNodeTreeMock.mock.calls[0];
// child-1 is at index 1 among ['child-0', 'child-1', 'child-2'] -> insert at 2.
expect(parentId).toBe('parent-1');
expect(index).toBe(2);
expect(tree.rootNodeId).not.toBe(COPIED_TREE.rootNodeId);
expect(selectNodeMock).toHaveBeenCalledTimes(1);
expect(selectNodeMock).toHaveBeenCalledWith(tree.rootNodeId);
expect(returned).toBe(tree.rootNodeId);
});
test('selectParent calls actions.selectNode with the parent id', () => {
render('child-1');
act(() => captured!.selectParent());
expect(selectNodeMock).toHaveBeenCalledWith('parent-1');
});
test('canSelectParent is false at a top-level node (parent is ROOT), true one level deeper', () => {
render('parent-1'); // parent-1's own parent is 'ROOT'
expect(captured!.canSelectParent).toBe(false);
rerender('child-1'); // child-1's parent is 'parent-1', a real node
expect(captured!.canSelectParent).toBe(true);
});
test('deleteNode calls actions.delete with the node id when deletable', () => {
render('child-1');
expect(captured!.canDelete).toBe(true);
act(() => captured!.deleteNode());
expect(deleteMock).toHaveBeenCalledWith('child-1');
});
test('ROOT nodeId disables every action and is a safe no-op', () => {
render('ROOT');
expect(captured!.canMoveUp).toBe(false);
expect(captured!.canMoveDown).toBe(false);
expect(captured!.canDelete).toBe(false);
expect(captured!.canSelectParent).toBe(false);
act(() => {
captured!.moveUp();
captured!.moveDown();
captured!.duplicate();
captured!.selectParent();
captured!.deleteNode();
});
expect(moveMock).not.toHaveBeenCalled();
expect(addNodeTreeMock).not.toHaveBeenCalled();
expect(selectNodeMock).not.toHaveBeenCalled();
expect(deleteMock).not.toHaveBeenCalled();
});
test('null nodeId disables every action and is a safe no-op', () => {
render(null);
expect(captured!.canMoveUp).toBe(false);
expect(captured!.canMoveDown).toBe(false);
expect(captured!.canDelete).toBe(false);
expect(captured!.canSelectParent).toBe(false);
});
});
+221
View File
@@ -0,0 +1,221 @@
import { useEditor } from '@craftjs/core';
import { regenerateTreeIds } from '../utils/craft-tree';
import { findDeletableTarget } from '../utils/craft-helpers';
export interface NodeActions {
moveUp: () => void;
moveDown: () => void;
/** Duplicates `nodeId`, inserting the copy immediately after the source in
* the parent's children and selecting it. Returns the new node's id (so
* callers -- e.g. `MobileSelectionToolbar` -- can scroll it into view),
* or null if the duplicate could not be performed (no-op for ROOT/null,
* or a caught error). */
duplicate: () => string | null;
deleteNode: () => void;
selectParent: () => void;
/** True if `nodeId` has an earlier sibling under the same parent (so
* `moveUp` would actually move it). False for ROOT/null/no-parent. */
canMoveUp: boolean;
/** True if `nodeId` has a later sibling under the same parent (so
* `moveDown` would actually move it). False for ROOT/null/no-parent. */
canMoveDown: boolean;
/** True if `findDeletableTarget` resolves to a real, deletable node (either
* `nodeId` itself, or an ancestor when `nodeId` is an empty linked-node
* slot whose siblings are all also empty -- see `craft-helpers.ts`). */
canDelete: boolean;
/** True if `nodeId` has a real parent to select -- i.e. the parent is
* neither ROOT nor missing. `selectParent` on a top-level section (whose
* parent IS 'ROOT') would only select the page-wide ROOT node, which has
* no on-canvas outline and no toolbar of its own -- a dead end for a
* mobile user with no way back. False for ROOT/null/no-parent too. */
canSelectParent: boolean;
}
/**
* Shared node-action logic (move up/down, duplicate, delete, select parent)
* extracted from `ContextMenu.tsx` (Phase B) so both the desktop right-click
* menu AND the mobile on-canvas selection toolbar (`MobileSelectionToolbar`)
* drive the exact same behavior from one place instead of two independent
* copies drifting apart.
*
* IMPORTANT gotcha this hook works around: `@craftjs/core`'s `useEditor`
* collector (`@craftjs/utils`' `useCollector`) only synchronously computes
* the collector function ONCE, on this hook's very first mount. After that,
* it updates purely in reaction to the underlying store's OWN change
* notifications, invoking whatever collector closure is current AT THAT
* NOTIFICATION -- so a collector that closes over `nodeId` (an argument that
* changes across renders of the SAME mounted hook instance, e.g. every time
* `MobileSelectionToolbar` re-renders with a newly-selected node) goes stale
* for exactly one render: the cached value from the last store notification
* (computed against the PREVIOUS nodeId) is what gets returned, until some
* unrelated store event happens to trigger a fresh computation. An earlier
* version of this hook computed `canMoveUp`/`canMoveDown`/`canDelete` inside
* such a collector and was caught showing the PREVIOUS selection's move
* boundaries in the mobile toolbar for one render after tapping a new node
* (verified with real Playwright touch taps against a real Craft.js
* document -- a plain mocked `useEditor` in a unit test doesn't reproduce
* this, since a hand-rolled mock has no reason to replicate the real
* library's caching).
*
* The fix: get `actions`/`query` from a collector-FREE `useEditor()` call
* (an always-live reference, same pattern `ContextMenu.tsx` used before this
* extraction) and compute `canMoveUp`/`canMoveDown`/`canDelete` as plain
* synchronous code during render using that live `query` -- never cached.
*
* That still leaves one gap: `nodeId` staying the SAME across renders while
* its position changes (e.g. tapping "Move Up" repeatedly on the same
* still-selected node) needs SOMETHING to trigger a re-render so the boundary
* flags below get recomputed. An earlier version of this hook forced that
* via a second `useEditor((state) => ({ _: state.nodes }))` subscription --
* but subscribing to the WHOLE node map reacts to every `dom` ref
* assignment too (Craft's `connectors.connect(ref)` calls `actions.setDOM`
* synchronously from a React ref callback during COMMIT, i.e. while some
* OTHER component is still mounting), which trips React's "Cannot update a
* component while rendering a different component" warning the moment a
* freshly-added container with children mounts. Callers that need
* `canMoveUp`/`canMoveDown` to refresh after a move they themselves
* triggered (`MobileSelectionToolbar`) should instead bump their OWN local
* state right after calling `moveUp`/`moveDown` -- a plain, local,
* event-handler-triggered re-render, not a store-wide subscription.
*/
export function useNodeActions(nodeId: string | null | undefined): NodeActions {
const { actions, query } = useEditor();
const isRootOrNull = !nodeId || nodeId === 'ROOT';
let canMoveUp = false;
let canMoveDown = false;
let canSelectParent = false;
if (!isRootOrNull) {
try {
const node = query.node(nodeId).get();
const parentId: string | null | undefined = node?.data?.parent;
if (parentId) {
canSelectParent = parentId !== 'ROOT';
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
const idx = siblings.indexOf(nodeId);
canMoveUp = idx > 0;
canMoveDown = idx !== -1 && idx < siblings.length - 1;
}
} catch {
// Node no longer exists (e.g. deleted out from under a stale
// reference) -- leave both false.
}
}
const canDelete = !isRootOrNull && !!findDeletableTarget(query, nodeId);
const getParentId = (): string | null => {
if (!nodeId) return null;
try {
const node = query.node(nodeId).get();
return node?.data?.parent || null;
} catch {
return null;
}
};
const duplicate = (): string | null => {
if (!nodeId || nodeId === 'ROOT') return null;
try {
const parentId = getParentId();
if (!parentId) return null;
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree());
// Insert the copy IMMEDIATELY AFTER the source node, not appended at
// the end of the parent -- on a top-level section, "append at end"
// landed the copy at the bottom of the page, off-screen, with the
// ORIGINAL still selected, so a duplicate looked like nothing had
// happened at all. Resolve the source's index among its siblings so
// the copy lands right next to what it was copied from; if that can't
// be resolved for any reason, fall back to the old append behavior
// rather than guessing at an index (or throwing).
let insertIndex: number | undefined;
try {
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
const sourceIndex = siblings.indexOf(nodeId);
if (sourceIndex !== -1) insertIndex = sourceIndex + 1;
} catch {
// Leave insertIndex undefined -- addNodeTree appends when omitted.
}
if (insertIndex !== undefined) {
actions.addNodeTree(tree, parentId, insertIndex);
} else {
actions.addNodeTree(tree, parentId);
}
// Select the new copy (not the original) so the toolbar/context menu
// and any on-canvas outline immediately reflect what was just created.
actions.selectNode(tree.rootNodeId);
return tree.rootNodeId;
} catch (e) {
console.error('Duplicate failed:', e);
return null;
}
};
const moveUp = () => {
if (!nodeId || nodeId === 'ROOT') return;
try {
const parentId = getParentId();
if (!parentId) return;
const parent = query.node(parentId).get();
const children = parent.data.nodes || [];
const idx = children.indexOf(nodeId);
if (idx > 0) {
actions.move(nodeId, parentId, idx - 1);
}
} catch (e) {
console.error('Move up failed:', e);
}
};
const moveDown = () => {
if (!nodeId || nodeId === 'ROOT') return;
try {
const parentId = getParentId();
if (!parentId) return;
const parent = query.node(parentId).get();
const children = parent.data.nodes || [];
const idx = children.indexOf(nodeId);
if (idx < children.length - 1) {
actions.move(nodeId, parentId, idx + 2);
}
} catch (e) {
console.error('Move down failed:', e);
}
};
const selectParent = () => {
if (!nodeId || nodeId === 'ROOT') return;
const parentId = getParentId();
if (parentId) {
actions.selectNode(parentId);
}
};
const deleteNode = () => {
const target = findDeletableTarget(query, nodeId);
if (!target) return;
try {
actions.delete(target);
} catch (e) {
console.error('Delete failed:', e);
}
};
return {
moveUp,
moveDown,
duplicate,
deleteNode,
selectParent,
canMoveUp,
canMoveDown,
canDelete,
canSelectParent,
};
}
+146
View File
@@ -0,0 +1,146 @@
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { useVisualViewportInsets } from './useVisualViewport';
/**
* Fast-follow coverage for `useVisualViewportInsets` (BottomSheet's
* keyboard-avoidance source of truth). Mirrors the bare createRoot + act
* harness `useIsMobile.test.tsx` uses (no @testing-library/react in this
* repo). Covers:
* - the no-`visualViewport` fallback (older WebViews) returns
* `{ height: window.innerHeight, keyboardInset: 0 }` AND registers no
* listener (there's nothing to listen to).
* - the keyboard-open math: `keyboardInset = innerHeight - (vv.height +
* vv.offsetTop)`, recomputed when the mocked vv fires `resize`.
* - both `resize` and `scroll` listeners are added on mount and the SAME
* handler is removed for both on unmount (a leaked listener would keep
* reacting after the owning component -- e.g. BottomSheet -- is gone).
*/
let container: HTMLDivElement;
let root: Root;
let originalInnerHeight: number;
let originalVisualViewport: VisualViewport | null;
function render(ui: React.ReactElement) {
container = document.createElement('div');
document.body.appendChild(container);
act(() => {
root = createRoot(container);
root.render(ui);
});
}
function unmount() {
act(() => {
root.unmount();
});
container.remove();
}
/** A minimal fake `visualViewport`: just enough surface for the hook
* (`height`, `offsetTop`, `addEventListener`/`removeEventListener`). */
function makeVisualViewport(height: number, offsetTop: number) {
const listeners: Record<string, Array<() => void>> = { resize: [], scroll: [] };
const vv: any = {
height,
offsetTop,
addEventListener: vi.fn((type: string, fn: () => void) => {
listeners[type].push(fn);
}),
removeEventListener: vi.fn((type: string, fn: () => void) => {
const i = listeners[type].indexOf(fn);
if (i !== -1) listeners[type].splice(i, 1);
}),
};
return {
vv,
fire: (type: 'resize' | 'scroll') => listeners[type].forEach((fn) => fn()),
listenerCount: (type: 'resize' | 'scroll') => listeners[type].length,
};
}
let probed: { height: number; keyboardInset: number } | null = null;
const Probe: React.FC = () => {
probed = useVisualViewportInsets();
return <span data-height={probed.height} data-inset={probed.keyboardInset} />;
};
beforeEach(() => {
originalInnerHeight = window.innerHeight;
originalVisualViewport = window.visualViewport;
probed = null;
});
afterEach(() => {
Object.defineProperty(window, 'innerHeight', {
value: originalInnerHeight,
configurable: true,
writable: true,
});
Object.defineProperty(window, 'visualViewport', {
value: originalVisualViewport,
configurable: true,
});
});
describe('useVisualViewportInsets', () => {
test('falls back to innerHeight/0 and registers no listener when visualViewport is undefined', () => {
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true });
render(<Probe />);
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
unmount();
});
test('computes keyboardInset from visualViewport and recomputes on resize', () => {
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
const { vv, fire } = makeVisualViewport(800, 0);
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
render(<Probe />);
// No keyboard open: vv fills the layout viewport exactly.
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
// Simulate the on-screen keyboard opening: the visual viewport shrinks.
vv.height = 500;
vv.offsetTop = 0;
act(() => {
fire('resize');
});
expect(probed).toEqual({ height: 500, keyboardInset: 300 });
unmount();
});
test('registers resize and scroll listeners on mount and removes both (same handler) on unmount', () => {
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
const { vv, listenerCount } = makeVisualViewport(800, 0);
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
render(<Probe />);
expect(vv.addEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
expect(vv.addEventListener).toHaveBeenCalledWith('scroll', expect.any(Function));
expect(listenerCount('resize')).toBe(1);
expect(listenerCount('scroll')).toBe(1);
const resizeHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'resize')[1];
const scrollHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'scroll')[1];
expect(resizeHandler).toBe(scrollHandler);
unmount();
expect(vv.removeEventListener).toHaveBeenCalledWith('resize', resizeHandler);
expect(vv.removeEventListener).toHaveBeenCalledWith('scroll', scrollHandler);
expect(listenerCount('resize')).toBe(0);
expect(listenerCount('scroll')).toBe(0);
});
});
+55
View File
@@ -0,0 +1,55 @@
import { useEffect, useState } from 'react';
export interface VisualViewportInsets {
/** The visual viewport's current height (shrinks when the on-screen
* keyboard opens). Falls back to `window.innerHeight` when
* `visualViewport` isn't supported. */
height: number;
/** Extra inset a `position: fixed`, bottom-anchored element should add to
* its own `bottom` offset to stay clear of the on-screen keyboard --
* `window.innerHeight` minus the visual viewport's bottom edge (its
* height + offsetTop). Zero whenever no keyboard is open, or
* `visualViewport` isn't supported (a safe no-op fallback). */
keyboardInset: number;
}
const ZERO_INSETS: VisualViewportInsets = { height: 0, keyboardInset: 0 };
function computeInsets(): VisualViewportInsets {
if (typeof window === 'undefined') return ZERO_INSETS;
const vv = window.visualViewport;
if (!vv) return { height: window.innerHeight, keyboardInset: 0 };
const keyboardInset = Math.max(0, window.innerHeight - (vv.height + vv.offsetTop));
return { height: vv.height, keyboardInset };
}
/**
* Tracks `window.visualViewport`'s height/offset (item 5, Phase B) so
* `BottomSheet` can stay clear of the on-screen keyboard. `position: fixed`
* elements are positioned against the LAYOUT viewport, which does NOT shrink
* when a mobile keyboard opens -- only the visual viewport does -- so a
* bottom-anchored sheet's inputs can otherwise end up hidden underneath the
* keyboard with no visual indication anything is wrong.
*
* Guards for browsers without `visualViewport` (older WebViews): falls back
* to `{ height: window.innerHeight, keyboardInset: 0 }`, i.e. a no-op, so
* the sheet just keeps its existing (keyboard-unaware) sizing there.
*/
export function useVisualViewportInsets(): VisualViewportInsets {
const [insets, setInsets] = useState<VisualViewportInsets>(computeInsets);
useEffect(() => {
if (typeof window === 'undefined' || !window.visualViewport) return;
const vv = window.visualViewport;
const handleChange = () => setInsets(computeInsets());
handleChange();
vv.addEventListener('resize', handleChange);
vv.addEventListener('scroll', handleChange);
return () => {
vv.removeEventListener('resize', handleChange);
vv.removeEventListener('scroll', handleChange);
};
}, []);
return insets;
}
+23 -58
View File
@@ -1,10 +1,10 @@
import React, { useEffect, useCallback, useRef } from 'react'; import React, { useEffect, useCallback, useRef } from 'react';
import { useEditor } from '@craftjs/core'; import { useEditor } from '@craftjs/core';
import { findDeletableTarget } from '../../utils/craft-helpers';
import { useSitesmithModal } from '../../state/SitesmithContext'; import { useSitesmithModal } from '../../state/SitesmithContext';
import { buildSitesmithTarget } from '../../utils/sitesmith-target'; import { buildSitesmithTarget } from '../../utils/sitesmith-target';
import { regenerateTreeIds } from '../../utils/craft-tree'; import { regenerateTreeIds } from '../../utils/craft-tree';
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard'; import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
import { useNodeActions } from '../../hooks/useNodeActions';
interface ContextMenuProps { interface ContextMenuProps {
visible: boolean; visible: boolean;
@@ -65,19 +65,16 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
} }
}, [nodeId, query]); }, [nodeId, query]);
const duplicate = useCallback(() => { // Shared move/duplicate/delete/select-parent logic (item 1, Phase B) --
if (!nodeId || nodeId === 'ROOT') return; // extracted into `useNodeActions` so the mobile selection toolbar drives
try { // the exact same behavior. Wrapped here purely to also `onClose()` the
const parentId = getParentId(); // menu after each action, same as before the extraction.
if (!parentId) return; const nodeActions = useNodeActions(nodeId);
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree()); const duplicate = useCallback(() => {
actions.addNodeTree(tree, parentId); nodeActions.duplicate();
} catch (e) {
console.error('Duplicate failed:', e);
}
onClose(); onClose();
}, [nodeId, actions, query, getParentId, onClose]); }, [nodeActions, onClose]);
const copyNode = useCallback(() => { const copyNode = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; if (!nodeId || nodeId === 'ROOT') return;
@@ -118,47 +115,19 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
}, [nodeId, actions, query, onClose]); }, [nodeId, actions, query, onClose]);
const moveUp = useCallback(() => { const moveUp = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; nodeActions.moveUp();
try {
const parentId = getParentId();
if (!parentId) return;
const parent = query.node(parentId).get();
const children = parent.data.nodes || [];
const idx = children.indexOf(nodeId);
if (idx > 0) {
actions.move(nodeId, parentId, idx - 1);
}
} catch (e) {
console.error('Move up failed:', e);
}
onClose(); onClose();
}, [nodeId, actions, query, getParentId, onClose]); }, [nodeActions, onClose]);
const moveDown = useCallback(() => { const moveDown = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; nodeActions.moveDown();
try {
const parentId = getParentId();
if (!parentId) return;
const parent = query.node(parentId).get();
const children = parent.data.nodes || [];
const idx = children.indexOf(nodeId);
if (idx < children.length - 1) {
actions.move(nodeId, parentId, idx + 2);
}
} catch (e) {
console.error('Move down failed:', e);
}
onClose(); onClose();
}, [nodeId, actions, query, getParentId, onClose]); }, [nodeActions, onClose]);
const selectParent = useCallback(() => { const selectParent = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; nodeActions.selectParent();
const parentId = getParentId();
if (parentId) {
actions.selectNode(parentId);
}
onClose(); onClose();
}, [nodeId, actions, getParentId, onClose]); }, [nodeActions, onClose]);
const askSitesmith = useCallback(() => { const askSitesmith = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return; if (!nodeId || nodeId === 'ROOT') return;
@@ -172,18 +141,9 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
}, [nodeId, query, openSitesmith, onClose]); }, [nodeId, query, openSitesmith, onClose]);
const deleteNode = useCallback(() => { const deleteNode = useCallback(() => {
const target = findDeletableTarget(query, nodeId); nodeActions.deleteNode();
if (!target) {
onClose(); onClose();
return; }, [nodeActions, onClose]);
}
try {
actions.delete(target);
} catch (e) {
console.error('Delete failed:', e);
}
onClose();
}, [nodeId, actions, query, onClose]);
if (!visible) return null; if (!visible) return null;
@@ -235,7 +195,12 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
label: 'Select Parent', label: 'Select Parent',
icon: 'level-up', icon: 'level-up',
action: selectParent, action: selectParent,
disabled: isRoot, // Not just `isRoot`: the real dead-end is when nodeId's PARENT is
// ROOT (selecting a top-level section -> Select Parent would only
// select the page-wide, un-editable ROOT -- no outline, no toolbar).
// `canSelectParent` (useNodeActions) already encodes that and matches
// the mobile selection toolbar's identical guard.
disabled: !nodeActions.canSelectParent,
dividerAfter: true, dividerAfter: true,
}, },
{ {
+103 -19
View File
@@ -1,5 +1,7 @@
import React, { useState } from 'react'; import React, { useCallback, useState } from 'react';
import { useEditor } from '@craftjs/core'; import { useEditor } from '@craftjs/core';
import { useIsMobile } from '../../hooks/useIsMobile';
import { useMobileChrome } from '../../state/MobileChromeContext';
import { Container } from '../../components/layout/Container'; import { Container } from '../../components/layout/Container';
import { Section } from '../../components/layout/Section'; import { Section } from '../../components/layout/Section';
import { ColumnLayout } from '../../components/layout/ColumnLayout'; import { ColumnLayout } from '../../components/layout/ColumnLayout';
@@ -146,6 +148,8 @@ const categories: CategoryDef[] = [
export const BlocksPanel: React.FC = () => { export const BlocksPanel: React.FC = () => {
const { connectors, actions, query } = useEditor(); const { connectors, actions, query } = useEditor();
const isMobile = useIsMobile();
const { closeSheet } = useMobileChrome();
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => { const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => {
const initial: Record<string, boolean> = {}; const initial: Record<string, boolean> = {};
categories.forEach((cat, index) => { categories.forEach((cat, index) => {
@@ -158,6 +162,101 @@ export const BlocksPanel: React.FC = () => {
setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] })); setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] }));
}; };
/** Default insertion target when there's no usable selection to anchor
* to: the first real Craft.js canvas in the document (falls back to
* ROOT). Extracted from the pre-existing onDoubleClick handler so
* tap-to-add (mobile, item 3) and double-click (desktop, unchanged) share
* the exact same fallback. */
const findDefaultCanvasId = useCallback((): string => {
try {
const serialized = JSON.parse(query.serialize());
const nodeIds = Object.keys(serialized);
for (const id of nodeIds) {
if (serialized[id].isCanvas && id !== 'ROOT') return id;
}
} catch {
// Fall through to ROOT below.
}
return 'ROOT';
}, [query]);
/**
* Builds a fresh node tree for `block` and inserts it into the canvas,
* returning the new node's id (or null on failure). Shared by desktop's
* double-click (unchanged behavior/position: always appended to
* `findDefaultCanvasId()`) and mobile's tap-to-add (item 3), which instead
* prefers inserting as a sibling right after the current selection --
* `insertAfterSelection: true` only from the mobile tap handler below.
*/
const addBlockNode = useCallback((block: BlockDef, insertAfterSelection: boolean): string | null => {
try {
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
let inserted = false;
if (insertAfterSelection) {
try {
const selectedIds = query.getEvent('selected').all();
const selectedId = selectedIds.length > 0 ? selectedIds[0] : null;
if (selectedId && selectedId !== 'ROOT') {
const selectedNode = query.node(selectedId).get();
const parentId = selectedNode?.data?.parent;
if (parentId) {
const parent = query.node(parentId).get();
const siblings: string[] = parent?.data?.nodes || [];
const idx = siblings.indexOf(selectedId);
if (idx !== -1) {
actions.addNodeTree(tree, parentId, idx + 1);
inserted = true;
}
}
}
} catch {
// Selection isn't a valid sibling target (e.g. lives in a
// linkedNodes slot) -- fall through to the default canvas below.
}
}
if (!inserted) {
actions.addNodeTree(tree, findDefaultCanvasId());
}
return tree.rootNodeId;
} catch (e) {
console.error('Failed to add block:', e);
return null;
}
}, [query, actions, findDefaultCanvasId]);
/**
* Mobile tap-to-add (item 3): a single tap on a block tile inserts it,
* closes the Blocks sheet, then selects the new node and scrolls it into
* view so the user immediately sees it (and gets the selection toolbar).
* The select/scroll step is deferred two animation frames past the
* `addNodeTree` call -- Craft.js's own state update (and thus the new
* node's real DOM element) lands asynchronously after this handler
* returns, so `query.node(id).get().dom` isn't populated yet if read
* synchronously here.
*/
const handleTapToAdd = useCallback((block: BlockDef) => {
const newId = addBlockNode(block, true);
closeSheet();
if (!newId) return;
requestAnimationFrame(() => {
try {
actions.selectNode(newId);
} catch {
// Node may have failed to mount -- nothing to select.
}
requestAnimationFrame(() => {
try {
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} catch {
// Best-effort scroll -- not fatal if the node/DOM isn't found.
}
});
});
}, [addBlockNode, closeSheet, actions, query]);
return ( return (
<div> <div>
{categories.map((category) => { {categories.map((category) => {
@@ -178,24 +277,9 @@ export const BlocksPanel: React.FC = () => {
key={block.id} key={block.id}
className="block-item" className="block-item"
ref={(ref) => { if (ref) connectors.create(ref, block.component); }} ref={(ref) => { if (ref) connectors.create(ref, block.component); }}
onDoubleClick={() => { onDoubleClick={() => addBlockNode(block, false)}
try { onClick={isMobile ? () => handleTapToAdd(block) : undefined}
const serialized = JSON.parse(query.serialize()); title={isMobile ? `Tap to add ${block.label}` : `Drag or double-click to add ${block.label}`}
const nodeIds = Object.keys(serialized);
let canvasId = 'ROOT';
for (const nodeId of nodeIds) {
if (serialized[nodeId].isCanvas && nodeId !== 'ROOT') {
canvasId = nodeId;
break;
}
}
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
actions.addNodeTree(tree, canvasId);
} catch (e) {
console.error('Failed to add block:', e);
}
}}
title={`Drag or double-click to add ${block.label}`}
> >
<i className={`fa ${block.icon} block-item-icon`} /> <i className={`fa ${block.icon} block-item-icon`} />
<span className="block-item-label">{block.label}</span> <span className="block-item-label">{block.label}</span>
+1
View File
@@ -146,6 +146,7 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
{...clickableProps(handleActivate)} {...clickableProps(handleActivate)}
onMouseEnter={handleMouseEnter} onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave} onMouseLeave={handleMouseLeave}
className="layer-node-row"
style={{ style={{
position: 'relative', position: 'relative',
display: 'flex', display: 'flex',
+119 -5
View File
@@ -1,4 +1,5 @@
import React, { useEffect } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useVisualViewportInsets } from '../../hooks/useVisualViewport';
export interface BottomSheetProps { export interface BottomSheetProps {
open: boolean; open: boolean;
@@ -7,6 +8,10 @@ export interface BottomSheetProps {
children: React.ReactNode; children: React.ReactNode;
} }
/** Vertical drag distance (px) past which releasing the handle/header
* commits to closing the sheet, rather than snapping back open. */
const SWIPE_DISMISS_THRESHOLD_PX = 80;
/** /**
* Mobile-only bottom sheet (Phase A). Slides up from the bottom of the * Mobile-only bottom sheet (Phase A). Slides up from the bottom of the
* viewport to host one of the existing side-panel components * viewport to host one of the existing side-panel components
@@ -18,6 +23,22 @@ export interface BottomSheetProps {
* dialog chrome) -- this is anchored to the bottom, sized to ~65dvh, and * dialog chrome) -- this is anchored to the bottom, sized to ~65dvh, and
* has its own drag-handle affordance + internally scrollable body, all of * has its own drag-handle affordance + internally scrollable body, all of
* which Modal doesn't need for its centered use cases. * which Modal doesn't need for its centered use cases.
*
* Phase B adds two more deferred behaviors on top of Phase A's static sheet:
* - **Swipe-to-dismiss**: a touchstart/move/end drag tracked on the handle
* row + header (not the scrollable body, so it never fights a panel's own
* vertical scroll) that follows the finger while dragging down and either
* commits to `onClose()` past `SWIPE_DISMISS_THRESHOLD_PX` or snaps back
* with a short transition otherwise.
* - **On-screen-keyboard clearance**: `useVisualViewportInsets` reports how
* much the visual viewport has shrunk from the bottom (i.e. the
* keyboard's height); that's surfaced as a `--keyboard-inset` CSS custom
* property (see editor.css) which both lifts the whole backdrop/sheet
* clear of the keyboard AND caps the sheet's own max-height so it never
* extends into the space the keyboard occupies. A `focusin` listener also
* scrolls the newly-focused input into view once the keyboard has had a
* moment to animate in, as a second line of defense for a field that's
* still off-screen after the resize alone (e.g. deep in a long panel).
*/ */
export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title, children }) => { export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title, children }) => {
useEffect(() => { useEffect(() => {
@@ -35,6 +56,78 @@ export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title,
}; };
}, [open, onClose]); }, [open, onClose]);
const { keyboardInset } = useVisualViewportInsets();
const bodyRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const bodyEl = bodyRef.current;
if (!bodyEl) return;
const handleFocusIn = (e: FocusEvent) => {
const target = e.target as HTMLElement | null;
if (!target) return;
const tag = target.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable) {
// Give the on-screen keyboard a moment to finish animating in
// before scrolling -- doing it immediately measures the pre-keyboard
// layout and can undershoot.
window.setTimeout(() => {
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
}, 300);
}
};
bodyEl.addEventListener('focusin', handleFocusIn);
return () => bodyEl.removeEventListener('focusin', handleFocusIn);
}, [open]);
// Swipe-to-dismiss: tracked only on the handle row + header (never the
// scrollable `.mobile-sheet-body`, which needs its own vertical touch
// scrolling to keep working unimpeded).
//
// The authoritative drag distance lives in a REF (`dragOffsetRef`),
// updated synchronously and imperatively on every touchmove -- NOT solely
// in the `dragOffset` state used for rendering the drag transform. Two
// touchmoves can fire back-to-back inside the same synchronous event
// dispatch (e.g. a fast real swipe, or synthetic touch events fired
// without a yield between them), and React batches their `setDragOffset`
// calls into a single pending update that hasn't committed yet by the
// time `touchend` runs in that same tick -- reading the `dragOffset`
// STATE value directly in `handleTouchEnd` would then see a stale
// (pre-drag) value and wrongly decide the swipe didn't clear the
// threshold. The ref sidesteps that entirely (plain synchronous mutation,
// no batching). Relatedly, `onClose()` mutates an ANCESTOR component's
// state (MobileChromeContext's `closeSheet`) -- it must be called as a
// plain statement in the event handler, never from inside a `setState`
// functional updater (that runs during this component's own render phase
// and trips React's "Cannot update a component while rendering a
// different component" warning).
const dragStartYRef = useRef<number | null>(null);
const dragOffsetRef = useRef(0);
const [dragOffset, setDragOffset] = useState(0);
const handleTouchStart = useCallback((e: React.TouchEvent) => {
if (e.touches.length !== 1) return;
dragStartYRef.current = e.touches[0].clientY;
}, []);
const handleTouchMove = useCallback((e: React.TouchEvent) => {
if (dragStartYRef.current === null) return;
const delta = e.touches[0].clientY - dragStartYRef.current;
// Only follow downward drags -- dragging up shouldn't do anything (the
// sheet is already fully open; there's no "expand further" state).
const next = Math.max(0, delta);
dragOffsetRef.current = next;
setDragOffset(next);
}, []);
const handleTouchEnd = useCallback(() => {
dragStartYRef.current = null;
const finalOffset = dragOffsetRef.current;
dragOffsetRef.current = 0;
setDragOffset(0);
if (finalOffset > SWIPE_DISMISS_THRESHOLD_PX) onClose();
}, [onClose]);
if (!open) return null; if (!open) return null;
return ( return (
@@ -43,16 +136,37 @@ export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title,
onClick={(e) => { onClick={(e) => {
if (e.target === e.currentTarget) onClose(); if (e.target === e.currentTarget) onClose();
}} }}
style={{ ['--keyboard-inset' as any]: `${keyboardInset}px` }}
> >
{/* Deliberately NOT aria-modal: the tab bar stays reachable/operable {/* Deliberately NOT aria-modal: the tab bar stays reachable/operable
while a sheet is open (tapping another tab swaps sheets directly), while a sheet is open (tapping another tab swaps sheets directly),
so the rest of the screen must not be marked inert to assistive so the rest of the screen must not be marked inert to assistive
tech the way a true modal dialog would be. */} tech the way a true modal dialog would be. */}
<div className="mobile-sheet" role="dialog" aria-label={title}> <div
<div className="mobile-sheet-handle-row"> className="mobile-sheet"
role="dialog"
aria-label={title}
style={{
transform: dragOffset ? `translateY(${dragOffset}px)` : undefined,
transition: dragOffset ? 'none' : 'transform 0.2s ease',
}}
>
<div
className="mobile-sheet-handle-row"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onTouchCancel={handleTouchEnd}
>
<span className="mobile-sheet-handle" aria-hidden="true" /> <span className="mobile-sheet-handle" aria-hidden="true" />
</div> </div>
<div className="mobile-sheet-header"> <div
className="mobile-sheet-header"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
onTouchCancel={handleTouchEnd}
>
<span className="mobile-sheet-title">{title}</span> <span className="mobile-sheet-title">{title}</span>
<button <button
type="button" type="button"
@@ -63,7 +177,7 @@ export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title,
<i className="fa fa-times" aria-hidden="true" /> <i className="fa fa-times" aria-hidden="true" />
</button> </button>
</div> </div>
<div className="mobile-sheet-body">{children}</div> <div className="mobile-sheet-body" ref={bodyRef}>{children}</div>
</div> </div>
</div> </div>
); );
@@ -0,0 +1,213 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useEditor } from '@craftjs/core';
import { useNodeActions } from '../../hooks/useNodeActions';
import { useMobileChrome } from '../../state/MobileChromeContext';
/**
* Phase B mobile selection toolbar -- the on-canvas action bar that makes a
* tap-selected node actually EDITABLE by touch (reorder/duplicate/delete/
* select-parent/edit-styles), mirroring the desktop right-click ContextMenu.
* Both share the exact same behavior via `useNodeActions` (item 1).
*
* Mounted ONCE (in `EditorShell`'s mobile branch), reading the current
* selection from `useEditor` directly -- NOT per-node -- and positioned
* bottom-fixed just above the tab bar (simplest, robust; a node-anchored
* floating toolbar would have to constantly reposition as the canvas
* scrolls, and risks being clipped at the viewport edge for a node near the
* top or bottom of a tall page). This is a deliberate design call: see the
* report for the alternative (floating over the node) that was passed over.
*
* Hidden whenever a bottom sheet is open (`activeSheet !== null`) -- the
* sheet supersedes it, and the two must never visually stack.
*
* Delete is a two-tap in-app confirm (tap once -> the button becomes
* "Confirm?" for a few seconds; tap again within that window commits the
* delete; selecting something else cancels it) rather than a native
* `confirm()`, matching the project's no-native-dialogs rule.
*/
const DELETE_CONFIRM_TIMEOUT_MS = 3000;
export const MobileSelectionToolbar: React.FC = () => {
const { activeSheet, openSheet } = useMobileChrome();
const { selectedId } = useEditor((state) => {
const selected = state.events.selected;
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
return { selectedId: id && id !== 'ROOT' ? id : null };
});
// Collector-free -- an always-live reference (same pattern as
// GuidedStyles.tsx/BlocksPanel.tsx), used only for imperative DOM lookups
// below (scroll-into-view), never for anything that needs to react to
// store changes on its own.
const { query } = useEditor();
const nodeActions = useNodeActions(selectedId);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const confirmTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// `useNodeActions` computes canMoveUp/canMoveDown/canDelete synchronously
// from a live (never-cached) Craft.js query -- see that hook's doc comment
// for why it deliberately does NOT hold its own store subscription to force
// a refresh. Moving/duplicating/deleting via THIS toolbar changes the
// selected node's position/siblings WITHOUT changing `selectedId` itself
// (the node stays selected), so nothing else would otherwise trigger a
// re-render of this component to pick up the new boundary flags after,
// say, tapping "Move Up" until the node reaches the top. Bumping a plain
// local tick from these buttons' own click handlers -- an ordinary,
// locally-owned re-render -- covers exactly that, without the broader
// store-wide subscription that was found to trip React's "setState while
// rendering a different component" warning whenever some unrelated
// container mounts (see useNodeActions.ts).
const [, forceRefresh] = useState(0);
const bumpTick = useCallback(() => forceRefresh((n) => n + 1), []);
const clearConfirmTimeout = useCallback(() => {
if (confirmTimeoutRef.current) {
clearTimeout(confirmTimeoutRef.current);
confirmTimeoutRef.current = null;
}
}, []);
// Reset the two-tap delete confirmation whenever the selection changes
// (including being cleared) so a stale "Confirm?" state never lingers onto
// a different node.
const prevSelectedRef = useRef(selectedId);
useEffect(() => {
if (prevSelectedRef.current !== selectedId) {
prevSelectedRef.current = selectedId;
clearConfirmTimeout();
setConfirmingDelete(false);
}
}, [selectedId, clearConfirmTimeout]);
useEffect(() => clearConfirmTimeout, [clearConfirmTimeout]);
// Fast-follow item 3: the Styles bottom sheet covers the bottom ~65dvh of
// the canvas, so a selected node sitting anywhere in that band goes
// invisible the instant the sheet opens -- live style edits then have no
// visible effect until the user closes the sheet to check. Whenever the
// sheet becomes 'styles' (however it got opened -- currently only this
// toolbar's own "Style" button, but this is keyed on the sheet/selection
// state rather than the button tap so it stays correct if another entry
// point is added later) scroll the selected node to the top of the
// canvas's scroll area, into the sliver of screen the sheet leaves clear.
useEffect(() => {
if (activeSheet !== 'styles' || !selectedId) return;
try {
query.node(selectedId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'start' });
} catch {
// Best-effort -- not fatal if the node/DOM isn't found.
}
}, [activeSheet, selectedId, query]);
const handleDeleteTap = useCallback(() => {
if (confirmingDelete) {
clearConfirmTimeout();
setConfirmingDelete(false);
nodeActions.deleteNode();
bumpTick();
return;
}
setConfirmingDelete(true);
clearConfirmTimeout();
confirmTimeoutRef.current = setTimeout(() => setConfirmingDelete(false), DELETE_CONFIRM_TIMEOUT_MS);
}, [confirmingDelete, clearConfirmTimeout, nodeActions, bumpTick]);
const handleEditStyles = useCallback(() => {
openSheet('styles');
}, [openSheet]);
const handleMoveUp = useCallback(() => {
nodeActions.moveUp();
bumpTick();
}, [nodeActions, bumpTick]);
const handleMoveDown = useCallback(() => {
nodeActions.moveDown();
bumpTick();
}, [nodeActions, bumpTick]);
const handleDuplicate = useCallback(() => {
const newId = nodeActions.duplicate();
bumpTick();
if (!newId) return;
// Mirror BlocksPanel's tap-to-add pattern: the new node's real DOM
// element isn't attached yet the instant `duplicate()` returns (Craft.js
// mounts it asynchronously after this handler's synchronous state
// update), so defer two animation frames before reading `.dom` off the
// query, same as `handleTapToAdd` does.
requestAnimationFrame(() => {
requestAnimationFrame(() => {
try {
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
} catch {
// Best-effort scroll -- not fatal if the node/DOM isn't found.
}
});
});
}, [nodeActions, bumpTick, query]);
if (!selectedId || activeSheet !== null) return null;
return (
<div className="mobile-selection-toolbar" role="toolbar" aria-label="Selected element actions">
<button
type="button"
className="mobile-selection-toolbar-btn"
onClick={handleMoveUp}
disabled={!nodeActions.canMoveUp}
aria-label="Move up"
>
<i className="fa fa-arrow-up" aria-hidden="true" />
<span>Up</span>
</button>
<button
type="button"
className="mobile-selection-toolbar-btn"
onClick={handleMoveDown}
disabled={!nodeActions.canMoveDown}
aria-label="Move down"
>
<i className="fa fa-arrow-down" aria-hidden="true" />
<span>Down</span>
</button>
<button
type="button"
className="mobile-selection-toolbar-btn"
onClick={handleDuplicate}
aria-label="Duplicate"
>
<i className="fa fa-clone" aria-hidden="true" />
<span>Copy</span>
</button>
<button
type="button"
className="mobile-selection-toolbar-btn"
onClick={nodeActions.selectParent}
disabled={!nodeActions.canSelectParent}
aria-label="Select parent"
>
<i className="fa fa-level-up" aria-hidden="true" />
<span>Parent</span>
</button>
<button
type="button"
className="mobile-selection-toolbar-btn"
onClick={handleEditStyles}
aria-label="Edit styles"
>
<i className="fa fa-paint-brush" aria-hidden="true" />
<span>Style</span>
</button>
<button
type="button"
className={`mobile-selection-toolbar-btn danger${confirmingDelete ? ' confirming' : ''}`}
onClick={handleDeleteTap}
disabled={!nodeActions.canDelete}
aria-label={confirmingDelete ? 'Tap again to confirm delete' : 'Delete'}
>
<i className="fa fa-trash" aria-hidden="true" />
<span>{confirmingDelete ? 'Confirm?' : 'Delete'}</span>
</button>
</div>
);
};
@@ -0,0 +1,282 @@
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
/* NavStylePanel (via useNodeProp/LinkPicker in this file) needs useEditor
from @craftjs/core and usePages from PageContext. Mock both following the
DOM-harness pattern used across this repo's other *StylePanel tests (no
@testing-library/react here) -- PageContext itself is Wave-2's territory,
this package only READS pages via usePages(), so mocking it is the
correct boundary for these tests. */
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
updater(lastProps);
});
let lastProps: any;
vi.mock('@craftjs/core', () => ({
useEditor: () => ({ actions: { setProp: setPropSpy } }),
}));
let mockPages: { id: string; name: string; slug: string; craftState: string | null }[] = [];
vi.mock('../../../state/PageContext', () => ({
usePages: () => ({ pages: mockPages }),
}));
vi.mock('../../../ui/AssetPicker', () => ({
AssetPicker: () => null,
}));
import { NavStylePanel, LinkPicker, pageHref } from './NavStylePanel';
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);
});
}
function rerender(ui: React.ReactElement) {
act(() => { root.render(ui); });
}
function unmount() {
act(() => { root.unmount(); });
container.remove();
}
function setValue(el: HTMLInputElement | HTMLSelectElement, value: string) {
const proto = el instanceof HTMLSelectElement ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;
act(() => {
setter.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
});
}
function click(el: Element | null) {
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
beforeEach(() => {
setPropSpy.mockClear();
mockPages = [
{ id: 'home', name: 'Home', slug: 'index', craftState: null },
{ id: 'about', name: 'About', slug: 'about', craftState: null },
];
});
afterEach(() => {
if (container) unmount();
});
describe('pageHref (landing page is always "/")', () => {
test('index 0 (landing page) -> "/"', () => {
expect(pageHref(mockPages[0], 0)).toBe('/');
});
test('any other page -> "/{slug}"', () => {
expect(pageHref(mockPages[1], 1)).toBe('/about');
});
});
describe('LinkPicker (F1: link-to-page picker + manual URL/anchor/tel/mailto)', () => {
test('a value matching a page href starts in "Page" mode and lists every page', () => {
render(<LinkPicker value="/about" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('page');
const optionText = Array.from(container.querySelectorAll('option')).map((o) => o.textContent);
expect(optionText).toContain('Home');
expect(optionText).toContain('About');
});
test('picking a different page from the page dropdown emits that page\'s href', () => {
const onChange = vi.fn();
render(<LinkPicker value="/about" onChange={onChange} />);
const [, pageSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
setValue(pageSelect, '/');
expect(onChange).toHaveBeenCalledWith('/');
});
test('a "#section" value starts in Anchor mode', () => {
render(<LinkPicker value="#pricing" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('anchor');
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('#pricing');
});
test('switching mode to Anchor seeds a bare "#"', () => {
const onChange = vi.fn();
render(<LinkPicker value="/about" onChange={onChange} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
setValue(modeSelect, 'anchor');
expect(onChange).toHaveBeenCalledWith('#');
});
test('mailto: helper strips the scheme for editing and re-adds it on change', () => {
const onChange = vi.fn();
render(<LinkPicker value="mailto:foo@example.com" onChange={onChange} />);
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('foo@example.com');
setValue(input, 'bar@example.com');
expect(onChange).toHaveBeenCalledWith('mailto:bar@example.com');
});
test('tel: helper strips the scheme for editing and re-adds it on change', () => {
const onChange = vi.fn();
render(<LinkPicker value="tel:5551234567" onChange={onChange} />);
const input = container.querySelector('input[type="text"]') as HTMLInputElement;
expect(input.value).toBe('5551234567');
setValue(input, '5559876543');
expect(onChange).toHaveBeenCalledWith('tel:5559876543');
});
test('a plain https:// URL falls back to Custom URL mode', () => {
render(<LinkPicker value="https://example.com" onChange={vi.fn()} />);
const [modeSelect] = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
expect(modeSelect.value).toBe('url');
});
});
describe('NavStylePanel Links section: href set via LinkPicker (F1 wired into the panel)', () => {
test('choosing a page for a Navbar link writes that page\'s href onto the link', () => {
lastProps = {
links: [{ text: 'Home', href: '/old-home' }],
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const selects = Array.from(container.querySelectorAll('select')) as HTMLSelectElement[];
// First select for the one link item is its LinkPicker mode select (the
// href starts as a Custom URL, so it opens on "url" mode); switch it to
// "page" then pick the About page from the resulting page dropdown.
const modeSelect = selects[0];
setValue(modeSelect, 'page');
expect(setPropSpy).toHaveBeenCalled();
expect(lastProps.links[0].href).toBe('/'); // defaults to the first page
// The mock setProp mutates `lastProps` in place rather than triggering a
// real Craft.js state update, so force a re-render (passing the same,
// now-mutated, object) to get the LinkPicker to reflect its new "page"
// mode and render the page <select>.
rerender(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const pageSelect = Array.from(container.querySelectorAll('select'))[1] as HTMLSelectElement;
setValue(pageSelect, '/about');
expect(lastProps.links[0].href).toBe('/about');
});
test('toggling the Download checkbox for a link sets download:true', () => {
lastProps = { links: [{ text: 'Brochure', href: '/brochure.pdf' }] };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const checkbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement;
act(() => { checkbox.click(); });
expect(lastProps.links[0].download).toBe(true);
});
});
describe('NavStylePanel: "Sync links with Pages" (F2, regression vs legacy builder)', () => {
test('populates links from the mocked pages list and preserves the CTA link', () => {
lastProps = {
links: [
{ text: 'Old Home', href: '/old' },
{ text: 'Old About', href: '/old-about' },
{ text: 'Get Started', href: '#signup', isCta: true },
],
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'))!;
expect(syncBtn).toBeTruthy();
click(syncBtn);
expect(lastProps.links).toEqual([
{ text: 'Home', href: '/' },
{ text: 'About', href: '/about' },
{ text: 'Get Started', href: '#signup', isCta: true },
]);
});
test('with no CTA link, sync just replaces links 1:1 with the pages list', () => {
lastProps = { links: [{ text: 'Stale', href: '/stale' }] };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'))!;
click(syncBtn);
expect(lastProps.links).toEqual([
{ text: 'Home', href: '/' },
{ text: 'About', href: '/about' },
]);
});
test('the Links section (and its Sync button) is not shown for Footer (no `links` prop)', () => {
lastProps = { text: '© 2026' };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
const syncBtn = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes('Sync links with Pages'));
expect(syncBtn).toBeUndefined();
});
});
/** The Spacing/Border & Effects/Animation/Visibility CollapsibleSections all
* default closed (defaultOpen={false}, matching the pre-existing "Spacing"
* section's convention) -- open one by clicking its header button before
* asserting on / interacting with its contents. */
function openSection(title: string) {
const header = Array.from(container.querySelectorAll('button'))
.find((b) => b.textContent?.includes(title))!;
click(header);
}
describe('NavStylePanel: box-model + animation + visibility controls always present', () => {
test('Spacing (Margin/Padding), Border & Effects, Animation, and Visibility sections render for a Navbar', () => {
lastProps = {
backgroundColor: '#ffffff',
style: {},
animation: 'none',
animationDelay: '0',
hideOnDesktop: false,
hideOnTablet: false,
hideOnMobile: false,
};
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Spacing');
openSection('Border & Effects');
openSection('Animation');
openSection('Visibility');
expect(container.querySelector('[data-testid="spacing-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="border-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="animation-control"]')).toBeTruthy();
expect(container.querySelector('[data-testid="visibility-control"]')).toBeTruthy();
});
test('checking "Hide on Mobile" writes hideOnMobile:true via setProp', () => {
lastProps = { hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Visibility');
const checkbox = container.querySelector('[data-testid="visibility-hideOnMobile"]') as HTMLInputElement;
act(() => {
checkbox.click();
});
expect(lastProps.hideOnMobile).toBe(true);
});
test('picking an entrance animation writes animation via setProp', () => {
lastProps = { animation: 'none', animationDelay: '0' };
render(<NavStylePanel selectedId="node1" nodeProps={lastProps} />);
openSection('Animation');
const fadeInBtn = Array.from(container.querySelectorAll('[data-testid="animation-control"] button'))
.find((b) => b.textContent === 'Fade In')!;
click(fadeInBtn);
expect(lastProps.animation).toBe('fade-in');
});
});
+230 -15
View File
@@ -2,6 +2,7 @@ import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core'; import { useEditor } from '@craftjs/core';
import { import {
SPACING_PRESETS, SPACING_PRESETS,
SHADOW_PRESETS,
} from '../../../constants/presets'; } from '../../../constants/presets';
import { import {
StylePanelProps, StylePanelProps,
@@ -16,13 +17,145 @@ import {
smallInputStyle, smallInputStyle,
sectionGap, sectionGap,
useNodeProp, useNodeProp,
SpacingControl,
BorderControl,
BorderValue,
buildBorderShorthand,
AnimationControl,
VisibilityControl,
} from './shared'; } from './shared';
import { AssetPicker } from '../../../ui/AssetPicker'; import { AssetPicker } from '../../../ui/AssetPicker';
import { usePages } from '../../../state/PageContext';
import { PageData } from '../../../types';
/* ---------- NAV / MENU / LOGO ---------- */ /* ---------- Link-to-page helpers (F1/F2: link picker + Sync with Pages) ----------
Mirrors the export convention used elsewhere: the first page is always the
landing page and publishes to '/', every other page publishes to '/{slug}'.
See PageContext.tsx's uniqueSlug/slugify and the landing-page-lock comment
in renamePage() for why index 0 is special-cased this way. */
export function pageHref(page: PageData, index: number): string {
return index === 0 ? '/' : `/${page.slug}`;
}
type LinkMode = 'page' | 'url' | 'anchor' | 'tel' | 'mailto';
function detectLinkMode(value: string, pageHrefs: string[]): LinkMode {
const v = value || '';
if (pageHrefs.includes(v)) return 'page';
if (v.startsWith('#')) return 'anchor';
if (v.startsWith('tel:')) return 'tel';
if (v.startsWith('mailto:')) return 'mailto';
return 'url';
}
/* ---------- LinkPicker ----------
Reused for every link-href field in this panel (standalone Logo's href,
Navbar's logoUrl, and each Navbar/Menu link item's href): a dropdown of
the site's PAGES (read-only via usePages() -- PageContext itself is
Wave-2's territory) plus manual URL / #anchor / tel: / mailto: entry.
safeUrl (in toHtml) already allows tel:/mailto: schemes, so no export-side
change is needed for those. */
interface LinkPickerProps {
value: string;
onChange: (value: string) => void;
}
export const LinkPicker: React.FC<LinkPickerProps> = ({ value, onChange }) => {
const { pages } = usePages();
const pageOptions = pages.map((p, i) => ({ id: p.id, name: p.name, href: pageHref(p, i) }));
const mode = detectLinkMode(value || '', pageOptions.map((p) => p.href));
const switchMode = (next: LinkMode) => {
if (next === mode) return;
if (next === 'page') onChange(pageOptions[0]?.href || '/');
else if (next === 'anchor') onChange('#');
else if (next === 'tel') onChange('tel:');
else if (next === 'mailto') onChange('mailto:');
else onChange('');
};
return (
<div style={sectionGap} data-testid="link-picker">
<label style={labelStyle}>Link</label>
<select
value={mode}
onChange={(e) => switchMode(e.target.value as LinkMode)}
style={{ ...inputStyle, marginBottom: 4, cursor: 'pointer' }}
>
<option value="page">Page</option>
<option value="url">Custom URL</option>
<option value="anchor">Anchor (#section)</option>
<option value="tel">Phone (tel:)</option>
<option value="mailto">Email (mailto:)</option>
</select>
{mode === 'page' && (
pageOptions.length > 0 ? (
<select value={value} onChange={(e) => onChange(e.target.value)} style={inputStyle}>
{pageOptions.map((p) => (
<option key={p.id} value={p.href}>{p.name}</option>
))}
</select>
) : (
<div style={{ fontSize: 11, color: '#71717a' }}>No pages yet</div>
)
)}
{mode === 'anchor' && (
<input
type="text"
value={value || ''}
onChange={(e) => onChange(e.target.value.startsWith('#') ? e.target.value : `#${e.target.value}`)}
placeholder="#section-id"
style={inputStyle}
/>
)}
{mode === 'tel' && (
<input
type="text"
value={(value || '').replace(/^tel:/, '')}
onChange={(e) => onChange(`tel:${e.target.value}`)}
placeholder="+15551234567"
style={inputStyle}
/>
)}
{mode === 'mailto' && (
<input
type="text"
value={(value || '').replace(/^mailto:/, '')}
onChange={(e) => onChange(`mailto:${e.target.value}`)}
placeholder="name@example.com"
style={inputStyle}
/>
)}
{mode === 'url' && (
<input
type="text"
value={value || ''}
onChange={(e) => onChange(e.target.value)}
placeholder="https://example.com or /page"
style={inputStyle}
/>
)}
</div>
);
};
/* Parses a `border` shorthand ("2px solid #hex" / "none") back into the
{ width, style, color } shape BorderControl edits. */
function parseBorderShorthand(v: string | undefined): BorderValue {
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
const m = v.trim().match(/^(\S+)\s+(\S+)\s+(.+)$/);
if (!m) return { width: '', style: 'none', color: '#000000' };
return { width: m[1], style: m[2], color: m[3] };
}
function capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
/* ---------- NAV / MENU / LOGO / FOOTER ---------- */
export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => { export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor(); const { actions } = useEditor();
const { setProp, setPropStyle } = useNodeProp(selectedId); const { setProp, setPropStyle } = useNodeProp(selectedId);
const { pages } = usePages();
const links: any[] = nodeProps.links || []; const links: any[] = nodeProps.links || [];
@@ -48,6 +181,20 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
}); });
}, [actions, selectedId]); }, [actions, selectedId]);
/* F2: (re)populate the links array from the current pages list --
label = page name, href = '/' for the landing page else '/{slug}'.
Any existing CTA link (isCta: true) is preserved (appended after the
freshly-generated page links) rather than being wiped, matching the
legacy GrapesJS builder's "Sync with Pages" behavior. */
const syncWithPages = useCallback(() => {
actions.setProp(selectedId, (props: any) => {
const existing: any[] = props.links || [];
const ctaLinks = existing.filter((l) => l.isCta);
const pageLinks = pages.map((p, i) => ({ text: p.name, href: pageHref(p, i) }));
props.links = [...pageLinks, ...ctaLinks];
});
}, [actions, selectedId, pages]);
/* Detect standalone Logo vs Navbar/Menu */ /* Detect standalone Logo vs Navbar/Menu */
const isStandaloneLogo = nodeProps.type !== undefined && (nodeProps.type === 'text' || nodeProps.type === 'image') && nodeProps.logoText === undefined; const isStandaloneLogo = nodeProps.type !== undefined && (nodeProps.type === 'text' || nodeProps.type === 'image') && nodeProps.logoText === undefined;
@@ -66,6 +213,15 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
); );
const GAP_PRESETS = ['8px', '16px', '24px', '32px', '40px'].map((g) => ({ label: g, value: g })); const GAP_PRESETS = ['8px', '16px', '24px', '32px', '40px'].map((g) => ({ label: g, value: g }));
/* Box-model / animation / visibility values, read off `style` (margin,
padding, border, boxShadow, opacity) or top-level props (animation,
hideOn*). This panel is only ever mounted for the 4 owned components
(Navbar/Menu/Logo/Footer), which all now carry these props (see each
component's .craft.props), so -- unlike the Links/Colors sections above,
which are shared across a genuinely disparate prop schema -- these
sections render unconditionally rather than gating on presence. */
const style = nodeProps.style || {};
return ( return (
<> <>
{/* Standalone Logo component settings */} {/* Standalone Logo component settings */}
@@ -124,10 +280,11 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</div> </div>
</> </>
)} )}
<div style={sectionGap}> <LinkPicker value={nodeProps.href || '/'} onChange={(v) => setProp('href', v)} />
<label style={labelStyle}>Link URL</label> <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer', marginTop: -8, marginBottom: 12 }}>
<input type="text" value={nodeProps.href || '/'} onChange={(e) => setProp('href', e.target.value)} placeholder="/" style={inputStyle} /> <input type="checkbox" checked={!!nodeProps.download} onChange={(e) => setProp('download', e.target.checked)} />
</div> Download (link points at a file)
</label>
</CollapsibleSection> </CollapsibleSection>
)} )}
@@ -145,17 +302,22 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</div> </div>
)} )}
{nodeProps.logoUrl !== undefined && ( {nodeProps.logoUrl !== undefined && (
<div style={sectionGap}> <LinkPicker value={nodeProps.logoUrl || '/'} onChange={(v) => setProp('logoUrl', v)} />
<label style={labelStyle}>Logo Link URL</label>
<input type="text" value={nodeProps.logoUrl || ''} onChange={(e) => setProp('logoUrl', e.target.value)} placeholder="/" style={inputStyle} />
</div>
)} )}
</CollapsibleSection> </CollapsibleSection>
)} )}
{/* Links (not shown for standalone Logo) */} {/* Links (not shown for standalone Logo, or for components -- like
{!isStandaloneLogo && ( Footer -- that don't carry a `links` array at all). */}
{!isStandaloneLogo && nodeProps.links !== undefined && (
<CollapsibleSection title="Links"> <CollapsibleSection title="Links">
<button
onClick={syncWithPages}
title="Replace these links with one per page (preserves any CTA link)"
style={{ marginBottom: 8, width: '100%', padding: '6px', fontSize: 11, background: 'rgba(59,130,246,0.12)', color: '#93c5fd', border: '1px solid rgba(59,130,246,0.4)', borderRadius: 4, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}
>
<i className="fa fa-refresh" /> Sync links with Pages
</button>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{links.map((link, i) => ( {links.map((link, i) => (
<div key={i} style={{ background: '#1e1e22', borderRadius: 6, padding: 6, display: 'flex', flexDirection: 'column', gap: 3 }}> <div key={i} style={{ background: '#1e1e22', borderRadius: 6, padding: 6, display: 'flex', flexDirection: 'column', gap: 3 }}>
@@ -165,7 +327,11 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
<i className="fa fa-times" /> <i className="fa fa-times" />
</button> </button>
</div> </div>
<input type="text" value={link.href || ''} onChange={(e) => updateLink(i, 'href', e.target.value)} placeholder="URL" style={{ ...smallInputStyle, color: '#71717a' }} /> <LinkPicker value={link.href || ''} onChange={(v) => updateLink(i, 'href', v)} />
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10, color: '#a1a1aa', cursor: 'pointer', marginTop: -6 }}>
<input type="checkbox" checked={!!link.download} onChange={(e) => updateLink(i, 'download', e.target.checked)} />
Download (points at a file)
</label>
</div> </div>
))} ))}
</div> </div>
@@ -234,12 +400,61 @@ export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps
</CollapsibleSection> </CollapsibleSection>
)} )}
{/* Style overrides */} {/* Box model: margin + padding (per-side, via style.*). The old
single "Padding" preset row is folded into the Padding SpacingControl
below (still writes to style.padding when linked, matching the
previous behavior exactly). */}
<CollapsibleSection title="Spacing" defaultOpen={false}> <CollapsibleSection title="Spacing" defaultOpen={false}>
<SpacingControl
label="Margin"
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
onChange={(side, v) => setPropStyle(`margin${capitalize(side)}`, v)}
/>
<SpacingControl
label="Padding"
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
onChange={(side, v) => setPropStyle(`padding${capitalize(side)}`, v)}
presets={SPACING_PRESETS}
/>
</CollapsibleSection>
{/* Border & Effects: border, box-shadow, opacity */}
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
<BorderControl
value={parseBorderShorthand(style.border)}
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
/>
<div className="guided-section"> <div className="guided-section">
<SectionLabel>Padding</SectionLabel> <SectionLabel>Box Shadow</SectionLabel>
<PresetButtonGrid presets={SPACING_PRESETS} activeValue={(nodeProps.style || {}).padding as string} onSelect={(v) => setPropStyle('padding', v)} /> <PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow || 'none'} onSelect={(v) => setPropStyle('boxShadow', v)} />
</div> </div>
<div style={sectionGap}>
<label style={labelStyle}>Opacity</label>
<input
type="range"
min={0}
max={100}
value={style.opacity !== undefined ? Math.round(parseFloat(style.opacity) * 100) : 100}
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
style={{ width: '100%' }}
/>
</div>
</CollapsibleSection>
{/* Entrance animation */}
<CollapsibleSection title="Animation" defaultOpen={false}>
<AnimationControl
value={{ animation: nodeProps.animation, animationDelay: nodeProps.animationDelay }}
onChange={(v) => actions.setProp(selectedId, (p: any) => { p.animation = v.animation; p.animationDelay = v.animationDelay; })}
/>
</CollapsibleSection>
{/* Responsive visibility */}
<CollapsibleSection title="Visibility" defaultOpen={false}>
<VisibilityControl
value={{ hideOnDesktop: nodeProps.hideOnDesktop, hideOnTablet: nodeProps.hideOnTablet, hideOnMobile: nodeProps.hideOnMobile }}
onChange={(v) => actions.setProp(selectedId, (p: any) => { p.hideOnDesktop = v.hideOnDesktop; p.hideOnTablet = v.hideOnTablet; p.hideOnMobile = v.hideOnMobile; })}
/>
</CollapsibleSection> </CollapsibleSection>
</> </>
); );
@@ -0,0 +1,340 @@
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';
import {
NumericUnitInput,
parseCssLength,
SizeControl,
AspectRatioControl,
parseAspectRatioInput,
FocalPointGrid,
FOCAL_POINTS,
SpacingControl,
BorderControl,
buildBorderShorthand,
AnimationControl,
ANIMATIONS,
VisibilityControl,
} from './shared';
/* Same DOM-harness pattern as AssetPicker.test.tsx / ImageBlock.render.test.tsx
(no @testing-library/react in this repo). */
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);
});
}
function unmount() {
act(() => { root.unmount(); });
container.remove();
}
function click(el: Element | null) {
if (!el) throw new Error('element not found');
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
function setValue(input: HTMLInputElement | HTMLSelectElement, value: string) {
const proto = input instanceof HTMLSelectElement ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;
setter.call(input, value);
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
function blur(el: Element) {
act(() => { el.dispatchEvent(new FocusEvent('blur', { bubbles: true })); el.dispatchEvent(new FocusEvent('focusout', { bubbles: true })); });
}
function q<T extends Element = Element>(testId: string): T | null {
return container.querySelector(`[data-testid="${testId}"]`);
}
/* ---------- NumericUnitInput / parseCssLength ---------- */
describe('parseCssLength', () => {
test('parses "16px" into number 16 + unit px', () => {
expect(parseCssLength('16px')).toEqual({ num: '16', unit: 'px' });
});
test('parses "50%" into number 50 + unit %', () => {
expect(parseCssLength('50%', ['px', '%'])).toEqual({ num: '50', unit: '%' });
});
test('treats "auto" and "" as empty', () => {
expect(parseCssLength('auto')).toEqual({ num: '', unit: 'px' });
expect(parseCssLength('')).toEqual({ num: '', unit: 'px' });
expect(parseCssLength(undefined)).toEqual({ num: '', unit: 'px' });
});
test('falls back to the first configured unit for an unrecognized unit', () => {
expect(parseCssLength('16vh', ['px', '%'])).toEqual({ num: '16', unit: 'px' });
});
});
describe('NumericUnitInput', () => {
test('renders the parsed number and unit from a "16px" value', () => {
render(<NumericUnitInput value="16px" onChange={vi.fn()} />);
expect(q<HTMLInputElement>('numeric-unit-number')!.value).toBe('16');
expect(q<HTMLSelectElement>('numeric-unit-unit')!.value).toBe('px');
unmount();
});
test('changing the number emits the recombined string', () => {
const onChange = vi.fn();
render(<NumericUnitInput value="16px" onChange={onChange} />);
setValue(q<HTMLInputElement>('numeric-unit-number')!, '32');
expect(onChange).toHaveBeenCalledWith('32px');
unmount();
});
test('changing the unit re-emits with the current number', () => {
const onChange = vi.fn();
render(<NumericUnitInput value="16px" onChange={onChange} />);
setValue(q<HTMLSelectElement>('numeric-unit-unit')!, '%');
expect(onChange).toHaveBeenCalledWith('16%');
unmount();
});
test('clearing the number emits empty string, not "0px"', () => {
const onChange = vi.fn();
render(<NumericUnitInput value="16px" onChange={onChange} />);
setValue(q<HTMLInputElement>('numeric-unit-number')!, '');
expect(onChange).toHaveBeenCalledWith('');
unmount();
});
test('omits the unit <select> when only one unit is configured', () => {
render(<NumericUnitInput value="1px" onChange={vi.fn()} units={['px']} />);
expect(q('numeric-unit-unit')).toBeNull();
unmount();
});
});
/* ---------- SizeControl ---------- */
describe('SizeControl', () => {
test('clicking a preset button emits its value', () => {
const onChange = vi.fn();
render(<SizeControl label="Width" value="" onChange={onChange} />);
const buttons = container.querySelectorAll('[data-testid="size-control"] .preset-btn');
const hundred = Array.from(buttons).find((b) => b.textContent === '100%')!;
click(hundred);
expect(onChange).toHaveBeenCalledWith('100%');
unmount();
});
test('custom numeric input emits a non-preset value', () => {
const onChange = vi.fn();
render(<SizeControl label="Width" value="" onChange={onChange} />);
setValue(q<HTMLInputElement>('size-control-custom-number')!, '400');
expect(onChange).toHaveBeenCalledWith('400px');
unmount();
});
});
/* ---------- AspectRatioControl / parseAspectRatioInput ---------- */
describe('parseAspectRatioInput', () => {
test('parses "16:9" into "16 / 9"', () => {
expect(parseAspectRatioInput('16:9')).toBe('16 / 9');
});
test('accepts "16/9" and "16x9" separators too', () => {
expect(parseAspectRatioInput('16/9')).toBe('16 / 9');
expect(parseAspectRatioInput('16x9')).toBe('16 / 9');
});
test('returns empty string for unparseable input', () => {
expect(parseAspectRatioInput('not-a-ratio')).toBe('');
});
});
describe('AspectRatioControl', () => {
test('clicking the 16:9 preset emits "16 / 9"', () => {
const onChange = vi.fn();
render(<AspectRatioControl value="" onChange={onChange} />);
const buttons = container.querySelectorAll('[data-testid="aspect-ratio-control"] .preset-btn');
const btn = Array.from(buttons).find((b) => b.textContent === '16:9')!;
click(btn);
expect(onChange).toHaveBeenCalledWith('16 / 9');
unmount();
});
test('clicking Original emits empty string', () => {
const onChange = vi.fn();
render(<AspectRatioControl value="1 / 1" onChange={onChange} />);
const buttons = container.querySelectorAll('[data-testid="aspect-ratio-control"] .preset-btn');
const btn = Array.from(buttons).find((b) => b.textContent === 'Original')!;
click(btn);
expect(onChange).toHaveBeenCalledWith('');
unmount();
});
test('typing a custom "16:9" and blurring emits "16 / 9"', () => {
const onChange = vi.fn();
render(<AspectRatioControl value="" onChange={onChange} />);
const input = q<HTMLInputElement>('aspect-ratio-custom-input')!;
setValue(input, '16:9');
blur(input);
expect(onChange).toHaveBeenCalledWith('16 / 9');
unmount();
});
});
/* ---------- FocalPointGrid ---------- */
describe('FocalPointGrid', () => {
test('has 9 cells matching FOCAL_POINTS', () => {
render(<FocalPointGrid value="center" onChange={vi.fn()} />);
const cells = container.querySelectorAll('[data-testid="focal-point-grid"] button');
expect(cells.length).toBe(9);
expect(FOCAL_POINTS.length).toBe(9);
unmount();
});
test('clicking a cell emits its object-position value', () => {
const onChange = vi.fn();
render(<FocalPointGrid value="center" onChange={onChange} />);
click(q('focal-point-left-top'));
expect(onChange).toHaveBeenCalledWith('left top');
unmount();
});
test('the active cell is visually highlighted (distinct background)', () => {
render(<FocalPointGrid value="right bottom" onChange={vi.fn()} />);
const active = q<HTMLButtonElement>('focal-point-right-bottom')!;
const inactive = q<HTMLButtonElement>('focal-point-center')!;
expect(active.style.background).not.toBe(inactive.style.background);
unmount();
});
test('defaults the highlight to center when value is empty', () => {
render(<FocalPointGrid value="" onChange={vi.fn()} />);
const center = q<HTMLButtonElement>('focal-point-center')!;
const other = q<HTMLButtonElement>('focal-point-left-top')!;
expect(center.style.background).not.toBe(other.style.background);
unmount();
});
});
/* ---------- SpacingControl ---------- */
describe('SpacingControl', () => {
test('linked mode: editing the shared field emits onChange for all 4 sides with the same value', () => {
const onChange = vi.fn();
render(<SpacingControl label="Margin" value={{}} onChange={onChange} />);
setValue(q<HTMLInputElement>('spacing-linked-number')!, '16');
expect(onChange).toHaveBeenCalledWith('top', '16px');
expect(onChange).toHaveBeenCalledWith('right', '16px');
expect(onChange).toHaveBeenCalledWith('bottom', '16px');
expect(onChange).toHaveBeenCalledWith('left', '16px');
expect(onChange).toHaveBeenCalledTimes(4);
unmount();
});
test('a preset fills all sides with the preset value', () => {
const onChange = vi.fn();
render(<SpacingControl label="Padding" value={{}} onChange={onChange} />);
const buttons = container.querySelectorAll('[data-testid="spacing-control"] .preset-btn');
const medium = Array.from(buttons).find((b) => b.textContent === 'M')!;
click(medium);
expect(onChange).toHaveBeenCalledWith('top', '16px');
expect(onChange).toHaveBeenCalledWith('left', '16px');
expect(onChange).toHaveBeenCalledTimes(4);
unmount();
});
test('unlinking lets each side emit independently', () => {
const onChange = vi.fn();
render(<SpacingControl label="Margin" value={{ top: '4px', right: '4px', bottom: '4px', left: '4px' }} onChange={onChange} />);
click(q('spacing-link-toggle'));
setValue(q<HTMLInputElement>('spacing-top-number')!, '20');
expect(onChange).toHaveBeenCalledWith('top', '20px');
expect(onChange).toHaveBeenCalledTimes(1);
unmount();
});
});
/* ---------- BorderControl ---------- */
describe('BorderControl', () => {
test('changing width/style/color merges into the full BorderValue object', () => {
const onChange = vi.fn();
const value = { width: '1px', style: 'solid', color: '#000000' };
render(<BorderControl value={value} onChange={onChange} />);
setValue(q<HTMLSelectElement>('border-style-select')!, 'dashed');
expect(onChange).toHaveBeenCalledWith({ width: '1px', style: 'dashed', color: '#000000' });
unmount();
});
test('buildBorderShorthand builds a CSS border shorthand', () => {
expect(buildBorderShorthand({ width: '2px', style: 'solid', color: '#3b82f6' })).toBe('2px solid #3b82f6');
});
test('buildBorderShorthand returns "none" when style is none or width is empty', () => {
expect(buildBorderShorthand({ width: '2px', style: 'none', color: '#000' })).toBe('none');
expect(buildBorderShorthand({ width: '', style: 'solid', color: '#000' })).toBe('none');
});
});
/* ---------- AnimationControl ---------- */
describe('AnimationControl', () => {
test('ANIMATIONS matches the exact data-animation values html-export.ts supports', () => {
expect(ANIMATIONS.map((a) => a.value)).toEqual([
'none', 'fade-in', 'slide-up', 'slide-left', 'slide-right', 'zoom-in', 'bounce',
]);
});
test('selecting an animation emits { animation, animationDelay }', () => {
const onChange = vi.fn();
render(<AnimationControl value={{ animation: 'none' }} onChange={onChange} />);
const buttons = container.querySelectorAll('[data-testid="animation-control"] .preset-btn');
const fadeIn = Array.from(buttons).find((b) => b.textContent === 'Fade In')!;
click(fadeIn);
expect(onChange).toHaveBeenCalledWith({ animation: 'fade-in', animationDelay: '0' });
unmount();
});
test('the delay input is hidden when animation is "none" and shown otherwise', () => {
render(<AnimationControl value={{ animation: 'none' }} onChange={vi.fn()} />);
expect(q('animation-delay-input')).toBeNull();
unmount();
render(<AnimationControl value={{ animation: 'bounce', animationDelay: '0.5' }} onChange={vi.fn()} />);
expect(q<HTMLInputElement>('animation-delay-input')!.value).toBe('0.5');
unmount();
});
test('changing the delay emits the current animation with the new delay', () => {
const onChange = vi.fn();
render(<AnimationControl value={{ animation: 'zoom-in', animationDelay: '0' }} onChange={onChange} />);
setValue(q<HTMLInputElement>('animation-delay-input')!, '0.3');
expect(onChange).toHaveBeenCalledWith({ animation: 'zoom-in', animationDelay: '0.3' });
unmount();
});
});
/* ---------- VisibilityControl ---------- */
describe('VisibilityControl', () => {
test('emits the exact hideOnDesktop/hideOnTablet/hideOnMobile prop names', () => {
const onChange = vi.fn();
render(<VisibilityControl value={{}} onChange={onChange} />);
click(q('visibility-hideOnDesktop'));
expect(onChange).toHaveBeenCalledWith({ hideOnDesktop: true });
unmount();
});
test('toggling reflects existing true values back to false', () => {
const onChange = vi.fn();
render(<VisibilityControl value={{ hideOnMobile: true }} onChange={onChange} />);
click(q('visibility-hideOnMobile'));
expect(onChange).toHaveBeenCalledWith({ hideOnMobile: false });
unmount();
});
test('checkboxes reflect the initial value', () => {
render(<VisibilityControl value={{ hideOnTablet: true }} onChange={vi.fn()} />);
expect(q<HTMLInputElement>('visibility-hideOnDesktop')!.checked).toBe(false);
expect(q<HTMLInputElement>('visibility-hideOnTablet')!.checked).toBe(true);
expect(q<HTMLInputElement>('visibility-hideOnMobile')!.checked).toBe(false);
unmount();
});
});
+380
View File
@@ -2,6 +2,10 @@ import React, { useState, useCallback, CSSProperties } from 'react';
import { useEditor } from '@craftjs/core'; import { useEditor } from '@craftjs/core';
import { import {
GRADIENTS, GRADIENTS,
SIZE_PRESETS,
ASPECT_RATIOS,
SPACING_PRESETS,
BORDER_STYLES,
} from '../../../constants/presets'; } from '../../../constants/presets';
import { uploadAsset } from '../../../utils/assets'; import { uploadAsset } from '../../../utils/assets';
@@ -372,3 +376,379 @@ export const ArrayPropEditor: React.FC<ArrayPropEditorProps> = ({ selectedId, pr
</div> </div>
); );
}; };
/* =========================================================================
ENH-Foundation: reusable StylePanel controls
---------------------------------------------------------------------
Presentational (value + onChange) controls shared by upcoming feature
panels (size/spacing/border/typography/animation/visibility rollout).
Nothing below is wired into any feature panel yet -- that's the job of
the downstream feature branches. Each control's onChange API is
documented on its props interface; see
.superpowers/sdd/task-enh-foundation-report.md for the consolidated list.
========================================================================= */
/* ---------- NumericUnitInput ----------
A number field + unit dropdown that parses/holds a CSS length string
("16px", "50%", "auto", "") and calls onChange(nextString).
- Clearing the number field emits '' (not '0px') -- lets the consumer
treat '' as "unset/inherit" instead of forcing a 0 value.
- value === 'auto' or '' both display as a blank number field (with the
`placeholder` -- default "auto" -- shown as a hint).
- Changing the unit re-emits with the current number and the new unit;
if the number is blank, changing the unit is a no-op (still emits '').
- `units` is configurable (default ['px','%']); the unit <select> is
omitted entirely when only one unit is passed. */
export function parseCssLength(value: string | undefined, units: string[] = ['px', '%']): { num: string; unit: string } {
if (!value || value === 'auto') return { num: '', unit: units[0] };
const m = String(value).trim().match(/^(-?\d*\.?\d+)\s*([a-zA-Z%]*)$/);
if (!m) return { num: '', unit: units[0] };
const unit = m[2] || units[0];
return { num: m[1], unit: units.includes(unit) ? unit : units[0] };
}
export interface NumericUnitInputProps {
/** CSS length string, e.g. "16px" / "50%" / "auto" / "". */
value: string;
/** Called with the recombined string, e.g. "16px". Called with '' when the
* number field is cleared. */
onChange: (value: string) => void;
/** Allowed unit list; default ['px', '%']. Unit <select> is hidden when
* this has length 1. */
units?: string[];
min?: number;
max?: number;
step?: number;
placeholder?: string;
/** Base for the data-testid attrs (`${testId}`, `${testId}-number`,
* `${testId}-unit`); default 'numeric-unit'. */
testId?: string;
}
export const NumericUnitInput: React.FC<NumericUnitInputProps> = ({
value, onChange, units = ['px', '%'], min, max, step, placeholder = 'auto', testId = 'numeric-unit',
}) => {
const { num, unit } = parseCssLength(value, units);
const emit = (nextNum: string, nextUnit: string) => {
if (nextNum === '') { onChange(''); return; }
onChange(`${nextNum}${nextUnit}`);
};
return (
<div style={{ display: 'flex', gap: 4 }} data-testid={testId}>
<input
type="number"
data-testid={`${testId}-number`}
value={num}
min={min}
max={max}
step={step}
placeholder={placeholder}
onChange={(e) => emit(e.target.value, unit)}
style={{ ...inputStyle, flex: 1 }}
/>
{units.length > 1 && (
<select
data-testid={`${testId}-unit`}
value={unit}
onChange={(e) => emit(num, e.target.value)}
style={{ ...inputStyle, width: 60, flex: 'none' }}
>
{units.map((u) => <option key={u} value={u}>{u}</option>)}
</select>
)}
</div>
);
};
/* ---------- SizeControl ----------
Width (or height) editor: preset buttons (25/50/75/100%, Auto, Full) +
a custom NumericUnitInput. One dimension per instance -- render two
(label="Width" / label="Height") for components needing both, e.g.
ImageBlock / VideoBlock sizing. */
export interface SizeControlProps {
label: string;
/** CSS value for this one dimension, e.g. "100%" / "400px" / "auto" / "". */
value: string;
onChange: (value: string) => void;
presets?: { label: string; value: string }[];
units?: string[];
}
export const SizeControl: React.FC<SizeControlProps> = ({ label, value, onChange, presets = SIZE_PRESETS, units = ['px', '%'] }) => (
<div className="guided-section" data-testid="size-control">
<SectionLabel>{label}</SectionLabel>
<PresetButtonGrid presets={presets} activeValue={value} onSelect={onChange} />
<div style={{ marginTop: 6 }}>
<NumericUnitInput
value={presets.some((p) => p.value === value) ? '' : value}
onChange={onChange}
units={units}
testId="size-control-custom"
/>
</div>
</div>
);
/* ---------- AspectRatioControl ----------
Preset buttons + a custom "W:H" text entry. Emits a CSS `aspect-ratio`
value, e.g. "16 / 9". 'Original' emits ''. Custom entry accepts
"16:9" / "16/9" / "16x9" and is parsed on blur or Enter. */
export function parseAspectRatioInput(raw: string): string {
const m = raw.trim().match(/^(\d+(?:\.\d+)?)\s*[:xX/]\s*(\d+(?:\.\d+)?)$/);
if (!m) return '';
return `${m[1]} / ${m[2]}`;
}
function formatAspectRatioForInput(value: string): string {
const m = value.match(/^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/);
return m ? `${m[1]}:${m[2]}` : '';
}
export interface AspectRatioControlProps {
/** CSS `aspect-ratio` value, e.g. "16 / 9", or '' for Original/unset. */
value: string;
onChange: (value: string) => void;
presets?: { label: string; value: string }[];
}
export const AspectRatioControl: React.FC<AspectRatioControlProps> = ({ value, onChange, presets = ASPECT_RATIOS }) => {
const [custom, setCustom] = useState(() => formatAspectRatioForInput(value));
const applyCustom = () => onChange(parseAspectRatioInput(custom));
return (
<div className="guided-section" data-testid="aspect-ratio-control">
<SectionLabel>Aspect Ratio</SectionLabel>
<PresetButtonGrid presets={presets} activeValue={value} onSelect={(v) => { onChange(v); setCustom(''); }} />
<div style={{ marginTop: 6 }}>
<input
type="text"
data-testid="aspect-ratio-custom-input"
value={custom}
placeholder="W:H e.g. 16:9"
onChange={(e) => setCustom(e.target.value)}
onBlur={applyCustom}
onKeyDown={(e) => { if (e.key === 'Enter') applyCustom(); }}
style={{ ...inputStyle }}
/>
</div>
</div>
);
};
/* ---------- FocalPointGrid ----------
3x3 grid of buttons mapping to CSS `object-position` keyword pairs.
Used for image crop framing (object-position on an ImageBlock/VideoBlock
with object-fit: cover). Highlights the active cell; defaults the
highlight to 'center' when value is empty. */
export const FOCAL_POINTS: { label: string; value: string }[] = [
{ label: '↖', value: 'left top' }, { label: '↑', value: 'center top' }, { label: '↗', value: 'right top' },
{ label: '←', value: 'left center' }, { label: '•', value: 'center' }, { label: '→', value: 'right center' },
{ label: '↙', value: 'left bottom' }, { label: '↓', value: 'center bottom' }, { label: '↘', value: 'right bottom' },
];
export interface FocalPointGridProps {
/** CSS `object-position` value, e.g. "center" / "left top". */
value: string;
onChange: (value: string) => void;
}
export const FocalPointGrid: React.FC<FocalPointGridProps> = ({ value, onChange }) => {
const active = value || 'center';
return (
<div className="guided-section" data-testid="focal-point-grid">
<SectionLabel>Focal Point</SectionLabel>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4, width: 96 }}>
{FOCAL_POINTS.map((p) => (
<button
key={p.value}
data-testid={`focal-point-${p.value.replace(/\s+/g, '-')}`}
onClick={() => onChange(p.value)}
title={p.value}
style={{
aspectRatio: '1', border: '1px solid #3f3f46', borderRadius: 4, cursor: 'pointer',
background: active === p.value ? '#3b82f6' : '#27272a',
color: active === p.value ? '#fff' : '#71717a', fontSize: 12,
}}
>
{p.label}
</button>
))}
</div>
</div>
);
};
/* ---------- SpacingControl ----------
Margin OR padding, per-side, with a link/unlink toggle.
API: onChange(side, value) -- called once per side. In linked mode
(default), editing the single shared field or clicking a preset calls
onChange for all four sides ('top','right','bottom','left') with the
same value so the consumer can setPropStyle each side independently
(e.g. marginTop/marginRight/marginBottom/marginLeft). In unlinked mode
each side's NumericUnitInput calls onChange for just that side. */
export type SpacingSide = 'top' | 'right' | 'bottom' | 'left';
export interface SpacingSideValues { top?: string; right?: string; bottom?: string; left?: string; }
const SPACING_SIDES: SpacingSide[] = ['top', 'right', 'bottom', 'left'];
export interface SpacingControlProps {
label: string;
value: SpacingSideValues;
/** Called per-side. Linked edits/presets call this once for each of the
* 4 sides (in top/right/bottom/left order) with the same value. */
onChange: (side: SpacingSide, value: string) => void;
presets?: { label: string; value: string }[];
units?: string[];
}
export const SpacingControl: React.FC<SpacingControlProps> = ({ label, value, onChange, presets = SPACING_PRESETS, units = ['px', '%', 'em', 'rem'] }) => {
const [linked, setLinked] = useState(true);
const applyToAllSides = (v: string) => SPACING_SIDES.forEach((s) => onChange(s, v));
const linkedValue = value.top ?? '';
const isAllEqual = SPACING_SIDES.every((s) => (value[s] ?? '') === linkedValue);
return (
<div className="guided-section" data-testid="spacing-control">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<SectionLabel>{label}</SectionLabel>
<button
data-testid="spacing-link-toggle"
onClick={() => setLinked(!linked)}
title={linked ? 'Unlink sides' : 'Link sides'}
style={{ background: 'none', border: 'none', color: linked ? '#3b82f6' : '#71717a', cursor: 'pointer', padding: 2 }}
>
<i className={`fa fa-link${linked ? '' : '-slash'}`} />
</button>
</div>
<PresetButtonGrid presets={presets} activeValue={isAllEqual ? linkedValue : undefined} onSelect={applyToAllSides} />
{linked ? (
<div style={{ marginTop: 6 }}>
<NumericUnitInput value={linkedValue} onChange={applyToAllSides} units={units} testId="spacing-linked" />
</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 6 }}>
{SPACING_SIDES.map((s) => (
<div key={s}>
<label style={{ ...labelStyle, fontSize: 9 }}>{s}</label>
<NumericUnitInput value={value[s] ?? ''} onChange={(v) => onChange(s, v)} units={units} testId={`spacing-${s}`} />
</div>
))}
</div>
)}
</div>
);
};
/* ---------- BorderControl ----------
Width (px) + style (none/solid/dashed/dotted) + color. Single onChange
receives the merged { width, style, color } object so the consumer can
either setProp each part or build a shorthand via buildBorderShorthand()
(returns 'none' when width is falsy or style is 'none'). */
export interface BorderValue { width: string; style: string; color: string; }
export interface BorderControlProps {
value: BorderValue;
onChange: (value: BorderValue) => void;
label?: string;
}
export const BorderControl: React.FC<BorderControlProps> = ({ value, onChange, label = 'Border' }) => {
const set = (patch: Partial<BorderValue>) => onChange({ ...value, ...patch });
return (
<div className="guided-section" data-testid="border-control">
<SectionLabel>{label}</SectionLabel>
<div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
<div style={{ flex: 1 }}>
<NumericUnitInput value={value.width} onChange={(v) => set({ width: v })} units={['px']} placeholder="0" testId="border-width" />
</div>
<select
data-testid="border-style-select"
value={value.style}
onChange={(e) => set({ style: e.target.value })}
style={{ ...inputStyle, flex: 1 }}
>
{BORDER_STYLES.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}
</select>
</div>
<ColorPickerField label="Border Color" value={value.color} onChange={(v) => set({ color: v })} />
</div>
);
};
export function buildBorderShorthand(value: BorderValue): string {
if (!value.width || !value.style || value.style === 'none') return 'none';
return `${value.width} ${value.style} ${value.color || '#000000'}`;
}
/* ---------- AnimationControl ----------
"Entrance animation" picker + optional delay. Emits the EXACT prop names
the export machinery already consumes (verified against buildDataAttrs()
in src/utils/html-export.ts): `animation` and `animationDelay`.
NOTE: the export supports fade-in / slide-up / slide-left / slide-right /
zoom-in / bounce (no "slide-down" -- html-export.ts has no such variant;
slide-left/slide-right exist instead), so ANIMATIONS reflects that exact
set rather than guessing. animationDelay is a plain seconds string (e.g.
"0.3") -- html-export.ts's inline script assigns it straight to
el.style.animationDelay, so consumers should suffix/accept a unit-bearing
string like "0.3s" if that's what they choose to store; this control
stores/edits the raw numeric string and leaves unit formatting to the
caller (kept as the simplest contract; see report for the exact
behavior verified against html-export.ts). */
export const ANIMATIONS: { label: string; value: string }[] = [
{ label: 'None', value: 'none' },
{ label: 'Fade In', value: 'fade-in' },
{ label: 'Slide Up', value: 'slide-up' },
{ label: 'Slide Left', value: 'slide-left' },
{ label: 'Slide Right', value: 'slide-right' },
{ label: 'Zoom In', value: 'zoom-in' },
{ label: 'Bounce', value: 'bounce' },
];
export interface AnimationValue { animation: string; animationDelay?: string; }
export interface AnimationControlProps {
value: AnimationValue;
onChange: (value: AnimationValue) => void;
}
export const AnimationControl: React.FC<AnimationControlProps> = ({ value, onChange }) => {
const animation = value.animation || 'none';
const animationDelay = value.animationDelay ?? '0';
return (
<div className="guided-section" data-testid="animation-control">
<SectionLabel>Entrance Animation</SectionLabel>
<PresetButtonGrid presets={ANIMATIONS} activeValue={animation} onSelect={(v) => onChange({ animation: v, animationDelay })} />
{animation !== 'none' && (
<div style={{ marginTop: 6 }}>
<label style={labelStyle}>Delay (seconds)</label>
<input
type="number"
data-testid="animation-delay-input"
min={0}
step={0.1}
value={animationDelay}
onChange={(e) => onChange({ animation, animationDelay: e.target.value })}
style={inputStyle}
/>
</div>
)}
</div>
);
};
/* ---------- VisibilityControl ----------
Hide on Desktop / Tablet / Mobile toggles. Emits the EXACT prop names
the export machinery already consumes (verified against buildDataAttrs()
in src/utils/html-export.ts): `hideOnDesktop`, `hideOnTablet`,
`hideOnMobile` (each rendered as data-hide-desktop/tablet/mobile when
truthy). Single onChange receives the merged object. */
export interface VisibilityValue { hideOnDesktop?: boolean; hideOnTablet?: boolean; hideOnMobile?: boolean; }
export interface VisibilityControlProps {
value: VisibilityValue;
onChange: (value: VisibilityValue) => void;
}
const VISIBILITY_KEYS: (keyof VisibilityValue)[] = ['hideOnDesktop', 'hideOnTablet', 'hideOnMobile'];
export const VisibilityControl: React.FC<VisibilityControlProps> = ({ value, onChange }) => (
<div className="guided-section" data-testid="visibility-control">
<SectionLabel>Visibility</SectionLabel>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{VISIBILITY_KEYS.map((key) => (
<label key={key} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer' }}>
<input
type="checkbox"
data-testid={`visibility-${key}`}
checked={!!value[key]}
onChange={() => onChange({ ...value, [key]: !value[key] })}
/>
Hide on {key.replace('hideOn', '')}
</label>
))}
</div>
</div>
);
+12 -2
View File
@@ -1,4 +1,5 @@
import React from 'react'; import React from 'react';
import { createPortal } from 'react-dom';
import { useSiteDesign } from '../../state/SiteDesignContext'; import { useSiteDesign } from '../../state/SiteDesignContext';
import { Modal } from '../../ui/Modal'; import { Modal } from '../../ui/Modal';
@@ -10,7 +11,15 @@ interface HeadCodeModalProps {
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => { export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
const { design, updateDesign } = useSiteDesign(); const { design, updateDesign } = useSiteDesign();
return ( // Mobile-A2/Phase B: portaled to `document.body` -- same fix TemplateModal
// already got (see its comment). TopBar.tsx mounts this modal as a child
// of `.topbar`, which (as a flex item with its own z-index) forms its own
// stacking context; that trapped the modal's fixed-position backdrop
// underneath the mobile tab bar (z-index: var(--z-tabbar)) no matter how
// high the modal's own z-index was set. Portaling escapes that stacking
// context entirely so `--z-modal` (editor.css) is evaluated at the
// document root, same as TemplateModal/SitesmithModal.
return createPortal(
<Modal open={open} onClose={onClose}> <Modal open={open} onClose={onClose}>
<div style={modalStyle} onClick={(e) => e.stopPropagation()}> <div style={modalStyle} onClick={(e) => e.stopPropagation()}>
{/* Header */} {/* Header */}
@@ -82,7 +91,8 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
</button> </button>
</div> </div>
</div> </div>
</Modal> </Modal>,
document.body,
); );
}; };
+117 -4
View File
@@ -34,6 +34,11 @@
/* Phase A (mobile): fixed bottom tab bar height, used to size /* Phase A (mobile): fixed bottom tab bar height, used to size
.editor-container and the safe-area padding math below. */ .editor-container and the safe-area padding math below. */
--mobile-tabbar-height: 58px; --mobile-tabbar-height: 58px;
/* Phase B fast-follow item 4: rendered height of `.mobile-selection-toolbar`
(44px min-height content + 4px top/bottom padding + 1px border) -- used
to pad the canvas scroll area clear of it while it's visible, see
`.editor-canvas.has-mobile-selection-toolbar` below. */
--mobile-selection-toolbar-height: 53px;
/* Mobile-A2: explicit overlay layer scale (was ad-hoc numbers scattered /* Mobile-A2: explicit overlay layer scale (was ad-hoc numbers scattered
across the mobile block + Modal.tsx, causing accidental stacking -- across the mobile block + Modal.tsx, causing accidental stacking --
@@ -1626,6 +1631,90 @@ body {
color: var(--color-accent); color: var(--color-accent);
} }
/* --------------------------------------------------------------------
Mobile selection toolbar (MobileSelectionToolbar.tsx, Phase B item 2)
Bottom-fixed just above the tab bar -- simplest, robust positioning
that never has to track a scrolling/resizing node's DOM rect. Sits at
--z-selection-toolbar (600), above the tab bar (500) and sheet backdrop
(400) so it's never occluded by either, but well below --z-modal
(5000). Hidden entirely (component returns null) whenever a sheet is
open, so it never has to fight the sheet for the same screen space.
-------------------------------------------------------------------- */
.mobile-selection-toolbar {
position: fixed;
left: 0;
right: 0;
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px));
z-index: var(--z-selection-toolbar);
display: flex;
background: var(--color-bg-elevated);
border-top: 1px solid var(--color-border);
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.35);
padding: 4px calc(2px + env(safe-area-inset-right, 0px)) 4px calc(2px + env(safe-area-inset-left, 0px));
}
.mobile-selection-toolbar-btn {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2px;
min-height: 44px;
padding: 4px 2px;
font-size: 9px;
font-weight: 600;
line-height: 1;
color: var(--color-text);
background: transparent;
border: none;
border-radius: var(--radius-md);
cursor: pointer;
touch-action: manipulation;
}
.mobile-selection-toolbar-btn i {
font-size: 15px;
}
.mobile-selection-toolbar-btn:disabled {
color: var(--color-text-dim);
opacity: 0.4;
}
.mobile-selection-toolbar-btn.danger {
color: var(--color-danger);
}
.mobile-selection-toolbar-btn.danger.confirming {
background: rgba(239, 68, 68, 0.15);
}
/* Fast-follow item 4: while the toolbar above is visible, give the canvas
scroll area enough extra bottom padding to clear it (on top of the
regular 12px `.editor-canvas` padding, not replacing it), so the last
section of a short page is still reachable by scrolling instead of
sitting permanently underneath the fixed toolbar. */
.editor-canvas.has-mobile-selection-toolbar {
padding-bottom: calc(12px + var(--mobile-selection-toolbar-height));
}
/* Fast-follow item 3: while the Styles sheet is open with a node selected,
`MobileSelectionToolbar`'s scroll-into-view effect needs somewhere to
scroll THE NODE TO even when it's the last thing on the page -- without
extra room below it, the canvas is already at its max scrollTop and the
node's top can't be brought up past wherever it naturally landed
(verified live: the last section stayed stuck under the sheet). A full
extra viewport's worth of bottom padding guarantees any node's top can
always reach the very top of the canvas. Temporary/cosmetic cost (a
stretch of blank canvas below the real content while this is active) is
an acceptable trade for the node never being permanently unreachable.
-------------------------------------------------------------------- */
.editor-canvas.has-mobile-styles-sheet {
padding-bottom: 100vh;
padding-bottom: 100dvh;
}
/* -------------------------------------------------------------------- /* --------------------------------------------------------------------
Bottom sheet (BottomSheet.tsx) Bottom sheet (BottomSheet.tsx)
-------------------------------------------------------------------- */ -------------------------------------------------------------------- */
@@ -1637,8 +1726,13 @@ body {
/* Stop above the bottom tab bar (rather than a full-viewport `inset: 0`) /* Stop above the bottom tab bar (rather than a full-viewport `inset: 0`)
so the tab bar is never covered/blocked by the backdrop -- tapping a so the tab bar is never covered/blocked by the backdrop -- tapping a
different tab while a sheet is open swaps sheets directly instead of different tab while a sheet is open swaps sheets directly instead of
being swallowed by the overlay sitting on top of it. */ being swallowed by the overlay sitting on top of it.
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px)); `--keyboard-inset` (item 5, Phase B) is set inline by BottomSheet.tsx
from `useVisualViewportInsets` -- 0px when no on-screen keyboard is
open (the default below is the no-JS/unsupported-browser fallback),
otherwise the keyboard's height, so the whole sheet lifts clear of it
instead of the keyboard covering its lower portion. */
bottom: calc(var(--mobile-tabbar-height) + env(safe-area-inset-bottom, 0px) + var(--keyboard-inset, 0px));
background: rgba(0, 0, 0, 0.5); background: rgba(0, 0, 0, 0.5);
z-index: var(--z-sheet-backdrop); z-index: var(--z-sheet-backdrop);
display: flex; display: flex;
@@ -1647,8 +1741,12 @@ body {
.mobile-sheet { .mobile-sheet {
width: 100%; width: 100%;
max-height: 65vh; /* Capped a second time by the keyboard inset so the sheet's own
max-height: 65dvh; max-height shrinks along with the lifted backdrop -- without this the
sheet could still try to be 65dvh tall from its new (higher) bottom
edge and overflow off the top of the screen. */
max-height: calc(65vh - var(--keyboard-inset, 0px));
max-height: calc(65dvh - var(--keyboard-inset, 0px));
background: var(--color-bg-surface); background: var(--color-bg-surface);
border-top-left-radius: 16px; border-top-left-radius: 16px;
border-top-right-radius: 16px; border-top-right-radius: 16px;
@@ -1664,6 +1762,10 @@ body {
justify-content: center; justify-content: center;
padding: 8px 0 4px; padding: 8px 0 4px;
flex-shrink: 0; flex-shrink: 0;
/* Swipe-to-dismiss (item 4, Phase B) tracks its own touchmove here --
`none` stops the browser's native scroll/rubber-band gesture from
competing with it. */
touch-action: none;
} }
.mobile-sheet-handle { .mobile-sheet-handle {
@@ -1680,6 +1782,8 @@ body {
padding: 4px 12px 10px 16px; padding: 4px 12px 10px 16px;
border-bottom: 1px solid var(--color-border); border-bottom: 1px solid var(--color-border);
flex-shrink: 0; flex-shrink: 0;
/* Swipe-to-dismiss (item 4, Phase B) -- see .mobile-sheet-handle-row. */
touch-action: none;
} }
.mobile-sheet-title { .mobile-sheet-title {
@@ -1749,6 +1853,15 @@ body {
height: 40px; height: 40px;
} }
/* Layers panel rows (item 4) -- the reliable fallback selection path when
a node is hard to hit precisely on the canvas by touch. Bumped to the
44px touch-target minimum; tapping a row already selects (LayerNode's
`handleActivate`), unchanged. */
.mobile-sheet-body .layer-node-row {
min-height: 44px;
touch-action: manipulation;
}
/* -------------------------------------------------------------------- /* --------------------------------------------------------------------
Templates modal: category tabs stay horizontally scrollable and never Templates modal: category tabs stay horizontally scrollable and never
shrink below a comfortable touch target; close button enlarged to the shrink below a comfortable touch target; close button enlarged to the
+218
View File
@@ -0,0 +1,218 @@
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { Editor, Frame, Element, useEditor } from '@craftjs/core';
import { componentResolver } from '../components/resolver';
import { Container } from '../components/layout/Container';
import { EditorConfigProvider } from '../state/EditorConfigContext';
/**
* Real-`@craftjs/core` integration test harness.
*
* Mounts an ACTUAL `<Editor resolver={componentResolver}>` + `<Frame>` via
* `react-dom/client`'s `createRoot` (no `@testing-library/react`, matching
* the existing `*.test.tsx` convention in this repo -- see
* `useKeyboardShortcuts.test.tsx` / `RenderNode.test.tsx`). Nothing in
* `@craftjs/core` is mocked here: `query`/`actions` come straight out of a
* live `useEditor()` call, so `regenerateTreeIds`, `buildNodeTree`,
* `parseFreshNode`, `addNodeTree`, `deserialize`, and `serialize` all run
* their REAL implementations against a REAL Craft.js `EditorStore`.
*
* Why this catches bugs the mocked unit tests didn't: a hand-rolled fake
* `useEditor`/`query`/`node().toNodeTree()` can only echo back whatever
* plain-data shape the test author imagined -- it has no way to reproduce
* Craft's actual internal node shape (`data.type` as a live component
* function reference, real `parseFreshNode` resolver validation, real
* `<Frame>` rendering). Every one of the three historical bugs this suite
* targets (`regenerateTreeIds` + `structuredClone`, `TemplateModal` dropping
* `children`, `buildNodeTree` emitting `data.type={resolvedName}`) slipped
* past its mocked unit test for exactly that reason.
*
* jsdom shims: as of writing, mounting `<Editor><Frame>...` in this repo's
* jsdom (v29, see vitest.config.ts) did NOT require stubbing
* `ResizeObserver`/`matchMedia`/`getBoundingClientRect` -- none of the
* components exercised by these integration tests read layout geometry
* during render. `ensureJsdomShims()` below still installs a `ResizeObserver`
* stub defensively (idempotent, only if absent) since it's the one API
* Craft/DOM-heavy component code most commonly reaches for and a future
* template/component could easily start needing it; add further shims here
* (not per-test) if a future component trips over a missing browser API.
*/
let shimsInstalled = false;
/** Install browser APIs jsdom doesn't implement, if not already present. Safe
* to call multiple times (idempotent) and safe in a real browser (guarded by
* `typeof` checks, so it never clobbers a real implementation). */
export function ensureJsdomShims(): void {
if (shimsInstalled) return;
shimsInstalled = true;
if (typeof (globalThis as any).ResizeObserver === 'undefined') {
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
(globalThis as any).ResizeObserver = ResizeObserverStub;
}
if (typeof window !== 'undefined' && typeof window.matchMedia !== 'function') {
window.matchMedia = ((query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => false,
})) as unknown as typeof window.matchMedia;
}
// jsdom (as of v29, used by this repo's vitest.config.ts) does NOT
// implement `HTMLElement.prototype.innerText` at all -- `'innerText' in
// document.createElement('div')` is `false`, so assigning to it (as
// `Heading.tsx`/`TextBlock.tsx` do imperatively in a `useEffect`, to avoid
// fighting `contentEditable`'s caret position on every prop update) just
// sets a throwaway own-property that never touches `textContent`/
// `innerHTML` -- real rendered text from these two components would
// silently read back as empty in any DOM assertion. Shimmed as a plain
// `textContent` alias (real `innerText` also collapses whitespace/applies
// layout-based visibility, neither of which matters for these tests).
if (typeof HTMLElement !== 'undefined') {
if (!Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText')) {
Object.defineProperty(HTMLElement.prototype, 'innerText', {
configurable: true,
get(this: HTMLElement) {
return this.textContent;
},
set(this: HTMLElement, value: string) {
this.textContent = value;
},
});
}
}
}
interface CapturedApi {
query: any;
actions: any;
}
/** Invisible child that grabs a live `query`/`actions` pair out of a real
* `useEditor()` call and writes them into a mutable ref the harness owns --
* the same "Capture" pattern the brief describes and
* `template-zone-export.test.tsx` already uses ad hoc; this hoists it into a
* reusable helper. `query`/`actions` from Craft.js are live references (they
* read the current store at call time, not a react-state snapshot), so
* capturing them once on first render is sufficient -- no need to re-grab
* them after every store mutation. */
const Capture: React.FC<{ apiRef: React.MutableRefObject<CapturedApi | null> }> = ({ apiRef }) => {
const { query, actions } = useEditor();
apiRef.current = { query, actions };
return null;
};
export interface EditorHarnessOptions {
/** A `query.serialize()`-shaped JSON string to `actions.deserialize()`
* immediately after mount, replacing the default empty ROOT. */
initialState?: string;
/** Craft.js `Frame` seed root tag -- 'div' for a regular page, 'header'/
* 'footer' for zone editing (mirrors `Canvas.tsx`'s `frameTag`). Ignored
* once `initialState` is given (deserialize replaces ROOT anyway); only
* affects the very first (pre-deserialize) paint. */
frameTag?: 'div' | 'header' | 'footer';
}
export interface EditorHarness {
/** Live `query` from the real `useEditor()` -- reads current store state. */
readonly query: any;
/** Live `actions` from the real `useEditor()`. */
readonly actions: any;
/** `query.serialize()` -- the exact string `PageContext`/`useWhpApi` persist
* and `exportBodyHtml` consumes. */
getSerialized: () => string;
/** The DOM node the whole tree (including the real rendered `<Frame>`
* content) is mounted under -- assert on `.textContent`/`.innerHTML` here
* to verify actual rendering, not just serialized state. */
container: HTMLDivElement;
/** Re-exported `act` from `react-dom/test-utils` for convenience, matching
* the existing `*.test.tsx` files in this repo. */
act: typeof act;
/** Mount (or replace) an additional child inside the live `<Editor>` tree,
* alongside `<Frame>` -- e.g. a probe component that calls a real hook
* (`useNodeActions`, `useKeyboardShortcuts`) so the test can drive it
* against the REAL editor instance this harness set up. Wrapped in `act`. */
mountChild: (node: React.ReactNode) => void;
/** Unmounts the React tree and removes `container` from `document.body`. */
unmount: () => void;
}
/**
* Mounts a real `<Editor resolver={componentResolver}>` + `<Frame>` (via
* `EditorConfigProvider config={null}` -- standalone mode, no WHP backend)
* and returns live `query`/`actions` plus helpers for driving further
* real-editor interactions from a test.
*/
export function renderEditorHarness(opts: EditorHarnessOptions = {}): EditorHarness {
ensureJsdomShims();
const container = document.createElement('div');
document.body.appendChild(container);
const apiRef: React.MutableRefObject<CapturedApi | null> = { current: null };
let extraChild: React.ReactNode = null;
let root: Root;
const frameTag = opts.frameTag ?? 'div';
function paint() {
root.render(
<EditorConfigProvider config={null}>
<Editor resolver={componentResolver} enabled={true}>
<Frame>
<Element is={Container} canvas tag={frameTag} style={{}} />
</Frame>
<Capture apiRef={apiRef} />
{extraChild}
</Editor>
</EditorConfigProvider>,
);
}
act(() => {
root = createRoot(container);
paint();
});
if (opts.initialState) {
act(() => {
apiRef.current!.actions.deserialize(opts.initialState!);
});
}
return {
get query() {
return apiRef.current!.query;
},
get actions() {
return apiRef.current!.actions;
},
getSerialized: () => apiRef.current!.query.serialize(),
container,
act,
mountChild: (node: React.ReactNode) => {
extraChild = node;
act(() => {
paint();
});
},
unmount: () => {
act(() => {
root.unmount();
});
container.remove();
},
};
}
@@ -0,0 +1,185 @@
import { describe, test, expect, afterEach } from 'vitest';
import React from 'react';
import { renderEditorHarness, EditorHarness } from '../editorHarness';
import { useApplyAiResponse } from '../../utils/apply-ai-response';
import { exportBodyHtml } from '../../utils/html-export';
import type { SitesmithResponse } from '../../types/sitesmith';
/**
* Real-`@craftjs/core` integration coverage for applying a Sitesmith (AI)
* response.
*
* Historical bug: `buildNodeTree` used to hand `query.parseFreshNode`/the
* manually-constructed synthetic node a `data.type` of the SERIALIZED
* `{ resolvedName }` wrapper object (or, in an earlier attempt, a bare
* resolvedName string) instead of the actual component function reference
* from `componentResolver`. A live Craft.js node's renderer does
* `React.createElement(data.type, props)` directly, so anything other than
* a real component reference either fails Craft's own resolver validation
* inside `parseFreshNode`/`addNodeTree` ("component type ... does not exist
* in the resolver") or -- worse -- passes that validation but renders
* nothing/garbage. Either way, a section-replace or insert AI op became a
* silent no-op in the live app. The pre-existing mocked unit test
* (`apply-ai-response.test.ts`) fakes `query.parseFreshNode` as
* `(input) => ({ toNode: () => input })` -- a pure echo with NO validation
* at all -- so it could never have caught `buildNodeTree` emitting the
* wrong `data.type` shape.
*
* This suite drives the REAL `useApplyAiResponse()` hook (the exact
* consumer-facing API `SitesmithModal`/`useSitesmith` call after a
* successful AI response) against a real `EditorStore`/`<Frame>` from
* `editorHarness.tsx` -- so a regression in `buildNodeTree`'s `data.type`
* would throw here (real `parseFreshNode` resolver validation) or fail the
* "content actually landed" assertions (real render/export), exactly as it
* did live.
*/
const INITIAL_STATE = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'div' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: ['anchor-1'],
linkedNodes: {},
},
'anchor-1': {
type: { resolvedName: 'Heading' },
isCanvas: false,
props: { text: 'Anchor Heading', level: 'h2' },
displayName: 'Heading',
custom: {},
hidden: false,
parent: 'ROOT',
nodes: [],
linkedNodes: {},
},
});
let harness: EditorHarness | null = null;
afterEach(() => {
if (harness) {
harness.unmount();
harness = null;
}
});
/** Mounts `useApplyAiResponse()` (the real hook) inside the harness's live
* Editor and returns the captured `apply` function. */
function mountApplyFn(h: EditorHarness): { current: ReturnType<typeof useApplyAiResponse> | null } {
const ref: { current: ReturnType<typeof useApplyAiResponse> | null } = { current: null };
const Probe: React.FC = () => {
ref.current = useApplyAiResponse();
return null;
};
h.mountChild(<Probe />);
return ref;
}
describe('AI apply-response (real @craftjs/core editor)', () => {
test('section-scope replace with no target: appends a real, rendered node -- not a silent no-op', async () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const applyRef = mountApplyFn(harness);
expect(applyRef.current).not.toBeNull();
const resp: SitesmithResponse = {
type: 'replace',
scope: 'section',
pages: [
{
name: 'section',
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Inserted Heading Panel' }, nodes: [] },
},
],
message: 'inserted a section',
};
let result: { ok: boolean; message?: string } | undefined;
await harness.act(async () => {
result = await applyRef.current!(resp);
});
expect(result!.ok).toBe(true);
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toHaveLength(2);
expect(rootChildren).toContain('anchor-1');
const newId = rootChildren.find((id) => id !== 'anchor-1')!;
expect(newId).toBeDefined();
// Real node.data.type must be the actual component reference so React
// can render it -- not a `{resolvedName}` wrapper or a bare string.
const newNodeType = harness.query.node(newId).get().data.type;
expect(typeof newNodeType).toBe('function');
expect(harness.container.textContent).toContain('AI Inserted Heading Panel');
const { html } = exportBodyHtml(harness.getSerialized());
expect(html).toContain('AI Inserted Heading Panel');
});
test('section-scope replace WITH a target node: replaces that node in place (same slot, fresh id)', async () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const applyRef = mountApplyFn(harness);
const resp: SitesmithResponse = {
type: 'replace',
scope: 'section',
pages: [
{
name: 'section',
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Replaced The Anchor' }, nodes: [] },
},
],
message: 'replaced the section',
};
await harness.act(async () => {
await applyRef.current!(resp, 'anchor-1');
});
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toHaveLength(1); // still just one node in that slot
expect(rootChildren).not.toContain('anchor-1'); // the old node is gone
expect(harness.container.textContent).toContain('AI Replaced The Anchor');
expect(harness.container.textContent).not.toContain('Anchor Heading');
});
test('patch op insert_after: inserts a real node as the very next sibling', async () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const applyRef = mountApplyFn(harness);
const resp: SitesmithResponse = {
type: 'patch',
ops: [
{
op: 'insert_after',
node_id: 'anchor-1',
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Patched In After Anchor' }, nodes: [] },
},
],
message: 'patched',
};
let result: { ok: boolean; message?: string } | undefined;
await harness.act(async () => {
result = await applyRef.current!(resp);
});
expect(result!.ok).toBe(true);
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toHaveLength(2);
expect(rootChildren[0]).toBe('anchor-1');
const insertedId = rootChildren[1];
expect(typeof harness.query.node(insertedId).get().data.type).toBe('function');
expect(harness.container.textContent).toContain('AI Patched In After Anchor');
// The original anchor is untouched.
expect(harness.container.textContent).toContain('Anchor Heading');
});
});
@@ -0,0 +1,193 @@
import { describe, test, expect, afterEach } from 'vitest';
import React from 'react';
import { renderEditorHarness, EditorHarness } from '../editorHarness';
import { useNodeActions, NodeActions } from '../../hooks/useNodeActions';
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
/**
* Real-`@craftjs/core` integration coverage for duplicate/paste.
*
* Historical bug: `regenerateTreeIds` used `structuredClone(oldNode.data)` to
* clone a copied subtree. For a REAL (live) Craft.js node, `data.type` is the
* actual component function reference (not a plain `{resolvedName}` string
* wrapper) -- `structuredClone` cannot clone a function and throws
* `DataCloneError`, which silently broke duplicate/paste for EVERY
* component in the real app. The pre-existing mocked unit tests
* (`useNodeActions.test.tsx`, `useKeyboardShortcuts.test.tsx`) faked
* `query.node(id).toNodeTree()` to return a plain-data object with
* `type: { resolvedName: 'Container' }` -- never a function -- so
* `structuredClone` never saw anything it couldn't clone there, and the bug
* shipped anyway.
*
* This suite drives the REAL `useNodeActions`/`useKeyboardShortcuts` hooks
* (no `vi.mock('@craftjs/core')` anywhere) against a real
* `EditorStore`/`query`/`actions` from `editorHarness.tsx`, on a real
* `SocialLinks` node (its `.craft` config makes Craft.js store the actual
* `SocialLinks` function as `data.type`) -- so a regression back to
* `structuredClone(oldNode.data)` throws here exactly as it did live. See
* `task-integ-harness-report.md` for the recorded red-proof run.
*/
const INITIAL_STATE = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'div' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: ['social-1', 'heading-1'],
linkedNodes: {},
},
'social-1': {
type: { resolvedName: 'SocialLinks' },
isCanvas: false,
props: {
links: [{ platform: 'facebook', url: 'https://facebook.com/original' }],
iconColor: '#ffffff',
},
displayName: 'Social Links',
custom: {},
hidden: false,
parent: 'ROOT',
nodes: [],
linkedNodes: {},
},
'heading-1': {
type: { resolvedName: 'Heading' },
isCanvas: false,
props: { text: 'Sibling Heading', level: 'h2' },
displayName: 'Heading',
custom: {},
hidden: false,
parent: 'ROOT',
nodes: [],
linkedNodes: {},
},
});
let harness: EditorHarness | null = null;
afterEach(() => {
setClipboardNodeId(null);
if (harness) {
harness.unmount();
harness = null;
}
});
describe('duplicate/paste (real @craftjs/core editor)', () => {
test('useNodeActions().duplicate() on a real SocialLinks node: no throw, +1 node, inserted right after the source, with an independent props copy', () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const before = Object.keys(harness.query.getNodes());
expect(before).toHaveLength(3); // ROOT, social-1, heading-1
const probeRef: { current: NodeActions | null } = { current: null };
const Probe: React.FC = () => {
probeRef.current = useNodeActions('social-1');
return null;
};
harness.mountChild(<Probe />);
expect(probeRef.current).not.toBeNull();
let newId: string | null = null;
expect(() => {
harness!.act(() => {
newId = probeRef.current!.duplicate();
});
}).not.toThrow();
expect(newId).not.toBeNull();
expect(newId).not.toBe('social-1');
// +1 node overall.
const after = Object.keys(harness.query.getNodes());
expect(after).toHaveLength(4);
// Inserted immediately AFTER the source, not appended at the end.
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toEqual(['social-1', newId, 'heading-1']);
// The new node was selected.
expect(Array.from(harness.query.getEvent('selected').all())).toEqual([newId]);
// The copy's props object (and any nested arrays/objects within it) must
// be a SEPARATE object from the original -- not shared by reference.
const originalProps = harness.query.node('social-1').get().data.props;
const copyProps = harness.query.node(newId!).get().data.props;
expect(copyProps).not.toBe(originalProps);
expect(copyProps.links).not.toBe(originalProps.links);
expect(copyProps).toEqual(originalProps); // same VALUES though
// Mutating the copy via setProp must not affect the original.
harness.act(() => {
harness!.actions.setProp(newId!, (p: any) => {
p.links[0].url = 'https://facebook.com/MUTATED-COPY';
});
});
expect(harness.query.node(newId!).get().data.props.links[0].url).toBe(
'https://facebook.com/MUTATED-COPY',
);
expect(harness.query.node('social-1').get().data.props.links[0].url).toBe(
'https://facebook.com/original',
);
// Real DOM assertion, not just serialized state: the Frame actually
// re-rendered with a second SocialLinks <a> link on the canvas.
expect(harness.container.querySelectorAll('a[href="https://facebook.com/original"]')).toHaveLength(1);
expect(harness.container.querySelectorAll('a[href="https://facebook.com/MUTATED-COPY"]')).toHaveLength(1);
});
test('Ctrl+C / Ctrl+V (useKeyboardShortcuts) on the real editor: pastes a fresh-id sibling copy, original untouched', () => {
harness = renderEditorHarness({ initialState: INITIAL_STATE });
const Consumer: React.FC = () => {
useKeyboardShortcuts();
return null;
};
harness.mountChild(<Consumer />);
// Select + copy social-1.
harness.act(() => {
harness!.actions.selectNode('social-1');
});
harness.act(() => {
document.dispatchEvent(
new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }),
);
});
expect(getClipboardNodeId()).toBe('social-1');
// Select heading-1 (a sibling), then paste -- should land as a sibling
// of heading-1's parent (ROOT), with brand-new ids.
harness.act(() => {
harness!.actions.selectNode('heading-1');
});
const before = Object.keys(harness.query.getNodes());
expect(() => {
harness!.act(() => {
document.dispatchEvent(
new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, bubbles: true, cancelable: true }),
);
});
}).not.toThrow();
const after = Object.keys(harness.query.getNodes());
expect(after).toHaveLength(before.length + 1);
const pastedId = after.find((id) => !before.includes(id))!;
expect(pastedId).toBeDefined();
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
expect(rootChildren).toContain(pastedId);
// Independent props copy again -- same class of bug, same guard.
const pastedProps = harness.query.node(pastedId).get().data.props;
const originalProps = harness.query.node('social-1').get().data.props;
expect(pastedProps.links).not.toBe(originalProps.links);
expect(pastedProps).toEqual(originalProps);
});
});
@@ -0,0 +1,161 @@
import { describe, test, expect, afterEach } from 'vitest';
import { renderEditorHarness, EditorHarness } from '../editorHarness';
import { allTemplates } from '../../templates';
import { buildNodeTree } from '../../utils/craft-tree';
import { templateComponentToTreeNode } from '../../templates/apply-template';
import { exportBodyHtml } from '../../utils/html-export';
/**
* Real-`@craftjs/core` integration coverage for loading a template.
*
* Historical bug: `TemplateModal.addTemplateComponents` used to build each
* template component via `React.createElement(Component, comp.props)` with
* NO children argument, silently dropping every nested `children` array
* authored in `templates/definitions.ts` (e.g. `makeHeader()`'s
* `Container > Logo + Menu`, `makeFooterContent()`'s `Container > TextBlock`,
* or any page `Section` wrapping a `Heading`/`ColumnLayout`). The resulting
* Craft.js node had `nodes: []`, so both the editor's own header/footer zone
* preview AND the published HTML (same `exportBodyHtml` path) rendered as an
* empty strip instead of the real nav/footer/section content. The mocked
* unit test for `templateComponentToTreeNode` (`apply-template.test.ts`)
* tests the pure conversion function in isolation and would pass either way
* -- it never drove the result through a real Craft.js tree/render, so it
* couldn't have caught `TemplateModal` itself dropping children at the
* call site.
*
* This suite drives the EXACT same path `TemplateModal.tsx`'s
* `addTemplateComponents` uses against a REAL Craft.js editor mounted with a
* REAL `<Frame>` (via `editorHarness.tsx`) -- so it also exercises real
* component rendering (Section/Container SHELL_INNER canvases, ColumnLayout
* linked columns), not just tree-shape assertions.
*/
const tpl = allTemplates.find((t) => t.id === 'saas-landing')!;
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
function addTemplateComponents(harness: EditorHarness, components: any[]) {
for (const comp of components) {
const tree = buildNodeTree(harness.query, templateComponentToTreeNode(comp));
harness.actions.addNodeTree(tree, 'ROOT');
}
}
const EMPTY_HEADER_ROOT = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'header' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
const EMPTY_FOOTER_ROOT = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' },
isCanvas: true,
props: { style: {}, tag: 'footer' },
displayName: 'Container',
custom: {},
hidden: false,
nodes: [],
linkedNodes: {},
},
});
let harness: EditorHarness | null = null;
afterEach(() => {
if (harness) {
harness.unmount();
harness = null;
}
});
describe('template load (real @craftjs/core editor + real <Frame> render)', () => {
test('sanity: the SaaS Landing template actually has nested header/footer/page content to lose', () => {
expect(tpl).toBeDefined();
expect(tpl.header.components.length).toBeGreaterThan(0);
expect(tpl.footer.components.length).toBeGreaterThan(0);
expect(tpl.pages[0].content.components.length).toBeGreaterThan(0);
const hasNestedChildren = tpl.header.components.some((c: any) => (c.children?.length ?? 0) > 0);
expect(hasNestedChildren).toBe(true);
});
test('loading the header keeps its nested nav links + logo -- both in the real DOM and in export', () => {
harness = renderEditorHarness({ initialState: EMPTY_HEADER_ROOT, frameTag: 'header' });
expect(() => {
harness!.act(() => addTemplateComponents(harness!, tpl.header.components));
}).not.toThrow();
// Real rendered DOM -- not just serialized state.
expect(harness.container.textContent).toContain('FlowStack');
expect(harness.container.textContent).toContain('Features');
expect(harness.container.textContent).toContain('Start Free');
const { html } = exportBodyHtml(harness.getSerialized());
expect(html).toContain('FlowStack');
expect(html).toContain('Features');
expect(html).toContain('Start Free');
});
test('loading the footer keeps its nested copyright/tagline content -- both in the real DOM and in export', () => {
harness = renderEditorHarness({ initialState: EMPTY_FOOTER_ROOT, frameTag: 'footer' });
expect(() => {
harness!.act(() => addTemplateComponents(harness!, tpl.footer.components));
}).not.toThrow();
expect(harness.container.textContent).toContain('FlowStack, Inc.');
expect(harness.container.textContent).toContain('Ship products faster');
const { html } = exportBodyHtml(harness.getSerialized());
expect(html).toContain('FlowStack, Inc.');
expect(html).toContain('Ship products faster');
});
test('loading the home page keeps a Section-wrapped Heading\'s nested content -- both in the real DOM and in export', () => {
const homePage = tpl.pages[0];
const sectionComp = homePage.content.components.find((c: any) => c.type === 'Section');
expect(sectionComp).toBeDefined();
expect(sectionComp!.children?.length).toBeGreaterThan(0);
harness = renderEditorHarness(); // default empty 'div' root, like a regular page
expect(() => {
harness!.act(() => addTemplateComponents(harness!, [sectionComp]));
}).not.toThrow();
expect(harness.container.textContent).toContain('Trusted by 10,000+ development teams');
const { html } = exportBodyHtml(harness.getSerialized());
expect(html).toContain('Trusted by 10,000+ development teams');
});
test('loading the FULL home page (all components) keeps every top-level node\'s content -- no silent drops', () => {
const homePage = tpl.pages[0];
harness = renderEditorHarness();
expect(() => {
harness!.act(() => addTemplateComponents(harness!, homePage.content.components));
}).not.toThrow();
// ROOT should have exactly as many direct children as the template
// defines top-level page components -- if children got dropped, nested
// content wouldn't show up in ROOT's descendant count via serialize, but
// an easier, more direct regression signal is: every top-level
// component's OWN text ends up rendered somewhere on the canvas.
const serialized = JSON.parse(harness.getSerialized());
const totalNodeCount = Object.keys(serialized).length;
// A flat (children-dropped) tree would have exactly
// homePage.content.components.length + 1 (ROOT) nodes. The real template
// has nested children, so a correct load must produce MORE nodes than
// that -- this is the shape-level assertion the pre-existing mocked test
// could never make (it never touched a real tree).
expect(totalNodeCount).toBeGreaterThan(homePage.content.components.length + 1);
});
});
+31
View File
@@ -147,6 +147,37 @@ describe('regenerateTreeIds', () => {
expect(input.nodes['root-1'].data.props).toEqual({ alignment: 'left' }); expect(input.nodes['root-1'].data.props).toEqual({ alignment: 'left' });
}); });
// Regression test (found via real-browser Playwright touch verification,
// Phase B): a LIVE Craft.js node's `data.type` is the actual component
// function reference (not the `{resolvedName}` string wrapper used only
// in SERIALIZED state) -- `query.node(id).toNodeTree()` returns nodes
// shaped exactly like this. The previous implementation ran
// `structuredClone(oldNode.data)` on the WHOLE data object, which throws
// `DataCloneError` the instant `data.type` is a function, silently
// breaking Duplicate (ContextMenu.tsx / useNodeActions.ts) and Ctrl+V
// Paste (useKeyboardShortcuts.ts) for every real node in the app --
// masked by every other test in this suite using a plain string `type`
// ('div'), and by unit tests elsewhere that mock `@craftjs/core` entirely
// (so `toNodeTree()` never actually returns a function there).
test('does not throw when data.type is a live component function reference', () => {
const ButtonLikeComponent = (props: { text?: string }) => props.text;
const input = makeTree();
input.nodes['root-1'].data.type = ButtonLikeComponent as unknown as Node['data']['type'];
input.nodes['root-1'].data.props = { text: 'Click Me' };
expect(() => regenerateTreeIds(input)).not.toThrow();
const output = regenerateTreeIds(input);
const outputRoot = output.nodes[output.rootNodeId];
// The component reference itself is preserved (shared, not cloned --
// it's a stable reference, not mutable data).
expect(outputRoot.data.type).toBe(ButtonLikeComponent);
// Props are still genuinely deep-cloned (the actual bug fix's point).
expect(outputRoot.data.props).toEqual({ text: 'Click Me' });
(outputRoot.data.props as { text: string }).text = 'changed';
expect(input.nodes['root-1'].data.props).toEqual({ text: 'Click Me' });
});
}); });
describe('flattenTreeForCraft', () => { describe('flattenTreeForCraft', () => {
+21 -6
View File
@@ -366,12 +366,27 @@ export function regenerateTreeIds(tree: NodeTree): NodeTree {
newLinkedNodes[slot] = remapId(linkedId); newLinkedNodes[slot] = remapId(linkedId);
} }
// Deep-clone data so mutable sub-objects (props, custom, etc.) are never // Deep-clone only the mutable sub-objects (props, custom) so they're
// shared by reference between the original node and its regenerated // never shared by reference between the original node and its
// copy. Craft.js's setProp mutates data.props in place, so a shallow // regenerated copy -- Craft.js's setProp mutates data.props in place, so
// copy here would let edits to the duplicate silently corrupt the // a shallow copy here would let edits to the duplicate silently corrupt
// original. // the original.
const clonedData = structuredClone(oldNode.data); //
// Deliberately NOT `structuredClone(oldNode.data)` as a whole: for a
// LIVE Craft.js node (as opposed to a plain serialized one), `data.type`
// is the actual component function/class reference (see the long
// comment on `buildNodeTree` above) -- `structuredClone` cannot clone a
// function and throws `DataCloneError`, which silently broke EVERY
// duplicate/paste in the real app (masked in unit tests that mock
// `@craftjs/core` with plain-data fake nodes, so `toNodeTree()` never
// actually returns a function there). `type` is a stable reference that
// both the original and the duplicate should point at unchanged, so it
// never needed cloning in the first place.
const clonedData = {
...oldNode.data,
props: structuredClone(oldNode.data.props),
custom: structuredClone(oldNode.data.custom),
};
const newNode: Node = { const newNode: Node = {
...oldNode, ...oldNode,