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 { BrushCategory, BrushPresetId, CspBrush, DecorationCategory } from '../types/editor';
import {
ALL_BUILTIN_BRUSHES,
ALL_BUILTIN_BRUSH_SECTIONS,
BUILTIN_BRUSH_SECTIONS,
DECORATION_BRUSH_SECTIONS,
isDecorationCategory,
} from './presetBrushes';
import { ERASER_PRESET_ID, migrateLegacyPresetId } from './brushPresetManager';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';
export const SUBTOOL_GROUPS_STORAGE_KEY = 'ink_studio_subtool_groups_v1';
export type SubToolGroupIconId =
| 'folder'
| 'pen'
| 'pencil'
| 'paintbrush'
| 'droplets'
| 'palette'
| 'sparkles'
| 'star'
| 'layers';
export const SUBTOOL_GROUP_ICON_IDS: readonly SubToolGroupIconId[] = [
'folder',
'pen',
'pencil',
'paintbrush',
'droplets',
'palette',
'sparkles',
'star',
'layers',
];
export const SUBTOOL_GROUP_COLOR_SWATCHES: readonly {
id: string;
label: string;
hex: string | null;
}[] = [
{ id: 'none', label: 'Default', hex: null },
{ id: 'indigo', label: 'Indigo', hex: '#818cf8' },
{ id: 'sky', label: 'Sky', hex: '#38bdf8' },
{ id: 'emerald', label: 'Emerald', hex: '#34d399' },
{ id: 'amber', label: 'Amber', hex: '#fbbf24' },
{ id: 'rose', label: 'Rose', hex: '#fb7185' },
{ id: 'violet', label: 'Violet', hex: '#a78bfa' },
];
export type BuiltinTargetGroupId = BrushCategory | 'custom';
export type SubToolGroupScope = 'brush' | 'decoration';
export interface CustomSubToolGroup {
id: string;
name: string;
color?: string | null;
icon?: SubToolGroupIconId;
/** Tool group scope: 'brush' (default) or 'decoration' */
toolScope?: SubToolGroupScope;
/** Ordered list of BrushPresetIds (built-in or custom CspBrush IDs) assigned to this group */
brushIds: BrushPresetId[];
/** Last selected brush inside this group so opening the group restores it (CSP-style) */
lastActiveBrushId?: BrushPresetId;
createdAt: number;
}
export function isDecorationCustomGroup(group: CustomSubToolGroup): boolean {
return group.toolScope === 'decoration';
}
/**
* Active tab filter in the Sub Tool palette:
* - 'all': show every group (default, full list view)
* - BrushCategory: built-in section ('pen' | 'sketch' | 'brush' | 'blend' | 'natural-paint')
* - 'custom': Imported/Custom brushes section
* - string: a CustomSubToolGroup.id
*/
export type ActiveSubToolGroupTab = 'all' | BuiltinTargetGroupId | string;
export type ActiveDecorationSubToolTab = 'all' | DecorationCategory | string;
export type BrushGroupOverridesMap = Record<string, BuiltinTargetGroupId>;
export type BuiltinGroupOrdersMap = Partial<Record<BuiltinTargetGroupId, BrushPresetId[]>>;
export interface PersistedSubToolGroupsState {
version: 1;
groups: CustomSubToolGroup[];
activeTab: ActiveSubToolGroupTab;
activeDecorationTab?: ActiveDecorationSubToolTab;
/** Maps any BrushPresetId moved into a built-in/Imported group to that target group ID */
brushGroupOverrides?: BrushGroupOverridesMap;
/** Optional user-reordered brush sequence inside built-in/Imported groups */
builtinGroupOrders?: BuiltinGroupOrdersMap;
}
export const BUILTIN_CATEGORY_SET = new Set<string>(
ALL_BUILTIN_BRUSH_SECTIONS.map((s) => s.id)
);
export const BUILTIN_TARGET_GROUP_SET = new Set<string>([
...ALL_BUILTIN_BRUSH_SECTIONS.map((s) => s.id),
'custom',
]);
const VALID_ICON_SET = new Set<string>(SUBTOOL_GROUP_ICON_IDS);
let groupUidSeq = 1;
export function createSubToolGroupId(): string {
groupUidSeq += 1;
return `stg-${Date.now().toString(36)}-${groupUidSeq}-${Math.random().toString(36).slice(2, 5)}`;
}
export function normalizeBrushIdForGroup(presetId: string): BrushPresetId | null {
if (!presetId || typeof presetId !== 'string') return null;
const trimmed = presetId.trim();
if (!trimmed || trimmed === ERASER_PRESET_ID || trimmed === 'eraser') return null;
return migrateLegacyPresetId(trimmed);
}
export function isBuiltinGroupTab(tab: string): tab is BrushCategory {
return BUILTIN_CATEGORY_SET.has(tab);
}
export function isBuiltinTargetGroupId(id: string): id is BuiltinTargetGroupId {
return BUILTIN_TARGET_GROUP_SET.has(id);
}
export function getFactoryGroupIdForBrush(
presetId: BrushPresetId,
customBrushes?: readonly CspBrush[]
): BuiltinTargetGroupId {
const norm = migrateLegacyPresetId(presetId);
const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === norm);
if (builtin) return builtin.category;
if (customBrushes?.some((b) => b.id === presetId || b.id === norm)) {
return 'custom';
}
return 'custom';
}
export function getGroupDisplayLabel(
groupId: string,
customGroups: readonly CustomSubToolGroup[]
): string {
const custom = customGroups.find((g) => g.id === groupId);
if (custom) return custom.name;
const sec = ALL_BUILTIN_BRUSH_SECTIONS.find((s) => s.id === groupId);
if (sec) return sec.label;
if (groupId === 'custom') return 'Imported';
return groupId;
}
export function sanitizeSubToolGroupsState(raw: unknown): PersistedSubToolGroupsState {
const fallback: PersistedSubToolGroupsState = {
version: 1,
groups: [],
activeTab: 'all',
brushGroupOverrides: {},
builtinGroupOrders: {},
};
if (!raw || typeof raw !== 'object') return fallback;
const rec = raw as Record<string, unknown>;
const rawGroups = Array.isArray(rec.groups) ? rec.groups : [];
const seenGroupIds = new Set<string>();
const claimedBrushIds = new Set<string>();
const groups: CustomSubToolGroup[] = [];
for (const entry of rawGroups) {
if (!entry || typeof entry !== 'object') continue;
const g = entry as Record<string, unknown>;
const rawId = typeof g.id === 'string' && g.id.trim() ? g.id.trim() : createSubToolGroupId();
if (
seenGroupIds.has(rawId) ||
rawId === 'all' ||
rawId === 'custom' ||
BUILTIN_CATEGORY_SET.has(rawId)
) {
continue;
}
seenGroupIds.add(rawId);
const name =
typeof g.name === 'string' && g.name.trim().length > 0
? g.name.trim().slice(0, 32)
: `Custom Group ${groups.length + 1}`;
const color =
typeof g.color === 'string' && /^#[0-9a-fA-F]{3,6}$/.test(g.color.trim())
? g.color.trim()
: null;
const icon: SubToolGroupIconId =
typeof g.icon === 'string' && VALID_ICON_SET.has(g.icon)
? (g.icon as SubToolGroupIconId)
: 'folder';
const brushIds: BrushPresetId[] = [];
if (Array.isArray(g.brushIds)) {
for (const bid of g.brushIds) {
if (typeof bid !== 'string') continue;
const normalized = normalizeBrushIdForGroup(bid);
if (!normalized || claimedBrushIds.has(normalized)) continue;
claimedBrushIds.add(normalized);
brushIds.push(normalized);
}
}
const rawLast =
typeof g.lastActiveBrushId === 'string'
? normalizeBrushIdForGroup(g.lastActiveBrushId)
: null;
const lastActiveBrushId = rawLast && brushIds.includes(rawLast) ? rawLast : undefined;
const createdAt =
typeof g.createdAt === 'number' && Number.isFinite(g.createdAt) ? g.createdAt : Date.now();
const toolScope: SubToolGroupScope | undefined =
g.toolScope === 'decoration' ? 'decoration' : undefined;
groups.push({
id: rawId,
name,
color,
icon,
...(toolScope ? { toolScope } : {}),
brushIds,
lastActiveBrushId,
createdAt,
});
}
const brushGroupOverrides: BrushGroupOverridesMap = {};
if (rec.brushGroupOverrides && typeof rec.brushGroupOverrides === 'object') {
for (const [rawBrushId, rawTarget] of Object.entries(
rec.brushGroupOverrides as Record<string, unknown>
)) {
const norm = normalizeBrushIdForGroup(rawBrushId);
if (
norm &&
!claimedBrushIds.has(norm) &&
typeof rawTarget === 'string' &&
isBuiltinTargetGroupId(rawTarget)
) {
brushGroupOverrides[norm] = rawTarget;
}
}
}
const builtinGroupOrders: BuiltinGroupOrdersMap = {};
if (rec.builtinGroupOrders && typeof rec.builtinGroupOrders === 'object') {
for (const [rawGroupId, rawOrder] of Object.entries(
rec.builtinGroupOrders as Record<string, unknown>
)) {
if (!isBuiltinTargetGroupId(rawGroupId) || !Array.isArray(rawOrder)) continue;
const seenInOrder = new Set<string>();
const cleanedOrder: BrushPresetId[] = [];
for (const bid of rawOrder) {
if (typeof bid !== 'string') continue;
const norm = normalizeBrushIdForGroup(bid);
if (!norm || claimedBrushIds.has(norm) || seenInOrder.has(norm)) continue;
seenInOrder.add(norm);
cleanedOrder.push(norm);
}
if (cleanedOrder.length > 0) {
builtinGroupOrders[rawGroupId] = cleanedOrder;
}
}
}
let activeTab: ActiveSubToolGroupTab = 'all';
if (typeof rec.activeTab === 'string') {
const t = rec.activeTab;
if (
t === 'all' ||
t === 'custom' ||
BUILTIN_CATEGORY_SET.has(t) ||
groups.some((g) => g.id === t)
) {
activeTab = t;
}
}
let activeDecorationTab: ActiveDecorationSubToolTab = 'all';
if (typeof rec.activeDecorationTab === 'string') {
const dt = rec.activeDecorationTab;
if (
dt === 'all' ||
isDecorationCategory(dt) ||
groups.some((g) => g.id === dt && isDecorationCustomGroup(g))
) {
activeDecorationTab = dt;
}
}
return {
version: 1,
groups,
activeTab,
activeDecorationTab,
brushGroupOverrides,
builtinGroupOrders,
};
}
export function loadSubToolGroupsState(): PersistedSubToolGroupsState {
try {
const raw = safeLocalStorageGetItem(SUBTOOL_GROUPS_STORAGE_KEY);
if (!raw) {
return {
version: 1,
groups: [],
activeTab: 'all',
activeDecorationTab: 'all',
brushGroupOverrides: {},
builtinGroupOrders: {},
};
}
return sanitizeSubToolGroupsState(JSON.parse(raw));
} catch {
return {
version: 1,
groups: [],
activeTab: 'all',
activeDecorationTab: 'all',
brushGroupOverrides: {},
builtinGroupOrders: {},
};
}
}
export function saveSubToolGroupsState(state: PersistedSubToolGroupsState): void {
safeLocalStorageSetItem(
SUBTOOL_GROUPS_STORAGE_KEY,
JSON.stringify(state),
'custom sub tool groups'
);
}
/**
* Returns a lookup map from normalized BrushPresetId -> owning CustomSubToolGroup.
*/
export function buildBrushToCustomGroupMap(
groups: readonly CustomSubToolGroup[]
): Map<BrushPresetId, CustomSubToolGroup> {
const map = new Map<BrushPresetId, CustomSubToolGroup>();
for (const g of groups) {
for (const bid of g.brushIds) {
map.set(migrateLegacyPresetId(bid), g);
}
}
return map;
}
/**
* Resolves valid BrushPresetIds belonging to a given custom group (filtering out deleted custom brushes).
*/
export function getValidBrushIdsInCustomGroup(
group: CustomSubToolGroup,
customBrushes: readonly CspBrush[]
): BrushPresetId[] {
const builtinSet = new Set<string>(ALL_BUILTIN_BRUSHES.map((b) => b.id));
const customSet = new Set<string>(customBrushes.map((b) => b.id));
return group.brushIds.filter((id) => {
const norm = migrateLegacyPresetId(id);
return builtinSet.has(norm) || customSet.has(id) || customSet.has(norm);
});
}
/**
* Resolves the effective owning group ID (custom group ID, built-in category, or 'custom')
* for any brush preset, accounting for both custom groups and built-in group moves.
*/
export function getEffectiveBrushGroupId(
presetId: BrushPresetId,
customGroups: readonly CustomSubToolGroup[],
brushGroupOverrides: BrushGroupOverridesMap = {},
customBrushes?: readonly CspBrush[]
): string {
const norm = migrateLegacyPresetId(presetId);
for (const g of customGroups) {
if (g.brushIds.includes(norm) || g.brushIds.includes(presetId)) {
return g.id;
}
}
const override = brushGroupOverrides[norm] ?? brushGroupOverrides[presetId];
if (override) return override;
return getFactoryGroupIdForBrush(presetId, customBrushes);
}
/**
* Returns the ordered list of BrushPresetIds currently inside a built-in or 'custom' (Imported) group,
* respecting cross-group moves (`brushGroupOverrides`) and per-group reordering (`builtinGroupOrders`).
*/
export function getOrderedBrushIdsInBuiltinGroup(
groupId: BuiltinTargetGroupId,
customGroups: readonly CustomSubToolGroup[],
customBrushes: readonly CspBrush[],
brushGroupOverrides: BrushGroupOverridesMap = {},
builtinGroupOrders: BuiltinGroupOrdersMap = {}
): BrushPresetId[] {
const assignedToCustom = buildBrushToCustomGroupMap(customGroups);
const memberIds: BrushPresetId[] = [];
const memberSet = new Set<string>();
const pushIfMember = (id: BrushPresetId, defaultGroup: BuiltinTargetGroupId) => {
const norm = migrateLegacyPresetId(id);
if (assignedToCustom.has(norm)) return;
const effective = brushGroupOverrides[norm] ?? brushGroupOverrides[id] ?? defaultGroup;
if (effective !== groupId) return;
if (memberSet.has(norm)) return;
memberSet.add(norm);
memberIds.push(id);
};
// Built-in presets (Brush + Decoration)
for (const b of ALL_BUILTIN_BRUSHES) {
pushIfMember(b.id, b.category);
}
// Custom / imported brushes
for (const cb of customBrushes) {
pushIfMember(cb.id, 'custom');
}
const customOrder = builtinGroupOrders[groupId];
if (!customOrder || customOrder.length === 0) {
return memberIds;
}
// Apply explicit ordering while keeping any new/unlisted members appended in default order
const byNorm = new Map<string, BrushPresetId>(
memberIds.map((id) => [migrateLegacyPresetId(id), id])
);
const ordered: BrushPresetId[] = [];
const emitted = new Set<string>();
for (const rawId of customOrder) {
const norm = migrateLegacyPresetId(rawId);
const actual = byNorm.get(norm);
if (actual && !emitted.has(norm)) {
emitted.add(norm);
ordered.push(actual);
}
}
for (const id of memberIds) {
const norm = migrateLegacyPresetId(id);
if (!emitted.has(norm)) {
emitted.add(norm);
ordered.push(id);
}
}
return ordered;
}
/**
* Returns the ordered list of subtool BrushPresetIds for a specific tab view
* (matching the exact display order in SubToolList).
*/
export function getOrderedSubToolIdsForTab(
activeTab: ActiveSubToolGroupTab,
customGroups: readonly CustomSubToolGroup[],
customBrushes: readonly CspBrush[],
brushGroupOverrides: BrushGroupOverridesMap = {},
builtinGroupOrders: BuiltinGroupOrdersMap = {}
): BrushPresetId[] {
const customGroup = customGroups.find((g) => g.id === activeTab);
if (customGroup) {
return getValidBrushIdsInCustomGroup(customGroup, customBrushes);
}
if (isBuiltinTargetGroupId(activeTab)) {
return getOrderedBrushIdsInBuiltinGroup(
activeTab,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
}
// 'all' view: Brush custom groups first, then built-in sections, then Imported
const ordered: BrushPresetId[] = [];
for (const g of customGroups) {
if (isDecorationCustomGroup(g)) continue;
ordered.push(...getValidBrushIdsInCustomGroup(g, customBrushes));
}
for (const sec of BUILTIN_BRUSH_SECTIONS) {
ordered.push(
...getOrderedBrushIdsInBuiltinGroup(
sec.id,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
)
);
}
ordered.push(
...getOrderedBrushIdsInBuiltinGroup(
'custom',
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
)
);
return ordered;
}
export interface NavigableSubToolGroupEntry {
id: ActiveSubToolGroupTab;
label: string;
isCustom: boolean;
brushIds: BrushPresetId[];
}
/**
* Returns the ordered list of Sub Tool Groups for Next/Previous SubTool Group navigation
* (custom groups first, then non-empty built-in sections, then Imported if non-empty).
*/
export function getNavigableSubToolGroups(
customGroups: readonly CustomSubToolGroup[],
customBrushes: readonly CspBrush[],
brushGroupOverrides: BrushGroupOverridesMap = {},
builtinGroupOrders: BuiltinGroupOrdersMap = {}
): NavigableSubToolGroupEntry[] {
const entries: NavigableSubToolGroupEntry[] = [];
for (const g of customGroups) {
if (isDecorationCustomGroup(g)) continue;
entries.push({
id: g.id,
label: g.name,
isCustom: true,
brushIds: getValidBrushIdsInCustomGroup(g, customBrushes),
});
}
for (const sec of BUILTIN_BRUSH_SECTIONS) {
const ids = getOrderedBrushIdsInBuiltinGroup(
sec.id,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
if (ids.length > 0) {
entries.push({
id: sec.id,
label: sec.label,
isCustom: false,
brushIds: ids,
});
}
}
const importedIds = getOrderedBrushIdsInBuiltinGroup(
'custom',
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
if (importedIds.length > 0) {
entries.push({
id: 'custom',
label: 'Imported',
isCustom: false,
brushIds: importedIds,
});
}
return entries;
}
/**
* Returns the ordered list of Decoration subtool BrushPresetIds for a specific Decoration tab
* ('all' | 'deco-background' | 'deco-clothing' | 'deco-effect').
*/
export function getOrderedDecorationSubToolIdsForTab(
activeDecorationTab: ActiveDecorationSubToolTab,
customGroups: readonly CustomSubToolGroup[],
customBrushes: readonly CspBrush[],
brushGroupOverrides: BrushGroupOverridesMap = {},
builtinGroupOrders: BuiltinGroupOrdersMap = {}
): BrushPresetId[] {
const decoCustomGroup = customGroups.find(
(g) => g.id === activeDecorationTab && isDecorationCustomGroup(g)
);
if (decoCustomGroup) {
return getValidBrushIdsInCustomGroup(decoCustomGroup, customBrushes);
}
if (isDecorationCategory(activeDecorationTab)) {
return getOrderedBrushIdsInBuiltinGroup(
activeDecorationTab,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
}
const ordered: BrushPresetId[] = [];
for (const g of customGroups) {
if (!isDecorationCustomGroup(g)) continue;
ordered.push(...getValidBrushIdsInCustomGroup(g, customBrushes));
}
for (const sec of DECORATION_BRUSH_SECTIONS) {
ordered.push(
...getOrderedBrushIdsInBuiltinGroup(
sec.id,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
)
);
}
return ordered;
}
/**
* Returns the ordered list of Decoration Sub Tool Groups (custom Decoration groups first,
* then Background, Clothing, Effect) for Next/Previous SubTool Group navigation.
*/
export function getNavigableDecorationSubToolGroups(
customGroups: readonly CustomSubToolGroup[],
customBrushes: readonly CspBrush[],
brushGroupOverrides: BrushGroupOverridesMap = {},
builtinGroupOrders: BuiltinGroupOrdersMap = {}
): NavigableSubToolGroupEntry[] {
const entries: NavigableSubToolGroupEntry[] = [];
for (const g of customGroups) {
if (!isDecorationCustomGroup(g)) continue;
entries.push({
id: g.id,
label: g.name,
isCustom: true,
brushIds: getValidBrushIdsInCustomGroup(g, customBrushes),
});
}
for (const sec of DECORATION_BRUSH_SECTIONS) {
const ids = getOrderedBrushIdsInBuiltinGroup(
sec.id,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
if (ids.length > 0) {
entries.push({
id: sec.id,
label: sec.label,
isCustom: false,
brushIds: ids,
});
}
}
return entries;
}