Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Ease canvas navigation and tailor agent prompts
shinshin86903f7fa0fca9
diff --git a/README.md b/README.mdindex d6594f4..f058e24 100644--- a/README.md+++ b/README.md@@ -61,8 +61,9 @@ The guide recommends these setups:| Codex | GPT-6.1 Sol |The empty workspace offers a copyable project request. In **Drawn variants**, check-**Eyes**, **Mouth**, or both to show a request for the current project. Open Codex in the-displayed repository folder and paste the message. The development server automatically+**Eyes**, **Mouth**, or both to show a request for the current project. Open the selected agent in the+displayed repository folder and paste the message. Displayed home paths use `~`; path+copy buttons copy the full path. The development server automaticallyloads changed sprites into the current view.## Create a project from a new illustration@@ -119,7 +120,14 @@ may need manual retouching. Inpainting approximates the artwork hidden behind ha- Drag a handle or select an item to edit its numeric fields.- Double-click a polygon/polyline edge to insert a vertex; Alt-click a vertex to remove it.-- Use the mouse wheel to zoom at the cursor; Space-drag or middle-drag to pan; **Fit** resets the view.+- Pinch to zoom at the cursor; two-finger scrolling pans. A mouse wheel zooms by default;+ **Mouse wheel** can switch it to panning. Ctrl/Cmd-scroll always zooms.+- Drag empty space, Space-drag or middle-drag to pan. Use **− / +** to zoom, the percentage+ to return to 100% (one image pixel per screen pixel), **Fit** for the whole image, or+ **Fit selected part** for the current part. Double-clicking a part in the list also fits it.+ Zoom ranges from 10% to 1600%, while dots keep the same screen size.+- Ctrl/Cmd+plus, minus, 0 and 1 zoom in, zoom out, fit and reset to 100%. These shortcuts+ leave browser behavior alone when an input is focused.- **Undo** / **Redo** restore edits. Keyboard shortcuts: Ctrl/Cmd+Z, Ctrl/Cmd+Shift+Z and Ctrl/Cmd+S.- **Save rig** saves a listed project, or downloads the JSON for a browser-picked folder.Dropping a JSON file also loads it.@@ -130,8 +138,10 @@ may need manual retouching. Inpainting approximates the artwork hidden behind haavailable; otherwise the mesh mouth animates. This check does not play audio.**Drawn variants** shows eye and mouth image counts. Check the drawings you want and-copy the prepared agent message, which refers to the generation, import and review steps-in the guide. Changes in the local project's `variants/` and `built/sprites/` directories+copy the prepared message for **Codex** or **Claude Code**. Codex's message requests its+built-in image generation, local import and pose review, and the card states that images+will be sent to Codex image generation. Claude Code's message asks it to prepare masks+and prompts and explain where to save the drawings, then stop. The recipient is remembered. Changes in the local project's `variants/` and `built/sprites/` directoriesreload in place, keeping unsaved outlines, selection, zoom and undo history. The sample'srequest asks the agent to work on a copy under `projects/`, leaving the original intact.@@ -140,7 +150,8 @@ and prompts with `variant-requests.py`, or to drop or choose full-size PNGs withfilenames. The editor validates dimensions and pixels outside the mask before buildingsprites; rejected imports keep the previous drawings and sprites. Manual export and importneed a writable project from the development server. The app keeps images local; the-agent request asks for your permission before sending images to an external generator.+Codex card discloses the image-generation upload before you copy its request; other+external services are excluded from that request.## Verifydiff --git a/docs/agent-guide.md b/docs/agent-guide.mdindex aca3894..c4b00e4 100644--- a/docs/agent-guide.md+++ b/docs/agent-guide.md@@ -152,6 +152,8 @@ the rig is good enough: continue to Step 6, which removes them.## Step 6 — Drawn variants (closed eyes, mouth shapes)+Codex uses its built-in image generation (imagegen) for these variants.+Blinking and talking look much better with drawn variants. Create the requests:```shdiff --git a/e2e/agent-request.spec.ts b/e2e/agent-request.spec.tsnew file mode 100644index 0000000..b671621--- /dev/null+++ b/e2e/agent-request.spec.ts@@ -0,0 +1,47 @@+import { test, expect } from '@playwright/test';+import { resolve } from 'node:path';+import { homedir } from 'node:os';+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';++test('paths and tooltips use ~ while copies keep full paths, and recipient changes persist', async ({ page, context }) => {+ test.skip(!samplePresent, sampleSkipReason); await context.grantPermissions(['clipboard-read', 'clipboard-write']);+ await page.goto('/'); await dismissGuide(page);+ await page.locator('.open-menu > summary').click(); await page.getByTestId('project-sample-miko-qipao').click();+ await page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true }).check();+ const card = page.getByTestId('ask-agent-variants');+ await expect(card.locator('.root-path')).toHaveText(resolve('.').replace(homedir(), '~'));+ await expect(card.locator('.root-path')).toHaveAttribute('title', resolve('.').replace(homedir(), '~'));+ await expect(page.getByTestId('project-location')).toContainText('~/');+ await card.getByRole('button', { name: 'Copy full path', exact: true }).click(); expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(resolve('.'));+ const leaked = await page.locator('main').evaluate((main, home) => {+ const text = (main as HTMLElement).innerText, attributes = [...main.querySelectorAll('*')].flatMap(element => [...element.attributes].map(attr => attr.value));+ return [text, ...attributes].filter(value => value.includes(home));+ }, homedir()); expect(leaked).toEqual([]);+ await card.getByRole('button', { name: 'Copy message', exact: true }).click();+ const codex = await page.evaluate(() => navigator.clipboard.readText());+ for (const word of ['imagegen', 'source.png', 'variants/', 'build-sprites', 'render-poses', 'already consented', 'Do not use other external services']) expect(codex).toContain(word);+ await expect(card.getByText('Images will be sent to Codex image generation.', { exact: true })).toBeVisible();+ await card.getByRole('button', { name: 'Claude Code', exact: true }).click();+ await expect(card.getByRole('button', { name: 'Claude Code', exact: true })).toHaveAttribute('aria-pressed', 'true');+ await expect(card.locator('.agent-disclosure')).toHaveCount(0);+ await expect(card.getByRole('textbox')).toContainText('then stop'); await expect(card.getByRole('textbox')).toContainText('Do not generate or send images');+ await page.reload(); await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ await page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true }).check();+ await expect(card.getByRole('button', { name: 'Claude Code', exact: true })).toHaveAttribute('aria-pressed', 'true');+ await page.getByRole('button', { name: '日本語', exact: true }).click();+ await expect(card.getByRole('textbox')).toContainText('そこで止まってください'); await expect(card.locator('.agent-instruction')).toContainText('Claude Code');+ await card.getByRole('button', { name: 'Codex', exact: true }).click();+ await expect(card.getByText('画像は Codex の画像生成に送られます', { exact: true })).toBeVisible();+ await expect(card.getByRole('textbox')).toContainText('ユーザーは Codex の画像生成の利用に同意済み');+});+test('blocked preference storage still allows recipient and wheel mode changes', async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.addInitScript(() => { Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Blocked', 'SecurityError'); } }); });+ const errors: string[] = []; page.on('pageerror', error => errors.push(error.message));+ await page.goto('/'); await dismissGuide(page);+ await page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true }).check();+ await page.getByTestId('ask-agent-variants').getByRole('button', { name: 'Claude Code', exact: true }).click();+ await expect(page.getByTestId('ask-agent-variants').getByRole('textbox')).toContainText('Claude Code cannot generate images');+ await page.getByRole('combobox', { name: 'Mouse wheel', exact: true }).selectOption('pan');+ await expect(page.getByRole('combobox', { name: 'Mouse wheel', exact: true })).toHaveValue('pan'); expect(errors).toEqual([]);+});diff --git a/e2e/canvas-navigation.spec.ts b/e2e/canvas-navigation.spec.tsnew file mode 100644index 0000000..271d215--- /dev/null+++ b/e2e/canvas-navigation.spec.ts@@ -0,0 +1,74 @@+import { test, expect, type Page } from '@playwright/test';+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';++test.beforeEach(async ({ page }) => {+ test.skip(!samplePresent, sampleSkipReason);+ await page.goto('/'); await dismissGuide(page);+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ await expect.poll(async () => Number(await page.getByTestId('editor').getAttribute('data-scale'))).toBeLessThan(1);+});+async function view(page: Page) {+ return page.getByTestId('editor').evaluate(element => ({ scale: Number(element.dataset.scale), x: Number(element.dataset.offsetX), y: Number(element.dataset.offsetY) }));+}+async function wheel(page: Page, options: { deltaX?: number; deltaY: number; ctrlKey?: boolean; metaKey?: boolean; deltaMode?: number }) {+ return page.getByTestId('editor').evaluate((element, options) => {+ const rect = element.getBoundingClientRect();+ return !element.dispatchEvent(new WheelEvent('wheel', { ...options, clientX: rect.left + 190, clientY: rect.top + 230, bubbles: true, cancelable: true }));+ }, options);+}+test('pinch keeps its cursor anchor, two-finger scrolling pans, and mouse mode persists', async ({ page }) => {+ const first = await view(page);+ expect(await wheel(page, { deltaX: 12.5, deltaY: 25.5 })).toBe(true);+ await expect.poll(async () => (await view(page)).x).toBeCloseTo(first.x - 12.5);+ const panned = await view(page); expect(panned.scale).toBe(first.scale); expect(panned.y).toBeCloseTo(first.y - 25.5);+ expect(await wheel(page, { deltaY: -200, ctrlKey: true })).toBe(true);+ await expect.poll(async () => (await view(page)).scale).toBeCloseTo(first.scale * Math.exp(0.2));+ const zoomed = await view(page);+ expect((190 - zoomed.x) / zoomed.scale).toBeCloseTo((190 - panned.x) / panned.scale);+ expect((230 - zoomed.y) / zoomed.scale).toBeCloseTo((230 - panned.y) / panned.scale);+ await wheel(page, { deltaY: -3, deltaMode: 1 }); await expect.poll(async () => (await view(page)).scale).toBeCloseTo(zoomed.scale * Math.exp(0.048));+ await page.getByRole('combobox', { name: 'Mouse wheel', exact: true }).selectOption('pan');+ const before = await view(page); await wheel(page, { deltaY: 120 }); await expect.poll(async () => (await view(page)).y).toBeCloseTo(before.y - 120);+ expect((await view(page)).scale).toBe(before.scale);+ await wheel(page, { deltaY: -40, metaKey: true }); await expect.poll(async () => (await view(page)).scale).toBeGreaterThan(before.scale);+ await page.reload(); await expect(page.getByRole('combobox', { name: 'Mouse wheel', exact: true })).toHaveValue('pan');+});+test('Safari gesture events zoom from their starting scale without accumulating changes', async ({ page }) => {+ const initial = await view(page);+ const results = await page.getByTestId('editor').evaluate(element => {+ const rect = element.getBoundingClientRect();+ return [['gesturestart', 1], ['gesturechange', 1.5], ['gesturechange', 2], ['gestureend', 2]].map(([name, scale]) => {+ const event = new Event(String(name), { cancelable: true });+ Object.assign(event, { scale, clientX: rect.left + 190, clientY: rect.top + 230 });+ const cancelled = !element.dispatchEvent(event);+ if (name === 'gesturechange' && scale === 2) element.dispatchEvent(new WheelEvent('wheel', { deltaY: -200, ctrlKey: true, cancelable: true }));+ return cancelled;+ });+ });+ expect(results).toEqual([true, true, true, true]);+ await expect.poll(async () => (await view(page)).scale).toBeCloseTo(initial.scale * 2);+ const after = await view(page); expect((190 - after.x) / after.scale).toBeCloseTo((190 - initial.x) / initial.scale);+});+test('empty-space drag, zoom buttons, shortcuts, limits and part fitting keep rig edits untouched', async ({ page }) => {+ const initial = await view(page), canvas = page.getByTestId('editor'), box = (await canvas.boundingBox())!;+ await page.mouse.move(box.x + 12, box.y + 12); await page.mouse.down(); await page.mouse.move(box.x + 44, box.y + 34); await page.mouse.up();+ await expect.poll(async () => (await view(page)).x).toBeCloseTo(initial.x + 32);+ await expect(page.getByRole('button', { name: 'Undo', exact: true })).toBeDisabled();+ await page.getByTestId('zoom-value').click(); await expect(page.getByTestId('zoom-value')).toHaveText('100%');+ await page.getByRole('button', { name: 'Zoom in', exact: true }).click(); await expect(page.getByTestId('zoom-value')).toHaveText('125%');+ await page.getByRole('button', { name: 'Zoom out', exact: true }).click(); await expect(page.getByTestId('zoom-value')).toHaveText('100%');+ await canvas.focus(); await page.keyboard.press('Control+Equal'); await expect(page.getByTestId('zoom-value')).toHaveText('125%');+ await page.keyboard.press('Control+-'); await expect(page.getByTestId('zoom-value')).toHaveText('100%');+ await page.keyboard.press('Meta+0'); await expect.poll(async () => (await view(page)).scale).toBeCloseTo(initial.scale);+ await page.keyboard.press('Meta+1'); await expect(page.getByTestId('zoom-value')).toHaveText('100%');+ await page.getByTestId('part-mouth').click(); await page.getByRole('button', { name: 'Fit selected part', exact: true }).click();+ expect((await view(page)).scale).toBeGreaterThan(2); const fitted = await view(page);+ await page.getByRole('button', { name: 'Fit', exact: true }).click(); await page.getByTestId('part-mouth').dblclick();+ await expect.poll(async () => (await view(page)).scale).toBeCloseTo(fitted.scale);+ await wheel(page, { deltaY: -100000, ctrlKey: true }); await expect(page.getByTestId('zoom-value')).toHaveText('1600%');+ await wheel(page, { deltaY: 100000, ctrlKey: true }); await expect(page.getByTestId('zoom-value')).toHaveText('10%');+ await page.getByTestId('part-head').click(); const field = page.getByRole('spinbutton', { name: 'head.cx', exact: true }); await field.focus();+ const preserved = await view(page);+ expect(await field.evaluate(element => { const event = new KeyboardEvent('keydown', { key: '+', ctrlKey: true, bubbles: true, cancelable: true }); element.dispatchEvent(event); return event.defaultPrevented; })).toBe(false);+ expect(await view(page)).toEqual(preserved); await expect(field).toHaveValue('615'); await expect(page.getByTestId('stale-banner')).toHaveCount(0);+});diff --git a/e2e/projects-lipsync.spec.ts b/e2e/projects-lipsync.spec.tsindex c5fb73f..332d685 100644--- a/e2e/projects-lipsync.spec.ts+++ b/e2e/projects-lipsync.spec.ts@@ -1,3 +1,4 @@+import { homedir } from 'node:os';import { expect, test, type Page } from '@playwright/test';import { cp, mkdir, mkdtemp, readFile, rm } from 'node:fs/promises';import { resolve, basename, join } from 'node:path';@@ -41,7 +42,7 @@ test('listed project saves in place with one backup, supports keyboard save, patawait context.grantPermissions(['clipboard-read', 'clipboard-write']);await open(page, name);const location = page.getByTestId('project-location'); await expect(location).toContainText(`projects/${name}`);- await expect(location.locator('.project-path')).toHaveAttribute('title', directory);+ await expect(location.locator('.project-path')).toHaveAttribute('title', directory.replace(homedir(), '~'));await page.getByRole('button', { name: 'Copy full path' }).click();expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(directory);await expect(page.getByTestId('project-location').getByRole('button', { name: '✓ Copied', exact: true })).toHaveAttribute('aria-live', 'polite');diff --git a/e2e/workflow.spec.ts b/e2e/workflow.spec.tsindex 2bc7afb..26ec429 100644--- a/e2e/workflow.spec.ts+++ b/e2e/workflow.spec.ts@@ -2,6 +2,7 @@ import { test, expect, type Page } from '@playwright/test';import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { join, resolve, basename } from 'node:path';import { createHash } from 'node:crypto';+import { homedir } from 'node:os';import { PNG } from 'pngjs';import fixture from '../samples/miko-qipao/rig.json' with { type: 'json' };import { dismissGuide, samplePresent, sampleSkipReason } from './sample';@@ -42,8 +43,10 @@ async function drop(page: Page, bytes: Buffer, filename: string) {test('rebuild runs the real local tool, reloads changed pixels and keeps selection, zoom and undo history', async ({ page }) => {test.setTimeout(90000); await open(page); await editEye(page);const editor = page.getByTestId('editor'); const point = page.getByRole('spinbutton', { name: 'eyes.0.opening.0.0', exact: true });+ const initialScale = Number(await editor.getAttribute('data-scale'));await editor.hover(); await page.mouse.wheel(0, -200);- await expect(page.locator('.zoom-tools > span')).toHaveText('122%');+ await expect.poll(async () => Number(await editor.getAttribute('data-scale'))).toBeCloseTo(initialScale * Math.exp(0.2));+ const zoomText = await page.getByTestId('zoom-value').textContent();const before = await pixels(page), base = await readFile(join(directory, 'built/base.png'));const beforeSize = await page.getByTestId('preview').evaluate(canvas => [(canvas as HTMLCanvasElement).width, (canvas as HTMLCanvasElement).height]);const button = page.getByRole('button', { name: 'Save and rebuild layers', exact: true });@@ -51,7 +54,7 @@ test('rebuild runs the real local tool, reloads changed pixels and keeps selectiawait expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');expect(await page.getByTestId('preview').evaluate(canvas => [(canvas as HTMLCanvasElement).width, (canvas as HTMLCanvasElement).height])).toEqual(beforeSize);expect(await pixels(page)).not.toBe(before); expect(await readFile(join(directory, 'built/base.png'))).not.toEqual(base);- await expect(editor).toHaveAttribute('data-focus-group', 'eyes'); await expect(page.locator('.zoom-tools > span')).toHaveText('122%');+ await expect(editor).toHaveAttribute('data-focus-group', 'eyes'); await expect(page.getByTestId('zoom-value')).toHaveText(zoomText!);await expect(point).toHaveValue('451'); await expect(page.getByRole('button', { name: 'Undo', exact: true })).toBeEnabled();await page.getByRole('button', { name: 'Undo', exact: true }).click(); await expect(point).toHaveValue('446');await expect(page.getByTestId('stale-banner')).toBeVisible();@@ -77,7 +80,7 @@ test('requests provide masks, root handoff and prompts; drops accept valid drawiexpect(await page.evaluate(() => navigator.clipboard.readText())).toBe(resolve('.'));await agent.getByRole('button', { name: 'Copy message', exact: true }).click();const prompt = await page.evaluate(() => navigator.clipboard.readText()); expect(prompt).toContain(`projects/${name}`); expect(prompt).toContain('Step 6'); expect(prompt).toContain('mouth drawn variants');- expect(prompt).toContain('ask me before sending images to an external generator');+ expect(prompt).toContain('The user has already consented to Codex image generation'); expect(prompt).toContain('Do not use other external services');await expect(agent.getByRole('button', { name: '✓ Copied', exact: true })).toHaveCount(2);await expect(agent.getByRole('button', { name: 'Copy message', exact: true })).toBeVisible({ timeout: 5000 });await expect(agent.locator('ol')).toHaveCount(0); await expect(panel.locator('select')).toHaveCount(0);@@ -116,7 +119,7 @@ test('empty workspace has a single prompt copy and a one-line repository path, wawait page.route('**/miko-qipao/**/*.png', route => route.fulfill({ status: 404, body: '' }));await page.route('**/miko-qipao/source.png', route => route.fulfill({ status: 404, body: '' }));await page.goto('/'); const card = page.getByTestId('ask-agent-new'); await expect(card).toBeVisible();- await expect(card.locator('.root-path')).toHaveText(resolve('.'));+ await expect(card.locator('.root-path')).toHaveText(resolve('.').replace(homedir(), '~'));await card.getByRole('button', { name: 'Copy message', exact: true }).click();expect(await page.evaluate(() => navigator.clipboard.readText())).toContain('projects/my-avatar');await expect(card.getByRole('button', { name: '✓ Copied', exact: true })).toHaveAttribute('aria-live', 'polite');@@ -149,7 +152,10 @@ test('the read-only sample still gives a mouth request and keeps its source prottest('external sprite updates load automatically while keeping edited outlines, selection, zoom and undo', async ({ page, request }) => {test.setTimeout(90000); await page.setViewportSize({ width: 1440, height: 900 }); await open(page); await editEye(page);const point = page.getByRole('spinbutton', { name: 'eyes.0.opening.0.0', exact: true });- await page.getByTestId('editor').hover(); await page.mouse.wheel(0, -200); await expect(page.locator('.zoom-tools > span')).toHaveText('122%');+ const initialScale = Number(await page.getByTestId('editor').getAttribute('data-scale'));+ await page.getByTestId('editor').hover(); await page.mouse.wheel(0, -200);+ await expect.poll(async () => Number(await page.getByTestId('editor').getAttribute('data-scale'))).toBeCloseTo(initialScale * Math.exp(0.2));+ const zoomText = await page.getByTestId('zoom-value').textContent();await page.getByRole('tab', { name: 'Lip sync', exact: true }).click(); await page.getByRole('button', { name: 'あ', exact: true }).click(); await page.waitForTimeout(300);const before = await pixels(page);await page.screenshot({ path: 'docs/screenshots/ui4-auto-before-en-1440x900.png' });@@ -168,7 +174,7 @@ test('external sprite updates load automatically while keeping edited outlines,await page.screenshot({ path: 'docs/screenshots/ui4-auto-after-ja-1440x900.png' });await page.getByRole('button', { name: '英語', exact: true }).click();await expect(point).toHaveValue('451'); await expect(page.getByTestId('stale-banner')).toBeVisible();- await expect(page.getByTestId('editor')).toHaveAttribute('data-focus-group', 'eyes'); await expect(page.locator('.zoom-tools > span')).toHaveText('122%');+ await expect(page.getByTestId('editor')).toHaveAttribute('data-focus-group', 'eyes'); await expect(page.getByTestId('zoom-value')).toHaveText(zoomText!);await page.getByRole('button', { name: 'Undo', exact: true }).click(); await expect(point).toHaveValue('446');});test('pose and lip tabs keep a large preview at 1440 by 900 in both languages', async ({ page }) => {diff --git a/src/editor/App.tsx b/src/editor/App.tsxindex 3011f75..8ccfa1d 100644--- a/src/editor/App.tsx+++ b/src/editor/App.tsx@@ -48,11 +48,13 @@ function Workspace() {const [saving, setSaving] = useState(false);const [opening, setOpening] = useState(false);const [rootPath, setRootPath] = useState<string>();+ const [displayRootPath, setDisplayRootPath] = useState<string>();+ const [focusRequest, setFocusRequest] = useState<{ group: string; id: number }>();const [mouthSprites, setMouthSprites] = useState(true), [mouthRequest, setMouthRequest] = useState(0);const [job, setJob] = useState<ProjectJob | null>(null);const jobRef = useRef<ProjectJob | null>(null);const [rebuildError, setRebuildError] = useState<ProjectJobError | null>(null);- useEffect(() => { void repositoryContext().then(context => setRootPath(context?.rootPath)); }, []);+ useEffect(() => { void repositoryContext().then(context => { setRootPath(context?.rootPath); setDisplayRootPath(context?.displayRootPath); }); }, []);const [recent, setRecent] = useState(readRecent);const [reopen, setReopen] = useState(() => readPreference(REOPEN_KEY) !== '0');const remember = (entry: RecentProject) => {@@ -341,7 +343,7 @@ function Workspace() {</header>{(localProject || pickedName) && <div className="project-location" data-testid="project-location"><strong>{localProject?.readOnly ? t.sampleProject : localProject?.name || pickedName}</strong>- <span className="project-path" title={localProject?.absolutePath}>{localProject?.relativePath || t.unknownPath}</span>+ <span className="project-path" title={localProject?.displayPath ?? localProject?.relativePath}>{localProject?.displayPath ?? localProject?.relativePath ?? t.unknownPath}</span>{localProject && <><CopyButton value={localProject.absolutePath} label={t.copyPath} icon /><button className="icon-button" aria-label={navigator.platform.includes('Mac') ? t.showFinder : t.showFolder} title={navigator.platform.includes('Mac') ? t.showFinder : t.showFolder} onClick={() => { void reveal(); }}><Icon name="folder" /></button>{localProject.readOnly && <span className="badge">{t.readOnly}</span>}</>}@@ -352,13 +354,13 @@ function Workspace() {{localProject && !localProject.readOnly ? <button className="primary" disabled={job !== null || saving} onClick={() => { setRebuildError(null); void runJob('rebuild').catch(error => setRebuildError(error instanceof ProjectJobError ? error : new ProjectJobError('toolFailed'))); }}>{job === 'rebuild' ? t.rebuilding : t.rebuild}</button> : <p>{t.rebuildUnavailable}</p>}{rebuildError && <JobFeedback error={rebuildError} />}</div>}- {!sourceUrl && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} />{errorNotice}</section>}+ {!sourceUrl && <section className="panel empty-project"><h2>{checking ? t.checking : t.emptyTitle}</h2><p>{t.projectHelp}</p><p>{t.emptyHelp}</p>{recentControl}<AskAgent newProject rootPath={rootPath} displayRootPath={displayRootPath} />{errorNotice}</section>}{sourceUrl && <div className="workspace">- <div className="parts-container" inert={job !== null}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onVisible={setVisible} /></div>+ <div className="parts-container" inert={job !== null}><PartList rig={rig} visible={visible} selected={selected} onSelect={selectPart} onFocus={group => { selectPart(group); setFocusRequest(current => ({ group, id: (current?.id ?? 0) + 1 })); }} onVisible={setVisible} /></div><section className="panel editor-panel" inert={job !== null}><div className="panel-title"><h2>{t.source}</h2><span>{rig.image.width} × {rig.image.height} {t.px}</span></div><div className="canvas-stage">- <EditorCanvas sourceUrl={sourceUrl} rig={rig} visible={visible} selected={selected} onSelect={setSelected} onChange={update}+ <EditorCanvas sourceUrl={sourceUrl} rig={rig} visible={visible} selected={selected} onSelect={setSelected} onChange={update} focusRequest={focusRequest}onBegin={() => { history.begin(); setDragStale(changed.length > 0); }}onEnd={() => { history.end(); setRig(structuredClone(history.present)); setDragStale(null); }} />{guide && <FirstGuide onDismiss={dismissGuide} />}@@ -366,8 +368,8 @@ function Workspace() {</section><div className="right-column"><Preview rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={() => setMouthRequest(value => value + 1)} />- <VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={job !== null || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />- {!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} /></details>}+ <VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} displayRootPath={displayRootPath} busy={job !== null || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />+ {!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} displayRootPath={displayRootPath} /></details>}<aside className="panel inspector" inert={job !== null}><div className="selection-heading"><h2>{selectedPart?.[0] ?? t.selection}</h2></div>{errorNotice}diff --git a/src/editor/AskAgent.tsx b/src/editor/AskAgent.tsxindex a9fb12f..dc6ff6e 100644--- a/src/editor/AskAgent.tsx+++ b/src/editor/AskAgent.tsx@@ -1,15 +1,22 @@+import { useState } from 'react';+import { readPreference, savePreference } from './preferences';import { useI18n } from './i18n';import { CopyButton } from './CopyButton';-export function AskAgent({ rootPath, projectPath, target = 'both', newProject = false, readOnlySource }: {- rootPath?: string; projectPath?: string; target?: 'eyes' | 'mouth' | 'both'; newProject?: boolean; readOnlySource?: string;+export function AskAgent({ rootPath, displayRootPath, projectPath, target = 'both', newProject = false, readOnlySource }: {+ rootPath?: string; displayRootPath?: string; projectPath?: string; target?: 'eyes' | 'mouth' | 'both'; newProject?: boolean; readOnlySource?: string;}) {const { t } = useI18n();+ const [recipient, setRecipient] = useState(() => readPreference('mesh-avatar-agent-recipient') === 'claude' ? 'claude' : 'codex');+ const agent = newProject || recipient === 'codex' ? 'Codex' : 'Claude Code';const path = projectPath ?? 'projects/my-avatar';- const prompt = (readOnlySource ? t.agentCopySample.replace('SOURCE', readOnlySource).replace('PROJECT', path) : '') + (newProject ? t.agentNewPrompt : t.agentVariantPrompt).replace('PROJECT', path).replace('TARGET', target === 'eyes' ? t.agentEyes : target === 'mouth' ? t.agentMouth : t.agentBoth);+ const prompt = (readOnlySource ? t.agentCopySample.replace('SOURCE', readOnlySource).replace('PROJECT', path) : '') + (newProject ? t.agentNewPrompt : recipient === 'codex' ? t.agentCodexPrompt : t.agentClaudePrompt).replace('PROJECT', path).replace('TARGET', target === 'eyes' ? t.agentEyes : target === 'mouth' ? t.agentMouth : t.agentBoth);return <section className="ask-agent" data-testid={newProject ? 'ask-agent-new' : 'ask-agent-variants'} aria-label={t.askAgent}>- <p className="agent-instruction">{t.agentInstruction}</p>- {rootPath ? <div className="agent-path"><code className="root-path" title={rootPath}>{rootPath}</code><CopyButton value={rootPath} label={t.copyPath} icon /></div> : <p className="workflow-note">{t.rootUnavailable}</p>}+ <p className="agent-instruction">{t.agentInstruction.replace('AGENT', agent)}</p>+ {rootPath ? <div className="agent-path"><code className="root-path" title={displayRootPath}>{displayRootPath ?? t.rootUnavailable}</code><CopyButton value={rootPath} label={t.copyPath} icon /></div> : <p className="workflow-note">{t.rootUnavailable}</p>}+ {!newProject && <><div className="agent-recipient" role="group" aria-label={t.agentRecipient}>+ {(['codex', 'claude'] as const).map(value => <button key={value} type="button" aria-pressed={recipient === value} onClick={() => { setRecipient(value); savePreference('mesh-avatar-agent-recipient', value); }}>{value === 'codex' ? 'Codex' : 'Claude Code'}</button>)}+ </div>{recipient === 'codex' && <p className="agent-disclosure">{t.agentDisclosure}</p>}</>}<textarea aria-label={t.copyPrompt} readOnly value={prompt} rows={4} /><CopyButton value={prompt} label={t.copyPrompt} /></section>;diff --git a/src/editor/EditorCanvas.tsx b/src/editor/EditorCanvas.tsxindex 96cff59..5c0c836 100644--- a/src/editor/EditorCanvas.tsx+++ b/src/editor/EditorCanvas.tsx@@ -3,6 +3,8 @@ import type { Point, Rig } from '../rig/types';import { buildOverlay, changeVertex, imagePoint, moveHandle, nearestEdge, nearestHandle, screen, type Handle, type Viewport } from './model';import { useI18n, type PartGroup } from './i18n';import { PART_COLORS } from './parts';+import { readPreference, savePreference } from './preferences';+import { coarseWheel, fitBounds, inputFocused, partBounds, zoomAt } from './viewport';interface Props {rig: Rig;@@ -13,20 +15,27 @@ interface Props {onChange: (rig: Rig) => void;onBegin?: () => void;onEnd?: () => void;+ focusRequest?: { group: string; id: number };}-export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChange, onBegin, onEnd }: Props) {+export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChange, onBegin, onEnd, focusRequest }: Props) {const { t, title } = useI18n();const canvas = useRef<HTMLCanvasElement>(null);const source = useRef<HTMLImageElement | null>(null);const [imageReady, setImageReady] = useState(false);- const [size, setSize] = useState({ width: 600, height: 600 });+ const [size, setSize] = useState({ width: 0, height: 0 });const [view, setView] = useState<Viewport>({ scale: 1, x: 0, y: 0 });- const [zoom, setZoom] = useState(1);- const [pan, setPan] = useState<Point>([0, 0]);+ const viewRef = useRef(view);+ const setViewport = (value: Viewport | ((current: Viewport) => Viewport)) => {+ viewRef.current = typeof value === 'function' ? value(viewRef.current) : value;+ setView(viewRef.current);+ };+ const [wheelMode, setWheelMode] = useState(() => readPreference('mesh-avatar-wheel-mode') === 'pan' ? 'pan' : 'auto');+ const measured = useRef({ width: 0, height: 0, source: '' });+ const focused = useRef(0);const space = useRef(false);const [hover, setHover] = useState<{ handle: Handle; point: Point } | null>(null);const [dragging, setDragging] = useState(false);- const drag = useRef<{ handle?: Handle; rig: Rig; start: Point; pan: Point; offset: Point } | null>(null);+ const drag = useRef<{ handle?: Handle; rig: Rig; start: Point; view: Viewport; offset: Point } | null>(null);const overlay = useMemo(() => buildOverlay(rig), [rig]);const handles = overlay.handles.filter(h => visible.includes(h.group));const shapes = overlay.shapes.filter(s => visible.includes(s.group));@@ -35,6 +44,7 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChconst interactiveShapes = shapes.filter(s => !focusGroup || s.group === focusGroup);const hint = !selected ? t.pickHint : interactiveShapes.some(s => s.editable) ? t.lineHint : interactiveHandles.length ? t.dragHint : t.noDots;useEffect(() => {+ setImageReady(false); source.current = null;const image = new Image();image.onload = () => { source.current = image; setImageReady(true); };image.src = sourceUrl;@@ -45,11 +55,69 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChobserver.observe(canvas.current!);return () => { image.onload = null; observer.disconnect(); };}, [sourceUrl]);+ const fitImage = () => setViewport(fitBounds({ x: 0, y: 0, ...rig.image }, size));+ const fitPart = (group: string) => {+ const bounds = partBounds(group, overlay.shapes, overlay.handles);+ if (bounds) setViewport(fitBounds(bounds, size, 28));+ };+ useEffect(() => {+ if (!size.width || !size.height) return;+ const key = `${sourceUrl}:${rig.image.width}:${rig.image.height}`, previous = measured.current;+ if (key !== previous.source) fitImage();+ else setViewport(current => ({ ...current, x: current.x + (size.width - previous.width) / 2, y: current.y + (size.height - previous.height) / 2 }));+ measured.current = { ...size, source: key };+ }, [size, rig.image.width, rig.image.height, sourceUrl]);+ useEffect(() => {+ if (!focusRequest || focusRequest.id === focused.current || !size.width || !size.height) return;+ focused.current = focusRequest.id; fitPart(focusRequest.group);+ }, [focusRequest, overlay, size]);useEffect(() => {- const scale = Math.min(size.width / rig.image.width, size.height / rig.image.height) * zoom;- setView({ scale, x: (size.width - rig.image.width * scale) / 2 + pan[0],- y: (size.height - rig.image.height * scale) / 2 + pan[1] });- }, [size, rig.image.width, rig.image.height, zoom, pan]);+ const element = canvas.current!;+ const point = (event: { clientX: number; clientY: number }): Point => {+ const rect = element.getBoundingClientRect();+ return [event.clientX - rect.left, event.clientY - rect.top];+ };+ const wheel = (event: WheelEvent) => {+ if (element.closest('[inert]') || drag.current) return;+ event.preventDefault(); setHover(null);+ if (gesture) return;+ const units = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? size.height : 1;+ if (event.ctrlKey || event.metaKey || (wheelMode === 'auto' && coarseWheel(event))) {+ setViewport(current => zoomAt(current, current.scale * Math.exp(-event.deltaY * units * 0.001), point(event)));+ } else setViewport(current => ({ ...current, x: current.x - event.deltaX * units, y: current.y - event.deltaY * units }));+ };+ type Gesture = Event & { scale: number; clientX: number; clientY: number };+ let gesture: { view: Viewport; point: Point; scale: number } | null = null;+ const start = (raw: Event) => {+ if (element.closest('[inert]') || drag.current) return;+ raw.preventDefault(); setHover(null); const event = raw as Gesture;+ const anchor = point(event);+ gesture = { view: { ...viewRef.current }, point: anchor.every(Number.isFinite) && anchor[0] >= 0 && anchor[0] <= size.width && anchor[1] >= 0 && anchor[1] <= size.height ? anchor : [size.width / 2, size.height / 2], scale: event.scale > 0 ? event.scale : 1 };+ };+ const change = (raw: Event) => {+ if (!gesture) return;+ raw.preventDefault(); const event = raw as Gesture;+ if (Number.isFinite(event.scale) && event.scale > 0) setViewport(zoomAt(gesture.view, gesture.view.scale * event.scale / gesture.scale, gesture.point));+ };+ const end = (event: Event) => { if (gesture) event.preventDefault(); gesture = null; };+ element.addEventListener('wheel', wheel, { passive: false });+ element.addEventListener('gesturestart', start, { passive: false });+ element.addEventListener('gesturechange', change, { passive: false });+ element.addEventListener('gestureend', end, { passive: false });+ return () => { element.removeEventListener('wheel', wheel); element.removeEventListener('gesturestart', start); element.removeEventListener('gesturechange', change); element.removeEventListener('gestureend', end); };+ }, [size, wheelMode]);+ useEffect(() => {+ const keyboard = (event: KeyboardEvent) => {+ if (!(event.ctrlKey || event.metaKey) || inputFocused(event.target) || canvas.current?.closest('[inert]')) return;+ const key = event.key;+ if (!['+', '=', '-', '0', '1'].includes(key)) return;+ event.preventDefault(); setHover(null);+ if (key === '0') fitImage();+ else setViewport(current => zoomAt(current, key === '1' ? 1 : current.scale * (key === '-' ? 0.8 : 1.25), [size.width / 2, size.height / 2]));+ };+ window.addEventListener('keydown', keyboard);+ return () => window.removeEventListener('keydown', keyboard);+ }, [size, rig.image.width, rig.image.height]);useEffect(() => {const element = canvas.current!;element.width = Math.round(size.width);@@ -107,37 +175,31 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChdata-focus-group={focusGroup} data-visible-groups={visible.join(',')}data-dimmed-groups={focusGroup ? visible.filter(g => g !== focusGroup).join(',') : ''}data-inactive-opacity={focusGroup ? '0.2' : '0.6'}- style={{ cursor: dragging ? 'grabbing' : hover ? 'grab' : 'default' }}+ style={{ cursor: dragging ? 'grabbing' : 'grab' }}onKeyDown={event => { if (event.code === 'Space') { event.preventDefault(); space.current = true; } }}onKeyUp={event => { if (event.code === 'Space') space.current = false; }}onBlur={() => { space.current = false; }}onContextMenu={event => event.preventDefault()}- onWheel={event => {- event.preventDefault();- const point = local(event), ratio = Math.exp(-event.deltaY * 0.001);- const nextZoom = Math.min(8, Math.max(0.25, zoom * ratio));- const effective = nextZoom / zoom;- setZoom(nextZoom);- setPan([pan[0] + (point[0] - size.width / 2 - pan[0]) * (1 - effective),- pan[1] + (point[1] - size.height / 2 - pan[1]) * (1 - effective)]);- }}onPointerDown={event => {event.preventDefault();event.currentTarget.focus();const point = local(event);if (event.button === 1 || space.current) {- drag.current = { rig, start: point, pan, offset: [0, 0] };+ drag.current = { rig, start: point, view: { ...viewRef.current }, offset: [0, 0] };} else if (event.button === 0) {const handle = nearestHandle(interactiveHandles, point, view);- if (!handle) return;- onSelect(handle.item);- if (event.altKey && handle.vertex) {- onChange(changeVertex(rig, handle.vertex.path, handle.vertex.index, null, handle.vertex.closed));- return;+ if (!handle) {+ drag.current = { rig, start: point, view: { ...viewRef.current }, offset: [0, 0] };+ } else {+ onSelect(handle.item);+ if (event.altKey && handle.vertex) {+ onChange(changeVertex(rig, handle.vertex.path, handle.vertex.index, null, handle.vertex.closed));+ return;+ }+ const origin = imagePoint(point, view);+ drag.current = { handle, rig, start: point, view: { ...viewRef.current }, offset: [handle.point[0] - origin[0], handle.point[1] - origin[1]] };+ onBegin?.();}- const origin = imagePoint(point, view);- drag.current = { handle, rig, start: point, pan, offset: [handle.point[0] - origin[0], handle.point[1] - origin[1]] };- onBegin?.();} else return;setHover(null);setDragging(true);@@ -150,7 +212,7 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onChreturn;}const point = local(event), current = drag.current;- if (!current.handle) setPan([current.pan[0] + point[0] - current.start[0], current.pan[1] + point[1] - current.start[1]]);+ if (!current.handle) setViewport({ ...current.view, x: current.view.x + point[0] - current.start[0], y: current.view.y + point[1] - current.start[1] });else {const target = imagePoint(point, view);onChange(moveHandle(current.rig, current.handle, [target[0] + current.offset[0], target[1] + current.offset[1]]));@@ -171,8 +233,15 @@ export function EditorCanvas({ rig, sourceUrl, visible, selected, onSelect, onCh</div><div className="canvas-help"><span className="context-hint">{hint}</span>- <div className="zoom-tools"><span title={t.zoom}>{Math.round(zoom * 100)}%</span><button title={t.panHint} onClick={() => { setZoom(1); setPan([0, 0]); }}>{t.fit}</button></div>+ <div className="zoom-tools" role="group" aria-label={t.zoom}>+ <button disabled={view.scale <= 0.1} aria-label={t.zoomOut} title={t.zoomOut} onClick={() => setViewport(current => zoomAt(current, current.scale * 0.8, [size.width / 2, size.height / 2]))}>−</button>+ <button className="zoom-value" data-testid="zoom-value" title={t.actualSize} aria-label={t.actualSize} onClick={() => setViewport(current => zoomAt(current, 1, [size.width / 2, size.height / 2]))}>{Math.round(view.scale * 100)}%</button>+ <button disabled={view.scale >= 16} aria-label={t.zoomIn} title={t.zoomIn} onClick={() => setViewport(current => zoomAt(current, current.scale * 1.25, [size.width / 2, size.height / 2]))}>+</button>+ <button title={t.panHint} onClick={fitImage}>{t.fit}</button>+ <button disabled={!focusGroup || !partBounds(focusGroup, overlay.shapes, overlay.handles)} onClick={() => fitPart(focusGroup)}>{t.fitPart}</button>+ </div></div>+ <label className="wheel-setting">{t.wheelMode}<select aria-label={t.wheelMode} value={wheelMode} onChange={event => { setWheelMode(event.target.value); savePreference('mesh-avatar-wheel-mode', event.target.value); }}><option value="auto">{t.wheelAuto}</option><option value="pan">{t.wheelPan}</option></select></label></div>);}diff --git a/src/editor/Guide.tsx b/src/editor/Guide.tsxindex 99b5533..153a548 100644--- a/src/editor/Guide.tsx+++ b/src/editor/Guide.tsx@@ -17,7 +17,7 @@ export function Help({ onClose, onGuide }: { onClose: () => void; onGuide: () =><div className="panel-title"><h2>{t.help}</h2><button autoFocus className="icon-button" aria-label={t.close} onClick={onClose}><Icon name="close" /></button></div><div className="help-body"><GuideSteps /><h3>{t.shortcuts}</h3><dl>{[[t.shortcutUndo, '⌘Z / ⇧⌘Z'], [t.shortcutSave, '⌘S'], [t.shortcutPan, t.spaceDrag],- [t.shortcutZoom, t.wheel], [t.shortcutVertex, t.vertexKeys]].map(([label, keys]) =>+ [t.shortcutZoom, `${t.wheel} · ⌘+/⌘−/⌘0/⌘1`], [t.shortcutVertex, t.vertexKeys]].map(([label, keys]) =><div key={label}><dt>{label}</dt><dd>{keys}</dd></div>)}</dl><button onClick={onGuide}>{t.guideAgain}</button></div></section>;diff --git a/src/editor/PartList.tsx b/src/editor/PartList.tsxindex e284321..8390d5b 100644--- a/src/editor/PartList.tsx+++ b/src/editor/PartList.tsx@@ -2,8 +2,8 @@ import type { Rig } from '../rig/types';import { useI18n, type PartGroup } from './i18n';import { PART_COLORS, partPresent, SECTIONS } from './parts';import { Icon } from './Icon';-export function PartList({ rig, visible, selected, onSelect, onVisible }: {- rig: Rig; visible: string[]; selected: string | null; onSelect: (group: string) => void; onVisible: (groups: string[]) => void;+export function PartList({ rig, visible, selected, onSelect, onFocus, onVisible }: {+ rig: Rig; visible: string[]; selected: string | null; onSelect: (group: string) => void; onFocus: (group: string) => void; onVisible: (groups: string[]) => void;}) {const { t, parts } = useI18n();const section = (groups: readonly PartGroup[]) => {@@ -20,7 +20,7 @@ export function PartList({ rig, visible, selected, onSelect, onVisible }: {return <div key={group} className={`part-row ${selected?.split('.')[0] === group ? 'is-selected' : ''} ${present ? '' : 'is-absent'}`}data-part={group} data-visible={shown}><button className="part-select" data-testid={`part-${group}`} disabled={!present}- aria-pressed={selected?.split('.')[0] === group} onClick={() => onSelect(group)}>+ aria-pressed={selected?.split('.')[0] === group} onClick={() => onSelect(group)} onDoubleClick={() => onFocus(group)}><span className="part-swatch" style={{ background: PART_COLORS[group] }} /><span><strong>{parts[group][0]}</strong><small title={present ? parts[group][1] : t.notPresent}>{present ? parts[group][1] : t.notPresent}</small></span></button>diff --git a/src/editor/VariantsPanel.tsx b/src/editor/VariantsPanel.tsxindex 849eaf6..44eec50 100644--- a/src/editor/VariantsPanel.tsx+++ b/src/editor/VariantsPanel.tsx@@ -6,8 +6,8 @@ import { JobFeedback } from './JobFeedback';import { CopyButton } from './CopyButton';const labels = ['eyesClosed', 'eyesHalf', 'eyesSmile', 'mouthA', 'mouthAHalf', 'mouthI', 'mouthO'] as const;-export function VariantsPanel({ project, projectPath, assets, rootPath, busy, stale, onRun, mouthRequest, onMouthPresence }: {- project: LocalProject | null; projectPath?: string; assets?: Record<string, string>; rootPath?: string; busy: boolean; stale: boolean;+export function VariantsPanel({ project, projectPath, assets, rootPath, displayRootPath, busy, stale, onRun, mouthRequest, onMouthPresence }: {+ project: LocalProject | null; projectPath?: string; assets?: Record<string, string>; rootPath?: string; displayRootPath?: string; busy: boolean; stale: boolean;onRun: (action: ProjectJob, files?: File[]) => Promise<JobResult>; mouthRequest: number; onMouthPresence: (present: boolean) => void;}) {const { t } = useI18n();@@ -58,7 +58,7 @@ export function VariantsPanel({ project, projectPath, assets, rootPath, busy, st<label><input type="checkbox" checked={eyes} onChange={event => setEyes(event.target.checked)} aria-label={t.targetEyes} /><span>{t.targetEyes}<small>{t.eyesKinds}</small></span><span className="variant-count">{count('eyes_', 3)}</span></label><label><input ref={mouthCheckbox} type="checkbox" checked={mouth} onChange={event => setMouth(event.target.checked)} aria-label={t.targetMouth} /><span>{t.targetMouth}<small>{t.mouthKinds}</small></span><span className="variant-count">{count('mouth_', 4)}</span></label></div>- {(eyes || mouth) && projectPath && (projectPath.startsWith('<') ? <p className="workflow-note">{t.agentUnknownPath}</p> : <AskAgent rootPath={rootPath} projectPath={project?.readOnly || projectPath === 'samples/miko-qipao' ? 'projects/miko-qipao-variants' : projectPath} readOnlySource={project?.readOnly || projectPath === 'samples/miko-qipao' ? projectPath : undefined} target={target} />)}+ {(eyes || mouth) && projectPath && (projectPath.startsWith('<') ? <p className="workflow-note">{t.agentUnknownPath}</p> : <AskAgent rootPath={rootPath} displayRootPath={displayRootPath} projectPath={project?.readOnly || projectPath === 'samples/miko-qipao' ? 'projects/miko-qipao-variants' : projectPath} readOnlySource={project?.readOnly || projectPath === 'samples/miko-qipao' ? projectPath : undefined} target={target} />)}<details className="manual-variants"><summary>{t.manualVariants}</summary><p>{t.manualHelp}</p>{writable ? <button disabled={busy || stale} onClick={() => { void run('variant-requests'); }}>{busy ? t.operationBusy : t.createRequests}</button> : <p className="workflow-note">{t.variantsUnavailable}</p>}diff --git a/src/editor/i18n.tsx b/src/editor/i18n.tsxindex 46cd1d5..8644ff7 100644--- a/src/editor/i18n.tsx+++ b/src/editor/i18n.tsx@@ -22,10 +22,10 @@ const en = {help: 'Help', close: 'Close help', language: 'Language', english: 'English', japanese: '日本語', enCode: 'EN', jaCode: 'JA',parts: 'Parts', faceSection: 'Face', hairSection: 'Hair & accessories', bodySection: 'Body', advanced: 'Advanced',notPresent: 'Not in this rig', show: 'Show overlay', hide: 'Hide overlay', showAll: 'Show all', hideAll: 'Hide all',- source: 'Source & rig', canvas: 'Rig editor canvas', fit: 'Fit', zoom: 'Zoom',+ source: 'Source & rig', canvas: 'Rig editor canvas', fit: 'Fit', zoom: 'Zoom', zoomOut: 'Zoom out', zoomIn: 'Zoom in', actualSize: 'Reset to 100%', fitPart: 'Fit selected part', wheelMode: 'Mouse wheel', wheelAuto: 'Zoom', wheelPan: 'Scroll to pan',pickHint: 'Pick a part on the left, or click a dot', dragHint: 'Drag dots to move them',lineHint: 'Drag dots · double-click a line to add a dot · Alt-click a dot to remove it',- panHint: 'Scroll to zoom · Space-drag to pan', noDots: 'Edit the values in the selected part card',+ panHint: 'Pinch to zoom · scroll or drag empty space to pan', noDots: 'Edit the values in the selected part card',preview: 'Live preview', idle: 'Idle motion', play: 'Play idle motion', pause: 'Pause idle motion',pose: 'Pose test', reset: 'Reset', sweep: 'Sweep angles', stopSweep: 'Stop sweep',lipSync: 'Lip sync', release: 'Release', lipText: 'Kana text', lipPlay: 'Play', lipStop: 'Stop',@@ -62,10 +62,10 @@ const ja: typeof en = {help: 'ヘルプ', close: 'ヘルプを閉じる', language: '言語', english: '英語', japanese: '日本語', enCode: '英語', jaCode: '日本語',parts: 'パーツ', faceSection: '顔', hairSection: '髪・飾り', bodySection: '体', advanced: '詳細設定',notPresent: 'この設定にはありません', show: 'ガイドを表示', hide: 'ガイドを非表示', showAll: 'すべて表示', hideAll: 'すべて非表示',- source: '元画像と動く範囲', canvas: '動く範囲の編集キャンバス', fit: '全体表示', zoom: '表示倍率',+ source: '元画像と動く範囲', canvas: '動く範囲の編集キャンバス', fit: '全体表示', zoom: '表示倍率', zoomOut: '縮小', zoomIn: '拡大', actualSize: '100% に戻す', fitPart: '選択中のパーツに合わせる', wheelMode: 'マウスのホイール', wheelAuto: '拡大・縮小', wheelPan: 'スクロールで移動',pickHint: '左のパーツか、画像の点を選んでください', dragHint: '点をドラッグして位置を調整',lineHint: '点をドラッグ · 線をダブルクリックで点を追加 · ⌥+点をクリックで削除',- panHint: 'スクロールで拡大・縮小 · スペース+ドラッグで移動', noDots: '右の選択パーツ欄で数値を調整',+ panHint: 'ピンチで拡大・縮小 · スクロールや余白のドラッグで移動', noDots: '右の選択パーツ欄で数値を調整',preview: '動きのプレビュー', idle: '待機中の動き', play: '待機中の動きを再生', pause: '待機中の動きを一時停止',pose: 'ポーズ確認', reset: 'リセット', sweep: '角度を連続確認', stopSweep: '連続確認を停止',lipSync: '口の動き', release: '解除', lipText: 'かなの文章', lipPlay: '再生', lipStop: '停止',diff --git a/src/editor/project.ts b/src/editor/project.tsindex eab3ac9..059a227 100644--- a/src/editor/project.ts+++ b/src/editor/project.ts@@ -36,6 +36,7 @@ export interface LocalProject {name: string;relativePath: string;absolutePath: string;+ displayPath?: string;updatedAt: string;hasSprites: boolean;hasVariants: boolean;@@ -52,7 +53,7 @@ export async function localProjects(): Promise<LocalProject[] | null> {} catch { return null; }}const baseUrl = (project: LocalProject) => `/__studio/projects/${encodeURIComponent(project.name)}/`;-export async function repositoryContext(): Promise<{ rootPath: string } | null> {+export async function repositoryContext(): Promise<{ rootPath: string; displayRootPath: string } | null> {if (!import.meta.env.DEV) return null;try { const response = await fetch('/__studio/context'); return response.ok && response.headers.get('content-type')?.includes('application/json') ? await response.json() : null; } catch { return null; }}diff --git a/src/editor/style.css b/src/editor/style.cssindex 62cefc3..3c2b484 100644--- a/src/editor/style.css+++ b/src/editor/style.css@@ -88,7 +88,7 @@ main:has(.project-location):has(.stale) .editor-panel { height: calc(100dvh - 21.editor-canvas { display: block; width: 100%; height: 100%; touch-action: none; outline: none; }.canvas-help { min-height: 56px; display: flex; gap: 8px; align-items: center; padding: 8px 12px; border-top: 1px solid var(--line); color: var(--muted); font-size: 12px; }.context-hint { flex: 1; line-height: 1.5; }-.zoom-tools { display: flex; gap: 8px; align-items: center; flex-shrink: 0; }+.zoom-tools { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px; align-items: center; flex-shrink: 0; }.zoom-tools button { padding: 5px 8px; font-size: 12px; }.handle-tooltip { position: absolute; z-index: 2; pointer-events: none; max-width: 210px; background: var(--ink); color: white; padding: 6px 8px; border-radius: 6px; font-size: 12px; box-shadow: 0 2px 8px #0002; }.right-column { display: flex; flex-direction: column; gap: 12px; min-height: 0; }@@ -224,3 +224,12 @@ main:has(.stale) .editor-panel, main:has(.stale) .parts-panel { height: calc(100.right-column { grid-column: 1; grid-template-columns: 1fr; }.inspector { max-height: 500px; }}++.zoom-value { min-width: 60px; }+.wheel-setting { display: flex; gap: 8px; align-items: center; justify-content: flex-end; font-size: 11px; color: var(--muted); padding: 4px 12px 8px; }+.wheel-setting select { border: 1px solid var(--line); border-radius: 6px; padding: 3px; background: white; font-size: 11px; }+.canvas-help { flex-wrap: wrap; }+.agent-recipient { display: flex; gap: 4px; margin-top: 10px; }+.agent-recipient button { font-size: 12px; padding: 5px 8px; }+.agent-recipient button[aria-pressed="true"] { color: var(--accent); background: var(--accent-soft); border-color: #b3cdfa; }+.agent-disclosure { font-size: 11px; color: var(--muted); margin: 6px 0; }diff --git a/src/editor/viewport.ts b/src/editor/viewport.tsnew file mode 100644index 0000000..9d531d2--- /dev/null+++ b/src/editor/viewport.ts@@ -0,0 +1,33 @@+import type { Point } from '../rig/types';+import type { Viewport, Shape, Handle } from './model';++export const MIN_SCALE = 0.1, MAX_SCALE = 16;+export const clampScale = (scale: number) => Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale));+export function zoomAt(view: Viewport, scale: number, point: Point): Viewport {+ const next = clampScale(scale), ratio = next / view.scale;+ return { scale: next, x: point[0] - (point[0] - view.x) * ratio, y: point[1] - (point[1] - view.y) * ratio };+}+export function fitBounds(bounds: { x: number; y: number; width: number; height: number }, size: { width: number; height: number }, padding = 16): Viewport {+ const scale = clampScale(Math.min(Math.max(1, size.width - padding * 2) / Math.max(1, bounds.width), Math.max(1, size.height - padding * 2) / Math.max(1, bounds.height)));+ return { scale, x: size.width / 2 - (bounds.x + bounds.width / 2) * scale, y: size.height / 2 - (bounds.y + bounds.height / 2) * scale };+}+export function partBounds(group: string, shapes: Shape[], handles: Handle[]) {+ const bands = new Set(shapes.filter(shape => shape.band).map(shape => shape.item));+ const points: Point[] = handles.filter(handle => handle.group === group && !bands.has(handle.item)).map(handle => handle.point);+ for (const shape of shapes.filter(shape => shape.group === group && !shape.band)) {+ if (shape.kind === 'ellipse') {+ const [rx, ry] = shape.radius!, angle = shape.angle ?? 0, [cx, cy] = shape.points[0];+ const dx = Math.hypot(rx * Math.cos(angle), ry * Math.sin(angle)), dy = Math.hypot(rx * Math.sin(angle), ry * Math.cos(angle));+ points.push([cx - dx, cy - dy], [cx + dx, cy + dy]);+ } else points.push(...shape.points);+ }+ if (!points.length) return null;+ const xs = points.map(point => point[0]), ys = points.map(point => point[1]);+ return { x: Math.min(...xs), y: Math.min(...ys), width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys) };+}+export function coarseWheel(event: Pick<WheelEvent, 'deltaMode' | 'deltaX' | 'deltaY'>) {+ return event.deltaMode !== 0 || (event.deltaX === 0 && Number.isInteger(event.deltaY) && Math.abs(event.deltaY) >= 80);+}+export function inputFocused(target: EventTarget | null) {+ return target instanceof HTMLElement && (!!target.closest('input, textarea, select') || target.isContentEditable);+}diff --git a/src/editor/workflow-i18n.ts b/src/editor/workflow-i18n.tsindex 409639e..043344a 100644--- a/src/editor/workflow-i18n.ts+++ b/src/editor/workflow-i18n.ts@@ -1,12 +1,14 @@export const workflowEn = {- agentInstruction: 'Open Codex in this repository folder and paste the following message.',+ agentInstruction: 'Open AGENT in this repository folder and paste the following message.',variantsReloaded: 'Drawn variants loaded.', mouthFallback: 'No drawn mouth images; using mesh deformation.', drawMouth: '→ Draw mouth variants',eyesKinds: 'Closed, half-closed, smiling', mouthKinds: 'あ, half-open あ, い, お', variantCount: 'COUNT of TOTAL images',askAgent: 'Ask your agent',copyPrompt: 'Copy message', copyDone: 'Copied', rootUnavailable: 'Open the folder containing this app and docs/agent-guide.md. Start the development server to copy its full path here.',newIllustration: 'Create from a new illustration',agentNewPrompt: 'Using the illustration I provide, create a project at PROJECT following docs/agent-guide.md Steps 1–5. Start with its model check and coordinate calibration, build the layers, and visually review the poses. Keep all image files inside this repository. If that folder already exists, use a new unused name. Tell me when it is ready to open from the app’s project menu.',- agentVariantPrompt: 'Create TARGET drawn variants for PROJECT following docs/agent-guide.md Step 6. Prepare the local masks and prompts, ask me before sending images to an external generator, import the returned drawings with build-sprites, and review the poses in Step 5. Keep all files inside this repository.',+ agentRecipient: 'Request recipient', agentDisclosure: 'Images will be sent to Codex image generation.',+ agentCodexPrompt: 'Create TARGET drawn variants for PROJECT following docs/agent-guide.md Step 6. Use Codex’s built-in image generation (imagegen): prepare masks with variant-requests, generate the requested drawings from source.png and each mask, save the full-size PNGs in variants/, import them with build-sprites, and visually review render-poses (Step 5). The user has already consented to Codex image generation. Do not use other external services. Keep all files inside this repository.',+ agentClaudePrompt: 'Prepare TARGET drawn variant requests for PROJECT following docs/agent-guide.md Step 6. Run variant-requests to prepare the masks and prompts. Claude Code cannot generate images: tell me exactly which source.png, masks and prompts to give to Codex or another image generator and which full-size PNG filenames to save in variants/, then stop. Do not generate or send images, or run build-sprites yet. Keep all files inside this repository.',agentCopySample: 'First copy the read-only project at SOURCE into PROJECT; if the destination exists, use an unused name. Keep the original project unchanged. ',agentUnknownPath: 'The browser cannot read this folder’s full path. Open it from the development server’s project list to prepare an exact request.',agentEyes: 'eye', agentMouth: 'mouth', agentBoth: 'eye and mouth',@@ -27,14 +29,16 @@ export const workflowEn = {variantsNeedRebuild: 'Rebuild the changed outlines first, so the masks match the current layers.',};export const workflowJa: typeof workflowEn = {- agentInstruction: 'このリポジトリのフォルダで Codex を開いて、次の文章を貼ってください。',+ agentInstruction: 'このリポジトリのフォルダで AGENT を開いて、次の文章を貼ってください。',variantsReloaded: '描き分け画像を読み込みました', mouthFallback: '描き分け画像がないため、メッシュの変形で代用しています', drawMouth: '→ 口を描き分ける',eyesKinds: '閉じた目・半目・笑った目', mouthKinds: 'あ・半分のあ・い・お', variantCount: 'TOTAL枚中COUNT枚',askAgent: 'エージェントに依頼',copyPrompt: '依頼文をコピー', copyDone: 'コピーしました', rootUnavailable: 'このアプリと docs/agent-guide.md があるフォルダで開いてください。開発サーバーを起動すると、ここでフルパスをコピーできます。',newIllustration: '新しいイラストから作る',agentNewPrompt: '私が渡すイラストから、docs/agent-guide.md の Step 1〜5 に沿って PROJECT にプロジェクトを作ってください。最初にモデルの確認と座標読取りの校正を行い、レイヤーを作成して、ポーズを目視で確認してください。画像と生成物はすべてこのリポジトリ内に保存してください。作成先がすでに存在する場合は、未使用の名前を選んでください。アプリのプロジェクト一覧から開ける状態になったら知らせてください。',- agentVariantPrompt: 'PROJECT の TARGETの描き分け画像を、docs/agent-guide.md の Step 6 に沿って作ってください。ローカルでマスクと依頼文を準備し、外部の画像生成サービスへ送る前には私に確認してください。戻ってきた画像を build-sprites で取り込み、Step 5 のポーズ確認を行ってください。ファイルはすべてこのリポジトリ内に保存してください。',+ agentRecipient: '依頼する相手', agentDisclosure: '画像は Codex の画像生成に送られます',+ agentCodexPrompt: 'PROJECT の TARGETの描き分け画像を、docs/agent-guide.md の Step 6 に沿って作ってください。Codex の組み込みの画像生成(imagegen)を使い、variant-requests で用意するマスクと source.png から、指定した描き分けを生成してください。同じ大きさの PNG を variants/ に保存し、build-sprites で取り込み、render-poses で Step 5 のポーズを目視確認するところまで行ってください。ユーザーは Codex の画像生成の利用に同意済みです。ほかの外部サービスは使わないでください。ファイルはすべてこのリポジトリ内に保存してください。',+ agentClaudePrompt: 'PROJECT の TARGETの描き分けについて、docs/agent-guide.md の Step 6 に沿って variant-requests でマスクと依頼文を用意してください。Claude Code は画像を生成できません。source.png と各マスク・依頼文のどのファイルを Codex などの画像生成に渡すか、結果を variants/ のどの PNG 名で保存するかを具体的に案内して、そこで止まってください。画像の生成・送信や build-sprites の実行はまだ行わないでください。ファイルはすべてこのリポジトリ内に保存してください。',agentCopySample: '最初に読み取り専用の SOURCE を PROJECT にコピーしてください。作成先が存在する場合は未使用の名前を選び、元のプロジェクトは変更しないでください。',agentUnknownPath: 'ブラウザで選んだフォルダの実際の場所は取得できません。正しい場所を含む依頼文を作るには、開発サーバーのプロジェクト一覧から開いてください。',agentEyes: '目', agentMouth: '口', agentBoth: '目と口',diff --git a/src/server/local-projects.ts b/src/server/local-projects.tsindex 2b2dcc4..3810251 100644--- a/src/server/local-projects.ts+++ b/src/server/local-projects.ts@@ -1,5 +1,6 @@import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';+import { homedir } from 'node:os';import { readFile, readdir, realpath, stat, writeFile, rename, unlink } from 'node:fs/promises';import { resolve, relative, extname, sep } from 'node:path';import type { IncomingMessage, ServerResponse } from 'node:http';@@ -8,6 +9,7 @@ import { validateRig } from '../rig/validate';import { decodeVariants, JobError, projectJob, runTool, variantState, VARIANTS, type Runner } from './project-jobs';const SAMPLE = 'sample-miko-qipao';+const displayPath = (path: string) => path === homedir() ? '~' : path.startsWith(`${homedir()}${sep}`) ? `~${path.slice(homedir().length)}` : path;const safeName = /^[A-Za-z0-9._-]+$/;class HttpError extends Error { constructor(public status: number, message: string) { super(message); } }const inside = (base: string, path: string) => { const rel = relative(base, path); return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !rel.startsWith(sep)); };@@ -69,7 +71,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runnconst draft = resolve(path, 'rig.draft.json');if (!await exists(rigPath) && !(await exists(draft) && await exists(resolve(path, 'built')))) return null;const file = await checked(path, await exists(rigPath) ? rigPath : draft);- return { name, relativePath: relative(root, path).split(sep).join('/'), absolutePath: path,+ return { name, relativePath: relative(root, path).split(sep).join('/'), absolutePath: path, displayPath: displayPath(path),rigFile: await exists(rigPath) ? 'rig.json' : 'rig.draft.json',updatedAt: (await stat(file)).mtime.toISOString(), hasSprites: await exists(resolve(path, 'built/sprites/sprites.json')),hasVariants: await exists(resolve(path, 'variants')), readOnly: name === SAMPLE };@@ -88,7 +90,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runnif (!safeName.test(value) || value === '.' || value === '..') throw new HttpError(400, 'Invalid path segment.');return value;});- if (parts.length === 1 && parts[0] === 'context' && req.method === 'GET') { json(200, { rootPath: root }); return; }+ if (parts.length === 1 && parts[0] === 'context' && req.method === 'GET') { json(200, { rootPath: root, displayRootPath: displayPath(root) }); return; }if (parts.length === 1 && parts[0] === 'reveal' && req.method === 'POST') { await reveal(root); json(200, { path: root }); return; }if (parts[0] !== 'projects') throw new HttpError(404, 'Not found.');if (parts.length === 1 && req.method === 'GET') {diff --git a/src/server/project-jobs.ts b/src/server/project-jobs.tsindex 27ed593..4b5efa2 100644--- a/src/server/project-jobs.ts+++ b/src/server/project-jobs.ts@@ -1,3 +1,4 @@+import { homedir } from 'node:os';import { execFile } from 'node:child_process';import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';import { join, resolve, relative, dirname } from 'node:path';@@ -11,7 +12,7 @@ export type Runner = (root: string, project: string, tool: Tool) => Promise<striexport const runTool: Runner = (root, project, tool) => new Promise((done, reject) => {const args = ['run', '--no-project', '--no-python-downloads', '--python', '>=3.10', '--with', 'numpy', '--with', 'pillow', '--with', 'opencv-python-headless', resolve(root, `tools/${tool}.py`), project];execFile('uv', args, { cwd: root, timeout: 120_000, maxBuffer: 2 * 1024 * 1024 }, (error, stdout, stderr) => {- const log = `${stdout}\n${stderr}`.replaceAll(root, '<repo>').trim().slice(-12000);+ const log = `${stdout}\n${stderr}`.replaceAll(root, '<repo>').replaceAll(homedir(), '~').trim().slice(-12000);if (!error) { done(log); return; }const missing = (error as NodeJS.ErrnoException).code === 'ENOENT' || /No interpreter found|No Python installation|Python interpreter not found/i.test(log);reject(new JobError(missing ? 'dependencies' : 'toolFailed', log || (missing ? 'uv is not installed.' : 'The local tool did not finish.')));diff --git a/tests/local-projects.test.ts b/tests/local-projects.test.tsindex 9169348..2f70c48 100644--- a/tests/local-projects.test.ts+++ b/tests/local-projects.test.ts@@ -1,5 +1,6 @@import { beforeEach, afterEach, expect, test, vi } from 'vitest';import { mkdtemp, mkdir, writeFile, readFile, rm, symlink } from 'node:fs/promises';+import { homedir } from 'node:os';import { resolve, join } from 'node:path';import { Readable } from 'node:stream';import type { IncomingMessage, ServerResponse } from 'node:http';@@ -41,8 +42,9 @@ test('lists eligible projects and the read-only installed sample, and serves proconst response = await call('/__studio/projects'); expect(response.status).toBe(200);const list = JSON.parse(response.body);expect(list.map((item: { name: string }) => item.name).sort()).toEqual(['draft', 'nova', 'sample-miko-qipao']);- expect(list.find((item: { name: string }) => item.name === 'nova')).toMatchObject({ relativePath: 'projects/nova', absolutePath: resolve(root, 'projects/nova'), hasSprites: true, hasVariants: true, readOnly: false });+ expect(list.find((item: { name: string }) => item.name === 'nova')).toMatchObject({ relativePath: 'projects/nova', absolutePath: resolve(root, 'projects/nova'), displayPath: resolve(root, 'projects/nova').replace(homedir(), '~'), hasSprites: true, hasVariants: true, readOnly: false });expect(list.find((item: { name: string }) => item.name === 'sample-miko-qipao').readOnly).toBe(true);+ expect(JSON.parse((await call('/__studio/context')).body)).toEqual({ rootPath: root, displayRootPath: root.replace(homedir(), '~') });const image = await call('/__studio/projects/nova/built/base.png');expect(image.status).toBe(200); expect(image.body).toBe('synthetic base bytes'); expect(image.headers['Content-Type']).toBe('image/png');expect((await call('/__studio/projects/nova/rig.json.bak')).status).toBe(404);diff --git a/tests/viewport.test.ts b/tests/viewport.test.tsnew file mode 100644index 0000000..ebced4b--- /dev/null+++ b/tests/viewport.test.ts@@ -0,0 +1,32 @@+import { test, expect } from 'vitest';+import fixture from '../samples/miko-qipao/rig.json';+import { buildOverlay, imagePoint, nearestHandle, screen } from '../src/editor/model';+import { parseRig } from '../src/rig/validate';+import { zoomAt, fitBounds, partBounds } from '../src/editor/viewport';++test('zoom keeps the image coordinate under the cursor even at both scale limits', () => {+ const view = { scale: 0.6, x: -100, y: 45 }, cursor: [number, number] = [190, 235];+ const origin = imagePoint(cursor, view);+ for (const scale of [0.001, 0.5, 2, 100]) {+ const next = zoomAt(view, scale, cursor);+ expect(next.scale).toBeGreaterThanOrEqual(0.1); expect(next.scale).toBeLessThanOrEqual(16);+ expect(imagePoint(cursor, next)[0]).toBeCloseTo(origin[0], 10);+ expect(imagePoint(cursor, next)[1]).toBeCloseTo(origin[1], 10);+ }+});+test('part fitting includes rotated ellipses and excludes bands across the entire image', () => {+ const bounds = partBounds('head', [{ item: 'head', group: 'head', kind: 'ellipse', points: [[100, 100]], radius: [40, 10], angle: Math.PI / 4 }, { item: 'head.weightBand', group: 'head', kind: 'line', band: true, points: [[0, 0], [2000, 0]] }], []);+ expect(bounds!.width).toBeCloseTo(Math.sqrt(850) * 2); expect(bounds!.height).toBeCloseTo(Math.sqrt(850) * 2);+ const size = { width: 700, height: 500 }, view = fitBounds(bounds!, size, 28);+ const low = screen([bounds!.x, bounds!.y], view), high = screen([bounds!.x + bounds!.width, bounds!.y + bounds!.height], view);+ expect(low[0]).toBeGreaterThanOrEqual(28); expect(low[1]).toBeCloseTo(28);+ expect(high[0]).toBeLessThanOrEqual(672); expect(high[1]).toBeCloseTo(472);+});+test('handle hit distance stays eight CSS pixels across the supported zoom range', () => {+ const handles = buildOverlay(parseRig(fixture)).handles.filter(handle => handle.id === 'head.center');+ for (const scale of [0.1, 1, 16]) {+ const view = { scale, x: 40, y: -90 }, center = screen(handles[0].point, view);+ expect(nearestHandle(handles, [center[0] + 7, center[1]], view)?.id).toBe('head.center');+ expect(nearestHandle(handles, [center[0] + 9, center[1]], view)).toBeUndefined();+ }+});