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 { createPortal } from 'react-dom';
import {
Droplets,
Paintbrush,
Palette,
PenTool,
Pencil,
Plus,
Copy,
Download,
Trash2,
Loader2,
FolderDown,
FolderPlus,
Folder,
ChevronDown,
ChevronRight,
Sliders,
AlertTriangle,
Star,
Sparkles,
Layers,
MoreHorizontal,
Keyboard,
PencilLine,
ArrowLeft,
ArrowRight,
Check,
X,
Undo2,
GripVertical,
} from 'lucide-react';
import {
BrushCategory,
BrushPresetId,
BrushSettings,
CspBrush,
DecorationCategory,
isPaintTool,
} from '../types/editor';
import type { BrushListStyle, DensityPreset } from '../types/appearance';
import {
buildExportableBrush,
exportBrushToInkbFile,
importBrushFile,
isSupportedBrushFileName,
} from '../utils/inkbBrushFormat';
import {
deleteCustomBrush,
saveCustomBrush,
} from '../utils/brushStorage';
import {
ALL_BUILTIN_BRUSHES,
ALL_BUILTIN_BRUSH_SECTIONS,
BUILTIN_BRUSHES,
BUILTIN_BRUSH_SECTIONS,
DECORATION_BRUSHES,
DECORATION_BRUSH_SECTIONS,
DEFAULT_DECORATION_PRESET_ID,
BuiltinBrushDefinition,
isDecorationCategory,
resolveStaticBrushAssetUrl,
} from '../utils/presetBrushes';
import {
DEFAULT_BRUSH_PRESET_ID,
migrateLegacyPresetId,
saveActiveDecorationPresetId,
saveActivePresetId,
} from '../utils/brushPresetManager';
import {
useToolStore,
useUiStore,
uiStoreActions,
useWorkspaceStore,
workspaceStoreActions,
useSubToolGroupStore,
subToolGroupStoreActions,
} from '../stores';
import {
BuiltinTargetGroupId,
CustomSubToolGroup,
SUBTOOL_GROUP_COLOR_SWATCHES,
SubToolGroupIconId,
getEffectiveBrushGroupId,
getFactoryGroupIdForBrush,
getGroupDisplayLabel,
getOrderedBrushIdsInBuiltinGroup,
isBuiltinGroupTab,
isBuiltinTargetGroupId,
isDecorationCustomGroup,
} from '../utils/subToolGroups';
import { activateSubToolPreset } from '../utils/subToolNavigation';
import {
DEFAULT_COMMANDS,
buildSubToolShortcutCommands,
formatShortcutLabel,
getSubToolCommandId,
getSubToolGroupCommandId,
} from '../utils/shortcutManager';
import { SubToolShortcutModal } from './SubToolShortcutModal';
import { BrushPreview } from './BrushPreview';
import { IconButton } from './ui';
import { resolveAppearanceTokens } from '../utils/themeEngine';
import { NEUTRAL_BRUSH_DEFAULTS } from '../utils/brushPresetManager';
import { isImeComposing, useI18n } from '../i18n';
export interface SubToolListProps {
customBrushes: CspBrush[];
setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;
}
type BrushPointerDropTarget =
| { kind: 'create-group' }
| { kind: 'group-tab'; groupId: string }
| { kind: 'group-section'; groupId: string }
| {
kind: 'brush-row';
groupId: string;
targetPresetId: BrushPresetId;
position: 'before' | 'after';
}
| { kind: 'quick-brush-panel' };
interface ActiveBrushPointerDrag {
presetId: BrushPresetId;
name: string;
sourceGroupId: string;
pointerX: number;
pointerY: number;
target: BrushPointerDropTarget | null;
}
interface ActiveGroupTabPointerDrag {
groupId: string;
name: string;
pointerX: number;
pointerY: number;
targetGroupId: string | null;
}
function renderBuiltinIcon(icon: BuiltinBrushDefinition['icon']) {
if (icon === 'pen') return <PenTool className="w-3 h-3 shrink-0 opacity-80" />;
if (icon === 'pencil') return <Pencil className="w-3 h-3 shrink-0 opacity-80" />;
if (icon === 'droplets') return <Droplets className="w-3 h-3 shrink-0 text-sky-500" />;
if (icon === 'palette') return <Palette className="w-3 h-3 shrink-0 text-rose-500" />;
if (icon === 'sparkles') return <Sparkles className="w-3 h-3 shrink-0 text-violet-500" />;
return <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />;
}
function buildCustomBrushPreviewSettings(custom: CspBrush): Partial<BrushSettings> {
const tipDataUrl = custom.tipDataUrl || custom.subTips?.[0]?.dataUrl;
return {
...NEUTRAL_BRUSH_DEFAULTS,
preset: custom.id,
brushName: custom.name,
size: custom.size,
minSizeFactor: custom.minSizeFactor,
flow: custom.flow,
opacity: custom.opacity,
spacing: custom.spacing,
hardness: custom.hardness,
thickness: custom.thickness,
thicknessVertical: custom.thicknessVertical,
customTipDataUrl: tipDataUrl,
customTipAngle: custom.angle,
customTipAngleDynamics: custom.angleDynamics,
isColorTip: custom.isColorTip,
isDualToneTip: custom.isDualToneTip,
isRibbon: custom.isRibbon,
subTips: custom.subTips,
subTipOrder: custom.subTipOrder,
dynamics: custom.dynamics,
spray: custom.spray,
taper: custom.taper,
paperTexture: custom.paperTexture,
surfaceTextureId: custom.surfaceTextureId,
grainMappingMode: custom.grainMappingMode,
textureDensity: custom.textureDensity,
colorMixing: custom.colorMixing,
wetEdge: custom.wetEdge,
dualBrush: custom.dualBrush,
dualBrushConfig: custom.dualBrushConfig,
dualTipDataUrl: custom.secondaryTipDataUrl,
renderMode: custom.renderMode,
bristle: custom.bristle,
naturalPaint: custom.naturalPaint,
impasto: custom.impasto,
};
}
const STROKE_PREVIEW_METRICS: Record<
DensityPreset,
{ rowClass: string; compactRowClass: string; strokeW: number; strokeH: number; gridPreviewH: number }
> = {
compact: {
rowClass: 'min-h-[28px] py-0.5 px-2',
compactRowClass: 'min-h-[22px] py-0.5 px-2',
strokeW: 58,
strokeH: 20,
gridPreviewH: 26,
},
balanced: {
rowClass: 'min-h-[34px] py-1 px-2',
compactRowClass: 'min-h-[25px] py-1 px-2',
strokeW: 66,
strokeH: 24,
gridPreviewH: 30,
},
comfortable: {
rowClass: 'min-h-[40px] py-1.5 px-2.5',
compactRowClass: 'min-h-[30px] py-1.5 px-2.5',
strokeW: 74,
strokeH: 28,
gridPreviewH: 36,
},
};
function renderGroupIcon(icon: SubToolGroupIconId | undefined, color?: string | null) {
const style = color ? { color } : undefined;
const cls = 'w-2.5 h-2.5 shrink-0';
switch (icon) {
case 'pen':
return <PenTool className={cls} style={style} />;
case 'pencil':
return <Pencil className={cls} style={style} />;
case 'paintbrush':
return <Paintbrush className={cls} style={style} />;
case 'droplets':
return <Droplets className={cls} style={style} />;
case 'palette':
return <Palette className={cls} style={style} />;
case 'sparkles':
return <Sparkles className={cls} style={style} />;
case 'star':
return <Star className={cls} style={style} />;
case 'layers':
return <Layers className={cls} style={style} />;
case 'folder':
default:
return <Folder className={cls} style={style} />;
}
}
function shortBuiltinTabLabel(id: BrushCategory, fallback: string): string {
if (id === 'natural-paint') return 'Natural';
if (id === 'texture-fx') return 'FX';
return fallback;
}
function pointInRect(x: number, y: number, rect: DOMRect): boolean {
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
}
/**
* Pure hit-test for pointer-driven brush drag-and-drop (works reliably in Tauri 2 WebView2,
* browsers, mouse, and stylus without HTML5 drag-drop interference).
*/
function detectBrushDropTarget(
clientX: number,
clientY: number,
draggedPresetId: BrushPresetId,
rootEl: HTMLElement | null
): BrushPointerDropTarget | null {
if (typeof document === 'undefined') return null;
// 1. Check floating Quick Brush Panel first (outside SubToolList root)
const quickPanel = document.querySelector?.('[data-testid="quick-brush-panel"]') as HTMLElement | null;
if (quickPanel && pointInRect(clientX, clientY, quickPanel.getBoundingClientRect())) {
return { kind: 'quick-brush-panel' };
}
if (!rootEl) return null;
// 2. Check "+ Group" button directly
const createBtns = rootEl.querySelectorAll?.('[data-subtool-drop="create-group"]');
if (createBtns) {
for (let i = 0; i < createBtns.length; i++) {
const el = createBtns[i] as HTMLElement;
if (pointInRect(clientX, clientY, el.getBoundingClientRect())) {
return { kind: 'create-group' };
}
}
}
// 3. Check specific group tabs (custom & built-in)
const tabEls = rootEl.querySelectorAll?.('[data-subtool-drop-tab]');
if (tabEls) {
for (let i = 0; i < tabEls.length; i++) {
const el = tabEls[i] as HTMLElement;
const gid = el.getAttribute('data-subtool-drop-tab');
if (gid && pointInRect(clientX, clientY, el.getBoundingClientRect())) {
return { kind: 'group-tab', groupId: gid };
}
}
}
// 4. Empty space on the tab bar -> CSP drag-to-create new group!
const tabBar = rootEl.querySelector?.(
'[data-testid="subtool-group-tab-bar"], [data-testid="subtool-decoration-tab-bar"]'
) as HTMLElement | null;
if (tabBar && pointInRect(clientX, clientY, tabBar.getBoundingClientRect())) {
return { kind: 'create-group' };
}
// 5. Check individual brush rows for precise before/after insertion
const rowEls = rootEl.querySelectorAll?.('[data-subtool-drop-row]');
if (rowEls) {
for (let i = 0; i < rowEls.length; i++) {
const el = rowEls[i] as HTMLElement;
const rect = el.getBoundingClientRect();
if (!pointInRect(clientX, clientY, rect)) continue;
const raw = el.getAttribute('data-subtool-drop-row');
if (!raw) continue;
const sep = raw.indexOf('|');
if (sep < 0) continue;
const groupId = raw.slice(0, sep);
const targetPresetId = raw.slice(sep + 1);
if (targetPresetId === draggedPresetId) {
return { kind: 'group-section', groupId };
}
const midY = rect.top + rect.height / 2;
return {
kind: 'brush-row',
groupId,
targetPresetId,
position: clientY < midY ? 'before' : 'after',
};
}
}
// 6. Check group section containers (headers, empty zones, bottom padding)
const secEls = rootEl.querySelectorAll?.('[data-subtool-drop-section]');
if (secEls) {
for (let i = 0; i < secEls.length; i++) {
const el = secEls[i] as HTMLElement;
const gid = el.getAttribute('data-subtool-drop-section');
if (gid && pointInRect(clientX, clientY, el.getBoundingClientRect())) {
return { kind: 'group-section', groupId: gid };
}
}
}
return null;
}
function detectCustomGroupTabDropTarget(
clientX: number,
clientY: number,
draggedGroupId: string,
rootEl: HTMLElement | null
): string | null {
if (!rootEl) return null;
const tabEls = rootEl.querySelectorAll?.('[data-subtool-custom-tab]');
if (!tabEls) return null;
for (let i = 0; i < tabEls.length; i++) {
const el = tabEls[i] as HTMLElement;
const gid = el.getAttribute('data-subtool-custom-tab');
if (gid && gid !== draggedGroupId && pointInRect(clientX, clientY, el.getBoundingClientRect())) {
return gid;
}
}
return null;
}
export const SubToolList: React.FC<SubToolListProps> = React.memo(
({ customBrushes, setCustomBrushes }) => {
const { t, td } = useI18n();
const currentTool = useToolStore((s) => s.tool);
const activePreset = useToolStore((s) => s.activePresetId);
const quickBrushIds = useWorkspaceStore((s) => s.quickBrushPanel.brushIds);
const quickBrushVisible = useWorkspaceStore((s) => s.quickBrushPanel.visible);
const customGroups = useSubToolGroupStore((s) => s.groups);
const activeTab = useSubToolGroupStore((s) => s.activeTab);
const activeDecorationTab = useSubToolGroupStore((s) => s.activeDecorationTab);
const brushGroupOverrides = useSubToolGroupStore((s) => s.brushGroupOverrides);
const builtinGroupOrders = useSubToolGroupStore((s) => s.builtinGroupOrders);
const appSettings = useUiStore((s) => s.appSettings);
const shortcuts = appSettings.shortcuts;
const appearance = appSettings.appearance;
const brushListStyle: BrushListStyle = appearance.brushListStyle ?? 'stroke';
const density: DensityPreset = appearance.density ?? 'balanced';
const listMetrics = STROKE_PREVIEW_METRICS[density] ?? STROKE_PREVIEW_METRICS.balanced;
const resolvedTheme = useMemo(() => resolveAppearanceTokens(appearance), [appearance]);
const isLightScheme = resolvedTheme.colorScheme === 'light';
const previewInkColor = resolvedTheme.tokens['--ui-text-primary'];
const previewSecondaryColor = resolvedTheme.tokens['--ui-text-muted'];
const isDecorationMode = currentTool === 'decoration';
const quickBrushSet = useMemo(
() => new Set(quickBrushIds.map((id) => migrateLegacyPresetId(id))),
[quickBrushIds]
);
const builtinById = useMemo(
() => new Map<string, BuiltinBrushDefinition>(ALL_BUILTIN_BRUSHES.map((b) => [b.id, b])),
[]
);
const customById = useMemo(
() => new Map<string, CspBrush>(customBrushes.map((b) => [b.id, b])),
[customBrushes]
);
const customPreviewSettingsMap = useMemo(() => {
const map = new Map<string, Partial<BrushSettings>>();
for (const b of customBrushes) {
map.set(b.id, buildCustomBrushPreviewSettings(b));
}
return map;
}, [customBrushes]);
const allShortcutCommands = useMemo(
() => [...DEFAULT_COMMANDS, ...buildSubToolShortcutCommands(customBrushes, customGroups)],
[customBrushes, customGroups]
);
const [isImportingSut, setIsImportingSut] = useState(false);
const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);
const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>({});
const [isCreatingGroup, setIsCreatingGroup] = useState(false);
const [newGroupName, setNewGroupName] = useState('');
const [newGroupColor, setNewGroupColor] = useState<string | null>(
SUBTOOL_GROUP_COLOR_SWATCHES[1]?.hex ?? null
);
const [renamingGroupId, setRenamingGroupId] = useState<string | null>(null);
const [renameDraft, setRenameDraft] = useState('');
const [addBrushesGroupId, setAddBrushesGroupId] = useState<string | null>(null);
// Pointer-event drag-and-drop state (works natively in Tauri 2 WebView2 & browsers)
const [activeBrushDrag, setActiveBrushDrag] = useState<ActiveBrushPointerDrag | null>(null);
const [activeGroupDrag, setActiveGroupDrag] = useState<ActiveGroupTabPointerDrag | null>(null);
const suppressNextClickRef = useRef(false);
const [brushContextMenu, setBrushContextMenu] = useState<{
presetId: BrushPresetId;
name: string;
isCustom: boolean;
customBrush?: CspBrush;
x: number;
y: number;
} | null>(null);
const [groupContextMenu, setGroupContextMenu] = useState<{
group: CustomSubToolGroup;
index: number;
x: number;
y: number;
} | null>(null);
const [shortcutModalTarget, setShortcutModalTarget] = useState<{
commandId: string;
label: string;
kind: 'subtool' | 'group';
} | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
const scrollListRef = useRef<HTMLDivElement>(null);
const sutInputRef = useRef<HTMLInputElement>(null);
const contextMenuRef = useRef<HTMLDivElement>(null);
// Keep latest data accessible inside window pointer drag listeners
const customGroupsRef = useRef(customGroups);
customGroupsRef.current = customGroups;
const customBrushesRef = useRef(customBrushes);
customBrushesRef.current = customBrushes;
// Close context menus on outside click or Escape
useEffect(() => {
if (!brushContextMenu && !groupContextMenu) return;
const handleOutside = (e: MouseEvent) => {
if (contextMenuRef.current?.contains(e.target as Node)) return;
setBrushContextMenu(null);
setGroupContextMenu(null);
};
const handleKey = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') {
setBrushContextMenu(null);
setGroupContextMenu(null);
}
};
window.addEventListener('mousedown', handleOutside);
window.addEventListener('keydown', handleKey);
return () => {
window.removeEventListener('mousedown', handleOutside);
window.removeEventListener('keydown', handleKey);
};
}, [brushContextMenu, groupContextMenu]);
const brushCustomGroups = useMemo(
() => customGroups.filter((g) => !isDecorationCustomGroup(g)),
[customGroups]
);
const decorationCustomGroups = useMemo(
() => customGroups.filter((g) => isDecorationCustomGroup(g)),
[customGroups]
);
const scopedCustomGroups = isDecorationMode ? decorationCustomGroups : brushCustomGroups;
// Ensure activeTab remains valid if a custom group was deleted externally
const effectiveActiveTab = useMemo(() => {
if (activeTab === 'all' || activeTab === 'custom' || isBuiltinGroupTab(activeTab)) {
return activeTab;
}
return brushCustomGroups.some((g) => g.id === activeTab) ? activeTab : 'all';
}, [activeTab, brushCustomGroups]);
const effectiveActiveDecorationTab = useMemo(() => {
if (activeDecorationTab === 'all' || isDecorationCategory(activeDecorationTab)) {
return activeDecorationTab;
}
return decorationCustomGroups.some((g) => g.id === activeDecorationTab)
? activeDecorationTab
: 'all';
}, [activeDecorationTab, decorationCustomGroups]);
const activeCustomGroup = useMemo(() => {
const targetTab = isDecorationMode ? effectiveActiveDecorationTab : effectiveActiveTab;
return scopedCustomGroups.find((g) => g.id === targetTab) ?? null;
}, [isDecorationMode, effectiveActiveDecorationTab, effectiveActiveTab, scopedCustomGroups]);
const builtinGroupMemberIds = useMemo(() => {
const map: Record<BuiltinTargetGroupId, BrushPresetId[]> = {
pen: [],
sketch: [],
brush: [],
blend: [],
'natural-paint': [],
'texture-fx': [],
'deco-background': [],
'deco-clothing': [],
'deco-effect': [],
custom: [],
};
for (const sec of ALL_BUILTIN_BRUSH_SECTIONS) {
map[sec.id] = getOrderedBrushIdsInBuiltinGroup(
sec.id,
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
}
map.custom = getOrderedBrushIdsInBuiltinGroup(
'custom',
customGroups,
customBrushes,
brushGroupOverrides,
builtinGroupOrders
);
return map;
}, [customGroups, customBrushes, brushGroupOverrides, builtinGroupOrders]);
const builtinGroupMemberIdsRef = useRef(builtinGroupMemberIds);
builtinGroupMemberIdsRef.current = builtinGroupMemberIds;
const handleTogglePinToQuickPanel = (
presetId: BrushPresetId,
brushName: string,
e?: React.MouseEvent
) => {
e?.stopPropagation();
const added = workspaceStoreActions.toggleQuickBrush(presetId);
if (added && !useWorkspaceStore.getState().quickBrushPanel.visible) {
workspaceStoreActions.setQuickBrushPanelVisible(true);
}
uiStoreActions.showToast(
added
? t('Added "{name}" to Quick Brush Panel', { name: td(brushName) })
: t('Removed "{name}" from Quick Brush Panel', { name: td(brushName) })
);
};
const toggleSection = (key: string) => {
setCollapsedSections((prev) => ({ ...prev, [key]: !prev[key] }));
};
const handleSelectBrushPreset = (presetId: BrushPresetId) => {
activateSubToolPreset(presetId, customBrushes);
};
const updateShortcutOverride = (
commandId: string,
shortcut: string | null,
clearConflictIds?: string[]
) => {
const latest = useUiStore.getState().appSettings;
const nextShortcuts = { ...latest.shortcuts };
if (clearConflictIds) {
for (const cid of clearConflictIds) {
nextShortcuts[cid] = '';
}
}
if (shortcut === null) {
delete nextShortcuts[commandId];
} else {
nextShortcuts[commandId] = shortcut;
}
uiStoreActions.updateAppSettings({ ...latest, shortcuts: nextShortcuts });
if (shortcut) {
uiStoreActions.showToast(
t('Shortcut assigned: {shortcut}', { shortcut: formatShortcutLabel(shortcut) })
);
} else {
uiStoreActions.showToast(t('Shortcut cleared'));
}
};
const removeOrphanShortcut = (commandId: string) => {
const latest = useUiStore.getState().appSettings;
if (Object.prototype.hasOwnProperty.call(latest.shortcuts, commandId)) {
const nextShortcuts = { ...latest.shortcuts };
delete nextShortcuts[commandId];
uiStoreActions.updateAppSettings({ ...latest, shortcuts: nextShortcuts });
}
};
const handleImportBrush = async (file: File) => {
setIsImportingSut(true);
try {
const parsedBrush = await importBrushFile(file);
setCustomBrushes((prev) => [
parsedBrush,
...prev.filter(
(b) =>
b.name.toLowerCase() !== parsedBrush.name.toLowerCase() && b.id !== parsedBrush.id
),
]);
if (isDecorationMode) {
if (activeCustomGroup) {
subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, activeCustomGroup.id);
} else {
const targetDecoGroup = isDecorationCategory(effectiveActiveDecorationTab)
? effectiveActiveDecorationTab
: 'deco-effect';
subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, targetDecoGroup);
}
saveActiveDecorationPresetId(parsedBrush.id);
} else if (activeCustomGroup) {
subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, activeCustomGroup.id);
saveActivePresetId(parsedBrush.id);
} else if (isBuiltinGroupTab(effectiveActiveTab)) {
subToolGroupStoreActions.moveBrushToGroup(parsedBrush.id, effectiveActiveTab);
saveActivePresetId(parsedBrush.id);
} else {
saveActivePresetId(parsedBrush.id);
}
if (parsedBrush.importWarnings && parsedBrush.importWarnings.length > 0) {
const count = parsedBrush.importWarnings.length;
const first = parsedBrush.importWarnings[0];
uiStoreActions.showToast(
count === 1
? t('Imported "{name}" (Notice: {notice})', {
name: parsedBrush.name,
notice: first,
})
: t('Imported "{name}" with {count} CSP import notices — check inspector', {
name: parsedBrush.name,
count,
})
);
} else {
uiStoreActions.showToast(
activeCustomGroup
? t('Imported "{name}" into "{group}"', {
name: parsedBrush.name,
group: activeCustomGroup.name,
})
: t('Imported brush "{name}"', { name: parsedBrush.name })
);
}
} catch (err: unknown) {
const msg =
err instanceof Error ? err.message : t('Failed to import brush file.');
void uiStoreActions.alertDialog({
title: t('Brush Import Failed'),
message: msg,
});
} finally {
setIsImportingSut(false);
}
};
const handleExportBrush = async (presetId: string, e?: React.MouseEvent) => {
e?.stopPropagation();
try {
const liveSettings = useToolStore.getState().brushSettings;
const brush = buildExportableBrush(presetId, customBrushes, liveSettings);
const res = await exportBrushToInkbFile(brush);
if (res.exported) {
uiStoreActions.showToast(t('Saved brush "{fileName}"', { fileName: res.fileName }));
}
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : t('Failed to export brush.');
void uiStoreActions.alertDialog({
title: t('Brush Export Failed'),
message: msg,
});
}
};
const handleDeleteCustomBrush = async (e: React.MouseEvent | undefined, brush: CspBrush) => {
e?.stopPropagation();
const subtitle = brush.badge
? t('{badge} brush', { badge: td(brush.badge) })
: t('Imported custom brush');
const confirmed = await uiStoreActions.confirmDialog({
variant: 'danger',
title: t('Delete Brush'),
message: t('Are you sure you want to delete this brush?'),
detail: t('This permanently removes the brush from your library and cannot be undone.'),
confirmLabel: t('Delete'),
cancelLabel: t('Cancel'),
preview: {
imageUrl: brush.tipDataUrl,
title: brush.name,
subtitle,
},
});
if (confirmed) {
await deleteCustomBrush(brush.id);
workspaceStoreActions.removeQuickBrush(brush.id);
subToolGroupStoreActions.removeBrushFromAllGroups(brush.id);
removeOrphanShortcut(getSubToolCommandId(brush.id));
setCustomBrushes((prev) => prev.filter((b) => b.id !== brush.id));
if (activePreset === brush.id) {
const fallbackId = isDecorationMode
? DEFAULT_DECORATION_PRESET_ID ||
customBrushes.find((b) => b.id !== brush.id && isDecorationCategory(b.category))?.id ||
DEFAULT_BRUSH_PRESET_ID
: DEFAULT_BRUSH_PRESET_ID;
handleSelectBrushPreset(fallbackId);
}
}
};
const handleCreateNewBrush = async () => {
const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const base = buildExportableBrush(DEFAULT_BRUSH_PRESET_ID, customBrushes);
const targetCategory: BrushCategory = isDecorationMode
? isDecorationCategory(effectiveActiveDecorationTab)
? effectiveActiveDecorationTab
: 'deco-effect'
: isBuiltinGroupTab(effectiveActiveTab) && !isDecorationCategory(effectiveActiveTab)
? effectiveActiveTab
: 'pen';
const newBrush: CspBrush = {
...base,
id,
name: isDecorationMode ? t('New Decoration Brush') : t('New Brush'),
category: targetCategory,
badge: isDecorationMode ? 'Decoration' : 'Studio',
importedAt: Date.now(),
};
await saveCustomBrush(newBrush);
setCustomBrushes((prev) => [newBrush, ...prev]);
if (isDecorationMode) {
subToolGroupStoreActions.moveBrushToGroup(
newBrush.id,
activeCustomGroup ? activeCustomGroup.id : targetCategory
);
} else if (activeCustomGroup) {
subToolGroupStoreActions.moveBrushToGroup(newBrush.id, activeCustomGroup.id);
} else if (isBuiltinGroupTab(effectiveActiveTab)) {
subToolGroupStoreActions.moveBrushToGroup(newBrush.id, effectiveActiveTab);
}
activateSubToolPreset(newBrush.id, [newBrush, ...customBrushes]);
uiStoreActions.setBrushStudioModalOpen(true);
};
const handleDuplicateActiveBrush = async (sourcePresetId?: BrushPresetId) => {
const sourceId = sourcePresetId || activePreset || DEFAULT_BRUSH_PRESET_ID;
const liveSettings = useToolStore.getState().brushSettings;
const exported = buildExportableBrush(sourceId, customBrushes, liveSettings);
const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const dupBrush: CspBrush = {
...exported,
id,
name: t('{name} Copy', { name: td(exported.name) }),
badge: 'Studio',
importedAt: Date.now(),
};
await saveCustomBrush(dupBrush);
const nextList = [dupBrush, ...customBrushes];
setCustomBrushes(nextList);
const ownerGroupId = getEffectiveBrushGroupId(
sourceId,
customGroups,
brushGroupOverrides,
customBrushes
);
if (ownerGroupId && ownerGroupId !== 'custom') {
subToolGroupStoreActions.moveBrushToGroup(dupBrush.id, ownerGroupId);
}
activateSubToolPreset(dupBrush.id, nextList);
uiStoreActions.setBrushStudioModalOpen(true);
};
const handleCommitCreateGroup = () => {
const created = subToolGroupStoreActions.createGroup({
name: newGroupName.trim() || t('Custom Group {n}', { n: scopedCustomGroups.length + 1 }),
color: newGroupColor,
toolScope: isDecorationMode ? 'decoration' : 'brush',
selectTab: true,
});
setIsCreatingGroup(false);
setNewGroupName('');
uiStoreActions.showToast(t('Created Sub Tool group "{name}"', { name: created.name }));
};
const handleCreateGroupFromBrush = useCallback((presetId: BrushPresetId, brushName: string) => {
const decoScope = useToolStore.getState().tool === 'decoration';
const existingCount = useSubToolGroupStore
.getState()
.groups.filter((g) => (decoScope ? isDecorationCustomGroup(g) : !isDecorationCustomGroup(g)))
.length;
const created = subToolGroupStoreActions.createGroup({
name: t('Custom Group {n}', { n: existingCount + 1 }),
color: SUBTOOL_GROUP_COLOR_SWATCHES[1]?.hex ?? null,
toolScope: decoScope ? 'decoration' : 'brush',
initialBrushIds: [presetId],
selectTab: true,
});
setRenamingGroupId(created.id);
setRenameDraft(created.name);
uiStoreActions.showToast(
t('Created "{group}" with "{brush}"', { group: created.name, brush: td(brushName) })
);
}, [t, td]);
const handleDeleteCustomGroup = async (group: CustomSubToolGroup) => {
const confirmed = await uiStoreActions.confirmDialog({
variant: 'danger',
title: t('Delete Sub Tool Group'),
message: t('Delete custom group "{name}"?', { name: group.name }),
detail:
group.brushIds.length === 1
? t('Its 1 sub tool will safely return to their default sections.')
: group.brushIds.length > 1
? t('Its {count} sub tools will safely return to their default sections.', {
count: group.brushIds.length,
})
: t('This removes the empty custom Sub Tool group.'),
confirmLabel: t('Delete Group'),
cancelLabel: t('Cancel'),
});
if (confirmed) {
subToolGroupStoreActions.deleteGroup(group.id);
removeOrphanShortcut(getSubToolGroupCommandId(group.id));
if (addBrushesGroupId === group.id) setAddBrushesGroupId(null);
uiStoreActions.showToast(t('Deleted group "{name}"', { name: group.name }));
}
};
const handleCommitRenameGroup = (groupId: string) => {
const trimmed = renameDraft.trim();
if (trimmed) {
subToolGroupStoreActions.renameGroup(groupId, trimmed);
}
setRenamingGroupId(null);
setRenameDraft('');
};
const openBrushMenu = (
e: React.MouseEvent,
presetId: BrushPresetId,
name: string,
customBrush?: CspBrush
) => {
e.preventDefault();
e.stopPropagation();
setGroupContextMenu(null);
const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
setBrushContextMenu({
presetId,
name,
isCustom: Boolean(customBrush),
customBrush,
x: Math.max(8, Math.min(vw - 216, e.clientX)),
y: Math.max(40, Math.min(vh - 340, e.clientY)),
});
};
const openGroupMenu = (e: React.MouseEvent, group: CustomSubToolGroup, index: number) => {
e.preventDefault();
e.stopPropagation();
setBrushContextMenu(null);
const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
setGroupContextMenu({
group,
index,
x: Math.max(8, Math.min(vw - 196, e.clientX)),
y: Math.max(40, Math.min(vh - 240, e.clientY)),
});
};
// Unified Pointer-Event Drag for Brush Rows (works in Tauri 2 Windows WebView2 + Browser + Stylus!)
const startBrushPointerDrag = useCallback(
(
e: React.PointerEvent<HTMLDivElement>,
presetId: BrushPresetId,
name: string,
sourceGroupId: string
) => {
if (e.button !== 0) return;
// Never hijack clicks on inner action buttons (Pin star, menu, export, delete)
if ((e.target as HTMLElement | null)?.closest?.('button, input')) return;
const startX = e.clientX;
const startY = e.clientY;
let isDragging = false;
let latestTarget: BrushPointerDropTarget | null = null;
const cleanup = () => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancel);
window.removeEventListener('keydown', onKeyDown);
if (typeof document !== 'undefined' && document.body?.style) {
document.body.style.cursor = '';
}
setActiveBrushDrag(null);
};
const onKeyDown = (ev: KeyboardEvent) => {
if (ev.key === 'Escape' && isDragging) {
ev.preventDefault();
ev.stopPropagation();
cleanup();
}
};
const onMove = (ev: PointerEvent) => {
const dist = Math.hypot(ev.clientX - startX, ev.clientY - startY);
if (!isDragging) {
if (dist < 6) return;
isDragging = true;
setBrushContextMenu(null);
setGroupContextMenu(null);
if (typeof document !== 'undefined' && document.body?.style) {
document.body.style.cursor = 'grabbing';
}
}
// Gentle auto-scroll near top/bottom of SubToolList scroll area
const scrollEl = scrollListRef.current;
if (scrollEl) {
const sr = scrollEl.getBoundingClientRect();
if (ev.clientX >= sr.left && ev.clientX <= sr.right) {
if (ev.clientY >= sr.top && ev.clientY < sr.top + 22) {
scrollEl.scrollTop -= 8;
} else if (ev.clientY <= sr.bottom && ev.clientY > sr.bottom - 22) {
scrollEl.scrollTop += 8;
}
}
}
latestTarget = detectBrushDropTarget(ev.clientX, ev.clientY, presetId, rootRef.current);
setActiveBrushDrag({
presetId,
name,
sourceGroupId,
pointerX: ev.clientX,
pointerY: ev.clientY,
target: latestTarget,
});
};
const onCancel = () => {
cleanup();
};
const onUp = () => {
const wasDragging = isDragging;
const finalTarget = latestTarget;
cleanup();
if (!wasDragging) return;
// Suppress the synthetic trailing click right after drag release
suppressNextClickRef.current = true;
setTimeout(() => {
suppressNextClickRef.current = false;
}, 0);
if (!finalTarget) return;
if (finalTarget.kind === 'create-group') {
handleCreateGroupFromBrush(presetId, name);
return;
}
if (finalTarget.kind === 'quick-brush-panel') {
const added = workspaceStoreActions.addQuickBrush(presetId);
const displayName = td(name);
uiStoreActions.showToast(
added
? t('Added "{name}" to Quick Brushes', { name: displayName })
: t('"{name}" is already in Quick Brushes', { name: displayName })
);
return;
}
if (finalTarget.kind === 'brush-row') {
const visibleIds = isBuiltinTargetGroupId(finalTarget.groupId)
? builtinGroupMemberIdsRef.current[finalTarget.groupId]
: undefined;
subToolGroupStoreActions.reorderBrushInGroup(
finalTarget.groupId,
presetId,
finalTarget.targetPresetId,
finalTarget.position,
visibleIds
);
if (finalTarget.groupId !== sourceGroupId) {
const targetLabel = td(
getGroupDisplayLabel(finalTarget.groupId, customGroupsRef.current)
);
uiStoreActions.showToast(
t('Moved "{name}" to "{group}"', { name: td(name), group: targetLabel })
);
}
return;
}
if (finalTarget.kind === 'group-tab' || finalTarget.kind === 'group-section') {
if (finalTarget.groupId === sourceGroupId) return;
const visibleIds = isBuiltinTargetGroupId(finalTarget.groupId)
? builtinGroupMemberIdsRef.current[finalTarget.groupId]
: undefined;
const moved = subToolGroupStoreActions.moveBrushToGroup(
presetId,
finalTarget.groupId,
undefined,
visibleIds
);
if (moved) {
const targetLabel = td(
getGroupDisplayLabel(finalTarget.groupId, customGroupsRef.current)
);
uiStoreActions.showToast(
t('Moved "{name}" to "{group}"', { name: td(name), group: targetLabel })
);
}
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancel);
window.addEventListener('keydown', onKeyDown);
},
[handleCreateGroupFromBrush, t, td]
);
// Unified Pointer-Event Drag for Reordering Custom Group Tabs
const startCustomGroupTabDrag = useCallback(
(e: React.PointerEvent<HTMLButtonElement>, group: CustomSubToolGroup) => {
if (e.button !== 0) return;
const startX = e.clientX;
const startY = e.clientY;
let isDragging = false;
let latestTargetGroupId: string | null = null;
const cleanup = () => {
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancel);
window.removeEventListener('keydown', onKeyDown);
setActiveGroupDrag(null);
};
const onKeyDown = (ev: KeyboardEvent) => {
if (ev.key === 'Escape' && isDragging) {
ev.preventDefault();
cleanup();
}
};
const onMove = (ev: PointerEvent) => {
if (!isDragging) {
if (Math.hypot(ev.clientX - startX, ev.clientY - startY) < 6) return;
isDragging = true;
}
latestTargetGroupId = detectCustomGroupTabDropTarget(
ev.clientX,
ev.clientY,
group.id,
rootRef.current
);
setActiveGroupDrag({
groupId: group.id,
name: group.name,
pointerX: ev.clientX,
pointerY: ev.clientY,
targetGroupId: latestTargetGroupId,
});
};
const onCancel = () => cleanup();
const onUp = () => {
const wasDragging = isDragging;
const targetId = latestTargetGroupId;
cleanup();
if (!wasDragging) return;
suppressNextClickRef.current = true;
setTimeout(() => {
suppressNextClickRef.current = false;
}, 0);
if (targetId && targetId !== group.id) {
subToolGroupStoreActions.reorderGroup(group.id, targetId);
}
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancel);
window.addEventListener('keydown', onKeyDown);
},
[]
);
const resolveMemberEntry = (
presetId: BrushPresetId
): { id: BrushPresetId; builtin?: BuiltinBrushDefinition; custom?: CspBrush } | null => {
const custom = customById.get(presetId);
if (custom) return { id: custom.id, custom };
const norm = migrateLegacyPresetId(presetId);
const builtin = builtinById.get(norm);
if (builtin) return { id: builtin.id, builtin };
return null;
};
const renderBrushTipIcon = (
builtin?: BuiltinBrushDefinition,
custom?: CspBrush,
sizeClass = 'w-3.5 h-3.5'
) => {
if (custom) {
return custom.tipDataUrl ? (
<img
src={custom.tipDataUrl}
alt=""
draggable={false}
className={`${sizeClass} object-contain shrink-0 pointer-events-none ${
custom.isColorTip ? '' : isLightScheme ? 'invert' : 'brightness-125'
}`}
/>
) : (
<Paintbrush className="w-3 h-3 shrink-0 opacity-75" />
);
}
if (builtin) {
const firstStaticTip = Array.isArray(builtin.staticTips) ? builtin.staticTips[0] : undefined;
if (firstStaticTip?.assetPath) {
return (
<img
src={resolveStaticBrushAssetUrl(firstStaticTip.assetPath)}
alt=""
draggable={false}
className={`${sizeClass} object-contain shrink-0 pointer-events-none ${
builtin.settings.isColorTip ? '' : isLightScheme ? 'invert' : 'brightness-110'
}`}
/>
);
}
return renderBuiltinIcon(builtin.icon);
}
return <Paintbrush className="w-3 h-3 shrink-0 opacity-75" />;
};
const renderBrushRow = (
presetId: BrushPresetId,
options: {
builtin?: BuiltinBrushDefinition;
custom?: CspBrush;
ownerGroupId: string;
}
) => {
const { builtin, custom, ownerGroupId } = options;
const name = custom ? custom.name : builtin ? builtin.name : presetId;
const displayName = custom ? custom.name : builtin ? td(builtin.name, 'brushName') : td(presetId, 'brushName');
const isSelected =
isPaintTool(currentTool) &&
(activePreset === presetId ||
(!activePreset &&
presetId ===
(isDecorationMode ? DEFAULT_DECORATION_PRESET_ID : DEFAULT_BRUSH_PRESET_ID)));
const isPinned = quickBrushSet.has(migrateLegacyPresetId(presetId));
const boundShortcut = shortcuts[getSubToolCommandId(presetId)] || '';
const previewSettings = custom
? customPreviewSettingsMap.get(custom.id)
: builtin?.settings;
const isBeingDragged = activeBrushDrag?.presetId === presetId;
const dropRowMatch =
activeBrushDrag?.target?.kind === 'brush-row' &&
activeBrushDrag.target.groupId === ownerGroupId &&
activeBrushDrag.target.targetPresetId === presetId
? activeBrushDrag.target.position
: null;
const shortcutSuffix = boundShortcut ? ` (${formatShortcutLabel(boundShortcut)})` : '';
const rowTitle = builtin
? t('{name} — {desc}{shortcut} · Drag to move or reorder', {
name: displayName,
desc: td(builtin.desc),
shortcut: shortcutSuffix,
})
: t('{name}{shortcut} · Drag to move or reorder', {
name: displayName,
shortcut: shortcutSuffix,
});
// 1. GRID MODE: Clean 2-column visual brush cards with stroke preview + name below
if (brushListStyle === 'grid') {
return (
<div
key={presetId}
data-testid={`subtool-row-${presetId}`}
data-brush-view="grid"
data-selected={isSelected ? 'true' : 'false'}
data-subtool-drop-row={`${ownerGroupId}|${presetId}`}
onPointerDown={(e) => startBrushPointerDrag(e, presetId, name, ownerGroupId)}
onClick={() => {
if (suppressNextClickRef.current) return;
handleSelectBrushPreset(presetId);
}}
onContextMenu={(e) => openBrushMenu(e, presetId, name, custom)}
title={rowTitle}
className={`relative group flex flex-col gap-1 p-1.5 rounded-ui-sm border text-left transition-colors cursor-pointer select-none overflow-hidden ${
isBeingDragged
? 'opacity-40 bg-ui-control-hover border-ui-subtle'
: isSelected
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border'
: 'bg-ui-header/70 text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover hover:border-ui-default'
}`}
>
{isSelected && (
<span
aria-hidden="true"
className="pointer-events-none absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full bg-ui-accent"
/>
)}
{dropRowMatch === 'before' && (
<div
data-testid={`subtool-drop-indicator-before-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -top-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
{dropRowMatch === 'after' && (
<div
data-testid={`subtool-drop-indicator-after-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -bottom-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
{/* Stroke Preview Stage */}
<div className="relative w-full rounded-ui-xs bg-ui-input/75 border border-ui-subtle/80 flex items-center justify-center px-1 overflow-hidden">
<BrushPreview
preset={presetId}
settings={previewSettings}
strokeColor={previewInkColor}
secondaryColor={previewSecondaryColor}
height={listMetrics.gridPreviewH}
lazy
className="w-full"
/>
{/* Miniature tip glyph top-left */}
<span className="pointer-events-none absolute top-1 left-1 opacity-75 flex items-center justify-center">
{renderBrushTipIcon(builtin, custom, 'w-3 h-3')}
</span>
{/* Quick star & menu overlay top-right */}
<div className="absolute top-0.5 right-0.5 flex items-center gap-0.5">
<button
type="button"
data-testid={`subtool-quick-pin-${presetId}`}
onClick={(e) => handleTogglePinToQuickPanel(presetId, name, e)}
title={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-label={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-pressed={isPinned}
className={`w-4 h-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-opacity ${
isPinned
? 'opacity-95 text-ui-warning bg-ui-panel/80'
: 'opacity-0 group-hover:opacity-100 focus:opacity-100 text-ui-muted hover:text-ui-warning bg-ui-panel/90'
}`}
>
<Star className="w-2.5 h-2.5" fill={isPinned ? 'currentColor' : 'none'} />
</button>
<button
type="button"
data-testid={`subtool-menu-btn-${presetId}`}
onClick={(e) => openBrushMenu(e, presetId, name, custom)}
title={t('Sub Tool options for {name} (move group, shortcut, export)', {
name: displayName,
})}
aria-label={t('Options for {name}', { name: displayName })}
className="opacity-0 group-hover:opacity-100 focus:opacity-100 w-4 h-4 rounded-ui-xs bg-ui-panel/90 text-ui-muted hover:text-ui-primary flex items-center justify-center cursor-pointer transition-opacity"
>
<MoreHorizontal className="w-2.5 h-2.5" />
</button>
</div>
</div>
{/* Label & Shortcut Footer */}
<div className="flex items-center justify-between gap-1 min-w-0 px-0.5">
<span className="text-[10.5px] leading-tight truncate flex-1">{displayName}</span>
{custom?.importWarnings && custom.importWarnings.length > 0 && (
<span
title={custom.importWarnings.join('\n')}
className="text-ui-warning shrink-0"
aria-label={t('Import warning')}
>
<AlertTriangle className="w-2.5 h-2.5" />
</span>
)}
{boundShortcut && (
<span
data-testid={`subtool-shortcut-badge-${presetId}`}
className="text-[8px] font-ui-mono tabular-nums px-1 py-px rounded-ui-xs bg-ui-input text-ui-accent border border-ui-subtle shrink-0"
title={t('Shortcut: {shortcut}', {
shortcut: formatShortcutLabel(boundShortcut),
})}
>
{formatShortcutLabel(boundShortcut)}
</span>
)}
</div>
</div>
);
}
// 2. COMPACT MODE: Ultra-dense single-line high-capacity brush browser
if (brushListStyle === 'compact') {
return (
<div
key={presetId}
data-testid={`subtool-row-${presetId}`}
data-brush-view="compact"
data-selected={isSelected ? 'true' : 'false'}
data-subtool-drop-row={`${ownerGroupId}|${presetId}`}
onPointerDown={(e) => startBrushPointerDrag(e, presetId, name, ownerGroupId)}
onClick={() => {
if (suppressNextClickRef.current) return;
handleSelectBrushPreset(presetId);
}}
onContextMenu={(e) => openBrushMenu(e, presetId, name, custom)}
title={rowTitle}
className={`relative group w-full flex items-center gap-1.5 ${listMetrics.compactRowClass} rounded-ui-xs border text-left transition-colors cursor-pointer select-none ${
isBeingDragged
? 'opacity-40 bg-ui-control-hover border-transparent'
: isSelected
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-secondary border-transparent hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
{isSelected && (
<span
aria-hidden="true"
className="pointer-events-none absolute left-0 top-1 bottom-1 w-[2px] rounded-full bg-ui-accent"
/>
)}
{dropRowMatch === 'before' && (
<div
data-testid={`subtool-drop-indicator-before-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -top-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
{dropRowMatch === 'after' && (
<div
data-testid={`subtool-drop-indicator-after-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -bottom-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
<span className="w-3.5 h-3.5 flex items-center justify-center shrink-0">
{renderBrushTipIcon(builtin, custom, 'w-3 h-3')}
</span>
<span className="text-[11px] truncate leading-tight flex-1 min-w-0">{displayName}</span>
{custom?.importWarnings && custom.importWarnings.length > 0 && (
<span
title={custom.importWarnings.join('\n')}
className="text-ui-warning shrink-0"
aria-label={t('Import warning')}
>
<AlertTriangle className="w-2.5 h-2.5" />
</span>
)}
{boundShortcut && (
<span
data-testid={`subtool-shortcut-badge-${presetId}`}
className="text-[8.5px] font-ui-mono tabular-nums px-1 py-px rounded-ui-xs bg-ui-input text-ui-accent border border-ui-subtle shrink-0"
title={t('Shortcut: {shortcut}', {
shortcut: formatShortcutLabel(boundShortcut),
})}
>
{formatShortcutLabel(boundShortcut)}
</span>
)}
<div className="flex items-center gap-0.5 shrink-0">
<button
type="button"
data-testid={`subtool-quick-pin-${presetId}`}
onClick={(e) => handleTogglePinToQuickPanel(presetId, name, e)}
title={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-label={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-pressed={isPinned}
className={`shrink-0 cursor-pointer transition-opacity ${
isPinned
? 'opacity-95 text-ui-warning'
: isSelected
? 'opacity-55 hover:opacity-100 text-ui-muted hover:text-ui-warning'
: 'opacity-0 group-hover:opacity-100 focus:opacity-100 text-ui-muted hover:text-ui-warning'
}`}
>
<Star className="w-2.5 h-2.5" fill={isPinned ? 'currentColor' : 'none'} />
</button>
<button
type="button"
data-testid={`subtool-menu-btn-${presetId}`}
onClick={(e) => openBrushMenu(e, presetId, name, custom)}
title={t('Sub Tool options for {name} (move group, shortcut, export)', {
name: displayName,
})}
aria-label={t('Options for {name}', { name: displayName })}
className="opacity-0 group-hover:opacity-100 focus:opacity-100 text-ui-muted hover:text-ui-primary shrink-0 cursor-pointer"
>
<MoreHorizontal className="w-2.5 h-2.5" />
</button>
<button
type="button"
onClick={(e) => handleExportBrush(presetId, e)}
title={t('Export {name} (.inkb)', { name: displayName })}
className="opacity-0 group-hover:opacity-100 text-ui-muted hover:text-ui-primary shrink-0 cursor-pointer"
>
<Download className="w-2.5 h-2.5" />
</button>
{custom && (
<button
type="button"
onClick={(e) => void handleDeleteCustomBrush(e, custom)}
title={t('Delete brush')}
className="opacity-0 group-hover:opacity-100 text-ui-muted hover:text-ui-danger shrink-0 cursor-pointer"
>
<Trash2 className="w-2.5 h-2.5" />
</button>
)}
</div>
</div>
);
}
// 3. STROKE MODE (Atelier default): Miniature tip icon left, clean truncated name,
// subtle favorite star on hover/active, and crisp live stroke-curve preview on the right
return (
<div
key={presetId}
data-testid={`subtool-row-${presetId}`}
data-brush-view="stroke"
data-selected={isSelected ? 'true' : 'false'}
data-subtool-drop-row={`${ownerGroupId}|${presetId}`}
onPointerDown={(e) => startBrushPointerDrag(e, presetId, name, ownerGroupId)}
onClick={() => {
if (suppressNextClickRef.current) return;
handleSelectBrushPreset(presetId);
}}
onContextMenu={(e) => openBrushMenu(e, presetId, name, custom)}
title={rowTitle}
className={`relative group w-full flex items-center gap-1.5 ${listMetrics.rowClass} rounded-ui-xs border text-left transition-colors cursor-pointer select-none ${
isBeingDragged
? 'opacity-40 bg-ui-control-hover border-transparent'
: isSelected
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-secondary border-transparent hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
{isSelected && (
<span
aria-hidden="true"
className="pointer-events-none absolute left-0 top-1 bottom-1 w-[2px] rounded-full bg-ui-accent"
/>
)}
{/* Crisp CSP-style insertion indicator bar */}
{dropRowMatch === 'before' && (
<div
data-testid={`subtool-drop-indicator-before-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -top-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
{dropRowMatch === 'after' && (
<div
data-testid={`subtool-drop-indicator-after-${presetId}`}
className="pointer-events-none absolute left-1 right-1 -bottom-[1px] h-[2px] rounded-full bg-ui-accent z-20"
/>
)}
{/* Miniature tip icon slot */}
<span
className={`w-4 h-4 rounded-ui-xs flex items-center justify-center shrink-0 ${
isSelected ? 'text-ui-primary' : 'text-ui-icon-muted group-hover:text-ui-primary'
}`}
>
{renderBrushTipIcon(builtin, custom, 'w-3.5 h-3.5')}
</span>
{/* Clean single-line name + optional warning/shortcut/star */}
<div className="flex-1 min-w-0 flex items-center gap-1">
<span className="text-[11px] truncate leading-tight">{displayName}</span>
{custom?.importWarnings && custom.importWarnings.length > 0 && (
<span
title={custom.importWarnings.join('\n')}
className="text-ui-warning shrink-0"
aria-label={t('Import warning')}
>
<AlertTriangle className="w-2.5 h-2.5" />
</span>
)}
{boundShortcut && (
<span
data-testid={`subtool-shortcut-badge-${presetId}`}
className="text-[8.5px] font-ui-mono tabular-nums px-1 py-px rounded-ui-xs bg-ui-input text-ui-accent border border-ui-subtle shrink-0"
title={t('Shortcut: {shortcut}', {
shortcut: formatShortcutLabel(boundShortcut),
})}
>
{formatShortcutLabel(boundShortcut)}
</span>
)}
<button
type="button"
data-testid={`subtool-quick-pin-${presetId}`}
onClick={(e) => handleTogglePinToQuickPanel(presetId, name, e)}
title={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-label={
isPinned
? t('Remove {name} from Quick Brush Panel', { name: displayName })
: t('Add {name} to Quick Brush Panel', { name: displayName })
}
aria-pressed={isPinned}
className={`shrink-0 cursor-pointer transition-opacity ${
isPinned
? 'opacity-95 text-ui-warning'
: isSelected
? 'opacity-50 hover:opacity-100 text-ui-muted hover:text-ui-warning'
: 'opacity-0 group-hover:opacity-100 focus:opacity-100 text-ui-muted hover:text-ui-warning'
}`}
>
<Star className="w-2.5 h-2.5" fill={isPinned ? 'currentColor' : 'none'} />
</button>
</div>
{/* Crisp Theme-Adaptive Stroke Curve Preview */}
<div className="shrink-0 flex items-center justify-end relative">
<BrushPreview
preset={presetId}
settings={previewSettings}
strokeColor={previewInkColor}
secondaryColor={previewSecondaryColor}
width={listMetrics.strokeW}
height={listMetrics.strokeH}
lazy
className={isSelected ? 'opacity-100' : 'opacity-80 group-hover:opacity-100 transition-opacity'}
/>
{/* Hover action pill overlaid cleanly over right edge (zero layout shift) */}
<div className="opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity absolute right-0 top-1/2 -translate-y-1/2 flex items-center gap-0.5 px-1 py-0.5 rounded-ui-xs bg-ui-elevated/95 border border-ui-subtle shadow-sm">
<button
type="button"
data-testid={`subtool-menu-btn-${presetId}`}
onClick={(e) => openBrushMenu(e, presetId, name, custom)}
title={t('Sub Tool options for {name} (move group, shortcut, export)', {
name: displayName,
})}
aria-label={t('Options for {name}', { name: displayName })}
className="p-0.5 rounded-ui-xs text-ui-muted hover:text-ui-primary cursor-pointer"
>
<MoreHorizontal className="w-2.5 h-2.5" />
</button>
<button
type="button"
onClick={(e) => handleExportBrush(presetId, e)}
title={t('Export {name} (.inkb)', { name: displayName })}
className="p-0.5 rounded-ui-xs text-ui-muted hover:text-ui-primary cursor-pointer"
>
<Download className="w-2.5 h-2.5" />
</button>
{custom && (
<button
type="button"
onClick={(e) => void handleDeleteCustomBrush(e, custom)}
title={t('Delete brush')}
className="p-0.5 rounded-ui-xs text-ui-muted hover:text-ui-danger cursor-pointer"
>
<Trash2 className="w-2.5 h-2.5" />
</button>
)}
</div>
</div>
</div>
);
};
const renderBrushCollection = (
items: Array<{ id: BrushPresetId; builtin?: BuiltinBrushDefinition; custom?: CspBrush }>,
ownerGroupId: string
) => (
<div
className={
brushListStyle === 'grid'
? 'grid grid-cols-2 gap-1.5 pt-0.5'
: 'space-y-0.5'
}
>
{items.map((m) =>
renderBrushRow(m.id, {
builtin: m.builtin,
custom: m.custom,
ownerGroupId,
})
)}
</div>
);
const renderCustomGroupSection = (
group: CustomSubToolGroup,
groupIndex: number,
isFocusedSingleView: boolean
) => {
const sectionKey = `custom-group:${group.id}`;
const isCollapsed = !isFocusedSingleView && Boolean(collapsedSections[sectionKey]);
const groupShortcut = shortcuts[getSubToolGroupCommandId(group.id)] || '';
const isRenaming = renamingGroupId === group.id;
const isAddingBrushes = addBrushesGroupId === group.id;
const isSectionHighlighted =
activeBrushDrag?.target?.kind === 'group-section' &&
activeBrushDrag.target.groupId === group.id;
const resolvedMembers = group.brushIds
.map((bid) => resolveMemberEntry(bid))
.filter((x): x is NonNullable<typeof x> => x !== null);
return (
<div
key={group.id}
data-testid={`subtool-custom-group-section-${group.id}`}
data-subtool-drop-section={group.id}
className={`space-y-0.5 rounded-ui-xs transition-colors ${
!isFocusedSingleView ? 'border-t border-ui-subtle first:border-t-0 pt-1.5 first:pt-0.5' : ''
} ${
isSectionHighlighted
? 'bg-ui-accent-subtle ring-1 ring-ui-accent p-0.5'
: ''
}`}
>
{/* Custom Group Header */}
<div className="group/grp flex items-center justify-between gap-1 px-1 py-0.5">
{isRenaming ? (
<div className="flex items-center gap-1 flex-1 min-w-0">
<input
type="text"
data-testid={`subtool-group-rename-input-${group.id}`}
autoFocus
value={renameDraft}
maxLength={32}
onChange={(e) => setRenameDraft(e.target.value)}
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Enter') handleCommitRenameGroup(group.id);
if (e.key === 'Escape') {
setRenamingGroupId(null);
setRenameDraft('');
}
}}
onBlur={() => handleCommitRenameGroup(group.id)}
className="flex-1 min-w-0 bg-ui-input px-1.5 py-0.5 rounded-ui-xs text-[10px] text-ui-primary border border-ui-focus"
/>
</div>
) : (
<button
type="button"
onClick={() =>
isFocusedSingleView ? undefined : toggleSection(sectionKey)
}
onDoubleClick={() => {
setRenamingGroupId(group.id);
setRenameDraft(group.name);
}}
onContextMenu={(e) => openGroupMenu(e, group, groupIndex)}
className="flex items-center gap-1 min-w-0 flex-1 text-left text-[9.5px] uppercase tracking-[0.06em] text-ui-secondary hover:text-ui-primary select-none cursor-pointer"
title={t('{name} (double-click to rename, right-click for options)', {
name: group.name,
})}
>
{!isFocusedSingleView &&
(isCollapsed ? (
<ChevronRight className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
) : (
<ChevronDown className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
))}
{group.color ? (
<span
className="w-1.5 h-1.5 rounded-full shrink-0"
style={{ backgroundColor: group.color }}
/>
) : (
renderGroupIcon(group.icon, group.color)
)}
<span className="truncate font-medium">{group.name}</span>
<span className="text-[9px] text-ui-muted font-ui-mono tabular-nums shrink-0">
{resolvedMembers.length}
</span>
</button>
)}
<div className="flex items-center gap-0.5 shrink-0">
{groupShortcut && (
<span
data-testid={`subtool-group-shortcut-badge-${group.id}`}
className="text-[8.5px] font-ui-mono px-1 py-px rounded-ui-xs bg-ui-input text-ui-accent border border-ui-subtle"
title={t('Group shortcut: {shortcut}', {
shortcut: formatShortcutLabel(groupShortcut),
})}
>
{formatShortcutLabel(groupShortcut)}
</span>
)}
<button
type="button"
data-testid={`subtool-group-add-brushes-btn-${group.id}`}
onClick={() =>
setAddBrushesGroupId((cur) => (cur === group.id ? null : group.id))
}
title={t('Add or manage brushes in "{name}"', { name: group.name })}
className={`p-0.5 rounded-ui-xs cursor-pointer transition-colors ${
isAddingBrushes
? 'text-ui-accent bg-ui-control-active'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
<Plus className="w-2.5 h-2.5" />
</button>
<button
type="button"
data-testid={`subtool-group-menu-btn-${group.id}`}
onClick={(e) => openGroupMenu(e, group, groupIndex)}
title={t('Options for "{name}"', { name: group.name })}
className="p-0.5 rounded-ui-xs text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
>
<MoreHorizontal className="w-2.5 h-2.5" />
</button>
</div>
</div>
{/* Inline Add Brushes Picker for this custom group */}
{isAddingBrushes && (
<div
data-testid={`subtool-group-brush-picker-${group.id}`}
className="mx-0.5 p-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle space-y-1"
>
<div className="flex items-center justify-between text-[9.5px] text-ui-secondary">
<span>{t('Assign brushes to \u201c{name}\u201d', { name: group.name })}</span>
<button
type="button"
onClick={() => setAddBrushesGroupId(null)}
className="text-ui-muted hover:text-ui-primary cursor-pointer"
aria-label={t('Close brush picker')}
>
<X className="w-3 h-3" />
</button>
</div>
<div className="max-h-32 overflow-y-auto space-y-0.5 pr-0.5">
{customBrushes.map((cb) => {
const inThisGroup = group.brushIds.includes(cb.id);
return (
<button
key={cb.id}
type="button"
data-testid={`subtool-group-pick-${group.id}-${cb.id}`}
onClick={() => {
if (inThisGroup) {
subToolGroupStoreActions.removeBrushFromAllGroups(cb.id);
} else {
subToolGroupStoreActions.moveBrushToGroup(cb.id, group.id);
}
}}
className={`w-full flex items-center justify-between gap-1 px-1.5 py-0.5 rounded-ui-xs text-[10px] cursor-pointer ${
inThisGroup
? 'bg-ui-control-active text-ui-primary'
: 'text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'
}`}
>
<span className="truncate">{cb.name}</span>
{inThisGroup ? (
<Check className="w-2.5 h-2.5 text-ui-accent shrink-0" />
) : (
<Plus className="w-2.5 h-2.5 opacity-60 shrink-0" />
)}
</button>
);
})}
{(isDecorationMode ? DECORATION_BRUSHES : BUILTIN_BRUSHES).map((bb) => {
const inThisGroup = group.brushIds.includes(bb.id);
return (
<button
key={bb.id}
type="button"
data-testid={`subtool-group-pick-${group.id}-${bb.id}`}
onClick={() => {
if (inThisGroup) {
subToolGroupStoreActions.removeBrushFromAllGroups(bb.id);
} else {
subToolGroupStoreActions.moveBrushToGroup(bb.id, group.id);
}
}}
className={`w-full flex items-center justify-between gap-1 px-1.5 py-0.5 rounded-ui-xs text-[10px] cursor-pointer ${
inThisGroup
? 'bg-ui-control-active text-ui-primary'
: 'text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'
}`}
>
<span className="truncate">{td(bb.name)}</span>
{inThisGroup ? (
<Check className="w-2.5 h-2.5 text-ui-accent shrink-0" />
) : (
<Plus className="w-2.5 h-2.5 opacity-60 shrink-0" />
)}
</button>
);
})}
</div>
</div>
)}
{!isCollapsed &&
(resolvedMembers.length === 0 ? (
<div className="mx-0.5 px-2 py-2 rounded-ui-sm border border-dashed border-ui-default bg-ui-input text-center space-y-1">
<div className="text-[10px] text-ui-muted">
{t('Drag any brush here or add sub tools')}
</div>
<button
type="button"
onClick={() => setAddBrushesGroupId(group.id)}
className="px-2 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer"
>
{t('+ Add Sub Tools')}
</button>
</div>
) : (
renderBrushCollection(resolvedMembers, group.id)
))}
</div>
);
};
const getDragGhostHint = (drag: ActiveBrushPointerDrag): string | null => {
const target = drag.target;
if (!target) return null;
if (target.kind === 'create-group') return t('+ Create New Group');
if (target.kind === 'quick-brush-panel') return t('+ Pin to Quick Brushes');
if (target.kind === 'group-tab' || target.kind === 'group-section') {
if (target.groupId === drag.sourceGroupId) return null;
return t('Move to {group}', {
group: td(getGroupDisplayLabel(target.groupId, customGroups)),
});
}
if (target.kind === 'brush-row') {
const grpLabel = td(getGroupDisplayLabel(target.groupId, customGroups));
return target.groupId === drag.sourceGroupId
? target.position === 'before'
? t('Reorder (before)')
: t('Reorder (after)')
: t('Move to {group}', { group: grpLabel });
}
return null;
};
const importedMemberIds = builtinGroupMemberIds.custom;
const isCreateGroupDropActive = activeBrushDrag?.target?.kind === 'create-group';
return (
<div
ref={rootRef}
data-testid="subtool-list-root"
data-brush-list-style={brushListStyle}
data-density={density}
className="flex flex-col flex-1 min-h-0 overflow-hidden bg-ui-panel text-ui-primary"
>
{/* Top Action Bar */}
<div className="px-1.5 py-1 flex items-center justify-between gap-0.5 shrink-0 border-b border-ui-subtle">
<div className="flex items-center gap-0.5">
<IconButton
size="xs"
onClick={handleCreateNewBrush}
title={t('Create New Brush in Brush Studio')}
icon={<Plus className="w-3 h-3" />}
label={t('New')}
/>
<IconButton
size="xs"
data-testid="subtool-toolbar-new-group-btn"
active={isCreatingGroup}
onClick={() => {
setIsCreatingGroup((v) => !v);
setNewGroupName('');
}}
title={t('Create Custom Sub Tool Group')}
icon={<FolderPlus className="w-3 h-3" />}
/>
<IconButton
size="xs"
onClick={() => void handleDuplicateActiveBrush()}
title={t('Duplicate Active Brush')}
icon={<Copy className="w-2.5 h-2.5" />}
/>
<IconButton
size="xs"
onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}
title={t('Edit Active Brush in Brush Studio')}
icon={<Sliders className="w-2.5 h-2.5" />}
/>
</div>
<div className="flex items-center gap-0.5">
<IconButton
size="xs"
variant="warning"
data-testid="subtool-toggle-quick-brush-panel"
active={quickBrushVisible}
onClick={() => workspaceStoreActions.toggleQuickBrushPanelVisible()}
title={
quickBrushVisible
? t('Hide Quick-Access Brush Panel (Shift+B)')
: t('Show Quick-Access Brush Panel (Shift+B)')
}
aria-pressed={quickBrushVisible}
icon={<Star className="w-2.5 h-2.5" fill={quickBrushVisible ? 'currentColor' : 'none'} />}
/>
<IconButton
size="xs"
onClick={() => sutInputRef.current?.click()}
title={t('Import Brush (.inkb, .sut)')}
icon={<FolderDown className="w-2.5 h-2.5" />}
/>
<IconButton
size="xs"
onClick={() =>
handleExportBrush(
activePreset ||
(isDecorationMode
? DEFAULT_DECORATION_PRESET_ID || DEFAULT_BRUSH_PRESET_ID
: DEFAULT_BRUSH_PRESET_ID)
)
}
title={t('Export Active Brush (.inkb)')}
icon={<Download className="w-2.5 h-2.5" />}
/>
</div>
</div>
{/* Wrapping CSP-Style Sub Tool Group Tab Bar (scoped to Decoration when Decoration tool is active) */}
{isDecorationMode ? (
<div
data-testid="subtool-decoration-tab-bar"
className={`px-1.5 py-1 flex flex-wrap items-center gap-1 shrink-0 bg-ui-header border-b transition-colors ${
isCreateGroupDropActive
? 'border-ui-accent bg-ui-accent-subtle'
: 'border-ui-subtle'
}`}
>
<button
type="button"
data-testid="subtool-deco-tab-all"
onClick={() => subToolGroupStoreActions.setActiveDecorationTab('all')}
className={`relative h-5 px-1.5 rounded-ui-xs text-[10px] shrink-0 transition-colors cursor-pointer border ${
effectiveActiveDecorationTab === 'all'
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
title={t('Show all Decoration sub tools')}
>
{t('All')}
{effectiveActiveDecorationTab === 'all' && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
{/* User Custom Decoration SubTool Group Tabs */}
{decorationCustomGroups.map((group, idx) => {
const isTabActive = effectiveActiveDecorationTab === group.id;
const grpShortcut = shortcuts[getSubToolGroupCommandId(group.id)];
const isBrushDropOver =
activeBrushDrag?.target?.kind === 'group-tab' &&
activeBrushDrag.target.groupId === group.id;
const isGroupReorderOver = activeGroupDrag?.targetGroupId === group.id;
return (
<button
key={group.id}
type="button"
data-testid={`subtool-group-tab-${group.id}`}
data-subtool-drop-tab={group.id}
data-subtool-custom-tab={group.id}
onPointerDown={(e) => startCustomGroupTabDrag(e, group)}
onClick={() => {
if (suppressNextClickRef.current) return;
subToolGroupStoreActions.setActiveDecorationTab(group.id);
}}
onDoubleClick={() => {
subToolGroupStoreActions.setActiveDecorationTab(group.id);
setRenamingGroupId(group.id);
setRenameDraft(group.name);
}}
onContextMenu={(e) => openGroupMenu(e, group, idx)}
title={t('{name}{shortcut} — Drag brushes here or right-click for options', {
name: group.name,
shortcut: grpShortcut ? ` (${formatShortcutLabel(grpShortcut)})` : '',
})}
className={`relative h-5 px-1.5 rounded-ui-xs flex items-center gap-1 text-[10px] shrink-0 max-w-[100px] transition-colors cursor-pointer border ${
isBrushDropOver || isGroupReorderOver
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent ring-1 ring-ui-accent'
: isTabActive
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{group.color ? (
<span
className="w-1.5 h-1.5 rounded-full shrink-0"
style={{ backgroundColor: group.color }}
/>
) : (
renderGroupIcon(group.icon, group.color)
)}
<span className="truncate">{group.name}</span>
{isTabActive && !isBrushDropOver && !isGroupReorderOver && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
);
})}
{DECORATION_BRUSH_SECTIONS.map((sec) => {
const isTabActive = effectiveActiveDecorationTab === sec.id;
const isBrushDropOver =
activeBrushDrag?.target?.kind === 'group-tab' &&
activeBrushDrag.target.groupId === sec.id;
const secLabel = td(sec.label);
return (
<button
key={sec.id}
type="button"
data-testid={`subtool-group-tab-${sec.id}`}
data-subtool-drop-tab={sec.id}
onClick={() =>
subToolGroupStoreActions.setActiveDecorationTab(sec.id as DecorationCategory)
}
title={t(
'{label} decoration brushes — Drag any brush here to move it into {label}',
{ label: secLabel }
)}
className={`relative h-5 px-1.5 rounded-ui-xs text-[10px] shrink-0 transition-colors cursor-pointer border ${
isBrushDropOver
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent ring-1 ring-ui-accent'
: isTabActive
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{secLabel}
{isTabActive && !isBrushDropOver && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
);
})}
{/* Always-visible "+ Group" Button & CSP Drag-to-Create Drop Target */}
<button
type="button"
data-testid="subtool-create-group-btn"
data-subtool-drop="create-group"
onClick={() => {
setIsCreatingGroup((v) => !v);
setNewGroupName('');
}}
title={t('Create Custom Sub Tool Group (click or drag any brush here)')}
aria-label={t('Create Custom Sub Tool Group')}
className={`h-5 px-1.5 rounded-ui-xs flex items-center gap-0.5 text-[10px] shrink-0 transition-colors cursor-pointer border ${
isCreateGroupDropActive
? 'bg-ui-accent text-ui-accent-contrast border-transparent font-semibold'
: isCreatingGroup
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
: activeBrushDrag
? 'bg-ui-control text-ui-accent border-dashed border-ui-accent-border'
: 'bg-ui-control text-ui-secondary hover:text-ui-accent hover:bg-ui-control-hover border-ui-subtle'
}`}
>
<FolderPlus className="w-2.5 h-2.5 shrink-0" />
<span>{activeBrushDrag ? t('New Group') : t('+ Group')}</span>
</button>
</div>
) : (
<div
data-testid="subtool-group-tab-bar"
className={`px-1.5 py-1 flex flex-wrap items-center gap-1 shrink-0 bg-ui-header border-b transition-colors ${
isCreateGroupDropActive
? 'border-ui-accent bg-ui-accent-subtle'
: 'border-ui-subtle'
}`}
>
<button
type="button"
data-testid="subtool-group-tab-all"
onClick={() => subToolGroupStoreActions.setActiveTab('all')}
className={`relative h-5 px-1.5 rounded-ui-xs text-[10px] shrink-0 transition-colors cursor-pointer border ${
effectiveActiveTab === 'all'
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
title={t('Show all Sub Tool groups')}
>
{t('All')}
{effectiveActiveTab === 'all' && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
{/* User Custom SubTool Group Tabs */}
{brushCustomGroups.map((group, idx) => {
const isTabActive = effectiveActiveTab === group.id;
const grpShortcut = shortcuts[getSubToolGroupCommandId(group.id)];
const isBrushDropOver =
activeBrushDrag?.target?.kind === 'group-tab' &&
activeBrushDrag.target.groupId === group.id;
const isGroupReorderOver = activeGroupDrag?.targetGroupId === group.id;
return (
<button
key={group.id}
type="button"
data-testid={`subtool-group-tab-${group.id}`}
data-subtool-drop-tab={group.id}
data-subtool-custom-tab={group.id}
onPointerDown={(e) => startCustomGroupTabDrag(e, group)}
onClick={() => {
if (suppressNextClickRef.current) return;
subToolGroupStoreActions.setActiveTab(group.id);
}}
onDoubleClick={() => {
subToolGroupStoreActions.setActiveTab(group.id);
setRenamingGroupId(group.id);
setRenameDraft(group.name);
}}
onContextMenu={(e) => openGroupMenu(e, group, idx)}
title={t('{name}{shortcut} — Drag brushes here or right-click for options', {
name: group.name,
shortcut: grpShortcut ? ` (${formatShortcutLabel(grpShortcut)})` : '',
})}
className={`relative h-5 px-1.5 rounded-ui-xs flex items-center gap-1 text-[10px] shrink-0 max-w-[100px] transition-colors cursor-pointer border ${
isBrushDropOver || isGroupReorderOver
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent ring-1 ring-ui-accent'
: isTabActive
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{group.color ? (
<span
className="w-1.5 h-1.5 rounded-full shrink-0"
style={{ backgroundColor: group.color }}
/>
) : (
renderGroupIcon(group.icon, group.color)
)}
<span className="truncate">{group.name}</span>
{isTabActive && !isBrushDropOver && !isGroupReorderOver && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
);
})}
{/* Built-in Category Tabs (now full drop targets so you can move ANY brush into ANY group!) */}
{BUILTIN_BRUSH_SECTIONS.map((sec) => {
const isTabActive = effectiveActiveTab === sec.id;
const isBrushDropOver =
activeBrushDrag?.target?.kind === 'group-tab' &&
activeBrushDrag.target.groupId === sec.id;
const secLabel = td(sec.label);
return (
<button
key={sec.id}
type="button"
data-testid={`subtool-group-tab-${sec.id}`}
data-subtool-drop-tab={sec.id}
onClick={() => subToolGroupStoreActions.setActiveTab(sec.id)}
title={t('{label} sub tools — Drag any brush here to move it into {label}', {
label: secLabel,
})}
className={`relative h-5 px-1.5 rounded-ui-xs text-[10px] shrink-0 transition-colors cursor-pointer border ${
isBrushDropOver
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent ring-1 ring-ui-accent'
: isTabActive
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{td(shortBuiltinTabLabel(sec.id, sec.label))}
{isTabActive && !isBrushDropOver && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
);
})}
{importedMemberIds.length > 0 && (
<button
type="button"
data-testid="subtool-group-tab-custom"
data-subtool-drop-tab="custom"
onClick={() => subToolGroupStoreActions.setActiveTab('custom')}
title={t('Imported & custom brushes — Drag any brush here to move it into Imported')}
className={`relative h-5 px-1.5 rounded-ui-xs text-[10px] shrink-0 transition-colors cursor-pointer border ${
activeBrushDrag?.target?.kind === 'group-tab' &&
activeBrushDrag.target.groupId === 'custom'
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent ring-1 ring-ui-accent'
: effectiveActiveTab === 'custom'
? 'bg-ui-accent-subtle text-ui-primary font-medium border-ui-accent-border/45'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
}`}
>
{t('Imported')}
{effectiveActiveTab === 'custom' &&
!(activeBrushDrag?.target?.kind === 'group-tab' && activeBrushDrag.target.groupId === 'custom') && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
)}
{/* Always-visible "+ Group" Button & CSP Drag-to-Create Drop Target */}
<button
type="button"
data-testid="subtool-create-group-btn"
data-subtool-drop="create-group"
onClick={() => {
setIsCreatingGroup((v) => !v);
setNewGroupName('');
}}
title={t('Create Custom Sub Tool Group (click or drag any brush here)')}
aria-label={t('Create Custom Sub Tool Group')}
className={`h-5 px-1.5 rounded-ui-xs flex items-center gap-0.5 text-[10px] shrink-0 transition-colors cursor-pointer border ${
isCreateGroupDropActive
? 'bg-ui-accent text-ui-accent-contrast border-transparent font-semibold'
: isCreatingGroup
? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
: activeBrushDrag
? 'bg-ui-control text-ui-accent border-dashed border-ui-accent-border'
: 'bg-ui-control text-ui-secondary hover:text-ui-accent hover:bg-ui-control-hover border-ui-subtle'
}`}
>
<FolderPlus className="w-2.5 h-2.5 shrink-0" />
<span>{activeBrushDrag ? t('New Group') : t('+ Group')}</span>
</button>
</div>
)}
{/* Inline New Custom Group Creator */}
{isCreatingGroup && (
<div
data-testid="subtool-create-group-form"
className="px-2 py-1.5 bg-ui-header border-b border-ui-subtle space-y-1.5 shrink-0"
>
<div className="flex items-center gap-1">
<input
type="text"
data-testid="subtool-create-group-input"
autoFocus
value={newGroupName}
maxLength={32}
placeholder={t('Custom Group {n}', { n: scopedCustomGroups.length + 1 })}
onChange={(e) => setNewGroupName(e.target.value)}
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Enter') {
e.preventDefault();
handleCommitCreateGroup();
} else if (e.key === 'Escape') {
setIsCreatingGroup(false);
}
}}
className="flex-1 min-w-0 h-6 px-2 rounded-ui-sm bg-ui-input text-[11px] text-ui-primary placeholder:text-ui-muted border border-ui-default"
/>
<button
type="button"
data-testid="subtool-create-group-confirm"
onClick={handleCommitCreateGroup}
className="h-6 px-2 rounded-ui-sm bg-ui-accent text-ui-accent-contrast text-[10px] font-medium cursor-pointer shrink-0"
>
{t('Create')}
</button>
<button
type="button"
onClick={() => setIsCreatingGroup(false)}
aria-label={t('Cancel creating group')}
className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer shrink-0"
>
<X className="w-3 h-3" />
</button>
</div>
<div className="flex items-center gap-1.5">
<span className="text-[9.5px] text-ui-muted">{t('Tag:')}</span>
{SUBTOOL_GROUP_COLOR_SWATCHES.map((sw) => {
const selected = newGroupColor === sw.hex;
const swLabel = td(sw.label);
return (
<button
key={sw.id}
type="button"
onClick={() => setNewGroupColor(sw.hex)}
title={swLabel}
aria-label={t('Color {label}', { label: swLabel })}
className={`w-3.5 h-3.5 rounded-full flex items-center justify-center cursor-pointer transition-transform ${
selected ? 'ring-1 ring-ui-primary scale-110' : 'opacity-70 hover:opacity-100'
}`}
style={{
backgroundColor: sw.hex || 'var(--ui-bg-control-active)',
}}
/>
);
})}
</div>
</div>
)}
<input
type="file"
ref={sutInputRef}
accept=".inkb,.sut"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleImportBrush(file);
e.target.value = '';
}}
/>
{/* Compact High-Density Sectioned Sub-Tool List */}
<div
ref={scrollListRef}
onDragOver={(e) => {
if (e.dataTransfer.types.includes('Files')) {
e.preventDefault();
setIsDraggingFileOver(true);
}
}}
onDragLeave={() => setIsDraggingFileOver(false)}
onDrop={(e) => {
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
e.preventDefault();
setIsDraggingFileOver(false);
const files = Array.from(e.dataTransfer.files).filter((f) =>
isSupportedBrushFileName(f.name)
);
for (const f of files) handleImportBrush(f);
} else {
setIsDraggingFileOver(false);
}
}}
className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-1 relative min-h-[84px]"
>
{isDraggingFileOver && (
<div className="absolute inset-1 bg-ui-elevated/95 border border-ui-accent-border rounded-ui-sm flex flex-col items-center justify-center p-2 text-center z-30 pointer-events-none">
<FolderDown className="w-4 h-4 text-ui-accent mb-1" />
<span className="text-[10px] text-ui-primary">{t('Drop .inkb / .sut')}</span>
</div>
)}
{isImportingSut && (
<div className="px-2 py-1 rounded-ui-sm bg-ui-control border border-ui-subtle text-[10px] text-ui-primary flex items-center gap-1.5">
<Loader2 className="w-3 h-3 animate-spin" />
<span className="truncate">{t('Importing...')}</span>
</div>
)}
{/* Focused Single Custom Group View (works in both Brush and Decoration modes) */}
{activeCustomGroup &&
renderCustomGroupSection(
activeCustomGroup,
scopedCustomGroups.findIndex((g) => g.id === activeCustomGroup.id),
true
)}
{/* 'All' View: User Custom Groups at top (scoped to active tool mode) */}
{((isDecorationMode && effectiveActiveDecorationTab === 'all') ||
(!isDecorationMode && effectiveActiveTab === 'all')) &&
scopedCustomGroups.map((group, idx) => renderCustomGroupSection(group, idx, false))}
{/* Decoration Tool Group Sections (Background, Clothing, Effect — CSP-style) */}
{isDecorationMode &&
effectiveActiveDecorationTab === 'all' &&
decorationCustomGroups.length === 0 &&
!activeBrushDrag &&
DECORATION_BRUSH_SECTIONS.every((sec) => builtinGroupMemberIds[sec.id].length === 0) && (
<div
data-testid="subtool-decoration-empty-state"
className="px-2 py-4 text-[10px] text-ui-muted text-center border border-dashed border-ui-default rounded-ui-sm"
>
{t('No decoration brushes. Import (.inkb / .sut) or click New to add one.')}
</div>
)}
{isDecorationMode &&
(effectiveActiveDecorationTab === 'all' ||
isDecorationCategory(effectiveActiveDecorationTab)) &&
DECORATION_BRUSH_SECTIONS.filter(
(sec) =>
effectiveActiveDecorationTab === 'all' || sec.id === effectiveActiveDecorationTab
).map((section) => {
const memberIds = builtinGroupMemberIds[section.id];
const resolvedItems = memberIds
.map((id) => resolveMemberEntry(id))
.filter((x): x is NonNullable<typeof x> => x !== null);
if (
resolvedItems.length === 0 &&
effectiveActiveDecorationTab === 'all' &&
!activeBrushDrag
) {
return null;
}
const isCollapsed =
effectiveActiveDecorationTab === 'all' && Boolean(collapsedSections[section.id]);
const isSectionHighlighted =
activeBrushDrag?.target?.kind === 'group-section' &&
activeBrushDrag.target.groupId === section.id;
return (
<div
key={section.id}
data-testid={`subtool-builtin-section-${section.id}`}
data-subtool-drop-section={section.id}
className={`space-y-0.5 rounded-ui-xs transition-colors ${
effectiveActiveDecorationTab === 'all'
? 'border-t border-ui-subtle first:border-t-0 pt-1.5 first:pt-0.5'
: ''
} ${
isSectionHighlighted
? 'bg-ui-accent-subtle ring-1 ring-ui-accent p-0.5'
: ''
}`}
>
{effectiveActiveDecorationTab === 'all' && (
<button
type="button"
onClick={() => toggleSection(section.id)}
className="w-full flex items-center justify-between gap-1 px-1 py-0.5 text-[9px] uppercase tracking-[0.06em] text-ui-muted hover:text-ui-primary select-none cursor-pointer"
>
<span className="flex items-center gap-1 min-w-0">
{isCollapsed ? (
<ChevronRight className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
) : (
<ChevronDown className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
)}
<span className="truncate font-medium">{td(section.label)}</span>
</span>
<span className="text-[9px] text-ui-muted font-ui-mono tabular-nums shrink-0">
{resolvedItems.length}
</span>
</button>
)}
{!isCollapsed &&
(resolvedItems.length === 0 ? (
<div className="px-2 py-2 text-[10px] text-ui-muted text-center border border-dashed border-ui-default rounded-ui-sm">
{t('Drag any brush here to add to {label}', { label: td(section.label) })}
</div>
) : (
renderBrushCollection(resolvedItems, section.id)
))}
</div>
);
})}
{/* Built-in Sections (full drop targets for cross-group drag & reorder!) */}
{!isDecorationMode &&
(effectiveActiveTab === 'all' || isBuiltinGroupTab(effectiveActiveTab)) &&
BUILTIN_BRUSH_SECTIONS.filter(
(sec) => effectiveActiveTab === 'all' || sec.id === effectiveActiveTab
).map((section) => {
const memberIds = builtinGroupMemberIds[section.id];
const resolvedItems = memberIds
.map((id) => resolveMemberEntry(id))
.filter((x): x is NonNullable<typeof x> => x !== null);
if (resolvedItems.length === 0 && effectiveActiveTab === 'all' && !activeBrushDrag) {
return null;
}
const isCollapsed =
effectiveActiveTab === 'all' && Boolean(collapsedSections[section.id]);
const isSectionHighlighted =
activeBrushDrag?.target?.kind === 'group-section' &&
activeBrushDrag.target.groupId === section.id;
return (
<div
key={section.id}
data-testid={`subtool-builtin-section-${section.id}`}
data-subtool-drop-section={section.id}
className={`space-y-0.5 rounded-ui-xs transition-colors ${
effectiveActiveTab === 'all'
? 'border-t border-ui-subtle first:border-t-0 pt-1.5 first:pt-0.5'
: ''
} ${
isSectionHighlighted
? 'bg-ui-accent-subtle ring-1 ring-ui-accent p-0.5'
: ''
}`}
>
{effectiveActiveTab === 'all' && (
<button
type="button"
onClick={() => toggleSection(section.id)}
className="w-full flex items-center justify-between gap-1 px-1 py-0.5 text-[9px] uppercase tracking-[0.06em] text-ui-muted hover:text-ui-primary select-none cursor-pointer"
>
<span className="flex items-center gap-1 min-w-0">
{isCollapsed ? (
<ChevronRight className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
) : (
<ChevronDown className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
)}
<span className="truncate font-medium">{td(section.label)}</span>
</span>
<span className="text-[9px] text-ui-muted font-ui-mono tabular-nums shrink-0">
{resolvedItems.length}
</span>
</button>
)}
{!isCollapsed &&
(resolvedItems.length === 0 ? (
<div className="px-2 py-2 text-[10px] text-ui-muted text-center border border-dashed border-ui-default rounded-ui-sm">
{t('Drag any brush here to add to {label}', { label: td(section.label) })}
</div>
) : (
renderBrushCollection(resolvedItems, section.id)
))}
</div>
);
})}
{/* Imported / Custom Brushes Section */}
{!isDecorationMode &&
(effectiveActiveTab === 'all' || effectiveActiveTab === 'custom') &&
(importedMemberIds.length > 0 || (effectiveActiveTab === 'custom' && activeBrushDrag)) &&
(() => {
const resolvedImported = importedMemberIds
.map((id) => resolveMemberEntry(id))
.filter((x): x is NonNullable<typeof x> => x !== null);
return (
<div
data-testid="subtool-builtin-section-custom"
data-subtool-drop-section="custom"
className={`space-y-0.5 rounded-ui-xs transition-colors ${
effectiveActiveTab === 'all'
? 'border-t border-ui-subtle first:border-t-0 pt-1.5 first:pt-0.5'
: ''
} ${
activeBrushDrag?.target?.kind === 'group-section' &&
activeBrushDrag.target.groupId === 'custom'
? 'bg-ui-accent-subtle ring-1 ring-ui-accent p-0.5'
: ''
}`}
>
{effectiveActiveTab === 'all' && (
<button
type="button"
onClick={() => toggleSection('custom')}
className="w-full flex items-center justify-between gap-1 px-1 py-0.5 text-[9px] uppercase tracking-[0.06em] text-ui-muted hover:text-ui-primary select-none cursor-pointer"
>
<span className="flex items-center gap-1 min-w-0">
{collapsedSections.custom ? (
<ChevronRight className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
) : (
<ChevronDown className="w-2.5 h-2.5 shrink-0 text-ui-icon-muted" />
)}
<span className="truncate font-medium">{t('Imported')}</span>
</span>
<span className="text-[9px] text-ui-muted font-ui-mono tabular-nums shrink-0">
{resolvedImported.length}
</span>
</button>
)}
{(effectiveActiveTab === 'custom' || !collapsedSections.custom) &&
renderBrushCollection(resolvedImported, 'custom')}
</div>
);
})()}
</div>
{/* Portaled Floating Drag Ghost (Brush Move / Reorder / Create Group) */}
{activeBrushDrag &&
typeof document !== 'undefined' &&
createPortal(
<div
data-testid="subtool-drag-ghost"
style={{
position: 'fixed',
left: activeBrushDrag.pointerX + 14,
top: activeBrushDrag.pointerY + 12,
zIndex: 1200,
}}
className="pointer-events-none select-none flex items-center gap-1.5 px-2.5 py-1 rounded-ui-md bg-ui-floating border border-ui-accent shadow-ui-floating text-[11px] text-ui-primary"
>
<GripVertical className="w-3 h-3 text-ui-accent shrink-0" />
<span className="font-medium max-w-[140px] truncate">{td(activeBrushDrag.name)}</span>
{getDragGhostHint(activeBrushDrag) && (
<span className="text-[10px] text-ui-accent border-l border-ui-subtle pl-1.5 whitespace-nowrap">
{getDragGhostHint(activeBrushDrag)}
</span>
)}
</div>,
document.body
)}
{/* Portaled Floating Drag Ghost (Custom Group Tab Reorder) */}
{activeGroupDrag &&
typeof document !== 'undefined' &&
createPortal(
<div
style={{
position: 'fixed',
left: activeGroupDrag.pointerX + 12,
top: activeGroupDrag.pointerY + 10,
zIndex: 1200,
}}
className="pointer-events-none select-none flex items-center gap-1.5 px-2 py-1 rounded-ui-sm bg-ui-floating border border-ui-accent shadow-ui-floating text-[10px] text-ui-primary"
>
<Folder className="w-3 h-3 text-ui-accent" />
<span>{activeGroupDrag.name}</span>
</div>,
document.body
)}
{/* Portaled Brush Right-Click / Options Context Menu */}
{brushContextMenu &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={contextMenuRef}
data-testid="subtool-brush-context-menu"
style={{
position: 'fixed',
left: brushContextMenu.x,
top: brushContextMenu.y,
zIndex: 1000,
}}
onPointerDown={(e) => e.stopPropagation()}
className="w-52 max-h-[80vh] overflow-y-auto rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover p-1 text-[11px] text-ui-primary select-none"
>
<div className="px-2 py-0.5 text-[10px] text-ui-muted truncate font-medium">
{td(brushContextMenu.name)}
</div>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid="subtool-ctx-set-shortcut"
onClick={() => {
const target = brushContextMenu;
setBrushContextMenu(null);
setShortcutModalTarget({
commandId: getSubToolCommandId(target.presetId),
label: target.name,
kind: 'subtool',
});
}}
className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<span className="flex items-center gap-1.5">
<Keyboard className="w-3 h-3 text-ui-accent" />
<span>{t('Set Shortcut...')}</span>
</span>
{shortcuts[getSubToolCommandId(brushContextMenu.presetId)] && (
<span className="text-[9px] font-ui-mono text-ui-muted">
{formatShortcutLabel(shortcuts[getSubToolCommandId(brushContextMenu.presetId)])}
</span>
)}
</button>
{shortcuts[getSubToolCommandId(brushContextMenu.presetId)] && (
<button
type="button"
onClick={() => {
updateShortcutOverride(getSubToolCommandId(brushContextMenu.presetId), null);
setBrushContextMenu(null);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover text-ui-secondary hover:text-ui-primary cursor-pointer text-left"
>
<X className="w-3 h-3" />
<span>{t('Clear Shortcut')}</span>
</button>
)}
<div className="my-0.5 border-t border-ui-subtle" />
<div className="px-2 py-0.5 text-[9.5px] uppercase tracking-wider text-ui-muted">
{t('Move to Sub Tool Group')}
</div>
{(() => {
const currentGroupId = getEffectiveBrushGroupId(
brushContextMenu.presetId,
customGroups,
brushGroupOverrides,
customBrushes
);
const factoryGroupId = getFactoryGroupIdForBrush(
brushContextMenu.presetId,
customBrushes
);
return (
<>
{scopedCustomGroups.map((g) => {
const isMember = currentGroupId === g.id;
return (
<button
key={g.id}
type="button"
data-testid={`subtool-ctx-move-group-${g.id}`}
onClick={() => {
subToolGroupStoreActions.moveBrushToGroup(
brushContextMenu.presetId,
g.id
);
uiStoreActions.showToast(
t('Moved "{name}" to "{group}"', {
name: td(brushContextMenu.name),
group: g.name,
})
);
setBrushContextMenu(null);
}}
className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<span className="flex items-center gap-1.5 min-w-0">
<span
className="w-1.5 h-1.5 rounded-full shrink-0"
style={{ backgroundColor: g.color || 'var(--ui-icon-muted)' }}
/>
<span className="truncate">{g.name}</span>
</span>
{isMember && <Check className="w-3 h-3 text-ui-accent shrink-0" />}
</button>
);
})}
{(isDecorationMode ? DECORATION_BRUSH_SECTIONS : BUILTIN_BRUSH_SECTIONS).map(
(sec) => {
const isMember = currentGroupId === sec.id;
const secLabel = td(sec.label);
return (
<button
key={sec.id}
type="button"
data-testid={`subtool-ctx-move-group-${sec.id}`}
onClick={() => {
subToolGroupStoreActions.moveBrushToGroup(
brushContextMenu.presetId,
sec.id,
undefined,
builtinGroupMemberIds[sec.id]
);
uiStoreActions.showToast(
t('Moved "{name}" to "{group}"', {
name: td(brushContextMenu.name),
group: secLabel,
})
);
setBrushContextMenu(null);
}}
className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover text-ui-secondary hover:text-ui-primary cursor-pointer text-left"
>
<span className="truncate">{secLabel}</span>
{isMember && <Check className="w-3 h-3 text-ui-accent shrink-0" />}
</button>
);
})}
<button
type="button"
data-testid="subtool-ctx-new-group-with-brush"
onClick={() => {
const target = brushContextMenu;
setBrushContextMenu(null);
handleCreateGroupFromBrush(target.presetId, target.name);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover text-ui-accent cursor-pointer text-left"
>
<FolderPlus className="w-3 h-3 shrink-0" />
<span>{t('New Group with Brush...')}</span>
</button>
{currentGroupId !== factoryGroupId && (
<button
type="button"
data-testid="subtool-ctx-return-default"
onClick={() => {
subToolGroupStoreActions.removeBrushFromAllGroups(
brushContextMenu.presetId
);
uiStoreActions.showToast(
t('Returned "{name}" to default section', {
name: td(brushContextMenu.name),
})
);
setBrushContextMenu(null);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover text-ui-secondary hover:text-ui-primary cursor-pointer text-left"
>
<Undo2 className="w-3 h-3 shrink-0" />
<span>{t('Return to Default Section')}</span>
</button>
)}
</>
);
})()}
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
onClick={() => {
handleTogglePinToQuickPanel(brushContextMenu.presetId, brushContextMenu.name);
setBrushContextMenu(null);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<Star className="w-3 h-3 text-ui-warning" />
<span>
{quickBrushSet.has(migrateLegacyPresetId(brushContextMenu.presetId))
? t('Unpin from Quick Brushes')
: t('Pin to Quick Brushes')}
</span>
</button>
<button
type="button"
onClick={() => {
const target = brushContextMenu;
setBrushContextMenu(null);
activateSubToolPreset(target.presetId, customBrushes);
uiStoreActions.setBrushStudioModalOpen(true);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<Sliders className="w-3 h-3 text-ui-muted" />
<span>{t('Edit in Brush Studio')}</span>
</button>
<button
type="button"
onClick={() => {
const target = brushContextMenu;
setBrushContextMenu(null);
void handleDuplicateActiveBrush(target.presetId);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<Copy className="w-3 h-3 text-ui-muted" />
<span>{t('Duplicate')}</span>
</button>
<button
type="button"
onClick={() => {
const target = brushContextMenu;
setBrushContextMenu(null);
void handleExportBrush(target.presetId);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<Download className="w-3 h-3 text-ui-muted" />
<span>{t('Export (.inkb)')}</span>
</button>
{brushContextMenu.customBrush && (
<>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
onClick={() => {
const cb = brushContextMenu.customBrush!;
setBrushContextMenu(null);
void handleDeleteCustomBrush(undefined, cb);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-danger/15 text-ui-danger cursor-pointer text-left"
>
<Trash2 className="w-3 h-3" />
<span>{t('Delete Brush')}</span>
</button>
</>
)}
</div>,
document.body
)}
{/* Portaled Custom Group Right-Click / Options Menu */}
{groupContextMenu &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={contextMenuRef}
data-testid="subtool-group-context-menu"
style={{
position: 'fixed',
left: groupContextMenu.x,
top: groupContextMenu.y,
zIndex: 1000,
}}
onPointerDown={(e) => e.stopPropagation()}
className="w-48 rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover p-1 text-[11px] text-ui-primary select-none"
>
<div className="px-2 py-0.5 text-[10px] text-ui-muted truncate font-medium">
{t('Group: {name}', { name: groupContextMenu.group.name })}
</div>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid="subtool-grp-ctx-rename"
onClick={() => {
const grp = groupContextMenu.group;
setGroupContextMenu(null);
setRenamingGroupId(grp.id);
setRenameDraft(grp.name);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<PencilLine className="w-3 h-3 text-ui-muted" />
<span>{t('Rename Group')}</span>
</button>
<button
type="button"
data-testid="subtool-grp-ctx-add-brushes"
onClick={() => {
const grp = groupContextMenu.group;
setGroupContextMenu(null);
if (isDecorationCustomGroup(grp)) {
subToolGroupStoreActions.setActiveDecorationTab(grp.id);
} else {
subToolGroupStoreActions.setActiveTab(grp.id);
}
setAddBrushesGroupId(grp.id);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<Plus className="w-3 h-3 text-ui-accent" />
<span>{t('Manage Brushes...')}</span>
</button>
<button
type="button"
data-testid="subtool-grp-ctx-shortcut"
onClick={() => {
const grp = groupContextMenu.group;
setGroupContextMenu(null);
setShortcutModalTarget({
commandId: getSubToolGroupCommandId(grp.id),
label: t('Group: {name}', { name: grp.name }),
kind: 'group',
});
}}
className="w-full flex items-center justify-between gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
>
<span className="flex items-center gap-1.5">
<Keyboard className="w-3 h-3 text-ui-accent" />
<span>{t('Set Shortcut...')}</span>
</span>
{shortcuts[getSubToolGroupCommandId(groupContextMenu.group.id)] && (
<span className="text-[9px] font-ui-mono text-ui-muted">
{formatShortcutLabel(
shortcuts[getSubToolGroupCommandId(groupContextMenu.group.id)]
)}
</span>
)}
</button>
<div className="px-2 py-1 space-y-1">
<div className="text-[9.5px] text-ui-muted">{t('Group Tag Color')}</div>
<div className="flex items-center gap-1.5">
{SUBTOOL_GROUP_COLOR_SWATCHES.map((sw) => (
<button
key={sw.id}
type="button"
onClick={() => {
subToolGroupStoreActions.updateGroupAppearance(
groupContextMenu.group.id,
{ color: sw.hex }
);
setGroupContextMenu(null);
}}
title={td(sw.label)}
className={`w-3.5 h-3.5 rounded-full cursor-pointer ${
groupContextMenu.group.color === sw.hex
? 'ring-1 ring-ui-primary scale-110'
: 'opacity-75 hover:opacity-100'
}`}
style={{ backgroundColor: sw.hex || 'var(--ui-bg-control-active)' }}
/>
))}
</div>
</div>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
disabled={groupContextMenu.index <= 0}
onClick={() => {
subToolGroupStoreActions.moveGroup(groupContextMenu.group.id, -1);
setGroupContextMenu(null);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer text-left"
>
<ArrowLeft className="w-3 h-3 text-ui-muted" />
<span>{t('Move Group Left')}</span>
</button>
<button
type="button"
disabled={groupContextMenu.index >= scopedCustomGroups.length - 1}
onClick={() => {
subToolGroupStoreActions.moveGroup(groupContextMenu.group.id, 1);
setGroupContextMenu(null);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer text-left"
>
<ArrowRight className="w-3 h-3 text-ui-muted" />
<span>{t('Move Group Right')}</span>
</button>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid="subtool-grp-ctx-delete"
onClick={() => {
const grp = groupContextMenu.group;
setGroupContextMenu(null);
void handleDeleteCustomGroup(grp);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-danger/15 text-ui-danger cursor-pointer text-left"
>
<Trash2 className="w-3 h-3" />
<span>{t('Delete Group')}</span>
</button>
</div>,
document.body
)}
{/* Inline SubTool / Custom Group Shortcut Recorder Modal */}
{shortcutModalTarget && (
<SubToolShortcutModal
commandId={shortcutModalTarget.commandId}
targetLabel={shortcutModalTarget.label}
targetKind={shortcutModalTarget.kind}
currentShortcut={shortcuts[shortcutModalTarget.commandId] || ''}
shortcuts={shortcuts}
allCommands={allShortcutCommands}
onAssign={(cmdId, shortcut, conflictIds) =>
updateShortcutOverride(cmdId, shortcut, conflictIds)
}
onClear={(cmdId) => updateShortcutOverride(cmdId, null)}
onClose={() => setShortcutModalTarget(null)}
/>
)}
</div>
);
}
);
SubToolList.displayName = 'SubToolList';