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 React, { Profiler, act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
ALL_DOCK_PANEL_IDS,
BUILT_IN_WORKSPACE_PRESET_IDS,
INK_WORKSPACE_FORMAT_ID,
INK_WORKSPACE_SCHEMA_VERSION,
} from '../../types/workspace';
import {
DEFAULT_APPEARANCE_CONFIG,
createAppearanceFromPreset,
} from '../../types/appearance';
import {
CLIP_STUDIO_LAYOUT,
DEFAULT_ILLUSTRATION_LAYOUT,
PHOTOSHOP_STUDIO_LAYOUT,
detachPanelToFloatingInLayout,
findPanelLocation,
getColumnWidthBounds,
getPresetLayout,
listVisiblePanelIds,
mirrorWorkspaceLayout,
parseWorkspaceBundle,
sanitizeLayout,
} from '../workspacePresets';
import {
toolStoreActions,
uiStoreActions,
useToolStore,
useUiStore,
useWorkspaceStore,
workspaceStoreActions,
} from '../../stores';
import { ToolOptionsBar } from '../../components/ToolOptionsBar';
import { Header } from '../../components/Header';
import { StatusBar } from '../../components/StatusBar';
import { RightSidebar } from '../../components/RightSidebar';
import { QuickBrushPanel } from '../../components/QuickBrushPanel';
import { FloatingBrushPill } from '../../components/FloatingBrushPill';
import { AppearanceStudioDrawer } from '../../components/AppearanceStudioDrawer';
import { LayerItem, MenuSection } from '../../types/editor';
function createMemoryStorage(): Storage {
const store = new Map<string, string>();
return {
get length() {
return store.size;
},
clear() {
store.clear();
},
getItem(key: string) {
return store.has(key) ? store.get(key)! : null;
},
key(index: number) {
return Array.from(store.keys())[index] ?? null;
},
removeItem(key: string) {
store.delete(key);
},
setItem(key: string, value: string) {
store.set(key, String(value));
},
};
}
class MiniText {
nodeType = 3;
nodeName = '#text';
parentNode: MiniEl | null = null;
constructor(
public nodeValue: string,
public ownerDocument: MiniDoc
) {}
}
class MiniComment {
nodeType = 8;
nodeName = '#comment';
parentNode: MiniEl | null = null;
constructor(
public nodeValue: string,
public ownerDocument: MiniDoc
) {}
}
class MiniStyle {
private map = new Map<string, string>();
[key: string]: unknown;
setProperty(k: string, v: string) {
this.map.set(k, String(v));
this[k] = String(v);
}
getPropertyValue(k: string): string {
return this.map.get(k) ?? (typeof this[k] === 'string' ? (this[k] as string) : '');
}
removeProperty(k: string) {
this.map.delete(k);
delete this[k];
}
}
class MiniEl extends EventTarget {
nodeType = 1;
nodeName: string;
tagName: string;
namespaceURI = 'http://www.w3.org/1999/xhtml';
parentNode: MiniEl | null = null;
childNodes: Array<MiniEl | MiniText | MiniComment> = [];
style = new MiniStyle();
className = '';
disabled = false;
type = '';
checked = false;
selected = false;
defaultSelected = false;
oninput: ((ev: Event) => void) | null = null;
onchange: ((ev: Event) => void) | null = null;
clientWidth = 200;
clientHeight = 26;
attrs = new Map<string, string>();
private _value = '';
private legacyListeners = new Map<string, Set<(ev: unknown) => void>>();
constructor(
tag: string,
public ownerDocument: MiniDoc
) {
super();
this.nodeName = tag.toUpperCase();
this.tagName = tag.toUpperCase();
}
get value(): string {
return this._value;
}
set value(v: string) {
this._value = String(v);
}
get firstChild() {
return this.childNodes[0] ?? null;
}
get options(): MiniEl[] {
return this.findAll((el) => el.tagName === 'OPTION');
}
get textContent(): string {
return this.childNodes
.map((c) =>
c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''
)
.join('');
}
set textContent(val: string) {
this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];
}
getBoundingClientRect() {
return {
left: 80,
top: 40,
width: this.clientWidth,
height: this.clientHeight,
right: 80 + this.clientWidth,
bottom: 40 + this.clientHeight,
x: 80,
y: 40,
toJSON: () => ({}),
};
}
focus() {
this.ownerDocument.activeElement = this;
this.dispatchEvent(new Event('focus', { bubbles: false }));
this.dispatchEvent(new Event('focusin', { bubbles: true }));
}
blur() {
if (this.ownerDocument.activeElement === this) {
this.ownerDocument.activeElement = this.ownerDocument.body;
}
this.dispatchEvent(new Event('blur', { bubbles: false }));
this.dispatchEvent(new Event('focusout', { bubbles: true }));
}
select() {}
click() {
this.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
}
attachEvent(eventName: string, listener: (ev: unknown) => void) {
let set = this.legacyListeners.get(eventName);
if (!set) {
set = new Set();
this.legacyListeners.set(eventName, set);
}
set.add(listener);
}
detachEvent(eventName: string, listener: (ev: unknown) => void) {
this.legacyListeners.get(eventName)?.delete(listener);
}
fireLegacyPropertyChange(propertyName: string) {
const set = this.legacyListeners.get('onpropertychange');
if (!set) return;
const ev = { type: 'propertychange', propertyName, target: this, srcElement: this };
set.forEach((fn) => fn(ev));
}
closest(selectorList: string): MiniEl | null {
const selectors = selectorList.split(',').map((s) => s.trim().toUpperCase());
let cur: MiniEl | null = this;
while (cur) {
if (selectors.includes(cur.tagName)) return cur;
cur = cur.parentNode;
}
return null;
}
appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
if (child.parentNode) child.parentNode.removeChild(child);
child.parentNode = this;
this.childNodes.push(child);
return child;
}
removeChild<T extends MiniEl | MiniText | MiniComment>(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 MiniEl | MiniText | MiniComment>(
node: T,
ref: MiniEl | MiniText | MiniComment | null
): T {
if (node.parentNode) node.parentNode.removeChild(node);
node.parentNode = this;
const idx = ref ? this.childNodes.indexOf(ref) : -1;
if (idx >= 0) this.childNodes.splice(idx, 0, node);
else this.childNodes.push(node);
return node;
}
setAttribute(k: string, v: string) {
this.attrs.set(k, String(v));
if (k === 'type') this.type = String(v);
if (k === 'value') this._value = String(v);
if (k === 'disabled') this.disabled = true;
}
getAttribute(k: string): string | null {
return this.attrs.get(k) ?? null;
}
removeAttribute(k: string) {
this.attrs.delete(k);
if (k === 'disabled') this.disabled = false;
}
contains(target: unknown): boolean {
if (target === this) return true;
for (const c of this.childNodes) {
if (c === target) return true;
if (c instanceof MiniEl && c.contains(target)) return true;
}
return false;
}
override dispatchEvent(event: Event): boolean {
if (!event.target) {
Object.defineProperty(event, 'target', { value: this, configurable: true });
}
let cur: MiniEl | null = this;
while (cur) {
Object.defineProperty(event, 'currentTarget', { value: cur, configurable: true });
EventTarget.prototype.dispatchEvent.call(cur, event);
if (!event.bubbles || event.cancelBubble) break;
cur = cur.parentNode;
}
return !event.defaultPrevented;
}
findAll(pred: (el: MiniEl) => boolean): MiniEl[] {
const out: MiniEl[] = [];
const walk = (node: MiniEl | MiniText | MiniComment) => {
if (node instanceof MiniEl) {
if (pred(node)) out.push(node);
for (const child of node.childNodes) walk(child);
}
};
walk(this);
return out;
}
findByAttr(attr: string, value: string): MiniEl | null {
return this.findAll((el) => el.getAttribute(attr) === value)[0] ?? null;
}
}
interface MiniDoc {
nodeType: number;
nodeName: string;
documentElement: MiniEl;
body: MiniEl;
activeElement: MiniEl;
defaultView: Record<string, unknown>;
oninput: ((ev: Event) => void) | null;
onchange: ((ev: Event) => void) | null;
createElement: (tag: string) => MiniEl;
createElementNS: (_ns: string, tag: string) => MiniEl;
createTextNode: (text: string) => MiniText;
createComment: (text: string) => MiniComment;
addEventListener: EventTarget['addEventListener'];
removeEventListener: EventTarget['removeEventListener'];
dispatchEvent: EventTarget['dispatchEvent'];
}
function installMiniDom() {
const g = globalThis as unknown as Record<string, unknown>;
const saved: Record<string, unknown> = {
window: g.window,
document: g.document,
HTMLElement: g.HTMLElement,
HTMLInputElement: g.HTMLInputElement,
Node: g.Node,
Element: g.Element,
localStorage: g.localStorage,
requestAnimationFrame: g.requestAnimationFrame,
cancelAnimationFrame: g.cancelAnimationFrame,
IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
};
g.IS_REACT_ACT_ENVIRONMENT = true;
Object.defineProperty(globalThis, 'localStorage', {
value: createMemoryStorage(),
configurable: true,
writable: true,
});
const winTarget = new EventTarget();
const docTarget = new EventTarget();
const mockDoc: MiniDoc = {
nodeType: 9,
nodeName: '#document',
documentElement: null as unknown as MiniEl,
body: null as unknown as MiniEl,
activeElement: null as unknown as MiniEl,
defaultView: null as unknown as Record<string, unknown>,
oninput: null,
onchange: null,
createElement: (tag: string) => new MiniEl(tag, mockDoc),
createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),
createTextNode: (text: string) => new MiniText(text, mockDoc),
createComment: (text: string) => new MiniComment(text, mockDoc),
addEventListener: docTarget.addEventListener.bind(docTarget),
removeEventListener: docTarget.removeEventListener.bind(docTarget),
dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
};
mockDoc.documentElement = new MiniEl('html', mockDoc);
mockDoc.body = new MiniEl('body', mockDoc);
mockDoc.documentElement.appendChild(mockDoc.body);
mockDoc.activeElement = mockDoc.body;
class MockIFrame extends MiniEl {}
const rafMock = () => 1;
const cancelRafMock = () => {};
const mockWin: Record<string, unknown> = {
innerWidth: 1440,
innerHeight: 900,
devicePixelRatio: 1,
document: mockDoc,
Node: MiniEl,
Element: MiniEl,
HTMLElement: MiniEl,
HTMLInputElement: MiniEl,
SVGElement: MiniEl,
HTMLIFrameElement: MockIFrame,
Event,
CustomEvent,
getSelection: () => ({
anchorNode: null,
anchorOffset: 0,
focusNode: null,
focusOffset: 0,
}),
addEventListener: winTarget.addEventListener.bind(winTarget),
removeEventListener: winTarget.removeEventListener.bind(winTarget),
dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
requestAnimationFrame: rafMock,
cancelAnimationFrame: cancelRafMock,
};
mockDoc.defaultView = mockWin;
g.window = mockWin;
g.document = mockDoc;
g.HTMLElement = MiniEl;
g.HTMLInputElement = MiniEl;
g.Node = MiniEl;
g.Element = MiniEl;
g.requestAnimationFrame = rafMock;
g.cancelAnimationFrame = cancelRafMock;
const container = new MiniEl('div', mockDoc);
mockDoc.body.appendChild(container);
return {
container,
mockDoc,
cleanup: () => {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete g[k];
else g[k] = v;
}
},
};
}
function clickEl(el: MiniEl) {
el.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
}
function fireKey(target: EventTarget, key: string) {
target.dispatchEvent(
Object.assign(new Event('keydown', { bubbles: true, cancelable: true }), { key })
);
}
function setInputText(inputEl: MiniEl, nextValue: string) {
inputEl.focus();
const nativeSetter = Object.getOwnPropertyDescriptor(MiniEl.prototype, 'value')?.set;
nativeSetter?.call(inputEl, nextValue);
inputEl.fireLegacyPropertyChange('value');
inputEl.dispatchEvent(new Event('input', { bubbles: true }));
}
describe('Pass 5: Workspace Archetypes, Left-Handed Mirror & Custom Workspaces', () => {
const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;
beforeEach(() => {
Object.defineProperty(globalThis, 'localStorage', {
value: createMemoryStorage(),
configurable: true,
writable: true,
});
useWorkspaceStore.reset();
useToolStore.reset();
useUiStore.reset();
});
afterEach(() => {
if (prevStorage === undefined) {
delete (globalThis as unknown as Record<string, unknown>).localStorage;
} else {
Object.defineProperty(globalThis, 'localStorage', {
value: prevStorage,
configurable: true,
writable: true,
});
}
});
it('validates photoshop-studio and clip-studio presets with all panels, zero duplicates, and valid bounds', () => {
for (const presetId of BUILT_IN_WORKSPACE_PRESET_IDS) {
const raw = getPresetLayout(presetId);
const sanitized = sanitizeLayout(raw);
expect(sanitized).not.toBeNull();
// Count every panel occurrence to guarantee zero duplicates
const seen: string[] = [];
for (const col of [...raw.leftDocks, ...raw.rightDocks]) {
const bounds = getColumnWidthBounds(col);
expect(col.width).toBeGreaterThanOrEqual(bounds.min);
expect(col.width).toBeLessThanOrEqual(bounds.max);
for (const grp of col.groups) {
expect(grp.heightRatio).toBeGreaterThan(0);
expect(grp.panelIds).toContain(grp.activePanelId);
seen.push(...grp.panelIds);
}
}
expect(new Set(seen).size).toBe(seen.length);
}
// Photoshop Studio specifics: slim left tools rail, right Color/Brushes/Layers stack, auto Tool Options Bar
const psVisible = listVisiblePanelIds(PHOTOSHOP_STUDIO_LAYOUT);
for (const pid of ALL_DOCK_PANEL_IDS) {
expect(psVisible.has(pid)).toBe(true);
}
expect(PHOTOSHOP_STUDIO_LAYOUT.leftDocks).toHaveLength(1);
expect(PHOTOSHOP_STUDIO_LAYOUT.leftDocks[0].width).toBe(46);
expect(findPanelLocation(PHOTOSHOP_STUDIO_LAYOUT, 'tools')?.side).toBe('left');
expect(findPanelLocation(PHOTOSHOP_STUDIO_LAYOUT, 'color')?.side).toBe('right');
expect(findPanelLocation(PHOTOSHOP_STUDIO_LAYOUT, 'subtool')?.side).toBe('right');
expect(findPanelLocation(PHOTOSHOP_STUDIO_LAYOUT, 'layers')?.side).toBe('right');
workspaceStoreActions.applyPreset('photoshop-studio');
expect(useWorkspaceStore.getState().activePreset).toBe('photoshop-studio');
expect(useWorkspaceStore.getState().showToolOptionsBar).toBe(true);
// Clip Studio specifics: left SubTool/ToolProperty/BrushSize + right Navigator/Color/Layers
const cspVisible = listVisiblePanelIds(CLIP_STUDIO_LAYOUT);
for (const pid of ALL_DOCK_PANEL_IDS) {
expect(cspVisible.has(pid)).toBe(true);
}
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'subtool')?.side).toBe('left');
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'tool-property')?.side).toBe('left');
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'brush-size')?.side).toBe('left');
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'navigator')?.side).toBe('right');
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'color')?.side).toBe('right');
expect(findPanelLocation(CLIP_STUDIO_LAYOUT, 'layers')?.side).toBe('right');
workspaceStoreActions.applyPreset('clip-studio');
expect(useWorkspaceStore.getState().activePreset).toBe('clip-studio');
expect(useWorkspaceStore.getState().showToolOptionsBar).toBe(false);
});
it('mirrors workspace layout with exact double-mirror reversibility and moves tools rail to outer right edge', () => {
const withFloating = detachPanelToFloatingInLayout(DEFAULT_ILLUSTRATION_LAYOUT, 'sub-view', {
x: 340,
y: 120,
});
const layoutsToVerify = [
DEFAULT_ILLUSTRATION_LAYOUT,
PHOTOSHOP_STUDIO_LAYOUT,
CLIP_STUDIO_LAYOUT,
withFloating,
];
for (const original of layoutsToVerify) {
const normalizedOrig = {
...original,
floatingPanels: original.floatingPanels ?? [],
};
const once = mirrorWorkspaceLayout(normalizedOrig);
const twice = mirrorWorkspaceLayout(once);
// Double mirror must restore exact column order, sides, groups, and floating lastDock
expect(twice).toEqual(normalizedOrig);
// Single mirror puts narrow tools rail on the far right outer edge
const lastRightCol = once.rightDocks[once.rightDocks.length - 1];
expect(lastRightCol.groups[0].panelIds).toContain('tools');
expect(findPanelLocation(once, 'layers')?.side).toBe('left');
}
// Floating panel lastDock.side flips on single mirror and restores on double mirror
const mirroredFloat = mirrorWorkspaceLayout(withFloating).floatingPanels?.[0];
expect(mirroredFloat?.lastDock?.side).toBe('left');
// Store toggle persists across reload and auto-mirrors newly applied presets
expect(useWorkspaceStore.getState().leftHandedMode).toBe(false);
workspaceStoreActions.toggleLeftHandedMode();
expect(useWorkspaceStore.getState().leftHandedMode).toBe(true);
expect(findPanelLocation(useWorkspaceStore.getState().layout, 'tools')?.side).toBe('right');
useWorkspaceStore.reset();
expect(useWorkspaceStore.getState().leftHandedMode).toBe(true);
expect(findPanelLocation(useWorkspaceStore.getState().layout, 'tools')?.side).toBe('right');
// Switching preset while Left-Handed Mode is ON keeps the new preset mirrored
workspaceStoreActions.applyPreset('photoshop-studio');
expect(useWorkspaceStore.getState().leftHandedMode).toBe(true);
const psRight = useWorkspaceStore.getState().layout.rightDocks;
expect(psRight[psRight.length - 1].groups[0].panelIds).toContain('tools');
expect(findPanelLocation(useWorkspaceStore.getState().layout, 'layers')?.side).toBe('left');
});
it('supports named custom workspace CRUD and complete .inkworkspace JSON export/import round-trip', () => {
// 1. Configure a distinctive Lineart workspace + Warm Paper appearance
workspaceStoreActions.applyPreset('photoshop-studio');
workspaceStoreActions.setLeftHandedMode(true);
workspaceStoreActions.setStatusBarModule('pressureMeter', false);
const warmLook = createAppearanceFromPreset('warm-paper-light', {
accent: 'vermilion',
chromeStyle: 'islands',
});
uiStoreActions.replaceAppearance(warmLook, { persist: true });
const lineartProfile = workspaceStoreActions.saveCustomWorkspace('Lineart', {
includeAppearance: true,
});
expect(lineartProfile.name).toBe('Lineart');
expect(lineartProfile.leftHandedMode).toBe(true);
expect(lineartProfile.showToolOptionsBar).toBe(true);
expect(lineartProfile.appearance?.lookPreset).toBe('warm-paper-light');
expect(useWorkspaceStore.getState().activeSavedWorkspaceId).toBe(lineartProfile.id);
// 2. Switch to a different preset & appearance, save "Coloring"
workspaceStoreActions.resetWorkspace();
workspaceStoreActions.applyPreset('clip-studio');
uiStoreActions.replaceAppearance({ ...DEFAULT_APPEARANCE_CONFIG }, { persist: true });
const coloringProfile = workspaceStoreActions.saveCustomWorkspace('Coloring', {
includeAppearance: false,
});
expect(useWorkspaceStore.getState().savedWorkspaces).toHaveLength(2);
// 3. Reload "Lineart" in 1 click -> restores layout, LH mode, options bar, status modules & appearance
const loaded = workspaceStoreActions.loadCustomWorkspace(lineartProfile.id);
expect(loaded?.id).toBe(lineartProfile.id);
expect(useWorkspaceStore.getState().leftHandedMode).toBe(true);
expect(useWorkspaceStore.getState().showToolOptionsBar).toBe(true);
expect(useWorkspaceStore.getState().statusBarModules.pressureMeter).toBe(false);
expect(useUiStore.getState().appSettings.appearance.lookPreset).toBe('warm-paper-light');
expect(useUiStore.getState().appSettings.appearance.chromeStyle).toBe('islands');
// 4. Rename & Delete saved workspace
expect(workspaceStoreActions.renameCustomWorkspace(coloringProfile.id, 'Coloring Pro')).toBe(true);
expect(
useWorkspaceStore.getState().savedWorkspaces.find((w) => w.id === coloringProfile.id)?.name
).toBe('Coloring Pro');
expect(workspaceStoreActions.deleteCustomWorkspace(coloringProfile.id)).toBe(true);
expect(useWorkspaceStore.getState().savedWorkspaces).toHaveLength(1);
// 5. Export .inkworkspace JSON bundle and round-trip import on clean state
const exportedJson = workspaceStoreActions.exportWorkspaceBundleJson({
profileId: lineartProfile.id,
includeAppearance: true,
author: 'Sora',
});
const parsedCheck = parseWorkspaceBundle(exportedJson);
expect(parsedCheck.ok).toBe(true);
if (parsedCheck.ok) {
expect(parsedCheck.bundle.format).toBe(INK_WORKSPACE_FORMAT_ID);
expect(parsedCheck.bundle.version).toBe(INK_WORKSPACE_SCHEMA_VERSION);
expect(parsedCheck.bundle.name).toBe('Lineart');
expect(parsedCheck.bundle.leftHandedMode).toBe(true);
expect(parsedCheck.bundle.showToolOptionsBar).toBe(true);
expect(parsedCheck.bundle.appearance?.accent).toBe('vermilion');
}
// Clear storage and import fresh
localStorage.clear();
useWorkspaceStore.reset();
uiStoreActions.replaceAppearance({ ...DEFAULT_APPEARANCE_CONFIG }, { persist: true });
expect(useWorkspaceStore.getState().savedWorkspaces).toHaveLength(0);
const imported = workspaceStoreActions.importWorkspaceBundleJson(exportedJson, {
applyNow: true,
applyAppearance: true,
});
expect(imported.ok).toBe(true);
if (imported.ok) {
expect(imported.profile.name).toBe('Lineart');
expect(useWorkspaceStore.getState().leftHandedMode).toBe(true);
expect(useWorkspaceStore.getState().showToolOptionsBar).toBe(true);
expect(useWorkspaceStore.getState().statusBarModules.pressureMeter).toBe(false);
expect(useUiStore.getState().appSettings.appearance.lookPreset).toBe('warm-paper-light');
}
// 6. Malicious / corrupt .inkworkspace JSON is safely rejected
const badFormat = workspaceStoreActions.importWorkspaceBundleJson('{"format":"nope"}');
expect(badFormat.ok).toBe(false);
const maliciousAppearance = JSON.stringify({
format: INK_WORKSPACE_FORMAT_ID,
version: INK_WORKSPACE_SCHEMA_VERSION,
name: 'Evil',
layout: PHOTOSHOP_STUDIO_LAYOUT,
leftHandedMode: false,
showToolOptionsBar: true,
showStatusBar: true,
showDocumentTabs: true,
showCommandBar: true,
appearance: {
tokenOverrides: { '--ui-bg-panel': 'url(javascript:alert(1))' },
},
});
const blocked = workspaceStoreActions.importWorkspaceBundleJson(maliciousAppearance);
expect(blocked.ok).toBe(false);
});
});
describe('Pass 5 UI Components: ToolOptionsBar Isolation, Left-Handed HUDs, Header, StatusBar & Workspace Tab', () => {
let dom: ReturnType<typeof installMiniDom>;
let root: Root | null = null;
beforeEach(() => {
dom = installMiniDom();
useWorkspaceStore.reset();
useToolStore.reset();
useUiStore.reset();
});
afterEach(() => {
if (root) {
act(() => {
root?.unmount();
});
root = null;
}
dom.cleanup();
});
it('renders ToolOptionsBar with live brush size/opacity updates and ZERO re-renders of Header or RightSidebar', () => {
const noop = () => {};
const layers: LayerItem[] = [
{
id: 'l1',
name: 'Lineart',
type: 'raster',
visible: true,
opacity: 1,
blendMode: 'normal',
locked: false,
collapsed: false,
parentId: null,
},
];
const menuSections: MenuSection[] = [
{ id: 'file', label: 'File', items: [{ id: 'new', label: 'New', onClick: noop }] },
];
workspaceStoreActions.setShowToolOptionsBar(true);
toolStoreActions.selectTool('brush');
toolStoreActions.updateBrushSettings({ size: 20, opacity: 0.8, flow: 0.9, stabilization: 10 });
let headerRenders = 0;
let layerListRenders = 0;
let optionsBarRenders = 0;
act(() => {
root = createRoot(dom.container as unknown as Element);
root.render(
<div>
<Profiler
id="Header"
onRender={() => {
headerRenders += 1;
}}
>
<Header
canUndo={false}
canRedo={false}
onUndo={noop}
onRedo={noop}
zoom={1}
onZoomIn={noop}
onZoomOut={noop}
onResetZoom={noop}
rotation={0}
onResetRotation={noop}
menuSections={menuSections}
hasOpenDocument
/>
</Profiler>
<Profiler
id="ToolOptionsBar"
onRender={() => {
optionsBarRenders += 1;
}}
>
<ToolOptionsBar />
</Profiler>
<Profiler
id="RightSidebar"
onRender={() => {
layerListRenders += 1;
}}
>
<RightSidebar
hasOpenDocument
hideColorPanel
colorMode="color"
historyList={[]}
historyIndex={-1}
onJumpToHistory={noop}
canUndo={false}
canRedo={false}
onUndo={noop}
onRedo={noop}
layers={layers}
activeLayerId="l1"
selectedLayerIds={['l1']}
onSelectLayer={noop}
onAddLayer={noop}
onDuplicateLayer={noop}
onDeleteLayer={noop}
onToggleVisibility={noop}
onSetOpacity={noop}
onSetBlendMode={noop}
onToggleLock={noop}
onToggleCollapse={noop}
onRenameLayer={noop}
onMoveLayerToFolder={noop}
width={200}
/>
</Profiler>
</div>
);
});
expect(headerRenders).toBe(1);
expect(layerListRenders).toBe(1);
expect(optionsBarRenders).toBe(1);
const optionsBar = dom.container.findByAttr('data-testid', 'tool-options-bar')!;
expect(optionsBar).not.toBeNull();
expect(optionsBar.getAttribute('data-active-tool')).toBe('brush');
// Adjust brush size & opacity directly via ToolOptionsBar ScrubSliders
const sizeSlider = dom.container.findByAttr('data-testid', 'tool-options-size-slider')!;
const opacitySlider = dom.container.findByAttr('data-testid', 'tool-options-opacity-slider')!;
expect(sizeSlider).not.toBeNull();
expect(opacitySlider).not.toBeNull();
act(() => {
fireKey(sizeSlider, 'ArrowRight');
fireKey(opacitySlider, 'ArrowLeft');
});
expect(useToolStore.getState().brushSettings.size).toBe(20.5);
expect(useToolStore.getState().brushSettings.opacity).toBeCloseTo(0.79, 2);
// Critical zero-rerender guarantee: Header and RightSidebar NEVER re-rendered!
expect(headerRenders).toBe(1);
expect(layerListRenders).toBe(1);
// Clicking Brush Studio button opens Brush Studio modal
const studioBtn = dom.container.findByAttr('data-testid', 'tool-options-brush-studio-btn')!;
act(() => clickEl(studioBtn));
expect(useUiStore.getState().isBrushStudioModalOpen).toBe(true);
// Switching tool updates contextual controls cleanly without re-rendering Header/Layers
act(() => toolStoreActions.selectTool('fill'));
expect(
dom.container.findByAttr('data-testid', 'tool-options-bar')?.getAttribute('data-active-tool')
).toBe('fill');
expect(dom.container.findByAttr('data-testid', 'tool-options-fill-method')).not.toBeNull();
expect(headerRenders).toBe(1);
expect(layerListRenders).toBe(1);
});
it('mirrors automatic edge anchoring for QuickBrushPanel and FloatingBrushPill when Left-Handed Mode toggles', () => {
act(() => {
root = createRoot(dom.container as unknown as Element);
root.render(
<div>
<QuickBrushPanel customBrushes={[]} />
<FloatingBrushPill
tool="brush"
brushSettings={useToolStore.getState().brushSettings}
onUpdateBrushSettings={() => {}}
/>
</div>
);
});
// Right-handed default: QuickBrushPanel anchors right, FloatingBrushPill anchors left
expect(
dom.container.findByAttr('data-testid', 'quick-brush-panel')?.getAttribute('data-anchor-side')
).toBe('right');
expect(
dom.container.findByAttr('data-testid', 'floating-brush-pill')?.getAttribute('data-anchor-side')
).toBe('left');
// Toggle Left-Handed Mode ON -> anchors mirror automatically!
act(() => {
workspaceStoreActions.setLeftHandedMode(true);
});
expect(
dom.container.findByAttr('data-testid', 'quick-brush-panel')?.getAttribute('data-anchor-side')
).toBe('left');
expect(
dom.container.findByAttr('data-testid', 'floating-brush-pill')?.getAttribute('data-anchor-side')
).toBe('right');
});
it('supports Header Home|Workspace switcher, customizable StatusBar modules, and Appearance Studio Workspace & Bars tab', () => {
const onSelectAppView = vi.fn();
const showToast = vi.fn();
uiStoreActions.setAppearanceStudioOpen(true);
const Harness: React.FC = () => {
const modules = useWorkspaceStore((s) => s.statusBarModules);
return (
<div>
<Header
canUndo={false}
canRedo={false}
onUndo={() => {}}
onRedo={() => {}}
zoom={1}
onZoomIn={() => {}}
onZoomOut={() => {}}
onResetZoom={() => {}}
rotation={0}
onResetRotation={() => {}}
appView="workspace"
onSelectAppView={onSelectAppView}
/>
<StatusBar
tool="brush"
brushSettings={useToolStore.getState().brushSettings}
dimensions={{ width: 2400, height: 3200, dpi: 300 }}
zoom={1}
rotation={0}
onResetRotation={() => {}}
modules={modules}
hasOpenDocument
onToggleValueCheck={() => {}}
/>
<AppearanceStudioDrawer showToast={showToast} />
</div>
);
};
act(() => {
root = createRoot(dom.container as unknown as Element);
root.render(<Harness />);
});
// 1. Header Home | Workspace switcher
const homeBtn = dom.container.findByAttr('data-testid', 'header-view-home')!;
expect(homeBtn).not.toBeNull();
act(() => clickEl(homeBtn));
expect(onSelectAppView).toHaveBeenCalledWith('home');
// 2. StatusBar displays dimensions & all modules initially
const canvasInfo = dom.container.findByAttr('data-testid', 'status-module-canvas-info')!;
expect(canvasInfo.textContent).toContain('2400×3200px');
expect(canvasInfo.textContent).toContain('300dpi');
expect(dom.container.findByAttr('data-testid', 'status-module-cursor-coords')).not.toBeNull();
expect(dom.container.findByAttr('data-testid', 'status-module-pressure')).not.toBeNull();
// 3. Switch to "Workspace" tab in AppearanceStudioDrawer and customize live
const wsTabBtn = dom.container.findByAttr('data-testid', 'appearance-tab-workspace')!;
expect(wsTabBtn).not.toBeNull();
act(() => clickEl(wsTabBtn));
expect(dom.container.findByAttr('data-testid', 'appearance-workspace-tab')).not.toBeNull();
// Toggle off Cursor Coordinates & Pressure Meter modules from drawer -> StatusBar hides them immediately
act(() => {
clickEl(dom.container.findByAttr('data-testid', 'statusbar-mod-cursorCoords')!);
clickEl(dom.container.findByAttr('data-testid', 'statusbar-mod-pressureMeter')!);
});
expect(dom.container.findByAttr('data-testid', 'status-module-cursor-coords')).toBeNull();
expect(dom.container.findByAttr('data-testid', 'status-module-pressure')).toBeNull();
// Click Photoshop Studio archetype -> enables Tool Options Bar
act(() => clickEl(dom.container.findByAttr('data-testid', 'workspace-tab-preset-photoshop-studio')!));
expect(useWorkspaceStore.getState().activePreset).toBe('photoshop-studio');
expect(useWorkspaceStore.getState().showToolOptionsBar).toBe(true);
// Save a named workspace directly from the Workspace & Bars tab
const nameInput = dom.container.findByAttr('data-testid', 'workspace-tab-save-name-input')!;
act(() => setInputText(nameInput, 'iPad Sketching'));
act(() => clickEl(dom.container.findByAttr('data-testid', 'workspace-tab-save-btn')!));
expect(useWorkspaceStore.getState().savedWorkspaces.some((w) => w.name === 'iPad Sketching')).toBe(
true
);
});
});