Compare commits

..
10 Commits
Author SHA1 Message Date
shadowdaoandClaude Opus 4.8 36c3b2f503 fix(builder): sanitize CSS-value sinks to prevent style/<style> breakout XSS
Adds a single cssValue() sanitizer (src/utils/escape.ts) that strips
<>{};"'\ and neutralizes url(), safe for both style="..." attribute and
<style>...</style> element contexts. Applies it at every raw user-prop
CSS-value interpolation sink found via grep across src/components (colors,
sizes, gaps interpolated directly into style strings/<style> blocks),
including the highest-risk <style>-context sinks: ColumnLayout gap,
Menu/Navbar hover and background colors. Also Number()-coerces the
`columns` grid-template-columns sinks in Gallery/Testimonials/NumberCounter
as defense in depth. Regression tests assert </style><script> payloads are
neutralized and normal colors still render.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:56:25 -07:00
shadowdaoandClaude Opus 4.8 5acf172511 docs(builder): update CLAUDE.md for hardening branch (remove dead settings/zones, asset picker)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:39:16 -07:00
shadowdaoandClaude Opus 4.8 ebb8fe1027 refactor(builder): type the AI-response/patch boundary
applyPatch's `ops` param was typed `any[]`, discarding the SitesmithPatchOp
discriminated union that SitesmithResponse.ops already carried at the call
site. Type it ops: SitesmithPatchOp[] so op.props/op.tree/op.op narrow
correctly per-variant in the switch instead of being `any`, and update the
unit tests' inline op literals to SitesmithPatchOp[] so tsc checks them too.

SerializedTreeNode/SitesmithPatchOp themselves, and buildNodeTree/
sanitizeAiTree's tree params, were already typed from a prior task -- this
closes the one remaining any at the op-handling site. Runtime validation
(protected-key guard, style-merge guard, unknown-resolvedName soft-skip) is
unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:30:56 -07:00
shadowdaoandClaude Opus 4.8 b88b242b6a refactor(builder): extract shared Modal component for the three editor modals
New src/ui/Modal.tsx ({ open, onClose, title?, children, width?,
closeOnEscape?, closeOnBackdropClick?, backdropStyle?, backdropProps? })
owns the backdrop, Escape-to-close, backdrop-click-to-close, and a new
body-scroll-lock while open. Adopted by TemplateModal, HeadCodeModal, and
SitesmithModal; each keeps its own panel styling/header/footer as children
since those differ per modal.

- TemplateModal: Escape/backdrop-click still close the confirm-template
  sub-dialog first via a wrapped onClose passed to Modal; the header's X
  button keeps using the raw onClose prop (always fully closes), matching
  prior asymmetric behavior.
- HeadCodeModal: straightforward adoption, no prior custom close logic.
- SitesmithModal: previously had no `open` prop, no Escape-to-close, and no
  backdrop-click-to-close. Preserved via open (always mounted-open by its
  parent already), closeOnEscape={false}, closeOnBackdropClick={false}; role
  and aria-modal are passed through via backdropProps to keep them on the
  same backdrop element as before.

Body scroll-lock while a modal is open is a small new addition (requested by
the task) applied uniformly; it has no visible effect since each modal's
opaque fixed-position backdrop already fully covers the viewport.

Added a light Modal.test.tsx (renders children, Escape/backdrop-click close
behavior, scroll-lock) using the existing react-dom/client + act harness.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:22:05 -07:00
shadowdaoandClaude Opus 4.8 8f51b5144a refactor(builder): extract shared ArrayItemFieldsEditor from SectionTypePanel/GenericPropsEditor
Both panels had a ~90-line near-byte-identical per-item field editor
(boolean->checkbox, number->number, /color/->color, long->textarea, else
text, fields derived from Object.keys(items[0])). Moved into a new
ArrayItemFieldsEditor component in ArrayItemFields.tsx used by both.
SectionTypePanel keeps its own FeaturesGrid special-case (key === 'features'
-> FeaturesEditor) and its empty-array guard ahead of the shared call.
Behavior-preserving (task E4.2).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:15:34 -07:00
shadowdaoandClaude Opus 4.8 4733fe84b5 refactor(builder): extract useNodeProp hook, dedup StylePanel setProp boilerplate
Adopted in BackgroundSectionStylePanel, ButtonStylePanel, ContainerStylePanel,
FormStylePanel, GenericPropsEditor, HeroStylePanel, ImageStylePanel,
MediaStylePanel, NavStylePanel, SectionTypePanel, SocialStylePanel,
TextStylePanel — only where the inline setProp/setPropStyle were behaviorally
identical to the hook. PricingStylePanel and FeaturesEditor keep their own
array-mutation logic since it differs. Behavior-preserving (task E4.1).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:13:35 -07:00
shadowdaoandClaude Opus 4.8 3cd4ad0154 test(builder): cover Ctrl+C/V shortcut id-regeneration and guards
Regression coverage for the safety-sensitive part of keyboard copy/paste:
nothing previously tested that Ctrl/Cmd+V regenerates node ids via
regenerateTreeIds before actions.addNodeTree -- the exact logic whose
absence caused a duplicate-id corruption bug. Also covers sibling-parent
targeting (with ROOT fallback), the empty-clipboard no-op, and the
existing input/contentEditable focus guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:08:46 -07:00
shadowdaoandClaude Opus 4.8 6421306849 feat(builder): implement Ctrl+C/V copy-paste shortcuts
The context menu advertised Ctrl+C/Ctrl+V hints but useKeyboardShortcuts
only handled undo/redo/delete/duplicate/escape -- pressing them did
nothing. Add a tiny shared module-level clipboard (src/hooks/clipboard.ts)
used by both the keyboard hook and the context menu so copying via one
entry point and pasting via the other stay consistent.

Ctrl/Cmd+C stores the selected node id (skipping ROOT). Ctrl/Cmd+V
inserts a copy as a sibling of the current selection via
regenerateTreeIds, mirroring the existing context-menu paste behavior.
Both respect the existing "disabled while typing" guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 15:01:30 -07:00
shadowdaoandClaude Opus 4.8 e40d55b2f2 chore(builder): point dev proxy at current test server
192.168.1.105 was decommissioned; local npm run dev save/load now
proxies /api to the current test server (whp-al10-test, .148).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 14:59:42 -07:00
shadowdaoandClaude Opus 4.8 1958b8e0b5 chore(builder): remove GuidedStyles classification cruft
Drop the computed-but-unused resolvedName/resolverMap, anchor the hero
regex (/^hero/i) so it stops matching any type name containing "hero",
and remove the isContainer alternations for the now-deleted
HeaderZone/FooterZone components.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-12 14:59:39 -07:00
53 changed files with 1143 additions and 571 deletions
+58 -46
View File
@@ -41,14 +41,12 @@ craft/
│ │ └── Canvas.tsx # Craft.js <Frame> with device-width switching
│ │
│ ├── components/
│ │ ├── resolver.ts # Component map for Craft.js serialization (20 components)
│ │ ├── resolver.ts # Component map for Craft.js serialization (39 components)
│ │ ├── layout/
│ │ │ ├── Container.tsx # Generic container (div/section/article/header/footer/main)
│ │ │ ├── Section.tsx # Full-width section with centered inner container
│ │ │ ├── ColumnLayout.tsx # Flex columns (1-6, with split ratios)
│ │ │ ├── BackgroundSection.tsx # Section with background image/gradient overlay
│ │ │ ├── HeaderZone.tsx # Page-level header zone wrapper
│ │ │ └── FooterZone.tsx # Page-level footer zone wrapper
│ │ │ └── BackgroundSection.tsx # Section with background image/gradient overlay
│ │ ├── basic/
│ │ │ ├── Heading.tsx # Inline-editable heading (h1-h6)
│ │ │ ├── TextBlock.tsx # Inline-editable paragraph
@@ -73,7 +71,8 @@ craft/
│ ├── panels/
│ │ ├── topbar/
│ │ │ ├── TopBar.tsx # Back button, domain badge, device switcher, undo/redo, save, templates
│ │ │ └── TemplateModal.tsx # Template browser with categories and one-click loading
│ │ │ ├── TemplateModal.tsx # Template browser with categories and one-click loading
│ │ │ └── HeadCodeModal.tsx # Edits SiteDesign.headCode (site-wide, not per-page)
│ │ ├── left/
│ │ │ ├── LeftPanel.tsx # Tabs: Blocks | Pages | Layers | Assets
│ │ │ ├── BlocksPanel.tsx # Draggable block toolbox with categories
@@ -81,9 +80,10 @@ craft/
│ │ │ ├── LayersPanel.tsx # Component hierarchy tree view
│ │ │ └── AssetsPanel.tsx # Asset browser with upload, drag-drop, thumbnails
│ │ ├── right/
│ │ │ ├── RightPanel.tsx # Tabs: Styles | Settings | Head
│ │ │ ├── GuidedStyles.tsx # Context-aware style panel (shows selected type)
│ │ │ └── SiteDesignPanel.tsx # Site-wide design tokens editor (Basic/Advanced tabs)
│ │ │ ├── RightPanel.tsx # Single "Styles" tab -- renders GuidedStyles only
│ │ │ ├── GuidedStyles.tsx # Context-aware dispatcher: picks a StylePanel by selected type
│ │ │ ├── SiteDesignPanel.tsx # Site-wide design tokens editor (Basic/Advanced tabs)
│ │ │ └── styles/ # Per-type StylePanels (Text, Button, Image, Container, Nav, Form, etc.)
│ │ └── context-menu/
│ │ └── ContextMenu.tsx # Right-click context menu (duplicate, copy, paste, delete, etc.)
│ │
@@ -98,7 +98,8 @@ craft/
│ │ └── definitions.ts # 16 template definitions across 4 categories
│ │
│ ├── ui/
│ │ └── SettingsTabs.tsx # Reusable General/Style/Advanced tabs for component settings
│ │ ├── AssetPicker.tsx # Reusable image/video source picker (upload/browse-uploaded/URL), full+compact variants
│ │ └── Modal.tsx # Reusable modal dialog shell
│ │
│ ├── constants/
│ │ └── presets.ts # Color, font, spacing, radius, gradient, device width presets
@@ -165,7 +166,7 @@ The PHP wrapper (`/docker/whp/web/site-builder/index.php`) injects `WHP_CONFIG`
5. **API compatibility** - The save endpoint sends data in the same format as the GrapesJS version (`{ site_id, name, html, css, grapesjs: serializedJson }`), so the PHP backend doesn't need changes.
6. **Component-based architecture** - Each visual element is a React component that doubles as a Craft.js `UserComponent`. All rendering, settings UI, and HTML export are co-located in one file.
6. **Component-based architecture** - Each visual element is a React component that doubles as a Craft.js `UserComponent`. Rendering and HTML export are co-located in one file; style editing is handled by a shared per-type `StylePanel` in `src/panels/right/styles/` rather than a per-component settings panel.
7. **Site Design Tokens** - A `SiteDesignContext` provides 17 design properties (colors, fonts, radii, nav style) that components can reference. Templates import their own design tokens when loaded.
@@ -188,28 +189,21 @@ export const MyComponent: UserComponent<MyComponentProps> = ({ text, style }) =>
return <div ref={(r) => { if (r) connect(drag(r)); }} style={style}>{text}</div>;
};
// 3. Settings panel (rendered in right panel when selected)
const MyComponentSettings: React.FC = () => {
const { actions: { setProp }, props } = useNode((node) => ({
props: node.data.props as MyComponentProps,
}));
return <div>/* preset buttons, inputs, etc. */</div>;
};
// 4. Craft config (displayName, default props, rules, related settings)
// 3. Craft config (displayName, default props, rules)
MyComponent.craft = {
displayName: 'My Component',
props: { text: 'Default text', style: {} },
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
related: { settings: MyComponentSettings },
};
// 5. HTML export (static method for serializing to HTML string)
// 4. HTML export (static method for serializing to HTML string)
(MyComponent as any).toHtml = (props: MyComponentProps, childrenHtml: string) => {
return { html: `<div style="...">${childrenHtml}</div>` };
};
```
Style editing for the new type is added separately as a `StylePanel` under `src/panels/right/styles/` (or reuses an existing generic one), and wired into `GuidedStyles.tsx`'s type dispatch -- components no longer carry their own settings UI.
### Component Resolver
All components must be registered in `src/components/resolver.ts`. This map is passed to `<Editor resolver={componentResolver}>` so Craft.js can serialize/deserialize the node tree.
@@ -270,7 +264,7 @@ The editor auto-saves every 30 seconds when running inside WHP. The save status
- `whpConfig` - The full config object (or null in standalone mode)
- `isWHP` - Boolean shorthand for whether we're running inside WHP
## All Components (22)
## All Components (39)
| # | Component | Type | File | Features |
|---|-----------|------|------|----------|
@@ -278,24 +272,41 @@ The editor auto-saves every 30 seconds when running inside WHP. The save status
| 2 | Section | Layout | `layout/Section.tsx` | Full-width with centered inner container, bg color/gradient, vertical padding, inner max-width |
| 3 | ColumnLayout | Layout | `layout/ColumnLayout.tsx` | 1-6 columns, split ratios (50-50, 30-70, 70-30, 33-33-33, 25-25-25-25, etc.), gap control |
| 4 | BackgroundSection | Layout | `layout/BackgroundSection.tsx` | Section with background image, gradient overlay, parallax-ready |
| 5 | HeaderZone | Layout | `layout/HeaderZone.tsx` | Page-level header wrapper zone, used by PageContext |
| 6 | FooterZone | Layout | `layout/FooterZone.tsx` | Page-level footer wrapper zone, used by PageContext |
| 7 | Heading | Basic | `basic/Heading.tsx` | Inline-editable, h1-h6 level, color, font family/size/weight, text align |
| 8 | TextBlock | Basic | `basic/TextBlock.tsx` | Inline-editable paragraph, color, font family/size/weight, text align, line height |
| 9 | ButtonLink | Basic | `basic/ButtonLink.tsx` | Link text/URL/target, 8 color presets (auto text contrast), radius, padding, font size |
| 5 | Heading | Basic | `basic/Heading.tsx` | Inline-editable, h1-h6 level, color, font family/size/weight, text align |
| 6 | TextBlock | Basic | `basic/TextBlock.tsx` | Inline-editable paragraph, color, font family/size/weight, text align, line height |
| 7 | ButtonLink | Basic | `basic/ButtonLink.tsx` | Link text/URL/target, 8 color presets (auto text contrast), radius, padding, font size |
| 8 | Logo | Basic | `basic/Logo.tsx` | Text or image logo, link href, font family/size/weight, image width |
| 9 | Menu | Basic | `basic/Menu.tsx` | Link list with optional CTA styling, horizontal/vertical orientation, alignment, hover colors |
| 10 | Navbar | Basic | `basic/Navbar.tsx` | Text or image logo, page links, external links, CTA buttons, light/dark nav style |
| 11 | Footer | Basic | `basic/Footer.tsx` | Footer with links, copyright, social links |
| 12 | Divider | Basic | `basic/Divider.tsx` | Horizontal rule with color and thickness controls |
| 13 | Spacer | Basic | `basic/Spacer.tsx` | Vertical spacing element with height control |
| 14 | ImageBlock | Media | `media/ImageBlock.tsx` | SVG placeholder, URL input, upload, browse assets, alt text, width/height, object-fit, radius |
| 15 | VideoBlock | Media | `media/VideoBlock.tsx` | YouTube, Vimeo, direct files (.mp4/.webm/.ogg), background mode, autoplay, loop |
| 16 | HeroSimple | Section | `sections/HeroSimple.tsx` | Pre-built hero with heading, subtext, CTA button, gradient/color background |
| 17 | FeaturesGrid | Section | `sections/FeaturesGrid.tsx` | 3-column feature cards with icons, titles, descriptions |
| 18 | CTASection | Section | `sections/CTASection.tsx` | Call-to-action banner with heading, text, button |
| 19 | FormContainer | Form | `forms/FormContainer.tsx` | Form wrapper with action URL and method |
| 20 | InputField | Form | `forms/InputField.tsx` | Text input with label, placeholder, type (text/email/tel/password/number) |
| 21 | TextareaField | Form | `forms/TextareaField.tsx` | Textarea with label and placeholder |
| 22 | FormButton | Form | `forms/FormButton.tsx` | Submit button with color and style controls |
| 14 | Icon | Basic | `basic/Icon.tsx` | Font Awesome icon, size/color, background shape, optional link |
| 15 | ImageBlock | Media | `media/ImageBlock.tsx` | SVG placeholder, URL input, upload, browse assets, alt text, width/height, object-fit, radius |
| 16 | VideoBlock | Media | `media/VideoBlock.tsx` | YouTube, Vimeo, direct files (.mp4/.webm/.ogg), background mode, autoplay, loop |
| 17 | MapEmbed | Media | `media/MapEmbed.tsx` | Embedded map by address, zoom level, height |
| 18 | HeroSimple | Section | `sections/HeroSimple.tsx` | Pre-built hero with heading, subtext, CTA button, gradient/color background |
| 19 | FeaturesGrid | Section | `sections/FeaturesGrid.tsx` | 3-column feature cards with icons, titles, descriptions |
| 20 | CTASection | Section | `sections/CTASection.tsx` | Call-to-action banner with heading, text, button |
| 21 | Countdown | Section | `sections/Countdown.tsx` | Countdown timer to a target date, heading, digit/label colors |
| 22 | Testimonials | Section | `sections/Testimonials.tsx` | Grid or single-layout testimonial cards, star color, card background |
| 23 | FormContainer | Form | `forms/FormContainer.tsx` | Form wrapper with action URL and method |
| 24 | InputField | Form | `forms/InputField.tsx` | Text input with label, placeholder, type (text/email/tel/password/number) |
| 25 | TextareaField | Form | `forms/TextareaField.tsx` | Textarea with label and placeholder |
| 26 | FormButton | Form | `forms/FormButton.tsx` | Submit button with color and style controls |
| 27 | ContactForm | Form | `forms/ContactForm.tsx` | Configurable field list, recipient email, success message or thank-you URL redirect |
| 28 | StarRating | Basic | `basic/StarRating.tsx` | Star rating display, rating/max stars, filled/empty color |
| 29 | SocialLinks | Basic | `basic/SocialLinks.tsx` | Social icon links, size/color/shape, gap, alignment |
| 30 | CallToAction | Section | `sections/CallToAction.tsx` | Heading/description with 1-2 buttons, color/gradient/image background with overlay |
| 31 | Accordion | Section | `sections/Accordion.tsx` | Expand/collapse item list, header/content colors |
| 32 | Tabs | Section | `sections/Tabs.tsx` | Tabbed content panels, active/inactive tab colors |
| 33 | PricingTable | Section | `sections/PricingTable.tsx` | Pricing plan cards, featured plan highlight, bullet list |
| 34 | Gallery | Section | `sections/Gallery.tsx` | Image grid gallery, configurable columns/gap, optional lightbox |
| 35 | ContentSlider | Section | `sections/ContentSlider.tsx` | Auto-playing image/content slider, dots/arrows, configurable interval |
| 36 | NumberCounter | Section | `sections/NumberCounter.tsx` | Animated stat counters, columns, number/label colors |
| 37 | SubscribeForm | Form | `forms/SubscribeForm.tsx` | Inline/stacked email signup form, heading, button color |
| 38 | SearchBar | Basic | `basic/SearchBar.tsx` | Search input with optional button, placeholder text |
| 39 | HtmlBlock | Basic | `basic/HtmlBlock.tsx` | Raw/custom HTML embed block, sanitized on export |
## Site Design Tokens
@@ -351,7 +362,7 @@ Templates are loaded via the Template Modal (opened from TopBar). Loading a temp
## Multi-Page System
Pages are managed through `PageContext`:
- Each page has: `id`, `name`, `slug`, `craftState`, `headCode`
- Each page has: `id`, `name`, `slug`, `craftState` (`headCode` is site-wide only, on `SiteDesignContext`/`SiteDesign`, edited via the TopBar's Head Code modal -- not a per-page field)
- Header and Footer are stored as separate "page" entries with fixed IDs (`__header__`, `__footer__`)
- Page switching serializes the current canvas, stores it, then deserializes the target page
- Header/Footer editing puts the canvas in a distinct mode
@@ -392,21 +403,22 @@ The Assets panel (`AssetsPanel.tsx`) provides:
- Delete asset
- Integration with WHP API for server-side storage
Image and Video components also have inline asset selection (browse button in settings).
Image and video fields elsewhere in the editor (ImageStylePanel, MediaStylePanel, HeroStylePanel, NavStylePanel, BackgroundSectionStylePanel, and array-editor cards like FeaturesEditor) use the shared `AssetPicker` (`src/ui/AssetPicker.tsx`) for upload / browse-uploaded / paste-URL, in a `full` or `compact` variant depending on space.
## Adding New Components
1. Create `src/components/<category>/<ComponentName>.tsx` following the pattern above
2. Add the component to `src/components/resolver.ts`
3. Add a block entry in `src/panels/left/BlocksPanel.tsx` under the appropriate category
4. Implement the `toHtml` static for HTML export
5. Build and test: `npm run dev`, drag the block onto the canvas, verify settings panel, verify HTML export
4. Add or extend a `StylePanel` in `src/panels/right/styles/` and wire it into `GuidedStyles.tsx`'s type dispatch so the new component is editable when selected
5. Implement the `toHtml` static for HTML export
6. Build and test: `npm run dev`, drag the block onto the canvas, verify the style panel, verify HTML export
### Checklist for a new component:
- [ ] Props interface with `style?: CSSProperties`
- [ ] `useNode()` with `connect(drag(ref))` on the root element
- [ ] Settings panel using `useNode()` with `setProp()`
- [ ] `.craft` config with `displayName`, default `props`, `rules`, `related.settings`
- [ ] `StylePanel` entry (new or reused) wired into `GuidedStyles.tsx`
- [ ] `.craft` config with `displayName`, default `props`, `rules`
- [ ] `.toHtml()` static method using `cssPropsToString()`
- [ ] Registered in `resolver.ts`
- [ ] Block added to `BlocksPanel.tsx`
@@ -421,7 +433,7 @@ The editor uses a dark theme defined via CSS custom properties in `src/styles/ed
- **Border:** `#2d2d3a`
- **Font:** Inter
All editor chrome (panels, topbar, settings) is styled via `editor.css`. User content on the canvas uses inline styles exclusively.
All editor chrome (panels, topbar, style panels) is styled via `editor.css`. User content on the canvas uses inline styles exclusively.
## Presets
@@ -446,7 +458,7 @@ Every component has a static `toHtml(props, childrenHtml)` method. The `html-exp
## Testing Approach
- **Manual testing:** Run `npm run dev`, drag components, edit props, verify settings panels
- **Manual testing:** Run `npm run dev`, drag components, edit props, verify style panels
- **Type checking:** `tsc --noEmit` (part of build step)
- **HTML export:** Verify `toHtml()` output matches expected HTML structure
- **Device preview:** Switch between desktop/tablet/mobile and verify responsive behavior
@@ -455,9 +467,9 @@ Every component has a static `toHtml(props, childrenHtml)` method. The `html-exp
## Development Notes
- Path alias `@/` maps to `./src/` (configured in both tsconfig.json and vite.config.ts)
- `GuidedStyles` shows selected component type and delegates to per-component settings panels
- `GuidedStyles` shows the selected component type and dispatches to a shared `StylePanel` in `src/panels/right/styles/` (components no longer carry their own settings UI)
- Text components (Heading, TextBlock) use `contentEditable` for inline editing when selected
- Button/link navigation is prevented in the editor via `e.preventDefault()`
- Image upload integrates with WHP API; in standalone mode falls back to local `blob:` URLs
- Auto-save runs every 30 seconds when connected to WHP API
- The SettingsTabs UI component provides a reusable General/Style/Advanced tab layout for component settings
- `AssetPicker` (`src/ui/AssetPicker.tsx`) is the shared upload/browse/URL control reused across StylePanels for every image and video field
@@ -30,3 +30,17 @@ describe('Menu.toHtml deterministic + unique scope ids (thread node id, no Math.
expect(html1).toBe(html2);
});
});
describe('Menu.toHtml XSS hardening (linkHoverColor into <style>)', () => {
test('a linkHoverColor value containing </style><script> is neutralized', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
const { html } = toHtml({ linkHoverColor: malicious }, '', 'node-xss');
expect(html).not.toContain('</style><script');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a normal linkHoverColor still renders in the hover rule', () => {
const { html } = toHtml({ linkHoverColor: '#ff0000' }, '', 'node-normal');
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
});
});
+11 -7
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, useState } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
/* ---------- Types ---------- */
@@ -125,14 +125,18 @@ Menu.craft = {
/* ---------- HTML export ---------- */
(Menu as any).toHtml = (props: MenuProps, _childrenHtml: string, nodeId?: string) => {
const linkCol = props.linkColor || '#3f3f46';
const hoverCol = props.linkHoverColor || '#3b82f6';
const ctaBg = props.ctaBgColor || '#3b82f6';
const ctaText = props.ctaTextColor || '#ffffff';
const gap = props.gap || '24px';
// Sanitized once here -- linkCol/hoverCol/ctaBg/ctaText/gap/fSize are raw
// string-interpolation sinks below (hoverCol goes into a <style> block,
// the worst case: </style> breakout -> arbitrary <script>), see
// task-cssxss-brief.md.
const linkCol = cssValue(props.linkColor) || '#3f3f46';
const hoverCol = cssValue(props.linkHoverColor) || '#3b82f6';
const ctaBg = cssValue(props.ctaBgColor) || '#3b82f6';
const ctaText = cssValue(props.ctaTextColor) || '#ffffff';
const gap = cssValue(props.gap) || '24px';
const orientation = props.orientation || 'horizontal';
const alignment = props.alignment || 'right';
const fSize = props.fontSize || '14px';
const fSize = cssValue(props.fontSize) || '14px';
const justifyMap: Record<string, string> = { left: 'flex-start', center: 'center', right: 'flex-end' };
@@ -26,3 +26,38 @@ describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
expect(html).not.toContain('navbar-hamburger');
});
});
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
const malicious = '#fff}</style><script>alert(1)</script><style>{';
const { html } = toHtml({ hoverColor: malicious }, '');
expect(html).not.toContain('</style><script');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a backgroundColor value containing </style><script> is neutralized (mobile media-query rule)', () => {
const malicious = '#fff}</style><script>alert(2)</script><style>{';
const { html } = toHtml({ backgroundColor: malicious, showMobileMenu: true }, '');
expect(html).not.toContain('</style><script');
expect(html).not.toContain('<script>alert(2)</script>');
});
test('a ctaColor value containing </style><script> is neutralized', () => {
const malicious = '#fff}</style><script>alert(3)</script><style>{';
const { html } = toHtml({ ctaColor: malicious }, '');
expect(html).not.toContain('</style><script');
expect(html).not.toContain('<script>alert(3)</script>');
});
test('a textColor value containing a quote breakout does not escape the hamburger span style attribute', () => {
const malicious = '#333" onmouseover="alert(1)';
const { html } = toHtml({ textColor: malicious, showMobileMenu: true }, '');
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
});
test('normal colors still render correctly', () => {
const { html } = toHtml({ hoverColor: '#ff0000', backgroundColor: '#123456', ctaColor: '#00ff00' }, '');
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
expect(html).toContain('background-color:#123456');
});
});
+10 -7
View File
@@ -2,7 +2,7 @@ import React, { CSSProperties, useState } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { useSiteDesign } from '../../state/SiteDesignContext';
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
/* ---------- Types ---------- */
@@ -211,12 +211,15 @@ Navbar.craft = {
/* ---------- HTML export ---------- */
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string) => {
const bgColor = props.backgroundColor || '#ffffff';
const textCol = props.textColor || '#3f3f46';
const hoverCol = props.hoverColor || '#3b82f6';
const ctaCol = props.ctaColor || '#3b82f6';
const ctaTextCol = props.ctaTextColor || '#ffffff';
const pad = props.padding || '16px 24px';
// Sanitized once here -- these are raw string-interpolation sinks below
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
const bgColor = cssValue(props.backgroundColor) || '#ffffff';
const textCol = cssValue(props.textColor) || '#3f3f46';
const hoverCol = cssValue(props.hoverColor) || '#3b82f6';
const ctaCol = cssValue(props.ctaColor) || '#3b82f6';
const ctaTextCol = cssValue(props.ctaTextColor) || '#ffffff';
const pad = cssValue(props.padding) || '16px 24px';
const alignment = props.navAlignment || 'space-between';
const sticky = props.isSticky;
const mobile = props.showMobileMenu;
+5 -4
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeAttr, safeUrl } from '../../utils/escape';
import { escapeAttr, safeUrl, cssValue } from '../../utils/escape';
interface SocialLink {
platform: string;
@@ -163,9 +163,10 @@ SocialLinks.craft = {
(SocialLinks as any).toHtml = (props: SocialLinksProps, _childrenHtml: string) => {
const links = props.links || defaultLinks;
const iconSize = props.iconSize || '20px';
const iconColor = props.iconColor || '#ffffff';
const iconBgColor = props.iconBgColor || '#374151';
// Sanitized -- raw string-interpolation sinks in aStyle/getShapeStr below.
const iconSize = cssValue(props.iconSize) || '20px';
const iconColor = cssValue(props.iconColor) || '#ffffff';
const iconBgColor = cssValue(props.iconBgColor) || '#374151';
const iconShape = props.iconShape || 'circle';
const gap = props.gap || '10px';
const alignment = props.alignment || 'center';
@@ -21,3 +21,22 @@ describe('StarRating.toHtml accessibility (F2.2)', () => {
expect(html).toContain('aria-label="Rating: 2 out of 10"');
});
});
describe('StarRating.toHtml XSS hardening (filledColor/emptyColor/size into style=)', () => {
test('a filledColor value containing a quote breakout is neutralized', () => {
const malicious = '#f00" onmouseover="alert(1)';
const { html } = toHtml({ rating: 3, maxStars: 5, filledColor: malicious }, '');
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
});
test('a size value containing </style><script> is neutralized', () => {
const malicious = '24px</style><script>alert(1)</script>';
const { html } = toHtml({ rating: 3, maxStars: 5, size: malicious }, '');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a normal filled color still renders', () => {
const { html } = toHtml({ rating: 5, maxStars: 5, filledColor: '#ff9900' }, '');
expect(html).toContain('color:#ff9900');
});
});
+5 -3
View File
@@ -1,6 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { cssValue } from '../../utils/escape';
interface StarRatingProps {
rating?: number;
@@ -99,9 +100,10 @@ StarRating.craft = {
(StarRating as any).toHtml = (props: StarRatingProps, _childrenHtml: string) => {
const rating = props.rating ?? 4.5;
const maxStars = props.maxStars || 5;
const size = props.size || '24px';
const filledColor = props.filledColor || '#f59e0b';
const emptyColor = props.emptyColor || '#d1d5db';
// Sanitized -- raw string-interpolation sinks in the star glyphs below.
const size = cssValue(props.size) || '24px';
const filledColor = cssValue(props.filledColor) || '#f59e0b';
const emptyColor = cssValue(props.emptyColor) || '#d1d5db';
const wrapperStyle = cssPropsToString({
display: 'inline-flex',
alignItems: 'center',
+6 -4
View File
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { relayFormWiring } from '../../utils/form-relay-wiring';
import { escapeHtml, escapeAttr, slugId } from '../../utils/escape';
import { escapeHtml, escapeAttr, slugId, cssValue } from '../../utils/escape';
interface ContactFormField {
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
@@ -175,9 +175,11 @@ ContactForm.craft = {
gap: '20px',
...props.style,
});
const labelColor = props.labelColor || '#374151';
const inputBg = props.inputBg || '#ffffff';
const inputBorder = props.inputBorder || '#d1d5db';
// Sanitized -- raw string-interpolation sinks in inputStyleStr/labelHtml
// below.
const labelColor = cssValue(props.labelColor) || '#374151';
const inputBg = cssValue(props.inputBg) || '#ffffff';
const inputBorder = cssValue(props.inputBorder) || '#d1d5db';
const inputStyleStr = `width:100%;padding:10px 14px;font-size:14px;font-family:Inter,sans-serif;border:1px solid ${inputBorder};border-radius:6px;background-color:${inputBg};color:#1f2937;box-sizing:border-box;outline:none`;
const fieldsHtml = (props.fields || defaultFields).map((field, i) => {
@@ -59,3 +59,24 @@ describe('ColumnLayout.toHtml deterministic + unique scope ids (thread node id,
expect(html1).toBe(html2);
});
});
describe('ColumnLayout.toHtml XSS hardening (gap into <style>)', () => {
test('a gap value containing </style><script> is neutralized in the <style>-context nth-child rule', () => {
const malicious = '0px)}</style><script>alert(1)</script><style>{';
const { html } = toHtml({ columns: 2, split: '50-50', gap: malicious }, '<div>A</div><div>B</div>', 'node-xss');
expect(html).not.toContain('</style><script');
expect(html).not.toContain('<script>alert(1)</script>');
});
test('a gap value containing a quote/semicolon breakout is neutralized in the style attribute', () => {
const malicious = '16px" onmouseover="alert(1)';
const { html } = toHtml({ columns: 2, split: '50-50', gap: malicious }, '', 'node-xss2');
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
});
test('a normal gap value still renders correctly', () => {
const { html } = toHtml({ columns: 2, split: '50-50', gap: '24px' }, '<div>A</div>', 'node-normal');
expect(html).toContain('gap:24px');
expect(html).toMatch(/calc\(50% - 24px\)/);
});
});
+6 -2
View File
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
import { useNode, Element, UserComponent } from '@craftjs/core';
import { Container } from './Container';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeAttr, scopeId } from '../../utils/escape';
import { escapeAttr, scopeId, cssValue } from '../../utils/escape';
type SplitOption =
| '100'
@@ -117,7 +117,11 @@ ColumnLayout.craft = {
(ColumnLayout as any).toHtml = (props: ColumnLayoutProps, childrenHtml: string, nodeId?: string) => {
const columns = props.columns || 2;
const split = props.split || '50-50';
const gap = props.gap || '16px';
// Sanitized once here so BOTH the raw <style> nth-child rule below AND the
// cssPropsToString-built outerStyle get a safe value -- gap is a raw
// string-interpolation sink into a <style> block (worst case: </style>
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
const gap = cssValue(props.gap) || '16px';
const widths = getWidths(split, columns);
const outerStyle = cssPropsToString({
+3 -2
View File
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
import { useNode, Element, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { Container } from './Container';
import { escapeAttr } from '../../utils/escape';
import { escapeAttr, cssValue } from '../../utils/escape';
/* ---------- Shape Divider SVG Paths ---------- */
@@ -167,7 +167,8 @@ function buildDividerHtml(
const isTop = position === 'top';
const h = height || '50px';
const c = color || '#ffffff';
// Sanitized -- raw string-interpolation sink in the SVG `fill:${c}` below.
const c = cssValue(color) || '#ffffff';
const wrapperStyle = cssPropsToString({
position: 'absolute',
+7 -5
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, useState } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr } from '../../utils/escape';
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
interface AccordionItem {
title: string;
@@ -151,10 +151,12 @@ Accordion.craft = {
...props.style,
});
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
const headerBg = props.headerBg || '#f8fafc';
const headerColor = props.headerColor || '#18181b';
const contentBg = props.contentBg || '#ffffff';
const borderColor = props.borderColor || '#e2e8f0';
// Sanitized -- raw string-interpolation sinks in the <details>/<summary>
// style attributes below.
const headerBg = cssValue(props.headerBg) || '#f8fafc';
const headerColor = cssValue(props.headerColor) || '#18181b';
const contentBg = cssValue(props.contentBg) || '#ffffff';
const borderColor = cssValue(props.borderColor) || '#e2e8f0';
const items = props.items || defaultItems;
const panels = items.map((item, i) => {
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { CtaButton, normalizeCtas, ctaInlineStyle, ctasToHtml } from './_cta-helpers';
import { escapeHtml, escapeAttr } from '../../utils/escape';
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
interface CallToActionProps {
heading?: string;
@@ -144,7 +144,9 @@ CallToAction.craft = {
(CallToAction as any).toHtml = (props: CallToActionProps, _childrenHtml: string) => {
const bgType = props.bgType || 'gradient';
const bgValue = props.bgValue || defaultGradient;
const textColor = props.textColor || '#ffffff';
// Sanitized -- raw string-interpolation sink in the heading/description
// style attributes below.
const textColor = cssValue(props.textColor) || '#ffffff';
const buttonColor = props.buttonColor || '#ffffff';
const isButtonDark = buttonColor === '#ffffff' || buttonColor === '#f8fafc';
const buttonTextColor = isButtonDark ? '#18181b' : '#ffffff';
@@ -1,7 +1,7 @@
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
interface Slide {
type: 'image' | 'content';
@@ -266,11 +266,14 @@ ContentSlider.craft = {
const slidesHtml = items.map((slide, i) => {
const hasBgImage = slide.imageSrc;
// Sanitized -- slide.bgColor is a per-slide raw string-interpolation
// sink (a malicious value could break out of the style="..." attribute).
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
const bgStyle = hasBgImage
? `background-image:url('${escapeAttr(safeUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
: slide.bgColor?.startsWith('linear-gradient')
? `background-image:${slide.bgColor}`
: `background-color:${slide.bgColor || '#3b82f6'}`;
? `background-image:${safeBgColor}`
: `background-color:${safeBgColor}`;
const contentParts: string[] = [];
if (slide.heading) {
+5 -3
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, useEffect, useState } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
interface CountdownProps {
targetDate?: string;
@@ -154,10 +154,12 @@ Countdown.craft = {
targetDate = DEFAULT_TARGET,
heading = 'Coming Soon',
style = {},
digitColor = '#ffffff',
labelColor = 'rgba(255,255,255,0.7)',
bgColor = '#18181b',
} = props;
// Sanitized -- raw string-interpolation sinks in the heading/digit/label
// style attributes below.
const digitColor = cssValue(props.digitColor) || '#ffffff';
const labelColor = cssValue(props.labelColor) || 'rgba(255,255,255,0.7)';
const sectionStyle = cssPropsToString({
padding: '60px 20px',
+9 -3
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, safeUrl, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
interface GalleryImage {
src: string;
@@ -130,8 +130,14 @@ Gallery.craft = {
...props.style,
});
const images = props.images || defaultImages;
const columns = props.columns || 3;
const gap = props.gap || '16px';
// Number() coercion: `columns` is a raw string-interpolation sink into the
// grid style attribute below (repeat(${columns},1fr)) -- a non-numeric
// (e.g. hand-crafted/AI-generated tree) value would otherwise be able to
// break out; Number() of anything non-numeric collapses safely to NaN.
const columns = Number(props.columns) || 3;
// Sanitized -- gap is a raw string-interpolation sink into the grid style
// attribute below.
const gap = cssValue(props.gap) || '16px';
const lightbox = props.lightbox || false;
// Deterministic AND unique id, scoped on the Craft node id, for this
+6 -4
View File
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { CtaButton, normalizeCtas, ctaInlineStyle, ctasToHtml } from './_cta-helpers';
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
interface HeroProps {
heading?: string;
@@ -220,7 +220,8 @@ HeroSimple.craft = {
let overlayHtml = '';
if ((props.overlayOpacity || 0) > 0) {
overlayHtml = `<div style="position:absolute;top:0;left:0;right:0;bottom:0;background-color:${props.overlayColor || '#000'};opacity:${(props.overlayOpacity || 0) / 100};z-index:1"></div>`;
const overlayColor = cssValue(props.overlayColor) || '#000';
overlayHtml = `<div style="position:absolute;top:0;left:0;right:0;bottom:0;background-color:${overlayColor};opacity:${(props.overlayOpacity || 0) / 100};z-index:1"></div>`;
}
let videoHtml = '';
@@ -239,12 +240,13 @@ HeroSimple.craft = {
});
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
const heroTextColor = cssValue(props.textColor) || '#fff';
return {
html: `<section${idAttr} style="${sectionStyle}">
${videoHtml}${overlayHtml}
<div style="max-width:800px;width:100%;position:relative;z-index:2;text-align:${textAlign}">
<h1 style="font-size:48px;font-weight:700;color:${props.textColor || '#fff'};margin-bottom:16px;line-height:1.2">${escapeHtml(props.heading || '')}</h1>
<p style="font-size:20px;color:${props.textColor || '#fff'};opacity:0.85;margin-bottom:32px;line-height:1.6;white-space:pre-line">${escapeHtml(props.subtitle || '')}</p>
<h1 style="font-size:48px;font-weight:700;color:${heroTextColor};margin-bottom:16px;line-height:1.2">${escapeHtml(props.heading || '')}</h1>
<p style="font-size:20px;color:${heroTextColor};opacity:0.85;margin-bottom:32px;line-height:1.6;white-space:pre-line">${escapeHtml(props.subtitle || '')}</p>
<div style="display:flex;gap:12px;justify-content:${justifyBtn};flex-wrap:wrap">${buttonsHtml}</div>
</div>
</section>`,
@@ -1,7 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
interface Counter {
number: number;
@@ -112,12 +112,17 @@ NumberCounter.craft = {
(NumberCounter as any).toHtml = (props: NumberCounterProps, _childrenHtml: string, nodeId?: string) => {
const {
counters = defaultCounters,
columns = 4,
numberColor = '#3b82f6',
labelColor = '#6b7280',
numberSize = '48px',
style = {},
} = props;
// Number() coercion: `columns` is a raw string-interpolation sink into the
// grid style attribute below (repeat(${columns},1fr)); Number() of
// anything non-numeric collapses safely to NaN instead of breaking out.
const columns = Number(props.columns) || 4;
// Sanitized -- raw string-interpolation sinks in the counter/label spans
// below.
const numberColor = cssValue(props.numberColor) || '#3b82f6';
const labelColor = cssValue(props.labelColor) || '#6b7280';
const numberSize = cssValue(props.numberSize) || '48px';
const items = counters.length > 0 ? counters : defaultCounters;
@@ -1,7 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
interface PricingPlan {
name: string;
@@ -225,7 +225,9 @@ PricingTable.craft = {
});
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
const plans = props.plans || defaultPlans;
const featuredBg = props.featuredBg || '#3b82f6';
// Sanitized -- featuredBg is a raw string-interpolation sink below (drives
// cardBg/btnBg/btnColor, all raw-interpolated into style="...").
const featuredBg = cssValue(props.featuredBg) || '#3b82f6';
const cards = plans.map((plan) => {
const cardBg = plan.isFeatured ? featuredBg : '#ffffff';
+10 -6
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, useState } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
import { escapeHtml, escapeAttr, scopeId, cssValue } from '../../utils/escape';
interface TabItem {
label: string;
@@ -131,11 +131,15 @@ Tabs.craft = {
});
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
const tabs = props.tabs || defaultTabs;
const activeTabBg = props.activeTabBg || '#3b82f6';
const activeTabColor = props.activeTabColor || '#ffffff';
const inactiveTabBg = props.inactiveTabBg || '#f1f5f9';
const inactiveTabColor = props.inactiveTabColor || '#64748b';
const contentBg = props.contentBg || '#ffffff';
// Sanitized -- raw string-interpolation sinks below, both into style="..."
// attributes AND into an inline <script> as single-quoted JS string
// literals (a stray `'` there breaks out of the JS string, not just CSS);
// cssValue strips quotes too so it neutralizes both contexts at once.
const activeTabBg = cssValue(props.activeTabBg) || '#3b82f6';
const activeTabColor = cssValue(props.activeTabColor) || '#ffffff';
const inactiveTabBg = cssValue(props.inactiveTabBg) || '#f1f5f9';
const inactiveTabColor = cssValue(props.inactiveTabColor) || '#64748b';
const contentBg = cssValue(props.contentBg) || '#ffffff';
// tabId scopes the functional wiring (onclick/getElementById) as well as
// the ARIA tab<->panel linking ids. It must be BOTH deterministic (so
@@ -1,7 +1,7 @@
import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { escapeHtml, escapeAttr } from '../../utils/escape';
import { escapeHtml, escapeAttr, cssValue } from '../../utils/escape';
interface Testimonial {
quote: string;
@@ -139,11 +139,16 @@ Testimonials.craft = {
const {
testimonials = defaultTestimonials,
layout = 'grid',
columns = 3,
style = {},
cardBg = '#f8fafc',
starColor = '#f59e0b',
} = props;
// Number() coercion: `columns` is a raw string-interpolation sink into the
// grid style attribute below (repeat(${columns},1fr)); Number() of
// anything non-numeric collapses safely to NaN instead of breaking out.
const columns = Number(props.columns) || 3;
// Sanitized -- raw string-interpolation sinks below (cardCss / starsHtml
// style attributes).
const cardBg = cssValue(props.cardBg) || '#f8fafc';
const starColor = cssValue(props.starColor) || '#f59e0b';
const items = testimonials.length > 0 ? testimonials : defaultTestimonials;
+11 -4
View File
@@ -1,5 +1,5 @@
import { CSSProperties } from 'react';
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
export type CtaVariant = 'primary' | 'outline' | 'ghost';
@@ -68,14 +68,21 @@ export function ctaInlineStyle(cta: CtaButton, defaults: CtaStyleDefaults): CSSP
export function ctaCssString(cta: CtaButton, defaults: CtaStyleDefaults): string {
const variant = cta.variant || 'primary';
// Sanitized -- these are raw string-interpolation sinks into style="...".
// Callers pass user-controlled design-token colors (e.g. HeroSimple's
// buttonBgColor/buttonTextColor/textColor) through CtaStyleDefaults, so
// sanitize once here rather than at every call site.
const outlineText = cssValue(defaults.outlineText) || '#000000';
const primaryBg = cssValue(defaults.primaryBg) || '#000000';
const primaryText = cssValue(defaults.primaryText) || '#ffffff';
switch (variant) {
case 'outline':
return `display:inline-block;padding:14px 36px;background-color:transparent;color:${defaults.outlineText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px;border:2px solid ${defaults.outlineText}`;
return `display:inline-block;padding:14px 36px;background-color:transparent;color:${outlineText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px;border:2px solid ${outlineText}`;
case 'ghost':
return `display:inline-block;padding:14px 24px;background-color:transparent;color:${defaults.outlineText};text-decoration:underline;border-radius:8px;font-weight:600;font-size:16px`;
return `display:inline-block;padding:14px 24px;background-color:transparent;color:${outlineText};text-decoration:underline;border-radius:8px;font-weight:600;font-size:16px`;
case 'primary':
default:
return `display:inline-block;padding:14px 36px;background-color:${defaults.primaryBg};color:${defaults.primaryText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px`;
return `display:inline-block;padding:14px 36px;background-color:${primaryBg};color:${primaryText};text-decoration:none;border-radius:8px;font-weight:600;font-size:16px`;
}
}
+29
View File
@@ -0,0 +1,29 @@
import { describe, test, expect, afterEach } from 'vitest';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
describe('clipboard', () => {
afterEach(() => {
setClipboardNodeId(null);
});
test('starts empty', () => {
expect(getClipboardNodeId()).toBeNull();
});
test('set then get returns the stored node id', () => {
setClipboardNodeId('node-123');
expect(getClipboardNodeId()).toBe('node-123');
});
test('is a shared module-level store -- overwriting replaces the previous value', () => {
setClipboardNodeId('first');
setClipboardNodeId('second');
expect(getClipboardNodeId()).toBe('second');
});
test('can be cleared back to null', () => {
setClipboardNodeId('node-123');
setClipboardNodeId(null);
expect(getClipboardNodeId()).toBeNull();
});
});
+23
View File
@@ -0,0 +1,23 @@
/**
* Tiny shared clipboard for canvas node copy/paste.
*
* Both the context menu (right-click Copy/Paste) and the keyboard shortcuts
* hook (Ctrl/Cmd+C / Ctrl/Cmd+V) read and write this single module-level
* store, so copying a node via one entry point and pasting via the other
* behaves consistently instead of each maintaining its own clipboard.
*
* Deliberately not React state -- nothing in the UI needs to re-render
* reactively when the clipboard changes; consumers just read the current
* value at the moment they need it (on paste, or when a menu opens).
*/
let clipboardNodeId: string | null = null;
/** Returns the id of the node currently on the clipboard, or null if empty. */
export function getClipboardNodeId(): string | null {
return clipboardNodeId;
}
/** Sets (or clears, with `null`) the node id on the clipboard. */
export function setClipboardNodeId(nodeId: string | null): void {
clipboardNodeId = nodeId;
}
@@ -0,0 +1,259 @@
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 { useKeyboardShortcuts } from './useKeyboardShortcuts';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
/**
* Regression coverage: Ctrl/Cmd+V must run the copied subtree through
* `regenerateTreeIds` BEFORE handing it to `actions.addNodeTree`. Pasting
* with the source node's ORIGINAL ids re-inserted them into the live Craft.js
* node map, producing duplicate ids and corrupting the tree -- that bug is
* exactly what this suite guards against. Also covers the sibling-parent /
* ROOT-fallback targeting, the empty-clipboard no-op, and the existing
* input-focus guard.
*
* Mock pattern mirrors PageContext.pure-updaters.test.tsx /
* PageContext.slug.test.tsx: a fake `useEditor` exposing `query`/`actions`,
* mounted via a bare consumer component, with REAL `keydown` events
* dispatched on `document` (where useKeyboardShortcuts attaches its
* listener) to exercise the actual handler rather than calling it directly.
*
* `regenerateTreeIds` itself is NOT mocked -- we partially mock
* `../utils/craft-tree` to wrap the real implementation in a `vi.fn()` so we
* can assert it was called, while still getting genuinely fresh ids back.
*/
const addNodeTreeMock = vi.fn();
let selectedIds: string[] = [];
function makeNode(id: string, parent: string | null, children: string[] = []): Node {
return {
id,
data: {
props: {},
type: { resolvedName: 'Container' },
name: 'Container',
displayName: 'Container',
isCanvas: false,
parent,
linkedNodes: {},
nodes: children,
hidden: false,
},
info: {},
events: { selected: false, dragged: false, hovered: false },
dom: null,
related: {},
rules: {},
_hydrationTimestamp: 0,
} as unknown as Node;
}
// The tree `toNodeTree()` returns for the node that was Ctrl+C'd -- a root
// with one child, so regeneration has more than one id to remap.
const COPIED_TREE: NodeTree = {
rootNodeId: 'copied-root-1',
nodes: {
'copied-root-1': makeNode('copied-root-1', null, ['copied-child-1']),
'copied-child-1': makeNode('copied-child-1', 'copied-root-1'),
},
};
const nodeStore: Record<string, { data: { parent: string | null } }> = {
'selected-1': { data: { parent: 'parent-container-1' } },
ROOT: { data: { parent: null } },
'copied-root-1': { data: { parent: 'wherever-it-originally-lived' } },
};
function makeQueryNode(id: string) {
return {
get: () => nodeStore[id] ?? null,
toNodeTree: () => {
if (id !== 'copied-root-1') {
throw new Error(`unexpected toNodeTree() call for "${id}"`);
}
return COPIED_TREE;
},
};
}
vi.mock('@craftjs/core', () => ({
useEditor: () => ({
query: {
getEvent: () => ({ all: () => selectedIds }),
node: (id: string) => makeQueryNode(id),
},
actions: {
addNodeTree: addNodeTreeMock,
history: { undo: vi.fn(), redo: vi.fn() },
delete: vi.fn(),
clearEvents: vi.fn(),
},
}),
}));
// Partial mock: keep the real `regenerateTreeIds` implementation (so pasted
// trees genuinely get fresh ids) but wrap it in a spy so we can assert the
// handler actually calls it, rather than only inferring that from the
// output.
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;
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 pressKey(key: string, opts: Partial<KeyboardEventInit> = {}) {
act(() => {
document.dispatchEvent(
new KeyboardEvent('keydown', { key, ctrlKey: true, bubbles: true, cancelable: true, ...opts }),
);
});
}
const Consumer: React.FC = () => {
useKeyboardShortcuts();
return null;
};
beforeEach(() => {
selectedIds = [];
addNodeTreeMock.mockClear();
regenerateTreeIdsMock.mockClear();
setClipboardNodeId(null);
});
afterEach(() => {
setClipboardNodeId(null);
if (root) unmount();
});
describe('useKeyboardShortcuts: Ctrl/Cmd+C / Ctrl/Cmd+V', () => {
test('Ctrl+C copies the selected node id to the clipboard', () => {
render(<Consumer />);
selectedIds = ['selected-1'];
pressKey('c');
expect(getClipboardNodeId()).toBe('selected-1');
});
test('Ctrl+V pastes as a sibling of the selection (selected node`s data.parent) with FRESH ids', () => {
render(<Consumer />);
selectedIds = ['copied-root-1'];
pressKey('c');
expect(getClipboardNodeId()).toBe('copied-root-1');
selectedIds = ['selected-1'];
pressKey('v');
// regenerateTreeIds actually ran before the tree was handed to Craft.js.
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
expect(regenerateTreeIdsMock).toHaveBeenCalledWith(COPIED_TREE);
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [pastedTree, targetParent] = addNodeTreeMock.mock.calls[0];
// Sibling of the current selection: selected-1's data.parent.
expect(targetParent).toBe('parent-container-1');
// The regression this guards: pasted ids must be fresh, never reuse the
// ids the copied node already occupies in the live Craft.js tree.
expect(pastedTree.rootNodeId).not.toBe(COPIED_TREE.rootNodeId);
const originalIds = new Set(Object.keys(COPIED_TREE.nodes));
const pastedIds = new Set(Object.keys(pastedTree.nodes));
expect(pastedIds.size).toBe(originalIds.size);
for (const id of pastedIds) {
expect(originalIds.has(id)).toBe(false);
}
});
test('Ctrl+V with selection at ROOT falls back to ROOT as the insertion parent', () => {
render(<Consumer />);
selectedIds = ['copied-root-1'];
pressKey('c');
selectedIds = ['ROOT'];
pressKey('v');
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
const [, targetParent] = addNodeTreeMock.mock.calls[0];
expect(targetParent).toBe('ROOT');
});
test('Ctrl+V with an empty clipboard is a no-op', () => {
render(<Consumer />);
selectedIds = ['selected-1'];
pressKey('v');
expect(addNodeTreeMock).not.toHaveBeenCalled();
expect(regenerateTreeIdsMock).not.toHaveBeenCalled();
});
test('shortcuts are ignored while focus is in an input element', () => {
const input = document.createElement('input');
document.body.appendChild(input);
input.focus();
expect(document.activeElement).toBe(input);
render(<Consumer />);
selectedIds = ['selected-1'];
pressKey('c');
expect(getClipboardNodeId()).toBeNull();
setClipboardNodeId('copied-root-1');
pressKey('v');
expect(addNodeTreeMock).not.toHaveBeenCalled();
input.remove();
});
test('shortcuts are ignored while focus is in a contentEditable element', () => {
// jsdom does not implement `HTMLElement.isContentEditable` (it always
// reports false regardless of the contentEditable attribute -- a known
// jsdom limitation), so a real contentEditable + focus() can't exercise
// this branch of the guard. Stub `document.activeElement` directly with
// a fake element that reports isContentEditable: true, matching what
// the guard (`isInputFocused` in useKeyboardShortcuts.ts) actually reads.
const fakeEditable = { tagName: 'DIV', isContentEditable: true } as unknown as Element;
const activeElementSpy = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(fakeEditable);
render(<Consumer />);
selectedIds = ['selected-1'];
pressKey('c');
expect(getClipboardNodeId()).toBeNull();
activeElementSpy.mockRestore();
});
});
+40
View File
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import { useEditor } from '@craftjs/core';
import { findDeletableTarget } from '../utils/craft-helpers';
import { regenerateTreeIds } from '../utils/craft-tree';
import { getClipboardNodeId, setClipboardNodeId } from './clipboard';
function isInputFocused(): boolean {
const el = document.activeElement;
@@ -85,6 +86,45 @@ export function useKeyboardShortcuts() {
return;
}
// Ctrl+C: copy selected node id to the shared clipboard
if (ctrl && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
try {
const selected = query.getEvent('selected').all();
if (selected.length > 0 && selected[0] !== 'ROOT') {
setClipboardNodeId(selected[0]);
}
} catch (err) {
console.error('Copy failed:', err);
}
return;
}
// Ctrl+V: paste the clipboard node as a sibling of the current selection
if (ctrl && (e.key === 'v' || e.key === 'V')) {
e.preventDefault();
try {
const sourceId = getClipboardNodeId();
if (!sourceId || !query.node(sourceId).get()) return;
const selected = query.getEvent('selected').all();
if (selected.length === 0) return;
const selectedId = selected[0];
let targetParent = 'ROOT';
if (selectedId !== 'ROOT') {
const node = query.node(selectedId).get();
targetParent = node?.data?.parent || 'ROOT';
}
const tree = regenerateTreeIds(query.node(sourceId).toNodeTree());
actions.addNodeTree(tree, targetParent);
} catch (err) {
console.error('Paste failed:', err);
}
return;
}
// Escape: deselect all
if (e.key === 'Escape') {
e.preventDefault();
@@ -4,6 +4,7 @@ import { findDeletableTarget } from '../../utils/craft-helpers';
import { useSitesmithModal } from '../../state/SitesmithContext';
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
import { regenerateTreeIds } from '../../utils/craft-tree';
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
interface ContextMenuProps {
visible: boolean;
@@ -32,7 +33,6 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
const { actions, query } = useEditor();
const { open: openSitesmith } = useSitesmithModal();
const menuRef = useRef<HTMLDivElement>(null);
const clipboardRef = useRef<string | null>(null);
// Close on click outside
useEffect(() => {
@@ -80,7 +80,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
const copyNode = useCallback(() => {
if (!nodeId || nodeId === 'ROOT') return;
try {
clipboardRef.current = nodeId;
setClipboardNodeId(nodeId);
} catch (e) {
console.error('Copy failed:', e);
}
@@ -88,7 +88,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
}, [nodeId, onClose]);
const pasteNode = useCallback(() => {
const sourceId = clipboardRef.current;
const sourceId = getClipboardNodeId();
if (!sourceId) {
onClose();
return;
@@ -210,7 +210,7 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
label: 'Paste',
shortcut: 'Ctrl+V',
action: pasteNode,
disabled: !clipboardRef.current,
disabled: !getClipboardNodeId(),
dividerAfter: true,
},
{
+3 -11
View File
@@ -1,6 +1,5 @@
import React from 'react';
import { useEditor } from '@craftjs/core';
import { componentResolver } from '../../components/resolver';
import { SiteDesignPanel } from './SiteDesignPanel';
import { useSitesmithModal } from '../../state/SitesmithContext';
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
@@ -31,27 +30,21 @@ import {
================================================================ */
export const GuidedStyles: React.FC = () => {
const resolverMap = componentResolver as Record<string, any>;
const { open: openSitesmith } = useSitesmithModal();
const { query } = useEditor();
const { selected, selectedType, nodeProps, resolvedName } = useEditor((state) => {
const { selected, selectedType, nodeProps } = useEditor((state) => {
const currentNodeId = state.events.selected
? Array.from(state.events.selected)[0]
: undefined;
let selectedType: string | null = null;
let nodeProps: Record<string, any> = {};
let resolvedName: string | null = null;
if (currentNodeId) {
const node = state.nodes[currentNodeId];
if (node) {
selectedType = node.data.displayName || node.data.name || null;
nodeProps = node.data.props || {};
const nodeType = node.data.type as any;
if (nodeType && typeof nodeType === 'object' && nodeType.resolvedName) {
resolvedName = nodeType.resolvedName;
}
}
}
@@ -59,7 +52,6 @@ export const GuidedStyles: React.FC = () => {
selected: currentNodeId || null,
selectedType,
nodeProps,
resolvedName,
};
});
@@ -75,8 +67,8 @@ export const GuidedStyles: React.FC = () => {
const isButton = /^button$/i.test(typeName);
const isImage = /^image$/i.test(typeName);
const isBgSection = /^background section$/i.test(typeName);
const isContainer = /^container$|^section$|^columns$|^header zone$|^footer zone$/i.test(typeName);
const isHero = /hero/i.test(typeName);
const isContainer = /^container$|^section$|^columns$/i.test(typeName);
const isHero = /^hero/i.test(typeName);
const isNav = /^menu$|^logo$|^navbar$|^footer$/i.test(typeName);
const isMedia = /^video$|^gallery$|^map$|^content slider$/i.test(typeName);
const isForm = /^form$|^input$|^textarea$|^subscribe|^contact form$|^submit button$|^search bar$/i.test(typeName);
@@ -0,0 +1,127 @@
import React from 'react';
import { useEditor } from '@craftjs/core';
import { CollapsibleSection, ArrayPropEditor, smallInputStyle } from './shared';
/* ---------- Shared array-item field editor ----------
Extracted from SectionTypePanel and GenericPropsEditor, which both had a
near-byte-identical per-item field renderer for generic array props
(features/items/plans/testimonials/etc.). Infers an input type per field:
boolean -> checkbox, number -> number, /color/ -> color swatch, long
string -> textarea, else text. Fields are derived from Object.keys(items[0]).
Callers keep their own special-casing (e.g. SectionTypePanel routes
key === 'features' to FeaturesEditor instead of using this component). */
export const ArrayItemFieldsEditor: React.FC<{ selectedId: string; propKey: string; items: any[] }> = ({
selectedId, propKey, items,
}) => {
const { actions } = useEditor();
const arrayItems = items;
const sampleItem = arrayItems[0] || {};
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
return (
<CollapsibleSection title={propKey.replace(/([A-Z])/g, ' $1').trim()}>
<ArrayPropEditor
selectedId={selectedId}
propKey={propKey}
items={arrayItems}
renderItem={(item: any, index: number) => {
if (typeof item !== 'object' || item === null) {
return (
<input
type="text"
value={String(item)}
onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = e.target.value;
props[propKey] = updated;
});
}}
style={smallInputStyle}
/>
);
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
{itemFields.map((field) => {
const fieldVal = item[field];
if (typeof fieldVal === 'boolean') {
return (
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
<input type="checkbox" checked={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = { ...updated[index], [field]: e.target.checked };
props[propKey] = updated;
});
}} />
{field}
</label>
);
}
if (typeof fieldVal === 'number') {
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
<input type="number" value={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
props[propKey] = updated;
});
}} style={smallInputStyle} />
</div>
);
}
// color fields
if (/color/i.test(field) && typeof fieldVal === 'string') {
return (
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[propKey] = updated;
});
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
</div>
);
}
// long text
const strVal = String(fieldVal ?? '');
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
{isLongField ? (
<textarea value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[propKey] = updated;
});
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
) : (
<input type="text" value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[propKey] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[propKey] = updated;
});
}} style={smallInputStyle} />
)}
</div>
);
})}
</div>
);
}}
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
: ''
}
/>
</CollapsibleSection>
);
};
@@ -1,5 +1,4 @@
import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import React from 'react';
import {
BG_COLORS,
SPACING_PRESETS,
@@ -15,22 +14,13 @@ import {
labelStyle,
inputStyle,
sectionGap,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
/* ---------- BACKGROUND SECTION ---------- */
export const BackgroundSectionStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const style = nodeProps.style || {};
@@ -12,6 +12,7 @@ import {
PresetButtonGrid,
TextInputField,
autoTextColor,
useNodeProp,
} from './shared';
/* ---------- BUTTON ---------- */
@@ -19,14 +20,7 @@ export const ButtonStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePr
const { actions } = useEditor();
const style: CSSProperties = nodeProps.style || {};
const setPropStyle = useCallback(
(property: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [property]: value };
});
},
[actions, selectedId],
);
const { setPropStyle } = useNodeProp(selectedId);
const setButtonColor = useCallback(
(bgColor: string) => {
@@ -1,5 +1,4 @@
import React, { useCallback, CSSProperties } from 'react';
import { useEditor } from '@craftjs/core';
import React, { CSSProperties } from 'react';
import {
BG_COLORS,
SPACING_PRESETS,
@@ -14,28 +13,14 @@ import {
labelStyle,
inputStyle,
sectionGap,
useNodeProp,
} from './shared';
/* ---------- CONTAINER / SECTION ---------- */
export const ContainerStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const style: CSSProperties = nodeProps.style || {};
const setPropStyle = useCallback(
(property: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [property]: value };
});
},
[actions, selectedId],
);
const setProp = useCallback(
(key: string, value: string) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
},
[actions, selectedId],
);
const { setProp, setPropStyle } = useNodeProp(selectedId);
return (
<>
@@ -1,5 +1,4 @@
import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import React from 'react';
import {
BG_COLORS,
SPACING_PRESETS,
@@ -15,21 +14,12 @@ import {
inputStyle,
btnActiveStyle,
sectionGap,
useNodeProp,
} from './shared';
/* ---------- FORM ---------- */
export const FormStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const style = nodeProps.style || {};
@@ -1,5 +1,4 @@
import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import React from 'react';
import {
TEXT_COLORS,
BG_COLORS,
@@ -12,30 +11,20 @@ import {
PresetButtonGrid,
CollapsibleSection,
ColorPickerField,
ArrayPropEditor,
labelStyle,
inputStyle,
smallInputStyle,
sectionGap,
useNodeProp,
} from './shared';
import { ArrayItemFieldsEditor } from './ArrayItemFields';
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
selectedId, nodeProps, typeName,
}) => {
const { actions } = useEditor();
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
const setPropValue = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setStyleValue = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
// Categorize all props
const allProps = Object.entries(nodeProps).filter(([key]) => !SKIP_PROPS.has(key));
@@ -105,116 +94,9 @@ export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Recor
)}
{/* Array props */}
{arrayProps.map(([key, items]) => {
const arrayItems = items as any[];
const sampleItem = arrayItems[0] || {};
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
return (
<CollapsibleSection key={key} title={key.replace(/([A-Z])/g, ' $1').trim()}>
<ArrayPropEditor
selectedId={selectedId}
propKey={key}
items={arrayItems}
renderItem={(item: any, index: number) => {
if (typeof item !== 'object' || item === null) {
return (
<input
type="text"
value={String(item)}
onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = e.target.value;
props[key] = updated;
});
}}
style={smallInputStyle}
/>
);
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
{itemFields.map((field) => {
const fieldVal = item[field];
if (typeof fieldVal === 'boolean') {
return (
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
<input type="checkbox" checked={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.checked };
props[key] = updated;
});
}} />
{field}
</label>
);
}
if (typeof fieldVal === 'number') {
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
<input type="number" value={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
props[key] = updated;
});
}} style={smallInputStyle} />
</div>
);
}
if (/color/i.test(field) && typeof fieldVal === 'string') {
return (
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
</div>
);
}
const strVal = String(fieldVal ?? '');
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
{isLongField ? (
<textarea value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
) : (
<input type="text" value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} style={smallInputStyle} />
)}
</div>
);
})}
</div>
);
}}
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
: ''
}
/>
</CollapsibleSection>
);
})}
{arrayProps.map(([key, items]) => (
<ArrayItemFieldsEditor key={key} selectedId={selectedId} propKey={key} items={items as any[]} />
))}
{/* Style controls */}
<CollapsibleSection title="Style">
@@ -1,5 +1,4 @@
import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import React from 'react';
import {
StylePanelProps,
CollapsibleSection,
@@ -8,16 +7,13 @@ import {
inputStyle,
btnActiveStyle,
sectionGap,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
/* ---------- HERO STYLE PANEL ---------- */
export const HeroStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const { setProp } = useNodeProp(selectedId);
const bgType = nodeProps.bgType || 'color';
@@ -1,4 +1,4 @@
import React, { useCallback, CSSProperties } from 'react';
import React, { CSSProperties } from 'react';
import { useEditor } from '@craftjs/core';
import {
IMAGE_RADIUS_PRESETS,
@@ -8,6 +8,7 @@ import {
SectionLabel,
PresetButtonGrid,
TextInputField,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
@@ -16,14 +17,7 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
const { actions } = useEditor();
const style: CSSProperties = nodeProps.style || {};
const setPropStyle = useCallback(
(property: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [property]: value };
});
},
[actions, selectedId],
);
const { setPropStyle } = useNodeProp(selectedId);
const maxWidthPresets = [
{ label: '25%', value: '25%' },
@@ -1,4 +1,4 @@
import React, { useCallback } from 'react';
import React from 'react';
import { useEditor } from '@craftjs/core';
import {
BG_COLORS,
@@ -17,22 +17,14 @@ import {
inputStyle,
smallInputStyle,
sectionGap,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const style = nodeProps.style || {};
@@ -15,22 +15,14 @@ import {
inputStyle,
smallInputStyle,
sectionGap,
useNodeProp,
} from './shared';
import { AssetPicker } from '../../../ui/AssetPicker';
/* ---------- NAV / MENU / LOGO ---------- */
export const NavStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const links: any[] = nodeProps.links || [];
@@ -1,5 +1,4 @@
import React, { useCallback } from 'react';
import { useEditor } from '@craftjs/core';
import React from 'react';
import {
BG_COLORS,
SPACING_PRESETS,
@@ -12,27 +11,17 @@ import {
PresetButtonGrid,
CollapsibleSection,
ColorPickerField,
ArrayPropEditor,
labelStyle,
inputStyle,
smallInputStyle,
sectionGap,
useNodeProp,
} from './shared';
import { FeaturesEditor } from './FeaturesEditor';
import { ArrayItemFieldsEditor } from './ArrayItemFields';
/* ---------- SECTION-TYPE (Accordion, Tabs, Pricing, Testimonials, etc.) ---------- */
export const SectionTypePanel: React.FC<StylePanelProps & { typeName: string }> = ({ selectedId, nodeProps, typeName }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const style = nodeProps.style || {};
@@ -108,115 +97,8 @@ export const SectionTypePanel: React.FC<StylePanelProps & { typeName: string }>
}
const arrayItems = items as any[];
if (arrayItems.length === 0 && typeof arrayItems[0] !== 'object') return null;
const sampleItem = arrayItems[0] || {};
const itemFields = typeof sampleItem === 'object' && sampleItem !== null ? Object.keys(sampleItem) : [];
return (
<CollapsibleSection key={key} title={key.replace(/([A-Z])/g, ' $1').trim()}>
<ArrayPropEditor
selectedId={selectedId}
propKey={key}
items={arrayItems}
renderItem={(item: any, index: number) => {
if (typeof item !== 'object' || item === null) {
return (
<input
type="text"
value={String(item)}
onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = e.target.value;
props[key] = updated;
});
}}
style={smallInputStyle}
/>
);
}
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
{itemFields.map((field) => {
const fieldVal = item[field];
if (typeof fieldVal === 'boolean') {
return (
<label key={field} style={{ fontSize: 10, color: '#71717a', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer' }}>
<input type="checkbox" checked={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.checked };
props[key] = updated;
});
}} />
{field}
</label>
);
}
if (typeof fieldVal === 'number') {
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
<input type="number" value={fieldVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: parseFloat(e.target.value) || 0 };
props[key] = updated;
});
}} style={smallInputStyle} />
</div>
);
}
// color fields
if (/color/i.test(field) && typeof fieldVal === 'string') {
return (
<div key={field} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize', width: 50 }}>{field}</label>
<input type="color" value={fieldVal || '#000000'} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} style={{ width: 24, height: 20, border: 'none', cursor: 'pointer', background: 'none', padding: 0 }} />
</div>
);
}
// long text
const strVal = String(fieldVal ?? '');
const isLongField = strVal.length > 50 || field === 'description' || field === 'text' || field === 'content';
return (
<div key={field}>
<label style={{ fontSize: 9, color: '#52525b', textTransform: 'capitalize' }}>{field}</label>
{isLongField ? (
<textarea value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
) : (
<input type="text" value={strVal} onChange={(e) => {
actions.setProp(selectedId, (props: any) => {
const updated = [...(props[key] || [])];
updated[index] = { ...updated[index], [field]: e.target.value };
props[key] = updated;
});
}} style={smallInputStyle} />
)}
</div>
);
})}
</div>
);
}}
emptyItem={typeof sampleItem === 'object' && sampleItem !== null
? Object.fromEntries(itemFields.map((f) => [f, typeof sampleItem[f] === 'number' ? 0 : typeof sampleItem[f] === 'boolean' ? false : '']))
: ''
}
/>
</CollapsibleSection>
);
return <ArrayItemFieldsEditor key={key} selectedId={selectedId} propKey={key} items={arrayItems} />;
})}
{/* Style */}
@@ -1,4 +1,4 @@
import React, { useCallback } from 'react';
import React from 'react';
import { useEditor } from '@craftjs/core';
import {
BG_COLORS,
@@ -16,21 +16,13 @@ import {
smallInputStyle,
btnActiveStyle,
sectionGap,
useNodeProp,
} from './shared';
/* ---------- SOCIAL / ICON / STAR RATING ---------- */
export const SocialStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => {
actions.setProp(selectedId, (props: any) => { props[key] = value; });
}, [actions, selectedId]);
const setPropStyle = useCallback((key: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [key]: value };
});
}, [actions, selectedId]);
const { setProp, setPropStyle } = useNodeProp(selectedId);
const style = nodeProps.style || {};
@@ -1,5 +1,4 @@
import React, { useCallback, CSSProperties } from 'react';
import { useEditor } from '@craftjs/core';
import React, { CSSProperties } from 'react';
import {
TEXT_COLORS,
FONT_FAMILIES,
@@ -11,21 +10,14 @@ import {
SectionLabel,
ColorSwatchGrid,
PresetButtonGrid,
useNodeProp,
} from './shared';
/* ---------- TEXT ---------- */
export const TextStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
const { actions } = useEditor();
const style: CSSProperties = nodeProps.style || {};
const setPropStyle = useCallback(
(property: string, value: string) => {
actions.setProp(selectedId, (props: any) => {
props.style = { ...props.style, [property]: value };
});
},
[actions, selectedId],
);
const { setPropStyle } = useNodeProp(selectedId);
return (
<>
+12
View File
@@ -288,6 +288,18 @@ export interface StylePanelProps {
nodeProps: Record<string, any>;
}
/* ---------- useNodeProp ----------
Shared setProp/setPropStyle boilerplate repeated across many *StylePanel.tsx
files. Only adopted where a panel's inline definitions were byte-equivalent
to this (some panels use different param names or extra logic and keep
their own local versions). */
export function useNodeProp(selectedId: string) {
const { actions } = useEditor();
const setProp = useCallback((key: string, value: any) => actions.setProp(selectedId, (p: any) => { p[key] = value; }), [actions, selectedId]);
const setPropStyle = useCallback((prop: string, value: string) => actions.setProp(selectedId, (p: any) => { p.style = { ...p.style, [prop]: value }; }), [actions, selectedId]);
return { setProp, setPropStyle };
}
/* ---------- Array Prop Editor (reusable for features, items, plans, etc.) ---------- */
interface ArrayPropEditorProps {
selectedId: string;
+10 -3
View File
@@ -11,6 +11,7 @@ import { MessageList } from './MessageList';
import { ChatInput } from './ChatInput';
import { WorkingIndicator } from './WorkingIndicator';
import { SitesmithResponse } from '../../types/sitesmith';
import { Modal } from '../../ui/Modal';
interface Props {
onClose: () => void;
@@ -39,7 +40,6 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
const canChat = summary && (summary.status === 'OK_BONUS' || summary.status === 'OK_MONTHLY');
const overlay: React.CSSProperties = { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.8)', zIndex: 9000, display: 'flex', alignItems: 'center', justifyContent: 'center' };
const panel: React.CSSProperties = { background: '#0f0f17', border: '1px solid #27272a', borderRadius: 12, width: 'min(720px, 90vw)', maxHeight: '90vh', display: 'flex', flexDirection: 'column' };
const header: React.CSSProperties = { display: 'flex', alignItems: 'center', padding: '14px 18px', borderBottom: '1px solid #27272a', gap: 8 };
const body: React.CSSProperties = { flex: 1, padding: '14px 18px', overflowY: 'auto', display: 'flex', flexDirection: 'column' };
@@ -93,7 +93,14 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
};
return (
<div role="dialog" aria-modal="true" style={overlay}>
<Modal
open
onClose={onClose}
closeOnEscape={false}
closeOnBackdropClick={false}
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', zIndex: 9000 }}
backdropProps={{ role: 'dialog', 'aria-modal': true }}
>
<div style={panel}>
<div style={header}>
<div style={{ fontWeight: 600, color: '#fff' }}>✨ Sitesmith</div>
@@ -166,6 +173,6 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
onCancel={() => setPendingReplace(null)}
/>
</div>
</div>
</Modal>
);
};
+4 -27
View File
@@ -1,5 +1,6 @@
import React, { useEffect } from 'react';
import React from 'react';
import { useSiteDesign } from '../../state/SiteDesignContext';
import { Modal } from '../../ui/Modal';
interface HeadCodeModalProps {
open: boolean;
@@ -9,19 +10,8 @@ interface HeadCodeModalProps {
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
const { design, updateDesign } = useSiteDesign();
useEffect(() => {
if (!open) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [open, onClose]);
if (!open) return null;
return (
<div style={backdropStyle} onClick={onClose}>
<Modal open={open} onClose={onClose}>
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
{/* Header */}
<div style={modalHeaderStyle}>
@@ -92,25 +82,12 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
</button>
</div>
</div>
</div>
</Modal>
);
};
/* ---------- Styles ---------- */
const backdropStyle: React.CSSProperties = {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.65)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 10000,
};
const modalStyle: React.CSSProperties = {
width: '90vw',
maxWidth: 700,
+10 -41
View File
@@ -10,6 +10,7 @@ import {
} from '../../templates';
import { componentResolver } from '../../components/resolver';
import { clickableProps } from '../../utils/a11y';
import { Modal } from '../../ui/Modal';
// ---------------------------------------------------------------------------
// Types
@@ -60,18 +61,15 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
};
}, []);
// Close on Escape key
useEffect(() => {
if (!open) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
// Escape / backdrop-click close the confirmation dialog first if it's open,
// otherwise close the modal. Passed to <Modal> below, which handles the
// Escape listener and the backdrop-click detection itself; the header's own
// close button (X) below still uses the raw `onClose` prop directly, so it
// always fully closes the modal even mid-confirmation (unchanged behavior).
const handleModalClose = useCallback(() => {
if (confirmTemplate) setConfirmTemplate(null);
else onClose();
}
};
document.addEventListener('keydown', handler);
return () => document.removeEventListener('keydown', handler);
}, [open, confirmTemplate, onClose]);
}, [confirmTemplate, onClose]);
// Filter templates by category
const filtered = useMemo(() => {
@@ -236,24 +234,8 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
}
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
// Close on backdrop click
const handleBackdropClick = useCallback(
(e: React.MouseEvent) => {
if (e.target === e.currentTarget) {
if (confirmTemplate) {
setConfirmTemplate(null);
} else {
onClose();
}
}
},
[confirmTemplate, onClose],
);
if (!open) return null;
return (
<div style={backdropStyle} onClick={handleBackdropClick}>
<Modal open={open} onClose={handleModalClose}>
<div style={modalStyle}>
{/* Header */}
<div style={modalHeaderStyle}>
@@ -377,7 +359,7 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
</div>
)}
</div>
</div>
</Modal>
);
};
@@ -473,19 +455,6 @@ const TemplateCard: React.FC<{
// Styles
// ---------------------------------------------------------------------------
const backdropStyle: React.CSSProperties = {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.65)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 10000,
};
const modalStyle: React.CSSProperties = {
width: '90vw',
maxWidth: 900,
+96
View File
@@ -0,0 +1,96 @@
import { describe, test, expect, vi, afterEach } from 'vitest';
import React from 'react';
import { createRoot, Root } from 'react-dom/client';
import { act } from 'react-dom/test-utils';
import { Modal } from './Modal';
/* ---------- DOM test harness (no @testing-library/react in this repo, see
src/ui/AssetPicker.test.tsx for the same pattern: react-dom/client +
react-dom/test-utils `act`, both transitive deps of react-dom already). ---------- */
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 pressEscape() {
act(() => {
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
});
}
function click(el: Element | null) {
if (!el) throw new Error('element not found');
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
}
afterEach(() => {
if (container) unmount();
document.body.style.overflow = '';
});
describe('Modal', () => {
test('renders children when open', () => {
render(<Modal open onClose={vi.fn()}><div data-testid="body">hello</div></Modal>);
expect(container.querySelector('[data-testid="body"]')?.textContent).toBe('hello');
});
test('renders nothing when closed', () => {
render(<Modal open={false} onClose={vi.fn()}><div data-testid="body">hello</div></Modal>);
expect(container.querySelector('[data-testid="body"]')).toBeNull();
});
test('Escape calls onClose by default', () => {
const onClose = vi.fn();
render(<Modal open onClose={onClose}><div>body</div></Modal>);
pressEscape();
expect(onClose).toHaveBeenCalledTimes(1);
});
test('Escape does not call onClose when closeOnEscape is false', () => {
const onClose = vi.fn();
render(<Modal open onClose={onClose} closeOnEscape={false}><div>body</div></Modal>);
pressEscape();
expect(onClose).not.toHaveBeenCalled();
});
test('clicking the backdrop calls onClose by default', () => {
const onClose = vi.fn();
render(<Modal open onClose={onClose}><div data-testid="body">body</div></Modal>);
// The backdrop is the outermost rendered element.
click(container.firstElementChild);
expect(onClose).toHaveBeenCalledTimes(1);
});
test('clicking inside the content does not call onClose', () => {
const onClose = vi.fn();
render(<Modal open onClose={onClose}><div data-testid="body">body</div></Modal>);
click(container.querySelector('[data-testid="body"]'));
expect(onClose).not.toHaveBeenCalled();
});
test('clicking the backdrop does not call onClose when closeOnBackdropClick is false', () => {
const onClose = vi.fn();
render(<Modal open onClose={onClose} closeOnBackdropClick={false}><div>body</div></Modal>);
click(container.firstElementChild);
expect(onClose).not.toHaveBeenCalled();
});
test('locks body scroll while open and restores it on close', () => {
render(<Modal open onClose={vi.fn()}><div>body</div></Modal>);
expect(document.body.style.overflow).toBe('hidden');
act(() => { root.render(<Modal open={false} onClose={vi.fn()}><div>body</div></Modal>); });
expect(document.body.style.overflow).toBe('');
});
});
+94
View File
@@ -0,0 +1,94 @@
import React, { useEffect } from 'react';
export interface ModalProps {
open: boolean;
onClose: () => void;
title?: string;
children: React.ReactNode;
width?: number | string;
/** Override the backdrop's own inline styles (e.g. a different overlay
* opacity/z-index). Merged on top of the shared defaults. */
backdropStyle?: React.CSSProperties;
/** Escape key closes the modal. Default true — set false to preserve a
* modal that never handled Escape before this component existed. */
closeOnEscape?: boolean;
/** Clicking the backdrop (outside the modal content) closes the modal.
* Default true — set false to preserve a modal that never handled
* backdrop clicks before this component existed. */
closeOnBackdropClick?: boolean;
/** Extra attributes spread onto the backdrop div (e.g. role="dialog",
* aria-modal) for a modal that previously set those directly. */
backdropProps?: React.HTMLAttributes<HTMLDivElement>;
}
const defaultBackdropStyle: React.CSSProperties = {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.65)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 10000,
};
/* ---------- Shared modal chrome ----------
Backdrop + centered panel wrapper + Escape-to-close + scroll-lock, extracted
from TemplateModal / HeadCodeModal / SitesmithModal (task E4.3). Each
modal's own content — including its own header, close button, and panel
styling (background, radius, shadow, dimensions) — stays in that modal's
own file and is passed in as `children`, since those visuals differ across
the three. `closeOnEscape` / `closeOnBackdropClick` default to true (the
behavior TemplateModal and HeadCodeModal already had); SitesmithModal had
neither before this extraction, so it opts out of both to keep its exact
prior behavior. */
export const Modal: React.FC<ModalProps> = ({
open,
onClose,
title,
children,
width,
backdropStyle,
closeOnEscape = true,
closeOnBackdropClick = true,
backdropProps,
}) => {
useEffect(() => {
if (!open || !closeOnEscape) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [open, closeOnEscape, onClose]);
useEffect(() => {
if (!open) return;
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = prevOverflow;
};
}, [open]);
if (!open) return null;
return (
<div
{...backdropProps}
style={backdropStyle ? { ...defaultBackdropStyle, ...backdropStyle } : defaultBackdropStyle}
onClick={(e) => {
if (closeOnBackdropClick && e.target === e.currentTarget) onClose();
}}
>
<div style={width !== undefined ? { width } : undefined}>
{title !== undefined && (
<div style={{ fontSize: 15, fontWeight: 600, marginBottom: 8 }}>{title}</div>
)}
{children}
</div>
</div>
);
};
+5 -4
View File
@@ -1,5 +1,6 @@
import { describe, test, expect, vi } from 'vitest';
import { sanitizeAiTree, __test } from './apply-ai-response';
import type { SitesmithPatchOp } from '../types/sitesmith';
describe('findNodeIdByAiNodeId', () => {
const query = {
@@ -173,7 +174,7 @@ describe('applyPatch', () => {
text: 'Old',
style: { color: 'red', fontSize: '16px' },
});
const ops = [
const ops: SitesmithPatchOp[] = [
{
op: 'update_props',
node_id: 'ai-node-1',
@@ -194,7 +195,7 @@ describe('applyPatch', () => {
text: 'Old',
style: { color: 'red', fontSize: '16px' },
});
const ops = [
const ops: SitesmithPatchOp[] = [
{
op: 'update_props',
node_id: 'ai-node-1',
@@ -211,7 +212,7 @@ describe('applyPatch', () => {
const { query, actions, propsById } = makeSingleNodeHarness('craft-1', 'ai-node-1', {
style: { color: 'red', fontSize: '16px' },
});
const ops = [
const ops: SitesmithPatchOp[] = [
{ op: 'update_props', node_id: 'ai-node-1', props: { style: { color: 'blue' } } },
];
__test.applyPatch(actions, query, ops);
@@ -221,7 +222,7 @@ describe('applyPatch', () => {
test('an op with an unknown resolvedName tree is skipped without throwing; other ops in the batch still apply', () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { query, actions, propsById } = makeSingleNodeHarness('craft-1', 'ai-node-1', {});
const ops = [
const ops: SitesmithPatchOp[] = [
{
op: 'insert_after',
node_id: 'ai-node-1',
+8 -3
View File
@@ -1,7 +1,7 @@
import { useEditor } from '@craftjs/core';
import type { NodeTree } from '@craftjs/core';
import { usePages } from '../state/PageContext';
import { SitesmithResponse, SerializedTreeNode } from '../types/sitesmith';
import { SitesmithResponse, SerializedTreeNode, SitesmithPatchOp } from '../types/sitesmith';
import { sanitizeAiTree, flattenTreeForCraft } from './craft-tree';
// Re-exported for existing callers/tests that import sanitizeAiTree from
@@ -155,7 +155,7 @@ export function useApplyAiResponse() {
function applyPatch(
actions: any,
query: any,
ops: any[],
ops: SitesmithPatchOp[],
): { ok: boolean; message?: string } {
for (const op of ops) {
const id = findNodeIdByAiNodeId(query, op.node_id);
@@ -237,7 +237,12 @@ function applyPatch(
break;
default:
console.warn('sitesmith patch: unknown op', (op as any).op);
// Every SitesmithPatchOp variant is handled above, so `op` is typed
// `never` here at compile time — but the AI response is untrusted
// JSON (see useSitesmith.ts's `j: SendResult = await r.json()`), so
// a malformed/unrecognized `op` field can still reach this branch at
// runtime. Log the raw value rather than assuming a shape.
console.warn('sitesmith patch: unknown op', op);
}
}
return { ok: true };
+78
View File
@@ -0,0 +1,78 @@
import { describe, test, expect } from 'vitest';
import { cssValue } from './escape';
describe('cssValue', () => {
test('neutralizes </style> breakout', () => {
expect(cssValue('0px)}</style><script>alert(1)</script><style>{')).not.toContain('</style');
expect(cssValue('0px)}</style><script>alert(1)</script><style>{')).not.toContain('<script');
});
test('strips double quote (attribute breakout)', () => {
expect(cssValue('red" onmouseover="alert(1)')).not.toContain('"');
});
test('strips single quote', () => {
expect(cssValue("red' onmouseover='alert(1)")).not.toContain("'");
});
test('strips semicolon (declaration injection)', () => {
expect(cssValue('red;background:url(javascript:alert(1))')).not.toContain(';');
});
test('strips curly braces (rule injection)', () => {
expect(cssValue('red}body{background:red')).not.toContain('{');
expect(cssValue('red}body{background:red')).not.toContain('}');
});
test('strips angle brackets', () => {
expect(cssValue('<b>red</b>')).not.toContain('<');
expect(cssValue('<b>red</b>')).not.toContain('>');
});
test('strips backslash', () => {
expect(cssValue('red\\3c script')).not.toContain('\\');
});
test('neutralizes url( to block javascript: via background shorthand', () => {
expect(cssValue("red;background:url(javascript:alert(1))")).not.toMatch(/url\s*\(/i);
});
test('non-string input returns empty string', () => {
expect(cssValue(undefined)).toBe('');
expect(cssValue(null)).toBe('');
expect(cssValue(123 as unknown)).toBe('');
expect(cssValue({} as unknown)).toBe('');
});
test('preserves hex colors', () => {
expect(cssValue('#fff')).toBe('#fff');
expect(cssValue('#3b82f6')).toBe('#3b82f6');
});
test('preserves rgba()', () => {
expect(cssValue('rgba(0,0,0,.5)')).toBe('rgba(0,0,0,.5)');
});
test('preserves linear-gradient()', () => {
expect(cssValue('linear-gradient(90deg,#aaa 0%,#bbb 100%)')).toBe('linear-gradient(90deg,#aaa 0%,#bbb 100%)');
});
test('preserves calc()', () => {
expect(cssValue('calc(50% - 8px)')).toBe('calc(50% - 8px)');
});
test('preserves var()', () => {
expect(cssValue('var(--x)')).toBe('var(--x)');
});
test('preserves border shorthand', () => {
expect(cssValue('1px solid #ccc')).toBe('1px solid #ccc');
});
test('preserves px/%/em/rem sizes', () => {
expect(cssValue('24px')).toBe('24px');
expect(cssValue('50%')).toBe('50%');
expect(cssValue('1.5em')).toBe('1.5em');
expect(cssValue('2rem')).toBe('2rem');
});
});
+24
View File
@@ -79,6 +79,30 @@ export function safeUrl(s: string): string {
return trimmed;
}
/**
* Neutralizes CSS-context breakout for a single design-token value (color,
* length, gradient, etc.) so it is safe to interpolate RAW into either CSS
* context found in exported HTML:
* - ATTRIBUTE context: `style="color:${v}"` -- a `"` or `'` closes the
* attribute early; a `;` injects an extra declaration.
* - ELEMENT context: `<style>.x{color:${v}}</style>` -- `<`, `>`, `{`, `}`
* let a value close the rule / the `<style>` element itself and open a
* `<script>`, which is the worst case (arbitrary script execution).
* Strips the characters that can terminate a value, declaration, rule, or
* the `<style>` element itself, and neutralizes `url(` so a background
* shorthand can't smuggle a `javascript:` URL. None of hex colors,
* `rgb()`/`rgba()`, `var(...)`, gradients, `calc(...)`, or `px`/`%`/`em`/
* `rem` sizes contain any stripped character, so legitimate values pass
* through unchanged. If a sink legitimately needs a background image URL,
* route that value through `safeUrl` instead of `cssValue`.
*/
export function cssValue(v: unknown): string {
if (typeof v !== 'string') return '';
return v
.replace(/[<>{};"'\\]/g, '')
.replace(/url\s*\(/gi, '');
}
/**
* Derives a deterministic, HTML-id-safe slug from a field's `name`/`label`
* for wiring `<label for>` to a matching `<input id>` in exported markup.
+1 -1
View File
@@ -24,7 +24,7 @@ export default defineConfig({
server: {
port: 5173,
proxy: {
'/api': 'http://192.168.1.105:8080',
'/api': 'http://192.168.1.148:8080',
},
},
})