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, { useState, useEffect, useCallback } from 'react';
import {
X,
Paintbrush,
Spline,
Grid3X3,
Layers,
Droplets,
Sparkles,
Sliders,
Info,
RotateCcw,
} from 'lucide-react';
import type { BrushCategory, BrushSettings, CspBrush } from '../types/editor';
import { useToolStore, toolStoreActions } from '../stores';
import { IconButton } from './ui';
import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';
import {
DEFAULT_BRUSH_PRESET_ID,
NEUTRAL_BRUSH_DEFAULTS,
resetBrushSettingsToDefault,
saveActivePresetId,
} from '../utils/brushPresetManager';
import {
getCachedCustomBrushes,
prepareBrushSettingsForCsp,
saveCustomBrush,
saveCustomBrushDebounced,
} from '../utils/brushStorage';
import {
buildExportableBrush,
exportBrushToInkbFile,
importBrushFile,
} from '../utils/inkbBrushFormat';
import { BrushStudioScratchpad } from './brushStudio/BrushStudioScratchpad';
import {
DualBrushTab,
ShapeBristlesTab,
StrokeTaperTab,
TextureGrainTab,
} from './brushStudio/BrushStudioTabsPrimary';
import {
AboutPresetsTab,
DynamicsSensorMatrixTab,
ImpastoWetEdgeTab,
NaturalPaintMixingTab,
} from './brushStudio/BrushStudioTabsSecondary';
import { isImeComposing, useI18n } from '../i18n';
type StudioTabId =
| 'shape'
| 'stroke'
| 'texture'
| 'dual'
| 'mixing'
| 'impasto'
| 'dynamics'
| 'about';
const STUDIO_TABS: Array<{ id: StudioTabId; label: string; icon: React.ReactNode }> = [
{ id: 'shape', label: 'Shape & Bristles', icon: <Paintbrush className="w-3.5 h-3.5" /> },
{ id: 'stroke', label: 'Stroke & Taper', icon: <Spline className="w-3.5 h-3.5" /> },
{ id: 'texture', label: 'Texture & Grain', icon: <Grid3X3 className="w-3.5 h-3.5" /> },
{ id: 'dual', label: 'Dual Brush', icon: <Layers className="w-3.5 h-3.5" /> },
{ id: 'mixing', label: 'Natural Paint', icon: <Droplets className="w-3.5 h-3.5" /> },
{ id: 'impasto', label: 'Impasto & Wet', icon: <Sparkles className="w-3.5 h-3.5" /> },
{ id: 'dynamics', label: 'Sensor Matrix', icon: <Sliders className="w-3.5 h-3.5" /> },
{ id: 'about', label: 'About & Presets', icon: <Info className="w-3.5 h-3.5" /> },
];
export interface BrushStudioModalProps {
isOpen: boolean;
onClose: () => void;
showToast?: (msg: string) => void;
}
export const BrushStudioModal: React.FC<BrushStudioModalProps> = ({
isOpen,
onClose,
showToast,
}) => {
const { t, tc, td } = useI18n();
const brushSettings = useToolStore((s) => s.brushSettings);
const activePreset = useToolStore((s) => s.activePresetId) || DEFAULT_BRUSH_PRESET_ID;
const [activeTab, setActiveTab] = useState<StudioTabId>('shape');
const [brushName, setBrushName] = useState<string>(brushSettings.brushName || 'Brush');
const [category, setCategory] = useState<BrushCategory | 'custom'>('natural-paint');
const [description, setDescription] = useState<string>('');
useEffect(() => {
if (!isOpen) return;
const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === activePreset);
const custom = getCachedCustomBrushes().find((b) => b.id === activePreset);
setBrushName(custom?.name || builtin?.name || brushSettings.brushName || 'Custom Brush');
setCategory(custom?.category || builtin?.category || 'custom');
setDescription(custom?.desc || builtin?.desc || '');
}, [isOpen, activePreset, brushSettings.brushName]);
useEffect(() => {
if (!isOpen) return;
const onKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') {
e.stopPropagation();
onClose();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [isOpen, onClose]);
const handlePatchSettings = useCallback(
(patch: Partial<BrushSettings>) => {
toolStoreActions.updateBrushSettings(patch);
const custom = getCachedCustomBrushes().find((b) => b.id === activePreset);
if (custom) {
const merged = { ...useToolStore.getState().brushSettings, ...patch };
const updated: CspBrush = {
...buildExportableBrush(activePreset, getCachedCustomBrushes(), merged),
id: custom.id,
name: brushName || custom.name,
category,
desc: description,
badge: custom.badge || 'INKB',
};
saveCustomBrushDebounced(updated);
}
},
[activePreset, brushName, category, description]
);
const handleSaveAsNewPreset = async (suffix: string = '') => {
const live = useToolStore.getState().brushSettings;
const baseName = td(brushName || live.brushName || t('Custom Brush')).trim();
const finalName = suffix === 'Copy' ? t('{name} Copy', { name: baseName }) : suffix ? `${baseName} ${suffix}` : baseName;
const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const exported = buildExportableBrush(activePreset, getCachedCustomBrushes(), live);
const newBrush: CspBrush = {
...exported,
id,
name: finalName,
category,
desc: description || exported.desc,
badge: 'Studio',
importedAt: Date.now(),
};
await saveCustomBrush(newBrush);
saveActivePresetId(newBrush.id);
const prepared = await prepareBrushSettingsForCsp(newBrush);
toolStoreActions.updateBrushSettings({
...NEUTRAL_BRUSH_DEFAULTS,
...prepared,
preset: newBrush.id,
});
showToast?.(t('Saved preset "{name}"', { name: finalName }));
};
const handleResetDefault = () => {
const restored = resetBrushSettingsToDefault(activePreset, getCachedCustomBrushes());
toolStoreActions.updateBrushSettings({
...NEUTRAL_BRUSH_DEFAULTS,
...restored,
preset: activePreset,
});
showToast?.(t('Brush reset to default'));
};
const handleExportInkb = async () => {
try {
const live = useToolStore.getState().brushSettings;
const exportBrush: CspBrush = {
...buildExportableBrush(activePreset, getCachedCustomBrushes(), live),
name: brushName || live.brushName || activePreset,
category,
desc: description,
};
const res = await exportBrushToInkbFile(exportBrush);
if (res.exported) showToast?.(t('Exported {fileName}', { fileName: res.fileName }));
} catch (err) {
showToast?.(err instanceof Error ? err.message : t('Export failed'));
}
};
const handleImportInkb = async (file: File) => {
try {
const parsed = await importBrushFile(file);
saveActivePresetId(parsed.id);
if (parsed.importWarnings && parsed.importWarnings.length > 0) {
const count = parsed.importWarnings.length;
showToast?.(
count === 1
? t('Imported "{name}" (Notice: {notice})', {
name: parsed.name,
notice: parsed.importWarnings[0],
})
: t('Imported "{name}" with {count} CSP import notices', {
name: parsed.name,
count,
})
);
} else {
showToast?.(t('Imported "{name}"', { name: parsed.name }));
}
} catch (err) {
showToast?.(err instanceof Error ? err.message : t('Import failed'));
}
};
if (!isOpen) return null;
const displayBrushName = td(brushName, 'brushName');
const isTabFeatureActive = (tabId: StudioTabId): boolean => {
switch (tabId) {
case 'texture':
return (brushSettings.grain ?? brushSettings.textureDensity ?? 0) > 0.01;
case 'dual':
return Boolean(brushSettings.dualBrush);
case 'mixing':
return Boolean(brushSettings.naturalPaint?.enabled || brushSettings.colorMixing);
case 'impasto':
return Boolean(brushSettings.impasto?.enabled || (brushSettings.wetEdge ?? 0) > 0.01);
default:
return false;
}
};
return (
<div
role="dialog"
aria-modal="true"
aria-label={t('Brush Studio — {name}', { name: displayBrushName })}
data-testid="brush-studio-modal"
className="fixed inset-0 z-50 bg-ui-overlay flex items-center justify-center p-4 select-none"
onPointerDown={(e) => {
if (e.target === e.currentTarget) onClose();
}}
>
<div className="w-full max-w-[1080px] h-[min(86vh,740px)] bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover flex flex-col overflow-hidden text-ui-primary">
{/* Instrument Header */}
<div className="h-11 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between gap-3 shrink-0">
<div className="flex items-center gap-2.5 min-w-0">
<div className="w-6 h-6 rounded-ui-xs bg-ui-panel border border-ui-subtle flex items-center justify-center text-ui-accent shrink-0">
<Paintbrush className="w-3.5 h-3.5" />
</div>
<div className="flex items-baseline gap-2 min-w-0">
<span className="text-[10px] font-ui-mono uppercase tracking-[0.1em] text-ui-muted shrink-0">
{t('Brush Studio')}
</span>
<span className="text-ui-disabled shrink-0">/</span>
<h2 className="text-[13px] font-medium tracking-tight truncate text-ui-primary">
{displayBrushName}
</h2>
</div>
<span className="text-[9.5px] font-ui-mono px-1.5 py-0.5 rounded-ui-xs bg-ui-input border border-ui-subtle text-ui-secondary uppercase shrink-0">
{tc('renderMode', brushSettings.renderMode ?? 'stamp')}
</span>
</div>
<div className="flex items-center gap-1.5 shrink-0">
<IconButton
size="sm"
variant="subtle"
onClick={handleResetDefault}
title={t('Reset brush to default')}
icon={<RotateCcw className="w-3.5 h-3.5" />}
/>
<button
type="button"
onClick={() => handleSaveAsNewPreset()}
className="h-[var(--ui-control-height)] px-3 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer"
>
{t('Save New Preset')}
</button>
<IconButton
size="sm"
onClick={onClose}
title={t('Close Brush Studio (Esc)')}
icon={<X className="w-4 h-4" />}
/>
</div>
</div>
{/* Main 3-Column Instrument Layout: Category Rail | Framed Scratchpad | Property Inspector */}
<div className="flex-1 flex min-h-0">
{/* Left Category Navigation Rail */}
<nav
aria-label={t('Brush Studio Sections')}
className="w-[164px] bg-ui-header border-r border-ui-subtle p-1.5 space-y-0.5 shrink-0 overflow-y-auto"
>
{STUDIO_TABS.map((tab) => {
const selected = activeTab === tab.id;
const featureOn = isTabFeatureActive(tab.id);
const tabLabel = t(tab.label);
return (
<button
key={tab.id}
type="button"
data-testid={`brush-studio-tab-${tab.id}`}
aria-current={selected ? 'page' : undefined}
onClick={() => setActiveTab(tab.id)}
className={`ui-icon-stroke relative w-full flex items-center justify-between gap-2 px-2.5 py-2 rounded-ui-xs text-[11px] transition-colors cursor-pointer border text-left ${
selected
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/40'
: 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{selected && (
<span
aria-hidden="true"
className="pointer-events-none absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full bg-ui-accent"
/>
)}
<span className="flex items-center gap-2 min-w-0">
<span className={selected ? 'text-ui-accent shrink-0' : 'text-ui-icon-muted shrink-0'}>
{tab.icon}
</span>
<span className="truncate">{tabLabel}</span>
</span>
{featureOn && (
<span
aria-label={t('{label} active', { label: tabLabel })}
className="w-1.5 h-1.5 rounded-full bg-ui-accent shrink-0"
/>
)}
</button>
);
})}
</nav>
{/* Center Interactive Live Scratchpad */}
<div className="flex-1 min-w-[320px] flex flex-col min-h-0">
<BrushStudioScratchpad
brushSettings={brushSettings}
onPatchSettings={handlePatchSettings}
/>
</div>
{/* Right Parameter Inspector (Hairline SectionDisclosure stack) */}
<div className="w-[376px] bg-ui-panel border-l border-ui-subtle overflow-y-auto overflow-x-hidden shrink-0">
{activeTab === 'shape' && (
<ShapeBristlesTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'stroke' && (
<StrokeTaperTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'texture' && (
<TextureGrainTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'dual' && (
<DualBrushTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'mixing' && (
<NaturalPaintMixingTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'impasto' && (
<ImpastoWetEdgeTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'dynamics' && (
<DynamicsSensorMatrixTab bs={brushSettings} onPatch={handlePatchSettings} />
)}
{activeTab === 'about' && (
<AboutPresetsTab
bs={brushSettings}
onPatch={handlePatchSettings}
brushName={brushName}
onBrushNameChange={(name) => {
setBrushName(name);
handlePatchSettings({ brushName: name });
}}
category={category}
onCategoryChange={setCategory}
description={description}
onDescriptionChange={setDescription}
onResetDefault={handleResetDefault}
onSaveAsNewPreset={() => handleSaveAsNewPreset()}
onDuplicateBrush={() => handleSaveAsNewPreset('Copy')}
onExportInkb={handleExportInkb}
onImportInkb={handleImportInkb}
/>
)}
</div>
</div>
</div>
</div>
);
};