A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import {
Plus,
MoreHorizontal,
LayoutGrid,
Copy,
Check,
Trash2,
Pencil,
Download,
Upload,
FolderPlus,
RefreshCw,
X,
} from 'lucide-react';
import { CanvasColorMode } from '../types/editor';
import { enforceColorMode } from '../utils/colorUtils';
import {
useColorSetsStore,
colorSetsStoreActions,
SWATCH_COLUMN_OPTIONS,
SwatchColumnCount,
ColorSwatch,
useToolStore,
toolStoreActions,
uiStoreActions,
} from '../stores';
import { IconButton } from './ui';
import { saveFileWithDialog } from '../utils/fileSaveDialog';
import {
COLOR_SET_IMPORT_ACCEPT,
isSupportedColorSetFilename,
} from '../utils/colorSetImport';
import {
extractFilenameFromPath,
isExternalFileDrag,
readTauriFileBytes,
} from '../utils/fileDropImport';
import { isImeComposing, useI18n } from '../i18n';
export interface ColorSetsPanelProps {
colorMode?: CanvasColorMode;
containerWidth?: number;
}
const ACTIVE_SWATCH_SHADOW = 'inset 0 0 0 1.5px #ffffff, inset 0 0 0 2.5px #111111';
function getSwatchHeightClass(columns: SwatchColumnCount): string {
if (columns >= 5) return 'aspect-square min-h-[16px] max-h-[34px]';
if (columns >= 3) return 'h-7';
return 'h-6';
}
function clampPopoverPosition(
anchorX: number,
anchorY: number,
menuWidth: number,
menuHeight: number
): { left: number; top: number } {
if (typeof window === 'undefined') return { left: anchorX, top: anchorY };
const pad = 8;
const left = Math.max(pad, Math.min(window.innerWidth - menuWidth - pad, anchorX));
const top = Math.max(pad, Math.min(window.innerHeight - menuHeight - pad, anchorY));
return { left, top };
}
export const ColorSetsPanel: React.FC<ColorSetsPanelProps> = React.memo(
({ colorMode = 'color', containerWidth = 224 }) => {
const { t, td } = useI18n();
const sets = useColorSetsStore((s) => s.sets);
const activeSetId = useColorSetsStore((s) => s.activeSetId);
const columns = useColorSetsStore((s) => s.setsColumns);
const primaryColor = useToolStore((s) => s.primaryColor);
const activeSet = sets.find((s) => s.id === activeSetId) ?? sets[0];
const isNarrow = containerWidth < 138;
// Inline create / rename state
const [editMode, setEditMode] = useState<'create' | 'rename' | null>(null);
const [editValue, setEditValue] = useState('');
const editInputRef = useRef<HTMLInputElement | null>(null);
// Set actions popover menu
const [setMenuOpen, setSetMenuOpen] = useState(false);
const [setMenuPos, setSetMenuPos] = useState<{ left: number; top: number } | null>(null);
const setMenuBtnRef = useRef<HTMLButtonElement | null>(null);
const setMenuRef = useRef<HTMLDivElement | null>(null);
// Swatch right-click context menu
const [swatchMenu, setSwatchMenu] = useState<{
swatch: ColorSwatch;
left: number;
top: number;
} | null>(null);
const swatchMenuRef = useRef<HTMLDivElement | null>(null);
// Drag-to-reorder state
const [dragIndex, setDragIndex] = useState<number | null>(null);
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
// External file drop state (.json, .cls, .png)
const panelRef = useRef<HTMLDivElement | null>(null);
const [isDragOverFiles, setIsDragOverFiles] = useState(false);
// Hidden file input for color set import (.json, .cls, .png)
const fileInputRef = useRef<HTMLInputElement | null>(null);
// Auto-focus inline input when entering create/rename mode
useEffect(() => {
if (editMode) {
editInputRef.current?.focus();
editInputRef.current?.select();
}
}, [editMode]);
// Dismiss set menu on outside click / Escape
useEffect(() => {
if (!setMenuOpen) return;
const onPointerDown = (e: MouseEvent) => {
const target = e.target as Node;
if (setMenuRef.current?.contains(target) || setMenuBtnRef.current?.contains(target)) {
return;
}
setSetMenuOpen(false);
};
const onKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') setSetMenuOpen(false);
};
window.addEventListener('mousedown', onPointerDown);
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('mousedown', onPointerDown);
window.removeEventListener('keydown', onKeyDown);
};
}, [setMenuOpen]);
// Dismiss swatch context menu on outside click / Escape
useEffect(() => {
if (!swatchMenu) return;
const onPointerDown = (e: MouseEvent) => {
const target = e.target as Node;
if (swatchMenuRef.current?.contains(target)) return;
setSwatchMenu(null);
};
const onKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') setSwatchMenu(null);
};
window.addEventListener('mousedown', onPointerDown);
window.addEventListener('keydown', onKeyDown);
return () => {
window.removeEventListener('mousedown', onPointerDown);
window.removeEventListener('keydown', onKeyDown);
};
}, [swatchMenu]);
const openSetMenu = useCallback(() => {
setSetMenuOpen((prev) => {
if (!prev) {
const rect = setMenuBtnRef.current?.getBoundingClientRect();
if (rect) {
setSetMenuPos(clampPopoverPosition(rect.right - 208, rect.bottom + 4, 208, 210));
} else {
setSetMenuPos({ left: 16, top: 64 });
}
return true;
}
return false;
});
}, []);
const beginCreateSet = useCallback(() => {
setSetMenuOpen(false);
setEditValue(t('Custom Set {n}', { n: sets.length + 1 }));
setEditMode('create');
}, [sets.length, t]);
const beginRenameSet = useCallback(() => {
if (!activeSet) return;
setSetMenuOpen(false);
setEditValue(td(activeSet.name));
setEditMode('rename');
}, [activeSet, td]);
const commitEdit = useCallback(() => {
const trimmed = editValue.trim();
if (!trimmed) {
setEditMode(null);
return;
}
if (editMode === 'create') {
colorSetsStoreActions.createSet(trimmed);
} else if (editMode === 'rename' && activeSet) {
colorSetsStoreActions.renameSet(activeSet.id, trimmed);
}
setEditMode(null);
}, [activeSet, editMode, editValue]);
const handleDuplicateSet = useCallback(() => {
if (!activeSet) return;
colorSetsStoreActions.duplicateSet(activeSet.id);
setSetMenuOpen(false);
}, [activeSet]);
const handleDeleteSet = useCallback(() => {
if (!activeSet || sets.length <= 1) return;
colorSetsStoreActions.deleteSet(activeSet.id);
setSetMenuOpen(false);
}, [activeSet, sets.length]);
const handleExportSet = useCallback(async () => {
if (!activeSet) return;
setSetMenuOpen(false);
const json = colorSetsStoreActions.exportSetJson(activeSet.id);
if (!json) return;
try {
const safeFileName = activeSet.name
.toLowerCase()
.replace(/[^a-z0-9-_]+/g, '-')
.replace(/^-+|-+$/g, '');
const suggestedName = `${safeFileName || 'color-set'}.inkcolorset.json`;
const res = await saveFileWithDialog({
data: json,
suggestedName,
mimeType: 'application/json',
description: t('Ink Studio Color Set'),
extensions: ['.json'],
category: 'color-set',
title: t('Save Color Set As'),
});
if (res.canceled) return;
uiStoreActions.showToast(
t('Exported color set "{name}"', { name: td(activeSet.name) })
);
} catch {
uiStoreActions.showToast(t('Could not export color set.'));
}
}, [activeSet, t, td]);
const importColorSetFiles = useCallback(async (files: File[]) => {
if (files.length === 0) return;
if (files.length === 1) {
try {
const result = await colorSetsStoreActions.importSetFile(files[0]);
if (result.ok) {
uiStoreActions.showToast(
t('Imported "{name}" ({count} colors)', {
name: td(result.set.name),
count: result.set.swatches.length,
})
);
} else {
uiStoreActions.showToast(td(result.error));
}
} catch {
uiStoreActions.showToast(t('Failed to read color set file.'));
}
return;
}
let importedCount = 0;
let lastImportedName = '';
let lastSwatchCount = 0;
let failedCount = 0;
let lastError = '';
for (const file of files) {
try {
const result = await colorSetsStoreActions.importSetFile(file);
if (result.ok) {
importedCount += 1;
lastImportedName = result.set.name;
lastSwatchCount = result.set.swatches.length;
} else {
failedCount += 1;
lastError = result.error;
}
} catch {
failedCount += 1;
lastError = 'Failed to read color set file.';
}
}
if (importedCount === 1 && failedCount === 0) {
uiStoreActions.showToast(
t('Imported "{name}" ({count} colors)', {
name: td(lastImportedName),
count: lastSwatchCount,
})
);
} else if (importedCount > 0) {
if (failedCount > 0) {
uiStoreActions.showToast(
importedCount === 1
? t('Imported {count} color set ({skipped} skipped)', {
count: importedCount,
skipped: failedCount,
})
: t('Imported {count} color sets ({skipped} skipped)', {
count: importedCount,
skipped: failedCount,
})
);
} else {
uiStoreActions.showToast(
importedCount === 1
? t('Imported {count} color set', { count: importedCount })
: t('Imported {count} color sets', { count: importedCount })
);
}
} else {
uiStoreActions.showToast(
lastError ? td(lastError) : t('Failed to import color set files.')
);
}
}, [t, td]);
const handleTriggerImport = useCallback(() => {
setSetMenuOpen(false);
fileInputRef.current?.click();
}, []);
const handleImportFileChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files ? Array.from(e.target.files) : [];
e.target.value = '';
await importColorSetFiles(files);
},
[importColorSetFiles]
);
const handlePanelDragOver = useCallback((e: React.DragEvent<HTMLDivElement>) => {
if (!isExternalFileDrag(e.dataTransfer)) return;
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = 'copy';
setIsDragOverFiles(true);
}, []);
const handlePanelDragLeave = useCallback((e: React.DragEvent<HTMLDivElement>) => {
if (!isDragOverFiles) return;
const related = e.relatedTarget as Node | null;
if (related && panelRef.current?.contains(related)) return;
setIsDragOverFiles(false);
}, [isDragOverFiles]);
const handlePanelDrop = useCallback(
(e: React.DragEvent<HTMLDivElement>) => {
if (!isExternalFileDrag(e.dataTransfer)) return;
e.preventDefault();
e.stopPropagation();
setIsDragOverFiles(false);
const files = e.dataTransfer.files ? Array.from(e.dataTransfer.files) : [];
if (files.length > 0) {
void importColorSetFiles(files);
}
},
[importColorSetFiles]
);
// Native Tauri v2 OS drag-and-drop listener for dropping .cls / .png / .json onto Color Sets
useEffect(() => {
if (typeof window === 'undefined') return;
if (!(window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__) return;
let cancelled = false;
let unlisten: (() => void) | null = null;
let hasSupportedPaths = false;
const isPointInPanel = (pos: { x: number; y: number }): boolean => {
const el = panelRef.current;
if (!el) return false;
const dpr = window.devicePixelRatio || 1;
const x = pos.x / dpr;
const y = pos.y / dpr;
const rect = el.getBoundingClientRect();
return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
};
void (async () => {
try {
const { getCurrentWebview } = await import('@tauri-apps/api/webview');
if (cancelled) return;
const stop = await getCurrentWebview().onDragDropEvent((event) => {
if (cancelled) return;
const payload = event.payload;
if (payload.type === 'enter') {
hasSupportedPaths =
payload.paths.length === 0 ||
payload.paths.some((p) => isSupportedColorSetFilename(p));
setIsDragOverFiles(hasSupportedPaths && isPointInPanel(payload.position));
} else if (payload.type === 'over') {
setIsDragOverFiles(hasSupportedPaths && isPointInPanel(payload.position));
} else if (payload.type === 'leave') {
hasSupportedPaths = false;
setIsDragOverFiles(false);
} else if (payload.type === 'drop') {
hasSupportedPaths = false;
setIsDragOverFiles(false);
if (!isPointInPanel(payload.position) || payload.paths.length === 0) return;
void (async () => {
let importedCount = 0;
let lastImportedName = '';
let lastSwatchCount = 0;
let failedCount = 0;
let lastError = '';
for (const filePath of payload.paths) {
const filename = extractFilenameFromPath(filePath);
if (!isSupportedColorSetFilename(filename)) {
failedCount += 1;
lastError =
'Unsupported color set format. Use .json, Clip Studio .cls, or .png palette files.';
continue;
}
try {
const bytes = await readTauriFileBytes(filePath);
const result = colorSetsStoreActions.importSetBytes(bytes, filename);
if (result.ok) {
importedCount += 1;
lastImportedName = result.set.name;
lastSwatchCount = result.set.swatches.length;
} else {
failedCount += 1;
lastError = result.error;
}
} catch {
failedCount += 1;
lastError = 'Failed to read color set file.';
}
}
if (importedCount === 1 && failedCount === 0) {
uiStoreActions.showToast(
t('Imported "{name}" ({count} colors)', {
name: td(lastImportedName),
count: lastSwatchCount,
})
);
} else if (importedCount > 0) {
if (failedCount > 0) {
uiStoreActions.showToast(
importedCount === 1
? t('Imported {count} color set ({skipped} skipped)', {
count: importedCount,
skipped: failedCount,
})
: t('Imported {count} color sets ({skipped} skipped)', {
count: importedCount,
skipped: failedCount,
})
);
} else {
uiStoreActions.showToast(
importedCount === 1
? t('Imported {count} color set', { count: importedCount })
: t('Imported {count} color sets', { count: importedCount })
);
}
} else if (lastError) {
uiStoreActions.showToast(td(lastError));
}
})();
}
});
if (cancelled) {
stop();
} else {
unlisten = stop;
}
} catch {
// Ignore when Tauri webview API is unavailable
}
})();
return () => {
cancelled = true;
unlisten?.();
};
}, [t, td]);
const handleAddCurrentColor = useCallback(() => {
if (!activeSet) return;
const effective =
colorMode && colorMode !== 'color'
? enforceColorMode(primaryColor, colorMode)
: primaryColor;
colorSetsStoreActions.addSwatch(effective, { setId: activeSet.id });
}, [activeSet, colorMode, primaryColor]);
const handleSwatchClick = useCallback(
(e: React.MouseEvent, swatch: ColorSwatch) => {
if (e.altKey && activeSet) {
e.preventDefault();
colorSetsStoreActions.removeSwatch(activeSet.id, swatch.id);
return;
}
toolStoreActions.setPrimaryColor(swatch.hex, true, colorMode);
},
[activeSet, colorMode]
);
const handleSwatchAuxClick = useCallback(
(e: React.MouseEvent, swatch: ColorSwatch) => {
if (e.button === 1) {
e.preventDefault();
toolStoreActions.setSecondaryColor(swatch.hex, true, colorMode);
}
},
[colorMode]
);
const handleSwatchContextMenu = useCallback(
(e: React.MouseEvent, swatch: ColorSwatch) => {
e.preventDefault();
e.stopPropagation();
const pos = clampPopoverPosition(e.clientX, e.clientY, 172, 160);
setSwatchMenu({ swatch, left: pos.left, top: pos.top });
},
[]
);
const handleCopyHex = useCallback(
(hex: string) => {
try {
void navigator.clipboard?.writeText(hex.toUpperCase());
} catch {
// Ignore clipboard errors in restricted environments
}
uiStoreActions.showToast(t('Copied {hex}', { hex: hex.toUpperCase() }));
setSwatchMenu(null);
},
[t]
);
const normalizedPrimary = primaryColor.toLowerCase();
const swatchHeightClass = getSwatchHeightClass(columns);
return (
<div
ref={panelRef}
data-testid="color-sets-panel"
onDragOver={handlePanelDragOver}
onDragLeave={handlePanelDragLeave}
onDrop={handlePanelDrop}
className={`flex flex-col h-full w-full min-h-0 select-none bg-ui-panel text-ui-primary overflow-hidden ${
isDragOverFiles ? 'ring-2 ring-inset ring-ui-accent bg-ui-accent-subtle' : ''
}`}
>
{/* Hidden color set import input (.json, .cls, .png) */}
<input
ref={fileInputRef}
data-testid="color-sets-import-input"
type="file"
accept={COLOR_SET_IMPORT_ACCEPT}
multiple
onChange={handleImportFileChange}
className="hidden"
/>
{/* Row 1: Set Selector + Management Menu */}
<div className="h-7 px-1.5 flex items-center gap-1 shrink-0 bg-ui-header border-b border-ui-subtle">
<select
data-testid="color-sets-selector"
aria-label={t('Active Color Set')}
value={activeSet?.id ?? ''}
onChange={(e) => colorSetsStoreActions.selectSet(e.target.value)}
className="flex-1 min-w-0 h-5 bg-ui-input text-ui-primary border border-ui-subtle hover:border-ui-default text-[11px] px-1.5 rounded-ui-xs cursor-pointer truncate"
>
{sets.map((set) => (
<option key={set.id} value={set.id} className="bg-ui-elevated text-ui-primary">
{td(set.name)}
</option>
))}
</select>
<button
ref={setMenuBtnRef}
type="button"
data-testid="color-sets-menu-btn"
onClick={openSetMenu}
title={t('Color Set Actions')}
aria-label={t('Color Set Actions')}
aria-expanded={setMenuOpen}
className="w-5 h-5 rounded-ui-xs flex items-center justify-center shrink-0 text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
>
<MoreHorizontal className="w-3.5 h-3.5" />
</button>
</div>
{/* Optional Inline Create / Rename Bar */}
{editMode && (
<div
data-testid="color-sets-inline-editor"
className="px-1.5 py-1 flex items-center gap-1 shrink-0 bg-ui-control border-b border-ui-subtle"
>
<input
ref={editInputRef}
data-testid="color-sets-name-input"
type="text"
value={editValue}
maxLength={48}
placeholder={editMode === 'create' ? t('New set name...') : t('Set name...')}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Enter') {
e.preventDefault();
commitEdit();
} else if (e.key === 'Escape') {
e.preventDefault();
setEditMode(null);
}
}}
className="flex-1 min-w-0 h-5 px-1.5 text-[11px] bg-ui-input text-ui-primary border border-ui-default focus:border-ui-focus rounded-ui-xs"
/>
<IconButton
size="xs"
data-testid="color-sets-name-confirm"
onClick={commitEdit}
title={t('Confirm')}
icon={<Check className="w-3 h-3 text-ui-success" />}
/>
<IconButton
size="xs"
data-testid="color-sets-name-cancel"
onClick={() => setEditMode(null)}
title={t('Cancel')}
icon={<X className="w-3 h-3" />}
/>
</div>
)}
{/* Row 2: Add Primary Swatch + Count + Column Width Selector (1..8) */}
<div className="h-6 px-1.5 flex items-center justify-between gap-1 shrink-0 bg-ui-panel border-b border-ui-subtle">
<div className="flex items-center gap-1 min-w-0">
<button
type="button"
data-testid="color-sets-add-swatch"
onClick={handleAddCurrentColor}
title={t('Add active color ({hex}) to "{set}"', {
hex: primaryColor.toUpperCase(),
set: activeSet ? td(activeSet.name) : t('Set'),
})}
aria-label={t('Add current color to set')}
className="h-4.5 px-1 rounded-ui-xs flex items-center gap-1 bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer shrink-0"
>
<span
className="w-2.5 h-2.5 rounded-[2px] border border-ui-strong shrink-0"
style={{ backgroundColor: primaryColor }}
/>
<Plus className="w-2.5 h-2.5" />
</button>
{!isNarrow && (
<span className="text-[10px] font-ui-mono tabular-nums text-ui-muted truncate">
{activeSet?.swatches.length ?? 0}
</span>
)}
</div>
<label
className="flex items-center gap-1 shrink-0 text-ui-muted"
title={t('Swatches per row (1–8)')}
>
{!isNarrow && <LayoutGrid className="w-2.5 h-2.5 text-ui-icon-muted shrink-0" />}
<select
data-testid="color-sets-columns-select"
aria-label={t('Color Sets columns')}
value={columns}
onChange={(e) =>
colorSetsStoreActions.setSetsColumns(
Number(e.target.value) as SwatchColumnCount
)
}
className="h-4.5 bg-ui-input text-ui-primary border border-ui-subtle hover:border-ui-default font-ui-mono tabular-nums text-[10px] px-1 rounded-ui-xs cursor-pointer"
>
{SWATCH_COLUMN_OPTIONS.map((n) => (
<option key={n} value={n} className="bg-ui-elevated text-ui-primary">
{n}
</option>
))}
</select>
</label>
</div>
{/* Swatch Grid */}
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden p-1.5">
{!activeSet || activeSet.swatches.length === 0 ? (
<div className="h-full min-h-[72px] flex flex-col items-center justify-center gap-1.5 text-center px-2 text-ui-muted">
<span className="text-[11px]">{t('Empty color set')}</span>
<button
type="button"
onClick={handleAddCurrentColor}
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 transition-colors"
>
{t('+ Add {hex}', { hex: primaryColor.toUpperCase() })}
</button>
</div>
) : (
<div
data-testid="color-sets-grid"
data-columns={columns}
style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
className="grid w-full border-t border-l border-ui-subtle"
>
{activeSet.swatches.map((swatch, idx) => {
const isActive = swatch.hex.toLowerCase() === normalizedPrimary;
const isDragTarget = dragOverIndex === idx && dragIndex !== null && dragIndex !== idx;
const swatchDisplayName = swatch.name ? td(swatch.name) : '';
const label = swatchDisplayName
? `${swatchDisplayName} (${swatch.hex.toUpperCase()})`
: swatch.hex.toUpperCase();
return (
<button
key={swatch.id}
type="button"
draggable
data-testid={`color-set-swatch-${idx}`}
data-hex={swatch.hex}
data-active={isActive ? 'true' : undefined}
aria-label={label}
aria-pressed={isActive}
title={t(
'{label} — Click: Primary · Middle: Secondary · Right-click: Menu · Alt+Click: Remove',
{ label }
)}
onClick={(e) => handleSwatchClick(e, swatch)}
onAuxClick={(e) => handleSwatchAuxClick(e, swatch)}
onContextMenu={(e) => handleSwatchContextMenu(e, swatch)}
onDragStart={(e) => {
setDragIndex(idx);
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', String(idx));
}}
onDragOver={(e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
if (dragOverIndex !== idx) setDragOverIndex(idx);
}}
onDragLeave={() => {
if (dragOverIndex === idx) setDragOverIndex(null);
}}
onDrop={(e) => {
e.preventDefault();
const from =
dragIndex !== null
? dragIndex
: Number.parseInt(e.dataTransfer.getData('text/plain'), 10);
if (Number.isFinite(from) && from !== idx) {
colorSetsStoreActions.reorderSwatch(activeSet.id, from, idx);
}
setDragIndex(null);
setDragOverIndex(null);
}}
onDragEnd={() => {
setDragIndex(null);
setDragOverIndex(null);
}}
style={{
backgroundColor: swatch.hex,
boxShadow: isActive ? ACTIVE_SWATCH_SHADOW : undefined,
}}
className={`relative w-full ${swatchHeightClass} border-r border-b border-ui-subtle cursor-pointer transition-opacity focus:outline-none focus-visible:z-20 focus-visible:ring-1 focus-visible:ring-ui-focus ${
isActive ? 'z-10' : 'hover:z-10'
} ${dragIndex === idx ? 'opacity-45' : ''} ${
isDragTarget ? 'ring-1 ring-inset ring-ui-accent z-20' : ''
}`}
/>
);
})}
</div>
)}
</div>
{/* Portaled Set Management Menu */}
{setMenuOpen &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={setMenuRef}
data-testid="color-sets-menu-popover"
style={{
position: 'fixed',
left: setMenuPos?.left ?? 16,
top: setMenuPos?.top ?? 64,
}}
className="w-52 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
>
<button
type="button"
data-testid="color-sets-action-new"
onClick={beginCreateSet}
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"
>
<FolderPlus className="w-3 h-3 text-ui-icon-muted" />
<span>{t('New Color Set')}</span>
</button>
<button
type="button"
data-testid="color-sets-action-rename"
onClick={beginRenameSet}
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"
>
<Pencil className="w-3 h-3 text-ui-icon-muted" />
<span>{t('Rename Set')}</span>
</button>
<button
type="button"
data-testid="color-sets-action-duplicate"
onClick={handleDuplicateSet}
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-icon-muted" />
<span>{t('Duplicate Set')}</span>
</button>
<div className="my-1 border-t border-ui-subtle" />
<button
type="button"
data-testid="color-sets-action-import"
onClick={handleTriggerImport}
title={t('Import Color Set (.json, Clip Studio .cls, or .png palette)')}
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"
>
<Upload className="w-3 h-3 text-ui-icon-muted shrink-0" />
<span>{t('Import Set (.json, .cls, .png)...')}</span>
</button>
<button
type="button"
data-testid="color-sets-action-export"
onClick={handleExportSet}
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-icon-muted" />
<span>{t('Export Set (JSON)...')}</span>
</button>
<div className="my-1 border-t border-ui-subtle" />
<button
type="button"
data-testid="color-sets-action-delete"
disabled={sets.length <= 1}
onClick={handleDeleteSet}
className={`w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm text-left ${
sets.length <= 1
? 'text-ui-disabled cursor-not-allowed'
: 'text-ui-danger hover:bg-ui-danger/15 cursor-pointer'
}`}
>
<Trash2 className="w-3 h-3" />
<span>{t('Delete Set')}</span>
</button>
</div>,
document.body
)}
{/* Portaled Swatch Context Menu */}
{swatchMenu &&
activeSet &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={swatchMenuRef}
data-testid="color-set-swatch-context-menu"
style={{
position: 'fixed',
left: swatchMenu.left,
top: swatchMenu.top,
}}
className="w-44 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
>
<div className="px-2 py-0.5 flex items-center gap-1.5 text-[10px] text-ui-muted">
<span
className="w-2.5 h-2.5 rounded-[2px] border border-ui-strong shrink-0"
style={{ backgroundColor: swatchMenu.swatch.hex }}
/>
<span className="font-ui-mono tabular-nums uppercase truncate">
{swatchMenu.swatch.hex}
</span>
{swatchMenu.swatch.name && (
<span className="truncate text-ui-secondary">· {td(swatchMenu.swatch.name)}</span>
)}
</div>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid="swatch-ctx-set-secondary"
onClick={() => {
toolStoreActions.setSecondaryColor(swatchMenu.swatch.hex, true, colorMode);
setSwatchMenu(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"
>
<span>{t('Set Secondary Color')}</span>
</button>
<button
type="button"
data-testid="swatch-ctx-replace"
onClick={() => {
const effective =
colorMode && colorMode !== 'color'
? enforceColorMode(primaryColor, colorMode)
: primaryColor;
colorSetsStoreActions.replaceSwatch(
activeSet.id,
swatchMenu.swatch.id,
effective
);
setSwatchMenu(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"
>
<RefreshCw className="w-3 h-3 text-ui-icon-muted" />
<span>{t('Replace with Primary')}</span>
</button>
<button
type="button"
data-testid="swatch-ctx-copy"
onClick={() => handleCopyHex(swatchMenu.swatch.hex)}
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-icon-muted" />
<span>{t('Copy Hex')}</span>
</button>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid="swatch-ctx-delete"
onClick={() => {
colorSetsStoreActions.removeSwatch(activeSet.id, swatchMenu.swatch.id);
setSwatchMenu(null);
}}
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 Swatch')}</span>
</button>
</div>,
document.body
)}
</div>
);
}
);
ColorSetsPanel.displayName = 'ColorSetsPanel';