feat(site-builder): section library catalog, modal and insertion

Catalog skeleton with per-family files (one seed each for hero, services,
contact), live token-styled thumbnails, insert-after-selection, and
save-as-section into project extras.

Refs #52

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-10-07 11:52:25 -07:00
1 parent 8860349c9b
commit 6e819f1ef2
23 files changed
+903 -10

No files matched your search

+130
View File
@@ -0,0 +1,130 @@
import { describe, test, expect, afterEach } from 'vitest';
import { renderEditorHarness, EditorHarness } from '../test-utils/editorHarness';
import { exportBodyHtml } from '../utils/html-export';
import { flattenTreeForCraft } from '../utils/craft-tree';
import { templateComponentToTreeNode } from '../templates/apply-template';
import { DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
import {
SECTION_FAMILIES, getSections, insertSection, nodeTreeToSerializedTree, searchSections, type SectionDef, type CustomSection,
} from './catalog';
import { buildSectionPreviewDoc } from './thumbnails';
import { HERO_SECTIONS } from './families';
let h: EditorHarness;
afterEach(() => h?.unmount());
const hero = HERO_SECTIONS[0];
const rootKids = () => h.query.node('ROOT').get().data.nodes as string[];
const nameOf = (id: string) => h.query.node(id).get().data.displayName;
function addBlank(): string {
const sec: SectionDef = { id: 'x', name: 'x', family: 'hero', keywords: [], tree: { type: 'Section', props: {}, children: [{ type: 'Heading', props: { text: 'blank' } }] } };
return insertSection(h.query, h.actions, sec, { select: false });
}
describe('insertSection (real editor)', () => {
test('inserts after the selected top-level section and selects the new root', () => {
h = renderEditorHarness();
const a = addBlank();
const b = addBlank();
expect(rootKids()).toEqual([a, b]);
h.act(() => { h.actions.selectNode(a); });
let id = '';
h.act(() => { id = insertSection(h.query, h.actions, hero); });
expect(rootKids()).toEqual([a, id, b]);
expect(h.query.getEvent('selected').all()).toEqual([id]);
});
test('a selection nested inside a section resolves to its top-level ancestor', () => {
h = renderEditorHarness();
const a = addBlank();
const b = addBlank();
const nested = Object.keys(h.query.getNodes()).find((k) => nameOf(k) === 'Heading' && h.query.node(k).ancestors().includes(a))!;
h.act(() => { h.actions.selectNode(nested); });
let id = '';
h.act(() => { id = insertSection(h.query, h.actions, hero); });
expect(rootKids()).toEqual([a, id, b]);
});
test('appends when nothing is selected', () => {
h = renderEditorHarness();
const a = addBlank();
let id = '';
h.act(() => { id = insertSection(h.query, h.actions, hero); });
expect(rootKids()).toEqual([a, id]);
});
test('seed hero is token-based: no seed hex in the tree or the exported body', () => {
expect(JSON.stringify(hero.tree)).not.toMatch(/#[0-9a-fA-F]{3,8}\b/);
h = renderEditorHarness();
let id = '';
h.act(() => { id = insertSection(h.query, h.actions, hero); });
const html = exportBodyHtml(h.getSerialized()).html;
expect(html).toContain('Welcome to Your Business');
expect(html).toContain('var(--wsb-bg)');
expect(html).not.toContain(DEFAULT_SITE_DESIGN.primaryColor);
expect(nameOf(id)).toBe('Section');
});
});
describe('nodeTreeToSerializedTree round trip', () => {
test('saved section re-inserts with the same displayName sequence and no node_id', () => {
h = renderEditorHarness();
let id = '';
h.act(() => { id = insertSection(h.query, h.actions, getSections().find((s) => s.id === 'services-grid')!); });
const names = (root: string) => [root, ...h.query.node(root).decendants(true)].map(nameOf);
const before = names(id);
const ser = nodeTreeToSerializedTree(h.query, id);
expect(JSON.stringify(ser)).not.toContain('node_id');
const custom: CustomSection = { id: 'c1', name: 'Mine', family: 'custom', tree: ser, createdAt: 1 };
const def = getSections([custom]).find((s) => s.id === 'c1')!;
let id2 = '';
h.act(() => { id2 = insertSection(h.query, h.actions, def); });
expect(id2).not.toBe(id);
expect(names(id2)).toEqual(before);
expect(before).toContain('Features Grid');
});
});
describe('search / families', () => {
test('family filter and keyword search', () => {
expect(searchSections('', 'hero').every((s) => s.family === 'hero')).toBe(true);
expect(searchSections('', 'hero').length).toBeGreaterThan(0);
expect(searchSections('banner').map((s) => s.id)).toContain('hero-centered');
expect(searchSections('banner', 'services')).toEqual([]);
expect(searchSections('zzzz-nothing')).toEqual([]);
});
test('unique ids and known families', () => {
const all = getSections();
expect(new Set(all.map((s) => s.id)).size).toBe(all.length);
const fam = new Set(SECTION_FAMILIES.map((f) => f.id));
for (const s of all) expect(fam.has(s.family)).toBe(true);
});
});
describe('every built-in section (validates content tasks after merge)', () => {
for (const def of getSections()) {
test(`${def.id} flattens, exports and previews`, () => {
expect(() => flattenTreeForCraft(templateComponentToTreeNode(def.tree))).not.toThrow();
const doc = buildSectionPreviewDoc(def, { ...DEFAULT_SITE_DESIGN, primaryColor: '#123456' });
expect(doc).toContain('--wsb-primary:#123456');
expect(doc).not.toContain('Export failed');
h = renderEditorHarness();
h.act(() => { insertSection(h.query, h.actions, def); });
const out = exportBodyHtml(h.getSerialized()).html;
expect(out.length).toBeGreaterThan(0);
expect(out).not.toContain('Export failed');
h.unmount();
});
}
});
describe('buildSectionPreviewDoc', () => {
test('carries the design tokens and the section heading text', () => {
const design = { ...DEFAULT_SITE_DESIGN, primaryColor: '#abcdef' };
const doc = buildSectionPreviewDoc(hero, design);
expect(doc).toContain('--wsb-primary:#abcdef');
expect(doc).toContain('Welcome to Your Business');
expect(doc).not.toContain('<script');
});
});
+175
View File
@@ -0,0 +1,175 @@
import { useMemo } from 'react';
import type { SerializedTreeNode } from '../types/sitesmith';
import type { TemplateComponent } from '../templates/definitions';
import { templateComponentToTreeNode } from '../templates/apply-template';
import { buildNodeTree } from '../utils/craft-tree';
import { getAncestorIds, getIndexInParent } from '../utils/craft-helpers';
import { componentResolver } from '../components/resolver';
import { useProjectExtras } from '../state/ProjectExtrasContext';
import { BUILTIN_SECTIONS } from './families';
export type SectionFamily =
| 'hero' | 'services' | 'about' | 'social-proof' | 'faq' | 'contact'
| 'hours' | 'cta' | 'pricing' | 'gallery' | 'team' | 'custom';
export interface SectionDef {
id: string;
name: string;
family: SectionFamily;
keywords: string[];
/** Token-based template tree (same DSL as templates/definitions.ts). */
tree: TemplateComponent;
}
export const SECTION_FAMILIES: Array<{ id: SectionFamily; label: string }> = [
{ id: 'hero', label: 'Hero' },
{ id: 'services', label: 'Services' },
{ id: 'about', label: 'About' },
{ id: 'social-proof', label: 'Social proof' },
{ id: 'faq', label: 'FAQ' },
{ id: 'contact', label: 'Contact' },
{ id: 'hours', label: 'Hours' },
{ id: 'cta', label: 'Call to action' },
{ id: 'pricing', label: 'Pricing' },
{ id: 'gallery', label: 'Gallery' },
{ id: 'team', label: 'Team' },
{ id: 'custom', label: 'My sections' },
];
/** `extras.customSections` entry: a section the user saved from their canvas. */
export interface CustomSection {
id: string;
name: string;
family: 'custom';
tree: SerializedTreeNode;
createdAt: number;
}
export const CUSTOM_SECTIONS_KEY = 'customSections';
/** Serialized tree -> the TemplateComponent DSL (inverse of templateComponentToTreeNode). */
function serializedToTemplate(node: SerializedTreeNode): TemplateComponent {
const comp: TemplateComponent = { type: node.type.resolvedName, props: { ...node.props } };
if (node.nodes && node.nodes.length) comp.children = node.nodes.map(serializedToTemplate);
return comp;
}
export function customToDef(c: CustomSection): SectionDef {
return { id: c.id, name: c.name, family: 'custom', keywords: [], tree: serializedToTemplate(c.tree) };
}
export function getSections(custom: CustomSection[] = []): SectionDef[] {
return [...BUILTIN_SECTIONS, ...custom.map(customToDef)];
}
/** Built-ins plus the site's own saved sections. Reads extras at render time
* (extras are ref-backed; callers that mutate them re-render themselves). */
export function useSections(version = 0): SectionDef[] {
const extras = useProjectExtras();
return useMemo(
() => getSections(extras.get<CustomSection[]>(CUSTOM_SECTIONS_KEY, [])),
// eslint-disable-next-line react-hooks/exhaustive-deps
[extras, version],
);
}
/** Case-insensitive match over name, family label and keywords; every query
* word must hit. Optional family restricts the pool first. */
export function searchSections(q: string, family?: SectionFamily | null, pool: SectionDef[] = getSections()): SectionDef[] {
const inFamily = family ? pool.filter((s) => s.family === family) : pool;
const words = q.toLowerCase().split(/\s+/).filter(Boolean);
if (words.length === 0) return inFamily;
return inFamily.filter((s) => {
const label = SECTION_FAMILIES.find((f) => f.id === s.family)?.label ?? '';
const hay = [s.name, label, s.family, ...s.keywords].join(' ').toLowerCase();
return words.every((w) => hay.includes(w));
});
}
export interface InsertSectionOptions {
/** Insert after the top-level section containing the selection (default true). */
afterSelection?: boolean;
/** Select the new root (default true). */
select?: boolean;
}
/** The id of the ROOT child that contains `id` (or is `id`), else null. */
function topLevelAncestor(query: any, id: string): string | null {
if (!id || id === 'ROOT') return null;
const chain = [id, ...getAncestorIds(query, id)];
return chain[chain.length - 1];
}
/** Materialize a section into ROOT: after the selected top-level section, or
* appended. Fresh node ids come from buildNodeTree. Returns the new root id. */
export function insertSection(query: any, actions: any, def: SectionDef, opts: InsertSectionOptions = {}): string {
const tree = buildNodeTree(query, templateComponentToTreeNode(def.tree));
let index: number | undefined;
if (opts.afterSelection !== false) {
try {
const sel: string[] = query.getEvent('selected').all();
const top = sel.length ? topLevelAncestor(query, sel[0]) : null;
if (top) {
const idx = getIndexInParent(query, top);
if (idx !== -1) index = idx + 1;
}
} catch {
// No usable selection: append.
}
}
actions.addNodeTree(tree, 'ROOT', index);
if (opts.select !== false) {
try { actions.selectNode(tree.rootNodeId); } catch { /* nothing to select */ }
}
return tree.rootNodeId;
}
function resolvedNameOf(data: any): string | null {
if (typeof data?.name === 'string' && data.name) return data.name;
if (data?.type?.resolvedName) return data.type.resolvedName;
for (const [name, comp] of Object.entries(componentResolver)) {
if (comp === data?.type) return name;
}
return null;
}
/**
* Live Craft subtree -> SerializedTreeNode (the shape buildNodeTree takes).
* Shell wrappers (Section's inner Container) are flattened back to plain
* children and ColumnLayout columns back to child nodes, the inverse of
* flattenTreeForCraft. `node_id` is dropped so a re-insert gets fresh ids;
* `aiName` is kept.
*/
export function nodeTreeToSerializedTree(query: any, rootId: string): SerializedTreeNode {
const walk = (id: string): SerializedTreeNode => {
const data = query.node(id).get()?.data;
const name = resolvedNameOf(data);
if (!name) throw new Error(`nodeTreeToSerializedTree: unknown component for node ${id}`);
const props: Record<string, unknown> = JSON.parse(JSON.stringify(data.props ?? {}));
delete props.node_id;
const children: string[] = [...(data.nodes || [])];
const linked: Record<string, string> = data.linkedNodes || {};
const out: SerializedTreeNode = { type: { resolvedName: name }, props };
const kids: SerializedTreeNode[] = children.map(walk);
if (name === 'ColumnLayout') {
Object.keys(linked)
.sort((a, b) => Number(a.replace(/\D/g, '')) - Number(b.replace(/\D/g, '')))
.forEach((k) => kids.push(walk(linked[k])));
} else {
for (const innerId of Object.values(linked)) {
// Section / BackgroundSection / FormContainer inner canvas: hoist its children.
const inner = query.node(innerId).get()?.data;
for (const cid of inner?.nodes || []) kids.push(walk(cid));
}
}
if (kids.length) out.nodes = kids;
return out;
};
return walk(rootId);
}
/** True when `id` is a direct child of ROOT (a saveable top-level section). */
export function isTopLevelSection(query: any, id: string | undefined): boolean {
if (!id || id === 'ROOT') return false;
try { return query.node(id).get()?.data?.parent === 'ROOT'; } catch { return false; }
}
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to ABOUT_SECTIONS only (see hero.ts for the shape). */
export const ABOUT_SECTIONS: SectionDef[] = [];
+21
View File
@@ -0,0 +1,21 @@
import type { SectionDef } from '../catalog';
import { tokenRef } from '../../utils/tokens';
/** Contact sections. Content tasks append to CONTACT_SECTIONS only. */
export const CONTACT_SECTIONS: SectionDef[] = [
{
id: 'contact-form',
name: 'Contact form',
family: 'contact',
keywords: ['form', 'message', 'enquiry', 'get in touch', 'email'],
tree: {
type: 'Section',
props: { aiName: 'Contact', style: { padding: '72px 20px', backgroundColor: tokenRef('bg') } },
children: [
{ type: 'Heading', props: { text: 'Get in Touch', level: 'h2', style: { textAlign: 'center', color: tokenRef('text'), fontFamily: tokenRef('heading-font'), marginBottom: '12px' } } },
{ type: 'TextBlock', props: { text: 'Send us a message and we will reply as soon as we can.', style: { textAlign: 'center', color: tokenRef('muted'), marginBottom: '24px' } } },
{ type: 'ContactForm', props: {} },
],
},
},
];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to CTA_SECTIONS only (see hero.ts for the shape). */
export const CTA_SECTIONS: SectionDef[] = [];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to FAQ_SECTIONS only (see hero.ts for the shape). */
export const FAQ_SECTIONS: SectionDef[] = [];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to GALLERY_SECTIONS only (see hero.ts for the shape). */
export const GALLERY_SECTIONS: SectionDef[] = [];
+26
View File
@@ -0,0 +1,26 @@
import type { SectionDef } from '../catalog';
import { tokenRef } from '../../utils/tokens';
/**
* Hero sections. Shape reference for the content tasks: append to
* HERO_SECTIONS only. Trees are token-based (no raw hex) so a section takes
* on the site's palette and fonts, and set no `animation` (the thumbnail
* iframe is script-less).
*/
export const HERO_SECTIONS: SectionDef[] = [
{
id: 'hero-centered',
name: 'Centered hero',
family: 'hero',
keywords: ['headline', 'banner', 'intro', 'welcome', 'landing'],
tree: {
type: 'Section',
props: { aiName: 'Hero', style: { padding: '96px 20px', backgroundColor: tokenRef('bg'), textAlign: 'center' } },
children: [
{ type: 'Heading', props: { text: 'Welcome to Your Business', level: 'h1', style: { textAlign: 'center', color: tokenRef('text'), fontFamily: tokenRef('heading-font'), marginBottom: '16px' } } },
{ type: 'TextBlock', props: { text: 'Tell visitors in one or two sentences what you do and who you do it for.', style: { textAlign: 'center', maxWidth: '640px', margin: '0 auto 24px', color: tokenRef('muted'), lineHeight: '1.7' } } },
{ type: 'ButtonLink', props: { text: 'Get in touch', href: 'contact' } },
],
},
},
];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to HOURS_SECTIONS only (see hero.ts for the shape). */
export const HOURS_SECTIONS: SectionDef[] = [];
+27
View File
@@ -0,0 +1,27 @@
import type { SectionDef } from '../catalog';
import { HERO_SECTIONS } from './hero';
import { SERVICES_SECTIONS } from './services';
import { ABOUT_SECTIONS } from './about';
import { CTA_SECTIONS } from './cta';
import { SOCIAL_PROOF_SECTIONS } from './social-proof';
import { FAQ_SECTIONS } from './faq';
import { PRICING_SECTIONS } from './pricing';
import { TEAM_SECTIONS } from './team';
import { CONTACT_SECTIONS } from './contact';
import { HOURS_SECTIONS } from './hours';
import { GALLERY_SECTIONS } from './gallery';
import { LOCAL_SECTIONS } from './local';
export {
HERO_SECTIONS, SERVICES_SECTIONS, ABOUT_SECTIONS, CTA_SECTIONS,
SOCIAL_PROOF_SECTIONS, FAQ_SECTIONS, PRICING_SECTIONS, TEAM_SECTIONS,
CONTACT_SECTIONS, HOURS_SECTIONS, GALLERY_SECTIONS, LOCAL_SECTIONS,
};
/** Every built-in section, in gallery order. `LOCAL_SECTIONS` entries carry
* one of the regular family ids (local-business flavoured content). */
export const BUILTIN_SECTIONS: SectionDef[] = [
...HERO_SECTIONS, ...SERVICES_SECTIONS, ...ABOUT_SECTIONS, ...CTA_SECTIONS,
...SOCIAL_PROOF_SECTIONS, ...FAQ_SECTIONS, ...PRICING_SECTIONS, ...TEAM_SECTIONS,
...CONTACT_SECTIONS, ...HOURS_SECTIONS, ...GALLERY_SECTIONS, ...LOCAL_SECTIONS,
];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to LOCAL_SECTIONS only (see hero.ts for the shape). */
export const LOCAL_SECTIONS: SectionDef[] = [];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to PRICING_SECTIONS only (see hero.ts for the shape). */
export const PRICING_SECTIONS: SectionDef[] = [];
+30
View File
@@ -0,0 +1,30 @@
import type { SectionDef } from '../catalog';
import { tokenRef } from '../../utils/tokens';
/** Services sections. Content tasks append to SERVICES_SECTIONS only. */
export const SERVICES_SECTIONS: SectionDef[] = [
{
id: 'services-grid',
name: 'Services grid',
family: 'services',
keywords: ['features', 'offerings', 'what we do', 'benefits'],
tree: {
type: 'Section',
props: { aiName: 'Services', style: { padding: '72px 20px', backgroundColor: tokenRef('bg') } },
children: [
{ type: 'Heading', props: { text: 'Our Services', level: 'h2', style: { textAlign: 'center', color: tokenRef('text'), fontFamily: tokenRef('heading-font'), marginBottom: '24px' } } },
{
type: 'FeaturesGrid',
props: {
features: [
{ title: 'Service one', description: 'A short description of what this service includes.', icon: '⭐' },
{ title: 'Service two', description: 'A short description of what this service includes.', icon: '🛠️' },
{ title: 'Service three', description: 'A short description of what this service includes.', icon: '💬' },
],
style: { backgroundColor: tokenRef('bg') },
},
},
],
},
},
];
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to SOCIAL_PROOF_SECTIONS only (see hero.ts for the shape). */
export const SOCIAL_PROOF_SECTIONS: SectionDef[] = [];
+4
View File
@@ -0,0 +1,4 @@
import type { SectionDef } from '../catalog';
/** Content task appends to TEAM_SECTIONS only (see hero.ts for the shape). */
export const TEAM_SECTIONS: SectionDef[] = [];
+21
View File
@@ -0,0 +1,21 @@
import type { SiteDesign } from '../state/SiteDesignContext';
import { templateComponentToTreeNode } from '../templates/apply-template';
import { flattenTreeForCraft } from '../utils/craft-tree';
import { exportToHtml } from '../utils/html-export';
import type { SectionDef } from './catalog';
/** Full HTML document of one section rendered with the site's own tokens and
* fonts, for a sandboxed (script-less) `<iframe srcdoc>` thumbnail. Uses the
* exact static export path, so it matches what publishing would produce. */
export function buildSectionPreviewDoc(def: SectionDef, design: SiteDesign): string {
const flat = flattenTreeForCraft(templateComponentToTreeNode(def.tree));
const nodes: Record<string, unknown> = { ...flat.nodes };
// exportToHtml walks from ROOT; hang the section under a synthetic one.
const rootChildren = [flat.rootNodeId];
(nodes[flat.rootNodeId] as any).parent = 'ROOT';
nodes.ROOT = {
type: { resolvedName: 'Container' }, isCanvas: true, props: {}, displayName: 'Container',
custom: {}, hidden: false, parent: null, nodes: rootChildren, linkedNodes: {},
};
return exportToHtml(JSON.stringify(nodes), { design, includeFonts: true }).html;
}