Skip to content

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.

7.7 KB
Raw Blame
// @vitest-environment happy-dom
import { act } from 'react';
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 }) }));
const builtin = { id: 'product-promo', kind: 'builtin', title: 'Product Promo', author: 'Hyperframes', description: 'Editable', tags: [], collection: 'builtin' };
const reference = { id: 'hf-moment-M953', kind: 'reference', title: 'Reference', author: 'Creator', description: 'Reference video', tags: [], collection: 'moment' };
let root: Root, container: HTMLDivElement;
let fetcher: ReturnType<typeof vi.fn>;
let clipboard: ReturnType<typeof vi.fn>;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
beforeEach(() => {
  state.disabled = false; vi.clearAllMocks(); vi.useFakeTimers();
  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') ? integration : {
    items: url.includes('category=builtin') ? [builtin] : [reference], total: 1, entryTotal: 1, catalogTotal: 2, offset: 0, next: null,
  })));
  vi.stubGlobal('fetch', fetcher);
});
afterEach(() => { act(() => root.unmount()); container.remove(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers(); });
async function render(locale: Locale = 'zh-CN') { await act(async () => { root.render(<I18nProvider initialLocale={locale}><HomeTemplates /></I18nProvider>); }); await act(async () => { await vi.runOnlyPendingTimersAsync(); }); }
const button = (text: string) => [...container.querySelectorAll('button')].find(item => item.textContent === text)!;
it('only editable templates open a new engineering project; references copy their exact Agent instruction', async () => {
  await render();
  expect(container.querySelector('.motion-editable-badge')?.textContent).toBe('可以二次剪辑');
  act(() => button('打开并编辑').click());
  expect(state.open).toHaveBeenCalledWith('templates', 'product-promo');
  act(() => button('精选参考').click());
  await act(async () => { await vi.runOnlyPendingTimersAsync(); });
  expect(container.querySelector('.motion-editable-badge')).toBeNull();
  await act(async () => button('一键复制').click());
  expect(clipboard).toHaveBeenCalledOnce();
  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('已复制');
});
it('blocked project actions remain unavailable and denied clipboard access offers a usable instruction', async () => {
  state.disabled = true;
  await render();
  expect(button('打开并编辑').disabled).toBe(true);
  act(() => button('精选参考').click());
  await act(async () => { await vi.runOnlyPendingTimersAsync(); });
  clipboard.mockRejectedValue(new Error('denied'));
  await act(async () => button('一键复制').click());
  expect(container.querySelector<HTMLTextAreaElement>('textarea')!.value).toContain('hf-moment-M953');
  expect(state.open).not.toHaveBeenCalled();
});
it('switching filters clears previous results and offers retry on a failed request', async () => {
  await render();
  fetcher.mockImplementation(async (_url: string) => new Response(JSON.stringify({ error: 'offline' }), { status: 503 }));
  act(() => button('精选参考').click());
  await act(async () => { await vi.runOnlyPendingTimersAsync(); });
  expect(container.querySelectorAll('.motion-home-template')).toHaveLength(0);
  expect(container.querySelector('[role="alert"]')?.textContent).toContain('offline');
  expect(button('重试')).toBeTruthy();
});

it('Prism templates open as editable projects and published catalog changes refresh the list', async () => {
  let version = 'first';
  fetcher.mockImplementation(async () => Response.json({
    items: [{ ...builtin, id: 'hf-moment-M1147', kind: 'prism', title: version === 'first' ? 'Figma 模板' : '更新后的模板' }],
    total: 1, entryTotal: 1, catalogTotal: 1, offset: 0, next: null, catalogVersion: version,
  }));
  await render();
  expect(container.textContent).toContain('Figma 模板');
  await act(async () => button('打开并编辑').click());
  expect(state.open).toHaveBeenCalledWith('templates', 'hf-moment-M1147');
  version = 'second';
  await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
  await act(async () => { await vi.advanceTimersByTimeAsync(1); });
  expect(container.textContent).toContain('更新后的模板');
  expect(state.open).toHaveBeenCalledTimes(1);
});

it('updates and clears cache warnings without resetting an unchanged template list', async () => {
  let warning: string | undefined;
  fetcher.mockImplementation(async () => Response.json({
    items: [{ ...builtin, kind: 'prism' }], total: 1, entryTotal: 1, catalogTotal: 1,
    offset: 0, next: null, catalogVersion: 'same-publication', warning,
  }));
  await render();
  const card = container.querySelector('.motion-home-template');
  warning = '模板更新失败,使用已缓存目录:HTTP 503';
  await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
  expect(container.querySelector('[role="status"]')?.textContent).toContain(warning);
  expect(container.querySelector('.motion-home-template')).toBe(card);
  warning = undefined;
  await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
  expect(container.querySelector('[role="status"]')).toBeNull();
  expect(container.querySelector('.motion-home-template')).toBe(card);
});

it.each(['de', 'ja', 'ru'] as const)('keeps Prism editing and project guards while localizing labels in %s', async locale => {
  const id = 'hf-moment-M1147';
  const warning = '模板更新失败,使用已缓存目录:HTTP 503';
  fetcher.mockImplementation(async () => Response.json({
    items: [{ ...builtin, id, kind: 'prism', title: 'Original template title', social: { platform: 'X', views: 12345, syncedAt: '2026-11-09' } }],
    total: 1, entryTotal: 1, catalogTotal: 1, offset: 0, next: null, warning,
  }));
  await render(locale);
  expect(container.textContent).toContain('Original template title');
  expect(container.querySelector('.motion-editable-badge')?.textContent).toBe(translate(locale, 'Ready to edit'));
  expect(container.querySelector('[role="status"]')?.textContent).toBe(translate(locale, warning));
  if (locale === 'de') expect(container.querySelector('.motion-template-footer small')?.textContent).toContain('12.345');
  const open = button(translate(locale, 'Open and edit'));
  expect(open.disabled).toBe(false);
  act(() => open.click());
  expect(state.open).toHaveBeenCalledWith('templates', id);
  state.disabled = true;
  await act(async () => { root.render(<I18nProvider initialLocale={locale}><HomeTemplates /></I18nProvider>); });
  expect(button(translate(locale, 'Open and edit')).disabled).toBe(true);
});