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, useCallback, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import {
Disc,
SlidersHorizontal,
ArrowLeftRight,
PanelBottom,
ChevronDown,
Trash2,
} from 'lucide-react';
import { ColorWheel } from './ColorWheel';
import { ColorSlider } from './ColorSlider';
import {
SphereColorPicker,
SphereColorPickerModal,
SpherePickerSharedState,
createInitialSphereState,
} from './SphereColorPicker';
import { ToolType, CanvasColorMode } from '../types/editor';
import { isValidHex, enforceColorMode } from '../utils/colorUtils';
import { safeLocalStorageSetItem } from '../utils/safeStorage';
import {
useColorSetsStore,
colorSetsStoreActions,
toolStoreActions,
} from '../stores';
import { isImeComposing, useI18n } from '../i18n';
export interface ColorPanelProps {
primaryColor: string;
secondaryColor: string;
onPrimaryColorChange: (color: string, commit?: boolean) => void;
onSecondaryColorChange: (color: string, commit?: boolean) => void;
onSwapColors: () => void;
colorMode?: CanvasColorMode;
currentTool?: ToolType;
onSelectTool?: (tool: ToolType) => void;
recentColors?: string[];
containerWidth?: number;
containerHeight?: number;
}
type ColorPanelTab = 'wheel' | 'slider' | 'sphere';
const ACTIVE_SWATCH_SHADOW = 'inset 0 0 0 1.5px #ffffff, inset 0 0 0 2.5px #111111';
export const ColorPanel: React.FC<ColorPanelProps> = ({
primaryColor,
secondaryColor,
onPrimaryColorChange,
onSecondaryColorChange,
onSwapColors,
colorMode = 'color',
currentTool = 'brush',
onSelectTool,
recentColors = [],
containerWidth = 180,
containerHeight,
}) => {
const { t } = useI18n();
const [activeTab, setActiveTab] = useState<ColorPanelTab>(() => {
try {
const saved = localStorage.getItem('ink_color_tab');
if (saved === 'wheel' || saved === 'slider' || saved === 'sphere') return saved;
} catch {
// ignore
}
return 'wheel';
});
const showInlineSlidersBelowWheel = useColorSetsStore(
(s) => s.showInlineSlidersBelowWheel
);
const lastNonSphereTabRef = useRef<'wheel' | 'slider'>(
activeTab === 'slider' ? 'slider' : 'wheel'
);
const safePrimaryColor =
typeof primaryColor === 'string' && primaryColor.trim().length > 0 ? primaryColor : '#000000';
const safeSecondaryColor =
typeof secondaryColor === 'string' && secondaryColor.trim().length > 0 ? secondaryColor : '#ffffff';
const [activeTarget, setActiveTarget] = useState<'primary' | 'secondary'>('primary');
const activeColor = activeTarget === 'primary' ? safePrimaryColor : safeSecondaryColor;
const isMonoCanvas = colorMode === 'grayscale' || colorMode === 'monochrome';
// Local hex draft so partial edits type cleanly
const [hexDraft, setHexDraft] = useState(() => activeColor.toUpperCase());
useEffect(() => {
setHexDraft(activeColor.toUpperCase());
}, [activeColor]);
// Inline Color History Dropdown Popover state
const [historyOpen, setHistoryOpen] = useState(false);
const [historyPos, setHistoryPos] = useState<{ left: number; top: number; width: number } | null>(
null
);
const historyBtnRef = useRef<HTMLButtonElement | null>(null);
const historyRowRef = useRef<HTMLDivElement | null>(null);
const historyPopoverRef = useRef<HTMLDivElement | null>(null);
const [isSphereFloating, setIsSphereFloating] = useState(false);
const [sphereState, setSphereState] = useState<SpherePickerSharedState>(() =>
createInitialSphereState(primaryColor, isMonoCanvas)
);
const selectTab = useCallback((next: ColorPanelTab) => {
if (next !== 'sphere') {
lastNonSphereTabRef.current = next;
} else {
// Dock back when explicitly selecting the Sphere tab
setIsSphereFloating(false);
}
setActiveTab(next);
safeLocalStorageSetItem('ink_color_tab', next, 'color panel preference');
}, []);
const handleToggleInlineSliders = useCallback(() => {
if (activeTab !== 'wheel') {
selectTab('wheel');
colorSetsStoreActions.setShowInlineSlidersBelowWheel(true);
} else {
colorSetsStoreActions.toggleShowInlineSlidersBelowWheel();
}
}, [activeTab, selectTab]);
const handleUnpinSphere = useCallback(() => {
setIsSphereFloating(true);
const fallback = lastNonSphereTabRef.current;
setActiveTab(fallback);
safeLocalStorageSetItem('ink_color_tab', fallback, 'color panel preference');
}, []);
const handlePinSphere = useCallback(() => {
setIsSphereFloating(false);
setActiveTab('sphere');
safeLocalStorageSetItem('ink_color_tab', 'sphere', 'color panel preference');
}, []);
const applyColorValue = useCallback(
(rawHex: string, commit: boolean) => {
const clean = rawHex.trim();
if (!isValidHex(clean)) return;
let hex = clean.startsWith('#') ? clean : `#${clean}`;
if (colorMode && colorMode !== 'color') {
hex = enforceColorMode(hex, colorMode);
}
if (activeTarget === 'primary') {
onPrimaryColorChange(hex, commit);
} else {
onSecondaryColorChange(hex, commit);
}
},
[activeTarget, colorMode, onPrimaryColorChange, onSecondaryColorChange]
);
const handleHexChange = (raw: string) => {
setHexDraft(raw.toUpperCase());
const clean = raw.trim();
const bare = clean.startsWith('#') ? clean.slice(1) : clean;
if (bare.length === 6 && isValidHex(clean)) {
applyColorValue(clean, true);
}
};
const handleHexCommit = () => {
const clean = hexDraft.trim();
if (isValidHex(clean)) {
applyColorValue(clean, true);
} else {
setHexDraft(activeColor.toUpperCase());
}
};
const handleSphereColorChange = useCallback(
({ hex }: { hex: string }, commit?: boolean) => {
const finalHex =
colorMode && colorMode !== 'color' ? enforceColorMode(hex, colorMode) : hex;
if (activeTarget === 'primary') {
onPrimaryColorChange(finalHex, commit);
} else {
onSecondaryColorChange(finalHex, commit);
}
},
[activeTarget, colorMode, onPrimaryColorChange, onSecondaryColorChange]
);
const computeHistoryPopoverPosition = useCallback(() => {
if (typeof window === 'undefined') return { left: 12, top: 64, width: 212 };
const rowRect = historyRowRef.current?.getBoundingClientRect();
const btnRect = historyBtnRef.current?.getBoundingClientRect();
const anchor = rowRect ?? btnRect;
const width = Math.max(196, Math.min(264, Math.round(anchor?.width ?? containerWidth)));
const estHeight = 204;
const pad = 8;
let left = anchor ? anchor.right - width : 12;
left = Math.max(pad, Math.min(window.innerWidth - width - pad, left));
let top = anchor ? anchor.bottom + 4 : 64;
if (anchor && top + estHeight > window.innerHeight - pad && anchor.top - estHeight - 4 >= pad) {
top = anchor.top - estHeight - 4;
} else {
top = Math.max(pad, Math.min(window.innerHeight - estHeight - pad, top));
}
return { left, top, width };
}, [containerWidth]);
useEffect(() => {
if (!historyOpen) return;
const onPointerDown = (e: MouseEvent) => {
const target = e.target as Node;
if (
historyPopoverRef.current?.contains(target) ||
historyBtnRef.current?.contains(target)
) {
return;
}
setHistoryOpen(false);
};
const onKeyDown = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') setHistoryOpen(false);
};
const onReposition = () => {
setHistoryPos(computeHistoryPopoverPosition());
};
window.addEventListener('mousedown', onPointerDown);
window.addEventListener('keydown', onKeyDown);
window.addEventListener('resize', onReposition);
window.addEventListener('scroll', onReposition, true);
return () => {
window.removeEventListener('mousedown', onPointerDown);
window.removeEventListener('keydown', onKeyDown);
window.removeEventListener('resize', onReposition);
window.removeEventListener('scroll', onReposition, true);
};
}, [historyOpen, computeHistoryPopoverPosition]);
const toggleHistoryDropdown = useCallback(() => {
setHistoryOpen((prev) => {
if (!prev) {
setHistoryPos(computeHistoryPopoverPosition());
return true;
}
return false;
});
}, [computeHistoryPopoverPosition]);
// Fit 6..10 crisp 14px square swatches inline beside the Hex input & chevron
const inlineSwatchCount = Math.max(
5,
Math.min(10, Math.floor(Math.max(70, containerWidth - 96) / 14))
);
const inlineHistorySwatches = recentColors.slice(0, inlineSwatchCount);
const normalizedActiveColor = activeColor.toLowerCase();
const headerChromeHeight = 52;
const bodyAvailHeight = containerHeight
? Math.max(72, containerHeight - headerChromeHeight)
: undefined;
const inlineWheelHeight = Math.min(
184,
Math.max(118, bodyAvailHeight ? Math.round(bodyAvailHeight * 0.54) : 148)
);
return (
<div
data-testid="color-panel"
className="flex flex-col h-full w-full select-none bg-ui-panel text-ui-primary overflow-hidden"
>
{/* Row 1: Primary/Secondary Swatches + Swap + Mode Switchers + Inline Sliders Toggle */}
<div className="h-[26px] px-2 flex items-center justify-between gap-1 shrink-0 bg-ui-header border-b border-ui-subtle">
<div className="flex items-center gap-1 min-w-0">
{/* Primary / Secondary Swatch Pair */}
<div className="flex items-center gap-1 shrink-0">
<button
type="button"
onClick={() => setActiveTarget('primary')}
title={t('Primary: {color}', { color: primaryColor.toUpperCase() })}
className={`w-3.5 h-3.5 rounded-ui-xs cursor-pointer transition-transform ${
activeTarget === 'primary'
? 'scale-110 ring-[1.5px] ring-ui-accent'
: 'opacity-75 hover:opacity-100 ring-1 ring-ui-strong'
}`}
style={{ backgroundColor: primaryColor }}
/>
<button
type="button"
onClick={() => setActiveTarget('secondary')}
title={t('Secondary: {color}', { color: secondaryColor.toUpperCase() })}
className={`w-3.5 h-3.5 rounded-ui-xs cursor-pointer transition-transform ${
activeTarget === 'secondary'
? 'scale-110 ring-[1.5px] ring-ui-accent'
: 'opacity-75 hover:opacity-100 ring-1 ring-ui-strong'
}`}
style={{ backgroundColor: secondaryColor }}
/>
</div>
<button
type="button"
onClick={onSwapColors}
title={t('Swap Colors (X)')}
aria-label={t('Swap Colors')}
className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer transition-colors"
>
<ArrowLeftRight className="w-2.5 h-2.5" />
</button>
</div>
{/* Wheel / Sliders / 3D Sphere Tabs + Show Sliders Below Wheel Toggle */}
<div className="flex items-center gap-0.5 shrink-0">
<button
type="button"
data-testid="color-panel-tab-wheel"
onClick={() => selectTab('wheel')}
title={t('Color Wheel')}
aria-pressed={activeTab === 'wheel'}
className={`w-5 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
activeTab === 'wheel'
? 'bg-ui-control-active text-ui-accent'
: 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
<Disc className="w-3 h-3" />
</button>
<button
type="button"
data-testid="color-panel-tab-slider"
onClick={() => selectTab('slider')}
title={t('Color Sliders')}
aria-pressed={activeTab === 'slider'}
className={`w-5 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
activeTab === 'slider'
? 'bg-ui-control-active text-ui-accent'
: 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
<SlidersHorizontal className="w-3 h-3" />
</button>
<button
type="button"
data-testid="color-panel-tab-sphere"
onClick={() => {
if (activeTab === 'sphere' && !isSphereFloating) {
handleUnpinSphere();
} else if (isSphereFloating) {
handlePinSphere();
} else {
selectTab('sphere');
}
}}
title={
isSphereFloating
? t('3D Sphere (Floating — click to dock)')
: activeTab === 'sphere'
? t('3D Sphere (Docked — click to unpin & float)')
: t('3D Sphere Color Picker')
}
aria-label={t('3D Sphere Color Picker')}
aria-pressed={activeTab === 'sphere' || isSphereFloating}
className={`w-5 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
activeTab === 'sphere' || isSphereFloating
? 'bg-ui-control-active ring-1 ring-ui-accent-border'
: 'hover:bg-ui-control-hover'
}`}
>
<span
className="w-3 h-3 rounded-full block ring-1 ring-ui-default"
style={{
background:
'radial-gradient(circle at 32% 30%, #f5f5f5 0%, #9ca3af 48%, #2e3440 100%)',
}}
/>
</button>
<span className="w-px h-3 bg-ui-subtle mx-0.5 shrink-0" aria-hidden="true" />
<button
type="button"
data-testid="toggle-inline-sliders-btn"
onClick={handleToggleInlineSliders}
title={
activeTab === 'wheel' && showInlineSlidersBelowWheel
? t('Hide Sliders Below Wheel')
: t('Show Sliders Below Wheel')
}
aria-label={t('Show Sliders Below Wheel')}
aria-pressed={activeTab === 'wheel' && showInlineSlidersBelowWheel}
className={`w-5 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
activeTab === 'wheel' && showInlineSlidersBelowWheel
? 'bg-ui-accent-subtle text-ui-accent border border-ui-accent-border'
: 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'
}`}
>
<PanelBottom className="w-3 h-3" />
</button>
</div>
</div>
{/* Row 2: Compact Hex Input + Inline Recent Color History Strip + Dropdown Chevron */}
<div
ref={historyRowRef}
className="h-[26px] px-2 flex items-center gap-1.5 shrink-0 bg-ui-panel border-b border-ui-subtle"
>
<input
type="text"
data-testid="color-panel-hex-input"
value={hexDraft}
onChange={(e) => handleHexChange(e.target.value)}
onBlur={handleHexCommit}
onKeyDown={(e) => {
if (isImeComposing(e)) return;
if (e.key === 'Enter') handleHexCommit();
}}
maxLength={7}
aria-label={t('Hex Color')}
className="w-[58px] h-[18px] shrink-0 bg-ui-input text-ui-primary border border-ui-subtle focus:border-ui-focus font-ui-mono tabular-nums text-[10px] px-1 rounded-ui-xs"
title={t('Hex Color')}
/>
{/* Compact Inline Recent-Color History Strip */}
<div
data-testid="color-panel-inline-history"
className="flex-1 min-w-0 flex items-center overflow-hidden"
>
{inlineHistorySwatches.length > 0 ? (
<div className="inline-flex items-center border-t border-l border-ui-subtle max-w-full overflow-hidden">
{inlineHistorySwatches.map((hex, idx) => {
const isActive = hex.toLowerCase() === normalizedActiveColor;
return (
<button
key={`${hex}-${idx}`}
type="button"
data-testid={`color-panel-inline-swatch-${idx}`}
data-hex={hex}
onClick={() => applyColorValue(hex, false)}
title={t('Recent: {color}', { color: hex.toUpperCase() })}
aria-label={t('Recent color {color}', { color: hex.toUpperCase() })}
style={{
backgroundColor: hex,
boxShadow: isActive ? ACTIVE_SWATCH_SHADOW : undefined,
}}
className={`w-3.5 h-3.5 shrink-0 border-r border-b border-ui-subtle cursor-pointer focus:outline-none ${
isActive ? 'relative z-10' : ''
}`}
/>
);
})}
</div>
) : (
<span className="text-[9.5px] text-ui-muted truncate">{t('No history')}</span>
)}
</div>
{/* History Popover Dropdown Chevron */}
<button
ref={historyBtnRef}
type="button"
data-testid="color-panel-history-dropdown-btn"
onClick={toggleHistoryDropdown}
aria-expanded={historyOpen}
aria-haspopup="true"
aria-label={t('Open Color History')}
title={t('Recent Color History')}
className={`w-4 h-[18px] shrink-0 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors border ${
historyOpen
? 'bg-ui-control-active text-ui-accent border-ui-accent-border'
: 'bg-ui-control text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover border-ui-subtle'
}`}
>
<ChevronDown className="w-3 h-3" />
</button>
</div>
{/* Docked Content: Wheel (+ optional Inline Sliders), Sliders, or Inline 3D Sphere */}
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden flex flex-col">
{activeTab === 'wheel' ? (
showInlineSlidersBelowWheel ? (
<>
<div
className="shrink-0 w-full flex items-center justify-center"
style={{ height: inlineWheelHeight }}
>
<ColorWheel
primaryColor={primaryColor}
secondaryColor={secondaryColor}
onPrimaryColorChange={onPrimaryColorChange}
onSecondaryColorChange={onSecondaryColorChange}
onSwapColors={onSwapColors}
colorMode={colorMode}
currentTool={currentTool}
onSelectTool={onSelectTool}
recentColors={recentColors}
containerWidth={containerWidth}
containerHeight={inlineWheelHeight}
activeTarget={activeTarget}
onActiveTargetChange={setActiveTarget}
hideHeader={true}
/>
</div>
<div
data-testid="color-panel-inline-sliders"
className="shrink-0 border-t border-ui-subtle"
>
<ColorSlider
primaryColor={primaryColor}
secondaryColor={secondaryColor}
onPrimaryColorChange={onPrimaryColorChange}
onSecondaryColorChange={onSecondaryColorChange}
onSwapColors={onSwapColors}
colorMode={colorMode}
currentTool={currentTool}
onSelectTool={onSelectTool}
recentColors={[]}
containerWidth={containerWidth}
activeTarget={activeTarget}
onActiveTargetChange={setActiveTarget}
hideHeader={true}
compact={true}
/>
</div>
</>
) : (
<ColorWheel
primaryColor={primaryColor}
secondaryColor={secondaryColor}
onPrimaryColorChange={onPrimaryColorChange}
onSecondaryColorChange={onSecondaryColorChange}
onSwapColors={onSwapColors}
colorMode={colorMode}
currentTool={currentTool}
onSelectTool={onSelectTool}
recentColors={recentColors}
containerWidth={containerWidth}
containerHeight={bodyAvailHeight}
activeTarget={activeTarget}
onActiveTargetChange={setActiveTarget}
hideHeader={true}
/>
)
) : activeTab === 'slider' ? (
<ColorSlider
primaryColor={primaryColor}
secondaryColor={secondaryColor}
onPrimaryColorChange={onPrimaryColorChange}
onSecondaryColorChange={onSecondaryColorChange}
onSwapColors={onSwapColors}
colorMode={colorMode}
currentTool={currentTool}
onSelectTool={onSelectTool}
recentColors={[]}
containerWidth={containerWidth}
containerHeight={bodyAvailHeight}
activeTarget={activeTarget}
onActiveTargetChange={setActiveTarget}
hideHeader={true}
/>
) : (
<SphereColorPicker
variant="docked"
isPinned={true}
onTogglePin={handleUnpinSphere}
initialColor={activeColor}
monochromeDefault={isMonoCanvas}
sharedState={sphereState}
onSharedStateChange={setSphereState}
onColorChange={handleSphereColorChange}
onEyedropper={onSelectTool ? () => onSelectTool('pipette') : undefined}
/>
)}
</div>
{/* Portaled Color History Dropdown Popover */}
{historyOpen &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={historyPopoverRef}
data-testid="color-panel-history-popover"
style={{
position: 'fixed',
left: historyPos?.left ?? 12,
top: historyPos?.top ?? 64,
width: historyPos?.width ?? 212,
}}
className="rounded-ui-md shadow-ui-popover z-[1000] bg-ui-elevated border border-ui-default text-ui-primary overflow-hidden select-none"
>
<div className="h-6 px-2 flex items-center justify-between bg-ui-header border-b border-ui-subtle">
<span className="text-[10px] font-medium text-ui-secondary">
{t('Color History')}
<span className="ml-1 font-ui-mono tabular-nums text-ui-muted">
({recentColors.length})
</span>
</span>
<button
type="button"
data-testid="color-panel-history-popover-clear"
disabled={recentColors.length === 0}
onClick={() => toolStoreActions.clearRecentColors()}
title={t('Clear Color History')}
aria-label={t('Clear Color History')}
className={`w-4.5 h-4.5 rounded-ui-xs flex items-center justify-center transition-colors ${
recentColors.length === 0
? 'text-ui-disabled cursor-not-allowed'
: 'text-ui-icon-muted hover:text-ui-danger hover:bg-ui-control-hover cursor-pointer'
}`}
>
<Trash2 className="w-3 h-3" />
</button>
</div>
<div className="p-1.5 max-h-[188px] overflow-y-auto overflow-x-hidden">
{recentColors.length === 0 ? (
<div className="py-4 text-center text-[10.5px] text-ui-muted">
{t('No recent colors')}
</div>
) : (
<div
data-testid="color-panel-history-popover-grid"
style={{ gridTemplateColumns: 'repeat(8, minmax(0, 1fr))' }}
className="grid w-full border-t border-l border-ui-subtle"
>
{recentColors.map((hex, idx) => {
const isActive = hex.toLowerCase() === normalizedActiveColor;
return (
<button
key={`${hex}-${idx}`}
type="button"
data-testid={`color-panel-popover-swatch-${idx}`}
data-hex={hex}
onClick={() => {
applyColorValue(hex, false);
setHistoryOpen(false);
}}
title={hex.toUpperCase()}
aria-label={t('Select recent color {color}', { color: hex.toUpperCase() })}
style={{
backgroundColor: hex,
boxShadow: isActive ? ACTIVE_SWATCH_SHADOW : undefined,
}}
className={`w-full aspect-square min-h-[18px] border-r border-b border-ui-subtle cursor-pointer focus:outline-none ${
isActive ? 'relative z-10' : 'hover:relative hover:z-10'
}`}
/>
);
})}
</div>
)}
</div>
</div>,
document.body
)}
{/* Unpinned Non-Blocking Draggable Floating 3D Sphere */}
<SphereColorPickerModal
isOpen={isSphereFloating}
onClose={() => setIsSphereFloating(false)}
onTogglePin={handlePinSphere}
initialColor={activeColor}
monochromeDefault={isMonoCanvas}
sharedState={sphereState}
onSharedStateChange={setSphereState}
onColorChange={handleSphereColorChange}
onEyedropper={onSelectTool ? () => onSelectTool('pipette') : undefined}
/>
</div>
);
};