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, useCallback } from 'react';
import { ToolType, BrushSettings, FillSettings, LiquifySettings, RetouchSettings } from '../types/editor';
import { useUiStore, useWorkspaceStore } from '../stores';
import { clampNumber } from './ui/sliderMath';
import { useI18n } from '../i18n';
interface FloatingBrushPillProps {
tool: ToolType;
brushSettings: BrushSettings;
onUpdateBrushSettings: (patch: Partial<BrushSettings>) => void;
fillSettings?: FillSettings;
onUpdateFillSettings?: (patch: Partial<FillSettings>) => void;
liquifySettings?: LiquifySettings;
onUpdateLiquifySettings?: (patch: Partial<LiquifySettings>) => void;
retouchSettings?: RetouchSettings;
onUpdateRetouchSettings?: (patch: Partial<RetouchSettings>) => void;
primaryColor?: string;
onSwapColors?: () => void;
zoom?: number;
}
const MIN_BRUSH_SIZE = 0.5;
const MAX_BRUSH_SIZE = 250;
const FINE_PRECISION_SCALE = 0.1;
function sizeToRatio(size: number, min: number, max: number): number {
const clamped = clampNumber(size, min, max);
return Math.sqrt((clamped - min) / (max - min));
}
function ratioToSize(ratio: number, min: number, max: number): number {
const r = clampNumber(ratio, 0, 1);
const raw = min + r * r * (max - min);
if (raw < 10) return Math.round(raw * 2) / 2;
return Math.round(raw);
}
const VerticalSizeRampSvg: React.FC<{ fillColor: string }> = React.memo(({ fillColor }) => (
<svg
viewBox="0 0 16 100"
preserveAspectRatio="none"
aria-hidden="true"
className="w-full h-full block pointer-events-none"
>
<path d="M 7.3 100 L 1.8 0 L 14.2 0 L 8.7 100 Z" fill={fillColor} />
</svg>
));
VerticalSizeRampSvg.displayName = 'VerticalSizeRampSvg';
export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({
tool,
brushSettings,
onUpdateBrushSettings,
fillSettings,
onUpdateFillSettings,
liquifySettings,
onUpdateLiquifySettings,
retouchSettings,
onUpdateRetouchSettings,
primaryColor = '#000000',
onSwapColors,
zoom = 1,
}) => {
const { t } = useI18n();
const sliderStyle = useUiStore((s) => s.appSettings.appearance.sliderStyle);
const leftHandedMode = useWorkspaceStore((s) => s.leftHandedMode);
const isTrackMode = sliderStyle === 'track';
const [activeDrag, setActiveDrag] = useState<'size' | 'opacity' | null>(null);
const [hoveredTrack, setHoveredTrack] = useState<'size' | 'opacity' | null>(null);
const sizeTrackRef = useRef<HTMLDivElement>(null);
const opacityTrackRef = useRef<HTMLDivElement>(null);
const dragRef = useRef<{
kind: 'size' | 'opacity' | null;
pointerId: number | null;
height: number;
lastClientY: number;
ratio: number;
}>({
kind: null,
pointerId: null,
height: 112,
lastClientY: 0,
ratio: 0,
});
const isLiquify = tool === 'liquify';
const isRetouch = tool === 'retouch';
const isPaintUnfilled = tool === 'fill' && fillSettings?.method === 'paint-unfilled';
const usesStrength = isLiquify || isRetouch;
const minSize = isLiquify ? 5 : isRetouch || isPaintUnfilled ? 2 : MIN_BRUSH_SIZE;
const maxSize = isLiquify ? 500 : isRetouch || isPaintUnfilled ? 300 : MAX_BRUSH_SIZE;
const defaultSize = isLiquify ? 80 : isRetouch ? 40 : isPaintUnfilled ? 24 : 12;
const currentSize = isLiquify
? (liquifySettings?.size ?? 80)
: isRetouch
? (retouchSettings?.size ?? 40)
: isPaintUnfilled
? (fillSettings?.brushSize ?? 24)
: brushSettings.size;
const currentOpacity = isLiquify
? (liquifySettings?.strength ?? 50) / 100
: isRetouch
? (retouchSettings?.strength ?? 50) / 100
: isPaintUnfilled
? (fillSettings?.opacity ?? 1)
: (brushSettings.opacity ?? 1);
const sizeRatio = sizeToRatio(currentSize, minSize, maxSize);
const opacityRatio = clampNumber(currentOpacity, 0.01, 1);
const applySizeValue = useCallback(
(nextSize: number) => {
const clamped = clampNumber(nextSize, minSize, maxSize);
if (isLiquify) {
onUpdateLiquifySettings?.({ size: Math.round(clamped) });
} else if (isRetouch) {
onUpdateRetouchSettings?.({ size: Math.round(clamped) });
} else if (isPaintUnfilled) {
onUpdateFillSettings?.({ brushSize: Math.round(clamped) });
} else {
onUpdateBrushSettings({ size: clamped });
}
},
[
isLiquify,
isRetouch,
isPaintUnfilled,
maxSize,
minSize,
onUpdateBrushSettings,
onUpdateFillSettings,
onUpdateLiquifySettings,
onUpdateRetouchSettings,
]
);
const applyOpacityRatio = useCallback(
(nextRatio: number) => {
const clamped = clampNumber(nextRatio, 0.01, 1);
if (isLiquify) {
onUpdateLiquifySettings?.({ strength: Math.round(clamped * 100) });
} else if (isRetouch) {
onUpdateRetouchSettings?.({ strength: Math.round(clamped * 100) });
} else if (isPaintUnfilled) {
onUpdateFillSettings?.({ opacity: Math.round(clamped * 100) / 100 });
} else {
onUpdateBrushSettings({ opacity: Math.round(clamped * 100) / 100 });
}
},
[
isLiquify,
isRetouch,
isPaintUnfilled,
onUpdateBrushSettings,
onUpdateFillSettings,
onUpdateLiquifySettings,
onUpdateRetouchSettings,
]
);
const startVerticalDrag = useCallback(
(kind: 'size' | 'opacity', e: React.PointerEvent<HTMLDivElement>) => {
if (e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
if (e.altKey) {
if (kind === 'size') applySizeValue(defaultSize);
else applyOpacityRatio(usesStrength ? 0.5 : 1);
return;
}
const el = kind === 'size' ? sizeTrackRef.current : opacityTrackRef.current;
const rect = el?.getBoundingClientRect();
const height = Math.max(1, rect?.height || 112);
let initialRatio = kind === 'size' ? sizeRatio : opacityRatio;
if (!e.shiftKey && rect) {
initialRatio = clampNumber(1 - (e.clientY - rect.top) / height, 0, 1);
if (kind === 'size') {
applySizeValue(ratioToSize(initialRatio, minSize, maxSize));
} else {
applyOpacityRatio(Math.max(0.01, initialRatio));
}
}
try {
e.currentTarget.setPointerCapture?.(e.pointerId);
} catch {
// Ignore in synthetic pointer events
}
dragRef.current = {
kind,
pointerId: e.pointerId,
height,
lastClientY: e.clientY,
ratio: initialRatio,
};
setActiveDrag(kind);
},
[
applyOpacityRatio,
applySizeValue,
defaultSize,
maxSize,
minSize,
opacityRatio,
sizeRatio,
usesStrength,
]
);
const moveVerticalDrag = useCallback(
(kind: 'size' | 'opacity', e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (drag.kind !== kind) return;
const dy = drag.lastClientY - e.clientY;
drag.lastClientY = e.clientY;
if (dy === 0) return;
const scale = e.shiftKey ? FINE_PRECISION_SCALE : 1;
const nextRatio = clampNumber(drag.ratio + (dy / drag.height) * scale, 0, 1);
drag.ratio = nextRatio;
if (kind === 'size') {
applySizeValue(ratioToSize(nextRatio, minSize, maxSize));
} else {
applyOpacityRatio(Math.max(0.01, nextRatio));
}
},
[applyOpacityRatio, applySizeValue, maxSize, minSize]
);
const endVerticalDrag = useCallback(
(kind: 'size' | 'opacity', e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
if (drag.kind !== kind) return;
const pid = drag.pointerId;
drag.kind = null;
drag.pointerId = null;
setActiveDrag(null);
if (pid !== null) {
try {
if (
typeof e.currentTarget.hasPointerCapture !== 'function' ||
e.currentTarget.hasPointerCapture(pid)
) {
e.currentTarget.releasePointerCapture?.(pid);
}
} catch {
// Ignore in synthetic events
}
}
},
[]
);
const handleSizeKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
const step = currentSize < 10 ? 0.5 : 1;
const coarse = Math.max(step * 10, Math.round((maxSize - minSize) * 0.08));
let next: number | null = null;
if (e.key === 'ArrowUp' || e.key === 'ArrowRight') next = currentSize + step;
else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') next = currentSize - step;
else if (e.key === 'PageUp') next = currentSize + coarse;
else if (e.key === 'PageDown') next = currentSize - coarse;
else if (e.key === 'Home') next = minSize;
else if (e.key === 'End') next = maxSize;
if (next !== null) {
e.preventDefault();
e.stopPropagation();
applySizeValue(next);
}
},
[applySizeValue, currentSize, maxSize, minSize]
);
const handleOpacityKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
const curPct = Math.round(opacityRatio * 100);
let nextPct: number | null = null;
if (e.key === 'ArrowUp' || e.key === 'ArrowRight') nextPct = curPct + 1;
else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') nextPct = curPct - 1;
else if (e.key === 'PageUp') nextPct = curPct + 10;
else if (e.key === 'PageDown') nextPct = curPct - 10;
else if (e.key === 'Home') nextPct = 1;
else if (e.key === 'End') nextPct = 100;
if (nextPct !== null) {
e.preventDefault();
e.stopPropagation();
applyOpacityRatio(clampNumber(nextPct, 1, 100) / 100);
}
},
[applyOpacityRatio, opacityRatio]
);
const showSizeHud = activeDrag === 'size' || hoveredTrack === 'size';
const showOpacityHud = activeDrag === 'opacity' || hoveredTrack === 'opacity';
const previewDiameter = Math.max(4, Math.min(220, currentSize * zoom));
const sizePct = sizeRatio * 100;
const opacityPct = opacityRatio * 100;
return (
<div
data-testid="floating-brush-pill"
data-native-occluder="true"
data-anchor-side={leftHandedMode ? 'right' : 'left'}
onPointerDown={(e) => e.stopPropagation()}
onWheel={(e) => e.stopPropagation()}
data-slider-mode={sliderStyle}
className={`absolute ${leftHandedMode ? 'right-3' : 'left-3'} top-1/2 -translate-y-1/2 z-35 flex flex-col items-center py-2 px-1 w-7 rounded-ui-lg bg-ui-floating border border-ui-default shadow-ui-floating select-none`}
>
{/* Top Vertical Slider: Brush Size */}
<div
ref={sizeTrackRef}
role="slider"
tabIndex={0}
aria-label={t('Brush Size')}
aria-orientation="vertical"
aria-valuemin={minSize}
aria-valuemax={maxSize}
aria-valuenow={currentSize}
aria-valuetext={`${currentSize}px`}
onPointerEnter={() => setHoveredTrack('size')}
onPointerLeave={() => setHoveredTrack((prev) => (prev === 'size' ? null : prev))}
onPointerDown={(e) => startVerticalDrag('size', e)}
onPointerMove={(e) => moveVerticalDrag('size', e)}
onPointerUp={(e) => endVerticalDrag('size', e)}
onPointerCancel={(e) => endVerticalDrag('size', e)}
onDoubleClick={(e) => {
e.stopPropagation();
applySizeValue(defaultSize);
}}
onKeyDown={handleSizeKeyDown}
title={t('Brush Size: {size}px (Drag · Shift for fine · Double-click to reset)', {
size: currentSize,
})}
className="relative w-4 h-28 flex items-center justify-center cursor-ns-resize touch-none group focus:outline-none"
>
{isTrackMode ? (
<>
<div className="w-[3px] h-full rounded-full bg-ui-control-hover relative overflow-hidden">
<div
className="absolute bottom-0 left-0 right-0 rounded-full bg-ui-accent/75"
style={{ height: `${sizePct}%` }}
/>
</div>
<div
className={`absolute left-1/2 -translate-x-1/2 w-[10px] h-[10px] rounded-full bg-ui-accent border border-ui-panel pointer-events-none ${
activeDrag === 'size'
? 'ring-2 ring-ui-focus/45'
: 'group-focus-visible:ring-2 group-focus-visible:ring-ui-focus/55'
}`}
style={{ bottom: `calc(${sizePct}% - 5px)` }}
/>
</>
) : (
<div
className={`w-3.5 h-full rounded-ui-sm bg-ui-input border relative overflow-hidden transition-colors ${
activeDrag === 'size'
? 'border-ui-focus'
: 'border-ui-subtle group-hover:border-ui-default group-focus-visible:border-ui-focus'
}`}
>
<div className="absolute inset-0 opacity-65">
<VerticalSizeRampSvg fillColor="var(--ui-border-subtle)" />
</div>
<div
className="absolute inset-0"
style={{ clipPath: `inset(${100 - sizePct}% 0 0 0)` }}
>
<VerticalSizeRampSvg
fillColor={activeDrag === 'size' ? 'var(--ui-accent-hover)' : 'var(--ui-accent-subtle)'}
/>
</div>
<div
className={`absolute left-[2px] right-[2px] h-[2px] -mb-[1px] rounded-[1px] bg-ui-accent transition-opacity ${
activeDrag === 'size' ? 'opacity-100' : 'opacity-80 group-hover:opacity-100'
}`}
style={{ bottom: `clamp(1px, ${sizePct}%, calc(100% - 1px))` }}
/>
</div>
)}
{showSizeHud && (
<div
className={`pointer-events-none absolute ${
leftHandedMode ? 'right-8 flex-row-reverse' : 'left-8'
} top-1/2 -translate-y-1/2 flex items-center gap-2.5`}
>
<div className="px-2 py-1 rounded-ui-sm bg-ui-elevated border border-ui-default shadow-ui-floating whitespace-nowrap flex items-center gap-1.5">
<span className="text-[10px] text-ui-muted">{t('Size')}</span>
<span className="text-[11px] font-ui-mono tabular-nums text-ui-primary font-medium">
{currentSize}px
</span>
</div>
{activeDrag === 'size' && (
<div
className="rounded-full border border-ui-primary/80 bg-ui-primary/10 shrink-0 ring-1 ring-ui-void/60"
style={{
width: `${previewDiameter}px`,
height: `${previewDiameter}px`,
}}
/>
)}
</div>
)}
</div>
{/* Center Active Color Swatch / Quick Swap */}
<button
type="button"
onClick={onSwapColors}
title={t('Active Color (Click to swap Primary/Secondary)')}
aria-label={t('Swap Primary and Secondary Colors')}
className="my-2 w-3.5 h-3.5 rounded-ui-xs shrink-0 cursor-pointer border border-ui-strong hover:border-ui-accent transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-ui-focus"
style={{ backgroundColor: primaryColor }}
/>
{/* Bottom Vertical Slider: Brush Opacity / Strength */}
<div
ref={opacityTrackRef}
role="slider"
tabIndex={0}
aria-label={usesStrength ? t('Strength') : t('Opacity')}
aria-orientation="vertical"
aria-valuemin={1}
aria-valuemax={100}
aria-valuenow={Math.round(opacityPct)}
aria-valuetext={`${Math.round(opacityPct)}%`}
onPointerEnter={() => setHoveredTrack('opacity')}
onPointerLeave={() => setHoveredTrack((prev) => (prev === 'opacity' ? null : prev))}
onPointerDown={(e) => startVerticalDrag('opacity', e)}
onPointerMove={(e) => moveVerticalDrag('opacity', e)}
onPointerUp={(e) => endVerticalDrag('opacity', e)}
onPointerCancel={(e) => endVerticalDrag('opacity', e)}
onDoubleClick={(e) => {
e.stopPropagation();
applyOpacityRatio(usesStrength ? 0.5 : 1);
}}
onKeyDown={handleOpacityKeyDown}
title={
usesStrength
? t('Strength: {pct}% (Drag · Shift for fine · Double-click to reset)', {
pct: Math.round(opacityPct),
})
: t('Opacity: {pct}% (Drag · Shift for fine · Double-click to reset)', {
pct: Math.round(opacityPct),
})
}
className="relative w-4 h-28 flex items-center justify-center cursor-ns-resize touch-none group focus:outline-none"
>
{isTrackMode ? (
<>
<div className="w-[4px] h-full rounded-full ui-checker-alpha border border-ui-subtle relative overflow-hidden">
<div
className="absolute inset-0"
style={{
backgroundImage:
'linear-gradient(0deg, transparent 0%, rgba(var(--ui-accent-rgb), 0.82) 100%)',
}}
/>
</div>
<div
className={`absolute left-1/2 -translate-x-1/2 w-[10px] h-[10px] rounded-full bg-ui-accent border border-ui-panel pointer-events-none ${
activeDrag === 'opacity'
? 'ring-2 ring-ui-focus/45'
: 'group-focus-visible:ring-2 group-focus-visible:ring-ui-focus/55'
}`}
style={{ bottom: `calc(${opacityPct}% - 5px)` }}
/>
</>
) : (
<div
className={`w-3.5 h-full rounded-ui-sm ui-checker-alpha border relative overflow-hidden transition-colors ${
activeDrag === 'opacity'
? 'border-ui-focus'
: 'border-ui-subtle group-hover:border-ui-default group-focus-visible:border-ui-focus'
}`}
>
<div
className="absolute inset-0"
style={{
backgroundImage:
'linear-gradient(0deg, transparent 0%, rgba(var(--ui-accent-rgb), 0.34) 100%)',
}}
/>
<div
className="absolute bottom-0 left-0 right-0"
style={{
height: `${opacityPct}%`,
backgroundColor:
activeDrag === 'opacity' ? 'var(--ui-accent-hover)' : 'var(--ui-accent-subtle)',
}}
/>
<div
className={`absolute left-[2px] right-[2px] h-[2px] -mb-[1px] rounded-[1px] bg-ui-accent transition-opacity ${
activeDrag === 'opacity' ? 'opacity-100' : 'opacity-80 group-hover:opacity-100'
}`}
style={{ bottom: `clamp(1px, ${opacityPct}%, calc(100% - 1px))` }}
/>
</div>
)}
{showOpacityHud && (
<div
className={`pointer-events-none absolute ${
leftHandedMode ? 'right-8' : 'left-8'
} top-1/2 -translate-y-1/2 px-2 py-1 rounded-ui-sm bg-ui-elevated border border-ui-default shadow-ui-floating whitespace-nowrap flex items-center gap-1.5`}
>
<span className="text-[10px] text-ui-muted">
{usesStrength ? t('Strength') : t('Opacity')}
</span>
<span className="text-[11px] font-ui-mono tabular-nums text-ui-primary font-medium">
{Math.round(opacityPct)}%
</span>
</div>
)}
</div>
</div>
);
});
FloatingBrushPill.displayName = 'FloatingBrushPill';