Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions e2e/mcp.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,47 @@ test('MCP reverses, freezes and curve-speeds video clips', async({ page }) => {
}
});

test('MCP and the sticker panel add stickers and shapes', async({ page }) => {
const { client, call } = await startServer();
try {
await page.addInitScript(({ mcpPort, code }) => {
localStorage.setItem('flycut.mcpBridge', '1');
localStorage.setItem('flycut.mcpPort', mcpPort);
localStorage.setItem('flycut.mcpCode', code);
}, { mcpPort: port, code: pairingCode });
await page.goto('/');
await expect(page.locator('.ai-status')).toHaveAttribute('data-status', 'connected');
const star = await call('add_sticker', { name: 'star', color: '#ff0000', outline: true, start: 0, duration: 1, x: 40 });
expect(star).toMatchObject({ type: 'image', start: 0, end: 1, x: 40 });
const fire = await call('add_sticker', { name: 'fire', start: 0, duration: 1 });
expect(fire).toMatchObject({ type: 'image', start: 0, end: 1 });
const heart = await call('add_sticker', { name: 'heart', start: 0, duration: 30 });
expect(heart).toMatchObject({ start: 0, end: 30 });
await call('undo');
expect((await call('get_timeline')).clips.map(({ id }: { id: string }) => id)).not.toContain(heart.id);
await expect(call('add_sticker', { name: 'unicorn' })).rejects.toThrow('Unknown sticker or shape');
await expect(call('add_sticker', { name: 'rect', color: 'not-a-colour' })).rejects.toThrow('CSS colour');
const assets = await call('list_assets');
expect(assets.filter(({ kind }: { kind: string }) => kind === 'image')).toHaveLength(3);

await page.locator('.tabsToggle > div', { hasText: '贴纸' }).click();
await page.locator('.sticker-panel .sticker-smile').click();
await expect.poll(() => call('get_timeline').then(({ clips }) => clips.length)).toBe(3);

const exported = page.waitForEvent('download');
await call('export_video', { fileName: 'stickers.mp4' });
expect((await (await exported).createReadStream()).readable).toBe(true);

const download = page.waitForEvent('download');
const { fileName } = await call('export_jianying', { draftRoot: '' });
const zip = unzipSync(new Uint8Array(Buffer.concat(await (await (await download).createReadStream()).toArray())));
const content = JSON.parse(strFromU8(zip[`${fileName.replace(/\.zip$/, '')}/draft_content.json`]));
expect(content.materials.videos.filter(({ type }: { type: string }) => type === 'photo')).toHaveLength(3);
} finally {
await client.close();
}
});

test('the local MCP server only accepts an editor with the pairing code', async({ page }) => {
const { client, call } = await startServer();
try {
Expand Down
19 changes: 19 additions & 0 deletions src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { saveRenderedVideo } from '@/utils/videoExport';
import { addSubtitles, textSegments, transcribeTimeline } from '@/subtitles';
import { formatSrt, parseSrt } from '@/subtitles/srt';
import { t } from '@/lib/i18n';
import { isShape, isSticker, shapes, stickers } from '@/data/stickers';
import { insertSticker } from '@/utils/insertSticker';

/**
* 编辑命令层:界面之外的调用方(本地 MCP 服务、WebMCP)都通过这里修改工程。
Expand Down Expand Up @@ -294,6 +296,23 @@ const handlers: Record<string, (args: Args) => unknown> = {
const track = await insertAsset(record, typeof start === 'number' ? frames(start) : undefined);
return describeById(track.id);
},
async add_sticker({ name, color, outline, start, duration, x, y }) {
const key = String(name);
if (!isShape(key) && !isSticker(key)) {
throw new Error(`Unknown sticker or shape ${key}; stickers: ${stickers.map(item => item.name).join(', ')}; shapes: ${shapes.map(item => item.name).join(', ')}`);
}
if (color !== undefined && (typeof color !== 'string' || !CSS.supports('color', color))) throw new Error('color must be a CSS colour');
// 时长和位置在加入时间轴前设置,按最终时长选轨道,一次撤销即可移除
const track = await insertSticker(key, { color: typeof color === 'string' ? color : '#FFFFFF', outline: outline === true }, typeof start === 'number' ? frames(start) : undefined, sticker => {
if (typeof duration === 'number') {
sticker.frameCount = Math.max(1, frames(duration));
sticker.end = sticker.start + sticker.frameCount;
}
if (typeof x === 'number') sticker.centerX = x;
if (typeof y === 'number') sticker.centerY = y;
});
return describeById(track.id);
},
add_text({ content, start, duration, fontSize, fill, stroke, x, y }) {
const track = new TextTrack({
content: String(content),
Expand Down
41 changes: 41 additions & 0 deletions src/commands/tools.json
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,47 @@
"additionalProperties": false
}
},
{
"name": "add_sticker",
"description": "Add a built-in sticker or shape as an image clip. The picture is imported into the asset list first. Returns the new clip.",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Sticker: smile, love, starBadge, fire, sparkle, check, cross, question, exclaim, lightning, music, crown, new, hot, like, sun. Shape: rect, roundRect, circle, triangle, diamond, hexagon, star, heart, bubble, arrow, line"
},
"color": {
"type": "string",
"description": "CSS colour of a shape, defaults to white; stickers keep their own colours"
},
"outline": {
"type": "boolean",
"description": "Draw the shape as an outline instead of filled"
},
"start": {
"type": "number",
"minimum": 0,
"description": "Seconds, defaults to the playhead"
},
"duration": {
"type": "number",
"exclusiveMinimum": 0,
"description": "Seconds, defaults to 60"
},
"x": {
"type": "number"
},
"y": {
"type": "number"
}
},
"required": [
"name"
],
"additionalProperties": false
}
},
{
"name": "add_text",
"description": "Add a text (caption) clip. Returns the new clip.",
Expand Down
1 change: 1 addition & 0 deletions src/components/ItemList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<MediaPanel v-if="activeKey === 'media'" />
<TextPanel v-if="activeKey === 'text'" />
<SubtitlePanel v-if="activeKey === 'subtitle'" />
<StickerPanel v-if="activeKey === 'sticker'" />
</div>
</div>
</template>
Expand Down
84 changes: 84 additions & 0 deletions src/components/StickerPanel/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<template>
<div class="p-4 flex-1 overflow-y-auto scrollbar-width-none sticker-panel">
<div class="text-sm mb-2">{{ t('贴纸') }}</div>
<ul class="stickerList">
<li
v-for="sticker in stickers"
:key="sticker.name"
:class="`sticker-${sticker.name}`"
:title="t(sticker.label)"
@click="add(sticker.name)"
>
<img :src="svgUrl(stickerSvg(sticker.name))" :alt="t(sticker.label)" draggable="false">
</li>
</ul>
<div class="text-sm mt-6 mb-2 flex items-center justify-between">
<span>{{ t('形状') }}</span>
<span class="flex items-center gap-2 text-xs">
<ColorPicker v-model="color" class="shape-color" />
<label class="flex items-center gap-1">
<Switch v-model="outline" class="shape-outline" />
{{ t('描边') }}
</label>
</span>
</div>
<ul class="stickerList">
<li
v-for="shape in shapes"
:key="shape.name"
:class="`shape-${shape.name}`"
:title="t(shape.label)"
@click="add(shape.name)"
>
<img :src="svgUrl(shapeSvg(shape.name, style))" :alt="t(shape.label)" draggable="false">
</li>
</ul>
</div>
</template>

<script setup lang="ts">
import { t } from '@/lib/i18n';
import { computed, ref } from 'vue';
import { shapes, shapeSvg, stickers, stickerSvg, type ShapeStyle } from '@/data/stickers';
import { insertSticker } from '@/utils/insertSticker';
import ColorPicker from '@/components/item/formItem/color/ColorPicker.vue';
import { Switch } from '@/components/ui/switch';

const color = ref('#FFFFFF');
const outline = ref(false);
const style = computed<ShapeStyle>(() => ({ color: color.value || '#FFFFFF', outline: outline.value }));
const svgUrl = (svg: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;

async function add(name: string) {
try {
await insertSticker(name, style.value);
} catch (error) {
console.error(error);
}
}
</script>

<style scoped>
.stickerList {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
}
.stickerList li {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 10px;
border-radius: 4px;
cursor: pointer;
background: repeating-conic-gradient(rgb(127 127 127 / 20%) 0 25%, transparent 0 50%) 50% / 12px 12px;
}
.stickerList li:hover {
outline: 2px solid #3b82f6;
}
.stickerList img {
max-width: 100%;
max-height: 100%;
}
</style>
2 changes: 2 additions & 0 deletions src/components/container/MobilePanels.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<MediaPanel v-if="current.key === 'media'" />
<TextPanel v-else-if="current.key === 'text'" />
<SubtitlePanel v-else-if="current.key === 'subtitle'" />
<StickerPanel v-else-if="current.key === 'sticker'" />
<AttributeContainer v-else embedded />
</div>
</div>
Expand All @@ -37,6 +38,7 @@
import { Button } from '@/components/ui/button';
import MediaPanel from '@/components/MediaPanel/index.vue';
import TextPanel from '@/components/TextPanel/index.vue';
import StickerPanel from '@/components/StickerPanel/index.vue';
import SubtitlePanel from '@/components/SubtitlePanel/index.vue';
import AttributeContainer from '@/components/container/AttributeContainer.vue';

Expand Down
3 changes: 2 additions & 1 deletion src/data/baseMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ interface MenuItem {
const menuData: MenuItem[] = [
{ title: '资源', key: 'media', icon: 'icon-shangchuan_line' },
{ title: '文字', key: 'text', icon: 'icon-wenzi_line' },
{ title: '字幕', key: 'subtitle', icon: 'icon-yuyin_line' }
{ title: '字幕', key: 'subtitle', icon: 'icon-yuyin_line' },
{ title: '贴纸', key: 'sticker', icon: 'icon-tiezhi_line' }
];

export { menuData };
Expand Down
28 changes: 28 additions & 0 deletions src/data/stickers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest';
import { isShape, isSticker, shapes, shapeSvg, stickers, stickerSvg } from './stickers';

const parse = (svg: string) => new DOMParser().parseFromString(svg, 'image/svg+xml');

describe('stickers and shapes', () => {
it('builds well-formed SVG for every item', () => {
[...shapes.map(({ name }) => shapeSvg(name, { color: '#FF0000' })), ...stickers.map(({ name }) => stickerSvg(name))].forEach(svg => {
expect(parse(svg).querySelector('parsererror')).toBeNull();
expect(parse(svg).documentElement.getAttribute('viewBox')).toMatch(/^0 0 100 \d+$/);
});
});

it('fills or outlines shapes in the chosen colour', () => {
const filled = parse(shapeSvg('star', { color: '#123456' })).querySelector('path')!;
expect(filled.getAttribute('fill')).toBe('#123456');
const outlined = parse(shapeSvg('star', { color: '#123456', outline: true })).querySelector('path')!;
expect(outlined.getAttribute('fill')).toBe('none');
expect(outlined.getAttribute('stroke')).toBe('#123456');
expect(parse(shapeSvg('line', { color: 'red' })).querySelector('path')!.getAttribute('stroke')).toBe('red');
});

it('escapes colour values and keeps names unique', () => {
expect(shapeSvg('rect', { color: '"><script>' })).not.toContain('<script>');
expect(new Set([...shapes, ...stickers].map(({ name }) => name)).size).toBe(shapes.length + stickers.length);
expect(isShape('arrow') && isSticker('fire') && !isShape('fire')).toBe(true);
});
});
Loading
Loading