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 { createStore } from './createStore';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from '../utils/safeStorage';
import { isValidHex } from '../utils/colorUtils';
import {
deriveColorSetNameFromFilename,
hasPngSignature,
hasSlccMagic,
parseClipStudioColorSet,
parsePngColorSet,
} from '../utils/colorSetImport';
export const COLOR_SETS_STORAGE_KEY = 'ink_studio_color_sets_v1';
export const COLOR_SET_EXPORT_FORMAT = 'ink-studio-color-set' as const;
export const COLOR_SET_EXPORT_VERSION = 1 as const;
export type SwatchColumnCount = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
export const SWATCH_COLUMN_OPTIONS: readonly SwatchColumnCount[] = [1, 2, 3, 4, 5, 6, 7, 8] as const;
export const MAX_COLOR_SETS = 64;
export const MAX_SWATCHES_PER_SET = 512;
const MAX_IMPORT_JSON_BYTES = 256 * 1024;
export interface ColorSwatch {
id: string;
/** Normalized 6-digit hex color string (#rrggbb) */
hex: string;
name?: string;
}
export interface ColorSet {
id: string;
name: string;
swatches: ColorSwatch[];
builtIn?: boolean;
}
export interface ColorSetsStoreState {
sets: ColorSet[];
activeSetId: string;
/** Number of swatch columns (1..8) for Color Sets palette */
setsColumns: SwatchColumnCount;
/** Number of swatch columns (1..8) for Color History palette */
historyColumns: SwatchColumnCount;
/** Whether ColorSlider is displayed inline directly below ColorWheel inside ColorPanel */
showInlineSlidersBelowWheel: boolean;
}
interface PersistedColorSetsPayload {
version: 1;
sets: ColorSet[];
activeSetId: string;
setsColumns: SwatchColumnCount;
historyColumns: SwatchColumnCount;
showInlineSlidersBelowWheel: boolean;
}
export interface ExportedColorSetFile {
format: typeof COLOR_SET_EXPORT_FORMAT;
version: typeof COLOR_SET_EXPORT_VERSION;
name: string;
swatches: Array<{ hex: string; name?: string }>;
}
export type ImportColorSetResult =
| { ok: true; set: ColorSet }
| { ok: false; error: string };
let idSeq = 1;
function makeId(prefix: string): string {
idSeq += 1;
return `${prefix}-${Date.now().toString(36)}-${idSeq}`;
}
/**
* Normalizes a valid 3- or 6-digit hex string (with or without leading `#`) to lowercase `#rrggbb`.
* Returns `null` if invalid.
*/
export function normalizeSwatchHex(raw: unknown): string | null {
if (typeof raw !== 'string') return null;
const trimmed = raw.trim();
if (!isValidHex(trimmed)) return null;
const bare = trimmed.startsWith('#') ? trimmed.slice(1) : trimmed;
if (bare.length === 3) {
return `#${bare[0]}${bare[0]}${bare[1]}${bare[1]}${bare[2]}${bare[2]}`.toLowerCase();
}
return `#${bare.slice(0, 6)}`.toLowerCase();
}
export function clampSwatchColumns(raw: unknown, fallback: SwatchColumnCount = 6): SwatchColumnCount {
if (typeof raw !== 'number' || !Number.isFinite(raw)) return fallback;
const rounded = Math.round(raw);
if (rounded < 1) return 1;
if (rounded > 8) return 8;
return rounded as SwatchColumnCount;
}
function makeSwatches(
prefix: string,
entries: ReadonlyArray<readonly [string, string?]>
): ColorSwatch[] {
return entries.map(([hex, name], idx) => ({
id: `${prefix}-${idx + 1}`,
hex: hex.toLowerCase(),
...(name ? { name } : {}),
}));
}
export function createDefaultColorSets(): ColorSet[] {
return [
{
id: 'set-atelier-neutrals',
name: 'Atelier Neutrals & Values',
builtIn: true,
swatches: makeSwatches('neut', [
['#000000', 'Sumi Black'],
['#1a1a1a', 'Charcoal 90%'],
['#333333', 'Graphite 80%'],
['#4d4d4d', 'Neutral 70%'],
['#666666', 'Neutral 60%'],
['#808080', 'Middle Grey 50%'],
['#999999', 'Neutral 40%'],
['#b3b3b3', 'Silver 30%'],
['#cccccc', 'Light Grey 20%'],
['#e6e6e6', 'Off White 10%'],
['#f5f3ee', 'Warm Paper'],
['#ffffff', 'Titanium White'],
['#2c221e', 'Raw Umber'],
['#4a3b32', 'Burnt Umber'],
['#6e5849', 'Warm Taupe'],
['#9b8675', 'Stone Khaki'],
['#c9b9a6', 'Parchment'],
['#eae0d2', 'Atelier Cream'],
['#1e242b', 'Payne Shadow'],
['#34404d', 'Slate Dark'],
['#52606e', 'Cool Mid'],
['#7a8999', 'Steel Grey'],
['#a9b5c2', 'Cool Mist'],
['#dce3ea', 'Cool Paper'],
]),
},
{
id: 'set-skin-portrait',
name: 'Skin & Portrait Tones',
builtIn: true,
swatches: makeSwatches('skin', [
['#fff1e6', 'Porcelain Highlight'],
['#fadac7', 'Fair Light'],
['#e8b89d', 'Fair Midtone'],
['#c68b6e', 'Fair Shadow'],
['#8f5642', 'Warm Umber Shadow'],
['#593126', 'Deep Core Shadow'],
['#f6dfc4', 'Golden Highlight'],
['#e4be96', 'Olive Light'],
['#c9976b', 'Warm Tan'],
['#a36f48', 'Golden Midtone'],
['#75492d', 'Ochre Shadow'],
['#482919', 'Espresso Shadow'],
['#c88e68', 'Chestnut Highlight'],
['#a86d4a', 'Warm Sienna'],
['#874f33', 'Rich Umber'],
['#663823', 'Deep Mahogany'],
['#472416', 'Dark Cocoa'],
['#2b140c', 'Deepest Occlusion'],
['#e68a8a', 'Soft Blush'],
['#c95d63', 'Rose Subsurface'],
['#a33d48', 'Lip Crimson'],
['#b88b99', 'Cool Mauve'],
['#7a6373', 'Shadow Violet'],
['#4a4356', 'Ambient Cool Shadow'],
]),
},
{
id: 'set-manga-ink',
name: 'Manga & Ink Accents',
builtIn: true,
swatches: makeSwatches('manga', [
['#111317', 'G-Pen Ink'],
['#26303d', 'Indigo Ink'],
['#c83e37', 'Vermilion Seal'],
['#e26a4b', 'Persimmon'],
['#e6a93b', 'Ochre Gold'],
['#f2d272', 'Soft Canary'],
['#5a9367', 'Matcha'],
['#2d6a5b', 'Pine'],
['#3b7ea1', 'Cerulean'],
['#2a4d7a', 'Prussian Blue'],
['#6e5a94', 'Wisteria'],
['#b84a76', 'Camellia'],
['#d98c9b', 'Sakura'],
['#88b8c8', 'Sky Wash'],
['#c9d3c0', 'Celadon'],
['#faf6ed', 'Manga Paper'],
]),
},
{
id: 'set-classic-primaries',
name: 'Classic Primaries',
builtIn: true,
swatches: makeSwatches('prim', [
['#b91c1c', 'Cadmium Deep'],
['#dc2626', 'Cadmium Red'],
['#ea580c', 'Burnt Orange'],
['#d97706', 'Deep Amber'],
['#eab308', 'Cadmium Yellow'],
['#84cc16', 'Chartreuse'],
['#16a34a', 'Viridian Green'],
['#0d9488', 'Teal'],
['#0284c7', 'Cerulean Blue'],
['#2563eb', 'Cobalt Blue'],
['#4f46e5', 'Ultramarine'],
['#9333ea', 'Dioxazine Violet'],
['#c026d3', 'Magenta'],
['#e11d48', 'Alizarin Rose'],
['#7f1d1d', 'Oxblood'],
['#78350f', 'Raw Sienna'],
['#14532d', 'Hooker Green'],
['#134e4a', 'Deep Pine'],
['#1e3a8a', 'Indigo'],
['#3b0764', 'Plum Dark'],
['#fca5a5', 'Pale Coral'],
['#fde68a', 'Naples Yellow'],
['#86efac', 'Mint Tint'],
['#93c5fd', 'Ice Blue'],
]),
},
];
}
function sanitizeSwatches(raw: unknown): ColorSwatch[] {
if (!Array.isArray(raw)) return [];
const out: ColorSwatch[] = [];
const seenIds = new Set<string>();
for (const item of raw) {
if (out.length >= MAX_SWATCHES_PER_SET) break;
if (typeof item === 'string') {
const hex = normalizeSwatchHex(item);
if (hex) {
const id = makeId('sw');
seenIds.add(id);
out.push({ id, hex });
}
continue;
}
if (!item || typeof item !== 'object') continue;
const rec = item as Record<string, unknown>;
const hex = normalizeSwatchHex(rec.hex ?? rec.color);
if (!hex) continue;
const rawId = typeof rec.id === 'string' && rec.id.trim() ? rec.id.trim().slice(0, 64) : makeId('sw');
const id = seenIds.has(rawId) ? makeId('sw') : rawId;
seenIds.add(id);
const name =
typeof rec.name === 'string' && rec.name.trim()
? rec.name.trim().slice(0, 48)
: undefined;
out.push(name ? { id, hex, name } : { id, hex });
}
return out;
}
function sanitizeColorSets(raw: unknown): ColorSet[] {
if (!Array.isArray(raw)) return createDefaultColorSets();
const out: ColorSet[] = [];
const seenIds = new Set<string>();
for (const entry of raw) {
if (out.length >= MAX_COLOR_SETS) break;
if (!entry || typeof entry !== 'object') continue;
const rec = entry as Record<string, unknown>;
const rawId = typeof rec.id === 'string' && rec.id.trim() ? rec.id.trim().slice(0, 64) : makeId('set');
const id = seenIds.has(rawId) ? makeId('set') : rawId;
seenIds.add(id);
const name =
typeof rec.name === 'string' && rec.name.trim()
? rec.name.trim().slice(0, 48)
: `Color Set ${out.length + 1}`;
const swatches = sanitizeSwatches(rec.swatches);
out.push({
id,
name,
swatches,
...(rec.builtIn === true ? { builtIn: true } : {}),
});
}
return out.length > 0 ? out : createDefaultColorSets();
}
export function createInitialColorSetsState(): ColorSetsStoreState {
const defaults = createDefaultColorSets();
const fallbackSetId = defaults[0]?.id ?? 'set-atelier-neutrals';
const fallback: ColorSetsStoreState = {
sets: defaults,
activeSetId: fallbackSetId,
setsColumns: 6,
historyColumns: 6,
showInlineSlidersBelowWheel: false,
};
try {
const raw = safeLocalStorageGetItem(COLOR_SETS_STORAGE_KEY);
if (!raw) return fallback;
const parsed = JSON.parse(raw) as Record<string, unknown>;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return fallback;
const sets = sanitizeColorSets(parsed.sets);
const activeSetId =
typeof parsed.activeSetId === 'string' && sets.some((s) => s.id === parsed.activeSetId)
? parsed.activeSetId
: (sets[0]?.id ?? fallbackSetId);
return {
sets,
activeSetId,
setsColumns: clampSwatchColumns(parsed.setsColumns, 6),
historyColumns: clampSwatchColumns(parsed.historyColumns, 6),
showInlineSlidersBelowWheel: Boolean(parsed.showInlineSlidersBelowWheel),
};
} catch {
return fallback;
}
}
export function saveColorSetsState(state: ColorSetsStoreState): void {
const payload: PersistedColorSetsPayload = {
version: 1,
sets: state.sets,
activeSetId: state.activeSetId,
setsColumns: state.setsColumns,
historyColumns: state.historyColumns,
showInlineSlidersBelowWheel: state.showInlineSlidersBelowWheel,
};
safeLocalStorageSetItem(COLOR_SETS_STORAGE_KEY, JSON.stringify(payload), 'color sets');
}
export const useColorSetsStore = createStore<ColorSetsStoreState>(createInitialColorSetsState);
function persist(): void {
saveColorSetsState(useColorSetsStore.getState());
}
export function serializeColorSetJson(set: ColorSet): string {
const payload: ExportedColorSetFile = {
format: COLOR_SET_EXPORT_FORMAT,
version: COLOR_SET_EXPORT_VERSION,
name: set.name,
swatches: set.swatches.map((sw) => (sw.name ? { hex: sw.hex, name: sw.name } : { hex: sw.hex })),
};
return JSON.stringify(payload, null, 2);
}
export function parseColorSetJson(rawJson: string): { ok: true; name: string; swatches: ColorSwatch[] } | { ok: false; error: string } {
if (typeof rawJson !== 'string' || rawJson.trim().length === 0) {
return { ok: false, error: 'Color set file is empty.' };
}
if (rawJson.length > MAX_IMPORT_JSON_BYTES) {
return { ok: false, error: 'Color set file exceeds 256 KB limit.' };
}
let parsed: unknown;
try {
parsed = JSON.parse(rawJson);
} catch {
return { ok: false, error: 'Invalid JSON file.' };
}
// Support plain array of hex strings
if (Array.isArray(parsed)) {
const swatches = sanitizeSwatches(parsed);
if (swatches.length === 0) {
return { ok: false, error: 'No valid hex color swatches found.' };
}
return { ok: true, name: 'Imported Set', swatches };
}
if (!parsed || typeof parsed !== 'object') {
return { ok: false, error: 'Color set JSON must be an object or array.' };
}
const root = parsed as Record<string, unknown>;
if (root.format !== undefined && root.format !== COLOR_SET_EXPORT_FORMAT) {
return {
ok: false,
error: `Unsupported color set format "${String(root.format)}".`,
};
}
const rawList = Array.isArray(root.swatches)
? root.swatches
: Array.isArray(root.colors)
? root.colors
: null;
if (!rawList) {
return { ok: false, error: 'Color set JSON is missing a "swatches" array.' };
}
const swatches = sanitizeSwatches(rawList);
const name =
typeof root.name === 'string' && root.name.trim()
? root.name.trim().slice(0, 48)
: 'Imported Set';
return { ok: true, name, swatches };
}
export function parseColorSetBytes(
data: Uint8Array | ArrayBuffer,
filename?: string
): { ok: true; name: string; swatches: ColorSwatch[] } | { ok: false; error: string } {
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
if (bytes.byteLength === 0) {
return { ok: false, error: 'Color set file is empty.' };
}
const lower = (filename ?? '').trim().toLowerCase();
if (hasSlccMagic(bytes) || lower.endsWith('.cls')) {
const parsed = parseClipStudioColorSet(bytes, filename, MAX_SWATCHES_PER_SET);
if (!parsed.ok) return parsed;
const swatches = sanitizeSwatches(parsed.swatches);
if (swatches.length === 0) {
return { ok: false, error: 'No valid colors found in Clip Studio color set.' };
}
return { ok: true, name: parsed.name, swatches };
}
if (hasPngSignature(bytes) || lower.endsWith('.png')) {
const parsed = parsePngColorSet(bytes, filename, MAX_SWATCHES_PER_SET);
if (!parsed.ok) return parsed;
const swatches = sanitizeSwatches(parsed.swatches);
if (swatches.length === 0) {
return { ok: false, error: 'No valid colors found in PNG color palette.' };
}
return { ok: true, name: parsed.name, swatches };
}
if (lower && !lower.endsWith('.json')) {
return {
ok: false,
error: 'Unsupported color set format. Use .json, Clip Studio .cls, or .png palette files.',
};
}
const text = new TextDecoder('utf-8').decode(bytes);
const jsonRes = parseColorSetJson(text);
if (!jsonRes.ok) return jsonRes;
const resolvedName =
jsonRes.name === 'Imported Set' && filename
? deriveColorSetNameFromFilename(filename, 'Imported Set')
: jsonRes.name;
return { ok: true, name: resolvedName, swatches: jsonRes.swatches };
}
function commitImportedColorSet(name: string, swatches: ColorSwatch[]): ImportColorSetResult {
const state = useColorSetsStore.getState();
if (state.sets.length >= MAX_COLOR_SETS) {
return {
ok: false,
error: `Maximum of ${MAX_COLOR_SETS} color sets reached. Delete a set before importing.`,
};
}
let uniqueName = name.trim().slice(0, 48) || 'Imported Set';
const existingLower = new Set(state.sets.map((s) => s.name.trim().toLowerCase()));
if (existingLower.has(uniqueName.toLowerCase())) {
let n = 2;
while (existingLower.has(`${uniqueName} (${n})`.toLowerCase()) && n < 100) {
n += 1;
}
uniqueName = `${uniqueName.slice(0, 42)} (${n})`;
}
const imported: ColorSet = {
id: makeId('set'),
name: uniqueName,
swatches,
};
useColorSetsStore.setState((prev) => ({
sets: [...prev.sets, imported].slice(0, MAX_COLOR_SETS),
activeSetId: imported.id,
}));
persist();
return { ok: true, set: imported };
}
export const colorSetsStoreActions = {
selectSet(setId: string): void {
const state = useColorSetsStore.getState();
if (state.activeSetId === setId || !state.sets.some((s) => s.id === setId)) return;
useColorSetsStore.setState({ activeSetId: setId });
persist();
},
createSet(name?: string, initialSwatches?: Array<{ hex: string; name?: string }>): ColorSet {
const state = useColorSetsStore.getState();
const trimmed = typeof name === 'string' ? name.trim().slice(0, 48) : '';
const resolvedName = trimmed || `Custom Set ${state.sets.length + 1}`;
const swatches = initialSwatches ? sanitizeSwatches(initialSwatches) : [];
const newSet: ColorSet = {
id: makeId('set'),
name: resolvedName,
swatches,
};
useColorSetsStore.setState((prev) => ({
sets: [...prev.sets, newSet].slice(0, MAX_COLOR_SETS),
activeSetId: newSet.id,
}));
persist();
return newSet;
},
renameSet(setId: string, nextName: string): boolean {
const trimmed = nextName.trim().slice(0, 48);
if (!trimmed) return false;
const state = useColorSetsStore.getState();
const target = state.sets.find((s) => s.id === setId);
if (!target || target.name === trimmed) return false;
useColorSetsStore.setState({
sets: state.sets.map((s) => (s.id === setId ? { ...s, name: trimmed } : s)),
});
persist();
return true;
},
duplicateSet(setId: string): ColorSet | null {
const state = useColorSetsStore.getState();
const source = state.sets.find((s) => s.id === setId);
if (!source) return null;
const copyName = `${source.name.slice(0, 42)} Copy`;
const duplicated: ColorSet = {
id: makeId('set'),
name: copyName,
swatches: source.swatches.map((sw) => ({
...sw,
id: makeId('sw'),
})),
};
const idx = state.sets.findIndex((s) => s.id === setId);
const nextSets = [...state.sets];
nextSets.splice(idx + 1, 0, duplicated);
useColorSetsStore.setState({
sets: nextSets.slice(0, MAX_COLOR_SETS),
activeSetId: duplicated.id,
});
persist();
return duplicated;
},
deleteSet(setId: string): boolean {
const state = useColorSetsStore.getState();
if (state.sets.length <= 1) return false;
const idx = state.sets.findIndex((s) => s.id === setId);
if (idx < 0) return false;
const nextSets = state.sets.filter((s) => s.id !== setId);
const nextActiveId =
state.activeSetId === setId
? (nextSets[Math.min(idx, nextSets.length - 1)]?.id ?? '')
: state.activeSetId;
useColorSetsStore.setState({
sets: nextSets,
activeSetId: nextActiveId,
});
persist();
return true;
},
addSwatch(hex: string, options?: { setId?: string; name?: string }): ColorSwatch | null {
const normalized = normalizeSwatchHex(hex);
if (!normalized) return null;
const state = useColorSetsStore.getState();
const targetSetId = options?.setId ?? state.activeSetId;
const targetSet = state.sets.find((s) => s.id === targetSetId);
if (!targetSet || targetSet.swatches.length >= MAX_SWATCHES_PER_SET) return null;
const cleanName =
typeof options?.name === 'string' && options.name.trim()
? options.name.trim().slice(0, 48)
: undefined;
const swatch: ColorSwatch = {
id: makeId('sw'),
hex: normalized,
...(cleanName ? { name: cleanName } : {}),
};
useColorSetsStore.setState({
sets: state.sets.map((s) =>
s.id === targetSetId ? { ...s, swatches: [...s.swatches, swatch] } : s
),
});
persist();
return swatch;
},
replaceSwatch(setId: string, swatchId: string, hex: string): boolean {
const normalized = normalizeSwatchHex(hex);
if (!normalized) return false;
const state = useColorSetsStore.getState();
const targetSet = state.sets.find((s) => s.id === setId);
if (!targetSet || !targetSet.swatches.some((sw) => sw.id === swatchId)) return false;
useColorSetsStore.setState({
sets: state.sets.map((s) =>
s.id === setId
? {
...s,
swatches: s.swatches.map((sw) =>
sw.id === swatchId ? { ...sw, hex: normalized } : sw
),
}
: s
),
});
persist();
return true;
},
removeSwatch(setId: string, swatchId: string): boolean {
const state = useColorSetsStore.getState();
const targetSet = state.sets.find((s) => s.id === setId);
if (!targetSet || !targetSet.swatches.some((sw) => sw.id === swatchId)) return false;
useColorSetsStore.setState({
sets: state.sets.map((s) =>
s.id === setId
? { ...s, swatches: s.swatches.filter((sw) => sw.id !== swatchId) }
: s
),
});
persist();
return true;
},
reorderSwatch(setId: string, fromIndex: number, toIndex: number): boolean {
const state = useColorSetsStore.getState();
const targetSet = state.sets.find((s) => s.id === setId);
if (!targetSet) return false;
const len = targetSet.swatches.length;
if (
fromIndex < 0 ||
fromIndex >= len ||
toIndex < 0 ||
toIndex >= len ||
fromIndex === toIndex
) {
return false;
}
const nextSwatches = [...targetSet.swatches];
const [moved] = nextSwatches.splice(fromIndex, 1);
nextSwatches.splice(toIndex, 0, moved);
useColorSetsStore.setState({
sets: state.sets.map((s) => (s.id === setId ? { ...s, swatches: nextSwatches } : s)),
});
persist();
return true;
},
setSetsColumns(columns: SwatchColumnCount): void {
const clamped = clampSwatchColumns(columns, 6);
if (useColorSetsStore.getState().setsColumns === clamped) return;
useColorSetsStore.setState({ setsColumns: clamped });
persist();
},
setHistoryColumns(columns: SwatchColumnCount): void {
const clamped = clampSwatchColumns(columns, 6);
if (useColorSetsStore.getState().historyColumns === clamped) return;
useColorSetsStore.setState({ historyColumns: clamped });
persist();
},
setShowInlineSlidersBelowWheel(show: boolean): void {
if (useColorSetsStore.getState().showInlineSlidersBelowWheel === show) return;
useColorSetsStore.setState({ showInlineSlidersBelowWheel: show });
persist();
},
toggleShowInlineSlidersBelowWheel(): boolean {
const next = !useColorSetsStore.getState().showInlineSlidersBelowWheel;
useColorSetsStore.setState({ showInlineSlidersBelowWheel: next });
persist();
return next;
},
exportSetJson(setId?: string): string | null {
const state = useColorSetsStore.getState();
const target = state.sets.find((s) => s.id === (setId ?? state.activeSetId));
if (!target) return null;
return serializeColorSetJson(target);
},
importSetJson(rawJson: string): ImportColorSetResult {
const parsed = parseColorSetJson(rawJson);
if (!parsed.ok) return parsed;
return commitImportedColorSet(parsed.name, parsed.swatches);
},
importSetBytes(data: Uint8Array | ArrayBuffer, filename?: string): ImportColorSetResult {
const parsed = parseColorSetBytes(data, filename);
if (!parsed.ok) return parsed;
return commitImportedColorSet(parsed.name, parsed.swatches);
},
async importSetFile(file: File): Promise<ImportColorSetResult> {
try {
const buffer = await file.arrayBuffer();
return this.importSetBytes(new Uint8Array(buffer), file.name);
} catch {
return { ok: false, error: 'Failed to read color set file.' };
}
},
};