A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import { act, useRef } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { BrushSettings, DocumentTab, LayerItem } from '../../types/editor';
import {
documentStoreActions,
uiStoreActions,
useDocumentStore,
useToolStore,
useUpdaterStore,
} from '../../stores';
import { INTERFACE_SCALE_APPLIED_EVENT } from '../interfaceScale';
const mockBridge = vi.hoisted(() => ({
nativeActive: true,
setNativeViewport: vi.fn(async () => {}),
setNativeOccludedRects: vi.fn(async () => {}),
setNativePolicy: vi.fn(async () => {}),
setNativeCamera: vi.fn(async () => {}),
setNativeDocument: vi.fn(async () => {}),
setNativeAppearance: vi.fn(async () => {}),
setNativeCursor: vi.fn(async () => {}),
setNativeMaskMode: vi.fn(async () => {}),
setNativeRulers: vi.fn(async () => {}),
setNativePressureCurve: vi.fn(async () => {}),
syncNativeFullBrushConfig: vi.fn(async () => {}),
requestNativeThumbnails: vi.fn(async () => {}),
nativeUndo: vi.fn(async (docId: string) => ({
doc: {
id: docId,
dimensions: { width: 1024, height: 1024, dpi: 300 },
layers: [],
activeLayerId: 'layer-1',
history: {
items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 1, timeFormatted: '00:00', thumbnailUrl: '' }],
currentIndex: -1,
canUndo: false,
canRedo: true,
},
},
layersChanged: false,
dimensionsChanged: false,
changedLayerIds: ['layer-1'],
})),
nativeRedo: vi.fn(async (docId: string) => ({
doc: {
id: docId,
dimensions: { width: 1024, height: 1024, dpi: 300 },
layers: [],
activeLayerId: 'layer-1',
history: {
items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 1, timeFormatted: '00:00', thumbnailUrl: '' }],
currentIndex: 0,
canUndo: true,
canRedo: false,
},
},
layersChanged: false,
dimensionsChanged: false,
changedLayerIds: ['layer-1'],
})),
viewportInvalidatedListeners: new Set<() => void>(),
strokeCommittedListeners: new Set<(ev: any) => void>(),
historyListeners: new Set<(ev: any) => void>(),
cameraListeners: new Set<(ev: any) => void>(),
}));
vi.mock('../nativeEngineBridge', async (importOriginal) => {
const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
return {
...actual,
isNativeCanvasActive: () => mockBridge.nativeActive,
initNativeEngineBridge: async () => mockBridge.nativeActive,
getNativeDiagnostics: async () => null,
canNativeEngineHandleBrush: () => true,
setNativeViewport: (...args: any[]) => (mockBridge.setNativeViewport as any)(...args),
setNativeOccludedRects: (...args: any[]) => (mockBridge.setNativeOccludedRects as any)(...args),
setNativePolicy: (...args: any[]) => (mockBridge.setNativePolicy as any)(...args),
setNativeCamera: (...args: any[]) => (mockBridge.setNativeCamera as any)(...args),
setNativeDocument: (...args: any[]) => (mockBridge.setNativeDocument as any)(...args),
setNativeAppearance: (...args: any[]) => (mockBridge.setNativeAppearance as any)(...args),
setNativeCursor: (...args: any[]) => (mockBridge.setNativeCursor as any)(...args),
setNativeMaskMode: (...args: any[]) => (mockBridge.setNativeMaskMode as any)(...args),
setNativeRulers: (...args: any[]) => (mockBridge.setNativeRulers as any)(...args),
setNativePressureCurve: (...args: any[]) => (mockBridge.setNativePressureCurve as any)(...args),
syncNativeFullBrushConfig: (...args: any[]) =>
(mockBridge.syncNativeFullBrushConfig as any)(...args),
requestNativeThumbnails: (...args: any[]) =>
(mockBridge.requestNativeThumbnails as any)(...args),
nativeGetHistory: async () => null,
nativeUndo: (...args: any[]) => (mockBridge.nativeUndo as any)(...args),
nativeRedo: (...args: any[]) => (mockBridge.nativeRedo as any)(...args),
subscribeNativeCanvasActive: () => () => {},
subscribeNativeCamera: (cb: (ev: any) => void) => {
mockBridge.cameraListeners.add(cb);
return () => mockBridge.cameraListeners.delete(cb);
},
subscribeNativeDiagnostics: () => () => {},
subscribeNativePointerStat: () => () => {},
subscribeNativeViewportInvalidated: (cb: () => void) => {
mockBridge.viewportInvalidatedListeners.add(cb);
return () => mockBridge.viewportInvalidatedListeners.delete(cb);
},
subscribeNativeStrokeCommitted: (cb: (ev: any) => void) => {
mockBridge.strokeCommittedListeners.add(cb);
return () => mockBridge.strokeCommittedListeners.delete(cb);
},
subscribeNativeHistory: (cb: (ev: any) => void) => {
mockBridge.historyListeners.add(cb);
return () => mockBridge.historyListeners.delete(cb);
},
};
});
import {
computePhysicalPixelRect,
useNativeEngineViewport,
} from '../../hooks/useNativeEngineViewport';
import {
useDrawingHistory,
UseDrawingHistoryResult,
} from '../../hooks/drawing/useDrawingHistory';
// Minimal DOM harness matching repo Vitest node environment
interface MiniNode {
nodeType: number;
nodeName: string;
parentNode: MiniElement | null;
ownerDocument: MiniDocument;
}
class MiniTextNode implements MiniNode {
public nodeType = 3;
public nodeName = '#text';
public nodeValue: string;
public parentNode: MiniElement | null = null;
public ownerDocument: MiniDocument;
constructor(text: string, ownerDocument: MiniDocument) {
this.nodeValue = text;
this.ownerDocument = ownerDocument;
}
}
class MiniCommentNode implements MiniNode {
public nodeType = 8;
public nodeName = '#comment';
public nodeValue: string;
public parentNode: MiniElement | null = null;
public ownerDocument: MiniDocument;
constructor(text: string, ownerDocument: MiniDocument) {
this.nodeValue = text;
this.ownerDocument = ownerDocument;
}
}
class MiniElement extends EventTarget implements MiniNode {
public nodeType = 1;
public nodeName: string;
public tagName: string;
public namespaceURI = 'http://www.w3.org/1999/xhtml';
public ownerDocument: MiniDocument;
public parentNode: MiniElement | null = null;
public childNodes: MiniNode[] = [];
public style: Record<string, string> = {};
public className = '';
public isContentEditable = false;
public rect = { left: 240, top: 68, right: 1200, bottom: 800, width: 960, height: 732 };
private attrs = new Map<string, string>();
constructor(tag: string, ownerDocument: MiniDocument) {
super();
this.nodeName = tag.toUpperCase();
this.tagName = tag.toUpperCase();
this.ownerDocument = ownerDocument;
}
get firstChild(): MiniNode | null {
return this.childNodes[0] ?? null;
}
appendChild<T extends MiniNode>(child: T): T {
if (child.parentNode) child.parentNode.removeChild(child);
child.parentNode = this;
this.childNodes.push(child);
return child;
}
removeChild<T extends MiniNode>(child: T): T {
const idx = this.childNodes.indexOf(child);
if (idx >= 0) {
this.childNodes.splice(idx, 1);
child.parentNode = null;
}
return child;
}
insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {
if (newNode.parentNode) newNode.parentNode.removeChild(newNode);
newNode.parentNode = this;
if (!refNode) {
this.childNodes.push(newNode);
return newNode;
}
const idx = this.childNodes.indexOf(refNode);
if (idx < 0) this.childNodes.push(newNode);
else this.childNodes.splice(idx, 0, newNode);
return newNode;
}
setAttribute(k: string, v: string) {
this.attrs.set(k, String(v));
}
getAttribute(k: string): string | null {
return this.attrs.get(k) ?? null;
}
removeAttribute(k: string) {
this.attrs.delete(k);
}
hasAttribute(k: string): boolean {
return this.attrs.has(k);
}
getBoundingClientRect() {
return { ...this.rect, x: this.rect.left, y: this.rect.top };
}
}
class MiniDocument extends EventTarget {
public nodeType = 9;
public nodeName = '#document';
public defaultView: any;
public body: MiniElement;
public documentElement: MiniElement;
public activeElement: MiniElement | null = null;
public occluders: MiniElement[] = [];
constructor(win: any) {
super();
this.defaultView = win;
this.documentElement = new MiniElement('html', this);
this.body = new MiniElement('body', this);
this.documentElement.appendChild(this.body);
}
createElement(tag: string) {
return new MiniElement(tag, this);
}
createElementNS(_ns: string, tag: string) {
return new MiniElement(tag, this);
}
createTextNode(text: string) {
return new MiniTextNode(text, this);
}
createComment(text: string) {
return new MiniCommentNode(text, this);
}
querySelectorAll(_selector: string) {
return this.occluders;
}
}
class MiniMutationObserver {
public static instances: MiniMutationObserver[] = [];
private cb: () => void;
constructor(cb: () => void) {
this.cb = cb;
MiniMutationObserver.instances.push(this);
}
observe() {}
disconnect() {}
trigger() {
this.cb();
}
}
function makeDoc(id: string): DocumentTab {
return {
id,
name: 'Untitled',
isDirty: false,
dimensions: { width: 1024, height: 1024, dpi: 300 },
colorMode: 'color',
layers: [
{
id: 'layer-1',
name: 'Layer 1',
type: 'raster',
visible: true,
opacity: 100,
blendMode: 'normal',
locked: false,
alphaLocked: false,
clipped: false,
parentId: null,
},
],
activeLayerId: 'layer-1',
};
}
describe('DirectComposition physical-pixel alignment, occlusion & StrokeCommitted sync', () => {
let prevWindow: any;
let prevDocument: any;
let prevMutationObserver: any;
let prevRaf: any;
let prevCancelRaf: any;
let prevActEnv: any;
let prevHtmlElement: any;
let prevHtmlIFrameElement: any;
let prevElement: any;
let prevNode: any;
let prevGetComputedStyle: any;
let miniWin: any;
let miniDoc: MiniDocument;
let hostEl: MiniElement;
let root: Root | null = null;
let pendingRafs: Map<number, FrameRequestCallback>;
let nextRafId: number;
const flushRaf = () => {
const callbacks = Array.from(pendingRafs.values());
pendingRafs.clear();
for (const cb of callbacks) cb(0);
};
beforeEach(() => {
vi.clearAllMocks();
mockBridge.nativeActive = true;
mockBridge.viewportInvalidatedListeners.clear();
mockBridge.strokeCommittedListeners.clear();
mockBridge.historyListeners.clear();
mockBridge.cameraListeners.clear();
MiniMutationObserver.instances = [];
pendingRafs = new Map();
nextRafId = 1;
prevWindow = (globalThis as any).window;
prevDocument = (globalThis as any).document;
prevMutationObserver = (globalThis as any).MutationObserver;
prevRaf = (globalThis as any).requestAnimationFrame;
prevCancelRaf = (globalThis as any).cancelAnimationFrame;
prevActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT;
prevHtmlElement = (globalThis as any).HTMLElement;
prevHtmlIFrameElement = (globalThis as any).HTMLIFrameElement;
prevElement = (globalThis as any).Element;
prevNode = (globalThis as any).Node;
prevGetComputedStyle = (globalThis as any).getComputedStyle;
const fakeGetComputedStyle = (el: MiniElement) => ({
display: el.style?.display ?? 'block',
visibility: el.style?.visibility ?? 'visible',
pointerEvents: el.style?.pointerEvents ?? 'auto',
opacity: el.style?.opacity ?? '1',
getPropertyValue: () => '#18181b',
});
const FakeIFrame = class HTMLIFrameElement {};
miniWin = Object.assign(new EventTarget(), {
devicePixelRatio: 1.25,
HTMLElement: MiniElement,
HTMLIFrameElement: FakeIFrame,
Element: MiniElement,
Node: MiniElement,
matchMedia: () => ({
matches: true,
addEventListener: () => {},
removeEventListener: () => {},
}),
getComputedStyle: fakeGetComputedStyle,
});
miniDoc = new MiniDocument(miniWin);
miniWin.document = miniDoc;
hostEl = miniDoc.createElement('div');
miniDoc.body.appendChild(hostEl);
(globalThis as any).window = miniWin;
(globalThis as any).document = miniDoc;
(globalThis as any).HTMLElement = MiniElement;
(globalThis as any).HTMLIFrameElement = FakeIFrame;
(globalThis as any).Element = MiniElement;
(globalThis as any).Node = MiniElement;
(globalThis as any).getComputedStyle = fakeGetComputedStyle;
(globalThis as any).MutationObserver = MiniMutationObserver;
(globalThis as any).requestAnimationFrame = (cb: FrameRequestCallback) => {
const id = nextRafId++;
pendingRafs.set(id, cb);
return id;
};
(globalThis as any).cancelAnimationFrame = (id: number) => {
pendingRafs.delete(id);
};
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
uiStoreActions.setAppView('workspace');
uiStoreActions.setBrushStudioModalOpen(false);
useUpdaterStore.setState({ isModalOpen: false });
const doc = makeDoc('doc-sync-1');
documentStoreActions.setDocuments([doc]);
documentStoreActions.setActiveDocumentId(doc.id);
});
afterEach(async () => {
if (root) {
await act(async () => {
root?.unmount();
});
root = null;
}
(globalThis as any).window = prevWindow;
(globalThis as any).document = prevDocument;
(globalThis as any).HTMLElement = prevHtmlElement;
(globalThis as any).HTMLIFrameElement = prevHtmlIFrameElement;
(globalThis as any).Element = prevElement;
(globalThis as any).Node = prevNode;
(globalThis as any).getComputedStyle = prevGetComputedStyle;
(globalThis as any).MutationObserver = prevMutationObserver;
(globalThis as any).requestAnimationFrame = prevRaf;
(globalThis as any).cancelAnimationFrame = prevCancelRaf;
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
});
it('computes exact outward-covered physical pixels across DPR 1.0..2.0 and interfaceScale 0.85..1.25 with zero 1px seams', () => {
const osDprs = [1.0, 1.25, 1.5, 2.0];
const interfaceScales = [0.85, 0.9, 1.0, 1.15, 1.25];
// Exact integer physical bounds must never expand by +1px even under IEEE-754 float noise
expect(
computePhysicalPixelRect({ left: 240, top: 64, right: 1200, bottom: 784 }, 1.25)
).toEqual({ xPx: 300, yPx: 80, widthPx: 1200, heightPx: 900 });
expect(
computePhysicalPixelRect({ left: 240, top: 64, right: 1200, bottom: 784 }, 1.5)
).toEqual({ xPx: 360, yPx: 96, widthPx: 1440, heightPx: 1080 });
expect(
computePhysicalPixelRect({ left: 240.8, top: 64.0, right: 1200.0, bottom: 784.0 }, 1.25)
).toEqual({ xPx: 301, yPx: 80, widthPx: 1199, heightPx: 900 });
// Minimize / collapsed viewport must yield 0x0 without negative dimensions
expect(computePhysicalPixelRect({ left: 0, top: 0, right: 0, bottom: 0 }, 1.5)).toEqual({
xPx: 0,
yPx: 0,
widthPx: 0,
heightPx: 0,
});
// Across every (osDpr, interfaceScale) pair, the physical box must completely cover the
// fractional CSS cutout (no 1px transparent border seam) with <= 1px overhang per edge.
const cssRect = { left: 241.33, top: 67.67, right: 1283.42, bottom: 811.79 };
for (const osDpr of osDprs) {
for (const scale of interfaceScales) {
const effDpr = osDpr * scale;
const phys = computePhysicalPixelRect(cssRect, effDpr);
expect(phys.xPx).toBeLessThanOrEqual(cssRect.left * effDpr + 1e-3);
expect(phys.yPx).toBeLessThanOrEqual(cssRect.top * effDpr + 1e-3);
expect(phys.xPx + phys.widthPx).toBeGreaterThanOrEqual(cssRect.right * effDpr - 1e-3);
expect(phys.yPx + phys.heightPx).toBeGreaterThanOrEqual(cssRect.bottom * effDpr - 1e-3);
expect(cssRect.left * effDpr - phys.xPx).toBeLessThan(1.0 + 1e-3);
expect(phys.xPx + phys.widthPx - cssRect.right * effDpr).toBeLessThan(1.0 + 1e-3);
}
}
});
it('syncs historyList, canUndo, and document isDirty (*) when Rust emits StrokeCommitted and during undo/redo', async () => {
let latest: UseDrawingHistoryResult | null = null;
const activeDoc = useDocumentStore.getState().documents[0];
function Harness() {
const dimsRef = useRef(activeDoc.dimensions);
const layerIdRef = useRef('layer-1');
const colorModeRef = useRef(activeDoc.colorMode);
const layersRef = useRef<LayerItem[] | undefined>(activeDoc.layers);
const isDrawingRef = useRef(false);
const lastStrokeEndRef = useRef(null);
const abortRef = useRef(() => {});
const maskThumbRef = useRef<((id: string) => void) | undefined>(undefined);
latest = useDrawingHistory({
activeSessionId: activeDoc.id,
activeLayerId: 'layer-1',
activeLayerLocked: false,
dimensions: activeDoc.dimensions,
dimensionsRef: dimsRef,
activeLayerIdRef: layerIdRef,
colorModeRef,
layersRef,
onUpdateLayerThumbnail: () => {},
onUpdateMaskThumbnailRef: maskThumbRef,
isDrawingRef,
lastStrokeEndRef,
abortActiveStrokeRef: abortRef,
});
return null;
}
root = createRoot(hostEl as any);
act(() => {
root!.render(<Harness />);
});
expect(useDocumentStore.getState().documents[0].isDirty).toBe(false);
expect(latest!.canUndo).toBe(false);
// Emit StrokeCommitted from Rust engine
act(() => {
for (const cb of mockBridge.strokeCommittedListeners) {
cb({
docId: activeDoc.id,
layerId: 'layer-1',
history: {
items: [{ id: 's1', type: 'stroke', label: 'Brush Stroke', timestamp: 123, timeFormatted: '00:00', thumbnailUrl: '' }],
currentIndex: 0,
canUndo: true,
canRedo: false,
},
});
}
});
expect(latest!.canUndo).toBe(true);
expect(latest!.canRedo).toBe(false);
expect(latest!.historyList).toHaveLength(1);
expect(latest!.historyList[0].label).toBe('Brush Stroke');
expect(useDocumentStore.getState().documents[0].isDirty).toBe(true);
// Reset dirty flag to verify Undo also marks document dirty and updates canUndo/canRedo
documentStoreActions.markDocumentDirty(activeDoc.id, false);
await act(async () => {
latest!.undo();
await Promise.resolve();
});
expect(mockBridge.nativeUndo).toHaveBeenCalledTimes(1);
expect(latest!.canUndo).toBe(false);
expect(latest!.canRedo).toBe(true);
expect(useDocumentStore.getState().documents[0].isDirty).toBe(true);
// Redo restores stroke history state
await act(async () => {
latest!.redo();
await Promise.resolve();
});
expect(mockBridge.nativeRedo).toHaveBeenCalledTimes(1);
expect(latest!.canUndo).toBe(true);
expect(latest!.canRedo).toBe(false);
});
it('hides DirectComposition on WelcomeScreen/no-doc, re-syncs on ViewportInvalidated & scale, and tracks modals/occluders', () => {
const viewportEl = miniDoc.createElement('div');
viewportEl.rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };
const floatingPill = miniDoc.createElement('div');
floatingPill.setAttribute('data-testid', 'floating-brush-pill');
floatingPill.setAttribute('data-native-occluder', 'true');
floatingPill.rect = { left: 500, top: 700, right: 780, bottom: 756, width: 280, height: 56 };
miniDoc.occluders = [floatingPill];
const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
const layer = useDocumentStore.getState().documents[0].layers[0];
function ViewportHarness({ hasOpenDocument }: { hasOpenDocument: boolean }) {
const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
useNativeEngineViewport({
viewportRef: vpRef,
dimensions: { width: 1024, height: 1024, dpi: 300 },
showCheckerboard: true,
hasOpenDocument,
tool: 'brush',
brushSettings,
primaryColor: '#111111',
activeLayer: layer,
isMaskMode: false,
isSquare: false,
thicknessRatio: 1,
thicknessVertical: false,
tipAngleDeg: 0,
isResizingBrush: false,
isSpaceDown: false,
isPanning: false,
isRotating: false,
isZoomDragging: false,
isRotateModifier: false,
pan: { x: 0, y: 0 },
zoom: 1,
rotation: 0,
flipX: false,
flipY: false,
});
return null;
}
root = createRoot(hostEl as any);
act(() => {
root!.render(<ViewportHarness hasOpenDocument={true} />);
});
// Initial workspace mount activates transparent cutout and pushes exact physical rect + FloatingBrushPill occluder
expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBe('true');
expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
xPx: 300,
yPx: 80,
widthPx: 1200,
heightPx: 900,
dpr: 1.25,
visible: true,
});
expect(mockBridge.setNativeOccludedRects).toHaveBeenLastCalledWith([
{ x: 625, y: 875, width: 350, height: 70 },
]);
// WM_DPICHANGED / restore invalidation re-syncs even if CSS dimensions stay identical
mockBridge.setNativeViewport.mockClear();
miniWin.devicePixelRatio = 1.5;
act(() => {
for (const cb of mockBridge.viewportInvalidatedListeners) cb();
flushRaf();
});
expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
xPx: 360,
yPx: 96,
widthPx: 1440,
heightPx: 1080,
dpr: 1.5,
visible: true,
});
// Interface scale change event triggers fresh alignment push
mockBridge.setNativeViewport.mockClear();
miniWin.devicePixelRatio = 1.875; // 1.5 * 1.25 interfaceScale
act(() => {
miniWin.dispatchEvent(new Event(INTERFACE_SCALE_APPLIED_EVENT));
flushRaf();
});
expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith({
xPx: 450,
yPx: 120,
widthPx: 1800,
heightPx: 1350,
dpr: 1.875,
visible: true,
});
// Opening Brush Studio modal pauses native engine via modalOpen: true
mockBridge.setNativePolicy.mockClear();
act(() => {
uiStoreActions.setBrushStudioModalOpen(true);
});
expect(mockBridge.setNativePolicy).toHaveBeenLastCalledWith(
expect.objectContaining({ modalOpen: true })
);
act(() => {
uiStoreActions.setBrushStudioModalOpen(false);
});
// Switching to WelcomeScreen ('home') hides DirectComposition visual & removes cutout attribute
mockBridge.setNativeViewport.mockClear();
act(() => {
uiStoreActions.setAppView('home');
});
expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBeNull();
expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith(
expect.objectContaining({ widthPx: 0, heightPx: 0, visible: false })
);
// Returning to workspace restores visible: true; closing document hides again
act(() => {
uiStoreActions.setAppView('workspace');
});
expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBe('true');
mockBridge.setNativeViewport.mockClear();
act(() => {
root!.render(<ViewportHarness hasOpenDocument={false} />);
});
expect(miniDoc.documentElement.getAttribute('data-native-canvas')).toBeNull();
expect(mockBridge.setNativeViewport).toHaveBeenLastCalledWith(
expect.objectContaining({ widthPx: 0, heightPx: 0, visible: false })
);
});
it('never echoes native Space+drag camera events back to Rust via setNativeCamera after rAF broadcast', () => {
const viewportEl = miniDoc.createElement('div');
viewportEl.rect = { left: 240, top: 64, right: 1200, bottom: 784, width: 960, height: 720 };
const cameraSubs = new Set<(cam: any, meta?: any) => void>();
let liveCam = { pan: { x: 500, y: 400 }, zoom: 1, rotation: 0, flipX: false, flipY: false };
let pendingSource: any = 'user';
let rafPending = false;
const mockNav: any = {
getCameraState: () => liveCam,
subscribeCamera: (cb: any) => {
cameraSubs.add(cb);
return () => cameraSubs.delete(cb);
},
setCameraLive: (next: any, commit = false, source = 'programmatic') => {
liveCam = { ...liveCam, ...next };
if (commit) {
cameraSubs.forEach((cb) => cb(liveCam, { source }));
} else {
pendingSource = source;
if (!rafPending) {
rafPending = true;
requestAnimationFrame(() => {
rafPending = false;
const emitSrc = pendingSource;
cameraSubs.forEach((cb) => cb(liveCam, { source: emitSrc }));
});
}
}
},
};
const brushSettings: BrushSettings = { ...useToolStore.getState().brushSettings };
const layer = useDocumentStore.getState().documents[0].layers[0];
function CameraSyncHarness() {
const vpRef = useRef<HTMLDivElement | null>(viewportEl as any);
useNativeEngineViewport({
viewportRef: vpRef,
navigation: mockNav,
dimensions: { width: 1024, height: 1024, dpi: 300 },
showCheckerboard: true,
hasOpenDocument: true,
tool: 'brush',
brushSettings,
primaryColor: '#000000',
activeLayer: layer,
isMaskMode: false,
isSquare: false,
thicknessRatio: 1,
thicknessVertical: false,
tipAngleDeg: 0,
isResizingBrush: false,
isSpaceDown: true,
isPanning: false,
isRotating: false,
isZoomDragging: false,
isRotateModifier: false,
pan: { x: 500, y: 400 },
zoom: 1,
rotation: 0,
flipX: false,
flipY: false,
});
return null;
}
root = createRoot(hostEl as any);
act(() => {
root!.render(<CameraSyncHarness />);
});
// Clear initial mount camera push
mockBridge.setNativeCamera.mockClear();
// Simulate Rust emitting live Space+drag camera updates (commit: false) followed by rAF flush
act(() => {
for (const cb of mockBridge.cameraListeners) {
cb({ panX: 520, panY: 410, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: false });
}
flushRaf();
for (const cb of mockBridge.cameraListeners) {
cb({ panX: 560, panY: 430, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: false });
}
flushRaf();
for (const cb of mockBridge.cameraListeners) {
cb({ panX: 590, panY: 445, zoom: 1, rotation: 0, flipX: false, flipY: false, commit: true });
}
});
// Zero stale camera echoes sent back to Rust during native drag!
expect(mockBridge.setNativeCamera).not.toHaveBeenCalled();
// User-initiated React camera change (e.g. Navigator drag) MUST still push to Rust
act(() => {
cameraSubs.forEach((cb) =>
cb({ pan: { x: 700, y: 500 }, zoom: 1.5, rotation: 0, flipX: false, flipY: false }, { source: 'user' })
);
});
expect(mockBridge.setNativeCamera).toHaveBeenCalledTimes(1);
expect(mockBridge.setNativeCamera).toHaveBeenCalledWith({
panX: 700,
panY: 500,
zoom: 1.5,
rotation: 0,
flipX: false,
flipY: false,
});
});
});