Files
openmotion/shared/design-catalog.ts
Tom Huang ef577a7844 feat(design): integrate Open Design HTML workflows, MCP tools, and Design Studio editor (#699)
* feat(design): add Design Studio project contract and locale resources

* feat(design): port Open Design templates, systems, skills, craft and scenario guides

* feat(design): add shared design-projects service, HTTP adapter, 4 MCP tools and openmotion-design Skill

* feat(design): add Design Studio HTML preview editor, scene tabs, Explore and MCP handbook entries

* feat(design): polish Design Studio UI, live preview bridge, packaging and stdio MCP E2E tests

- Upgrade Design Studio visual design: editorial hero and elevated composer dock with Design System swatches, Design Skill picker, and example prompt pills; edge-to-edge ScaledPreviewThumb gallery cards; dot-grid device frame canvas with dimension captions; syntax-highlighted line-numbered CodeViewer; inline project rename and Open-in actions; symmetrical 8-card Explore template shelf
- Keep preview bridge mounted for live HTML previews without iframe reloads on tool toggle, prevent overlay pointer capture from swallowing annotation popover clicks, and eliminate redundant initial raw preview fetches
- Complete all 10 non-English locale dictionaries in design-ui.json and design-editor-ui.json
- Register library/design and docs/design-studio.md in distribution packaging, include openmotion-design in package Skill checks, exercise all 4 openmotion_design_* tools in phase1-package.mjs, and schedule design test suites in CI
- Add live stdio MCP subprocess E2E coverage and CodeViewer/DesignProjectList Vitest coverage

* chore(design): remove redundant More studios dropdown from DesignSceneTabs

* feat(design): add Mobile App scenario with 390x844 phone preview default

* perf(design): freeze idle rAF/WebGL/CSS animations in preview thumbs and unmount offscreen iframes

* feat(design): reuse Motion Brand Kits for Design Studio picker with hover preview and detail modal

* feat(design): add Motion-aligned Design template detail preview modal with responsive stage and navigation

* feat(design): support @ mention autocomplete and composable multi-select templates, skills and prompts in composer

* fix(design): unify studio bar tab heights to eliminate layout shift between image and design scenes

* fix(design): keep Design Studio sub-navigation bar on a single responsive row

* feat(design): move Design Studio composer to floating bottom dock with scrollable middle template gallery

* chore(design): assign dedicated mobile-app templates from Open Design catalog without overlap with prototype

* feat(design): curate flagship-first template ordering and clean gallery-first card styling

* fix(design): constrain BrandKitPicker popover max-width and scroll container height to prevent overflow

* fix(design): align active scene tab styling with Text-to-Image and match search input and button heights

* fix(design): center editor toolbar with 3-column grid and remove idle pill background on annotation tools

* refactor(design): move Preview/Code and viewport selector into canvas toolbar and use compact annotation icons

* fix(design): remove inner textarea focus ring and align composer border radii

* fix(design): match filter input height to 32px md Button height

* fix(design): eliminate leaked media-surface border on composer textarea and align template detail stage with Motion

* docs(design): include mobile-app in Design Studio scenario documentation

* feat(design): make Copy to Agent prompts self-contained with MCP install and live workspace setup

* fix(design): replace opaque region fill with crisp translucent marquee and smart popover placement

* fix(design): remove internal-link demo URL and duplicate i18n keys that overwrote Studio translations

* feat(design): keep drawn pen strokes visible during compose, add visual previews in annotations, and focus on click

* fix(design): make toolbar Comments counter button toggle the Comments panel with active state

* fix(design): auto-size project title input and remove leaked media-surface fill and gap

* test(design): pass anchor in phase1 package comment smoke and target platform-export scenario by data attribute

* fix(design): address PR review findings on entry restore, preview isolation, coordinates, save revisions, and icons

* fix(design): reject overlapping write/delete paths, enable conflict overwrite retry, and hoist optional annotation bindings

* fix(design): fetch latest project and file before rebasing discarded code draft

* fix(design): clear codeLoading in finally when discard reload fails

---------

Co-authored-by: pftom <pftom@pftomdeMacBook-Pro.local>
Co-authored-by: pftom <pftom@pftomdeMBP.lan>
Co-authored-by: pftom <pftom@Mac.lan>
2026-11-20 14:38:40 +08:00

204 lines
10 KiB
TypeScript

/**
* Read-only catalogue of the Design Studio library under library/design: scenario guides,
* starter templates, design systems, design Skills and craft references. Ported from
* Open Design (Apache-2.0, see library/design/NOTICE.md). Node-only; synchronous reads
* are cached in memory per library root.
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
designRoutes, designScenarios, isDesignScenario,
type DesignScenarioId, type DesignSkillSummary, type DesignSystemSummary, type DesignTemplateSummary,
} from './design-project.ts';
export const designLibraryRoot = fileURLToPath(new URL('../library/design', import.meta.url));
export const DESIGN_CATALOG_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/;
export const isDesignCatalogId = (value: unknown): value is string => typeof value === 'string' && DESIGN_CATALOG_ID.test(value) && !value.includes('..');
type TemplateRecord = Omit<DesignTemplateSummary, 'previewUrl'>;
type SystemRecord = Omit<DesignSystemSummary, 'previewUrl'> & { preview?: string | null };
type SkillRecord = DesignSkillSummary;
type CatalogFile<K extends string, T> = { schemaVersion: number } & { [key in K]: T[] };
export type DesignScenarioGuide = (typeof designScenarios)[number] & { guide: string };
export type DesignTemplateDetail = DesignTemplateSummary & { dir: string; files: string[]; readme: string | null };
export type DesignSystemDetail = DesignSystemSummary & { designMd: string; tokensCss: string | null };
export type DesignSkillDetail = DesignSkillSummary & { content: string; references: string[] };
export type DesignTemplateQuery = { scenario?: string; q?: string; limit?: number; cursor?: string };
const MAX_LIMIT = 200;
const DEFAULT_LIMIT = 48;
const TEXT_REFERENCE = /\.(md|markdown|txt|json|html?|css|js|mjs|svg|py|ts|ya?ml)$/i;
function readText(file: string): string | null {
try { return readFileSync(file, 'utf8'); } catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR') return null;
throw error;
}
}
function readJson<T>(file: string, fallback: T): T {
const text = readText(file);
return text === null ? fallback : JSON.parse(text) as T;
}
/** Resolve a catalogue-relative path and refuse anything that escapes `base`. */
function inside(base: string, relative: string): string | null {
if (typeof relative !== 'string' || !relative || relative.includes('\0') || path.isAbsolute(relative)) return null;
const resolved = path.resolve(base, relative);
const rel = path.relative(base, resolved);
return !rel || rel.startsWith('..') || path.isAbsolute(rel) ? null : resolved;
}
function listFiles(base: string): string[] {
const out: string[] = [];
const walk = (relative: string) => {
let entries;
try { entries = readdirSync(path.join(base, relative), { withFileTypes: true }); } catch { return; }
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
if (entry.name.startsWith('.')) continue;
const child = relative ? `${relative}/${entry.name}` : entry.name;
if (entry.isDirectory()) walk(child);
else if (entry.isFile()) out.push(child);
}
};
walk('');
return out;
}
const normalize = (value: string) => value.toLowerCase().normalize('NFKD');
function matches(query: string | undefined, fields: Array<string | null | undefined | string[]>) {
const q = query?.trim();
if (!q) return true;
const haystack = normalize(fields.flat().filter(Boolean).join(' \u0000 '));
return normalize(q).split(/\s+/).every(term => haystack.includes(term));
}
function createCatalog(root: string) {
const templatesDir = path.join(root, 'templates');
const systemsDir = path.join(root, 'systems');
const skillsDir = path.join(root, 'skills');
const craftDir = path.join(root, 'craft');
const scenariosDir = path.join(root, 'scenarios');
let templateRecords: TemplateRecord[] | undefined;
let systemRecords: SystemRecord[] | undefined;
let skillRecords: SkillRecord[] | undefined;
let craftRecords: { id: string; title: string }[] | undefined;
let scenarioGuides: DesignScenarioGuide[] | undefined;
const loadTemplates = () => templateRecords ??= readJson<CatalogFile<'templates', TemplateRecord>>(path.join(templatesDir, 'catalog.json'), { schemaVersion: 1, templates: [] }).templates
.filter(item => isDesignCatalogId(item.id) && isDesignScenario(item.scenario));
const loadSystems = () => systemRecords ??= readJson<CatalogFile<'systems', SystemRecord>>(path.join(systemsDir, 'catalog.json'), { schemaVersion: 1, systems: [] }).systems
.filter(item => isDesignCatalogId(item.id));
const loadSkills = () => skillRecords ??= readJson<CatalogFile<'skills', SkillRecord>>(path.join(skillsDir, 'catalog.json'), { schemaVersion: 1, skills: [] }).skills
.filter(item => isDesignCatalogId(item.id))
.map(item => ({ ...item, scenario: isDesignScenario(item.scenario) ? item.scenario : null }));
const templateSummary = (record: TemplateRecord): DesignTemplateSummary => ({ ...record, previewUrl: designRoutes.catalogTemplatePreview(record.id, record.entry) });
const systemSummary = ({ preview, ...record }: SystemRecord): DesignSystemSummary => ({
...record,
// Systems have no dedicated static route; a preview page, when shipped, is served by the catalog system route.
previewUrl: preview ? `${designRoutes.catalogSystem(record.id)}/${preview}` : null,
});
return {
scenarios(): DesignScenarioGuide[] {
return scenarioGuides ??= designScenarios.map(scenario => ({ ...scenario, guide: readText(path.join(scenariosDir, `${scenario.id}.md`)) ?? '' }));
},
templates(opts: DesignTemplateQuery = {}): { items: DesignTemplateSummary[]; nextCursor: string | null } {
const filtered = loadTemplates().filter(item => (!opts.scenario || item.scenario === opts.scenario)
&& matches(opts.q, [item.id, item.title, item.description, item.category, item.tags, item.scenario]));
const limit = Math.max(1, Math.min(MAX_LIMIT, Math.floor(Number(opts.limit) || DEFAULT_LIMIT)));
const start = /^\d+$/.test(opts.cursor ?? '') ? Number(opts.cursor) : 0;
const items = filtered.slice(start, start + limit).map(templateSummary);
return { items, nextCursor: start + limit < filtered.length ? String(start + limit) : null };
},
template(id: string): DesignTemplateDetail | null {
if (!isDesignCatalogId(id)) return null;
const record = loadTemplates().find(item => item.id === id);
const dir = record && inside(templatesDir, id);
if (!record || !dir || !existsSync(dir)) return null;
return { ...templateSummary(record), dir, files: listFiles(dir), readme: readText(path.join(dir, 'README.md')) };
},
/** Absolute path of a template file for static preview serving, or null when missing or outside the template. */
templateFile(id: string, relative: string): string | null {
if (!isDesignCatalogId(id) || !loadTemplates().some(item => item.id === id)) return null;
const dir = inside(templatesDir, id);
const file = dir && inside(dir, relative);
try { return file && statSync(file).isFile() ? file : null; } catch { return null; }
},
systems(opts: { q?: string; category?: string } = {}): DesignSystemSummary[] {
return loadSystems().filter(item => (!opts.category || item.category === opts.category)
&& matches(opts.q, [item.id, item.title, item.description, item.category])).map(systemSummary);
},
system(id: string): DesignSystemDetail | null {
if (!isDesignCatalogId(id)) return null;
const record = loadSystems().find(item => item.id === id);
const dir = record && inside(systemsDir, id);
const designMd = dir ? readText(path.join(dir, 'DESIGN.md')) : null;
if (!record || !dir || designMd === null) return null;
return { ...systemSummary(record), designMd, tokensCss: readText(path.join(dir, 'tokens.css')) };
},
skills(opts: { scenario?: string; q?: string } = {}): DesignSkillSummary[] {
return loadSkills().filter(item => (!opts.scenario || item.scenario === opts.scenario)
&& matches(opts.q, [item.id, item.title, item.description, item.category, item.scenario]));
},
skill(id: string): DesignSkillDetail | null {
if (!isDesignCatalogId(id)) return null;
const record = loadSkills().find(item => item.id === id);
const dir = record && inside(skillsDir, id);
const content = dir ? readText(path.join(dir, 'SKILL.md')) : null;
if (!record || !dir || content === null) return null;
return { ...record, content, references: listFiles(dir).filter(file => file !== 'SKILL.md' && TEXT_REFERENCE.test(file)) };
},
skillReference(id: string, relative: string): string | null {
if (!isDesignCatalogId(id) || !loadSkills().some(item => item.id === id)) return null;
const dir = inside(skillsDir, id);
const file = dir && inside(dir, relative);
return file && TEXT_REFERENCE.test(file) ? readText(file) : null;
},
craft(): { id: string; title: string }[] {
return craftRecords ??= listFiles(craftDir)
.filter(file => /^[a-z0-9][a-z0-9._-]*\.md$/.test(file) && file !== 'README.md')
.map(file => {
const id = file.slice(0, -3);
const heading = /^#\s+(.+)$/m.exec(readText(path.join(craftDir, file)) ?? '')?.[1]?.trim();
return { id, title: heading || id };
});
},
craftDoc(id: string): string | null {
if (!isDesignCatalogId(id) || id === 'README') return null;
return readText(path.join(craftDir, `${id}.md`));
},
};
}
export type DesignCatalog = ReturnType<typeof createCatalog>;
const catalogs = new Map<string, DesignCatalog>();
export function designCatalog(root = designLibraryRoot): DesignCatalog {
const key = path.resolve(root);
let catalog = catalogs.get(key);
if (!catalog) catalogs.set(key, catalog = createCatalog(key));
return catalog;
}
/** Drop cached catalogue reads (tests and library maintenance scripts). */
export function resetDesignCatalogCache() { catalogs.clear(); }
export type { DesignScenarioId };