The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
[OPEND-4726] feat(studio): align template library with website catalog (#243)
open-design-crew[bot]af5497367ec2
diff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex c4f1f607..8f300913 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -20,7 +20,7 @@ Model Gateway remains a shared media-generation backend for MCP, using local Cod- The project sidebar opens as a modal drawer over the editor at every viewport size. It starts closed, leaves the editor dimensions unchanged, and closes via its button, outside click or Escape. The header toggle remains mounted for focus restoration; privacy, theme and language settings live in the drawer footer. Error and empty-session views retain a drawer toggle so users can select an existing project or create one. Project rows show names without dates; the heading offers a New project button instead of a count. Creation uses the existing save and revision guards before opening the blank project.- Preview zoom percentage and Fit sit in the MVP preview header, outside the picture; fullscreen retains the in-view controls.- The composition list marks the live preview target, including the full video. The MVP omits the duplicate preview breadcrumb; composition switching and existing return shortcuts remain available.-- The editor header keeps the OpenDesign logo, drawer toggle and template library on the left, centers the editable project name, and places undo/redo and export on the right. Transient save/error status remains available. The template modal preserves previews and author/source links, without integration setup sections.+- The editor header keeps the OpenDesign logo, drawer toggle and template library on the left, centers the editable project name, and places undo/redo and export on the right. Transient save/error status remains available. The template library reuses the website catalog layout: brand/use-case/video-type facets, configured featured templates, search and sorting, without site navigation, promotional hero or footer. Prism metadata and local cache updates drive the list. Previews, author/source links and editable-project opening remain available. The detail view keeps the motion.md download action (`motionDocumentUrl`) above its guide content (`styleDescription`, `reviewFocus`, `motionGuideUrl`). Recreate opens a separate prompt dialog; copied instructions never occupy the guide area.- The asset panel shows only the current project, with compact search/import controls, type filters, and a dedicated scrollable list. Usage filtering is omitted; used assets still sort first within each type. The global cache view remains in source but has no editor entry in the MVP.- Panel positions are fixed. Divider resizing and per-project size persistence remain; panel movement, closing and layout presets are absent. Preview alone can temporarily expand within the editor workspace, keeping the host chat visible and the player mounted. Its header button or Escape restores the previous layout and playback position; expansion is not persisted across reloads.- MVP controls share a locally bundled Remix Icon 4.9.1 set with the reference design system. Side-panel tabs remain text-only; brand artwork and timeline geometry are separate from control icons.@@ -28,7 +28,7 @@ Model Gateway remains a shared media-generation backend for MCP, using local Cod- The MVP omits the standalone timeline title strip to give its space to tracks, retaining the tool row and ruler.- The MVP shows Select and Split as adjacent timeline tools. Split at playhead remains available by keyboard shortcut, without a duplicate toolbar button. Tooltips add a short explanation for less familiar controls while simple actions retain a name-only hint.- 模板先展示真实成片效果;作者、出处、内容种类和有来源的热度帮助选择。-- 交给 Agent 的复刻指令保持简短;详细配置、模板 ID 和流程由参数化指引链接承载。+- Template copy uses the public environment-specific installation guide, the exact template title/ID, the requested HTML/MP4 deliverables and an empty requirements section. Local connection guides remain available for workspace setup.- 导出成功需要真实产物与验证证据;技术检查与画面、声音、播放器检查分别记录。## 对外主张与 Motion.md 方向diff --git a/prism-templates.ts b/prism-templates.tsindex c0a0f65f..823ca87d 100644--- a/prism-templates.ts+++ b/prism-templates.ts@@ -11,6 +11,9 @@ type PrismTemplate = {templateId: string; sortOrder: number; original: Record<string, string>;indexUrl: string; previewUrl: string; coverUrl: string; files: TemplateFile[];conversionStatus?: string; conversionNotes?: string;+ motionDocumentUrl?: string; motionGuideUrl?: string; projectFileUrl?: string; authorAvatarUrl?: string;+ brand?: string; creationModels?: string[]; colors?: string[]; industries?: string[];+ width?: number; height?: number; featuredOrder?: number | null;};type Publication = {resourceId: string; environment: string; channel: string; publicationId: string;@@ -18,6 +21,7 @@ type Publication = {};type Snapshot = { etag: string | null; publication: Publication };export type EditableTemplate = GalleryTemplate & { files?: TemplateFile[]; catalogVersion?: string; conversionStatus?: string; conversionNotes?: string };+const splitTags = (value = '') => value.split(/[,,]/).map(tag => tag.trim()).filter(Boolean);const builtinTemplates = libraryTemplates.filter(template => template.kind === 'builtin');const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');@@ -115,6 +119,13 @@ export class TemplateCatalog {sourceUrl: item.original.sourceUrl, previewUrl: item.previewUrl, posterUrl: item.coverUrl,files: item.files, catalogVersion: snapshot.publication.publicationId,conversionStatus: item.conversionStatus, conversionNotes: item.conversionNotes,+ motionDocumentUrl: item.motionDocumentUrl, motionGuideUrl: item.motionGuideUrl,+ projectFileUrl: item.projectFileUrl, authorAvatarUrl: item.authorAvatarUrl,+ styleDescription: item.original.styleDescription, reviewFocus: item.original.reviewFocus,+ brand: item.brand, uses: splitTags(item.original.promotionalUseCases), styles: splitTags(item.original.visualPresentation),+ industries: item.industries ?? [], creationModels: item.creationModels ?? [], colors: item.colors ?? [],+ width: item.width, height: item.height, sortOrder: item.sortOrder, featuredOrder: item.featuredOrder ?? null,+ hasHtmlProject: item.files.some(file => file.path === 'index.html'),}));return [...remote, ...builtinTemplates];}diff --git a/server.ts b/server.tsindex 1dc9b833..db19b4af 100644--- a/server.ts+++ b/server.ts@@ -304,6 +304,7 @@ export async function handler(req: IncomingMessage, res: ServerResponse, store =if (req.method === 'GET' && ['/api/integration', '/connect/guide', '/connect/config'].includes(url.pathname)) {const address = new URL(editorUrl);const info: IntegrationInfo = {+ templateEnvironment: templateCatalogFor(store.directory).environment as 'dev' | 'prod',name: 'OpenDesign', version: VERSION, previewUrl: address.origin, dataDirectory: store.directory,transport: { type: 'stdio', command: process.execPath, args: ['--experimental-strip-types', path.join(pluginRoot, 'mcp.ts')], cwd: pluginRoot,env: { MOTION_DATA_DIR: store.directory, PORT: address.port || '80', ...Object.fromEntries(['MOTION_TEMPLATE_ENV', 'MOTION_TEMPLATE_RESOURCE_ID', 'MOTION_TEMPLATE_LOCALE', 'MOTION_BROWSER_PATH', 'HYPERFRAMES_BROWSER_PATH', 'HYPERFRAMES_FFMPEG_PATH', 'HYPERFRAMES_FFPROBE_PATH', 'FFMPEG_PATH', 'FFPROBE_PATH'].filter(key => process.env[key]).map(key => [key, process.env[key]!])) } },diff --git a/shared/catalog.ts b/shared/catalog.tsindex 2c01fea0..9925f98b 100644--- a/shared/catalog.ts+++ b/shared/catalog.ts@@ -14,6 +14,11 @@ export type GalleryTemplate = {previewUrl?: string; posterUrl?: string; sourceUrl?: string; author: string; mediaFingerprint?: string;authorName?: string; social?: TemplateSocial;variants?: GalleryTemplate[];+ motionDocumentUrl?: string; motionGuideUrl?: string; projectFileUrl?: string; authorAvatarUrl?: string;+ styleDescription?: string; reviewFocus?: string;+ brand?: string; uses?: string[]; styles?: string[]; industries?: string[];+ creationModels?: string[]; colors?: string[]; width?: number; height?: number;+ sortOrder?: number; featuredOrder?: number | null; hasHtmlProject?: boolean;};export type SocialPlatform = 'X' | 'Instagram' | 'YouTube' | 'TikTok';export type TemplateSocial = { platform: SocialPlatform; views: number; sourceUrl: string; syncedAt: string; metadataUrl: string };@@ -23,7 +28,7 @@ export const featuredTemplateIds = ['hf-moment-M1023', 'hf-moment-M1000', 'hf-moment-M990',];const roleNames: Record<string, string> = { 'a-roll': '口播', hook: '开场', setup: '铺垫', proof: '产品展示', turn: '转场', payoff: '高潮', cta: '结尾' };-export function isEditableTemplate(template: GalleryTemplate): boolean { return template.kind === 'builtin' || template.kind === 'prism'; }+export function isEditableTemplate(template: GalleryTemplate): boolean { return template.kind === 'builtin' || (template.kind === 'prism' && template.hasHtmlProject !== false); }export function templateCategoryLabel(template: GalleryTemplate) {if (template.role === 'a-roll' || template.tags.includes('口播')) return 'A-roll Cuts';diff --git a/shared/integration.ts b/shared/integration.tsindex 43686c4f..3c0b3945 100644--- a/shared/integration.ts+++ b/shared/integration.ts@@ -11,6 +11,7 @@ export const hostDescriptions: Record<IntegrationHost, string> = {mcp: '连接你喜欢的 MCP 客户端,也可以从终端和脚本开始。',};export type IntegrationInfo = {+ templateEnvironment?: 'dev' | 'prod';name: string; version: string; previewUrl: string; dataDirectory: string;transport: { type: 'stdio'; command: string; args: string[]; cwd: string; env: Record<string, string> };tools: { name: string; description: string }[];@@ -70,8 +71,19 @@ export function setupPrompt(info: IntegrationInfo, host: IntegrationHost, localeif (host === 'chatgpt') return 'ChatGPT 云端需要公开 HTTPS MCP 服务。当前工作区使用本机 stdio,可先选择 Codex、Claude Code 或 DeepSeek Harness 开始创作。';return `请读取 ${guideUrl(info, host)},将 OpenDesign 接入 ${hostNames[host]},验证后带我开始创作。`;}-export function templatePrompt(info: IntegrationInfo, host: IntegrationHost, template: { id: string; title: string }) {- return `请读取 ${guideUrl(info, host, template.id)} 并在 OpenDesign 复刻模板 ${template.id},完成后打开可编辑工程。`;+export function templatePrompt(info: IntegrationInfo, _host: IntegrationHost, template: { id: string; title: string }, locale = 'zh-CN') {+ const environment = info.templateEnvironment ?? info.transport.env?.MOTION_TEMPLATE_ENV ?? 'prod';+ const installUrl = `https://releases.open-design.ai/open-motion/${environment === 'dev' ? 'dev/' : ''}install.md`;+ if (locale === 'zh-CN') return `使用说明:请使用 OpenMotion 插件。如未安装,请按 ${installUrl} 安装并接入后继续。+指定模板:${template.title}(${template.id})+创作要求:基于模板,结合我的要求和附件创作,默认保留主要动效与风格,并交付 HTML 和 MP4。+我的要求:+`;+ return `Instructions: Use the OpenMotion plugin. If it is not installed, follow ${installUrl} to install and connect it, then continue.+Selected template: ${template.title} (${template.id})+Creative brief: Adapt the template using my requirements and attachments. Preserve its main motion and style by default, and deliver HTML and MP4.+My requirements:+`;}export function agentGuide(info: IntegrationInfo, host: IntegrationHost) {diff --git a/studio/src/i18n/mvp-zh-CN.json b/studio/src/i18n/mvp-zh-CN.jsonindex c958e1e4..7ea5e33e 100644--- a/studio/src/i18n/mvp-zh-CN.json+++ b/studio/src/i18n/mvp-zh-CN.json@@ -706,7 +706,7 @@"Timeline-driven paper, tape, and flash dressing for a freeze-frame or background-removed subject": "随时间轴变化的纸张、胶带与闪光装饰,适用于定格画面或抠像主体。","Seek-safe falling-snow overlay: sparse or dense flakes drift down with size, speed and opacity correlated per flake for depth, radial-masked so the frame center stays clear": "支持任意时间预览的飘雪叠加。可调节雪花密度,通过不同大小、速度与透明度呈现纵深,并保持画面中心清晰。","Seek-safe night-sky overlay: sparse or dense stars in three size tiers that twinkle and drift in two parallax layers, radial-masked to keep the frame center clear": "支持任意时间预览的星空叠加。可调节星星密度,三种大小的星星在双层视差中闪烁漂移,并保持画面中心清晰。",- "Filters": "滤波",+ "Filters": "筛选","Dynamics": "动态处理","Non-linear": "非线性效果","Too much low-end body, so it booms.": "低频过重,声音轰鸣。",@@ -965,5 +965,44 @@"Technical details": "技术详情","Preparation progress unavailable": "暂时无法获取准备进度","Your files are ready to import": "所选文件可继续导入",- "Continue import": "继续导入"+ "Continue import": "继续导入",+ "Reference brands": "参考品牌",+ "Use cases": "使用场景",+ "Video types": "视频类型",+ "Industries": "行业",+ "Creation models": "创作模型",+ "Colors": "颜色",+ "Popular templates": "热门模板",+ "{count} templates": "{count} 个模板",+ "Sort": "排序",+ "Recommended order": "推荐顺序",+ "Name A–Z": "名称正序",+ "Name Z–A": "名称倒序",+ "Clear filters": "清除筛选",+ "Show more": "查看更多",+ "Landscape": "横屏",+ "Portrait": "竖屏",+ "Under 10 seconds": "10 秒以内",+ "10–15 seconds": "10–15 秒",+ "15–30 seconds": "15–30 秒",+ "30–60 seconds": "30–60 秒",+ "60 seconds or longer": "60 秒及以上",+ "monochrome": "黑白灰",+ "red": "红色",+ "orange": "橙色",+ "yellow": "黄色",+ "green": "绿色",+ "blue": "蓝色",+ "purple": "紫色",+ "multicolor": "多色",+ "Recreate template": "复刻模板",+ "Download motion.md": "下载 motion.md",+ "Downloading…": "下载中…",+ "Download failed. Please try again.": "下载失败,请重试。",+ "Download OpenMotion project": "下载 OpenMotion 工程",+ "Motion guide": "动效说明",+ "On this page": "本页目录",+ "Visual style": "风格描述",+ "Production notes": "制作要点",+ "View full page": "查看完整页面"}diff --git a/studio/src/motion/ConnectionDialog.tsx b/studio/src/motion/ConnectionDialog.tsxindex f569b733..5d665a9f 100644--- a/studio/src/motion/ConnectionDialog.tsx+++ b/studio/src/motion/ConnectionDialog.tsx@@ -3,6 +3,7 @@ import { useI18n } from '../i18n/I18n';import { useEffect, useRef } from 'react';import { mountConnection } from '../../../web/connect';import connectionPage from '../../../web/connect.html?raw';+import { TemplateLibraryDialog } from './TemplateLibraryDialog';import { MotionIcon } from './icons';import '../../../web/design-system/controls.css';import '../../../web/connect.css';@@ -12,6 +13,11 @@ type Props = { open: boolean; section?: 'setup' | 'templates'; busy: boolean; er/** The original integration page lives inside one modal; Studio stays mounted beneath it. */export function ConnectionDialog(props: Props) {+ const mvp = useMvpEditor();+ return mvp || props.section === 'templates' ? <TemplateLibraryDialog {...props} /> : <LegacyConnectionDialog {...props} />;+}++function LegacyConnectionDialog(props: Props) {const { t, locale } = useI18n();const mvp = useMvpEditor();const dialog = useRef<HTMLDialogElement>(null), root = useRef<HTMLDivElement>(null);diff --git a/studio/src/motion/HomeTemplates.test.tsx b/studio/src/motion/HomeTemplates.test.tsxindex b82576d3..7ccf3a02 100644--- a/studio/src/motion/HomeTemplates.test.tsx+++ b/studio/src/motion/HomeTemplates.test.tsx@@ -4,6 +4,12 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { I18nProvider, translate, type Locale } from '../i18n/I18n';import { HomeTemplates } from './HomeTemplates';+import type { IntegrationInfo } from '../../../shared/integration';++const integration: IntegrationInfo = {+ name: 'OpenMotion', version: 'test', previewUrl: 'http://localhost:4173', dataDirectory: '/test',+ transport: { type: 'stdio', command: 'node', args: [], cwd: '/test', env: { MOTION_TEMPLATE_ENV: 'dev' } }, tools: [],+};const state = vi.hoisted(() => ({ open: vi.fn(), disabled: false }));vi.mock('./WorkspaceFrame', () => ({ useWorkspaceChrome: () => ({ workspace: { open: state.open }, switchingDisabled: state.disabled }) }));@@ -18,7 +24,7 @@ beforeEach(() => {container = document.createElement('div'); document.body.append(container); root = createRoot(container);clipboard = vi.fn(async () => {});vi.spyOn(navigator.clipboard, 'writeText').mockImplementation(clipboard);- fetcher = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/integration') ? { previewUrl: 'http://localhost:4173' } : {+ fetcher = vi.fn(async (url: string) => new Response(JSON.stringify(url.endsWith('/integration') ? integration : {items: url.includes('category=builtin') ? [builtin] : [reference], total: 1, entryTotal: 1, catalogTotal: 2, offset: 0, next: null,})));vi.stubGlobal('fetch', fetcher);@@ -36,7 +42,9 @@ it('only editable templates open a new engineering project; references copy theiexpect(container.querySelector('.motion-editable-badge')).toBeNull();await act(async () => button('一键复制').click());expect(clipboard).toHaveBeenCalledOnce();- expect(clipboard.mock.calls[0][0]).toContain('template=hf-moment-M953');+ expect(clipboard.mock.calls[0][0]).toContain('指定模板:Reference(hf-moment-M953)');+ expect(clipboard.mock.calls[0][0]).toContain('https://releases.open-design.ai/open-motion/dev/install.md');+ expect(clipboard.mock.calls[0][0]).not.toContain('localhost');expect(state.open).toHaveBeenCalledTimes(1);expect(container.textContent).toContain('已复制');});diff --git a/studio/src/motion/HomeTemplates.tsx b/studio/src/motion/HomeTemplates.tsxindex 1bf5008c..591153bb 100644--- a/studio/src/motion/HomeTemplates.tsx+++ b/studio/src/motion/HomeTemplates.tsx@@ -71,7 +71,7 @@ export function HomeTemplates({ onSelect }: { onSelect?: (template: GalleryTempltry {const connection = info ?? await motionApi<IntegrationInfo>('/integration');setInfo(connection);- const prompt = templatePrompt(connection, host, template);+ const prompt = templatePrompt(connection, host, template, locale);try {await navigator.clipboard.writeText(prompt);void trackMotion('template_instruction_copy_result', { host_product: host, copy_status: 'clipboard_written' });diff --git a/studio/src/motion/TemplateLibraryDialog.module.css b/studio/src/motion/TemplateLibraryDialog.module.cssnew file mode 100644index 00000000..6dd08255--- /dev/null+++ b/studio/src/motion/TemplateLibraryDialog.module.css@@ -0,0 +1,101 @@+.library { --library-bg:var(--color-template-surface); --library-fg:var(--color-template-text); --library-muted:var(--color-template-muted); --library-line:var(--color-template-line); box-sizing:border-box; width:calc(100vw - 40px); max-width:1680px; height:calc(100dvh - 40px); max-height:none; margin:auto; padding:0; border:1px solid var(--library-line); border-radius:20px; background:var(--library-bg); color:var(--library-fg); font-family:inherit; overflow:auto; }+.library::backdrop,.detail::backdrop,.filters::backdrop { background:var(--color-template-backdrop); backdrop-filter:blur(5px); }+.library * { box-sizing:border-box; }+.library button,.library select,.library input,.library textarea { font:inherit; color:inherit; }+.library button { cursor:pointer; background:none; border:0; }+.library button:disabled { opacity:.5; cursor:wait; }+.library button:focus-visible,.library select:focus-visible,.library input:focus-visible { outline:2px solid var(--color-template-focus); outline-offset:3px; }+.header { display:flex; align-items:center; justify-content:space-between; padding:20px 30px; position:sticky; top:0; z-index:2; background:var(--library-bg); border-bottom:1px solid var(--library-line); }+.header h1 { font-size:18px; font-weight:600; margin:0; }+.header button,.close { display:grid; place-items:center; width:40px; height:40px; border-radius:50%; }+.header button:hover { background:var(--color-template-header-hover); }+.browser { display:grid; grid-template-columns:220px minmax(0,1fr); gap:42px; padding:32px; }+.sidebar { align-self:start; position:sticky; top:104px; max-height:calc(100dvh - 170px); overflow:auto; }+.sidebar button { width:100%; min-height:48px; padding:10px 14px; display:flex; align-items:center; gap:12px; text-align:left; font-size:14px; border-radius:28px; }+.sidebar button small,.all span { margin-left:auto; color:var(--library-muted); }+.sidebar .all { font-size:16px; font-weight:600; margin-bottom:12px; }+.sidebar button[aria-current=page],.sidebar button[aria-pressed=true] { color:var(--color-template-selected-text); background:var(--color-template-selected); }+.sidebar summary { padding:16px 14px; font-size:15px; font-weight:600; cursor:pointer; }+.sidebar summary::marker { font-size:11px; }+.sidebar button:hover { background:var(--color-template-hover); }+.brandIcon { display:grid; place-items:center; flex:none; width:25px; height:25px; border-radius:6px; background:var(--color-template-brand-bg); color:var(--color-template-brand-text); }+.results { min-width:0; }+.results h2 { font-size:24px; margin:0; font-weight:600; }+.featured { margin-bottom:54px; }+.featured h2 { margin-bottom:28px; }+.grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:32px 26px; }+.cover { display:block; width:100%; aspect-ratio:16/9; overflow:hidden; border:1px solid var(--library-line)!important; border-radius:14px; position:relative; padding:0; background:var(--color-template-preview-bg)!important; }+.cover>img,.cover>video { width:100%; height:100%; position:absolute; inset:0; object-fit:cover; }+.cover>video { transition:opacity .18s; }+.play { position:absolute; right:14px; bottom:14px; width:36px; height:36px; display:grid; place-items:center; border-radius:50%; background:var(--color-template-play-bg); }+.title { display:block; margin-top:14px; padding:0; font-size:17px!important; font-weight:500!important; text-align:left; line-height:1.4; }+.card p { margin:7px 0 0; font-size:13px; color:var(--library-muted); }+.toolbar { display:flex; align-items:center; justify-content:space-between; gap:20px; margin-bottom:28px; }+.toolbar h2 small { font-size:14px; font-weight:400; color:var(--library-muted); margin-left:8px; white-space:nowrap; }+.controls { display:flex; align-items:center; gap:0; flex-shrink:0; border:1px solid var(--library-line); background:var(--color-template-controls-bg); border-radius:28px; }+.controls button { display:flex; align-items:center; justify-content:center; gap:8px; min-height:44px; padding:10px 14px; }+.controls select { border:0; border-left:1px solid var(--library-line); background:none; padding:10px 12px; width:140px; outline-offset:0; }+.search { display:block; width:100%; border:1px solid var(--library-line); padding:12px 16px; border-radius:12px; background:white; margin-bottom:20px; }+.chips { display:flex; flex-wrap:wrap; gap:10px; margin-bottom:20px; }+.chips button { background:var(--color-template-selected); border-radius:18px; padding:8px 12px; }+.empty { padding:40px 0; color:var(--library-muted); }+.status { margin:12px 32px; padding:12px 16px; border-radius:8px; background:var(--color-template-controls-bg); font-size:14px; }+.status button { text-decoration:underline; margin-left:14px; }+.detail,.filters { background:var(--library-bg); color:var(--library-fg); margin:auto; border:1px solid var(--library-line); border-radius:20px; max-height:calc(100dvh - 80px); overflow:auto; padding:36px; }+.detail { width:calc(100vw - 100px); max-width:1400px; }+.close { margin-left:auto; margin-bottom:20px; border:1px solid var(--library-line)!important; }+.detailGrid { display:grid; grid-template-columns:1.5fr 1fr; gap:32px; }+.stage { display:grid; place-items:center; min-width:0; background:var(--color-template-preview-bg); border-radius:12px; overflow:hidden; aspect-ratio:16/9; }+.stage video,.stage img { width:100%; max-height:60dvh; object-fit:contain; }+.detailInfo h2 { font-size:30px; margin:14px 0; line-height:1.3; }+.detailInfo p { font-size:15px; line-height:1.7; color:var(--color-template-description); }+.detailInfo a { color:inherit; }+.detailInfo small { color:var(--color-template-description); }+.actions { display:flex; flex-wrap:wrap; gap:10px; margin:24px 0; }+.actions button { flex:1; border:1px solid var(--library-line); border-radius:30px; padding:14px 20px; white-space:nowrap; }+.actions button:last-child { background:var(--color-template-action-bg); color:var(--color-template-action-text); }+.detailInfo dl { display:grid; grid-template-columns:auto 1fr; gap:16px; font-size:14px; }+.detailInfo dt { color:var(--color-template-label); }+.detailInfo dd { text-align:right; margin:0; }+.prompt { display:block; width:100%; margin-top:24px; resize:vertical; min-height:170px; border:1px solid var(--library-line); border-radius:12px; padding:16px; background:var(--color-template-prompt-bg); line-height:1.8; white-space:pre-wrap; overflow-wrap:anywhere; }+.filters { width:600px; max-width:calc(100vw - 40px); }+.filters header,.filters footer { display:flex; justify-content:space-between; align-items:center; gap:20px; }+.filters fieldset { border:0; padding:20px 0; margin:0; border-bottom:1px solid var(--library-line); }+.filters legend { font-weight:600; padding-top:16px; }+.filters label { display:inline-flex; align-items:center; gap:6px; margin:10px 18px 0 0; font-size:14px; }+.filters input { accent-color:var(--color-template-checkbox); }+.filters footer { margin-top:20px; }+.filters footer button { padding:12px 20px; background:var(--color-template-selected); border-radius:20px; }+@media(max-width:1200px) { .browser { gap:24px; grid-template-columns:180px minmax(0,1fr); padding:24px; } .grid { gap:24px 18px; } .toolbar { flex-wrap:wrap; } }+@media(max-width:900px) { .grid { grid-template-columns:repeat(2,minmax(0,1fr)); } .detailGrid { grid-template-columns:1fr; } .sidebar { position:static; } }+@media(max-width:600px) { .library { width:100%; height:100dvh; border-radius:0; border:0; } .header { padding:12px 16px; } .browser { display:block; padding:16px; } .sidebar { display:none; } .grid { gap:24px 14px; } .title { font-size:14px!important; } .card p { font-size:12px; } .results h2 { font-size:20px; } .toolbar { gap:14px; } .controls { width:100%; justify-content:space-between; } .featured { margin-bottom:34px; } .detail { width:calc(100vw - 20px); padding:20px; } }+@media(prefers-reduced-motion:reduce) { .cover>video { transition:none; } }++.brandIcon img { width:100%; height:100%; object-fit:contain; border-radius:6px; }+.sidebar summary { list-style:none; display:flex; align-items:center; justify-content:space-between; }+.sidebar summary::-webkit-details-marker { display:none; }+.sidebar summary:after { content:"›"; font-size:20px; font-weight:400; }+.sidebar details[open]>summary:after { transform:rotate(90deg); }+.actions button:disabled { cursor:default; }+.projectActions { display:flex; flex-wrap:wrap; gap:16px; font-size:14px; }+.projectActions button { padding:0; text-decoration:underline; }+.guide { display:grid; grid-template-columns:200px minmax(0,1fr); gap:40px; border-top:1px solid var(--library-line); margin-top:40px; padding-top:32px; }+.guide h3 { font-size:20px; margin:0 0 20px; }+.guide aside a { display:block; color:var(--color-template-guide-link); padding:12px 0; }+.guide section { margin-bottom:32px; scroll-margin-top:24px; }+.guide p { white-space:pre-wrap; line-height:1.8; }+.guide iframe { width:100%; height:650px; border:1px solid var(--library-line); border-radius:12px; background:white; }+.guide section>a { display:block; margin-top:16px; color:inherit; }+.useDialog { width:760px; max-width:calc(100vw - 32px); max-height:calc(100dvh - 40px); margin:auto; padding:32px; overflow:auto; border:1px solid var(--library-line); border-radius:20px; color:var(--library-fg); background:var(--library-bg); }+.useDialog::backdrop { background:var(--color-template-backdrop); backdrop-filter:blur(5px); }+.useDialog header { display:flex; justify-content:space-between; align-items:center; margin-bottom:28px; }+.useDialog h2 { font-size:28px; margin:0; }+.handoff { display:flex; gap:20px; align-items:center; margin-bottom:24px; }+.handoff img { width:128px; aspect-ratio:16/9; border-radius:10px; object-fit:cover; }+.handoff strong { font-size:18px; }.handoff p { color:var(--library-muted); overflow-wrap:anywhere; }+.useDialog .prompt { margin:20px 0; }.useDialog .copyPrompt { padding:12px 24px; border-radius:24px; background:var(--color-template-action-bg); color:white; }+@media(max-width:700px) { .guide { grid-template-columns:1fr; gap:20px; }.guide aside { display:flex; flex-wrap:wrap; gap:16px; }.guide aside h3 { width:100%; }.useDialog { padding:24px; }.handoff img { width:88px; }.handoff { gap:12px; } }++.promptRow { display:flex; align-items:center; border:1px solid var(--library-line); border-radius:12px; background:var(--color-template-prompt-bg); padding-right:12px; }+.promptRow .prompt { border:0; margin:0; min-width:0; resize:vertical; }+.promptRow .copyPrompt { display:grid; place-items:center; width:44px; height:44px; flex:none; padding:0; border-radius:8px; color:var(--library-fg); background:transparent; }diff --git a/studio/src/motion/TemplateLibraryDialog.test.tsx b/studio/src/motion/TemplateLibraryDialog.test.tsxnew file mode 100644index 00000000..2e777a60--- /dev/null+++ b/studio/src/motion/TemplateLibraryDialog.test.tsx@@ -0,0 +1,57 @@+// @vitest-environment happy-dom+import React, { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { I18nProvider } from '../i18n/I18n';+import { TemplateLibraryDialog } from './TemplateLibraryDialog';++globalThis.IS_REACT_ACT_ENVIRONMENT = true;+let root: Root, host: HTMLDivElement;+const items = [+ { id: 'one', title: 'First', author: 'Author', brand: 'Figma', uses: ['Demo'], styles: ['UI'], tags: [], kind: 'prism', hasHtmlProject: true, sortOrder: 2, featuredOrder: 0, motionDocumentUrl: 'https://example.com/motion.zip', motionGuideUrl: 'https://example.com/guide', styleDescription: 'Visual rules', reviewFocus: 'Production rules', posterUrl: '/one.jpg' },+ { id: 'two', title: 'Second', author: 'Author', brand: 'Other', uses: ['Launch'], tags: [], kind: 'prism', hasHtmlProject: false, sortOrder: 1, posterUrl: '/two.jpg' },+];+beforeEach(() => {+ window.happyDOM.settings.enableIframePageLoading = false;+ vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} });+ vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {});+ vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue();+ vi.stubGlobal('fetch', vi.fn(async (url: string) => Response.json(url.endsWith('/integration') ? {+ templateEnvironment: 'dev', transport: { env: {} },+ } : { items, catalogVersion: 'v1', next: null, total: 2 })));+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); host.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });+const button = (label: string) => [...host.querySelectorAll<HTMLButtonElement>('button')].find(node => node.textContent === label)!;+async function mount(onOpen = vi.fn()) {+ await act(async () => root.render(<I18nProvider initialLocale="zh-CN"><TemplateLibraryDialog open busy={false} error="" onClose={() => {}} onOpen={onOpen} /></I18nProvider>));+ return onOpen;+}+it('shows featured/order and combines website facets without site chrome', async () => {+ await mount();+ expect(host.textContent).toContain('热门模板');+ expect([...host.querySelectorAll('[data-template-id]')].map(el => el.getAttribute('data-template-id'))).toEqual(['one', 'two', 'one']);+ expect(host.querySelector('nav')).toBeNull();+ expect(host.textContent).not.toContain('200+');+ await act(async () => [...host.querySelectorAll<HTMLButtonElement>('aside button')].find(el => el.textContent?.includes('Figma'))!.click());+ expect([...host.querySelectorAll('[data-template-id]')].map(el => el.getAttribute('data-template-id'))).toEqual(['one']);+ expect(host.textContent).not.toContain('热门模板');+ await act(async () => button('清除筛选').click());+ expect(host.querySelectorAll('[data-template-id]')).toHaveLength(3);+});+it('copies the requested remote DEV prompt and preserves editable opening', async () => {+ const onOpen = await mount();+ await act(async () => button('First').click());+ expect(host.querySelector('dialog[aria-label=模板预览] textarea')).toBeNull();+ expect(host.querySelector('iframe[title=动效说明]')?.getAttribute('src')).toBe('https://example.com/guide');+ expect(button('下载 motion.md').disabled).toBe(false);+ await act(async () => button('复刻模板').click());+ expect(host.querySelector('dialog[aria-label=复刻模板] textarea')).not.toBeNull();+ expect(host.querySelector('dialog[aria-label=模板预览] textarea')).toBeNull();+ await act(async () => host.querySelector<HTMLButtonElement>('button[aria-label=复制]')!.click());+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('使用说明:请使用 OpenMotion 插件。如未安装,请按 https://releases.open-design.ai/open-motion/dev/install.md 安装并接入后继续。\n指定模板:First(one)\n创作要求:基于模板,结合我的要求和附件创作,默认保留主要动效与风格,并交付 HTML 和 MP4。\n我的要求:\n');+ await act(async () => button('打开并编辑 ↗').click());+ expect(onOpen).toHaveBeenCalledWith('one');+ await act(async () => button('Second').click());+ expect(button('打开并编辑 ↗')).toBeUndefined();+});diff --git a/studio/src/motion/TemplateLibraryDialog.tsx b/studio/src/motion/TemplateLibraryDialog.tsxnew file mode 100644index 00000000..a8c110e2--- /dev/null+++ b/studio/src/motion/TemplateLibraryDialog.tsx@@ -0,0 +1,209 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { isEditableTemplate, type GalleryTemplate, type TemplatePage } from '../../../shared/catalog';+import { templatePrompt, type IntegrationInfo } from '../../../shared/integration';+import { useI18n } from '../i18n/I18n';+import { motionApi } from './useWorkspace';+import { MotionIcon } from './icons';+import styles from './TemplateLibraryDialog.module.css';+import figmaLogo from './template-brands/figma.png';+import lovableLogo from './template-brands/lovable.svg';+import linearLogo from './template-brands/linear.svg';+import firecrawlLogo from './template-brands/firecrawl.png';+import kimiLogo from './template-brands/kimi.png';+import pondLogo from './template-brands/pond.svg';+const brandLogos: Record<string, string> = {Figma: figmaLogo, Lovable: lovableLogo, Linear: linearLogo, Firecrawl: firecrawlLogo, Kimi: kimiLogo, Pond: pondLogo};++type Props = { open: boolean; busy: boolean; error: string; onClose: () => void; onOpen: (id: string) => void };+type Facet = 'brand' | 'uses' | 'styles' | 'industries' | 'creationModels' | 'colors' | 'ratio' | 'duration';+const facets: [Facet, string][] = [+ ['brand', 'Reference brands'], ['uses', 'Use cases'], ['styles', 'Video types'],+ ['industries', 'Industries'], ['creationModels', 'Creation models'], ['colors', 'Colors'],+ ['ratio', 'Aspect ratio'], ['duration', 'Duration'],+];+function values(template: GalleryTemplate, key: Facet): string[] {+ if (key === 'brand') return template.brand ? [template.brand] : [];+ if (key === 'ratio') {+ if (!template.width || !template.height) return [];+ if (template.width === template.height) return ['Square'];+ return [template.width > template.height ? 'Landscape' : 'Portrait'];+ }+ if (key === 'duration') {+ const duration = template.duration;+ if (!duration) return [];+ if (duration < 10) return ['Under 10 seconds'];+ if (duration < 15) return ['10–15 seconds'];+ if (duration < 30) return ['15–30 seconds'];+ if (duration < 60) return ['30–60 seconds'];+ return ['60 seconds or longer'];+ }+ return template[key] ?? [];+}++function TemplateCard({ template, onSelect }: { template: GalleryTemplate; onSelect: () => void }) {+ const { t } = useI18n();+ const video = useRef<HTMLVideoElement>(null);+ const [playing, setPlaying] = useState(false);+ const stop = () => { video.current?.pause(); setPlaying(false); };+ useEffect(() => {+ const element = video.current;+ if (!element) return;+ const observer = new IntersectionObserver(([entry]) => { if (!entry.isIntersecting) stop(); });+ observer.observe(element);+ return () => { observer.disconnect(); element.pause(); };+ }, []);+ const play = () => {+ if (!video.current || matchMedia('(prefers-reduced-motion: reduce)').matches) return;+ if (!video.current.src) video.current.src = template.previewUrl!;+ void video.current.play().then(() => setPlaying(true)).catch(() => {});+ };+ return <article className={styles.card} data-template-id={template.id}>+ <button className={styles.cover} onClick={onSelect} onMouseEnter={play} onMouseLeave={stop} onFocus={play} onBlur={stop} aria-label={t('Preview template {title}', { title: template.title })}>+ {template.posterUrl ? <img src={template.posterUrl} alt="" loading="lazy" /> : <span>{template.title}</span>}+ {template.previewUrl && <video ref={video} muted playsInline loop preload="none" aria-hidden="true" style={{ opacity: playing ? 1 : 0 }} />}+ <span className={styles.play}><MotionIcon name="play" size={18} /></span>+ </button>+ <button className={styles.title} onClick={onSelect}>{template.title}</button>+ <p>{template.brand || template.authorName || template.author}{template.duration ? ` · ${t('{value}s', { value: Number(template.duration.toFixed(1)) })}` : ''}</p>+ </article>;+}++/** The website's catalog region, backed by the editor's existing Prism cache and project actions. */+export function TemplateLibraryDialog(props: Props) {+ const { t, locale } = useI18n();+ const dialog = useRef<HTMLDialogElement>(null), detail = useRef<HTMLDialogElement>(null), filter = useRef<HTMLDialogElement>(null);+ const useDialog = useRef<HTMLDialogElement>(null);+ const [downloading, setDownloading] = useState(false), [downloadError, setDownloadError] = useState('');+ const [catalog, setCatalog] = useState<GalleryTemplate[]>([]);+ const [warning, setWarning] = useState(''), [error, setError] = useState(''), [loading, setLoading] = useState(false);+ const [attempt, retry] = useState(0), [query, setQuery] = useState(''), [sort, setSort] = useState('recommended');+ const [selected, setSelected] = useState<Partial<Record<Facet, string[]>>>({});+ const [moreBrands, setMoreBrands] = useState(false), [searchOpen, setSearchOpen] = useState(false);+ const [preview, setPreview] = useState<GalleryTemplate | null>(null), [prompt, setPrompt] = useState(''), [feedback, setFeedback] = useState('');+ const info = useRef<IntegrationInfo | null>(null);+ useEffect(() => {+ if (!props.open) return;+ dialog.current?.showModal();+ return () => { useDialog.current?.close(); detail.current?.close(); filter.current?.close(); dialog.current?.close(); setPreview(null); };+ }, [props.open]);+ useEffect(() => {+ if (!props.open) return;+ const controller = new AbortController();+ let version: string | undefined, pending = false;+ async function load() {+ pending = true; setLoading(true); setError('');+ try {+ const items: GalleryTemplate[] = []; let offset: number | null = 0;+ while (offset !== null) {+ const page: TemplatePage = await motionApi(`/template-catalog?category=all&covered=true&limit=60&offset=${offset}`, { signal: controller.signal });+ items.push(...page.items); offset = page.next; version = page.catalogVersion; setWarning(page.warning ?? '');+ }+ if (!controller.signal.aborted) setCatalog(items);+ } catch (err) { if (!controller.signal.aborted) setError((err as Error).message); }+ finally { pending = false; if (!controller.signal.aborted) setLoading(false); }+ }+ void load();+ const timer = setInterval(async () => {+ if (pending || document.hidden) return;+ pending = true;+ try {+ const page = await motionApi<TemplatePage>('/template-catalog?limit=1', { signal: controller.signal });+ if (controller.signal.aborted) return;+ setWarning(page.warning ?? '');+ if (page.catalogVersion !== version) await load();+ } catch {} finally { pending = false; }+ }, 5000);+ void motionApi<IntegrationInfo>('/integration', { signal: controller.signal }).then(value => { info.current = value; }).catch(() => {});+ return () => { controller.abort(); clearInterval(timer); };+ }, [props.open, attempt]);+ const available = useMemo(() => facets.map(([key, label]) => ({ key, label, values: [...new Set(catalog.flatMap(item => values(item, key)))] })).filter(facet => facet.values.length), [catalog]);+ const hasFilters = Boolean(query || Object.values(selected).some(items => items?.length));+ const visible = useMemo(() => catalog.filter(item => {+ const text = [item.id, item.title, item.description, item.author, ...item.tags, ...facets.flatMap(([key]) => values(item, key))].join(' ').toLocaleLowerCase();+ return text.includes(query.trim().toLocaleLowerCase()) && facets.every(([key]) => !selected[key]?.length || selected[key]!.some(value => values(item, key).includes(value)));+ }).sort((a, b) => sort === 'recommended' ? (a.sortOrder ?? Infinity) - (b.sortOrder ?? Infinity) : a.title.localeCompare(b.title, locale) * (sort === 'reverse' ? -1 : 1)), [catalog, query, selected, sort, locale]);+ const featured = catalog.filter(item => item.featuredOrder != null).sort((a, b) => a.featuredOrder! - b.featuredOrder!);+ const reset = () => { setQuery(''); setSelected({}); };+ const toggle = (key: Facet, value: string) => setSelected(previous => ({ ...previous, [key]: previous[key]?.includes(value) ? previous[key]!.filter(item => item !== value) : [...(previous[key] ?? []), value] }));+ async function showPrompt() {+ if (!preview) return;+ setFeedback('');+ useDialog.current?.showModal();+ try {+ const connection = info.current ?? await motionApi<IntegrationInfo>('/integration'); info.current = connection;+ setPrompt(templatePrompt(connection, 'codex', preview, locale));+ } catch (err) { setFeedback((err as Error).message); }+ }+ async function copy() {+ try { await navigator.clipboard.writeText(prompt); setFeedback(t('Copied')); }+ catch { setFeedback(t('Copy the instruction below and send it to your Agent.')); }+ }+ async function downloadMotion() {+ if (!preview?.motionDocumentUrl) return;+ setDownloading(true); setDownloadError('');+ try {+ const response = await fetch(preview.motionDocumentUrl, { credentials: 'omit' });+ if (!response.ok) throw new Error(`Download HTTP ${response.status}`);+ const url = URL.createObjectURL(await response.blob());+ const link = document.createElement('a'); link.href = url; link.download = 'motion.md'; link.click();+ setTimeout(() => URL.revokeObjectURL(url), 60_000);+ } catch { setDownloadError(t('Download failed. Please try again.')); }+ finally { setDownloading(false); }+ }+ const show = (item: GalleryTemplate) => { setPreview(item); setPrompt(''); setFeedback(''); setDownloadError(''); detail.current?.showModal(); };+ const cards = (items: GalleryTemplate[]) => <div className={styles.grid}>{items.map(item => <TemplateCard key={item.id} template={item} onSelect={() => show(item)} />)}</div>;+ return <dialog ref={dialog} className={styles.library} aria-label={t('Template library')} onKeyDown={event => event.stopPropagation()} onCancel={event => { if (event.target !== dialog.current) return; event.preventDefault(); if (!props.busy) props.onClose(); }}>+ <header className={styles.header}><h1>{t('Template library')}</h1><button disabled={props.busy} onClick={props.onClose} aria-label={t('Close template library')}><MotionIcon name="close" size={24} /></button></header>+ {(props.error || error) && <div className={styles.status} role="alert">{t(props.error || error)}{error && <button onClick={() => retry(value => value + 1)}>{t('Retry')}</button>}</div>}+ {warning && <p className={styles.status} role="status">{t(warning)}</p>}+ {props.busy && <p className={styles.status} role="status">{t('Preparing editable project…')}</p>}+ <div className={styles.browser}>+ <aside className={styles.sidebar} aria-label={t('Filters')}>+ <button className={styles.all} aria-current={!hasFilters ? 'page' : undefined} onClick={reset}>{t('All templates')}<span>{catalog.length}</span></button>+ {available.filter(facet => ['brand', 'uses', 'styles', 'industries', 'creationModels'].includes(facet.key)).map(facet => <details key={facet.key} open={facet.key === 'brand'}><summary>{t(facet.label)}</summary>+ {facet.values.slice(0, facet.key === 'brand' && !moreBrands ? 5 : undefined).map(value => <button key={value} aria-pressed={selected[facet.key]?.includes(value) ?? false} onClick={() => toggle(facet.key, value)}>+ {facet.key === 'brand' && <span className={styles.brandIcon} aria-hidden="true">{brandLogos[value] ? <img src={brandLogos[value]} alt="" /> : value.slice(0, 1)}</span>}<span>{value}</span><small>{catalog.filter(item => values(item, facet.key).includes(value)).length}</small>+ </button>)}+ {facet.key === 'brand' && facet.values.length > 5 && <button onClick={() => setMoreBrands(!moreBrands)}>{t(moreBrands ? 'Show less' : 'Show more')}</button>}+ </details>)}+ </aside>+ <main className={styles.results} aria-busy={loading}>+ {!hasFilters && featured.length > 0 && <section className={styles.featured}><h2>{t('Popular templates')}</h2>{cards(featured)}</section>}+ <div className={styles.toolbar}><h2>{t('All templates')} <small>{t('{count} templates', { count: visible.length })}</small></h2><div className={styles.controls}>+ <button aria-label={t('Search templates')} aria-expanded={searchOpen} onClick={() => setSearchOpen(!searchOpen)}><MotionIcon name="search" size={21} /></button>+ <button onClick={() => filter.current?.showModal()}><MotionIcon name="sliders" />{t('Filters')}{Object.values(selected).flat().length > 0 && ` (${Object.values(selected).flat().length})`}</button>+ <select aria-label={t('Sort')} value={sort} onChange={event => setSort(event.target.value)}><option value="recommended">{t('Recommended order')}</option><option value="name">{t('Name A–Z')}</option><option value="reverse">{t('Name Z–A')}</option></select>+ </div></div>+ {searchOpen && <input className={styles.search} autoFocus type="search" maxLength={200} value={query} onChange={event => setQuery(event.target.value)} placeholder={t('Search templates, creators, styles…')} aria-label={t('Search templates')} />}+ {hasFilters && <div className={styles.chips}>{facets.flatMap(([key]) => (selected[key] ?? []).map(value => <button key={key + value} onClick={() => toggle(key, value)}>{t(value)} ×</button>))}<button onClick={reset}>{t('Clear filters')}</button></div>}+ {loading && !catalog.length ? <p role="status">{t('Loading templates…')}</p> : cards(visible)}+ {!loading && !visible.length && !error && <p className={styles.empty}>{t('No matching templates. Try another name, creator or style.')}</p>}+ </main>+ </div>+ <dialog ref={filter} className={styles.filters} aria-label={t('Filters')}><header><h2>{t('Filters')}</h2><button onClick={() => filter.current?.close()} aria-label={t('Close')}><MotionIcon name="close" /></button></header>+ {available.map(facet => <fieldset key={facet.key}><legend>{t(facet.label)}</legend>{facet.values.map(value => <label key={value}><input type="checkbox" checked={selected[facet.key]?.includes(value) ?? false} onChange={() => toggle(facet.key, value)} />{t(value)}</label>)}</fieldset>)}+ <footer><button onClick={reset}>{t('Clear filters')}</button><button onClick={() => filter.current?.close()}>{t('Done')}</button></footer>+ </dialog>+ <dialog ref={detail} className={styles.detail} aria-label={t('Template preview')} onClose={() => { setPreview(null); setPrompt(''); }}>+ {preview && <><button className={styles.close} onClick={() => detail.current?.close()} aria-label={t('Close template preview')}><MotionIcon name="close" size={24} /></button><div className={styles.detailGrid}>+ <div className={styles.stage}>{preview.previewUrl ? <video key={preview.id} src={preview.previewUrl} poster={preview.posterUrl} controls playsInline /> : preview.posterUrl ? <img src={preview.posterUrl} alt={preview.title} /> : <p>{preview.title}</p>}</div>+ <div className={styles.detailInfo}><small>{preview.styles?.join(' · ') || preview.subtitle}</small><h2>{preview.title}</h2><p>{preview.description}</p>+ {preview.sourceUrl ? <a href={preview.sourceUrl} target="_blank" rel="noreferrer">{preview.authorName || preview.author} ↗</a> : <p>{preview.authorName || preview.author}</p>}+ <div className={styles.actions}><button disabled={!preview.motionDocumentUrl || downloading} onClick={() => void downloadMotion()}>{t(downloading ? 'Downloading…' : 'Download motion.md')}</button><button onClick={() => void showPrompt()}>{t('Recreate template')}</button></div>+ <div className={styles.projectActions}>{isEditableTemplate(preview) && <button disabled={props.busy} onClick={() => { detail.current?.close(); props.onOpen(preview.id); }}>{t('Open and edit')} ↗</button>}{preview.projectFileUrl && <a href={preview.projectFileUrl} target="_blank" rel="noreferrer">{t('Download OpenMotion project')} ↗</a>}</div>+ {downloadError && <p role="status">{downloadError}</p>}+ <dl><dt>{t('Video types')}</dt><dd>{preview.styles?.join(' · ') || '—'}</dd><dt>{t('Creation models')}</dt><dd>{preview.creationModels?.join(' · ') || '—'}</dd><dt>{t('Duration')}</dt><dd>{preview.duration ? t('{value}s', { value: preview.duration }) : '—'}</dd></dl>+ </div></div>+ {(preview.styleDescription || preview.reviewFocus || preview.motionGuideUrl) && <section className={styles.guide} aria-label={t('Motion guide')}>+ <aside><h3>{t('On this page')}</h3>{preview.styleDescription && <a href="#template-style">{t('Visual style')}</a>}{preview.reviewFocus && <a href="#template-notes">{t('Production notes')}</a>}{preview.motionGuideUrl && <a href="#template-guide">{t('Motion guide')}</a>}</aside>+ <div>{preview.styleDescription && <section id="template-style"><h3>{t('Visual style')}</h3><p>{preview.styleDescription}</p></section>}{preview.reviewFocus && <section id="template-notes"><h3>{t('Production notes')}</h3><p>{preview.reviewFocus}</p></section>}{preview.motionGuideUrl && <section id="template-guide"><h3>{t('Motion guide')}</h3><iframe src={preview.motionGuideUrl} title={t('Motion guide')} sandbox="allow-scripts" loading="lazy" referrerPolicy="no-referrer" /><a href={preview.motionGuideUrl} target="_blank" rel="noreferrer">{t('View full page')} ↗</a></section>}</div>+ </section>}</>}+ </dialog>+ <dialog ref={useDialog} className={styles.useDialog} aria-label={t('Recreate template')}>+ <header><h2>{t('Recreate template')}</h2><button onClick={() => useDialog.current?.close()} aria-label={t('Close')}><MotionIcon name="close" size={24} /></button></header>+ {preview && <div className={styles.handoff}>{preview.posterUrl && <img src={preview.posterUrl} alt="" />}<div><strong>{preview.title}</strong><p>{preview.id}</p></div></div>}+ <p>{t('Copy the instruction below and send it to your Agent.')}</p>+ <div className={styles.promptRow}><textarea className={styles.prompt} rows={8} readOnly value={prompt} aria-label={t('Content to copy')} />+ <button className={styles.copyPrompt} disabled={!prompt} onClick={() => void copy()} aria-label={t('Copy')}><MotionIcon name="copy" size={22} /></button></div><p role="status">{feedback}</p>+ </dialog>+ </dialog>;+}diff --git a/studio/src/motion/template-brands/figma.png b/studio/src/motion/template-brands/figma.pngnew file mode 100644index 00000000..b374a5ecBinary files /dev/null and b/studio/src/motion/template-brands/figma.png differdiff --git a/studio/src/motion/template-brands/firecrawl.png b/studio/src/motion/template-brands/firecrawl.pngnew file mode 100644index 00000000..a30a034aBinary files /dev/null and b/studio/src/motion/template-brands/firecrawl.png differdiff --git a/studio/src/motion/template-brands/kimi.png b/studio/src/motion/template-brands/kimi.pngnew file mode 100644index 00000000..a44a0203Binary files /dev/null and b/studio/src/motion/template-brands/kimi.png differdiff --git a/studio/src/motion/template-brands/linear.svg b/studio/src/motion/template-brands/linear.svgnew file mode 100644index 00000000..e7f24e2e--- /dev/null+++ b/studio/src/motion/template-brands/linear.svg@@ -0,0 +1,7 @@+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">+ <rect width="16" height="16" rx="2" fill="#000"/>+ <path+ d="M2.147 9.383c-.027-.114.109-.186.192-.103l4.381 4.38c.083.083.011.219-.103.192a6.02 6.02 0 0 1-4.47-4.47ZM2 7.627a.12.12 0 0 0 .035.091l6.247 6.247a.12.12 0 0 0 .091.035q.428-.027.836-.111a.117.117 0 0 0 .057-.198L2.31 6.734a.117.117 0 0 0-.198.057 6 6 0 0 0-.11.836Zm.505-2.062a.12.12 0 0 0 .025.132l7.773 7.773a.12.12 0 0 0 .132.025q.322-.144.623-.322a.118.118 0 0 0 .022-.185L3.012 4.92a.118.118 0 0 0-.185.022q-.178.3-.322.623m1.014-1.396a.12.12 0 0 1-.005-.163 6.006 6.006 0 1 1 8.48 8.48.12.12 0 0 1-.163-.005z"+ fill="#FFF"+ />+</svg>diff --git a/studio/src/motion/template-brands/lovable.svg b/studio/src/motion/template-brands/lovable.svgnew file mode 100644index 00000000..91a0a9d1--- /dev/null+++ b/studio/src/motion/template-brands/lovable.svg@@ -0,0 +1 @@+<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Lovable</title><path clip-rule="evenodd" d="M7.082 0c3.91 0 7.081 3.179 7.081 7.1v2.7h2.357c3.91 0 7.082 3.178 7.082 7.1 0 3.923-3.17 7.1-7.082 7.1H0V7.1C0 3.18 3.17 0 7.082 0z" fill="url(#lobe-icons-lovable-_R_0_)" fill-rule="evenodd"></path><defs><radialGradient cx="0" cy="0" gradientTransform="matrix(-1 22.49999 -30.45394 -1.3535 14 3)" gradientUnits="userSpaceOnUse" id="lobe-icons-lovable-_R_0_" r="1"><stop offset=".25" stop-color="#FE7B02"></stop><stop offset=".433" stop-color="#FE4230"></stop><stop offset=".548" stop-color="#FE529A"></stop><stop offset=".654" stop-color="#DD67EE"></stop><stop offset=".95" stop-color="#4B73FF"></stop></radialGradient></defs></svg>\ No newline at end of filediff --git a/studio/src/motion/template-brands/pond.svg b/studio/src/motion/template-brands/pond.svgnew file mode 100644index 00000000..59bcd224--- /dev/null+++ b/studio/src/motion/template-brands/pond.svg@@ -0,0 +1,4 @@+<svg width="400" height="400" viewBox="0 0 400 400" fill="none" xmlns="http://www.w3.org/2000/svg">+ <rect width="400" height="400" fill="#CBE25B"/>+ <path transform="translate(64 64)" d="M260.207 191.395C274.176 160.074 275.796 124.632 264.743 92.167C253.689 59.7024 230.779 32.6122 200.6 16.3222C170.421 0.0322125 135.202 -4.25484 101.997 4.31967C68.7914 12.8942 40.0512 33.6971 21.5326 62.5621C3.01401 91.427 -3.91575 126.223 2.13126 159.98C8.17828 193.737 26.7556 223.964 54.1424 244.606C81.5293 265.248 115.704 274.781 149.821 271.296C183.938 267.811 215.479 251.565 238.126 225.812L136 136L260.207 191.395Z" fill="#1B322D"/>+</svg>diff --git a/studio/src/styles/theme.css b/studio/src/styles/theme.cssindex e77e98b8..795a0481 100644--- a/studio/src/styles/theme.css+++ b/studio/src/styles/theme.css@@ -3,6 +3,30 @@* tokens in `:root` so plain CSS and canvas code can still read them. */@theme static {+ /* Website-aligned template catalog palette, independent of the editor theme. */+ --color-template-surface: #fcfff5;+ --color-template-text: #171a15;+ --color-template-muted: #858880;+ --color-template-line: #e5e8df;+ --color-template-backdrop: #0007;+ --color-template-focus: #297126;+ --color-template-header-hover: #edf0e7;+ --color-template-selected-text: #245c24;+ --color-template-selected: #eff2e8;+ --color-template-hover: #f0f3e9;+ --color-template-brand-bg: #e7eae1;+ --color-template-brand-text: #666c61;+ --color-template-preview-bg: #eceee7;+ --color-template-play-bg: #fcfff5f2;+ --color-template-controls-bg: #f1f3eb;+ --color-template-description: #62675c;+ --color-template-action-bg: #151713;+ --color-template-action-text: #fff;+ --color-template-label: #777c71;+ --color-template-prompt-bg: #f4f5f0;+ --color-template-checkbox: #246824;+ --color-template-guide-link: #376637;+/* ---------------------------------------------------------------- colour *//* Graphite. Each colour is `light-dark(light, dark)`, resolved where it is painted, so thediff --git a/tests/catalog.test.ts b/tests/catalog.test.tsindex 10901a92..20055490 100644--- a/tests/catalog.test.ts+++ b/tests/catalog.test.ts@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os';import path from 'node:path';import { catalogTemplates, featuredTemplateIds, groupTemplates, isCatalogMedia } from '../shared/catalog.ts';import { libraryTemplates, listTemplates, getTemplate, readTemplate } from '../template-catalog.ts';-import { templatePrompt } from '../shared/integration.ts';+import { templatePrompt, guideUrl } from '../shared/integration.ts';import { pluginRoot } from '../hyperframes.ts';import { callTool, rpc, mcpRegistry } from '../mcp.ts';import { WorkspaceStore } from '../workspace.ts';@@ -86,10 +86,12 @@ test('HTTP catalog, local posters and copied guides resolve the exact selected tconst template = getTemplate(id);for (const host of ['codex', 'claude', 'deepseek', 'mcp'] as const) {const prompt = templatePrompt(info, host, template);- assert.ok(prompt.includes(id)); assert.ok(prompt.length < 250); assert.equal(prompt.split('\n').length, 1);+ assert.ok(prompt.includes(id)); assert.ok(prompt.includes(template.title));+ assert.match(prompt, /https:\/\/releases.open-design.ai\/open-motion\/install.md/);+ assert.match(prompt, /并交付 HTML 和 MP4/); assert.ok(prompt.endsWith('我的要求:\n'));assert.doesNotMatch(prompt, /dataDirectory|motion_write_files|expectedRevision/);- const guideUrl = prompt.match(/http:\/\/localhost:4173\/connect\/guide\?[^\s]+/)![0];- const response = await request(guideUrl); assert.equal(response.status, 200);+ assert.doesNotMatch(prompt, /localhost|127\.0\.0\.1|connect\/guide/);+ const response = await request(guideUrl(info, host, id)); assert.equal(response.status, 200);const guide = await response.text(); assert.ok(guide.includes(`模板 ID:${id}`));assert.ok(guide.includes(template.title));const expectedRoute = template.kind === 'reference' ? 'recreate' : 'template';@@ -153,3 +155,14 @@ test('the visual gallery only includes verified local covers and keeps coverlessassert.equal(listTemplates({ query: 'hf-component-agent-cursor' }).total, 1);assert.ok(listTemplates({ covered: true, query: 'shapelayer' }).items.some(item => item.sourceUrl === 'https://x.com/shapelayer/status/2070884943199150467'));});++test('template prompts use public installation URLs for the effective package environment', () => {+ const info = { templateEnvironment: 'dev', previewUrl: 'http://127.0.0.1:1234', transport: { env: {} } } as Parameters<typeof templatePrompt>[0];+ const template = { id: 'exact-id', title: 'Selected template' };+ assert.match(templatePrompt(info, 'codex', template), /open-motion\/dev\/install.md/);+ info.templateEnvironment = 'prod';+ info.transport.env.MOTION_TEMPLATE_ENV = 'dev';+ const prompt = templatePrompt(info, 'claude', template, 'en');+ assert.match(prompt, /open-motion\/install.md/); assert.doesNotMatch(prompt, /\/dev\/|127\.0\.0\.1|localhost/);+ assert.match(prompt, /Selected template \(exact-id\)/); assert.match(prompt, /HTML and MP4/);+});diff --git a/tests/prism-templates.test.ts b/tests/prism-templates.test.tsindex 18cdd907..a9052bb8 100644--- a/tests/prism-templates.test.ts+++ b/tests/prism-templates.test.ts@@ -147,3 +147,18 @@ test('reopening a template reuses verified files without sharing mutable projectassert.equal(await readFile(path.join(directory, 'second', 'index.html'), 'utf8'), contents['index.html']);assert.equal((await reopened.detail('test-motion-1')).instructions, contents['TEMPLATE.md']);});++test('gallery carries Prism facets and ordering without leaking project files', async t => {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-library-facets-'));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const data = publication();+ Object.assign(data.content['zh-CN'].templates[0], { motionDocumentUrl: 'https://example.com/motion.zip', motionGuideUrl: 'https://example.com/guide', brand: 'Figma', featuredOrder: 0, creationModels: ['Model A'], colors: ['blue'], industries: ['Design'], width: 1920, height: 1080 });+ Object.assign(data.content['zh-CN'].templates[0].original, { promotionalUseCases: 'Launch, Demo', visualPresentation: 'UI, Typography' });+ const catalog = new TemplateCatalog(directory, { fetch: async () => Response.json(data) });+ const { items } = await catalog.page({ category: 'all' });+ assert.equal(items[0].motionDocumentUrl, 'https://example.com/motion.zip'); assert.equal(items[0].motionGuideUrl, 'https://example.com/guide');+ assert.equal(items[0].brand, 'Figma'); assert.equal(items[0].featuredOrder, 0);+ assert.deepEqual(items[0].uses, ['Launch', 'Demo']); assert.deepEqual(items[0].styles, ['UI', 'Typography']);+ assert.deepEqual(items[0].creationModels, ['Model A']); assert.equal(items[0].hasHtmlProject, true);+ assert.equal('files' in items[0], false);+});diff --git a/web/template-gallery.ts b/web/template-gallery.tsindex f87a00c6..6733f59e 100644--- a/web/template-gallery.ts+++ b/web/template-gallery.ts@@ -29,7 +29,7 @@ export function mountTemplates(root: HTMLElement, options: {svg.setAttribute('class', 'ui-icon'); svg.setAttribute('aria-hidden', 'true'); use.setAttribute('href', '/web/design-system/icons.svg#icon-' + name); svg.append(use); return svg;};const copyTemplate = (template: GalleryTemplate, button: HTMLButtonElement) => {- const info = options.info(); if (info && canCopy()) void options.copy(templatePrompt(info, options.host(), template), 'Template instruction', button);+ const info = options.info(); if (info && canCopy()) void options.copy(templatePrompt(info, options.host(), template, language.locale), 'Template instruction', button);};function configurePlayback() {playback.configure(active && enabled && !dialog.open && !document.hidden, window.innerWidth < 680 ? 1 : 2);@@ -201,7 +201,7 @@ export function mountTemplates(root: HTMLElement, options: {function updateConnection() {root.querySelectorAll<HTMLButtonElement>('[data-copy-template], #copy-preview-template').forEach(button => button.disabled = !canCopy());if (preview) {- const info = options.info(); language.text(element('preview-prompt'), info ? templatePrompt(info, options.host(), preview) : "Reconnect to copy the recreation instruction.");+ const info = options.info(); language.text(element('preview-prompt'), info ? templatePrompt(info, options.host(), preview, language.locale) : "Reconnect to copy the recreation instruction.");language.text(element('preview-copy-hint'), options.host() === 'chatgpt' ? 'Choose an available local client to start recreating.' : 'Copy the instruction and send it to {host} to start recreating.', { host: hostNames[options.host()] });}}