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 {
Menu,
Pin,
Minus,
X,
ArrowLeftToLine,
ArrowRightToLine,
ArrowDownToLine,
ChevronDown,
ChevronUp,
} from 'lucide-react';
import {
DOCK_PANEL_META,
DockPanelId,
FloatingPanelState,
} from '../types/workspace';
import { getFloatingSizeBounds } from '../utils/workspacePresets';
import { acquireWorkspaceInteractionLock } from '../utils/workspacePointerGuard';
import { useWorkspaceStore, workspaceStoreActions } from '../stores';
import { isImeComposing, useI18n } from '../i18n';
export const FLOATING_HEADER_HEIGHT = 28;
export interface FloatingPanelWindowProps {
panel: FloatingPanelState;
isDragging?: boolean;
isDockTargetActive?: boolean;
isMergeTabTarget?: boolean;
renderPanelIcon: (panelId: DockPanelId, className?: string) => React.ReactNode;
renderPanelBody: (
panelId: DockPanelId,
containerWidth: number,
containerHeight?: number
) => React.ReactNode;
onStartHeaderDrag: (e: React.PointerEvent<HTMLDivElement>, floatingId: string) => void;
onStartTabDrag: (
e: React.PointerEvent<HTMLButtonElement>,
panelId: DockPanelId,
floatingId: string
) => void;
}
type ResizeEdge = 'right' | 'left' | 'bottom' | 'bottom-right' | 'bottom-left';
export const FloatingPanelWindow: React.FC<FloatingPanelWindowProps> = React.memo(
({
panel,
isDragging = false,
isDockTargetActive = false,
isMergeTabTarget = false,
renderPanelIcon,
renderPanelBody,
onStartHeaderDrag,
onStartTabDrag,
}) => {
const { t, td } = useI18n();
const workspaceLocks = useWorkspaceStore((s) => s.workspaceLocks);
const { lockWidth, lockHeight, lockMove } = workspaceLocks;
const [menuOpen, setMenuOpen] = useState(false);
const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null);
const menuBtnRef = useRef<HTMLButtonElement>(null);
const portalMenuRef = useRef<HTMLDivElement>(null);
const safePanelIds = Array.isArray(panel?.panelIds)
? panel.panelIds.filter((pid) => Boolean(DOCK_PANEL_META[pid]))
: [];
const activePanelId = safePanelIds.includes(panel.activePanelId)
? panel.activePanelId
: safePanelIds[0];
const activeMeta = activePanelId ? DOCK_PANEL_META[activePanelId] : undefined;
const isMultiTab = safePanelIds.length > 1;
const isNarrow = panel.width < 150;
const computeMenuPosition = useCallback(() => {
const btn = menuBtnRef.current;
if (!btn || typeof window === 'undefined') return null;
const rect = btn.getBoundingClientRect();
const menuWidth = 184;
const estMenuHeight = 164;
const pad = 8;
let left = rect.left;
if (left + menuWidth > window.innerWidth - pad) {
left = rect.right - menuWidth;
}
left = Math.max(pad, Math.min(window.innerWidth - menuWidth - pad, left));
let top = rect.bottom + 4;
if (top + estMenuHeight > window.innerHeight - pad && rect.top - estMenuHeight - 4 >= pad) {
top = rect.top - estMenuHeight - 4;
} else {
top = Math.max(pad, Math.min(window.innerHeight - estMenuHeight - pad, top));
}
return { top, left };
}, []);
useEffect(() => {
if (!menuOpen) return;
const handleOutside = (e: MouseEvent) => {
const target = e.target as Node;
if (menuBtnRef.current?.contains(target) || portalMenuRef.current?.contains(target)) {
return;
}
setMenuOpen(false);
};
const handleKey = (e: KeyboardEvent) => {
if (isImeComposing(e)) return;
if (e.key === 'Escape') setMenuOpen(false);
};
const handleReposition = () => {
const next = computeMenuPosition();
if (next) setMenuPos(next);
else setMenuOpen(false);
};
window.addEventListener('mousedown', handleOutside);
window.addEventListener('keydown', handleKey);
window.addEventListener('resize', handleReposition);
return () => {
window.removeEventListener('mousedown', handleOutside);
window.removeEventListener('keydown', handleKey);
window.removeEventListener('resize', handleReposition);
};
}, [menuOpen, computeMenuPosition]);
const handleStartResize = useCallback(
(e: React.PointerEvent<HTMLDivElement>, edge: ResizeEdge) => {
if (e.button !== 0) return;
const canResizeW = !lockWidth && edge !== 'bottom';
const canResizeH = !lockHeight && edge !== 'left' && edge !== 'right';
if (!canResizeW && !canResizeH) return;
e.preventDefault();
e.stopPropagation();
workspaceStoreActions.bringFloatingPanelToFront(panel.id);
const releaseGuard = acquireWorkspaceInteractionLock('floating-panel-resize');
const targetEl = e.currentTarget;
const pointerId = e.pointerId;
try {
targetEl.setPointerCapture?.(pointerId);
} catch {
// Ignore synthetic pointer events
}
const startX = e.clientX;
const startY = e.clientY;
const origX = panel.x;
const origY = panel.y;
const origW = panel.width;
const origH = panel.height;
const bounds = getFloatingSizeBounds(panel.panelIds);
const computeNext = (clientX: number, clientY: number) => {
const dx = clientX - startX;
const dy = clientY - startY;
let nextX = origX;
let nextW = origW;
let nextH = origH;
if (canResizeW) {
if (edge === 'right' || edge === 'bottom-right') {
nextW = origW + dx;
}
if (edge === 'left' || edge === 'bottom-left') {
const clampedW = Math.max(bounds.minWidth, Math.min(bounds.maxWidth, origW - dx));
nextW = clampedW;
nextX = origX + (origW - clampedW);
}
}
if (canResizeH && (edge === 'bottom' || edge === 'bottom-right' || edge === 'bottom-left')) {
nextH = origH + dy;
}
return { x: nextX, y: origY, width: nextW, height: nextH };
};
const cleanup = () => {
releaseGuard();
try {
if (targetEl.hasPointerCapture?.(pointerId)) {
targetEl.releasePointerCapture?.(pointerId);
}
} catch {
// Ignore synthetic capture release errors
}
window.removeEventListener('pointermove', onMove);
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', onCancel);
};
const onMove = (ev: PointerEvent) => {
workspaceStoreActions.resizeFloatingPanel(
panel.id,
computeNext(ev.clientX, ev.clientY),
false
);
};
const onUp = (ev: PointerEvent) => {
cleanup();
workspaceStoreActions.resizeFloatingPanel(
panel.id,
computeNext(ev.clientX, ev.clientY),
true
);
};
const onCancel = () => {
cleanup();
};
window.addEventListener('pointermove', onMove);
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', onCancel);
},
[lockHeight, lockWidth, panel.id, panel.x, panel.y, panel.width, panel.height, panel.panelIds]
);
const zIndex = isDragging ? 49 : Math.min(48, 35 + panel.zIndex);
const bodyHeight = Math.max(80, panel.height - FLOATING_HEADER_HEIGHT);
if (!activePanelId || !activeMeta) {
return null;
}
const floatingContent = (
<div
data-testid={`floating-panel-${activePanelId}`}
data-floating-id={panel.id}
data-chrome-floating="true"
data-collapsed={String(panel.collapsed)}
role="region"
aria-label={t('{title} Floating Panel', { title: td(activeMeta.title) })}
onPointerDown={(e) => {
e.stopPropagation();
workspaceStoreActions.bringFloatingPanelToFront(panel.id);
}}
style={{
position: 'fixed',
left: panel.x,
top: panel.y,
width: panel.width,
height: panel.collapsed ? FLOATING_HEADER_HEIGHT : panel.height,
zIndex,
}}
className={`pointer-events-auto flex flex-col select-none rounded-ui-md bg-ui-floating text-ui-primary transition-shadow ${
isMergeTabTarget
? 'border border-ui-accent ring-1 ring-ui-accent-border shadow-ui-popover'
: isDragging && isDockTargetActive
? 'border border-ui-accent-border opacity-85 shadow-ui-popover'
: isDragging
? 'border border-ui-strong shadow-ui-popover'
: 'border border-ui-default shadow-ui-floating'
}`}
>
{/* Floating Panel Title Bar (CSP-style: Menu on left, Title/Tabs in center, Pin / - / X on right) */}
<div
data-drop-floating-header={panel.id}
data-chrome-floating-header="true"
data-testid={`floating-header-${activePanelId}`}
onPointerDown={(e) => {
if (e.button !== 0) return;
e.stopPropagation();
workspaceStoreActions.bringFloatingPanelToFront(panel.id);
if (!lockMove) {
onStartHeaderDrag(e, panel.id);
}
}}
onDoubleClick={(e) => {
if ((e.target as HTMLElement)?.closest?.('button')) return;
workspaceStoreActions.toggleFloatingCollapsed(panel.id);
}}
title={
lockMove
? t('Position locked — Double-click to collapse/expand')
: t('Drag to move or dock — Double-click to collapse/expand')
}
className={`h-7 px-1.5 flex items-center justify-between gap-1 shrink-0 bg-ui-header ${
lockMove ? 'cursor-default' : 'cursor-grab active:cursor-grabbing'
} ${
panel.collapsed ? 'rounded-ui-md' : 'rounded-t-ui-md border-b border-ui-subtle'
}`}
>
{/* Left: Options Menu Trigger (hamburger icon) */}
<div
className="flex items-center shrink-0"
onPointerDown={(e) => e.stopPropagation()}
>
<button
ref={menuBtnRef}
type="button"
data-testid={`floating-menu-btn-${activePanelId}`}
onClick={() => {
setMenuOpen((prev) => {
if (!prev) {
setMenuPos(computeMenuPosition());
return true;
}
return false;
});
}}
title={t('Panel Options')}
aria-label={t('Panel Options')}
className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
>
<Menu className="w-3.5 h-3.5" />
</button>
</div>
{/* Center: Title or Draggable Tab Strip */}
{isMultiTab ? (
<div className="flex-1 min-w-0 flex items-center gap-0.5 overflow-x-auto no-scrollbar h-full py-0.5">
{safePanelIds.map((pid) => {
const meta = DOCK_PANEL_META[pid];
if (!meta) return null;
const isActive = pid === activePanelId;
return (
<button
key={pid}
type="button"
data-testid={`floating-tab-${pid}`}
onPointerDown={(e) => {
e.stopPropagation();
if (!lockMove) {
onStartTabDrag(e, pid, panel.id);
}
}}
onClick={(e) => {
e.stopPropagation();
workspaceStoreActions.setFloatingActivePanel(panel.id, pid);
}}
title={
lockMove
? t('{title} (Position locked)', { title: td(meta.title) })
: t('{title} — Drag tab to split or dock', { title: td(meta.title) })
}
className={`relative h-5 px-1.5 rounded-ui-xs flex items-center gap-1 text-[10px] shrink-0 transition-colors ${
lockMove ? 'cursor-pointer' : 'cursor-grab active:cursor-grabbing'
} ${
isActive
? 'bg-ui-control text-ui-primary font-medium border border-ui-default'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'
}`}
>
{renderPanelIcon(pid, 'w-3 h-3 shrink-0')}
<span className="truncate max-w-[72px]">{td(meta.shortTitle, 'panelShort')}</span>
{isActive && (
<span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
)}
</button>
);
})}
</div>
) : (
<div className="flex-1 min-w-0 flex items-center justify-center gap-1.5 px-1 pointer-events-none">
{!isNarrow && renderPanelIcon(activePanelId, 'w-3 h-3 shrink-0 text-ui-icon-muted')}
<span className="text-[11px] font-medium text-ui-secondary truncate tracking-wide">
{isNarrow ? td(activeMeta.shortTitle, 'panelShort') : td(activeMeta.title)}
</span>
</div>
)}
{/* Upper-Right Corner: Pin (Reattach), Minus (Collapse/Hide), Close (X) */}
<div
className="flex items-center gap-0.5 shrink-0"
onPointerDown={(e) => e.stopPropagation()}
>
{!isNarrow && (
<button
type="button"
data-testid={`floating-pin-btn-${activePanelId}`}
onClick={() => workspaceStoreActions.dockFloatingPanel(panel.id)}
title={t('Reattach to Dock')}
aria-label={t('Reattach {title} to dock', { title: td(activeMeta.title) })}
className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
>
<Pin className="w-3 h-3" />
</button>
)}
<button
type="button"
data-testid={`floating-collapse-btn-${activePanelId}`}
onClick={() => workspaceStoreActions.toggleFloatingCollapsed(panel.id)}
title={panel.collapsed ? t('Expand Panel') : t('Hide / Collapse Panel')}
aria-label={
panel.collapsed
? t('Expand {title}', { title: td(activeMeta.title) })
: t('Hide {title}', { title: td(activeMeta.title) })
}
aria-expanded={!panel.collapsed}
className={`w-5 h-5 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
panel.collapsed
? 'text-ui-accent bg-ui-control-active'
: 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
}`}
>
<Minus className="w-3 h-3" />
</button>
<button
type="button"
data-testid={`floating-close-btn-${activePanelId}`}
onClick={() => workspaceStoreActions.closeFloatingPanel(panel.id)}
title={t('Close Panel')}
aria-label={t('Close {title}', { title: td(activeMeta.title) })}
className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
>
<X className="w-3 h-3" />
</button>
</div>
</div>
{/* Panel Content (hidden when collapsed via "-") */}
{!panel.collapsed && (
<div
data-testid={`floating-panel-body-${activePanelId}`}
className="flex-1 min-h-0 overflow-hidden flex flex-col rounded-b-ui-md bg-ui-panel"
>
{renderPanelBody(activePanelId, panel.width, bodyHeight)}
</div>
)}
{/* Resize Handles (positioned strictly on outer seam to stay clear of internal panel scrollbars) */}
<div
data-testid={`floating-resize-right-${activePanelId}`}
onPointerDown={(e) => handleStartResize(e, 'right')}
title={lockWidth ? t('Width locked') : t('Drag to resize width')}
className={`absolute top-1 bottom-2 -right-[3px] w-[6px] z-20 ${
lockWidth ? 'cursor-default pointer-events-none' : 'cursor-ew-resize'
}`}
/>
<div
data-testid={`floating-resize-left-${activePanelId}`}
onPointerDown={(e) => handleStartResize(e, 'left')}
title={lockWidth ? t('Width locked') : t('Drag to resize width')}
className={`absolute top-1 bottom-2 -left-[3px] w-[6px] z-20 ${
lockWidth ? 'cursor-default pointer-events-none' : 'cursor-ew-resize'
}`}
/>
{!panel.collapsed && (
<>
<div
data-testid={`floating-resize-bottom-${activePanelId}`}
onPointerDown={(e) => handleStartResize(e, 'bottom')}
title={lockHeight ? t('Height locked') : t('Drag to resize height')}
className={`absolute -bottom-[3px] left-2 right-2 h-[6px] z-20 ${
lockHeight ? 'cursor-default pointer-events-none' : 'cursor-ns-resize'
}`}
/>
<div
onPointerDown={(e) => handleStartResize(e, 'bottom-left')}
title={
lockWidth && lockHeight
? t('Size locked')
: lockWidth
? t('Drag to resize height')
: lockHeight
? t('Drag to resize width')
: t('Drag to resize')
}
className={`absolute -bottom-[2px] -left-[2px] w-3 h-3 z-30 ${
lockWidth && lockHeight
? 'cursor-default pointer-events-none'
: lockWidth
? 'cursor-ns-resize'
: lockHeight
? 'cursor-ew-resize'
: 'cursor-nesw-resize'
}`}
/>
<div
onPointerDown={(e) => handleStartResize(e, 'bottom-right')}
title={
lockWidth && lockHeight
? t('Size locked')
: lockWidth
? t('Drag to resize height')
: lockHeight
? t('Drag to resize width')
: t('Drag to resize')
}
className={`absolute bottom-0.5 right-0.5 w-3 h-3 transition-opacity z-30 ${
lockWidth && lockHeight
? 'cursor-default pointer-events-none opacity-15'
: lockWidth
? 'cursor-ns-resize opacity-35 hover:opacity-80'
: lockHeight
? 'cursor-ew-resize opacity-35 hover:opacity-80'
: 'cursor-nwse-resize opacity-35 hover:opacity-80'
}`}
style={{
background:
'linear-gradient(135deg, transparent 45%, var(--ui-icon-muted) 45%, var(--ui-icon-muted) 58%, transparent 58%, transparent 72%, var(--ui-icon-muted) 72%, var(--ui-icon-muted) 85%, transparent 85%)',
}}
/>
</>
)}
{/* Portaled Floating Panel Options Menu */}
{menuOpen &&
typeof document !== 'undefined' &&
createPortal(
<div
ref={portalMenuRef}
data-testid={`floating-menu-popover-${activePanelId}`}
style={{
position: 'fixed',
top: menuPos?.top ?? 0,
left: menuPos?.left ?? 0,
}}
className="w-48 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 text-[10px] text-ui-muted truncate">
{td(activeMeta.title)}
</div>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
data-testid={`floating-reattach-prev-${activePanelId}`}
onClick={() => {
workspaceStoreActions.dockFloatingPanel(panel.id);
setMenuOpen(false);
}}
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"
>
<Pin className="w-3 h-3 text-ui-accent" />
<span>{t('Reattach to Dock')}</span>
</button>
<button
type="button"
data-testid={`floating-dock-left-${activePanelId}`}
onClick={() => {
workspaceStoreActions.dockFloatingPanel(panel.id, { side: 'left' });
setMenuOpen(false);
}}
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"
>
<ArrowLeftToLine className="w-3 h-3 text-ui-muted" />
<span>{t('Dock to Left')}</span>
</button>
<button
type="button"
data-testid={`floating-dock-right-${activePanelId}`}
disabled={lockMove}
onClick={() => {
workspaceStoreActions.dockFloatingPanel(panel.id, { side: 'right' });
setMenuOpen(false);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
>
<ArrowRightToLine className="w-3 h-3 text-ui-muted" />
<span>{t('Dock to Right')}</span>
</button>
<button
type="button"
data-testid={`floating-dock-bottom-${activePanelId}`}
disabled={lockMove}
onClick={() => {
workspaceStoreActions.dockFloatingPanel(panel.id, { side: 'bottom' });
setMenuOpen(false);
}}
className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
>
<ArrowDownToLine className="w-3 h-3 text-ui-muted" />
<span>{t('Dock to Bottom')}</span>
</button>
<button
type="button"
onClick={() => {
workspaceStoreActions.toggleFloatingCollapsed(panel.id);
setMenuOpen(false);
}}
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"
>
{panel.collapsed ? (
<ChevronDown className="w-3 h-3 text-ui-muted" />
) : (
<ChevronUp className="w-3 h-3 text-ui-muted" />
)}
<span>{panel.collapsed ? t('Expand Panel') : t('Collapse Panel')}</span>
</button>
<div className="my-0.5 border-t border-ui-subtle" />
<button
type="button"
onClick={() => {
workspaceStoreActions.closeFloatingPanel(panel.id);
setMenuOpen(false);
}}
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"
>
<X className="w-3 h-3" />
<span>{t('Close Panel')}</span>
</button>
</div>,
document.body
)}
</div>
);
return typeof document !== 'undefined'
? createPortal(floatingContent, document.body)
: floatingContent;
}
);
FloatingPanelWindow.displayName = 'FloatingPanelWindow';