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, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
AlertTriangle,
Check,
ClipboardCheck,
Copy,
Download,
Eye,
GripVertical,
Palette,
PanelRight,
RotateCcw,
Shuffle,
SlidersHorizontal,
Undo2,
Upload,
X,
} from 'lucide-react';
import {
ACCENT_PIGMENTS,
APPEARANCE_LIMITS,
AppearanceConfig,
AppearanceTokenOverrides,
BrushListStyle,
BUILT_IN_ACCENT_PIGMENT_IDS,
BUILT_IN_LOOK_PRESET_IDS,
BuiltInLookPresetId,
CanvasMatteMode,
ChromeStyle,
CornerRadiusPreset,
DEFAULT_APPEARANCE_CONFIG,
DensityPreset,
FontProfile,
IconStrokeWidth,
LOOK_PRESETS,
LayerThumbSize,
OverridableTokenKey,
ScrollbarSize,
SliderStyle,
createAppearanceFromPreset,
isValidHex6,
isValidOverrideColorValue,
normalizeHex6,
} from '../types/appearance';
import {
applyAppearanceToDocument,
decodeThemeShareCode,
encodeThemeShareCode,
getContrastGrade,
oklchToHex,
parseThemePreset,
pickNextCuratedMix,
resolveAppearanceTokens,
rgbToHex,
serializeThemePreset,
} from '../utils/themeEngine';
import {
DEFAULT_INTERFACE_SCALE,
INTERFACE_SCALE_PRESETS,
INTERFACE_SCALE_STEP,
MAX_INTERFACE_SCALE,
MIN_INTERFACE_SCALE,
clampInterfaceScale,
} from '../utils/interfaceScale';
import { selectIsAnyModalOpen, uiStoreActions, useUiStore } from '../stores';
import { acquireWorkspaceInteractionLock } from '../utils/workspacePointerGuard';
import { saveFileWithDialog } from '../utils/fileSaveDialog';
import {
HairlineTabs,
IconButton,
ScrubSlider,
SectionDisclosure,
SegmentedControl,
} from './ui';
import { WorkspaceAndBarsTab } from './WorkspaceAndBarsTab';
import { isImeComposing, useI18n } from '../i18n';
type StudioAxisTab = 'surface' | 'chrome' | 'density' | 'controls' | 'workspace';
const DRAWER_WIDTH = 336;
const MAX_UNDO_STEPS = 30;
const LOOK_PRESET_SHORT_LABELS: Record<BuiltInLookPresetId, string> = {
'graphite-atelier': 'Graphite Atelier',
'obsidian-oled': 'Obsidian OLED',
'studio-neutral-18': 'Studio Neutral 18%',
'warm-paper-light': 'Warm Paper Light',
'daylight-crisp': 'Daylight Crisp',
'sumi-sepia': 'Sumi Sepia',
};
const OVERRIDABLE_TOKEN_ROWS: ReadonlyArray<{
key: OverridableTokenKey;
label: string;
}> = [
{ key: '--ui-canvas-matte', label: 'Canvas Matte' },
{ key: '--ui-bg-panel', label: 'Panel Surface' },
{ key: '--ui-bg-control', label: 'Control Surface' },
{ key: '--ui-border-default', label: 'Border' },
{ key: '--ui-text-primary', label: 'Primary Text' },
{ key: '--ui-text-muted', label: 'Muted Text' },
{ key: '--ui-accent', label: 'Accent' },
];
const CANVAS_MATTE_OPTIONS: ReadonlyArray<{
value: CanvasMatteMode;
label: string;
title: string;
}> = [
{ value: 'linked', label: 'Linked', title: 'Follow active look surface luminance' },
{ value: 'neutral-dark', label: 'Dark', title: 'Neutral dark charcoal matte (#161616)' },
{ value: 'neutral-mid', label: 'Mid 18%', title: '18% neutral grey matte for value judgment (#757575)' },
{ value: 'neutral-light', label: 'Light', title: 'Neutral light matte (#d4d4d4)' },
{ value: 'custom', label: 'Custom', title: 'Custom surround hex color' },
];
const CORNER_RADIUS_OPTIONS: ReadonlyArray<{ value: CornerRadiusPreset; label: string }> = [
{ value: 'sharp', label: 'Sharp' },
{ value: 'machined', label: 'Machined' },
{ value: 'soft', label: 'Soft' },
];
const CHROME_STYLE_OPTIONS: ReadonlyArray<{ value: ChromeStyle; label: string }> = [
{ value: 'flat', label: 'Flat' },
{ value: 'hairline', label: 'Hairline' },
{ value: 'islands', label: 'Islands' },
];
const DENSITY_OPTIONS: ReadonlyArray<{ value: DensityPreset; label: string }> = [
{ value: 'compact', label: 'Compact' },
{ value: 'balanced', label: 'Balanced' },
{ value: 'comfortable', label: 'Tablet' },
];
const FONT_PROFILE_OPTIONS: ReadonlyArray<{ value: FontProfile; label: string }> = [
{ value: 'system', label: 'System' },
{ value: 'humanist', label: 'Humanist' },
{ value: 'technical', label: 'Technical' },
];
const ICON_WEIGHT_OPTIONS: ReadonlyArray<{ value: '1.25' | '1.5' | '1.85'; label: string }> = [
{ value: '1.25', label: 'Thin 1.25' },
{ value: '1.5', label: 'Regular 1.5' },
{ value: '1.85', label: 'Bold 1.85' },
];
const SLIDER_STYLE_OPTIONS: ReadonlyArray<{ value: SliderStyle; label: string }> = [
{ value: 'scrubber', label: 'Bar Scrubber' },
{ value: 'track', label: 'Classic Track' },
];
const BRUSH_LIST_OPTIONS: ReadonlyArray<{ value: BrushListStyle; label: string }> = [
{ value: 'stroke', label: 'Stroke' },
{ value: 'compact', label: 'Compact' },
{ value: 'grid', label: 'Grid' },
];
const LAYER_THUMB_OPTIONS: ReadonlyArray<{ value: LayerThumbSize; label: string }> = [
{ value: 'compact', label: 'Compact' },
{ value: 'standard', label: 'Standard' },
{ value: 'large', label: 'Large' },
];
const SCROLLBAR_SIZE_OPTIONS: ReadonlyArray<{ value: ScrollbarSize; label: string; title: string }> = [
{ value: 'slim', label: 'Slim', title: '5px minimalist scrollbar' },
{ value: 'standard', label: 'Standard', title: '9px balanced scrollbar' },
{ value: 'tablet', label: 'Pen Display', title: '13px stylus-friendly scrollbar' },
{ value: 'large', label: 'Large', title: '16px wide pen & touch scrollbar' },
];
const AXIS_TABS: ReadonlyArray<{
value: StudioAxisTab;
label: string;
title?: string;
'data-testid': string;
}> = [
{ value: 'surface', label: 'Surface', 'data-testid': 'appearance-tab-surface' },
{ value: 'chrome', label: 'Chrome', 'data-testid': 'appearance-tab-chrome' },
{ value: 'density', label: 'Density', 'data-testid': 'appearance-tab-density' },
{ value: 'controls', label: 'Controls', 'data-testid': 'appearance-tab-controls' },
{
value: 'workspace',
label: 'Workspace',
title: 'Workspace & Bars',
'data-testid': 'appearance-tab-workspace',
},
];
function cloneAppearance(config: AppearanceConfig): AppearanceConfig {
return {
...config,
...(config.tokenOverrides ? { tokenOverrides: { ...config.tokenOverrides } } : {}),
};
}
function areAppearancesEqual(a: AppearanceConfig, b: AppearanceConfig): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
function colorTokenToHex6(value: string, fallback = '#808080'): string {
const trimmed = value.trim();
if (trimmed.startsWith('#')) {
return normalizeHex6(trimmed, fallback);
}
const rgbMatch = trimmed.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i);
if (rgbMatch) {
const r = Number(rgbMatch[1]);
const g = Number(rgbMatch[2]);
const b = Number(rgbMatch[3]);
if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) {
return rgbToHex({ r, g, b });
}
}
return fallback;
}
function slugifyThemeName(name: string): string {
const slug = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
return slug || 'ink-studio-theme';
}
export interface LookPresetCardProps {
presetId: BuiltInLookPresetId;
active: boolean;
accent?: AppearanceConfig['accent'];
customAccentHex?: string;
onSelect: (presetId: BuiltInLookPresetId) => void;
compact?: boolean;
'data-testid'?: string;
}
/**
* Miniature visual schematic preview card for a curated Look Preset (panel + canvas + border + accent chips).
*/
export const LookPresetCard: React.FC<LookPresetCardProps> = React.memo(
({
presetId,
active,
accent = 'neutral',
customAccentHex = '#e5e5e5',
onSelect,
compact = false,
'data-testid': dataTestId,
}) => {
const { td } = useI18n();
const def = LOOK_PRESETS[presetId];
const displayLabel = td(LOOK_PRESET_SHORT_LABELS[presetId] ?? def.label);
const previewTokens = useMemo(() => {
const cfg = createAppearanceFromPreset(presetId, {
accent,
customAccentHex,
});
return resolveAppearanceTokens(cfg).tokens;
}, [presetId, accent, customAccentHex]);
return (
<button
type="button"
data-testid={dataTestId ?? `look-preset-${presetId}`}
data-active={active ? 'true' : 'false'}
aria-pressed={active}
title={`${displayLabel} — ${td(def.description)}`}
onClick={() => onSelect(presetId)}
className={`group flex flex-col text-left rounded-ui-sm border transition-colors cursor-pointer overflow-hidden focus:outline-none focus-visible:border-ui-focus ${
active
? 'border-ui-accent bg-ui-control-active'
: 'border-ui-subtle bg-ui-header hover:border-ui-default hover:bg-ui-control'
}`}
>
{/* Tiny live workspace schematic: header, dock panels, canvas matte, paper sheet, border & accent */}
<div
className={`w-full relative overflow-hidden flex flex-col ${compact ? 'h-7' : 'h-8'}`}
style={{
backgroundColor: previewTokens['--ui-bg-void'],
borderBottom: `1px solid ${previewTokens['--ui-border-subtle']}`,
}}
>
{/* Mini top bar */}
<div
className="h-[6px] w-full flex items-center justify-between px-1 shrink-0"
style={{
backgroundColor: previewTokens['--ui-bg-header'],
borderBottom: `1px solid ${previewTokens['--ui-border-subtle']}`,
}}
>
<span
className="w-2.5 h-[2px] rounded-full"
style={{ backgroundColor: previewTokens['--ui-text-muted'] }}
/>
<span
className="w-1.5 h-[2px] rounded-full"
style={{ backgroundColor: previewTokens['--ui-accent'] }}
/>
</div>
{/* Mini 3-column workspace */}
<div className="flex-1 flex min-h-0">
{/* Mini left tool rail */}
<div
className="w-[10px] h-full flex flex-col items-center justify-center gap-[2px] shrink-0"
style={{
backgroundColor: previewTokens['--ui-bg-panel'],
borderRight: `1px solid ${previewTokens['--ui-border-default']}`,
}}
>
<span
className="w-[4px] h-[2px] rounded-[0.5px]"
style={{ backgroundColor: previewTokens['--ui-accent'] }}
/>
<span
className="w-[4px] h-[2px] rounded-[0.5px]"
style={{ backgroundColor: previewTokens['--ui-text-muted'] }}
/>
</div>
{/* Mini canvas matte + artboard */}
<div
className="flex-1 flex items-center justify-center p-[3px]"
style={{ backgroundColor: previewTokens['--ui-canvas-matte'] }}
>
<div
className="w-full h-full max-w-[20px] max-h-[14px] rounded-[1px]"
style={{
backgroundColor: '#f5f4f0',
border: `1px solid ${previewTokens['--ui-border-strong']}`,
}}
/>
</div>
{/* Mini right inspector panel */}
<div
className="w-[18px] h-full p-[2px] flex flex-col justify-center gap-[2px] shrink-0"
style={{
backgroundColor: previewTokens['--ui-bg-panel'],
borderLeft: `1px solid ${previewTokens['--ui-border-default']}`,
}}
>
<div
className="h-[3px] w-full rounded-[1px]"
style={{ backgroundColor: previewTokens['--ui-bg-control'] }}
/>
<div
className="h-[3px] w-full rounded-[1px] overflow-hidden"
style={{ backgroundColor: previewTokens['--ui-bg-input'] }}
>
<div
className="h-full w-2/3"
style={{ backgroundColor: previewTokens['--ui-accent'] }}
/>
</div>
</div>
</div>
</div>
{/* Concise preset label row */}
<div className="px-1.5 py-1 flex items-center justify-between gap-1 min-w-0">
<span
className={`text-[9.5px] leading-tight truncate ${
active ? 'text-ui-primary font-medium' : 'text-ui-secondary group-hover:text-ui-primary'
}`}
>
{displayLabel}
</span>
{active && <Check className="w-2.5 h-2.5 text-ui-accent shrink-0" />}
</div>
</button>
);
}
);
LookPresetCard.displayName = 'LookPresetCard';
export interface AppearanceStudioDrawerProps {
showToast?: (message: string) => void;
}
const AppearanceStudioPanel: React.FC<AppearanceStudioDrawerProps> = ({ showToast }) => {
const { t, tc, td } = useI18n();
const appearance = useUiStore((s) => s.appSettings.appearance);
const committedScale = useUiStore(
(s) => s.appSettings.interfaceScale ?? DEFAULT_INTERFACE_SCALE
);
const themePreset = useUiStore((s) => s.appSettings.themePreset);
const userName = useUiStore((s) => s.appSettings.userName);
const notify = useCallback(
(msg: string) => {
if (showToast) {
showToast(msg);
} else {
uiStoreActions.showToast(msg);
}
},
[showToast]
);
const drawerRef = useRef<HTMLDivElement>(null);
const importInputRef = useRef<HTMLInputElement>(null);
// Session initial snapshot (for Compare Original hold)
const initialAppearanceRef = useRef<AppearanceConfig>(cloneAppearance(appearance));
const latestAppearanceRef = useRef<AppearanceConfig>(appearance);
latestAppearanceRef.current = appearance;
// Undo stack & continuous slider drag snapshot
const [undoStack, setUndoStack] = useState<AppearanceConfig[]>([]);
const undoStackRef = useRef<AppearanceConfig[]>(undoStack);
undoStackRef.current = undoStack;
const dragUndoSnapshotRef = useRef<AppearanceConfig | null>(null);
const lastMixIndexRef = useRef<number>(-1);
// Axis tabs & Tier 3 disclosure
const [activeTab, setActiveTab] = useState<StudioAxisTab>('surface');
const [advancedOpen, setAdvancedOpen] = useState(false);
const [tokensExpanded, setTokensExpanded] = useState(true);
// Compare Original hold state
const [isComparing, setIsComparing] = useState(false);
const isComparingRef = useRef(false);
// Docked vs Floating draggable window state
const [isDocked, setIsDocked] = useState(true);
const [floatPos, setFloatPos] = useState<{ x: number; y: number }>({ x: 0, y: 44 });
const [isDraggingWindow, setIsDraggingWindow] = useState(false);
// Interface Scale draft state (never triggers root zoom thrash while dragging)
const [draftScale, setDraftScale] = useState<number>(() => clampInterfaceScale(committedScale));
useEffect(() => {
setDraftScale(clampInterfaceScale(committedScale));
}, [committedScale]);
// Custom hex draft inputs
const [customAccentDraft, setCustomAccentDraft] = useState(appearance.customAccentHex);
const [customMatteDraft, setCustomMatteDraft] = useState(appearance.canvasMatteCustomHex);
const [tokenDrafts, setTokenDrafts] = useState<Partial<Record<OverridableTokenKey, string>>>({});
useEffect(() => {
setCustomAccentDraft(appearance.customAccentHex);
}, [appearance.customAccentHex]);
useEffect(() => {
setCustomMatteDraft(appearance.canvasMatteCustomHex);
}, [appearance.canvasMatteCustomHex]);
// Theme code sharing UI state
const [pastePanelOpen, setPastePanelOpen] = useState(false);
const [pasteCodeDraft, setPasteCodeDraft] = useState('');
const [pasteError, setPasteError] = useState<string | null>(null);
const [justCopied, setJustCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const resolvedTheme = useMemo(() => resolveAppearanceTokens(appearance), [appearance]);
const anchorPresetId: BuiltInLookPresetId =
appearance.lookPreset === 'custom'
? (appearance.baseLookPreset ?? 'graphite-atelier')
: appearance.lookPreset;
const anchorPreset = LOOK_PRESETS[anchorPresetId] ?? LOOK_PRESETS['graphite-atelier'];
const activeOverrideCount = useMemo(
() => Object.keys(appearance.tokenOverrides ?? {}).length,
[appearance.tokenOverrides]
);
// Clean up timers & ensure current draft tokens are restored on unmount
useEffect(() => {
return () => {
if (copiedTimerRef.current) clearTimeout(copiedTimerRef.current);
if (isComparingRef.current) {
isComparingRef.current = false;
applyAppearanceToDocument(latestAppearanceRef.current, {
themePreset,
legacyAccent: latestAppearanceRef.current.accent,
});
}
};
}, [themePreset]);
// Escape key to close (non-blocking — ignores when editing a text input or when another modal is open)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key !== 'Escape' || e.defaultPrevented) return;
if (selectIsAnyModalOpen(useUiStore.getState())) return;
const target = e.target as HTMLElement | null;
if (
target &&
drawerRef.current?.contains(target) &&
(target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')
) {
const inputType = ((target as HTMLInputElement).type || 'text').toLowerCase();
if (inputType !== 'range' && inputType !== 'checkbox' && inputType !== 'button') {
e.preventDefault();
target.blur?.();
if (pastePanelOpen) {
setPastePanelOpen(false);
setPasteError(null);
}
return;
}
}
e.preventDefault();
uiStoreActions.setAppearanceStudioOpen(false);
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [pastePanelOpen]);
const pushUndoSnapshot = useCallback((snapshot: AppearanceConfig) => {
setUndoStack((prev) => {
const last = prev[prev.length - 1];
if (last && areAppearancesEqual(last, snapshot)) return prev;
const next = [...prev, cloneAppearance(snapshot)];
return next.length > MAX_UNDO_STEPS ? next.slice(next.length - MAX_UNDO_STEPS) : next;
});
}, []);
/** Discrete change (clicks, selects, swatches) — pushes 1 undo step and persists immediately. */
const commitAppearancePatch = useCallback(
(patch: Partial<AppearanceConfig>) => {
const current = latestAppearanceRef.current;
dragUndoSnapshotRef.current = null;
pushUndoSnapshot(current);
uiStoreActions.updateAppearance(patch, { persist: true });
},
[pushUndoSnapshot]
);
/** Full replacement (preset, mix, reset, import) — pushes 1 undo step and persists immediately. */
const commitAppearanceReplace = useCallback(
(nextConfig: AppearanceConfig) => {
const current = latestAppearanceRef.current;
dragUndoSnapshotRef.current = null;
if (!areAppearancesEqual(current, nextConfig)) {
pushUndoSnapshot(current);
}
uiStoreActions.replaceAppearance(nextConfig, { persist: true });
},
[pushUndoSnapshot]
);
/** 60fps live slider scrub — updates CSS vars & store without hammering localStorage. */
const handleLiveDialChange = useCallback((patch: Partial<AppearanceConfig>) => {
if (!dragUndoSnapshotRef.current) {
dragUndoSnapshotRef.current = cloneAppearance(latestAppearanceRef.current);
}
uiStoreActions.updateAppearance(patch, { persist: false });
}, []);
/** Finalizes a slider scrub — records 1 undo step and persists to storage. */
const handleLiveDialCommit = useCallback(
(patch: Partial<AppearanceConfig>) => {
const beforeDrag = dragUndoSnapshotRef.current ?? cloneAppearance(latestAppearanceRef.current);
dragUndoSnapshotRef.current = null;
uiStoreActions.updateAppearance(patch, { persist: true });
const afterDrag = useUiStore.getState().appSettings.appearance;
if (!areAppearancesEqual(beforeDrag, afterDrag)) {
pushUndoSnapshot(beforeDrag);
}
},
[pushUndoSnapshot]
);
// =========================================================================
// Tier 1 Actions: Look Preset, Mix/Surprise, Undo, Reset, Compare Original
// =========================================================================
const handleSelectLookPreset = useCallback(
(presetId: BuiltInLookPresetId) => {
const cur = latestAppearanceRef.current;
const next = createAppearanceFromPreset(presetId, {
accent: cur.accent,
customAccentHex: cur.customAccentHex,
cornerRadius: cur.cornerRadius,
chromeStyle: cur.chromeStyle,
floatingOpacity: cur.floatingOpacity,
density: cur.density,
fontProfile: cur.fontProfile,
iconStrokeWidth: cur.iconStrokeWidth,
sliderStyle: cur.sliderStyle,
brushListStyle: cur.brushListStyle,
layerThumbSize: cur.layerThumbSize,
scrollbarSize: cur.scrollbarSize,
});
setTokenDrafts({});
commitAppearanceReplace(next);
},
[commitAppearanceReplace]
);
const handleMixSurprise = useCallback(() => {
const cur = latestAppearanceRef.current;
const { index, name, appearance: mixed } = pickNextCuratedMix(cur, lastMixIndexRef.current);
lastMixIndexRef.current = index;
setTokenDrafts({});
commitAppearanceReplace(mixed);
notify(t('Look Mix: {name}', { name: td(name) }));
}, [commitAppearanceReplace, notify, t, td]);
const handleUndoTweak = useCallback(() => {
const stack = undoStackRef.current;
if (stack.length === 0) return;
const target = stack[stack.length - 1];
const nextStack = stack.slice(0, -1);
undoStackRef.current = nextStack;
dragUndoSnapshotRef.current = null;
setUndoStack(nextStack);
setTokenDrafts({});
uiStoreActions.replaceAppearance(target, { persist: true });
}, []);
const handleResetDefault = useCallback(() => {
setTokenDrafts({});
commitAppearanceReplace({ ...DEFAULT_APPEARANCE_CONFIG });
notify(t('Appearance reset to Graphite Atelier'));
}, [commitAppearanceReplace, notify, t]);
// Compare Original (Hold) — previews session-initial theme (or factory default if unchanged)
const stopCompareOriginal = useCallback(() => {
if (!isComparingRef.current) return;
isComparingRef.current = false;
setIsComparing(false);
const current = latestAppearanceRef.current;
applyAppearanceToDocument(current, {
themePreset,
legacyAccent: current.accent,
});
}, [themePreset]);
const startCompareOriginal = useCallback(() => {
if (isComparingRef.current) return;
isComparingRef.current = true;
setIsComparing(true);
const current = latestAppearanceRef.current;
const sessionInitial = initialAppearanceRef.current;
const compareTarget = areAppearancesEqual(current, sessionInitial)
? DEFAULT_APPEARANCE_CONFIG
: sessionInitial;
applyAppearanceToDocument(compareTarget, {
themePreset,
legacyAccent: compareTarget.accent,
});
const handleRelease = () => {
window.removeEventListener('pointerup', handleRelease);
window.removeEventListener('pointercancel', handleRelease);
window.removeEventListener('blur', handleRelease);
stopCompareOriginal();
};
window.addEventListener('pointerup', handleRelease);
window.addEventListener('pointercancel', handleRelease);
window.addEventListener('blur', handleRelease);
}, [stopCompareOriginal, themePreset]);
// =========================================================================
// Draggable / Dockable Header Handler
// =========================================================================
const handleHeaderDragStart = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (e.button !== 0) return;
const target = e.target as HTMLElement | null;
if (target?.closest?.('button, input')) return;
e.preventDefault();
e.stopPropagation();
const releaseGuard = acquireWorkspaceInteractionLock('appearance-drawer-drag');
const el = drawerRef.current;
const rect = el?.getBoundingClientRect();
const startX = e.clientX;
const startY = e.clientY;
const origLeft =
!isDocked
? floatPos.x
: rect && rect.width > 0
? rect.left
: Math.max(8, (typeof window !== 'undefined' ? window.innerWidth : 1280) - DRAWER_WIDTH - 10);
const origTop = !isDocked ? floatPos.y : rect && rect.top > 0 ? rect.top : 44;
let moved = false;
const clampPos = (rawX: number, rawY: number) => {
const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
return {
x: Math.max(8, Math.min(vw - DRAWER_WIDTH - 8, Math.round(rawX))),
y: Math.max(40, Math.min(vh - 140, Math.round(rawY))),
};
};
const onMove = (ev: PointerEvent) => {
const dx = ev.clientX - startX;
const dy = ev.clientY - startY;
if (!moved) {
if (Math.hypot(dx, dy) < 4) return;
moved = true;
setIsDraggingWindow(true);
setIsDocked(false);
}
setFloatPos(clampPos(origLeft + dx, origTop + dy));
};
const onUp = (ev: PointerEvent) => {
releaseGuard();
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onUp);
setIsDraggingWindow(false);
if (!moved) return;
const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
const finalPos = clampPos(origLeft + (ev.clientX - startX), origTop + (ev.clientY - startY));
if (finalPos.x >= vw - DRAWER_WIDTH - 22) {
setIsDocked(true);
} else {
setFloatPos(finalPos);
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onUp);
},
[floatPos.x, floatPos.y, isDocked]
);
// =========================================================================
// Tier 3 Actions: Token Overrides & .inktheme Export / Import / Share Code
// =========================================================================
const handleSetTokenOverride = useCallback(
(key: OverridableTokenKey, value: string) => {
const trimmed = value.trim();
if (!isValidOverrideColorValue(trimmed)) return;
const cur = latestAppearanceRef.current;
const nextOverrides: AppearanceTokenOverrides = {
...(cur.tokenOverrides ?? {}),
[key]: trimmed,
};
commitAppearancePatch({ tokenOverrides: nextOverrides });
},
[commitAppearancePatch]
);
const handleResetSingleToken = useCallback(
(key: OverridableTokenKey) => {
const cur = latestAppearanceRef.current;
if (!cur.tokenOverrides || !(key in cur.tokenOverrides)) return;
const nextOverrides: AppearanceTokenOverrides = { ...cur.tokenOverrides };
delete nextOverrides[key];
setTokenDrafts((prev) => {
const copy = { ...prev };
delete copy[key];
return copy;
});
commitAppearanceReplace({
...cur,
tokenOverrides: Object.keys(nextOverrides).length > 0 ? nextOverrides : undefined,
});
},
[commitAppearanceReplace]
);
const handleClearAllOverrides = useCallback(() => {
const cur = latestAppearanceRef.current;
if (!cur.tokenOverrides) return;
setTokenDrafts({});
commitAppearanceReplace({
...cur,
tokenOverrides: undefined,
});
notify(t('Custom token overrides cleared'));
}, [commitAppearanceReplace, notify, t]);
const handleExportThemeFile = useCallback(async () => {
const cur = latestAppearanceRef.current;
const baseName =
cur.lookPreset === 'custom'
? `${LOOK_PRESETS[cur.baseLookPreset ?? 'graphite-atelier'].label} Custom`
: LOOK_PRESETS[cur.lookPreset].label;
const json = serializeThemePreset(cur, {
name: baseName,
author: userName?.trim() || undefined,
createdAt: new Date().toISOString(),
});
const fileName = `${slugifyThemeName(baseName)}.inktheme`;
try {
const res = await saveFileWithDialog({
data: json,
suggestedName: fileName,
mimeType: 'application/json;charset=utf-8',
description: t('Ink Studio Theme'),
extensions: ['.inktheme', '.json'],
category: 'theme',
title: t('Save Theme As'),
});
if (res.canceled) return;
notify(t('Exported {fileName}', { fileName: res.fileName }));
} catch {
notify(t('Unable to export .inktheme file'));
}
}, [notify, t, userName]);
const handleImportThemeFile = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = '';
if (!file) return;
try {
const rawText = await file.text();
const result = parseThemePreset(rawText);
if (!result.ok) {
notify(t('Import failed: {error}', { error: result.error }));
return;
}
setTokenDrafts({});
commitAppearanceReplace(result.preset.appearance);
if (result.warnings.length > 0) {
notify(
t('Imported theme "{name}" ({count} dial clamped)', {
name: td(result.preset.name),
count: result.warnings.length,
})
);
} else {
notify(t('Imported theme "{name}"', { name: td(result.preset.name) }));
}
} catch {
notify(t('Failed to read .inktheme file'));
}
},
[commitAppearanceReplace, notify, t, td]
);
const handleCopyThemeCode = useCallback(async () => {
const cur = latestAppearanceRef.current;
const baseName =
cur.lookPreset === 'custom'
? `${LOOK_PRESETS[cur.baseLookPreset ?? 'graphite-atelier'].label} Custom`
: LOOK_PRESETS[cur.lookPreset].label;
const code = encodeThemeShareCode(cur, {
name: baseName,
author: userName?.trim() || undefined,
});
let copied = false;
try {
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(code);
copied = true;
}
} catch {
copied = false;
}
if (!copied && typeof document !== 'undefined') {
try {
const ta = document.createElement('textarea');
ta.value = code;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select?.();
copied = typeof document.execCommand === 'function' && document.execCommand('copy');
document.body.removeChild(ta);
} catch {
copied = false;
}
}
if (copied) {
setJustCopied(true);
if (copiedTimerRef.current) clearTimeout(copiedTimerRef.current);
copiedTimerRef.current = setTimeout(() => setJustCopied(false), 1800);
notify(t('Theme code copied to clipboard'));
} else {
setPastePanelOpen(true);
setPasteCodeDraft(code);
setPasteError(null);
notify(t('Theme code ready to copy below'));
}
}, [notify, t, userName]);
const handleApplyPastedCode = useCallback(() => {
const result = decodeThemeShareCode(pasteCodeDraft);
if (!result.ok) {
setPasteError(result.error);
notify(t('Invalid theme code: {error}', { error: result.error }));
return;
}
setPasteError(null);
setPasteCodeDraft('');
setPastePanelOpen(false);
setTokenDrafts({});
commitAppearanceReplace(result.preset.appearance);
if (result.warnings.length > 0) {
notify(
t('Applied theme "{name}" ({count} dial clamped)', {
name: td(result.preset.name),
count: result.warnings.length,
})
);
} else {
notify(t('Applied theme "{name}"', { name: td(result.preset.name) }));
}
}, [commitAppearanceReplace, notify, pasteCodeDraft, t, td]);
// Localized option lists (recomputed live on language switch)
const localizedAxisTabs = useMemo(
() =>
AXIS_TABS.map((tab) => ({
...tab,
label: tc('appearanceTab', tab.label),
...(tab.title ? { title: t(tab.title) } : {}),
})),
[t, tc]
);
const localizedCanvasMatteOptions = useMemo(
() =>
CANVAS_MATTE_OPTIONS.map((opt) => ({
...opt,
label:
opt.value === 'neutral-dark' || opt.value === 'neutral-light'
? tc('theme', opt.label)
: t(opt.label),
title: t(opt.title),
})),
[t, tc]
);
const localizedCornerRadiusOptions = useMemo(
() =>
CORNER_RADIUS_OPTIONS.map((opt) => ({
...opt,
label: tc('cornerRadius', opt.label),
})),
[tc]
);
const localizedChromeStyleOptions = useMemo(
() => CHROME_STYLE_OPTIONS.map((opt) => ({ ...opt, label: tc('chromeStyle', opt.label) })),
[tc]
);
const localizedDensityOptions = useMemo(
() => DENSITY_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })),
[t]
);
const localizedFontProfileOptions = useMemo(
() => FONT_PROFILE_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })),
[t]
);
const localizedIconWeightOptions = useMemo(
() => ICON_WEIGHT_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })),
[t]
);
const localizedSliderStyleOptions = useMemo(
() => SLIDER_STYLE_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })),
[t]
);
const localizedBrushListOptions = useMemo(
() =>
BRUSH_LIST_OPTIONS.map((opt) => ({
...opt,
label: opt.value === 'stroke' ? tc('brushStudio', opt.label) : t(opt.label),
})),
[t, tc]
);
const localizedLayerThumbOptions = useMemo(
() => LAYER_THUMB_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })),
[t]
);
const localizedScrollbarSizeOptions = useMemo(
() =>
SCROLLBAR_SIZE_OPTIONS.map((opt) => ({
...opt,
label: t(opt.label),
title: t(opt.title),
})),
[t]
);
// =========================================================================
// Contrast Indicators (Live WCAG 2.1)
// =========================================================================
const primaryRatio = resolvedTheme.contrast.primaryOnPanel;
const mutedRatio = resolvedTheme.contrast.mutedOnPanel;
const primaryGrade = getContrastGrade(primaryRatio);
const primaryGradeLabel = td(primaryGrade.label, 'contrast');
const hasContrastWarning = primaryRatio < 4.5 || mutedRatio < 3.0;
const drawerStyle: React.CSSProperties = isDocked
? {
position: 'fixed',
top: 44,
right: 10,
bottom: 32,
width: DRAWER_WIDTH,
zIndex: 46,
}
: {
position: 'fixed',
left: floatPos.x,
top: floatPos.y,
width: DRAWER_WIDTH,
maxHeight: 'calc(100vh - 64px)',
zIndex: 46,
};
const activeSurfaceBase: BuiltInLookPresetId = anchorPresetId;
return (
<aside
ref={drawerRef}
role="region"
aria-label={t('Appearance Studio')}
data-testid="appearance-studio-drawer"
data-docked={isDocked ? 'true' : 'false'}
data-comparing={isComparing ? 'true' : 'false'}
style={drawerStyle}
className={`pointer-events-auto flex flex-col overflow-hidden rounded-ui-lg bg-ui-floating border text-ui-primary shadow-ui-floating backdrop-blur-md select-none ui-icon-stroke ${
isDraggingWindow ? 'border-ui-strong shadow-ui-popover' : 'border-ui-default'
}`}
>
{/* Hidden .inktheme File Input */}
<input
ref={importInputRef}
type="file"
data-testid="appearance-import-file-input"
accept=".inktheme,.json,application/json"
onChange={handleImportThemeFile}
className="hidden"
/>
{/* Slim Draggable Studio Header */}
<div
data-testid="appearance-studio-drag-handle"
onPointerDown={handleHeaderDragStart}
onDoubleClick={(e) => {
if ((e.target as HTMLElement)?.closest?.('button')) return;
setIsDocked(true);
}}
title={
isDocked
? t('Drag to float Appearance Studio over canvas')
: t('Drag to move · Double-click to re-dock right')
}
className="h-8 px-2 flex items-center justify-between gap-1.5 shrink-0 bg-ui-header border-b border-ui-subtle cursor-grab active:cursor-grabbing"
>
<div className="flex items-center gap-1.5 min-w-0">
<GripVertical className="w-3 h-3 text-ui-icon-muted shrink-0" />
<Palette className="w-3.5 h-3.5 text-ui-accent shrink-0" />
<span className="text-[11px] font-medium text-ui-primary truncate">
{t('Appearance Studio')}
</span>
</div>
<div className="flex items-center gap-0.5 shrink-0">
{/* Compare Original (Hold) */}
<button
type="button"
data-testid="appearance-compare-btn"
aria-pressed={isComparing}
title={t('Hold to temporarily compare with original look')}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
startCompareOriginal();
}}
onPointerUp={(e) => {
e.stopPropagation();
stopCompareOriginal();
}}
onPointerCancel={(e) => {
e.stopPropagation();
stopCompareOriginal();
}}
onKeyDown={(e) => {
if ((e.key === ' ' || e.key === 'Enter') && !e.repeat) {
e.preventDefault();
startCompareOriginal();
}
}}
onKeyUp={(e) => {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
stopCompareOriginal();
}
}}
onBlur={stopCompareOriginal}
className={`h-5 px-1.5 rounded-ui-xs border text-[10px] font-medium flex items-center gap-1 transition-colors cursor-pointer ${
isComparing
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
: 'bg-ui-control text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border-ui-subtle'
}`}
>
<Eye className="w-3 h-3 shrink-0" />
<span>{isComparing ? t('Original') : t('Compare')}</span>
</button>
{!isDocked && (
<IconButton
data-testid="appearance-dock-btn"
size="xs"
icon={<PanelRight className="w-3 h-3" />}
title={t('Dock to Right Edge')}
onClick={() => setIsDocked(true)}
/>
)}
<IconButton
data-testid="appearance-close-btn"
size="xs"
icon={<X className="w-3 h-3" />}
title={t('Close Appearance Studio (Esc)')}
onClick={() => uiStoreActions.setAppearanceStudioOpen(false)}
/>
</div>
</div>
{/* ================================================================= */}
{/* TIER 1 — INSTANT LOOK BAR (Always pinned at top, 1 click) */}
{/* ================================================================= */}
<div className="p-2 bg-ui-panel border-b border-ui-subtle shrink-0 space-y-2">
<div
className="grid grid-cols-3 gap-1.5"
data-testid="appearance-look-presets-grid"
>
{BUILT_IN_LOOK_PRESET_IDS.map((presetId) => (
<LookPresetCard
key={presetId}
presetId={presetId}
active={appearance.lookPreset === presetId && activeOverrideCount === 0}
accent={appearance.accent}
customAccentHex={appearance.customAccentHex}
onSelect={handleSelectLookPreset}
compact
/>
))}
</div>
{/* Compact Action Strip: Mix / Undo / Reset */}
<div className="flex items-center gap-1">
<IconButton
data-testid="appearance-mix-btn"
size="xs"
variant="subtle"
icon={<Shuffle className="w-3 h-3 text-ui-accent" />}
label={t('Mix')}
title={t('Cycle curated harmonious look combinations')}
onClick={handleMixSurprise}
className="flex-1"
/>
<IconButton
data-testid="appearance-undo-btn"
size="xs"
variant="subtle"
icon={<Undo2 className="w-3 h-3" />}
label={t('Undo')}
title={
undoStack.length > 0
? t('Undo last tweak ({count} available)', { count: undoStack.length })
: t('No tweaks to undo yet')
}
disabled={undoStack.length === 0}
onClick={handleUndoTweak}
className="flex-1"
/>
<IconButton
data-testid="appearance-reset-btn"
size="xs"
variant="subtle"
icon={<RotateCcw className="w-3 h-3" />}
label={t('Reset')}
title={t('Reset appearance to Graphite Atelier defaults')}
onClick={handleResetDefault}
className="flex-1"
/>
</div>
</div>
{/* ================================================================= */}
{/* TIER 2 — 5 FOCUSED LIVE AXES (Tabbed) */}
{/* ================================================================= */}
<div className="px-2 bg-ui-header shrink-0">
<HairlineTabs<StudioAxisTab>
data-testid="appearance-axis-tabs"
aria-label={t('Appearance categories')}
value={activeTab}
tabs={localizedAxisTabs}
onChange={setActiveTab}
size="xs"
fullWidth
className="!gap-1"
/>
</div>
{/* Scrollable Body (Tier 2 Active Axis + Tier 3 Accordion) */}
<div className="flex-1 min-h-0 overflow-y-auto bg-ui-panel flex flex-col">
<div className="p-2.5 space-y-3">
{/* ------------------------------------------------------------- */}
{/* TAB 1: SURFACE & COLOR */}
{/* ------------------------------------------------------------- */}
{activeTab === 'surface' && (
<>
<div className="space-y-1.5">
<ScrubSlider
data-testid="appearance-brightness-slider"
label={t('Surface Brightness')}
min={APPEARANCE_LIMITS.surfaceBrightness.min}
max={APPEARANCE_LIMITS.surfaceBrightness.max}
step={1}
defaultValue={0}
value={appearance.surfaceBrightness}
formatValue={(v) => (v > 0 ? `+${Math.round(v)}` : `${Math.round(v)}`)}
onChange={(v) =>
handleLiveDialChange({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceBrightness: v,
})
}
onCommit={(v) =>
handleLiveDialCommit({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceBrightness: v,
})
}
/>
<ScrubSlider
data-testid="appearance-contrast-slider"
label={t('Contrast & Seams')}
min={APPEARANCE_LIMITS.surfaceContrast.min}
max={APPEARANCE_LIMITS.surfaceContrast.max}
step={0.02}
fineStep={0.01}
defaultValue={anchorPreset.defaultContrast}
value={appearance.surfaceContrast}
formatValue={(v) => `${Math.round(v * 100)}%`}
parseValue={(raw) => {
const n = parseFloat(raw.replace('%', '').trim());
if (!Number.isFinite(n)) return null;
return n > 5 ? n / 100 : n;
}}
onChange={(v) =>
handleLiveDialChange({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceContrast: v,
})
}
onCommit={(v) =>
handleLiveDialCommit({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceContrast: v,
})
}
/>
<div className="space-y-1">
<ScrubSlider
data-testid="appearance-warmth-slider"
label={t('Surface Warmth')}
min={APPEARANCE_LIMITS.surfaceWarmth.min}
max={APPEARANCE_LIMITS.surfaceWarmth.max}
step={1}
defaultValue={0}
value={appearance.surfaceWarmth}
formatValue={(v) => {
const r = Math.round(v);
if (r === 0) return t('Neutral 0');
return r > 0 ? t('+{n} Warm', { n: r }) : t('{n} Cool', { n: r });
}}
onChange={(v) =>
handleLiveDialChange({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceWarmth: v,
})
}
onCommit={(v) =>
handleLiveDialCommit({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceWarmth: v,
})
}
/>
<div className="flex items-center justify-between text-[9.5px] text-ui-muted px-0.5">
<span>{t('Cool Slate')}</span>
<button
type="button"
data-testid="appearance-warmth-neutral-btn"
onClick={() =>
commitAppearancePatch({
lookPreset: 'custom',
baseLookPreset: activeSurfaceBase,
surfaceWarmth: 0,
})
}
className={`px-1.5 py-[1px] rounded-ui-xs border font-ui-mono tabular-nums transition-colors cursor-pointer ${
appearance.surfaceWarmth === 0
? 'bg-ui-control-active text-ui-primary border-ui-default'
: 'bg-ui-input text-ui-muted hover:text-ui-primary border-ui-subtle'
}`}
title={t('Snap surface tint to strictly achromatic neutral 0')}
>
{t('Neutral 0')}
</button>
<span>{t('Warm Sumi')}</span>
</div>
</div>
</div>
{/* Accent Pigment Swatch Row */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[10.5px] font-medium text-ui-secondary">
{t('Accent Pigment')}
</span>
<span className="text-[10px] font-ui-mono text-ui-muted">
{appearance.accent === 'custom'
? appearance.customAccentHex
: td(ACCENT_PIGMENTS[appearance.accent].label)}
</span>
</div>
<div className="flex items-center gap-1" data-testid="appearance-accent-swatches">
{BUILT_IN_ACCENT_PIGMENT_IDS.map((pigmentId) => {
const def = ACCENT_PIGMENTS[pigmentId];
const tone = def[resolvedTheme.colorScheme];
const swatchHex = oklchToHex(tone.l, tone.c, tone.h);
const isSelected = appearance.accent === pigmentId;
return (
<button
key={pigmentId}
type="button"
data-testid={`appearance-accent-${pigmentId}`}
aria-label={td(def.label)}
aria-pressed={isSelected}
title={`${td(def.label)} — ${td(def.description)}`}
onClick={() => commitAppearancePatch({ accent: pigmentId })}
className={`flex-1 h-7 rounded-ui-sm border flex items-center justify-center transition-colors cursor-pointer focus:outline-none focus-visible:border-ui-focus ${
isSelected
? 'bg-ui-control-active border-ui-accent'
: 'bg-ui-input border-ui-subtle hover:border-ui-default'
}`}
>
<span
className="w-3.5 h-3.5 rounded-full border border-ui-strong/60 flex items-center justify-center"
style={{ backgroundColor: swatchHex }}
>
{isSelected && (
<span
className="w-1.5 h-1.5 rounded-full"
style={{ backgroundColor: resolvedTheme.tokens['--ui-accent-contrast'] }}
/>
)}
</span>
</button>
);
})}
{/* Custom Accent Swatch */}
<button
type="button"
data-testid="appearance-accent-custom"
aria-label={t('Custom Accent Pigment')}
aria-pressed={appearance.accent === 'custom'}
title={t('Custom Accent Hex')}
onClick={() => commitAppearancePatch({ accent: 'custom' })}
className={`h-7 px-2 rounded-ui-sm border flex items-center gap-1 text-[10px] transition-colors cursor-pointer focus:outline-none focus-visible:border-ui-focus ${
appearance.accent === 'custom'
? 'bg-ui-control-active border-ui-accent text-ui-primary font-medium'
: 'bg-ui-input border-ui-subtle text-ui-muted hover:text-ui-primary hover:border-ui-default'
}`}
>
<span
className="w-3 h-3 rounded-full border border-ui-strong/60 shrink-0"
style={{
backgroundColor: normalizeHex6(appearance.customAccentHex, '#e5e5e5'),
}}
/>
<span>{t('Custom')}</span>
</button>
</div>
{appearance.accent === 'custom' && (
<div className="flex items-center gap-1.5 p-1.5 rounded-ui-sm bg-ui-header border border-ui-subtle">
<input
type="color"
aria-label={t('Pick Custom Accent Color')}
data-testid="appearance-accent-custom-picker"
value={normalizeHex6(appearance.customAccentHex, '#e5e5e5')}
onChange={(e) => {
const hex = e.target.value;
setCustomAccentDraft(hex);
commitAppearancePatch({ accent: 'custom', customAccentHex: hex });
}}
className="w-6 h-6 rounded-ui-xs cursor-pointer bg-transparent border-0 p-0 shrink-0"
/>
<input
type="text"
aria-label={t('Custom Accent Hex')}
data-testid="appearance-accent-custom-hex"
value={customAccentDraft}
maxLength={7}
placeholder="#RRGGBB"
onChange={(e) => {
const val = e.target.value;
setCustomAccentDraft(val);
if (isValidHex6(val)) {
commitAppearancePatch({ accent: 'custom', customAccentHex: val });
}
}}
onBlur={() => {
setCustomAccentDraft(appearance.customAccentHex);
}}
className="flex-1 h-6 px-2 rounded-ui-xs bg-ui-input border border-ui-default font-ui-mono tabular-nums text-[11px] text-ui-primary"
/>
</div>
)}
</div>
{/* Canvas Surround (Matte) */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[10.5px] font-medium text-ui-secondary">
{t('Canvas Surround (Matte)')}
</span>
<span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
{resolvedTheme.tokens['--ui-canvas-matte']}
</span>
</div>
<SegmentedControl<CanvasMatteMode>
data-testid="appearance-matte-mode"
aria-label={t('Canvas Surround Matte')}
value={appearance.canvasMatteMode}
options={localizedCanvasMatteOptions}
onChange={(mode) => commitAppearancePatch({ canvasMatteMode: mode })}
size="xs"
fullWidth
/>
{appearance.canvasMatteMode === 'custom' && (
<div className="flex items-center gap-1.5 p-1.5 rounded-ui-sm bg-ui-header border border-ui-subtle">
<input
type="color"
aria-label={t('Pick Custom Canvas Matte Color')}
data-testid="appearance-matte-custom-picker"
value={normalizeHex6(appearance.canvasMatteCustomHex, '#161616')}
onChange={(e) => {
const hex = e.target.value;
setCustomMatteDraft(hex);
commitAppearancePatch({
canvasMatteMode: 'custom',
canvasMatteCustomHex: hex,
});
}}
className="w-6 h-6 rounded-ui-xs cursor-pointer bg-transparent border-0 p-0 shrink-0"
/>
<input
type="text"
aria-label={t('Custom Canvas Matte Hex')}
data-testid="appearance-matte-custom-hex"
value={customMatteDraft}
maxLength={7}
placeholder="#161616"
onChange={(e) => {
const val = e.target.value;
setCustomMatteDraft(val);
if (isValidHex6(val)) {
commitAppearancePatch({
canvasMatteMode: 'custom',
canvasMatteCustomHex: val,
});
}
}}
onBlur={() => {
setCustomMatteDraft(appearance.canvasMatteCustomHex);
}}
className="flex-1 h-6 px-2 rounded-ui-xs bg-ui-input border border-ui-default font-ui-mono tabular-nums text-[11px] text-ui-primary"
/>
</div>
)}
</div>
</>
)}
{/* ------------------------------------------------------------- */}
{/* TAB 2: SHAPE & CHROME */}
{/* ------------------------------------------------------------- */}
{activeTab === 'chrome' && (
<>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Corner Radius')}
</span>
<SegmentedControl<CornerRadiusPreset>
data-testid="appearance-corner-radius"
aria-label={t('Corner Radius')}
value={appearance.cornerRadius}
options={localizedCornerRadiusOptions}
onChange={(cornerRadius) => commitAppearancePatch({ cornerRadius })}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Panel Style')}
</span>
<SegmentedControl<ChromeStyle>
data-testid="appearance-chrome-style"
aria-label={t('Panel Style')}
value={appearance.chromeStyle}
options={localizedChromeStyleOptions}
onChange={(chromeStyle) => commitAppearancePatch({ chromeStyle })}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1.5 pt-0.5">
<ScrubSlider
data-testid="appearance-border-crispness-slider"
label={t('Border Crispness')}
min={APPEARANCE_LIMITS.borderCrispness.min}
max={APPEARANCE_LIMITS.borderCrispness.max}
step={1}
defaultValue={anchorPreset.defaultBorderCrispness}
unit="%"
value={appearance.borderCrispness}
onChange={(borderCrispness) => handleLiveDialChange({ borderCrispness })}
onCommit={(borderCrispness) => handleLiveDialCommit({ borderCrispness })}
/>
<ScrubSlider
data-testid="appearance-floating-opacity-slider"
label={t('Floating Panel Opacity')}
variant="opacity"
min={65}
max={100}
step={1}
defaultValue={96}
unit="%"
value={Math.round(appearance.floatingOpacity * 100)}
onChange={(pct) =>
handleLiveDialChange({
floatingOpacity: Math.round(pct) / 100,
})
}
onCommit={(pct) =>
handleLiveDialCommit({
floatingOpacity: Math.round(pct) / 100,
})
}
/>
</div>
</>
)}
{/* ------------------------------------------------------------- */}
{/* TAB 3: DENSITY & TYPE */}
{/* ------------------------------------------------------------- */}
{activeTab === 'density' && (
<>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Interface Density')}
</span>
<SegmentedControl<DensityPreset>
data-testid="appearance-density"
aria-label={t('Interface Density')}
value={appearance.density}
options={localizedDensityOptions}
onChange={(density) => commitAppearancePatch({ density })}
size="sm"
fullWidth
/>
</div>
{/* Interface Scale — drags draftScale cleanly, commits on release/chip */}
<div className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[10.5px] font-medium text-ui-secondary">
{t('Interface Scale')}
</span>
{draftScale !== committedScale && (
<span className="text-[9.5px] font-ui-mono text-ui-accent">
{t('Release to apply')}
</span>
)}
</div>
<ScrubSlider
data-testid="appearance-interface-scale-slider"
label={t('UI Scale')}
min={MIN_INTERFACE_SCALE}
max={MAX_INTERFACE_SCALE}
step={INTERFACE_SCALE_STEP}
defaultValue={DEFAULT_INTERFACE_SCALE}
unit="%"
value={draftScale}
onChange={(next) => setDraftScale(clampInterfaceScale(next))}
onCommit={(next) => {
const clamped = clampInterfaceScale(next);
setDraftScale(clamped);
uiStoreActions.updateInterfaceScale(clamped, { persist: true });
}}
/>
<div className="grid grid-cols-6 gap-1">
{INTERFACE_SCALE_PRESETS.map((preset) => {
const isSelected = draftScale === preset;
return (
<button
key={preset}
type="button"
data-testid={`appearance-scale-chip-${preset}`}
onClick={() => {
setDraftScale(preset);
uiStoreActions.updateInterfaceScale(preset, { persist: true });
}}
className={`h-5 rounded-ui-xs border font-ui-mono tabular-nums text-[9.5px] transition-colors cursor-pointer ${
isSelected
? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
: 'bg-ui-input text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-ui-subtle'
}`}
>
{preset}%
</button>
);
})}
</div>
</div>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Typography')}
</span>
<SegmentedControl<FontProfile>
data-testid="appearance-font-profile"
aria-label={t('Typography')}
value={appearance.fontProfile}
options={localizedFontProfileOptions}
onChange={(fontProfile) => commitAppearancePatch({ fontProfile })}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Icon Weight')}
</span>
<SegmentedControl<'1.25' | '1.5' | '1.85'>
data-testid="appearance-icon-weight"
aria-label={t('Icon Weight')}
value={String(appearance.iconStrokeWidth) as '1.25' | '1.5' | '1.85'}
options={localizedIconWeightOptions}
onChange={(val) =>
commitAppearancePatch({
iconStrokeWidth: Number(val) as IconStrokeWidth,
})
}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1">
<div className="flex items-center justify-between">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Scrollbar Size')}
</span>
<span className="text-[9.5px] font-ui-mono tabular-nums text-ui-muted">
{resolvedTheme.tokens['--ui-scrollbar-size']}
</span>
</div>
<SegmentedControl<ScrollbarSize>
data-testid="appearance-scrollbar-size"
aria-label={t('Scrollbar Size')}
value={appearance.scrollbarSize}
options={localizedScrollbarSizeOptions}
onChange={(scrollbarSize) => commitAppearancePatch({ scrollbarSize })}
size="xs"
fullWidth
/>
</div>
</>
)}
{/* ------------------------------------------------------------- */}
{/* TAB 4: CONTROLS CRAFT */}
{/* ------------------------------------------------------------- */}
{activeTab === 'controls' && (
<>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Slider Style')}
</span>
<SegmentedControl<SliderStyle>
data-testid="appearance-slider-style"
aria-label={t('Slider Style')}
value={appearance.sliderStyle}
options={localizedSliderStyleOptions}
onChange={(sliderStyle) => commitAppearancePatch({ sliderStyle })}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Brush List View')}
</span>
<SegmentedControl<BrushListStyle>
data-testid="appearance-brush-list-style"
aria-label={t('Brush List View')}
value={appearance.brushListStyle}
options={localizedBrushListOptions}
onChange={(brushListStyle) => commitAppearancePatch({ brushListStyle })}
size="sm"
fullWidth
/>
</div>
<div className="space-y-1">
<span className="text-[10.5px] font-medium text-ui-secondary block">
{t('Layer Thumbnails')}
</span>
<SegmentedControl<LayerThumbSize>
data-testid="appearance-layer-thumb-size"
aria-label={t('Layer Thumbnails')}
value={appearance.layerThumbSize}
options={localizedLayerThumbOptions}
onChange={(layerThumbSize) => commitAppearancePatch({ layerThumbSize })}
size="sm"
fullWidth
/>
</div>
</>
)}
{/* ------------------------------------------------------------- */}
{/* TAB 5: WORKSPACE & BARS */}
{/* ------------------------------------------------------------- */}
{activeTab === 'workspace' && <WorkspaceAndBarsTab onNotify={notify} />}
</div>
{/* ================================================================= */}
{/* TIER 3 — POWER USER & COMMUNITY SHARING (Collapsed by default) */}
{/* ================================================================= */}
<SectionDisclosure
data-testid="appearance-advanced-accordion"
title={t('Advanced & Share')}
open={advancedOpen}
onToggle={() => setAdvancedOpen((prev) => !prev)}
summary={
hasContrastWarning
? t('{ratio}:1 Low', { ratio: primaryRatio.toFixed(1) })
: activeOverrideCount > 0
? `${primaryRatio.toFixed(1)}:1 ${primaryGradeLabel} · ${activeOverrideCount}`
: `${primaryRatio.toFixed(1)}:1 ${primaryGradeLabel}`
}
summaryTone={hasContrastWarning ? 'default' : 'muted'}
className="mt-auto"
bodyClassName="space-y-2.5"
>
{/* Live WCAG Contrast Status Row */}
<div
data-testid="appearance-wcag-badge"
className={`flex items-center justify-between gap-2 px-2 py-1.5 rounded-ui-sm border text-[10px] ${
hasContrastWarning
? 'bg-ui-warning/10 border-ui-warning/40 text-ui-warning'
: 'bg-ui-header border-ui-subtle text-ui-secondary'
}`}
>
<div className="flex items-center gap-1.5 min-w-0">
{hasContrastWarning && <AlertTriangle className="w-3 h-3 shrink-0" />}
<span className="truncate">
{hasContrastWarning ? t('Low contrast warning') : t('WCAG Text Contrast')}
</span>
</div>
<div className="flex items-center gap-1.5 font-ui-mono tabular-nums shrink-0">
<span
className={
primaryRatio >= 4.5 ? 'text-ui-success font-medium' : 'text-ui-danger font-medium'
}
>
{primaryRatio.toFixed(1)}:1 {primaryGradeLabel}
</span>
<span className="text-ui-muted">
{t('· Muted {ratio}:1', { ratio: mutedRatio.toFixed(1) })}
</span>
</div>
</div>
{/* Custom Token Overrides (Expandable sub-list) */}
<div className="rounded-ui-sm border border-ui-subtle bg-ui-header overflow-hidden">
<div className="flex items-center justify-between px-2 py-1 border-b border-ui-subtle">
<button
type="button"
data-testid="appearance-token-overrides-toggle"
onClick={() => setTokensExpanded((prev) => !prev)}
className="flex items-center gap-1 text-[10px] font-medium text-ui-secondary hover:text-ui-primary cursor-pointer"
>
<SlidersHorizontal className="w-3 h-3 text-ui-icon-muted" />
<span>{t('Custom Token Overrides')}</span>
{activeOverrideCount > 0 && (
<span className="font-ui-mono text-[9.5px] text-ui-accent">
({activeOverrideCount})
</span>
)}
</button>
{activeOverrideCount > 0 && (
<button
type="button"
data-testid="appearance-clear-overrides-btn"
onClick={handleClearAllOverrides}
className="text-[9.5px] text-ui-muted hover:text-ui-primary cursor-pointer"
>
{t('Clear all')}
</button>
)}
</div>
{tokensExpanded && (
<div className="divide-y divide-ui-subtle">
{OVERRIDABLE_TOKEN_ROWS.map(({ key, label }) => {
const isOverridden = Boolean(appearance.tokenOverrides?.[key]);
const resolvedVal = resolvedTheme.tokens[key];
const displayVal = tokenDrafts[key] ?? appearance.tokenOverrides?.[key] ?? resolvedVal;
const swatchHex = colorTokenToHex6(resolvedVal, '#808080');
const trLabel = t(label);
return (
<div
key={key}
data-testid={`token-override-row-${key}`}
className="flex items-center gap-1.5 px-2 py-1"
>
<span
className={`text-[10px] truncate flex-1 min-w-0 ${
isOverridden ? 'text-ui-primary font-medium' : 'text-ui-secondary'
}`}
title={key}
>
{trLabel}
</span>
<input
type="color"
aria-label={t('{label} color picker', { label: trLabel })}
data-testid={`token-picker-${key}`}
value={swatchHex}
onChange={(e) => {
const hex = e.target.value;
setTokenDrafts((prev) => ({ ...prev, [key]: hex }));
handleSetTokenOverride(key, hex);
}}
className="w-5 h-5 rounded-ui-xs cursor-pointer bg-transparent border border-ui-default p-0 shrink-0"
/>
<input
type="text"
aria-label={t('{label} color value', { label: trLabel })}
data-testid={`token-input-${key}`}
value={displayVal}
onChange={(e) => {
const val = e.target.value;
setTokenDrafts((prev) => ({ ...prev, [key]: val }));
if (isValidOverrideColorValue(val)) {
handleSetTokenOverride(key, val);
}
}}
onBlur={() => {
setTokenDrafts((prev) => {
const copy = { ...prev };
delete copy[key];
return copy;
});
}}
className="w-[84px] h-5 px-1.5 rounded-ui-xs bg-ui-input border border-ui-subtle font-ui-mono tabular-nums text-[9.5px] text-ui-primary shrink-0"
/>
<IconButton
data-testid={`token-reset-${key}`}
size="xs"
icon={<RotateCcw className="w-2.5 h-2.5" />}
title={t('Reset {label}', { label: trLabel })}
disabled={!isOverridden}
onClick={() => handleResetSingleToken(key)}
/>
</div>
);
})}
</div>
)}
</div>
{/* Theme Sharing (.inktheme Export/Import & Copy/Paste Code) */}
<div className="space-y-1.5">
<span className="text-[10px] font-medium text-ui-secondary block">
{t('Theme Sharing (.inktheme)')}
</span>
<div className="grid grid-cols-2 gap-1">
<IconButton
data-testid="appearance-export-file-btn"
size="xs"
variant="subtle"
icon={<Download className="w-3 h-3" />}
label={t('Export .inktheme')}
onClick={handleExportThemeFile}
className="w-full"
/>
<IconButton
data-testid="appearance-import-file-btn"
size="xs"
variant="subtle"
icon={<Upload className="w-3 h-3" />}
label={t('Import .inktheme')}
onClick={() => importInputRef.current?.click()}
className="w-full"
/>
<IconButton
data-testid="appearance-copy-code-btn"
size="xs"
variant="subtle"
icon={
justCopied ? (
<ClipboardCheck className="w-3 h-3 text-ui-success" />
) : (
<Copy className="w-3 h-3" />
)
}
label={justCopied ? t('Copied!') : t('Copy Code')}
onClick={() => void handleCopyThemeCode()}
className="w-full"
/>
<IconButton
data-testid="appearance-paste-code-btn"
size="xs"
variant="subtle"
active={pastePanelOpen}
icon={<Upload className="w-3 h-3" />}
label={t('Paste Code')}
onClick={() => {
setPastePanelOpen((prev) => !prev);
setPasteError(null);
}}
className="w-full"
/>
</div>
{pastePanelOpen && (
<div className="space-y-1 p-1.5 rounded-ui-sm bg-ui-header border border-ui-subtle">
<div className="flex items-center gap-1">
<input
type="text"
data-testid="appearance-paste-code-input"
aria-label={t('Paste Theme Code')}
value={pasteCodeDraft}
onChange={(e) => {
setPasteCodeDraft(e.target.value);
if (pasteError) setPasteError(null);
}}
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Enter') {
e.preventDefault();
handleApplyPastedCode();
}
}}
placeholder={t('Paste INKTHEME1:... or JSON')}
className="flex-1 min-w-0 h-6 px-1.5 rounded-ui-xs bg-ui-input border border-ui-default font-ui-mono text-[10px] text-ui-primary"
/>
<button
type="button"
data-testid="appearance-apply-code-btn"
onClick={handleApplyPastedCode}
className="h-6 px-2 rounded-ui-xs bg-ui-control-active hover:bg-ui-control-hover border border-ui-accent-border text-[10px] font-medium text-ui-primary cursor-pointer shrink-0"
>
{t('Apply')}
</button>
</div>
{pasteError && (
<p
data-testid="appearance-paste-code-error"
className="text-[9.5px] text-ui-danger leading-snug"
>
{pasteError}
</p>
)}
</div>
)}
</div>
</SectionDisclosure>
</div>
</aside>
);
};
export const AppearanceStudioDrawer: React.FC<AppearanceStudioDrawerProps> = React.memo(
({ showToast }) => {
const isOpen = useUiStore((s) => s.isAppearanceStudioOpen);
if (!isOpen) return null;
return <AppearanceStudioPanel showToast={showToast} />;
}
);
AppearanceStudioDrawer.displayName = 'AppearanceStudioDrawer';