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
fixes
sora00149cd578f5
diff --git a/src/App.tsx b/src/App.tsxindex cf9b5ef..1f66bb6 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1487,6 +1487,7 @@ export function App() {handleTonalCancel={tonalActions.handleTonalCancel}handleTonalApply={tonalActions.handleTonalApply}handleTonalPreviewChange={tonalActions.handleTonalPreviewChange}+ handleApplyFilter={handleRecordedApplyFilter}handleApplyAdjustment={tonalActions.handleApplyAdjustment}handleApplyLayerStyles={tonalActions.handleApplyLayerStyles}handleConfirmTone={tonalActions.handleConfirmTone}diff --git a/src/components/AdjustmentModal.tsx b/src/components/AdjustmentModal.tsxindex b197e63..15f8d88 100644--- a/src/components/AdjustmentModal.tsx+++ b/src/components/AdjustmentModal.tsx@@ -435,57 +435,86 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({onClose();};+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, onClose]);+if (!isOpen) return null;const channelColor =curveChannel === 'r' ? '#ef4444' : curveChannel === 'g' ? '#22c55e' : curveChannel === 'b' ? '#3b82f6' : '#ffffff';return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-xs select-none">- <div className="bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl w-[480px] max-w-[95vw] overflow-hidden flex flex-col text-[#e5e5e5] text-xs">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="adjustment-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={onClose}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-[480px] max-w-[95vw] overflow-hidden flex flex-col text-[#e5e5e5] text-xs"+ >{/* Header */}- <div className="flex items-center justify-between px-4 py-2.5 border-b border-white/[0.06] bg-[#1a1a1a]">- <span className="font-medium text-[#e5e5e5] text-xs">+ <div className="h-9 flex items-center justify-between px-3.5 border-b border-[#2c2c2c] bg-[#161616]">+ <span id="adjustment-modal-title" className="font-medium text-[#e5e5e5] text-xs">{editingLayerId ? 'Edit Adjustment Layer' : 'New Adjustment Layer'}</span><button+ type="button"onClick={onClose}- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] rounded hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] rounded hover:bg-[#2c2c2c] transition-colors cursor-pointer"><X className="w-3.5 h-3.5" /></button></div>{/* Tab Selector */}- <div className="flex border-b border-white/[0.06] bg-[#161616] p-1 gap-1">+ <div className="flex border-b border-[#2c2c2c] bg-[#161616] p-1 gap-1"><button+ type="button"onClick={() => setActiveTab('curves')}- className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${- activeTab === 'curves' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors cursor-pointer ${+ activeTab === 'curves' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Tone Curves</button><button+ type="button"onClick={() => setActiveTab('gradient-map')}- className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${- activeTab === 'gradient-map' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors cursor-pointer ${+ activeTab === 'gradient-map' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Gradient Map</button><button+ type="button"onClick={() => setActiveTab('levels')}- className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${- activeTab === 'levels' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors cursor-pointer ${+ activeTab === 'levels' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Levels</button><button+ type="button"onClick={() => setActiveTab('color-balance')}- className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${- activeTab === 'color-balance' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors cursor-pointer ${+ activeTab === 'color-balance' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Color Balance@@ -973,9 +1002,10 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({</div>{/* Footer */}- <div className="flex items-center justify-between px-4 py-2.5 border-t border-white/[0.06] bg-[#1a1a1a]">+ <div className="flex items-center justify-between px-4 py-2.5 border-t border-[#2c2c2c] bg-[#161616]"><div className="flex items-center space-x-3"><button+ type="button"onClick={handleResetCurrent}className="px-2.5 py-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer">@@ -991,14 +1021,16 @@ export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({</label></div>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><button+ type="button"onClick={onClose}- className="px-3 py-1.5 text-xs text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ className="px-3.5 py-1.5 text-xs font-medium text-[#e5e5e5] bg-[#2a2a2a] hover:bg-[#363636] rounded transition-colors cursor-pointer">Cancel</button><button+ type="button"onClick={handleApply}className="px-4 py-1.5 text-xs bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium rounded transition-opacity cursor-pointer">diff --git a/src/components/AutoActionPanel.tsx b/src/components/AutoActionPanel.tsxindex 3d708fd..6b0e2f1 100644--- a/src/components/AutoActionPanel.tsx+++ b/src/components/AutoActionPanel.tsx@@ -96,12 +96,12 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(return (<div className="flex flex-col h-full w-full bg-[#202020] text-[#e5e5e5] select-none overflow-hidden">{/* Set Selector & Toolbar */}- <div className="p-2 border-b border-white/[0.06] space-y-1.5 shrink-0">+ <div className="p-2 border-b border-[#2c2c2c] space-y-1.5 shrink-0"><div className="flex items-center gap-1"><selectvalue={activeSet?.id ?? ''}onChange={(e) => autoActionStoreActions.selectSet(e.target.value)}- className="flex-1 bg-[#161616] text-[11px] text-[#e5e5e5] px-1.5 py-1 rounded border border-white/10 min-w-0"+ className="flex-1 bg-[#161616] text-[11px] text-[#e5e5e5] px-1.5 py-1 rounded border border-[#2c2c2c] min-w-0">{sets.map((s) => (<option key={s.id} value={s.id}>@@ -144,7 +144,7 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(if (e.key === 'Enter') handleCreateAction();}}placeholder="New action name..."- className="flex-1 bg-[#161616] text-[11px] text-[#e5e5e5] px-2 py-1 rounded border border-white/10 min-w-0 focus:outline-none focus:border-[var(--accent)]"+ className="flex-1 bg-[#161616] text-[11px] text-[#e5e5e5] px-2 py-1 rounded border border-[#2c2c2c] min-w-0 focus:outline-none focus:border-[var(--accent-border)]"/><buttontype="button"@@ -191,8 +191,8 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(key={action.id}className={`rounded border transition-colors ${isSelected- ? 'bg-[#2a2a2d] border-white/15'- : 'bg-[#1a1a1c] border-transparent hover:border-white/10'+ ? 'bg-[#2c2c2c] border-[#3a3a3a]'+ : 'bg-[#161616] border-[#262626] hover:border-[#2c2c2c]'}`}><div@@ -234,7 +234,7 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(onPlayAction(action);}}title="Play Auto Action"- className="p-1 rounded bg-[#161616] hover:bg-[var(--accent)] hover:text-black text-[#e5e5e5] disabled:opacity-35 cursor-pointer"+ className="p-1 rounded bg-[#161616] hover:bg-[var(--accent)] hover:text-[var(--accent-contrast)] text-[#e5e5e5] disabled:opacity-35 cursor-pointer transition-colors"><Play className="w-3 h-3" /></button>@@ -253,16 +253,16 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(</div>{isExpanded && (- <div className="px-2 pb-1.5 pt-0.5 space-y-1 border-t border-white/[0.05]">+ <div className="px-2 pb-1.5 pt-1 space-y-1 border-t border-[#2c2c2c]">{action.steps.length === 0 ? (- <div className="text-[10px] text-[#777777] italic py-1">+ <div className="text-[10px] text-[#8a8a8a] italic py-1">Empty. Press Record and perform layer/filter commands.</div>) : (action.steps.map((step) => (<divkey={step.id}- className="flex items-center gap-1.5 text-[10px] text-[#bdbdbd] bg-[#161616] rounded px-1.5 py-1"+ className="flex items-center gap-1.5 text-[10px] text-[#d4d4d4] bg-[#202020] rounded px-1.5 py-1"><inputtype="checkbox"@@ -301,15 +301,15 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(</div>{/* Bottom Transport Bar */}- <div className="p-2 border-t border-white/[0.06] flex items-center justify-between gap-1.5 shrink-0 bg-[#1a1a1a]">+ <div className="p-2 border-t border-[#2c2c2c] flex items-center justify-between gap-1.5 shrink-0 bg-[#161616]"><buttontype="button"disabled={!hasOpenDocument || isPlaying}onClick={handleToggleRecord}- className={`flex-1 py-1 px-2 rounded text-[11px] font-medium flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-40 ${+ className={`flex-1 py-1.5 px-2 rounded text-[11px] font-medium flex items-center justify-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 ${isRecording- ? 'bg-rose-600 hover:bg-rose-500 text-white'- : 'bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5]'+ ? 'bg-red-500/90 hover:bg-red-500 text-white'+ : 'bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5]'}`}>{isRecording ? (@@ -319,7 +319,7 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(</>) : (<>- <Circle className="w-3 h-3 text-rose-500 fill-rose-500" />+ <Circle className="w-3 h-3 text-red-400 fill-red-400" /><span>Record</span></>)}@@ -329,7 +329,7 @@ export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(type="button"disabled={!hasOpenDocument || isPlaying || !selectedAction || selectedAction.steps.length === 0}onClick={() => selectedAction && onPlayAction(selectedAction)}- className="flex-1 py-1 px-2 rounded text-[11px] font-medium bg-[#234b3e] hover:bg-[#2b604f] text-[#55eaab] border border-[#2e6e58] flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-40"+ className="flex-1 py-1.5 px-2 rounded text-[11px] font-medium bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 flex items-center justify-center gap-1.5 cursor-pointer transition-opacity disabled:opacity-40"><Play className="w-3 h-3 fill-current" /><span>Play</span>diff --git a/src/components/ClipboardInviteToast.tsx b/src/components/ClipboardInviteToast.tsxindex 2b03476..b8f57b8 100644--- a/src/components/ClipboardInviteToast.tsx+++ b/src/components/ClipboardInviteToast.tsx@@ -22,41 +22,51 @@ export const ClipboardInviteToast: React.FC<ClipboardInviteToastProps> = ({if (!invite) return null;return (- <div className="fixed top-14 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-top-4 duration-200">- <div className="flex items-center space-x-3.5 rounded-lg border border-rose-500/40 bg-[#1e1e1e]/95 backdrop-blur-md px-4 py-3 shadow-[0_10px_35px_rgba(0,0,0,0.65)] text-white">- <div className="flex items-center justify-center w-8 h-8 rounded-full bg-rose-600/20 text-rose-400 shrink-0">- <Users className="w-4 h-4" />+ <div+ role="status"+ aria-live="polite"+ className="fixed top-14 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-top-4 duration-200 select-none"+ >+ <div className="flex items-center gap-3 rounded-lg border border-[var(--accent-border)] bg-[#202020]/95 backdrop-blur-md px-3.5 py-2.5 shadow-[0_12px_36px_rgba(0,0,0,0.75)] text-[#e5e5e5]">+ <div className="flex items-center justify-center w-7 h-7 rounded-md bg-[#161616] border border-[#2c2c2c] text-[var(--accent)] shrink-0">+ <Users className="w-3.5 h-3.5" /></div>- <div className="max-w-xs sm:max-w-sm">- <div className="text-[11px] font-semibold text-rose-400 tracking-wide uppercase">- Invitation Detected+ <div className="max-w-xs sm:max-w-sm min-w-0">+ <div className="flex items-center gap-1.5">+ <span className="text-[11px] font-semibold text-[#e5e5e5]">+ Invitation Detected+ </span></div>- <div className="text-xs font-medium text-white truncate">- Room: <span className="font-semibold text-amber-300">"{invite.roomName}"</span>+ <div className="text-[11px] text-[#d4d4d4] truncate">+ Room: <span className="font-medium text-[#e5e5e5]">"{invite.roomName}"</span></div>- <div className="text-[10px] text-[#888888] font-mono mt-0.5">- Host: {invite.host}+ <div className="text-[10px] text-[#8a8a8a] font-mono truncate">+ {invite.host}{invite.port && invite.port !== 443 && invite.port !== 80 ? `:${invite.port}` : ''}</div></div>- <div className="flex items-center space-x-2 pl-2">+ <div className="flex items-center gap-1.5 pl-1 shrink-0"><button+ type="button"onClick={() =>onJoin(invite.host, invite.port, invite.roomName, invite.token, invite.isSecure)}- className="flex items-center space-x-1.5 rounded-md bg-rose-600 hover:bg-rose-500 px-3 py-1.5 text-xs font-semibold text-white transition-colors shadow-sm cursor-pointer"+ className="flex items-center gap-1 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-2.5 py-1.5 text-[11px] font-medium transition-opacity cursor-pointer"><span>Connect</span>- <ArrowRight className="w-3.5 h-3.5" />+ <ArrowRight className="w-3 h-3" /></button><button+ type="button"onClick={onDismiss}- className="p-1 rounded text-[#777777] hover:bg-[#333333] hover:text-white transition-colors cursor-pointer"+ aria-label="Dismiss invitation"+ title="Dismiss"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5] transition-colors cursor-pointer">- <X className="w-4 h-4" />+ <X className="w-3.5 h-3.5" /></button></div></div>diff --git a/src/components/ColorSlider.tsx b/src/components/ColorSlider.tsxindex 57ee814..531cabf 100644--- a/src/components/ColorSlider.tsx+++ b/src/components/ColorSlider.tsx@@ -368,23 +368,24 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({};return (- <div ref={containerRef} className="flex flex-col select-none text-[#cccccc] text-xs h-full justify-between">+ <div ref={containerRef} className="flex flex-col select-none text-[#e5e5e5] text-xs h-full justify-between">{/* Optional Standalone Header if rendered outside ColorPanel */}{!hideHeader && (- <div className="bg-[#2a2a2a] px-3 py-1.5 border-b border-[#333333] flex items-center justify-between shrink-0">- <div className="flex items-center space-x-2 text-xs font-medium text-[#cccccc]">- <Menu className="w-3.5 h-3.5 text-[#888888] cursor-pointer hover:text-white transition-colors" />+ <div className="bg-[#161616] px-3 py-1.5 border-b border-[#2c2c2c] flex items-center justify-between shrink-0">+ <div className="flex items-center space-x-2 text-xs font-medium text-[#e5e5e5]">+ <Menu className="w-3.5 h-3.5 text-[#8a8a8a] cursor-pointer hover:text-[#e5e5e5] transition-colors" /><div className="flex items-center space-x-1.5">- <Sliders className="w-3.5 h-3.5 text-[#5ce1e6]" />- <span className="font-semibold tracking-wide">Color Slider</span>+ <Sliders className="w-3.5 h-3.5 text-[var(--accent)]" />+ <span className="font-medium tracking-wide">Color Slider</span></div></div>{onSwapColors && (<button+ type="button"onClick={onSwapColors}title="Swap Primary & Secondary Colors (X)"- className="flex items-center space-x-1 px-1.5 py-0.5 bg-[#1e1e1e] hover:bg-[#333333] text-[#888888] hover:text-[#cccccc] rounded-[2px] border border-[#3a3a3a] transition-colors cursor-pointer"+ className="flex items-center space-x-1 px-1.5 py-0.5 bg-[#202020] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] rounded border border-[#2c2c2c] transition-colors cursor-pointer"><ArrowLeftRight className="w-3 h-3" /><span className="text-[10px] font-mono">X</span>@@ -393,20 +394,21 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({</div>)}- {/* Main Slider Area matching Clip Studio Paint Photo 2 */}- <div className="p-2.5 flex-1 flex flex-col justify-between space-y-2">+ {/* Main Slider Area */}+ <div className="p-2 flex-1 flex flex-col justify-between space-y-2">{/* Sliders Container with Left Vertical Mode Selector Strip */}<div className="flex items-stretch">- {/* Vertical Color Model Selector (CMYK, HSV, RGB rotated -90deg matching screenshot) */}- <div className="flex flex-col w-[22px] shrink-0 border border-[#3e3e42] border-r-0 rounded-l-[3px] bg-[#222224] overflow-hidden">+ {/* Vertical Color Model Selector */}+ <div className="flex flex-col w-[22px] shrink-0 border border-[#2c2c2c] border-r-0 rounded-l bg-[#161616] overflow-hidden">{/* RGB Mode */}<button+ type="button"onClick={() => setMode('rgb')}title="RGB Color Model"className={`flex-1 py-1 flex items-center justify-center cursor-pointer transition-colors relative ${mode === 'rgb'- ? 'bg-[#2b2b2e] text-[#f0f0f0] font-bold border-r border-[#2b2b2e]'- : 'text-[#777777] hover:text-[#bbbbbb] hover:bg-[#28282b]'+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-semibold'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#202020]'}`}><span className="-rotate-90 whitespace-nowrap text-[9px] font-mono tracking-wider">@@ -416,12 +418,13 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({{/* HSV Mode */}<button+ type="button"onClick={() => setMode('hsv')}title="HSV Color Model"- className={`flex-1 py-1 flex items-center justify-center cursor-pointer transition-colors border-t border-[#343438] relative ${+ className={`flex-1 py-1 flex items-center justify-center cursor-pointer transition-colors border-t border-[#2c2c2c] relative ${mode === 'hsv'- ? 'bg-[#2b2b2e] text-[#f0f0f0] font-bold border-r border-[#2b2b2e]'- : 'text-[#777777] hover:text-[#bbbbbb] hover:bg-[#28282b]'+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-semibold'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#202020]'}`}><span className="-rotate-90 whitespace-nowrap text-[9px] font-mono tracking-wider">@@ -431,12 +434,13 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({{/* CMYK Mode */}<button+ type="button"onClick={() => setMode('cmyk')}title="CMYK Color Model"- className={`flex-1 py-1 flex items-center justify-center cursor-pointer transition-colors border-t border-[#343438] relative ${+ className={`flex-1 py-1 flex items-center justify-center cursor-pointer transition-colors border-t border-[#2c2c2c] relative ${mode === 'cmyk'- ? 'bg-[#2b2b2e] text-[#f0f0f0] font-bold border-r border-[#2b2b2e]'- : 'text-[#777777] hover:text-[#bbbbbb] hover:bg-[#28282b]'+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-semibold'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#202020]'}`}><span className="-rotate-90 whitespace-nowrap text-[8.5px] font-mono tracking-wider">@@ -446,11 +450,11 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({</div>{/* Main Slider Box */}- <div className={`flex-1 bg-[#2b2b2e] border border-[#3e3e42] rounded-r-[3px] p-2.5 ${spacingClass}`}>+ <div className={`flex-1 bg-[#161616] border border-[#2c2c2c] rounded-r p-2.5 ${spacingClass}`}>{channels.map((channel) => (<div key={channel.id} className="flex items-center space-x-2">{/* Channel Label (R, G, B, H, S, V, C, M, Y, K) */}- <span className="w-3 text-xs font-semibold text-[#dddddd] text-center shrink-0">+ <span className="w-3 text-[11px] font-medium text-[#b5b5b5] text-center shrink-0">{channel.label}</span>@@ -462,16 +466,16 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({onPointerUp={(e) => handlePointerUp(channel.id, e)}onPointerCancel={(e) => handlePointerUp(channel.id, e)}>- {/* Track Bar (dynamic height, rounded-[1px], dynamic gradient) */}+ {/* Track Bar */}<divref={(el) => {trackRefs.current[channel.id] = el;}}style={{ background: channel.gradient, height: trackHeight }}- className="relative w-full rounded-[1px] border border-[#1b1b1b] shadow-inner"+ className="relative w-full rounded-[2px] border border-black/40"/>- {/* Caret Row (triangle pointing straight UP into the track matching Photo 2) */}+ {/* Caret Row */}<div className="relative h-2 w-full pointer-events-none overflow-visible"><divclassName="absolute top-0 -translate-x-1/2"@@ -481,7 +485,7 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({width="9"height="5"viewBox="0 0 9 5"- className="fill-[#cccccc] stroke-[#111111] stroke-[0.5] filter drop-shadow-[0_1px_1px_rgba(0,0,0,0.6)]"+ className="fill-[#e5e5e5] stroke-[#161616] stroke-[0.5]"><polygon points="4.5,0 9,5 0,5" /></svg>@@ -502,21 +506,23 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({handleChannelChange(channel.id, val, true);}}}- className="w-7 bg-transparent text-right font-mono text-[11px] text-[#dddddd] outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"+ className="w-7 bg-transparent text-right font-mono text-[11px] text-[#e5e5e5] outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"/>- {/* Clip Studio Paint Up/Down Stepper Chevrons */}+ {/* Stepper Chevrons */}<div className="flex flex-col justify-center -space-y-1"><button+ type="button"onClick={() => handleStep(channel.id, 1)}title="Increment (+1)"- className="p-0 text-[#777777] hover:text-[#5ce1e6] active:text-white cursor-pointer transition-colors"+ className="p-0 text-[#8a8a8a] hover:text-[var(--accent)] active:text-white cursor-pointer transition-colors"><ChevronUp className="w-2.5 h-2.5" /></button><button+ type="button"onClick={() => handleStep(channel.id, -1)}title="Decrement (-1)"- className="p-0 text-[#777777] hover:text-[#5ce1e6] active:text-white cursor-pointer transition-colors"+ className="p-0 text-[#8a8a8a] hover:text-[var(--accent)] active:text-white cursor-pointer transition-colors"><ChevronDown className="w-2.5 h-2.5" /></button>@@ -527,46 +533,46 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({</div></div>- {/* Clip Studio Paint Bottom 3 Rounded Swatches (Matching Photo 2 Reference) */}+ {/* Bottom 3 Swatches */}<div className="flex items-center space-x-2 pt-0.5">- {/* Swatch 1: Primary Color (Black in Photo 2 with Slate Blue Selection Ring) */}<button+ type="button"onClick={() => {setActiveTarget('primary');if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');}}title={`Primary Color: ${primaryColor} (Click to select & edit)`}- className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${+ className={`flex-1 ${swatchHeight} rounded cursor-pointer transition-all relative overflow-hidden ${activeTarget === 'primary' && !isTransparentActive- ? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'- : 'border border-[#555555] hover:border-[#888888]'+ ? 'ring-1 ring-[var(--accent)] ring-offset-1 ring-offset-[#202020] border border-black/80 z-10'+ : 'border border-[#2c2c2c] hover:border-[#4a4a4a]'}`}style={{ backgroundColor: primaryColor }}/>- {/* Swatch 2: Secondary Color (White in Photo 2) */}<button+ type="button"onClick={() => {setActiveTarget('secondary');if (currentTool === 'eraser' && onSelectTool) onSelectTool('brush');}}title={`Secondary Color: ${secondaryColor} (Click to select & edit)`}- className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${+ className={`flex-1 ${swatchHeight} rounded cursor-pointer transition-all relative overflow-hidden ${activeTarget === 'secondary' && !isTransparentActive- ? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'- : 'border border-[#555555] hover:border-[#888888]'+ ? 'ring-1 ring-[var(--accent)] ring-offset-1 ring-offset-[#202020] border border-black/80 z-10'+ : 'border border-[#2c2c2c] hover:border-[#4a4a4a]'}`}style={{ backgroundColor: secondaryColor }}/>- {/* Swatch 3: Transparent Color (Checkerboard pattern in Photo 2) */}<button+ type="button"onClick={handleToggleTransparent}title="Transparent Color / Eraser Mode (C)"- className={`flex-1 ${swatchHeight} rounded-[3px] cursor-pointer transition-all relative overflow-hidden ${+ className={`flex-1 ${swatchHeight} rounded cursor-pointer transition-all relative overflow-hidden ${isTransparentActive- ? 'ring-2 ring-[#7c91c0] ring-offset-1 ring-offset-[#252526] border border-black/80 shadow-sm z-10 scale-[1.02]'- : 'border border-[#555555] hover:border-[#888888]'+ ? 'ring-1 ring-[var(--accent)] ring-offset-1 ring-offset-[#202020] border border-black/80 z-10'+ : 'border border-[#2c2c2c] hover:border-[#4a4a4a]'}`}style={{backgroundImage: 'repeating-conic-gradient(#888888 0% 25%, #444444 0% 50%)',@@ -576,21 +582,22 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({</div>{/* Hex Input & Copy Shortcut */}- <div className="pt-1">+ <div className="pt-0.5"><div className="relative flex items-center">- <span className="absolute left-2 text-[#777777] font-mono text-[11px]">#</span>+ <span className="absolute left-2 text-[#8a8a8a] font-mono text-[11px]">#</span><inputtype="text"value={activeColor.replace('#', '').toUpperCase()}onChange={(e) => handleHexInput(e.target.value)}- className="w-full bg-[#1e1e1e] border border-[#333333] focus:border-[#5ce1e6] rounded-[2px] pl-5 pr-7 py-1 text-[#dddddd] font-mono text-xs outline-none"+ className="w-full bg-[#161616] border border-[#2c2c2c] focus:border-[var(--accent-border)] rounded pl-5 pr-7 py-1 text-[#e5e5e5] font-mono text-xs outline-none"maxLength={6}placeholder="000000"/><button+ type="button"onClick={copyHexToClipboard}title="Copy Hex Code"- className="absolute right-1.5 p-1 text-[#777777] hover:text-white rounded transition-colors"+ className="absolute right-1.5 p-1 text-[#8a8a8a] hover:text-[#e5e5e5] rounded transition-colors cursor-pointer">{copiedHex ? (<Check className="w-3 h-3 text-emerald-400" />@@ -603,23 +610,24 @@ export const ColorSlider: React.FC<ColorSliderProps> = ({{/* Recent Color History Swatches */}{recentColors && recentColors.length > 0 && (- <div className="pt-1.5 border-t border-[#2e2e30]">- <div className="flex items-center justify-between text-[10px] text-[#777777] mb-1 font-medium">+ <div className="pt-1.5 border-t border-[#2c2c2c]">+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a] mb-1 font-medium"><span>Recent Colors</span>- <span className="text-[9px] text-[#555555]">{recentColors.length} items</span>+ <span className="text-[9px] text-[#6e6e6e]">{recentColors.length} items</span></div>- <div className="flex items-center space-x-1 overflow-x-auto py-0.5 scrollbar-thin">+ <div className="flex items-center space-x-1 overflow-x-auto py-0.5 no-scrollbar">{recentColors.map((color, idx) => (<buttonkey={`${color}-${idx}`}+ type="button"onClick={() => {commitHexColor(color, false);}}title={`Recent: ${color}`}- className={`w-5 h-5 rounded-[2px] border shrink-0 cursor-pointer transition-transform hover:scale-110 ${+ className={`w-5 h-5 rounded border shrink-0 cursor-pointer transition-transform hover:scale-110 ${activeColor.toLowerCase() === color.toLowerCase()- ? 'border-white ring-1 ring-[#5ce1e6]'- : 'border-[#383838] hover:border-[#777777]'+ ? 'border-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'border-[#2c2c2c] hover:border-[#6e6e6e]'}`}style={{ backgroundColor: color }}/>diff --git a/src/components/ConfirmDialogModal.tsx b/src/components/ConfirmDialogModal.tsxnew file mode 100644index 0000000..d01f225--- /dev/null+++ b/src/components/ConfirmDialogModal.tsx@@ -0,0 +1,173 @@+import React, { useEffect } from 'react';+import { AlertTriangle, HelpCircle, Paintbrush, Trash2, X } from 'lucide-react';+import { uiStoreActions, useUiStore } from '../stores';++export const ConfirmDialogModal: React.FC = React.memo(() => {+ const dialog = useUiStore((s) => s.appDialog);++ useEffect(() => {+ if (!dialog.isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ uiStoreActions.resolveAppDialog(false);+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [dialog.isOpen]);++ if (!dialog.isOpen) return null;++ const isDanger = dialog.variant === 'danger';+ const isAlert = dialog.variant === 'alert';++ const handleCancel = () => {+ uiStoreActions.resolveAppDialog(false);+ };++ const handleConfirm = () => {+ uiStoreActions.resolveAppDialog(true);+ };++ return (+ <div+ role={isAlert ? 'alertdialog' : 'dialog'}+ aria-modal="true"+ aria-labelledby="app-confirm-dialog-title"+ data-testid="app-confirm-dialog"+ className="fixed inset-0 z-[70] flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={handleCancel}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-full max-w-[420px] overflow-hidden text-xs text-[#e5e5e5] border border-[#2c2c2c]"+ >+ {/* Title Bar */}+ <div className="h-9 px-3.5 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c]">+ <div className="flex items-center gap-2 min-w-0">+ {isDanger ? (+ <Trash2 className="w-3.5 h-3.5 text-red-400 shrink-0" />+ ) : isAlert ? (+ <AlertTriangle className="w-3.5 h-3.5 text-amber-400 shrink-0" />+ ) : (+ <HelpCircle className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ )}+ <span+ id="app-confirm-dialog-title"+ className="text-xs font-medium text-[#e5e5e5] tracking-wide truncate"+ >+ {dialog.title}+ </span>+ </div>+ <button+ type="button"+ onClick={handleCancel}+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer shrink-0"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ {/* Body */}+ <div className="p-4 space-y-3">+ {dialog.preview && (+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md p-2.5 flex items-center gap-3">+ <div className="w-10 h-10 bg-[#202020] border border-[#2c2c2c] overflow-hidden shrink-0 flex items-center justify-center rounded">+ {dialog.preview.imageUrl ? (+ <img+ src={dialog.preview.imageUrl}+ alt={dialog.preview.title}+ className="w-7 h-7 object-contain brightness-125"+ />+ ) : (+ <Paintbrush className="w-4 h-4 text-[#8a8a8a]" />+ )}+ </div>+ <div className="flex-1 min-w-0">+ <div+ className="text-xs font-medium text-[#e5e5e5] truncate"+ title={dialog.preview.title}+ >+ {dialog.preview.title}+ </div>+ {dialog.preview.subtitle && (+ <div+ className="text-[10px] text-[#8a8a8a] truncate mt-0.5"+ title={dialog.preview.subtitle}+ >+ {dialog.preview.subtitle}+ </div>+ )}+ </div>+ </div>+ )}++ <div className="flex items-start gap-3">+ {!dialog.preview && (+ <div+ className={`w-8 h-8 rounded-full border flex items-center justify-center shrink-0 mt-0.5 ${+ isDanger+ ? 'bg-red-500/10 border-red-500/25 text-red-400'+ : isAlert+ ? 'bg-amber-500/10 border-amber-500/25 text-amber-400'+ : 'bg-[#2a2a2a] border-[#3a3a3a] text-[#bdbdbd]'+ }`}+ >+ {isDanger ? (+ <Trash2 className="w-4 h-4" />+ ) : isAlert ? (+ <AlertTriangle className="w-4 h-4" />+ ) : (+ <HelpCircle className="w-4 h-4" />+ )}+ </div>+ )}++ <div className="flex-1 min-w-0 space-y-1">+ <p className="text-[12.5px] leading-relaxed text-[#e5e5e5] whitespace-pre-line break-words">+ {dialog.message}+ </p>+ {dialog.detail && (+ <p className="text-[11px] leading-relaxed text-[#8a8a8a] whitespace-pre-line break-words">+ {dialog.detail}+ </p>+ )}+ </div>+ </div>+ </div>++ {/* Footer */}+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end gap-2">+ {!isAlert && (+ <button+ type="button"+ onClick={handleCancel}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer"+ >+ {dialog.cancelLabel}+ </button>+ )}+ <button+ type="button"+ autoFocus+ onClick={handleConfirm}+ className={+ isDanger+ ? 'px-3.5 py-1.5 rounded bg-red-500/90 hover:bg-red-500 text-xs font-medium text-white transition-colors cursor-pointer inline-flex items-center gap-1.5'+ : 'px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 text-xs font-medium transition-opacity cursor-pointer'+ }+ >+ {isDanger && <Trash2 className="w-3.5 h-3.5" />}+ <span>{dialog.confirmLabel}</span>+ </button>+ </div>+ </div>+ </div>+ );+});++ConfirmDialogModal.displayName = 'ConfirmDialogModal';diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsxindex 5099aa4..1bedab9 100644--- a/src/components/DockWorkspace.tsx+++ b/src/components/DockWorkspace.tsx@@ -22,6 +22,8 @@ import {Images,Info,Play,+ PinOff,+ Minus,} from 'lucide-react';import { CanvasColorMode, CspBrush } from '../types/editor';import { ThemePreset } from '../types/settings';@@ -31,6 +33,7 @@ import {DockGroup,DockPanelId,DockSide,+ WorkspaceLayout,} from '../types/workspace';import {CUSTOM_BRUSHES_CHANGED_EVENT,@@ -61,6 +64,7 @@ import { SubViewPanel } from './SubViewPanel';import { InfoPanel } from './InfoPanel';import { AutoActionPanel, AutoActionPanelProps } from './AutoActionPanel';import { WorkspaceCommandHandlers } from './CommandBar';+import { FloatingPanelWindow, FLOATING_HEADER_HEIGHT } from './FloatingPanelWindow';const DND_PANEL_MIME = 'application/x-inkstudio-panel';@@ -198,21 +202,35 @@ interface DockGroupViewProps {side: DockSide;col: DockColumn;group: DockGroup;+ groupIndex?: number;themePreset: ThemePreset;draggingPanelId: DockPanelId | null;onStartDragPanel: (panelId: DockPanelId) => void;onEndDragPanel: () => void;- renderPanelBody: (panelId: DockPanelId, containerWidth: number) => React.ReactNode;+ onStartPointerTabDrag?: (+ e: React.PointerEvent<HTMLButtonElement>,+ panelId: DockPanelId,+ colId: string,+ groupId: string,+ groupPanelCount: number+ ) => void;+ renderPanelBody: (+ panelId: DockPanelId,+ containerWidth: number,+ containerHeight?: number+ ) => React.ReactNode;}export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({side,col,group,+ groupIndex = 0,themePreset: _themePreset,draggingPanelId,onStartDragPanel,onEndDragPanel,+ onStartPointerTabDrag,renderPanelBody,}) => {const [menuOpen, setMenuOpen] = useState(false);@@ -221,13 +239,14 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({const menuRef = useRef<HTMLDivElement>(null);const triggerBtnRef = useRef<HTMLButtonElement>(null);const portalMenuRef = useRef<HTMLDivElement>(null);+ const groupRootRef = useRef<HTMLDivElement>(null);const computeMenuPosition = useCallback(() => {const btn = triggerBtnRef.current;if (!btn || typeof window === 'undefined') return null;const rect = btn.getBoundingClientRect();- const menuWidth = 176; // w-44- const estMenuHeight = 168;+ const menuWidth = 184;+ const estMenuHeight = 196;const pad = 8;// Right-align to the button on the right dock; on the left dock prefer extending rightwards@@ -284,9 +303,24 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({? group.activePanelId: group.panelIds[0];+ const isCollapsed = Boolean(group.collapsed);const isCompactToolOnly =col.width <= 64 && group.panelIds.length === 1 && group.panelIds[0] === 'tools';+ const handleDetachActivePanel = useCallback(() => {+ const rect = groupRootRef.current?.getBoundingClientRect();+ const meta = DOCK_PANEL_META[activePanelId];+ if (rect && typeof window !== 'undefined') {+ const offsetX = side === 'left' ? rect.right + 16 : rect.left - meta.defaultFloatWidth - 16;+ workspaceStoreActions.detachPanel(activePanelId, {+ x: offsetX,+ y: Math.max(44, rect.top),+ });+ } else {+ workspaceStoreActions.detachPanel(activePanelId);+ }+ }, [activePanelId, side]);+const handleDropOnTabs = (e: React.DragEvent) => {e.preventDefault();e.stopPropagation();@@ -307,12 +341,22 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({return (<div+ ref={groupRootRef}data-testid={`dock-group-${group.id}`}- style={{ flexGrow: group.heightRatio, flexBasis: 0 }}- className="flex flex-col min-h-[72px] overflow-hidden bg-[#202020]"+ data-collapsed={String(isCollapsed)}+ data-drop-group={`${side}|${col.id}|${group.id}|${groupIndex}`}+ style={+ isCollapsed+ ? { flexGrow: 0, flexBasis: 'auto' }+ : { flexGrow: group.heightRatio, flexBasis: 0 }+ }+ className={`flex flex-col overflow-hidden bg-[#202020] ${+ isCollapsed ? 'shrink-0' : 'min-h-[72px]'+ }`}>- {/* Palette Tab Header Bar (Draggable!) */}+ {/* Palette Tab Header Bar (Draggable to dock or detach!) */}<div+ data-drop-tab-bar={`${side}|${col.id}|${group.id}`}onDragOver={(e) => {e.preventDefault();e.dataTransfer.dropEffect = 'move';@@ -320,6 +364,10 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({}}onDragLeave={() => setIsDragOverTab(false)}onDrop={handleDropOnTabs}+ onDoubleClick={(e) => {+ if ((e.target as HTMLElement)?.closest?.('button')) return;+ workspaceStoreActions.toggleGroupCollapsed(col.id, group.id);+ }}className={`h-6 flex items-center justify-between px-1 shrink-0 select-none relative transition-colors ${isDragOverTab? 'bg-[var(--accent-subtle)] ring-1 ring-inset ring-[var(--accent)]'@@ -334,7 +382,11 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({<buttonkey={pid}type="button"- draggable+ draggable={!onStartPointerTabDrag}+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ onStartPointerTabDrag?.(e, pid, col.id, group.id, group.panelIds.length);+ }}onDragStart={(e) => {e.dataTransfer.setData(DND_PANEL_MIME, pid);e.dataTransfer.setData('text/plain', pid);@@ -344,8 +396,8 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({onDragEnd={onEndDragPanel}onClick={() => workspaceStoreActions.setGroupActivePanel(col.id, group.id, pid)}data-testid={`dock-tab-${pid}`}- title={`${meta.title} — Drag tab to move palette`}- className={`h-5 px-1.5 rounded-sm flex items-center gap-1 text-[10px] transition-colors shrink-0 cursor-grab active:cursor-grabbing ${+ title={`${meta.title} — Drag tab to move or detach palette`}+ className={`h-5 ${isCompactToolOnly ? 'px-1' : 'px-1.5'} rounded-sm flex items-center gap-1 text-[10px] transition-colors shrink-0 cursor-grab active:cursor-grabbing ${isActive? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium': 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#262626]'@@ -362,9 +414,51 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({})}</div>- {/* Palette Options Menu (1-click Move Left/Right, New Column, Collapse, Hide) */}- {!isCompactToolOnly && (- <div className="relative shrink-0" ref={menuRef}>+ {/* Upper-right Palette Controls: Compact Tool Detach OR Detach + Minimize (-) + Options Menu */}+ {isCompactToolOnly ? (+ <button+ type="button"+ data-testid="dock-detach-btn-tools"+ onClick={handleDetachActivePanel}+ title="Detach & Float Tool Panel"+ aria-label="Detach Tool panel"+ className="w-4 h-4 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer shrink-0"+ >+ <PinOff className="w-2.5 h-2.5" />+ </button>+ ) : (+ <div className="flex items-center gap-0.5 shrink-0" ref={menuRef}>+ <button+ type="button"+ data-testid={`dock-detach-btn-${activePanelId}`}+ onClick={handleDetachActivePanel}+ title="Detach & Float Palette"+ aria-label={`Detach ${DOCK_PANEL_META[activePanelId].title}`}+ className="w-4 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"+ >+ <PinOff className="w-2.5 h-2.5" />+ </button>++ <button+ type="button"+ data-testid={`dock-collapse-group-btn-${activePanelId}`}+ onClick={() => workspaceStoreActions.toggleGroupCollapsed(col.id, group.id)}+ title={isCollapsed ? 'Expand Panel' : 'Hide / Collapse Panel'}+ aria-label={+ isCollapsed+ ? `Expand ${DOCK_PANEL_META[activePanelId].title}`+ : `Hide ${DOCK_PANEL_META[activePanelId].title}`+ }+ aria-expanded={!isCollapsed}+ className={`w-4 h-5 rounded flex items-center justify-center cursor-pointer transition-colors ${+ isCollapsed+ ? 'text-[var(--accent)] bg-[#2c2c2c]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Minus className="w-2.5 h-2.5" />+ </button>+<buttonref={triggerBtnRef}type="button"@@ -395,13 +489,26 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({top: menuPos?.top ?? 0,left: menuPos?.left ?? 0,}}- className="w-44 rounded-md shadow-2xl p-1 z-[1000] text-[11px] bg-[#202020] border border-white/[0.1] text-[#e5e5e5]"+ className="w-48 rounded-md shadow-2xl p-1 z-[1000] text-[11px] bg-[#202020] border border-white/[0.1] text-[#e5e5e5]"><div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate">{DOCK_PANEL_META[activePanelId].title}</div><div className="my-0.5 h-px bg-white/[0.08]" />+ <button+ type="button"+ data-testid={`detach-float-${activePanelId}`}+ onClick={() => {+ handleDetachActivePanel();+ setMenuOpen(false);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <PinOff className="w-3 h-3 text-[var(--accent)]" />+ <span>Detach & Float Palette</span>+ </button>+{side === 'right' ? (<buttontype="button"@@ -482,10 +589,15 @@ export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({)}</div>- {/* Active Panel Content */}- <div className="flex-1 min-h-0 overflow-hidden flex flex-col">- {renderPanelBody(activePanelId, col.width)}- </div>+ {/* Active Panel Content (hidden when collapsed via "-") */}+ {!isCollapsed && (+ <div+ data-testid={`dock-group-body-${activePanelId}`}+ className="flex-1 min-h-0 overflow-hidden flex flex-col"+ >+ {renderPanelBody(activePanelId, col.width)}+ </div>+ )}</div>);});@@ -494,20 +606,34 @@ DockGroupView.displayName = 'DockGroupView';interface DockColumnViewProps {side: DockSide;col: DockColumn;+ colIndex: number;themePreset: ThemePreset;draggingPanelId: DockPanelId | null;onStartDragPanel: (panelId: DockPanelId) => void;onEndDragPanel: () => void;- renderPanelBody: (panelId: DockPanelId, containerWidth: number) => React.ReactNode;+ onStartPointerTabDrag: (+ e: React.PointerEvent<HTMLButtonElement>,+ panelId: DockPanelId,+ colId: string,+ groupId: string,+ groupPanelCount: number+ ) => void;+ renderPanelBody: (+ panelId: DockPanelId,+ containerWidth: number,+ containerHeight?: number+ ) => React.ReactNode;}const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({side,col,+ colIndex,themePreset,draggingPanelId,onStartDragPanel,onEndDragPanel,+ onStartPointerTabDrag,renderPanelBody,}) => {const openPopover = useWorkspaceStore((s) => s.openPopover);@@ -590,11 +716,13 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({if (col.collapsed) {const allPanelIds = col.groups.flatMap((g) => g.panelIds);const popoverWidth = Math.max(204, col.width);+ const firstGroupId = col.groups[0]?.id ?? '';return (<divdata-testid={`dock-column-${col.id}`}data-collapsed="true"+ data-drop-collapsed-col={`${side}|${col.id}|${firstGroupId}`}className="relative w-[30px] h-full flex flex-col items-center py-1 gap-1 shrink-0 select-none z-20 bg-[#1c1c1c] border-x border-white/[0.04]">{/* Expand Column Button */}@@ -619,20 +747,18 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({{allPanelIds.map((pid) => {const meta = DOCK_PANEL_META[pid];const isOpen = activePopoverPanelId === pid;+ const ownerGrp = col.groups.find((g) => g.panelIds.includes(pid));return (<buttonkey={pid}type="button"- draggable- onDragStart={(e) => {- e.dataTransfer.setData(DND_PANEL_MIME, pid);- e.dataTransfer.setData('text/plain', pid);- onStartDragPanel(pid);+ onPointerDown={(e) => {+ if (e.button !== 0 || !ownerGrp) return;+ onStartPointerTabDrag(e, pid, col.id, ownerGrp.id, ownerGrp.panelIds.length);}}- onDragEnd={onEndDragPanel}onClick={() => workspaceStoreActions.togglePopover(col.id, pid)}data-testid={`collapsed-tab-${pid}`}- title={`${meta.title} (Click to pop out)`}+ title={`${meta.title} (Click to pop out, drag to move or detach)`}aria-pressed={isOpen}className={`relative w-6 h-7 rounded flex items-center justify-center transition-colors cursor-pointer shrink-0 ${isOpen@@ -671,6 +797,14 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({</span></div><div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ onClick={() => workspaceStoreActions.detachPanel(activePopoverPanelId)}+ title="Detach & Float Palette"+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer"+ >+ <PinOff className="w-3 h-3" />+ </button><buttontype="button"onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, false)}@@ -708,6 +842,7 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({ref={colRef}data-testid={`dock-column-${col.id}`}data-collapsed="false"+ data-drop-col={`${side}|${col.id}|${colIndex}`}style={{ width: col.width }}className="relative h-full flex flex-col shrink-0 overflow-hidden z-10 bg-[#161616]">@@ -754,10 +889,12 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({side={side}col={col}group={grp}+ groupIndex={idx}themePreset={themePreset}draggingPanelId={draggingPanelId}onStartDragPanel={onStartDragPanel}onEndDragPanel={onEndDragPanel}+ onStartPointerTabDrag={onStartPointerTabDrag}renderPanelBody={renderPanelBody}/>@@ -802,6 +939,347 @@ const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({});DockColumnView.displayName = 'DockColumnView';+interface PreviewRect {+ left: number;+ top: number;+ width: number;+ height: number;+}++type DockDropTarget =+ | {+ kind: 'dock-tab';+ side: DockSide;+ targetColId: string;+ targetGroupId: string;+ previewRect: PreviewRect;+ label: string;+ }+ | {+ kind: 'dock-split';+ side: DockSide;+ targetColId: string;+ insertGroupIndex: number;+ previewRect: PreviewRect;+ label: string;+ }+ | {+ kind: 'dock-column';+ side: DockSide;+ insertColumnIndex: number;+ previewRect: PreviewRect;+ label: string;+ }+ | {+ kind: 'floating-tab';+ targetFloatingId: string;+ previewRect: PreviewRect;+ label: string;+ }+ | {+ kind: 'self-noop';+ };++interface PointerDragSource {+ kind: 'docked-tab' | 'floating-window' | 'floating-tab';+ panelId: DockPanelId;+ sourceFloatingId?: string;+ sourceColId?: string;+ sourceGroupId?: string;+ sourceGroupPanelCount?: number;+}++interface ActivePointerDragUi {+ source: PointerDragSource;+ pointerX: number;+ pointerY: number;+ dropTarget: DockDropTarget | null;+}++function detectDockDropTarget(+ clientX: number,+ clientY: number,+ workspaceEl: HTMLDivElement | null,+ leftDockEl: HTMLDivElement | null,+ rightDockEl: HTMLDivElement | null,+ layout: WorkspaceLayout,+ source: PointerDragSource+): DockDropTarget | null {+ if (typeof document === 'undefined') return null;++ // 1. Check other floating panel headers (merge as tab into another floating panel)+ const floatingHeaders = Array.from(+ document.querySelectorAll<HTMLElement>('[data-drop-floating-header]')+ );+ let bestFloatingMatch: { id: string; z: number; rect: DOMRect } | null = null;+ for (const el of floatingHeaders) {+ const fId = el.getAttribute('data-drop-floating-header');+ if (!fId || fId === source.sourceFloatingId) continue;+ const rect = el.getBoundingClientRect();+ if (+ clientX >= rect.left &&+ clientX <= rect.right &&+ clientY >= rect.top - 4 &&+ clientY <= rect.bottom + 6+ ) {+ const fp = (layout.floatingPanels ?? []).find((p) => p.id === fId);+ const z = fp?.zIndex ?? 0;+ if (!bestFloatingMatch || z >= bestFloatingMatch.z) {+ bestFloatingMatch = { id: fId, z, rect };+ }+ }+ }+ if (bestFloatingMatch) {+ const targetFp = (layout.floatingPanels ?? []).find((p) => p.id === bestFloatingMatch!.id);+ const title = targetFp ? DOCK_PANEL_META[targetFp.activePanelId].title : 'Panel';+ return {+ kind: 'floating-tab',+ targetFloatingId: bestFloatingMatch.id,+ previewRect: {+ left: bestFloatingMatch.rect.left,+ top: bestFloatingMatch.rect.top,+ width: bestFloatingMatch.rect.width,+ height: bestFloatingMatch.rect.height,+ },+ label: `Group with ${title}`,+ };+ }++ if (!workspaceEl) return null;+ const wsRect = workspaceEl.getBoundingClientRect();+ if (clientY < wsRect.top - 12 || clientY > wsRect.bottom + 12) return null;++ // 2. Extreme outer workspace left / right edges -> create outermost dock column+ const outerEdgeWidth = 22;+ if (clientX >= wsRect.left - 8 && clientX <= wsRect.left + outerEdgeWidth) {+ return {+ kind: 'dock-column',+ side: 'left',+ insertColumnIndex: 0,+ previewRect: {+ left: wsRect.left + 2,+ top: wsRect.top + 4,+ width: 28,+ height: Math.max(40, wsRect.height - 8),+ },+ label: 'Dock Left Edge',+ };+ }+ if (clientX <= wsRect.right + 8 && clientX >= wsRect.right - outerEdgeWidth) {+ return {+ kind: 'dock-column',+ side: 'right',+ insertColumnIndex: layout.rightDocks.length,+ previewRect: {+ left: wsRect.right - 30,+ top: wsRect.top + 4,+ width: 28,+ height: Math.max(40, wsRect.height - 8),+ },+ label: 'Dock Right Edge',+ };+ }++ // 3. Collapsed dock column strips+ const collapsedCols = Array.from(+ workspaceEl.querySelectorAll<HTMLElement>('[data-drop-collapsed-col]')+ );+ for (const el of collapsedCols) {+ const rect = el.getBoundingClientRect();+ if (+ clientX >= rect.left - 6 &&+ clientX <= rect.right + 6 &&+ clientY >= rect.top &&+ clientY <= rect.bottom+ ) {+ const raw = el.getAttribute('data-drop-collapsed-col') || '';+ const [sideStr, colId, firstGroupId] = raw.split('|');+ if ((sideStr === 'left' || sideStr === 'right') && colId && firstGroupId) {+ return {+ kind: 'dock-tab',+ side: sideStr,+ targetColId: colId,+ targetGroupId: firstGroupId,+ previewRect: {+ left: rect.left,+ top: rect.top + 2,+ width: rect.width,+ height: Math.max(40, rect.height - 4),+ },+ label: 'Dock to Strip',+ };+ }+ }+ }++ // 4. Column seams for inserting a new column between existing columns+ const expandedCols = Array.from(workspaceEl.querySelectorAll<HTMLElement>('[data-drop-col]'));+ for (const el of expandedCols) {+ const rect = el.getBoundingClientRect();+ if (clientY < rect.top || clientY > rect.bottom) continue;+ const raw = el.getAttribute('data-drop-col') || '';+ const [sideStr, , idxStr] = raw.split('|');+ const colIdx = parseInt(idxStr, 10);+ if ((sideStr !== 'left' && sideStr !== 'right') || isNaN(colIdx)) continue;++ if (sideStr === 'left' && Math.abs(clientX - rect.right) <= 8) {+ return {+ kind: 'dock-column',+ side: 'left',+ insertColumnIndex: colIdx + 1,+ previewRect: {+ left: rect.right - 5,+ top: rect.top + 4,+ width: 10,+ height: Math.max(40, rect.height - 8),+ },+ label: 'New Left Column',+ };+ }+ if (sideStr === 'right' && Math.abs(clientX - rect.left) <= 8) {+ return {+ kind: 'dock-column',+ side: 'right',+ insertColumnIndex: colIdx,+ previewRect: {+ left: rect.left - 5,+ top: rect.top + 4,+ width: 10,+ height: Math.max(40, rect.height - 8),+ },+ label: 'New Right Column',+ };+ }+ }++ // 5. Expanded dock groups (tab bar / top stack / bottom stack / center merge as tab)+ const groups = Array.from(workspaceEl.querySelectorAll<HTMLElement>('[data-drop-group]'));+ for (const el of groups) {+ const rect = el.getBoundingClientRect();+ if (+ clientX >= rect.left &&+ clientX <= rect.right &&+ clientY >= rect.top &&+ clientY <= rect.bottom+ ) {+ const raw = el.getAttribute('data-drop-group') || '';+ const [sideStr, colId, groupId, idxStr] = raw.split('|');+ const groupIdx = parseInt(idxStr, 10);+ if ((sideStr !== 'left' && sideStr !== 'right') || !colId || !groupId || isNaN(groupIdx)) {+ continue;+ }++ // If dragging the sole panel of this group over itself, keep docked (avoid accidental self-detach)+ if (+ source.kind === 'docked-tab' &&+ source.sourceGroupId === groupId &&+ source.sourceGroupPanelCount === 1+ ) {+ return { kind: 'self-noop' };+ }++ const relY = (clientY - rect.top) / Math.max(1, rect.height);+ const isOverHeader = clientY <= rect.top + 26;+ if (isOverHeader) {+ return {+ kind: 'dock-tab',+ side: sideStr,+ targetColId: colId,+ targetGroupId: groupId,+ previewRect: {+ left: rect.left + 1,+ top: rect.top + 1,+ width: Math.max(24, rect.width - 2),+ height: 24,+ },+ label: 'Add as Tab',+ };+ }+ if (relY < 0.28) {+ return {+ kind: 'dock-split',+ side: sideStr,+ targetColId: colId,+ insertGroupIndex: groupIdx,+ previewRect: {+ left: rect.left + 2,+ top: rect.top + 2,+ width: Math.max(24, rect.width - 4),+ height: Math.max(18, Math.min(44, rect.height * 0.28)),+ },+ label: 'Stack Above',+ };+ }+ if (relY > 0.72) {+ return {+ kind: 'dock-split',+ side: sideStr,+ targetColId: colId,+ insertGroupIndex: groupIdx + 1,+ previewRect: {+ left: rect.left + 2,+ top: rect.bottom - Math.max(18, Math.min(44, rect.height * 0.28)) - 2,+ width: Math.max(24, rect.width - 4),+ height: Math.max(18, Math.min(44, rect.height * 0.28)),+ },+ label: 'Stack Below',+ };+ }+ return {+ kind: 'dock-tab',+ side: sideStr,+ targetColId: colId,+ targetGroupId: groupId,+ previewRect: {+ left: rect.left + 2,+ top: rect.top + 2,+ width: Math.max(24, rect.width - 4),+ height: Math.max(24, rect.height - 4),+ },+ label: 'Add as Tab',+ };+ }+ }++ // 6. Inner dock zone edges (beside left dock / right dock into canvas) -> new column+ if (leftDockEl && layout.leftDocks.length > 0) {+ const ldRect = leftDockEl.getBoundingClientRect();+ if (clientX > ldRect.right && clientX <= ldRect.right + 26) {+ return {+ kind: 'dock-column',+ side: 'left',+ insertColumnIndex: layout.leftDocks.length,+ previewRect: {+ left: ldRect.right + 2,+ top: wsRect.top + 4,+ width: 24,+ height: Math.max(40, wsRect.height - 8),+ },+ label: 'New Left Column',+ };+ }+ }+ if (rightDockEl && layout.rightDocks.length > 0) {+ const rdRect = rightDockEl.getBoundingClientRect();+ if (clientX < rdRect.left && clientX >= rdRect.left - 26) {+ return {+ kind: 'dock-column',+ side: 'right',+ insertColumnIndex: 0,+ previewRect: {+ left: rdRect.left - 26,+ top: wsRect.top + 4,+ width: 24,+ height: Math.max(40, wsRect.height - 8),+ },+ label: 'New Right Column',+ };+ }+ }++ return null;+}+export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({themePreset,colorMode,@@ -831,9 +1309,14 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({const [customBrushes, setCustomBrushes] = useSharedCustomBrushes();const [draggingPanelId, setDraggingPanelId] = useState<DockPanelId | null>(null);const [edgeDropSide, setEdgeDropSide] = useState<DockSide | null>(null);+ const [pointerDragUi, setPointerDragUi] = useState<ActivePointerDragUi | null>(null);const workspaceRef = useRef<HTMLDivElement>(null);+ const leftDockRef = useRef<HTMLDivElement>(null);+ const rightDockRef = useRef<HTMLDivElement>(null);++ const floatingPanels = layout.floatingPanels ?? [];- // Close collapsed-strip popover on Escape or outside click on canvas+ // Close collapsed-strip popover on EscapeuseEffect(() => {if (!openPopover) return;const handleKey = (e: KeyboardEvent) => {@@ -843,6 +1326,19 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({return () => window.removeEventListener('keydown', handleKey);}, [openPopover]);+ // Keep all floating panels safely inside the viewport when the window resizes+ useEffect(() => {+ if (floatingPanels.length === 0) return;+ const handleResize = () => {+ const fps = useWorkspaceStore.getState().layout.floatingPanels ?? [];+ for (const fp of fps) {+ workspaceStoreActions.moveFloatingPanel(fp.id, fp.x, fp.y, false);+ }+ };+ window.addEventListener('resize', handleResize);+ return () => window.removeEventListener('resize', handleResize);+ }, [floatingPanels.length]);+const handleStartDragPanel = useCallback((panelId: DockPanelId) => {setDraggingPanelId(panelId);}, []);@@ -852,6 +1348,271 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({setEdgeDropSide(null);}, []);+ // Unified pointer drag: drag any docked tab (or tab from a multi-tab floating panel)+ // to another dock location, another floating panel, or onto the open screen to detach & float!+ const startTabPointerDrag = useCallback(+ (+ e: React.PointerEvent<HTMLButtonElement>,+ panelId: DockPanelId,+ source: PointerDragSource+ ) => {+ if (e.button !== 0) return;+ const startX = e.clientX;+ const startY = e.clientY;+ let active = false;+ let latestTarget: DockDropTarget | null = null;++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ window.removeEventListener('keydown', onKeyDown);+ setPointerDragUi(null);+ };++ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape' && active) {+ ev.preventDefault();+ cleanup();+ }+ };++ const onMove = (ev: PointerEvent) => {+ const dist = Math.hypot(ev.clientX - startX, ev.clientY - startY);+ if (!active) {+ if (dist < 6) return;+ active = true;+ }+ const currentLayout = useWorkspaceStore.getState().layout;+ latestTarget = detectDockDropTarget(+ ev.clientX,+ ev.clientY,+ workspaceRef.current,+ leftDockRef.current,+ rightDockRef.current,+ currentLayout,+ source+ );+ setPointerDragUi({+ source,+ pointerX: ev.clientX,+ pointerY: ev.clientY,+ dropTarget: latestTarget,+ });+ };++ const onCancel = () => {+ cleanup();+ };++ const onUp = (ev: PointerEvent) => {+ const wasActive = active;+ const finalTarget = latestTarget;+ cleanup();+ if (!wasActive) return;++ if (!finalTarget) {+ const meta = DOCK_PANEL_META[panelId];+ workspaceStoreActions.detachPanel(panelId, {+ x: ev.clientX - Math.round(meta.defaultFloatWidth / 2),+ y: ev.clientY - Math.round(FLOATING_HEADER_HEIGHT / 2),+ });+ return;+ }++ if (finalTarget.kind === 'self-noop') return;++ if (finalTarget.kind === 'dock-tab') {+ workspaceStoreActions.movePanel(panelId, {+ side: finalTarget.side,+ targetColId: finalTarget.targetColId,+ targetGroupId: finalTarget.targetGroupId,+ });+ } else if (finalTarget.kind === 'dock-split') {+ workspaceStoreActions.movePanel(panelId, {+ side: finalTarget.side,+ targetColId: finalTarget.targetColId,+ insertGroupIndex: finalTarget.insertGroupIndex,+ });+ } else if (finalTarget.kind === 'dock-column') {+ workspaceStoreActions.movePanel(panelId, {+ side: finalTarget.side,+ insertColumnIndex: finalTarget.insertColumnIndex,+ });+ } else if (finalTarget.kind === 'floating-tab') {+ workspaceStoreActions.mergePanelIntoFloating(panelId, finalTarget.targetFloatingId);+ }+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ window.addEventListener('keydown', onKeyDown);+ },+ []+ );++ const handleStartDockedTabDrag = useCallback(+ (+ e: React.PointerEvent<HTMLButtonElement>,+ panelId: DockPanelId,+ colId: string,+ groupId: string,+ groupPanelCount: number+ ) => {+ startTabPointerDrag(e, panelId, {+ kind: 'docked-tab',+ panelId,+ sourceColId: colId,+ sourceGroupId: groupId,+ sourceGroupPanelCount: groupPanelCount,+ });+ },+ [startTabPointerDrag]+ );++ const handleStartFloatingTabDrag = useCallback(+ (+ e: React.PointerEvent<HTMLButtonElement>,+ panelId: DockPanelId,+ floatingId: string+ ) => {+ startTabPointerDrag(e, panelId, {+ kind: 'floating-tab',+ panelId,+ sourceFloatingId: floatingId,+ });+ },+ [startTabPointerDrag]+ );++ // Dragging a floating panel by its title bar: moves freely at 60fps AND snaps/reattaches+ // when dropped onto any dock zone or another floating panel's title bar!+ const handleStartFloatingHeaderDrag = useCallback(+ (e: React.PointerEvent<HTMLDivElement>, floatingId: string) => {+ if (e.button !== 0) return;+ const fp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(+ (f) => f.id === floatingId+ );+ if (!fp) return;++ e.preventDefault();+ e.stopPropagation();++ const startX = e.clientX;+ const startY = e.clientY;+ const origX = fp.x;+ const origY = fp.y;+ const source: PointerDragSource = {+ kind: 'floating-window',+ panelId: fp.activePanelId,+ sourceFloatingId: floatingId,+ };+ let active = false;+ let latestTarget: DockDropTarget | null = null;++ const cleanup = () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ window.removeEventListener('pointercancel', onCancel);+ window.removeEventListener('keydown', onKeyDown);+ setPointerDragUi(null);+ };++ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape' && active) {+ ev.preventDefault();+ workspaceStoreActions.moveFloatingPanel(floatingId, origX, origY, false);+ cleanup();+ }+ };++ const onMove = (ev: PointerEvent) => {+ const dx = ev.clientX - startX;+ const dy = ev.clientY - startY;+ if (!active) {+ if (Math.hypot(dx, dy) < 4) return;+ active = true;+ }+ workspaceStoreActions.moveFloatingPanel(floatingId, origX + dx, origY + dy, false);+ const currentLayout = useWorkspaceStore.getState().layout;+ latestTarget = detectDockDropTarget(+ ev.clientX,+ ev.clientY,+ workspaceRef.current,+ leftDockRef.current,+ rightDockRef.current,+ currentLayout,+ source+ );+ setPointerDragUi({+ source,+ pointerX: ev.clientX,+ pointerY: ev.clientY,+ dropTarget: latestTarget,+ });+ };++ const onCancel = () => {+ if (active) {+ workspaceStoreActions.moveFloatingPanel(floatingId, origX, origY, false);+ }+ cleanup();+ };++ const onUp = (ev: PointerEvent) => {+ const wasActive = active;+ const finalTarget = latestTarget;+ cleanup();+ if (!wasActive) return;++ if (!finalTarget || finalTarget.kind === 'self-noop') {+ workspaceStoreActions.moveFloatingPanel(+ floatingId,+ origX + (ev.clientX - startX),+ origY + (ev.clientY - startY),+ true+ );+ return;+ }++ if (finalTarget.kind === 'dock-tab') {+ workspaceStoreActions.dockFloatingPanel(floatingId, {+ side: finalTarget.side,+ targetColId: finalTarget.targetColId,+ targetGroupId: finalTarget.targetGroupId,+ });+ } else if (finalTarget.kind === 'dock-split') {+ workspaceStoreActions.dockFloatingPanel(floatingId, {+ side: finalTarget.side,+ targetColId: finalTarget.targetColId,+ insertGroupIndex: finalTarget.insertGroupIndex,+ });+ } else if (finalTarget.kind === 'dock-column') {+ workspaceStoreActions.dockFloatingPanel(floatingId, {+ side: finalTarget.side,+ insertColumnIndex: finalTarget.insertColumnIndex,+ });+ } else if (finalTarget.kind === 'floating-tab') {+ const latestFp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(+ (f) => f.id === floatingId+ );+ if (latestFp) {+ for (const pid of [...latestFp.panelIds]) {+ workspaceStoreActions.mergePanelIntoFloating(pid, finalTarget.targetFloatingId);+ }+ }+ }+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ window.addEventListener('pointercancel', onCancel);+ window.addEventListener('keydown', onKeyDown);+ },+ []+ );+const handleDropEdge = (e: React.DragEvent, side: DockSide) => {e.preventDefault();const rawId =@@ -868,7 +1629,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({};const renderPanelBody = useCallback(- (panelId: DockPanelId, containerWidth: number): React.ReactNode => {+ (panelId: DockPanelId, containerWidth: number, containerHeight?: number): React.ReactNode => {switch (panelId) {case 'tools':return (@@ -930,6 +1691,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({<RightSidebarColorSectioncolorMode={colorMode}containerWidth={containerWidth}+ containerHeight={containerHeight}fullHeight/>);@@ -987,6 +1749,11 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({]);+ const visibleDropTarget =+ pointerDragUi?.dropTarget && pointerDragUi.dropTarget.kind !== 'self-noop'+ ? pointerDragUi.dropTarget+ : null;+return (<divref={workspaceRef}@@ -997,23 +1764,26 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({{/* Left Dock Zone */}{!palettesHidden && (<div+ ref={leftDockRef}data-testid="left-dock-zone"className="flex h-full shrink-0 gap-px relative z-20">- {layout.leftDocks.map((col) => (+ {layout.leftDocks.map((col, colIdx) => (<DockColumnViewkey={col.id}side="left"col={col}+ colIndex={colIdx}themePreset={themePreset}draggingPanelId={draggingPanelId}onStartDragPanel={handleStartDragPanel}onEndDragPanel={handleEndDragPanel}+ onStartPointerTabDrag={handleStartDockedTabDrag}renderPanelBody={renderPanelBody}/>))}- {/* Left-side New Column Drop Zone while dragging */}+ {/* Left-side New Column Drop Zone while HTML5-dragging */}{draggingPanelId && (<divonDragOver={(e) => {@@ -1060,10 +1830,11 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({{/* Right Dock Zone */}{!palettesHidden && (<div+ ref={rightDockRef}data-testid="right-dock-zone"className="flex h-full shrink-0 gap-px relative z-20">- {/* Right-side New Column Drop Zone while dragging */}+ {/* Right-side New Column Drop Zone while HTML5-dragging */}{draggingPanelId && (<divonDragOver={(e) => {@@ -1081,20 +1852,101 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({/>)}- {layout.rightDocks.map((col) => (+ {layout.rightDocks.map((col, colIdx) => (<DockColumnViewkey={col.id}side="right"col={col}+ colIndex={colIdx}themePreset={themePreset}draggingPanelId={draggingPanelId}onStartDragPanel={handleStartDragPanel}onEndDragPanel={handleEndDragPanel}+ onStartPointerTabDrag={handleStartDockedTabDrag}renderPanelBody={renderPanelBody}/>))}</div>)}++ {/* Freely Floating Detached Panels (Portaled to document.body, non-blocking) */}+ {!palettesHidden &&+ floatingPanels.map((fp) => (+ <FloatingPanelWindow+ key={fp.id}+ panel={fp}+ isDragging={+ pointerDragUi?.source.kind === 'floating-window' &&+ pointerDragUi.source.sourceFloatingId === fp.id+ }+ isDockTargetActive={+ pointerDragUi?.source.kind === 'floating-window' &&+ pointerDragUi.source.sourceFloatingId === fp.id &&+ Boolean(visibleDropTarget)+ }+ isMergeTabTarget={+ visibleDropTarget?.kind === 'floating-tab' &&+ visibleDropTarget.targetFloatingId === fp.id+ }+ renderPanelIcon={renderPanelIcon}+ renderPanelBody={renderPanelBody}+ onStartHeaderDrag={handleStartFloatingHeaderDrag}+ onStartTabDrag={handleStartFloatingTabDrag}+ />+ ))}++ {/* Live Dock Drop Preview Overlay while dragging a panel */}+ {visibleDropTarget &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ data-testid="dock-drop-preview"+ style={{+ position: 'fixed',+ left: visibleDropTarget.previewRect.left,+ top: visibleDropTarget.previewRect.top,+ width: visibleDropTarget.previewRect.width,+ height: visibleDropTarget.previewRect.height,+ zIndex: 49,+ }}+ className="pointer-events-none rounded-sm border-2 border-[var(--accent)] bg-[var(--accent-subtle)] shadow-[0_0_18px_rgba(var(--accent-rgb),0.32)] flex items-center justify-center transition-all duration-75"+ >+ <span className="px-2 py-0.5 rounded bg-[#161616]/90 border border-[var(--accent-border)] text-[10px] font-medium text-[#f5f5f5] whitespace-nowrap shadow">+ {visibleDropTarget.label}+ </span>+ </div>,+ document.body+ )}++ {/* Floating Drag Ghost Pill when dragging a docked tab or splitting a floating tab */}+ {pointerDragUi &&+ pointerDragUi.source.kind !== 'floating-window' &&+ typeof document !== 'undefined' &&+ createPortal(+ <div+ data-testid="panel-drag-ghost"+ style={{+ position: 'fixed',+ left: pointerDragUi.pointerX + 12,+ top: pointerDragUi.pointerY + 12,+ zIndex: 49,+ }}+ className="pointer-events-none flex items-center gap-1.5 px-2.5 py-1.5 rounded-md bg-[#1a1a1a]/95 border border-white/[0.18] shadow-[0_10px_28px_rgba(0,0,0,0.75)] text-[11px] text-[#f0f0f0] select-none"+ >+ {renderPanelIcon(pointerDragUi.source.panelId, 'w-3.5 h-3.5 text-[var(--accent)]')}+ <span className="font-medium">+ {DOCK_PANEL_META[pointerDragUi.source.panelId].title}+ </span>+ <span className="text-[10px] text-[#9e9e9e] border-l border-white/[0.1] pl-1.5">+ {visibleDropTarget+ ? visibleDropTarget.label+ : pointerDragUi.dropTarget?.kind === 'self-noop'+ ? 'Drag outside to float'+ : 'Release to float'}+ </span>+ </div>,+ document.body+ )}</div>);});diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex f174eb9..e8e4001 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -401,7 +401,10 @@ export function useDocumentLifecycle({} catch (err: unknown) {console.error('Failed to paste from file:', err);const errMsg = err instanceof Error ? err.message : String(err);- alert(`Failed to paste image from file: ${errMsg}`);+ void uiStoreActions.alertDialog({+ title: 'Paste Image Failed',+ message: `Failed to paste image from file: ${errMsg}`,+ });} finally {if (pasteFileInputRef.current) {pasteFileInputRef.current.value = '';@@ -605,7 +608,11 @@ export function useDocumentLifecycle({} catch (err: unknown) {console.error('Failed to open file:', err);const errMsg = err instanceof Error ? err.message : String(err);- alert(`Could not open "${file.name}":\n${errMsg || 'Unsupported or corrupted file.'}`);+ void uiStoreActions.alertDialog({+ title: 'Could Not Open File',+ message: `Could not open "${file.name}".`,+ detail: errMsg || 'Unsupported or corrupted file.',+ });} finally {uiStoreActions.setLoading(false, '');if (fileInputRef.current) {@@ -787,7 +794,11 @@ export function useDocumentLifecycle({} catch (err: unknown) {console.error('[Recovery] Restore error:', err);const msg = err instanceof Error ? err.message : String(err);- alert('Failed to restore crashed session: ' + msg);+ void uiStoreActions.alertDialog({+ title: 'Recovery Failed',+ message: 'Failed to restore crashed session.',+ detail: msg,+ });}},[loadDocument, resetHistory, resetZoomAndCenter, showToast, pushHistoryStep, setActiveLayerId]@@ -997,7 +1008,11 @@ export function useDocumentLifecycle({if (msg === 'Save canceled') {return 'canceled';}- alert('Failed to save file: ' + msg);+ void uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Failed to save file.',+ detail: msg,+ });return 'error';} finally {uiStoreActions.setLoading(false, '');@@ -1028,7 +1043,11 @@ export function useDocumentLifecycle({if (msg === 'Save canceled') {return 'canceled';}- alert('Failed to save file: ' + msg);+ void uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Failed to save file.',+ detail: msg,+ });return 'error';}} finally {@@ -1080,7 +1099,11 @@ export function useDocumentLifecycle({} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);if (msg !== 'Save canceled') {- alert('Failed to save file: ' + msg);+ void uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Failed to save file.',+ detail: msg,+ });}} finally {uiStoreActions.setLoading(false, '');@@ -1100,7 +1123,11 @@ export function useDocumentLifecycle({} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);if (msg !== 'Export canceled') {- alert('Failed to export image: ' + msg);+ void uiStoreActions.alertDialog({+ title: 'Export Failed',+ message: 'Failed to export image.',+ detail: msg,+ });}} finally {uiStoreActions.setLoading(false, '');diff --git a/src/components/FilterModal.tsx b/src/components/FilterModal.tsxnew file mode 100644index 0000000..1e22f03--- /dev/null+++ b/src/components/FilterModal.tsx@@ -0,0 +1,437 @@+import React, { useEffect, useState } from 'react';+import { SlidersHorizontal, X } from 'lucide-react';+import { FilterType } from '../types/editor';+import { AnyFilterParams } from '../hooks/useTonalAndFilterActions';++export interface FilterModalProps {+ isOpen: boolean;+ type: FilterType;+ onClose: () => void;+ onApply: (type: FilterType, params: AnyFilterParams) => void;+}++const FILTER_TITLES: Record<FilterType, string> = {+ 'gaussian-blur': 'Gaussian Blur',+ 'motion-blur': 'Motion Blur',+ 'unsharp-mask': 'Unsharp Mask',+ 'film-grain': 'Film Grain',+};++export const FilterModal: React.FC<FilterModalProps> = ({+ isOpen,+ type,+ onClose,+ onApply,+}) => {+ const [gaussianRadius, setGaussianRadius] = useState(5);+ const [motionDistance, setMotionDistance] = useState(15);+ const [motionAngle, setMotionAngle] = useState(0);+ const [unsharpRadius, setUnsharpRadius] = useState(2);+ const [unsharpAmount, setUnsharpAmount] = useState(1.5);+ const [unsharpThreshold, setUnsharpThreshold] = useState(0);+ const [grainIntensity, setGrainIntensity] = useState(25);+ const [grainSize, setGrainSize] = useState(1);+ const [grainMono, setGrainMono] = useState(true);++ const resetCurrent = () => {+ if (type === 'gaussian-blur') {+ setGaussianRadius(5);+ } else if (type === 'motion-blur') {+ setMotionDistance(15);+ setMotionAngle(0);+ } else if (type === 'unsharp-mask') {+ setUnsharpRadius(2);+ setUnsharpAmount(1.5);+ setUnsharpThreshold(0);+ } else if (type === 'film-grain') {+ setGrainIntensity(25);+ setGrainSize(1);+ setGrainMono(true);+ }+ };++ useEffect(() => {+ if (!isOpen) return;+ resetCurrent();+ }, [isOpen, type]);++ const buildParams = (): AnyFilterParams => {+ switch (type) {+ case 'gaussian-blur':+ return { radius: Math.max(1, Math.min(100, gaussianRadius || 1)) };+ case 'motion-blur':+ return {+ distance: Math.max(1, Math.min(100, motionDistance || 1)),+ angle: Math.max(0, Math.min(360, motionAngle || 0)),+ };+ case 'unsharp-mask':+ return {+ radius: Math.max(0.5, Math.min(20, unsharpRadius || 0.5)),+ amount: Math.max(0.1, Math.min(5, unsharpAmount || 0.1)),+ threshold: Math.max(0, Math.min(255, unsharpThreshold || 0)),+ };+ case 'film-grain':+ return {+ intensity: Math.max(1, Math.min(100, grainIntensity || 1)),+ size: Math.max(1, Math.min(4, grainSize || 1)),+ monochromatic: grainMono,+ };+ }+ };++ const handleConfirm = () => {+ onApply(type, buildParams());+ onClose();+ };++ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ } else if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement)) {+ e.preventDefault();+ e.stopPropagation();+ onApply(type, buildParams());+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [+ isOpen,+ type,+ gaussianRadius,+ motionDistance,+ motionAngle,+ unsharpRadius,+ unsharpAmount,+ unsharpThreshold,+ grainIntensity,+ grainSize,+ grainMono,+ onApply,+ onClose,+ ]);++ if (!isOpen) return null;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="filter-modal-title"+ data-testid="filter-modal"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4 select-none"+ onClick={onClose}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-[360px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] flex flex-col overflow-hidden text-xs text-[#e5e5e5]"+ >+ {/* Title Bar */}+ <div className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between">+ <div className="flex items-center gap-2 min-w-0">+ <SlidersHorizontal className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ <span id="filter-modal-title" className="text-xs font-medium text-[#e5e5e5] truncate">+ {FILTER_TITLES[type]}+ </span>+ </div>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>++ {/* Body */}+ <div className="p-4 space-y-4">+ {type === 'gaussian-blur' && (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-gaussian-radius" className="text-[11px] text-[#8a8a8a]">+ Radius (px)+ </label>+ <input+ id="filter-gaussian-radius"+ type="number"+ min={1}+ max={100}+ step={1}+ value={gaussianRadius}+ onChange={(e) =>+ setGaussianRadius(Math.max(1, Math.min(100, Number(e.target.value) || 1)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={1}+ max={100}+ step={1}+ value={gaussianRadius}+ onChange={(e) => setGaussianRadius(Number(e.target.value))}+ className="w-full"+ />+ </div>+ )}++ {type === 'motion-blur' && (+ <div className="space-y-4">+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-motion-distance" className="text-[11px] text-[#8a8a8a]">+ Distance (px)+ </label>+ <input+ id="filter-motion-distance"+ type="number"+ min={1}+ max={100}+ value={motionDistance}+ onChange={(e) =>+ setMotionDistance(Math.max(1, Math.min(100, Number(e.target.value) || 1)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={1}+ max={100}+ value={motionDistance}+ onChange={(e) => setMotionDistance(Number(e.target.value))}+ className="w-full"+ />+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-motion-angle" className="text-[11px] text-[#8a8a8a]">+ Angle (°)+ </label>+ <input+ id="filter-motion-angle"+ type="number"+ min={0}+ max={360}+ value={motionAngle}+ onChange={(e) =>+ setMotionAngle(Math.max(0, Math.min(360, Number(e.target.value) || 0)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={0}+ max={360}+ value={motionAngle}+ onChange={(e) => setMotionAngle(Number(e.target.value))}+ className="w-full"+ />+ </div>+ </div>+ )}++ {type === 'unsharp-mask' && (+ <div className="space-y-4">+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-unsharp-radius" className="text-[11px] text-[#8a8a8a]">+ Radius (px)+ </label>+ <input+ id="filter-unsharp-radius"+ type="number"+ min={0.5}+ max={20}+ step={0.5}+ value={unsharpRadius}+ onChange={(e) =>+ setUnsharpRadius(Math.max(0.5, Math.min(20, Number(e.target.value) || 0.5)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={0.5}+ max={20}+ step={0.5}+ value={unsharpRadius}+ onChange={(e) => setUnsharpRadius(Number(e.target.value))}+ className="w-full"+ />+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-unsharp-amount" className="text-[11px] text-[#8a8a8a]">+ Amount+ </label>+ <input+ id="filter-unsharp-amount"+ type="number"+ min={0.1}+ max={5}+ step={0.1}+ value={unsharpAmount}+ onChange={(e) =>+ setUnsharpAmount(Math.max(0.1, Math.min(5, Number(e.target.value) || 0.1)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={0.1}+ max={5}+ step={0.1}+ value={unsharpAmount}+ onChange={(e) => setUnsharpAmount(Number(e.target.value))}+ className="w-full"+ />+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-unsharp-threshold" className="text-[11px] text-[#8a8a8a]">+ Threshold+ </label>+ <input+ id="filter-unsharp-threshold"+ type="number"+ min={0}+ max={255}+ step={1}+ value={unsharpThreshold}+ onChange={(e) =>+ setUnsharpThreshold(Math.max(0, Math.min(255, Number(e.target.value) || 0)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={0}+ max={255}+ step={1}+ value={unsharpThreshold}+ onChange={(e) => setUnsharpThreshold(Number(e.target.value))}+ className="w-full"+ />+ </div>+ </div>+ )}++ {type === 'film-grain' && (+ <div className="space-y-4">+ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-grain-intensity" className="text-[11px] text-[#8a8a8a]">+ Intensity (%)+ </label>+ <input+ id="filter-grain-intensity"+ type="number"+ min={1}+ max={100}+ value={grainIntensity}+ onChange={(e) =>+ setGrainIntensity(Math.max(1, Math.min(100, Number(e.target.value) || 1)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={1}+ max={100}+ value={grainIntensity}+ onChange={(e) => setGrainIntensity(Number(e.target.value))}+ className="w-full"+ />+ </div>++ <div className="space-y-1.5">+ <div className="flex items-center justify-between">+ <label htmlFor="filter-grain-size" className="text-[11px] text-[#8a8a8a]">+ Grain Size (px)+ </label>+ <input+ id="filter-grain-size"+ type="number"+ min={1}+ max={4}+ step={0.5}+ value={grainSize}+ onChange={(e) =>+ setGrainSize(Math.max(1, Math.min(4, Number(e.target.value) || 1)))+ }+ className="w-16 bg-[#161616] border border-[#2c2c2c] rounded px-2 py-0.5 text-right font-mono text-xs text-[#e5e5e5]"+ />+ </div>+ <input+ type="range"+ min={1}+ max={4}+ step={0.5}+ value={grainSize}+ onChange={(e) => setGrainSize(Number(e.target.value))}+ className="w-full"+ />+ </div>++ <label className="flex items-center justify-between bg-[#161616] border border-[#2c2c2c] rounded px-3 py-2 cursor-pointer">+ <span className="text-[11px] text-[#e5e5e5]">Monochromatic Grain</span>+ <input+ type="checkbox"+ checked={grainMono}+ onChange={(e) => setGrainMono(e.target.checked)}+ className="cursor-pointer"+ />+ </label>+ </div>+ )}+ </div>++ {/* Footer */}+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between">+ <button+ type="button"+ onClick={resetCurrent}+ className="text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Reset+ </button>++ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={onClose}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Cancel+ </button>+ <button+ type="button"+ autoFocus+ onClick={handleConfirm}+ className="px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 text-xs font-medium transition-opacity cursor-pointer"+ >+ Apply+ </button>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/FirstTimeNameModal.tsx b/src/components/FirstTimeNameModal.tsxindex 70d9290..5d953fd 100644--- a/src/components/FirstTimeNameModal.tsx+++ b/src/components/FirstTimeNameModal.tsx@@ -21,19 +21,24 @@ export const FirstTimeNameModal: React.FC<FirstTimeNameModalProps> = ({};return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 select-none">- <div className="bg-[#444447] border border-[#242426] rounded-[2px] shadow-[0_8px_24px_rgba(0,0,0,0.7)] w-full max-w-sm overflow-hidden text-[#d6d6da]">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="first-time-name-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ >+ <div className="bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-full max-w-[400px] overflow-hidden text-xs text-[#e5e5e5]">{/* Title Bar */}- <div className="px-4 py-2 border-b border-[#242426] bg-gradient-to-b from-[#525255] to-[#3e3e40] flex items-center space-x-2">- <User className="w-3.5 h-3.5 text-[#93c5fd]" />- <h2 className="text-xs font-semibold text-[#f0f0f4] tracking-wide">+ <div className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center gap-2">+ <User className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ <h2 id="first-time-name-title" className="text-xs font-medium text-[#e5e5e5] tracking-wide">Artist Profile</h2></div>- <form onSubmit={handleSubmit} className="p-4 space-y-4">- <div className="space-y-1.5">- <label htmlFor="user-name-input" className="block text-xs font-medium text-[#cccccc]">+ <form onSubmit={handleSubmit}>+ <div className="p-4 space-y-2">+ <label htmlFor="user-name-input" className="block text-[11px] font-medium text-[#e5e5e5]">Display Name</label><input@@ -44,19 +49,19 @@ export const FirstTimeNameModal: React.FC<FirstTimeNameModalProps> = ({onChange={(e) => setName(e.target.value)}placeholder="Artist"maxLength={40}- className="w-full px-2.5 py-1.5 bg-[#2b2b2e] border border-[#1e1e20] rounded-[2px] text-xs text-[#f0f0f4] placeholder-[#707075] outline-none focus:border-[#4a8fc7] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5)]"+ className="w-full px-3 py-2 bg-[#161616] border border-[#2c2c2c] rounded text-xs text-[#e5e5e5] placeholder-[#8a8a8a]/60 focus:border-[var(--accent-border)] outline-none"/>- <p className="text-[10px] text-[#8c8c92]">+ <p className="text-[11px] text-[#8a8a8a]">Configures session metadata. Editable anytime in Preferences.</p></div>- <div className="flex items-center justify-end space-x-2 pt-2 border-t border-[#363639]">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end"><buttontype="submit"- className="flex items-center space-x-1 px-4 py-1.5 rounded-[2px] bg-gradient-to-b from-[#56565a] to-[#424245] hover:from-[#626266] hover:to-[#4b4b4e] border border-[#242426] text-xs font-medium text-[#f0f0f4] shadow-[inset_0_1px_0_rgba(255,255,255,0.18),0_1px_1px_rgba(0,0,0,0.3)] cursor-pointer"+ className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 text-xs font-medium transition-opacity cursor-pointer">- <Check className="w-3.5 h-3.5 text-emerald-400" />+ <Check className="w-3.5 h-3.5" /><span>Continue</span></button></div>diff --git a/src/components/FloatingPanelWindow.tsx b/src/components/FloatingPanelWindow.tsxnew file mode 100644index 0000000..b0309ba--- /dev/null+++ b/src/components/FloatingPanelWindow.tsx@@ -0,0 +1,483 @@+import React, { useState, useRef, useEffect, useCallback } from 'react';+import { createPortal } from 'react-dom';+import {+ Menu,+ Pin,+ Minus,+ X,+ ArrowLeftToLine,+ ArrowRightToLine,+ ChevronDown,+ ChevronUp,+} from 'lucide-react';+import {+ DOCK_PANEL_META,+ DockPanelId,+ FloatingPanelState,+} from '../types/workspace';+import { getFloatingSizeBounds } from '../utils/workspacePresets';+import { workspaceStoreActions } from '../stores';++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 [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 activePanelId = panel.panelIds.includes(panel.activePanelId)+ ? panel.activePanelId+ : panel.panelIds[0];+ const activeMeta = DOCK_PANEL_META[activePanelId];+ const isMultiTab = panel.panelIds.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 (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;+ e.preventDefault();+ e.stopPropagation();+ workspaceStoreActions.bringFloatingPanelToFront(panel.id);++ 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 (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 (edge === 'bottom' || edge === 'bottom-right' || edge === 'bottom-left') {+ nextH = origH + dy;+ }+ return { x: nextX, y: origY, width: nextW, height: nextH };+ };++ const onMove = (ev: PointerEvent) => {+ workspaceStoreActions.resizeFloatingPanel(+ panel.id,+ computeNext(ev.clientX, ev.clientY),+ false+ );+ };++ const onUp = (ev: PointerEvent) => {+ workspaceStoreActions.resizeFloatingPanel(+ panel.id,+ computeNext(ev.clientX, ev.clientY),+ true+ );+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ },+ [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);++ const floatingContent = (+ <div+ data-testid={`floating-panel-${activePanelId}`}+ data-floating-id={panel.id}+ data-collapsed={String(panel.collapsed)}+ role="region"+ aria-label={`${activeMeta.title} Floating Panel`}+ 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-md bg-[#202020]/96 backdrop-blur-md text-[#e5e5e5] transition-shadow ${+ isMergeTabTarget+ ? 'border border-[var(--accent)] ring-2 ring-[var(--accent)]/40 shadow-[0_14px_38px_rgba(0,0,0,0.75)]'+ : isDragging && isDockTargetActive+ ? 'border border-[var(--accent)]/80 opacity-80 shadow-[0_18px_44px_rgba(0,0,0,0.8)]'+ : isDragging+ ? 'border border-white/[0.18] shadow-[0_18px_44px_rgba(0,0,0,0.8)]'+ : 'border border-white/[0.12] shadow-[0_12px_34px_rgba(0,0,0,0.68)]'+ }`}+ >+ {/* 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-testid={`floating-header-${activePanelId}`}+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ workspaceStoreActions.bringFloatingPanelToFront(panel.id);+ onStartHeaderDrag(e, panel.id);+ }}+ onDoubleClick={(e) => {+ if ((e.target as HTMLElement)?.closest?.('button')) return;+ workspaceStoreActions.toggleFloatingCollapsed(panel.id);+ }}+ title="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-[#1a1a1a] cursor-grab active:cursor-grabbing ${+ panel.collapsed ? 'rounded-md' : 'rounded-t-md border-b border-white/[0.08]'+ }`}+ >+ {/* 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="Panel Options"+ aria-label="Panel Options"+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] 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">+ {panel.panelIds.map((pid) => {+ const meta = DOCK_PANEL_META[pid];+ const isActive = pid === activePanelId;+ return (+ <button+ key={pid}+ type="button"+ data-testid={`floating-tab-${pid}`}+ onPointerDown={(e) => {+ e.stopPropagation();+ onStartTabDrag(e, pid, panel.id);+ }}+ onClick={(e) => {+ e.stopPropagation();+ workspaceStoreActions.setFloatingActivePanel(panel.id, pid);+ }}+ title={`${meta.title} — Drag tab to split or dock`}+ className={`h-5 px-1.5 rounded-sm flex items-center gap-1 text-[10px] shrink-0 transition-colors cursor-grab active:cursor-grabbing ${+ isActive+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#262626]'+ }`}+ >+ {renderPanelIcon(pid, 'w-3 h-3 shrink-0')}+ <span className="truncate max-w-[72px]">{meta.shortTitle}</span>+ </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-[#9e9e9e]')}+ <span className="text-[11px] font-medium text-[#d4d4d4] truncate tracking-wide">+ {isNarrow ? activeMeta.shortTitle : 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="Reattach to Dock"+ aria-label={`Reattach ${activeMeta.title} to dock`}+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] 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 ? 'Expand Panel' : 'Hide / Collapse Panel'}+ aria-label={panel.collapsed ? `Expand ${activeMeta.title}` : `Hide ${activeMeta.title}`}+ aria-expanded={!panel.collapsed}+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${+ panel.collapsed+ ? 'text-[var(--accent)] bg-[#2c2c2c]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Minus className="w-3 h-3" />+ </button>+ <button+ type="button"+ data-testid={`floating-close-btn-${activePanelId}`}+ onClick={() => workspaceStoreActions.closeFloatingPanel(panel.id)}+ title="Close Panel"+ aria-label={`Close ${activeMeta.title}`}+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] 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-md bg-[#202020]"+ >+ {renderPanelBody(activePanelId, panel.width, bodyHeight)}+ </div>+ )}++ {/* Resize Handles */}+ <div+ onPointerDown={(e) => handleStartResize(e, 'right')}+ title="Drag to resize width"+ className="absolute top-1 bottom-2 right-0 w-1.5 cursor-ew-resize z-20"+ />+ <div+ onPointerDown={(e) => handleStartResize(e, 'left')}+ title="Drag to resize width"+ className="absolute top-1 bottom-2 left-0 w-1.5 cursor-ew-resize z-20"+ />+ {!panel.collapsed && (+ <>+ <div+ onPointerDown={(e) => handleStartResize(e, 'bottom')}+ title="Drag to resize height"+ className="absolute bottom-0 left-2 right-2 h-1.5 cursor-ns-resize z-20"+ />+ <div+ onPointerDown={(e) => handleStartResize(e, 'bottom-left')}+ title="Drag to resize"+ className="absolute bottom-0 left-0 w-3 h-3 cursor-nesw-resize z-30"+ />+ <div+ onPointerDown={(e) => handleStartResize(e, 'bottom-right')}+ title="Drag to resize"+ className="absolute bottom-0.5 right-0.5 w-3 h-3 cursor-nwse-resize opacity-35 hover:opacity-80 transition-opacity z-30"+ style={{+ background:+ 'linear-gradient(135deg, transparent 45%, #8a8a8a 45%, #8a8a8a 58%, transparent 58%, transparent 72%, #8a8a8a 72%, #8a8a8a 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-md shadow-2xl p-1 z-[1000] text-[11px] bg-[#202020] border border-white/[0.1] text-[#e5e5e5]"+ >+ <div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate">+ {activeMeta.title}+ </div>+ <div className="my-0.5 h-px bg-white/[0.08]" />++ <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 hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <Pin className="w-3 h-3 text-[var(--accent)]" />+ <span>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 hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <ArrowLeftToLine className="w-3 h-3 text-[#8a8a8a]" />+ <span>Dock to Left</span>+ </button>++ <button+ type="button"+ data-testid={`floating-dock-right-${activePanelId}`}+ onClick={() => {+ workspaceStoreActions.dockFloatingPanel(panel.id, { side: 'right' });+ setMenuOpen(false);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ <ArrowRightToLine className="w-3 h-3 text-[#8a8a8a]" />+ <span>Dock to Right</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 hover:bg-[#2c2c2c] cursor-pointer text-left"+ >+ {panel.collapsed ? (+ <ChevronDown className="w-3 h-3 text-[#8a8a8a]" />+ ) : (+ <ChevronUp className="w-3 h-3 text-[#8a8a8a]" />+ )}+ <span>{panel.collapsed ? 'Expand Panel' : 'Collapse Panel'}</span>+ </button>++ <div className="my-0.5 h-px bg-white/[0.08]" />++ <button+ type="button"+ onClick={() => {+ workspaceStoreActions.closeFloatingPanel(panel.id);+ setMenuOpen(false);+ }}+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-rose-400 cursor-pointer text-left"+ >+ <X className="w-3 h-3" />+ <span>Close Panel</span>+ </button>+ </div>,+ document.body+ )}+ </div>+ );++ return typeof document !== 'undefined'+ ? createPortal(floatingContent, document.body)+ : floatingContent;+ }+);++FloatingPanelWindow.displayName = 'FloatingPanelWindow';diff --git a/src/components/HostModal.tsx b/src/components/HostModal.tsxindex 54d746f..b5f1d2f 100644--- a/src/components/HostModal.tsx+++ b/src/components/HostModal.tsx@@ -115,6 +115,20 @@ export const HostModal: React.FC<HostModalProps> = ({}}, [isOpen]);+ // Escape key closes modal+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, onClose]);+if (!isOpen) return null;const handleCopyLink = async () => {@@ -188,17 +202,26 @@ export const HostModal: React.FC<HostModalProps> = ({};return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-xs p-4">- <div className="relative w-full max-w-md rounded-lg border border-[#444444] bg-[#222222] shadow-2xl text-[#e0e0e0] overflow-hidden">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="host-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={onClose}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="relative w-full max-w-md rounded-lg border border-[#2c2c2c] bg-[#202020] shadow-[0_24px_64px_rgba(0,0,0,0.85)] text-[#e5e5e5] overflow-hidden"+ >{/* Header */}- <div className="flex items-center justify-between border-b border-[#333333] px-5 py-4 bg-[#282828]">- <div className="flex items-center space-x-2.5">- <div className="p-2 rounded-md bg-[#1e1e1e]/80 border border-[#383838] text-[#cccccc]">- <Users className="w-5 h-5" />- </div>- <div>- <h3 className="text-sm font-semibold text-white">Collaborative Drawing</h3>- <p className="text-[11px] text-[#888888]">+ <div className="h-11 px-4 flex items-center justify-between border-b border-[#2c2c2c] bg-[#161616]">+ <div className="flex items-center gap-2.5 min-w-0">+ <Users className="w-4 h-4 text-[var(--accent)] shrink-0" />+ <div className="min-w-0">+ <h3 id="host-modal-title" className="text-xs font-medium text-[#e5e5e5] leading-tight">+ Collaborative Drawing+ </h3>+ <p className="text-[10px] text-[#8a8a8a] truncate">{connectionStatus === 'reconnecting'? `Reconnecting (attempt ${reconnectAttempt || 1})...`: isConnected@@ -210,33 +233,37 @@ export const HostModal: React.FC<HostModalProps> = ({</div></div><button+ type="button"onClick={onClose}- className="rounded p-1 text-[#888888] hover:bg-[#333333] hover:text-white transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5] transition-colors cursor-pointer shrink-0">- <X className="w-4 h-4" />+ <X className="w-3.5 h-3.5" /></button></div>{/* Content */}- <div className="p-5 space-y-4">+ <div className="p-4 space-y-4">{connectionStatus === 'reconnecting' ? (<div className="space-y-4">- <div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3.5 flex items-start space-x-3">- <RefreshCw className="w-5 h-5 text-amber-400 shrink-0 mt-0.5 animate-spin" />+ <div className="rounded-md border border-amber-500/35 bg-amber-500/10 p-3.5 flex items-start space-x-3">+ <RefreshCw className="w-4 h-4 text-amber-400 shrink-0 mt-0.5 animate-spin" /><div className="flex-1 min-w-0">- <div className="text-xs font-semibold text-amber-300">+ <div className="text-xs font-medium text-amber-300">Reconnecting to Session...</div>- <div className="text-[11px] text-[#aaaaaa] mt-0.5 truncate">- Room: <span className="text-white font-medium">{hostInfo?.roomName || 'Studio'}</span>{' '}+ <div className="text-[11px] text-[#b5b5b5] mt-0.5 truncate">+ Room: <span className="text-[#e5e5e5] font-medium">{hostInfo?.roomName || 'Studio'}</span>{' '}(attempt {reconnectAttempt || 1})</div>- <div className="text-[10px] text-[#888888] mt-1">+ <div className="text-[10px] text-[#8a8a8a] mt-1">Session state is preserved. Missed tiles and layer updates will catch up automatically.</div></div></div><button+ type="button"onClick={() => {if (isHost) {onStopHosting();@@ -245,7 +272,7 @@ export const HostModal: React.FC<HostModalProps> = ({}onClose();}}- className="w-full flex items-center justify-center space-x-2 rounded border border-rose-500/30 bg-rose-500/10 hover:bg-rose-500/20 py-2 text-xs font-medium text-rose-400 transition-colors cursor-pointer"+ className="w-full flex items-center justify-center gap-2 rounded border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 py-2 text-xs font-medium text-red-400 transition-colors cursor-pointer"><LogOut className="w-3.5 h-3.5" /><span>{isHost ? 'Stop Session' : 'Cancel & Leave'}</span>@@ -255,27 +282,27 @@ export const HostModal: React.FC<HostModalProps> = ({// Active Host View<div className="space-y-4">{hostInfo?.isGlobal ? (- <div className="rounded-md border border-sky-500/30 bg-sky-500/10 p-3.5 flex items-start space-x-3">- <Globe className="w-5 h-5 text-sky-400 shrink-0 mt-0.5" />- <div className="flex-1">- <div className="text-xs font-semibold text-sky-300">+ <div className="rounded-md border border-[var(--accent-border)] bg-[#161616] p-3.5 flex items-start gap-3">+ <Globe className="w-4 h-4 text-[var(--accent)] shrink-0 mt-0.5" />+ <div className="flex-1 min-w-0">+ <div className="text-xs font-medium text-[#e5e5e5]">Worldwide Cloudflare Tunnel Active</div>- <div className="text-[11px] text-[#aaaaaa] mt-0.5">- Room: <span className="text-white font-medium">{hostInfo?.roomName}</span> —+ <div className="text-[11px] text-[#8a8a8a] mt-0.5">+ Room: <span className="text-[#e5e5e5] font-medium">{hostInfo?.roomName}</span> —anyone on any network can join via link in browser or desktop app.</div></div></div>) : (- <div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 p-3.5 flex items-start space-x-3">- <Wifi className="w-5 h-5 text-emerald-400 shrink-0 mt-0.5" />- <div className="flex-1">- <div className="text-xs font-semibold text-emerald-300">+ <div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 p-3.5 flex items-start gap-3">+ <Wifi className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />+ <div className="flex-1 min-w-0">+ <div className="text-xs font-medium text-emerald-300">Local Wi-Fi Server Active</div>- <div className="text-[11px] text-[#aaaaaa] mt-0.5">- Room: <span className="text-white font-medium">{hostInfo?.roomName}</span>{' '}+ <div className="text-[11px] text-[#b5b5b5] mt-0.5">+ Room: <span className="text-[#e5e5e5] font-medium">{hostInfo?.roomName}</span>{' '}(port {hostInfo?.port})</div></div>@@ -284,29 +311,30 @@ export const HostModal: React.FC<HostModalProps> = ({{/* Shareable Link Box */}<div>- <label className="block text-[11px] font-medium text-[#aaaaaa] mb-1.5 flex items-center justify-between">+ <label className="block text-[11px] font-medium text-[#8a8a8a] mb-1.5 flex items-center justify-between"><span>{hostInfo?.isGlobal- ? 'Worldwide Invite Link (Browser or Desktop App):'- : 'Local Wi-Fi Invite Link:'}+ ? 'Worldwide Invite Link (Browser or Desktop App)'+ : 'Local Wi-Fi Invite Link'}</span>{hostInfo?.isGlobal && (- <span className="text-[10px] text-sky-400 font-mono flex items-center space-x-1">- <span className="w-1.5 h-1.5 rounded-full bg-sky-400 animate-pulse" />+ <span className="text-[10px] text-[var(--accent)] font-mono flex items-center gap-1">+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" /><span>HTTPS + WSS</span></span>)}</label>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><inputtype="text"readOnlyvalue={hostInfo?.inviteUrl || ''}- className="flex-1 rounded border border-[#3e3e3e] bg-[#1a1a1a] px-3 py-1.5 text-xs text-white font-mono select-all focus:outline-hidden"+ className="flex-1 rounded border border-[#2c2c2c] bg-[#161616] px-3 py-1.5 text-xs text-[#e5e5e5] font-mono select-all focus:outline-hidden"/><button+ type="button"onClick={handleCopyLink}- className="flex items-center space-x-1.5 rounded border border-[#3e3e3e] bg-[#2a2a2a] hover:bg-[#333333] hover:border-[#4e4e4e] px-3 py-1.5 text-xs font-medium text-white transition-colors shadow-xs shrink-0 cursor-pointer"+ className="flex items-center gap-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 px-3 py-1.5 text-xs font-medium transition-opacity shrink-0 cursor-pointer">{copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}<span>{copied ? 'Copied' : 'Copy'}</span>@@ -314,21 +342,22 @@ export const HostModal: React.FC<HostModalProps> = ({</div>{hostInfo?.isGlobal && hostInfo.localInviteUrl && (- <div className="mt-2 pt-2 border-t border-[#333333] flex items-center justify-between text-[10px] text-[#888888]">+ <div className="mt-2 pt-2 border-t border-[#2c2c2c] flex items-center justify-between text-[10px] text-[#8a8a8a]"><span className="truncate">Local LAN:{' '}- <span className="font-mono text-[#aaaaaa]">{hostInfo.localInviteUrl}</span>+ <span className="font-mono text-[#b5b5b5]">{hostInfo.localInviteUrl}</span></span><button+ type="button"onClick={handleCopyLocalLink}- className="text-[#aaaaaa] hover:text-white underline cursor-pointer ml-2 shrink-0"+ className="text-[#b5b5b5] hover:text-[#e5e5e5] underline cursor-pointer ml-2 shrink-0">{copiedLocal ? 'Copied' : 'Copy Local'}</button></div>)}- <p className="text-[10px] text-[#777777] mt-1.5 leading-relaxed">+ <p className="text-[10px] text-[#8a8a8a] mt-1.5 leading-relaxed">Share this link to open directly in a browser or paste it into the Join tab in thedesktop app.</p>@@ -336,19 +365,19 @@ export const HostModal: React.FC<HostModalProps> = ({{/* Connected Peers List */}<div>- <div className="text-xs font-medium text-[#aaaaaa] mb-2 flex items-center justify-between">+ <div className="text-[11px] font-medium text-[#8a8a8a] mb-1.5 flex items-center justify-between"><span>Participants on Canvas ({peers.length + 1})</span></div>- <div className="rounded border border-[#333333] bg-[#1a1a1a] max-h-36 overflow-y-auto divide-y divide-[#2a2a2a]">+ <div className="rounded-md border border-[#2c2c2c] bg-[#161616] max-h-36 overflow-y-auto divide-y divide-[#252525]"><div className="flex items-center justify-between px-3 py-2 text-xs">- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><div- className="w-3 h-3 rounded-full shrink-0"+ className="w-2.5 h-2.5 rounded-full shrink-0"style={{ backgroundColor: myPeer.color }}/>- <span className="font-medium text-white">{myPeer.name} (You)</span>+ <span className="font-medium text-[#e5e5e5]">{myPeer.name} (You)</span></div>- <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-300">+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-300">Host</span></div>@@ -360,14 +389,14 @@ export const HostModal: React.FC<HostModalProps> = ({key={peer.id}className="flex items-center justify-between gap-2 px-3 py-2 text-xs">- <div className="flex items-center space-x-2 min-w-0">+ <div className="flex items-center gap-2 min-w-0"><div- className="w-3 h-3 rounded-full shrink-0"+ className="w-2.5 h-2.5 rounded-full shrink-0"style={{ backgroundColor: peer.color }}/>- <span className="text-[#dddddd] truncate">{peer.name}</span>+ <span className="text-[#d4d4d4] truncate">{peer.name}</span></div>- <div className="flex items-center space-x-1.5 shrink-0">+ <div className="flex items-center gap-1.5 shrink-0">{onSetPeerRole ? (<selectaria-label={`Role for ${peer.name}`}@@ -378,13 +407,13 @@ export const HostModal: React.FC<HostModalProps> = ({e.target.value === 'viewer' ? 'viewer' : 'editor')}- className="rounded border border-[#3e3e3e] bg-[#252525] px-1.5 py-0.5 text-[10px] text-[#e0e0e0] focus:outline-hidden cursor-pointer"+ className="rounded border border-[#2c2c2c] bg-[#202020] px-1.5 py-0.5 text-[10px] text-[#e5e5e5] focus:outline-hidden cursor-pointer"><option value="editor">Editor</option><option value="viewer">Viewer</option></select>) : (- <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#2a2a2a] text-[#aaaaaa] capitalize">+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#262626] text-[#8a8a8a] capitalize">{peerRole}</span>)}@@ -393,7 +422,7 @@ export const HostModal: React.FC<HostModalProps> = ({type="button"onClick={() => onKickPeer(peer.id)}title={`Kick ${peer.name}`}- className="p-1 rounded text-[#999999] hover:text-amber-300 hover:bg-amber-500/15 transition-colors cursor-pointer"+ className="p-1 rounded text-[#8a8a8a] hover:text-amber-300 hover:bg-amber-500/15 transition-colors cursor-pointer"><UserX className="w-3.5 h-3.5" /></button>@@ -403,7 +432,7 @@ export const HostModal: React.FC<HostModalProps> = ({type="button"onClick={() => onBanPeer(peer.id)}title={`Ban ${peer.name}`}- className="p-1 rounded text-[#999999] hover:text-rose-400 hover:bg-rose-500/15 transition-colors cursor-pointer"+ className="p-1 rounded text-[#8a8a8a] hover:text-red-400 hover:bg-red-500/15 transition-colors cursor-pointer"><Ban className="w-3.5 h-3.5" /></button>@@ -417,21 +446,21 @@ export const HostModal: React.FC<HostModalProps> = ({{bannedPeerIds.length > 0 && (<div>- <div className="text-[11px] font-medium text-[#aaaaaa] mb-1.5">+ <div className="text-[11px] font-medium text-[#8a8a8a] mb-1.5">Banned Peers ({bannedPeerIds.length})</div>- <div className="rounded border border-[#333333] bg-[#1a1a1a] max-h-24 overflow-y-auto divide-y divide-[#2a2a2a]">+ <div className="rounded-md border border-[#2c2c2c] bg-[#161616] max-h-24 overflow-y-auto divide-y divide-[#252525]">{bannedPeerIds.map((pid) => (<divkey={pid}className="flex items-center justify-between px-3 py-1.5 text-[11px]">- <span className="font-mono text-[#aaaaaa] truncate">{pid}</span>+ <span className="font-mono text-[#8a8a8a] truncate">{pid}</span>{onUnbanPeer && (<buttontype="button"onClick={() => onUnbanPeer(pid)}- className="text-[10px] text-sky-400 hover:text-sky-300 underline ml-2 shrink-0 cursor-pointer"+ className="text-[10px] text-[var(--accent)] hover:underline ml-2 shrink-0 cursor-pointer">Unban</button>@@ -443,13 +472,14 @@ export const HostModal: React.FC<HostModalProps> = ({)}{/* Stop Button */}- <div className="pt-2">+ <div className="pt-1"><button+ type="button"onClick={() => {onStopHosting();onClose();}}- className="w-full flex items-center justify-center space-x-2 rounded border border-rose-500/30 bg-rose-500/10 hover:bg-rose-500/20 py-2 text-xs font-medium text-rose-400 transition-colors cursor-pointer"+ className="w-full flex items-center justify-center gap-2 rounded border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 py-2 text-xs font-medium text-red-400 transition-colors cursor-pointer"><Power className="w-3.5 h-3.5" /><span>Stop Collaborative Session</span>@@ -459,18 +489,18 @@ export const HostModal: React.FC<HostModalProps> = ({) : isConnected ? (// Active Guest View<div className="space-y-4">- <div className="rounded-md border border-sky-500/30 bg-sky-500/10 p-3.5 flex items-start space-x-3">- <Globe className="w-5 h-5 text-sky-400 shrink-0 mt-0.5" />+ <div className="rounded-md border border-[var(--accent-border)] bg-[#161616] p-3.5 flex items-start gap-3">+ <Globe className="w-4 h-4 text-[var(--accent)] shrink-0 mt-0.5" /><div className="flex-1 min-w-0">- <div className="text-xs font-semibold text-sky-300">Connected to Session</div>- <div className="text-[11px] text-[#aaaaaa] mt-0.5 truncate">+ <div className="text-xs font-medium text-[#e5e5e5]">Connected to Session</div>+ <div className="text-[11px] text-[#8a8a8a] mt-0.5 truncate">Room:{' '}- <span className="text-white font-medium">+ <span className="text-[#e5e5e5] font-medium">{hostInfo?.roomName || 'Studio'}</span></div>{hostInfo?.localIp && (- <div className="text-[10px] text-[#888888] font-mono truncate mt-0.5">+ <div className="text-[10px] text-[#8a8a8a] font-mono truncate mt-0.5">{hostInfo.localIp}</div>)}@@ -478,23 +508,23 @@ export const HostModal: React.FC<HostModalProps> = ({</div><div>- <div className="text-xs font-medium text-[#aaaaaa] mb-2">+ <div className="text-[11px] font-medium text-[#8a8a8a] mb-1.5">Participants on Canvas ({peers.length + 1})</div>- <div className="rounded border border-[#333333] bg-[#1a1a1a] max-h-40 overflow-y-auto divide-y divide-[#2a2a2a]">+ <div className="rounded-md border border-[#2c2c2c] bg-[#161616] max-h-40 overflow-y-auto divide-y divide-[#252525]"><div className="flex items-center justify-between px-3 py-2 text-xs">- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><div- className="w-3 h-3 rounded-full shrink-0"+ className="w-2.5 h-2.5 rounded-full shrink-0"style={{ backgroundColor: myPeer.color }}/>- <span className="font-medium text-white">{myPeer.name} (You)</span>+ <span className="font-medium text-[#e5e5e5]">{myPeer.name} (You)</span></div><spanclassName={`text-[10px] font-mono px-1.5 py-0.5 rounded capitalize ${myRole === 'viewer'- ? 'bg-slate-500/20 text-slate-300'- : 'bg-emerald-500/20 text-emerald-300'+ ? 'bg-[#262626] text-[#8a8a8a]'+ : 'bg-emerald-500/15 text-emerald-300'}`}>{myRole}@@ -505,14 +535,14 @@ export const HostModal: React.FC<HostModalProps> = ({key={peer.id}className="flex items-center justify-between px-3 py-2 text-xs">- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><div- className="w-3 h-3 rounded-full shrink-0"+ className="w-2.5 h-2.5 rounded-full shrink-0"style={{ backgroundColor: peer.color }}/>- <span className="text-[#dddddd]">{peer.name}</span>+ <span className="text-[#d4d4d4]">{peer.name}</span></div>- <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#2a2a2a] text-[#aaaaaa] capitalize">+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#262626] text-[#8a8a8a] capitalize">{peer.isHost ? 'Host' : peer.role || 'Editor'}</span></div>@@ -520,13 +550,14 @@ export const HostModal: React.FC<HostModalProps> = ({</div></div>- <div className="pt-2">+ <div className="pt-1"><button+ type="button"onClick={() => {onLeaveRoom();onClose();}}- className="w-full flex items-center justify-center space-x-2 rounded border border-rose-500/30 bg-rose-500/10 hover:bg-rose-500/20 py-2 text-xs font-medium text-rose-400 transition-colors cursor-pointer"+ className="w-full flex items-center justify-center gap-2 rounded border border-red-500/30 bg-red-500/10 hover:bg-red-500/20 py-2 text-xs font-medium text-red-400 transition-colors cursor-pointer"><LogOut className="w-3.5 h-3.5" /><span>Leave Session</span>@@ -536,14 +567,14 @@ export const HostModal: React.FC<HostModalProps> = ({) : (// Disconnected: Host / Join Tabs<div className="space-y-4">- <div className="grid grid-cols-2 rounded-md border border-[#383838] bg-[#1a1a1a] p-0.5">+ <div className="grid grid-cols-2 rounded-md border border-[#2c2c2c] bg-[#161616] p-0.5"><buttontype="button"onClick={() => setActiveTab('host')}className={`rounded py-1.5 text-xs font-medium transition-colors cursor-pointer ${activeTab === 'host'- ? 'bg-[#2e2e2e] text-white'- : 'text-[#888888] hover:text-[#cccccc]'+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Host Session@@ -553,8 +584,8 @@ export const HostModal: React.FC<HostModalProps> = ({onClick={() => setActiveTab('join')}className={`rounded py-1.5 text-xs font-medium transition-colors cursor-pointer ${activeTab === 'join'- ? 'bg-[#2e2e2e] text-white'- : 'text-[#888888] hover:text-[#cccccc]'+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>Join via Link@@ -562,8 +593,8 @@ export const HostModal: React.FC<HostModalProps> = ({</div><div>- <label className="block text-xs font-medium text-[#cccccc] mb-1.5 flex items-center space-x-1">- <User className="w-3.5 h-3.5 text-[#888888]" />+ <label className="text-[11px] font-medium text-[#b5b5b5] mb-1.5 flex items-center gap-1.5">+ <User className="w-3.5 h-3.5 text-[#8a8a8a]" /><span>Your Nickname</span></label><input@@ -575,14 +606,14 @@ export const HostModal: React.FC<HostModalProps> = ({}}maxLength={40}placeholder="Your name"- className="w-full rounded border border-[#3e3e3e] bg-[#1a1a1a] px-3 py-2 text-xs text-white focus:border-[#007acc] focus:outline-hidden"+ className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] focus:border-[var(--accent-border)] focus:outline-hidden"/></div>{activeTab === 'host' ? (<><div>- <label className="block text-xs font-medium text-[#cccccc] mb-1.5">+ <label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">Room / Canvas Name</label><input@@ -593,13 +624,13 @@ export const HostModal: React.FC<HostModalProps> = ({setRoomName(e.target.value);}}placeholder="Ink Studio Session"- className="w-full rounded border border-[#3e3e3e] bg-[#1a1a1a] px-3 py-2 text-xs text-white focus:border-[#007acc] focus:outline-hidden"+ className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] focus:border-[var(--accent-border)] focus:outline-hidden"/></div>{/* Network Mode Switcher */}<div>- <label className="block text-xs font-medium text-[#cccccc] mb-1.5">+ <label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">Connection Mode</label><div className="grid grid-cols-2 gap-2">@@ -609,14 +640,14 @@ export const HostModal: React.FC<HostModalProps> = ({setIsGlobal(true);setStartError(null);}}- className={`flex items-start space-x-2 rounded-lg border p-2.5 text-left transition-colors cursor-pointer ${+ className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${isGlobal- ? 'border-sky-500 bg-sky-500/10 text-white'- : 'border-[#383838] bg-[#1a1a1a] text-[#888888] hover:border-[#484848] hover:text-[#cccccc]'+ ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'+ : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'}`}><Globe- className={`w-4 h-4 shrink-0 mt-0.5 ${isGlobal ? 'text-sky-400' : 'text-[#888888]'}`}+ className={`w-4 h-4 shrink-0 mt-0.5 ${isGlobal ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}/><div><div className="text-xs font-medium">Worldwide (Internet)</div>@@ -630,14 +661,14 @@ export const HostModal: React.FC<HostModalProps> = ({setIsGlobal(false);setStartError(null);}}- className={`flex items-start space-x-2 rounded-lg border p-2.5 text-left transition-colors cursor-pointer ${+ className={`flex items-start gap-2 rounded-md border p-2.5 text-left transition-colors cursor-pointer ${!isGlobal- ? 'border-emerald-500 bg-emerald-500/10 text-white'- : 'border-[#383838] bg-[#1a1a1a] text-[#888888] hover:border-[#484848] hover:text-[#cccccc]'+ ? 'border-[var(--accent-border)] bg-[var(--accent-subtle)] text-[#e5e5e5]'+ : 'border-[#2c2c2c] bg-[#161616] text-[#8a8a8a] hover:border-[#3a3a3a] hover:text-[#e5e5e5]'}`}><Wifi- className={`w-4 h-4 shrink-0 mt-0.5 ${!isGlobal ? 'text-emerald-400' : 'text-[#888888]'}`}+ className={`w-4 h-4 shrink-0 mt-0.5 ${!isGlobal ? 'text-[var(--accent)]' : 'text-[#8a8a8a]'}`}/><div><div className="text-xs font-medium">Local Network Only</div>@@ -649,25 +680,25 @@ export const HostModal: React.FC<HostModalProps> = ({{!isGlobal && (<div>- <label className="block text-xs font-medium text-[#cccccc] mb-1.5">+ <label className="block text-[11px] font-medium text-[#b5b5b5] mb-1.5">Local Port</label><inputtype="number"value={port}onChange={(e) => setPort(Number(e.target.value))}- className="w-full rounded border border-[#3e3e3e] bg-[#1a1a1a] px-3 py-2 text-xs text-white focus:border-[#007acc] focus:outline-hidden font-mono"+ className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] focus:border-[var(--accent-border)] focus:outline-hidden font-mono"/>- <p className="text-[10px] text-[#777777] mt-1">+ <p className="text-[10px] text-[#8a8a8a] mt-1">Default is 30303. Works over local Wi-Fi or virtual LAN (Tailscale).</p></div>)}{startError && (- <div className="rounded-md border border-rose-500/40 bg-rose-500/10 p-3 text-[11px] text-rose-300 space-y-2">- <div className="flex items-start space-x-2">- <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5 text-rose-400" />+ <div className="rounded-md border border-red-500/35 bg-red-500/10 p-3 text-[11px] text-red-300 space-y-2">+ <div className="flex items-start gap-2">+ <AlertTriangle className="w-4 h-4 shrink-0 mt-0.5 text-red-400" /><span className="break-words">{startError}</span></div>{isGlobal && (@@ -677,7 +708,7 @@ export const HostModal: React.FC<HostModalProps> = ({setIsGlobal(false);void handleStart(false);}}- className="text-[11px] text-white underline hover:text-emerald-300 cursor-pointer"+ className="text-[11px] text-[#e5e5e5] underline hover:text-white cursor-pointer">Start Local Wi-Fi Server instead</button>@@ -685,9 +716,9 @@ export const HostModal: React.FC<HostModalProps> = ({</div>)}- <div className="rounded-md border border-[#333333] bg-[#1a1a1a] p-3 text-[11px] text-[#aaaaaa] space-y-1.5">- <div className="flex items-center space-x-1.5 text-white font-medium">- <Shield className="w-3.5 h-3.5 text-[#888888]" />+ <div className="rounded-md border border-[#2c2c2c] bg-[#161616] p-3 text-[11px] text-[#8a8a8a] space-y-1">+ <div className="flex items-center gap-1.5 text-[#e5e5e5] font-medium">+ <Shield className="w-3.5 h-3.5 text-[#8a8a8a]" /><span>{isGlobal ? 'Encrypted Worldwide Tunnel' : 'Local Wi-Fi Access'}</span>@@ -700,13 +731,14 @@ export const HostModal: React.FC<HostModalProps> = ({</div><button+ type="button"disabled={isStarting}onClick={() => void handleStart()}- className="w-full flex items-center justify-center space-x-2 rounded border border-[#3e3e3e] bg-[#2a2a2a] hover:bg-[#333333] hover:border-[#4e4e4e] py-2.5 text-xs font-semibold text-white transition-colors shadow-xs disabled:opacity-50 cursor-pointer"+ className="w-full flex items-center justify-center gap-2 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 py-2 text-xs font-medium transition-opacity disabled:opacity-50 cursor-pointer">{isStarting ? (<>- <Loader2 className="w-4 h-4 text-sky-400 animate-spin" />+ <Loader2 className="w-3.5 h-3.5 animate-spin" /><span>{startStatus ||(isGlobal ? 'Starting Worldwide Tunnel...' : 'Starting Server...')}@@ -715,11 +747,11 @@ export const HostModal: React.FC<HostModalProps> = ({) : (<>{isGlobal ? (- <Globe className="w-4 h-4 text-sky-400" />+ <Globe className="w-3.5 h-3.5" />) : (- <Users className="w-4 h-4 text-[#cccccc]" />+ <Users className="w-3.5 h-3.5" />)}- <span>Start Server & Copy Link</span>+ <span>Start Server & Copy Link</span></>)}</button>@@ -727,8 +759,8 @@ export const HostModal: React.FC<HostModalProps> = ({) : (<form onSubmit={handleJoinSubmit} className="space-y-4"><div>- <label className="block text-xs font-medium text-[#cccccc] mb-1.5 flex items-center space-x-1">- <Link2 className="w-3.5 h-3.5 text-[#888888]" />+ <label className="text-[11px] font-medium text-[#b5b5b5] mb-1.5 flex items-center gap-1.5">+ <Link2 className="w-3.5 h-3.5 text-[#8a8a8a]" /><span>Invite Link</span></label><input@@ -736,9 +768,9 @@ export const HostModal: React.FC<HostModalProps> = ({value={joinUrl}onChange={(e) => setJoinUrl(e.target.value)}placeholder="https://....trycloudflare.com/?room=...&token=..."- className="w-full rounded border border-[#3e3e3e] bg-[#1a1a1a] px-3 py-2 text-xs text-white font-mono focus:border-[#007acc] focus:outline-hidden"+ className="w-full rounded border border-[#2c2c2c] bg-[#161616] px-3 py-2 text-xs text-[#e5e5e5] font-mono focus:border-[var(--accent-border)] focus:outline-hidden"/>- <p className="text-[10px] text-[#777777] mt-1">+ <p className="text-[10px] text-[#8a8a8a] mt-1">Paste the full worldwide or LAN invite link shared by the host.</p></div>@@ -746,16 +778,16 @@ export const HostModal: React.FC<HostModalProps> = ({<buttontype="submit"disabled={isJoining || !joinUrl.trim()}- className="w-full flex items-center justify-center space-x-2 rounded border border-[#3e3e3e] bg-[#2a2a2a] hover:bg-[#333333] hover:border-[#4e4e4e] py-2.5 text-xs font-semibold text-white transition-colors shadow-xs disabled:opacity-50 cursor-pointer"+ className="w-full flex items-center justify-center gap-2 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 py-2 text-xs font-medium transition-opacity disabled:opacity-50 cursor-pointer">{isJoining ? (<>- <Loader2 className="w-4 h-4 text-sky-400 animate-spin" />+ <Loader2 className="w-3.5 h-3.5 animate-spin" /><span>Connecting...</span></>) : (<>- <Link2 className="w-4 h-4 text-sky-400" />+ <Link2 className="w-3.5 h-3.5" /><span>Join Session</span></>)}diff --git a/src/components/LayerStylesModal.tsx b/src/components/LayerStylesModal.tsxindex 5c41333..e6f43e1 100644--- a/src/components/LayerStylesModal.tsx+++ b/src/components/LayerStylesModal.tsx@@ -267,9 +267,16 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({if (!isOpen) return null;return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-xs select-none">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="layer-styles-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={onClose}+ ><div- className="w-[640px] max-w-[95vw] bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl flex flex-col text-[#e5e5e5] overflow-hidden"+ onClick={(e) => e.stopPropagation()}+ className="w-[640px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] flex flex-col text-[#e5e5e5] overflow-hidden"style={{transform: `translate(${pos.x}px, ${pos.y}px)`,}}@@ -279,12 +286,17 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({onPointerDown={handlePointerDown}onPointerMove={handlePointerMove}onPointerUp={handlePointerUp}- className="flex items-center justify-between px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.06] cursor-move text-xs font-medium"+ className="h-9 flex items-center justify-between px-3.5 bg-[#161616] border-b border-[#2c2c2c] cursor-move text-xs font-medium">- <span className="text-[#e5e5e5]">Layer Style — {layerName}</span>+ <span id="layer-styles-modal-title" className="text-[#e5e5e5]">+ Layer Style — {layerName}+ </span><button+ type="button"onClick={onClose}- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"><X className="w-3.5 h-3.5" /></button>@@ -293,7 +305,7 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({{/* Modal Body: Left category sidebar + Right parameter panel */}<div className="flex flex-1 min-h-[380px] text-xs">{/* Left Column: Styles Checklist */}- <div className="w-48 bg-[#161616] border-r border-white/[0.06] p-2 flex flex-col justify-between">+ <div className="w-48 bg-[#161616] border-r border-[#2c2c2c] p-2 flex flex-col justify-between"><div className="space-y-1"><div className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-[#8a8a8a]">Styles@@ -673,22 +685,25 @@ export const LayerStylesModal: React.FC<LayerStylesModalProps> = ({</div>{/* Footer Actions */}- <div className="flex items-center justify-between px-4 py-2.5 bg-[#1a1a1a] border-t border-white/[0.06]">+ <div className="flex items-center justify-between px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c]"><button+ type="button"onClick={handleResetDefaults}- className="px-3 py-1.5 text-xs text-[#8a8a8a] hover:text-[#e5e5e5] bg-[#161616] hover:bg-[#2c2c2c] rounded border border-white/[0.06] transition-colors cursor-pointer"+ className="px-3 py-1.5 text-xs text-[#8a8a8a] hover:text-[#e5e5e5] bg-[#202020] hover:bg-[#2c2c2c] rounded border border-[#2c2c2c] transition-colors cursor-pointer">Reset Category</button>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><button+ type="button"onClick={onClose}- className="px-3.5 py-1.5 text-xs text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ className="px-3.5 py-1.5 text-xs font-medium text-[#e5e5e5] bg-[#2a2a2a] hover:bg-[#363636] rounded transition-colors cursor-pointer">Cancel</button><button+ type="button"onClick={handleConfirm}className="px-4 py-1.5 text-xs font-medium bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded transition-opacity cursor-pointer">diff --git a/src/components/LeftSidebar.tsx b/src/components/LeftSidebar.tsxindex 2384660..4b2d58f 100644--- a/src/components/LeftSidebar.tsx+++ b/src/components/LeftSidebar.tsx@@ -52,84 +52,88 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({}, [onSelectTool, onSwapColors, onToggleTransparentColor]);return (- <aside className="w-14 bg-[#252526] border-r border-[#333333] flex flex-col items-center py-3 select-none z-10 shrink-0">+ <aside className="w-14 bg-[#202020] border-r border-[#2c2c2c] flex flex-col items-center py-3 select-none z-10 shrink-0"><div className="flex flex-col items-center space-y-2">{/* Brush Button */}<button+ type="button"onClick={() => onSelectTool('brush')}title="Brush Tool (B)"- className={`w-10 h-10 rounded-[2px] flex items-center justify-center transition-colors relative group ${+ className={`w-10 h-10 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${currentTool === 'brush'- ? 'bg-[#383838] border border-[#4a4a4a] text-white shadow-sm'- : 'text-[#999999] hover:text-[#cccccc] hover:bg-[#2d2d2d] border border-transparent'+ ? 'bg-[#2c2c2c] border border-[#3a3a3a] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'}`}><Paintbrush className="w-5 h-5" />{/* Tooltip */}- <div className="absolute left-12 bg-[#252526] text-[#cccccc] text-xs px-2 py-1 rounded-[2px] border border-[#3a3a3a] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">+ <div className="absolute left-12 bg-[#161616] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-[#2c2c2c] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">Brush (B)</div></button>{/* Eraser Button */}<button+ type="button"onClick={() => onSelectTool('eraser')}title="Eraser Tool (E)"- className={`w-10 h-10 rounded-[2px] flex items-center justify-center transition-colors relative group ${+ className={`w-10 h-10 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${currentTool === 'eraser'- ? 'bg-[#383838] border border-[#4a4a4a] text-white shadow-sm'- : 'text-[#999999] hover:text-[#cccccc] hover:bg-[#2d2d2d] border border-transparent'+ ? 'bg-[#2c2c2c] border border-[#3a3a3a] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'}`}><Eraser className="w-5 h-5" />- <div className="absolute left-12 bg-[#252526] text-[#cccccc] text-xs px-2 py-1 rounded-[2px] border border-[#3a3a3a] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">+ <div className="absolute left-12 bg-[#161616] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-[#2c2c2c] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">Eraser (E)</div></button>{/* Pipette Button */}<button+ type="button"onClick={() => onSelectTool('pipette')}title="Pipette Tool (I / Hold Alt)"- className={`w-10 h-10 rounded-[2px] flex items-center justify-center transition-colors relative group ${+ className={`w-10 h-10 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${currentTool === 'pipette'- ? 'bg-[#383838] border border-[#4a4a4a] text-white shadow-sm'- : 'text-[#999999] hover:text-[#cccccc] hover:bg-[#2d2d2d] border border-transparent'+ ? 'bg-[#2c2c2c] border border-[#3a3a3a] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'}`}><Pipette className="w-5 h-5" />- <div className="absolute left-12 bg-[#252526] text-[#cccccc] text-xs px-2 py-1 rounded-[2px] border border-[#3a3a3a] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">+ <div className="absolute left-12 bg-[#161616] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-[#2c2c2c] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">Pipette (I / Hold Alt)</div></button>{/* Liquify Button */}<button+ type="button"onClick={() => onSelectTool('liquify')}title="Liquify Tool (J)"- className={`w-10 h-10 rounded-[2px] flex items-center justify-center transition-colors relative group ${+ className={`w-10 h-10 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${currentTool === 'liquify'- ? 'bg-[#383838] border border-[#4a4a4a] text-white shadow-sm'- : 'text-[#999999] hover:text-[#cccccc] hover:bg-[#2d2d2d] border border-transparent'+ ? 'bg-[#2c2c2c] border border-[#3a3a3a] text-[#e5e5e5]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'}`}><LiquifyIcon className="w-5 h-5" />- <div className="absolute left-12 bg-[#252526] text-[#cccccc] text-xs px-2 py-1 rounded-[2px] border border-[#3a3a3a] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">+ <div className="absolute left-12 bg-[#161616] text-[#e5e5e5] text-xs px-2 py-1 rounded border border-[#2c2c2c] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50">Liquify (J)</div></button></div>- <div className="my-3 w-8 h-px bg-[#333333]" />+ <div className="my-3 w-8 h-px bg-[#2c2c2c]" />- {/* Primary & Secondary Color Indicator Swatches (Clip Studio Paint style) */}+ {/* Primary & Secondary Color Indicator Swatches */}<div className="mt-auto flex flex-col items-center space-y-2 pb-1"><div className="relative w-9 h-9">{/* Secondary Color Swatch (bottom-right) */}<divonClick={onSwapColors}title={`Secondary Color: ${secondaryColor} (Click or press X to swap)`}- className="absolute bottom-0 right-0 w-6 h-6 rounded-[2px] border border-[#555555] cursor-pointer hover:border-white shadow-sm z-0"+ className="absolute bottom-0 right-0 w-6 h-6 rounded border border-[#3a3a3a] cursor-pointer hover:border-[#8a8a8a] shadow-sm z-0"style={{ backgroundColor: secondaryColor }}/>@@ -143,23 +147,23 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({}}}title={`Primary Active Color: ${primaryColor} (Click to select/swap)`}- className={`absolute top-0 left-0 w-6 h-6 rounded-[2px] cursor-pointer transition-all z-10 ${+ className={`absolute top-0 left-0 w-6 h-6 rounded cursor-pointer transition-all z-10 ${!isTransparentColor- ? 'border border-white shadow-md ring-1 ring-white/40'- : 'border border-[#555555] hover:border-white opacity-80'+ ? 'border border-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'border border-[#3a3a3a] hover:border-[#8a8a8a] opacity-80'}`}style={{ backgroundColor: primaryColor }}/></div>- {/* Transparent Color Swatch (Clip Studio Paint 'C' key toggle) */}+ {/* Transparent Color Swatch */}<divonClick={onToggleTransparentColor}title="Transparent Ink / Color (C) - Brush as textured eraser"- className={`w-7 h-3.5 rounded-[2px] border cursor-pointer relative overflow-hidden transition-all ${+ className={`w-7 h-3.5 rounded border cursor-pointer relative overflow-hidden transition-all ${isTransparentColor- ? 'border-[#38bdf8] ring-2 ring-[#38bdf8] shadow-md scale-105'- : 'border-[#555555] hover:border-white opacity-80 hover:opacity-100'+ ? 'border-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'border-[#3a3a3a] hover:border-[#8a8a8a] opacity-80 hover:opacity-100'}`}style={{backgroundImage:@@ -172,14 +176,15 @@ export const LeftSidebar: React.FC<LeftSidebarProps> = ({{/* Swap button */}<button+ type="button"onClick={onSwapColors}title="Swap Colors (X)"- className="p-1 text-[#888888] hover:text-[#cccccc] hover:bg-[#333333] rounded-[2px] transition-colors"+ className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"><ArrowLeftRight className="w-3.5 h-3.5" /></button>- <span className="text-[9px] text-[#777777] font-mono">+ <span className="text-[9px] text-[#6e6e6e] font-mono">X / C</span></div>diff --git a/src/components/MangaEffectsModal.tsx b/src/components/MangaEffectsModal.tsxindex 9afb8a6..72c57e5 100644--- a/src/components/MangaEffectsModal.tsx+++ b/src/components/MangaEffectsModal.tsx@@ -98,6 +98,19 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({}}, [isOpen, updatePreview]);+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, onClose]);+if (!isOpen) return null;// Handle clicking on preview canvas to set focal point for saturated lines@@ -127,21 +140,35 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({};return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-xs select-none">- <div className="w-[680px] bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl overflow-hidden flex flex-col text-[#e5e5e5] font-sans">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="manga-effects-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={onClose}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-[680px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] overflow-hidden flex flex-col text-[#e5e5e5] font-sans"+ >{/* Header */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.06] flex items-center justify-between">- <h2 className="text-xs font-medium text-[#e5e5e5]">Manga Effect Lines</h2>+ <div className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between">+ <h2 id="manga-effects-modal-title" className="text-xs font-medium text-[#e5e5e5]">+ Manga Effect Lines+ </h2><button+ type="button"onClick={onClose}- className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 flex items-center justify-center rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"><X className="w-3.5 h-3.5" /></button></div>{/* Tab Switcher */}- <div className="flex border-b border-white/[0.06] bg-[#1a1a1a] px-4">+ <div className="flex border-b border-[#2c2c2c] bg-[#161616] px-4"><buttononClick={() => setActiveTab('saturated')}className={`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors cursor-pointer ${@@ -396,7 +423,7 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({</div>{/* Footer */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-t border-white/[0.06] flex items-center justify-between">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between"><buttononClick={() => {if (activeTab === 'saturated') {@@ -429,16 +456,18 @@ export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({Reset Defaults</button>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><button+ type="button"onClick={onClose}- className="px-3 py-1.5 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-xs transition-colors cursor-pointer"+ className="px-3.5 py-1.5 bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] font-medium rounded text-xs transition-colors cursor-pointer">Cancel</button><button+ type="button"onClick={handleApplyClick}- className="px-3.5 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer"+ className="px-4 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer">Apply Effect</button>diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsxindex 82ddc05..8e67af2 100644--- a/src/components/ModalHost.tsx+++ b/src/components/ModalHost.tsx@@ -2,6 +2,7 @@ import React, { useCallback } from 'react';import { CheckCircle2, Loader2 } from 'lucide-react';import {AdjustmentLayerData,+ FilterType,LayerItem,LayerStyles,NewCanvasOptions,@@ -11,7 +12,7 @@ import { CollabPeer, CollabRole, ConnectionStatus, SessionHostInfo } from '../tyimport { ParsedInviteLink } from '../services/multiplayerService';import { CrashedSessionInfo } from '../services/recoveryService';import { TonalCorrectionType } from '../utils/tonalEngine';-import { AnyTonalParams } from '../hooks/useTonalAndFilterActions';+import { AnyFilterParams, AnyTonalParams } from '../hooks/useTonalAndFilterActions';import { SaturatedLinesOptions, StreamLinesOptions } from '../utils/mangaEffectsEngine';import { compositeCanvas, createDocumentRegionRenderer } from '../utils/saveManager';import { documentStore } from '../utils/documentStore';@@ -35,6 +36,8 @@ import { UpdateModal } from './UpdateModal';import { UpdateToast } from './UpdateToast';import { BrushStudioModal } from './BrushStudioModal';import { CloseConfirmModal } from './CloseConfirmModal';+import { ConfirmDialogModal } from './ConfirmDialogModal';+import { FilterModal } from './FilterModal';import { SaveDocumentResult } from '../utils/appCloseFlow';export type InviteLinkPayload = ParsedInviteLink;@@ -56,6 +59,7 @@ export interface ModalHostProps {params: AnyTonalParams,enabled: boolean) => void;+ handleApplyFilter: (type: FilterType, params?: AnyFilterParams) => void;handleApplyAdjustment: (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',data: AdjustmentLayerData@@ -126,6 +130,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(handleTonalCancel,handleTonalApply,handleTonalPreviewChange,+ handleApplyFilter,handleApplyAdjustment,handleApplyLayerStyles,handleConfirmTone,@@ -172,6 +177,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(const isAboutModalOpen = useUiStore((s) => s.isAboutModalOpen);const appSettings = useUiStore((s) => s.appSettings);const tonalModalState = useUiStore((s) => s.tonalModalState);+ const filterModalState = useUiStore((s) => s.filterModalState);const adjustmentModalState = useUiStore((s) => s.adjustmentModalState);const layerStylesModalState = useUiStore((s) => s.layerStylesModalState);const isToneModalOpen = useUiStore((s) => s.isToneModalOpen);@@ -274,6 +280,13 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(onPreviewChange={handleTonalPreviewChange}/>+ <FilterModal+ isOpen={filterModalState.isOpen}+ type={filterModalState.type}+ onClose={() => uiStoreActions.closeFilterModal()}+ onApply={handleApplyFilter}+ />+{adjustmentModalState.isOpen && (<AdjustmentModalisOpen={adjustmentModalState.isOpen}@@ -355,7 +368,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo({isLoadingFile && (<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 select-none">- <div className="bg-[#202020] rounded-md shadow-[0_16px_48px_rgba(0,0,0,0.75)] px-5 py-3.5 flex items-center gap-3 text-xs text-[#e5e5e5]">+ <div className="bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_16px_48px_rgba(0,0,0,0.75)] px-5 py-3.5 flex items-center gap-3 text-xs text-[#e5e5e5]"><Loader2 className="w-4 h-4 text-[var(--accent)] animate-spin" /><div className="flex flex-col"><span className="font-medium text-xs">@@ -372,7 +385,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo()}{toastMessage && (- <div className="fixed bottom-5 right-5 z-50 bg-[#202020] text-[#e5e5e5] px-3.5 py-2 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.65)] flex items-center gap-2 text-xs">+ <div className="fixed bottom-5 right-5 z-50 bg-[#202020] border border-[#2c2c2c] text-[#e5e5e5] px-3.5 py-2 rounded-lg shadow-[0_12px_32px_rgba(0,0,0,0.65)] flex items-center gap-2 text-xs"><CheckCircle2 className="w-3.5 h-3.5 text-[var(--accent)]" /><span className="font-medium">{toastMessage}</span></div>@@ -413,6 +426,8 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(<UpdateToast /><CloseConfirmModal onSaveDocumentById={handleSaveDocumentById} />++ <ConfirmDialogModal /></>);}diff --git a/src/components/ResizeCanvasModal.tsx b/src/components/ResizeCanvasModal.tsxindex 835a817..1e2417f 100644--- a/src/components/ResizeCanvasModal.tsx+++ b/src/components/ResizeCanvasModal.tsx@@ -1,4 +1,4 @@-import React, { useState, useId, useMemo, useEffect } from 'react';+import React, { useState, useId, useMemo, useEffect, useCallback } from 'react';import {X,Lock,@@ -88,6 +88,34 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({}}, [isOpen, currentDimensions]);+ const handleApplyResize = useCallback(() => {+ onResize({+ width,+ height,+ dpi: Math.max(1, Math.round(dpi)),+ scaleContent,+ anchor,+ });+ onClose();+ }, [onResize, width, height, dpi, scaleContent, anchor, onClose]);++ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {+ e.preventDefault();+ e.stopPropagation();+ handleApplyResize();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, onClose, handleApplyResize]);+// Simplified aspect ratio stringconst simplifiedRatio = useMemo(() => {if (width <= 0 || height <= 0) return '1:1';@@ -158,83 +186,77 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({setHeight(newH);};- const handleApplyResize = () => {- onResize({- width,- height,- dpi: Math.max(1, Math.round(dpi)),- scaleContent,- anchor,- });- onClose();- };-if (!isOpen) return null;return (<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 backdrop-blur-xs p-4 select-none animate-in fade-in duration-150"- onKeyDown={(e) => {- if (e.key === 'Escape') onClose();- if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleApplyResize();- }}+ role="dialog"+ aria-modal="true"+ aria-labelledby="resize-canvas-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={onClose}>- <div className="bg-[#222224] border border-[#3e3e42] rounded-lg shadow-2xl w-full max-w-2xl flex flex-col overflow-hidden text-xs text-[#cccccc]">+ <div+ onClick={(e) => e.stopPropagation()}+ className="bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-full max-w-[600px] flex flex-col overflow-hidden text-xs text-[#e5e5e5]"+ >{/* Header */}- <div className="flex items-center justify-between px-5 py-3.5 bg-[#2a2a2d] border-b border-[#38383a]">- <div className="flex items-center space-x-2.5">- <div className="w-5 h-5 rounded-[3px] bg-[#007acc]/20 border border-[#007acc]/40 flex items-center justify-center text-[#38bdf8]">- <Maximize2 className="w-3.5 h-3.5" />- </div>- <h2 className="text-sm font-semibold text-white tracking-wide">Resize Canvas</h2>+ <div className="h-10 px-4 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between shrink-0">+ <div className="flex items-center gap-2">+ <Maximize2 className="w-3.5 h-3.5 text-[var(--accent)]" />+ <h2 id="resize-canvas-modal-title" className="text-xs font-medium text-[#e5e5e5] tracking-wide">+ Resize Canvas+ </h2></div><button+ type="button"onClick={onClose}- className="p-1 rounded hover:bg-[#38383a] text-[#888888] hover:text-white transition-colors"- title="Close (Esc)"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer">- <X className="w-4 h-4" />+ <X className="w-3.5 h-3.5" /></button></div>{/* Body */}- <div className="p-5 space-y-4 max-h-[82vh] overflow-y-auto">+ <div className="p-4 space-y-3.5 max-h-[82vh] overflow-y-auto">{/* Current Canvas Status Bar */}- <div className="bg-[#18181a] border border-[#333336] rounded-md px-3.5 py-2.5 flex items-center justify-between">- <span className="text-[#888888] text-[11px]">Current Dimensions:</span>- <div className="flex items-center space-x-2 font-mono text-xs">- <span className="text-white font-semibold">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md px-3.5 py-2 flex items-center justify-between">+ <span className="text-[#8a8a8a] text-[11px]">Current Dimensions</span>+ <div className="flex items-center gap-2 font-mono text-xs">+ <span className="text-[#e5e5e5] font-medium">{currentDimensions.width} × {currentDimensions.height} px</span>- <span className="text-[#666666]">|</span>- <span className="text-[#38bdf8]">{currentDimensions.dpi || 300} DPI</span>+ <span className="text-[#4a4a4a]">|</span>+ <span className="text-[var(--accent)]">{currentDimensions.dpi || 300} DPI</span></div></div>{/* New Dimensions & Keep Aspect Ratio */}- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md p-3.5 space-y-3"><div className="flex items-center justify-between">- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider">+ <span className="text-[10px] font-medium text-[#8a8a8a] uppercase tracking-wider">New Dimensions</span>- <div className="flex items-center space-x-1.5">+ <div className="flex items-center gap-1.5"><buttontype="button"onClick={() => setLockRatio(!lockRatio)}- className={`flex items-center space-x-1.5 px-2.5 py-1 rounded text-xs transition-colors border ${+ className={`flex items-center gap-1.5 px-2.5 py-1 rounded text-[11px] transition-colors border cursor-pointer ${lockRatio- ? 'bg-[#007acc]/20 border-[#007acc]/50 text-[#38bdf8] font-medium'- : 'bg-[#2a2a2d] border-[#38383a] text-[#888888] hover:text-[#cccccc]'+ ? 'bg-[var(--accent-subtle)] border-[var(--accent-border)] text-[var(--accent)] font-medium'+ : 'bg-[#202020] border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}title={lockRatio ? 'Keep aspect ratio: editing width updates height' : 'Aspect ratio unlocked'}>- {lockRatio ? <Lock className="w-3.5 h-3.5" /> : <Unlock className="w-3.5 h-3.5 text-[#666666]" />}+ {lockRatio ? <Lock className="w-3 h-3" /> : <Unlock className="w-3 h-3 text-[#6e6e6e]" />}<span>{lockRatio ? 'Keep Aspect Ratio' : 'Ratio Free'}</span></button><buttontype="button"onClick={handleSwapDimensions}- className="p-1 rounded bg-[#2a2a2d] hover:bg-[#38383a] border border-[#38383a] text-[#aaaaaa] hover:text-white transition-colors"+ className="p-1 rounded bg-[#202020] hover:bg-[#2c2c2c] border border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer"title="Swap Width and Height (Landscape ⇄ Portrait)"><ArrowLeftRight className="w-3.5 h-3.5" />@@ -242,13 +264,13 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({</div></div>- <div className="grid grid-cols-2 gap-3.5">+ <div className="grid grid-cols-2 gap-3"><div className="space-y-1"><div className="flex items-center justify-between">- <label htmlFor={widthInputId} className="text-[11px] text-[#888888]">+ <label htmlFor={widthInputId} className="text-[11px] text-[#8a8a8a]">Width (px)</label>- <span className="text-[10px] font-mono text-[#666666]">{percentW}%</span>+ <span className="text-[10px] font-mono text-[#6e6e6e]">{percentW}%</span></div><inputid={widthInputId}@@ -257,16 +279,16 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({max="16384"value={width}onChange={(e) => handleWidthChange(Number(e.target.value))}- className="w-full bg-[#222225] border border-[#3e3e42] rounded px-3 py-1.5 font-mono text-sm text-white focus:outline-hidden focus:border-[#007acc]"+ className="w-full bg-[#202020] border border-[#2c2c2c] rounded px-3 py-1.5 font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><div className="space-y-1"><div className="flex items-center justify-between">- <label htmlFor={heightInputId} className="text-[11px] text-[#888888]">+ <label htmlFor={heightInputId} className="text-[11px] text-[#8a8a8a]">Height (px)</label>- <span className="text-[10px] font-mono text-[#666666]">{percentH}%</span>+ <span className="text-[10px] font-mono text-[#6e6e6e]">{percentH}%</span></div><inputid={heightInputId}@@ -275,14 +297,14 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({max="16384"value={height}onChange={(e) => handleHeightChange(Number(e.target.value))}- className="w-full bg-[#222225] border border-[#3e3e42] rounded px-3 py-1.5 font-mono text-sm text-white focus:outline-hidden focus:border-[#007acc]"+ className="w-full bg-[#202020] border border-[#2c2c2c] rounded px-3 py-1.5 font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div></div>{/* Quick Ratio Presets */}- <div className="flex items-center space-x-2 pt-1">- <span className="text-[11px] text-[#888888] whitespace-nowrap">Ratio Presets:</span>+ <div className="flex items-center gap-2 pt-0.5">+ <span className="text-[11px] text-[#8a8a8a] whitespace-nowrap">Ratio Presets:</span><div className="flex flex-wrap gap-1.5">{RATIO_PRESETS.map((r) => {const isActive = Math.abs(width / height - r.x / r.y) < 0.01;@@ -291,10 +313,10 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({key={r.label}type="button"onClick={() => handleApplyRatioPreset(r.x, r.y)}- className={`px-2 py-0.5 rounded text-[11px] font-mono transition-colors border ${+ className={`px-2 py-0.5 rounded text-[11px] font-mono transition-colors border cursor-pointer ${isActive- ? 'bg-[#007acc] border-[#007acc] text-white font-medium'- : 'bg-[#252528] border-[#38383c] text-[#aaaaaa] hover:bg-[#303034] hover:text-white'+ ? 'bg-[var(--accent)] border-transparent text-[var(--accent-contrast)] font-medium'+ : 'bg-[#202020] border-[#2c2c2c] text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5]'}`}>{r.label}@@ -306,15 +328,15 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({</div>{/* Resolution (DPI) */}- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-2.5">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md p-3.5 space-y-2.5"><div className="flex items-center justify-between">- <div className="flex items-center space-x-1.5">- <Printer className="w-3.5 h-3.5 text-[#38bdf8]" />- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider">+ <div className="flex items-center gap-1.5">+ <Printer className="w-3.5 h-3.5 text-[#8a8a8a]" />+ <span className="text-[10px] font-medium text-[#8a8a8a] uppercase tracking-wider">Resolution (DPI / PPI)</span></div>- <span className="font-mono text-[11px] text-[#38bdf8]">+ <span className="font-mono text-[11px] text-[var(--accent)]">Print: {printDimensionsCm.w} × {printDimensionsCm.h} cm</span></div>@@ -327,10 +349,10 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({key={p.dpi}type="button"onClick={() => setDpi(p.dpi)}- className={`flex flex-col items-center justify-center py-1 px-1 rounded border transition-colors ${+ className={`flex flex-col items-center justify-center py-1.5 px-1 rounded border transition-colors cursor-pointer ${isSelected- ? 'bg-[#007acc] border-[#007acc] text-white font-medium'- : 'bg-[#252528] border-[#38383c] text-[#bbbbbb] hover:bg-[#303034] hover:text-white'+ ? 'bg-[var(--accent)] border-transparent text-[var(--accent-contrast)] font-medium'+ : 'bg-[#202020] border-[#2c2c2c] text-[#b5b5b5] hover:bg-[#2c2c2c] hover:text-[#e5e5e5]'}`}><span className="font-mono text-xs font-semibold">{p.dpi}</span>@@ -340,9 +362,9 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({})}</div>- <div className="pt-2 border-t border-[#2e2e32] flex items-center justify-between">- <div className="flex items-center space-x-2">- <label htmlFor={dpiInputId} className="text-[11px] text-[#888888]">+ <div className="pt-2 border-t border-[#262626] flex items-center justify-between">+ <div className="flex items-center gap-2">+ <label htmlFor={dpiInputId} className="text-[11px] text-[#8a8a8a]">Manual DPI:</label><input@@ -352,17 +374,17 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({max="4800"value={dpi}onChange={(e) => setDpi(Math.max(1, Math.min(4800, Number(e.target.value) || 1)))}- className="w-20 bg-[#222225] border border-[#3e3e42] rounded px-2.5 py-1 text-center font-mono text-xs text-white focus:outline-hidden focus:border-[#007acc]"+ className="w-20 bg-[#202020] border border-[#2c2c2c] rounded px-2.5 py-1 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div>- <span className="text-[11px] text-[#888888] font-mono">Total Pixels: {megapixels} MP</span>+ <span className="text-[11px] text-[#8a8a8a] font-mono">Total Pixels: {megapixels} MP</span></div></div>{/* Mode & Anchor Grid */}- <div className="bg-[#1a1a1c] border border-[#333336] rounded-md p-3.5 space-y-3">- <span className="text-[11px] font-semibold text-[#aaaaaa] uppercase tracking-wider block">- Resize Behavior & Anchor+ <div className="bg-[#161616] border border-[#2c2c2c] rounded-md p-3.5 space-y-3">+ <span className="text-[10px] font-medium text-[#8a8a8a] uppercase tracking-wider block">+ Resize Behavior & Anchor</span>{/* Mode Toggle */}@@ -370,14 +392,14 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({<buttontype="button"onClick={() => setScaleContent(false)}- className={`p-2.5 rounded-md border text-left transition-all ${+ className={`p-2.5 rounded-md border text-left transition-colors cursor-pointer ${!scaleContent- ? 'bg-[#007acc]/15 border-[#007acc] text-white ring-1 ring-[#007acc]'- : 'bg-[#222225] border-[#38383c] text-[#aaaaaa] hover:border-[#4a4a4e]'+ ? 'bg-[var(--accent-subtle)] border-[var(--accent-border)] text-[#e5e5e5]'+ : 'bg-[#202020] border-[#2c2c2c] text-[#8a8a8a] hover:bg-[#262626] hover:text-[#e5e5e5]'}`}>- <div className="font-semibold text-xs text-white mb-0.5">Canvas Bounds (Anchor)</div>- <p className="text-[10px] text-[#888888] leading-tight">+ <div className="font-medium text-xs text-[#e5e5e5] mb-0.5">Canvas Bounds (Anchor)</div>+ <p className="text-[10px] text-[#8a8a8a] leading-snug">Expands or crops canvas area around artwork without distorting pixels.</p></button>@@ -385,14 +407,14 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({<buttontype="button"onClick={() => setScaleContent(true)}- className={`p-2.5 rounded-md border text-left transition-all ${+ className={`p-2.5 rounded-md border text-left transition-colors cursor-pointer ${scaleContent- ? 'bg-[#007acc]/15 border-[#007acc] text-white ring-1 ring-[#007acc]'- : 'bg-[#222225] border-[#38383c] text-[#aaaaaa] hover:border-[#4a4a4e]'+ ? 'bg-[var(--accent-subtle)] border-[var(--accent-border)] text-[#e5e5e5]'+ : 'bg-[#202020] border-[#2c2c2c] text-[#8a8a8a] hover:bg-[#262626] hover:text-[#e5e5e5]'}`}>- <div className="font-semibold text-xs text-white mb-0.5">Scale Content (Resample)</div>- <p className="text-[10px] text-[#888888] leading-tight">+ <div className="font-medium text-xs text-[#e5e5e5] mb-0.5">Scale Content (Resample)</div>+ <p className="text-[10px] text-[#8a8a8a] leading-snug">Stretches and scales all layer artwork to match the new dimensions.</p></button>@@ -400,13 +422,13 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({{/* 3x3 Anchor Grid when Canvas Bounds is active */}{!scaleContent && (- <div className="pt-2 border-t border-[#2e2e32] flex items-center justify-between">+ <div className="pt-2.5 border-t border-[#262626] flex items-center justify-between"><div>- <span className="text-xs text-white font-medium block">Anchor Position</span>- <span className="text-[11px] text-[#888888]">Choose where existing artwork remains</span>+ <span className="text-xs text-[#e5e5e5] font-medium block">Anchor Position</span>+ <span className="text-[11px] text-[#8a8a8a]">Choose where existing artwork remains</span></div>- <div className="grid grid-cols-3 gap-1 bg-[#151517] p-1.5 rounded-md border border-[#333336]">+ <div className="grid grid-cols-3 gap-1 bg-[#202020] p-1.5 rounded-md border border-[#2c2c2c]">{ANCHOR_GRID.map((item) => {const isSelected = anchor === item.id;return (@@ -414,10 +436,10 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({key={item.id}type="button"onClick={() => setAnchor(item.id)}- className={`w-7 h-7 rounded flex items-center justify-center transition-colors ${+ className={`w-7 h-7 rounded flex items-center justify-center transition-colors cursor-pointer ${isSelected- ? 'bg-[#007acc] text-white shadow-xs'- : 'bg-[#252528] text-[#888888] hover:bg-[#323236] hover:text-white'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'bg-[#161616] text-[#8a8a8a] hover:bg-[#2c2c2c] hover:text-[#e5e5e5]'}`}title={item.label}>@@ -432,25 +454,25 @@ export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({</div>{/* Footer */}- <div className="flex items-center justify-between px-5 py-3 bg-[#2a2a2d] border-t border-[#38383a]">- <span className="text-[11px] text-[#777777] hidden sm:block">- Ratio: <span className="font-mono text-[#aaaaaa]">{simplifiedRatio}</span>+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between shrink-0">+ <span className="text-[11px] text-[#8a8a8a] hidden sm:block">+ Ratio: <span className="font-mono text-[#e5e5e5]">{simplifiedRatio}</span></span>- <div className="flex items-center space-x-2.5 ml-auto">+ <div className="flex items-center gap-2 ml-auto"><buttontype="button"onClick={onClose}- className="px-4 py-1.5 rounded bg-[#333336] hover:bg-[#3d3d42] text-[#cccccc] hover:text-white border border-[#444448] transition-colors"+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-xs font-medium text-[#e5e5e5] transition-colors cursor-pointer">Cancel</button><buttontype="button"onClick={handleApplyResize}- className="flex items-center space-x-1.5 px-5 py-1.5 rounded bg-[#007acc] hover:bg-[#008be5] active:bg-[#006bb3] text-white font-medium shadow-sm transition-colors"+ className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 text-xs font-medium transition-opacity cursor-pointer">- <Check className="w-4 h-4" />+ <Check className="w-3.5 h-3.5" /><span>Resize Canvas</span></button></div>diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsxindex 550d10e..8cfe775 100644--- a/src/components/RightSidebar.tsx+++ b/src/components/RightSidebar.tsx@@ -43,6 +43,7 @@ import { useToolStore, toolStoreActions } from '../stores';interface RightSidebarColorSectionProps {colorMode: CanvasColorMode;containerWidth: number;+ containerHeight?: number;fullHeight?: boolean;primaryColor?: string;secondaryColor?: string;@@ -58,6 +59,7 @@ export const RightSidebarColorSection: React.FC<RightSidebarColorSectionProps> =({colorMode,containerWidth,+ containerHeight,fullHeight = false,primaryColor: primaryProp,secondaryColor: secondaryProp,@@ -98,6 +100,7 @@ export const RightSidebarColorSection: React.FC<RightSidebarColorSectionProps> =onSelectTool={onSelectTool ?? ((t) => toolStoreActions.selectTool(t))}recentColors={recentProp ?? storeRecent}containerWidth={containerWidth}+ containerHeight={containerHeight}/></section>);diff --git a/src/components/SimpleToneModal.tsx b/src/components/SimpleToneModal.tsxindex fbad9cf..6d7a1f1 100644--- a/src/components/SimpleToneModal.tsx+++ b/src/components/SimpleToneModal.tsx@@ -111,16 +111,27 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({return (<div- className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-xs select-none"+ role="dialog"+ aria-modal="true"+ aria-labelledby="simple-tone-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"onPointerDown={(e) => e.stopPropagation()}+ onClick={onClose}>- <div className="bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl w-96 flex flex-col overflow-hidden text-[#e5e5e5]">+ <div+ onClick={(e) => e.stopPropagation()}+ className="bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-96 max-w-[95vw] flex flex-col overflow-hidden text-[#e5e5e5]"+ >{/* Header */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.06] flex items-center justify-between">- <h2 className="text-xs font-medium text-[#e5e5e5]">Simple Tone Settings</h2>+ <div className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between">+ <h2 id="simple-tone-modal-title" className="text-xs font-medium text-[#e5e5e5]">+ Simple Tone Settings+ </h2><button+ type="button"onClick={onClose}- className="text-[#8a8a8a] hover:text-[#e5e5e5] p-1 rounded hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ aria-label="Close"+ className="w-6 h-6 flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] rounded hover:bg-[#2c2c2c] transition-colors cursor-pointer"title="Cancel (Esc)"><X className="w-3.5 h-3.5" />@@ -283,11 +294,11 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({</div>{/* Footer */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-t border-white/[0.06] flex items-center justify-end space-x-2">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end gap-2"><buttontype="button"onClick={onClose}- className="px-3 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] transition-colors cursor-pointer text-xs"+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] font-medium transition-colors cursor-pointer text-xs">Cancel</button>diff --git a/src/components/SphereColorPicker.tsx b/src/components/SphereColorPicker.tsxindex f4039a0..aed67ee 100644--- a/src/components/SphereColorPicker.tsx+++ b/src/components/SphereColorPicker.tsx@@ -14,6 +14,7 @@ import {PinOff,Compass,Sparkles,+ Minus,} from 'lucide-react';import {HSV,@@ -74,6 +75,9 @@ export interface SphereColorPickerProps {onSharedStateChange?: (state: SpherePickerSharedState) => void;/** Pointer down handler on the titlebar (used by floating draggable wrapper). */onHeaderDragStart?: (e: React.PointerEvent<HTMLDivElement>) => void;+ /** Controlled collapsed/shaded state for floating titlebar-only mode. */+ isCollapsed?: boolean;+ onToggleCollapse?: () => void;/** Additional container classes. */className?: string;}@@ -279,9 +283,17 @@ export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({sharedState,onSharedStateChange,onHeaderDragStart,+ isCollapsed: isCollapsedProp,+ onToggleCollapse,className = '',}) => {const isDocked = variant === 'docked';+ const [internalCollapsed, setInternalCollapsed] = useState(false);+ const isCollapsed = !isDocked && (isCollapsedProp ?? internalCollapsed);+ const handleToggleCollapse = useCallback(() => {+ if (onToggleCollapse) onToggleCollapse();+ else setInternalCollapsed((c) => !c);+ }, [onToggleCollapse]);const [previousColor] = useState<string>(() =>isValidHex(initialColor)@@ -709,12 +721,18 @@ export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({}onPointerDown={(e) => e.stopPropagation()}>- {/* Floating Studio Palette Title Bar (matches DockWorkspace h-6 #1a1a1a chrome) */}+ {/* Floating Studio Palette Title Bar (matches DockWorkspace #1a1a1a chrome) */}{!isDocked && (<divonPointerDown={onHeaderDragStart}- title="Drag to move palette"- className="h-6 px-2 flex items-center justify-between bg-[#1a1a1a] border-b border-white/[0.06] cursor-grab active:cursor-grabbing shrink-0"+ onDoubleClick={(e) => {+ if ((e.target as HTMLElement)?.closest?.('button')) return;+ handleToggleCollapse();+ }}+ title="Drag to move palette — Double-click to collapse/expand"+ className={`h-7 px-2 flex items-center justify-between bg-[#1a1a1a] cursor-grab active:cursor-grabbing shrink-0 ${+ isCollapsed ? '' : 'border-b border-white/[0.06]'+ }`}><div className="flex items-center gap-1.5 min-w-0"><span@@ -745,6 +763,21 @@ export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({{isPinned ? <PinOff className="w-3 h-3" /> : <Pin className="w-3 h-3" />}</button>)}+ <button+ type="button"+ onClick={handleToggleCollapse}+ data-testid="sphere-collapse-toggle"+ title={isCollapsed ? 'Expand Panel' : 'Hide / Collapse Panel'}+ aria-label={isCollapsed ? 'Expand Color Sphere' : 'Hide Color Sphere'}+ aria-expanded={!isCollapsed}+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${+ isCollapsed+ ? 'text-[var(--accent)] bg-[#2c2c2c]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Minus className="w-3 h-3" />+ </button>{onClose && (<buttontype="button"@@ -760,6 +793,7 @@ export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({</div>)}+ <div className={isCollapsed ? 'hidden' : 'flex flex-col flex-1 min-h-0'}>{/* Top Controls Bar: Gear + Light Orbit | Split Preview Bar | Eyedropper (+ Unpin when docked) */}<divclassName={`${compact ? 'px-2 pt-1.5 pb-1 gap-1.5' : 'px-2.5 pt-2 pb-1.5 gap-2'} flex items-center justify-between border-b border-white/[0.06] shrink-0`}@@ -1364,6 +1398,7 @@ export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({)}</button></div>+ </div></div>);};@@ -1423,6 +1458,7 @@ export const SphereColorPickerModal: React.FC<SphereColorPickerModalProps> = ({}) => {const [panelWidth, setPanelWidth] = useState<number>(() => loadSavedFloatWidth());const [pos, setPos] = useState<{ x: number; y: number }>(() => loadSavedFloatPos(panelWidth));+ const [isCollapsed, setIsCollapsed] = useState(false);const dragOriginRef = useRef<{ startX: number; startY: number; origX: number; origY: number } | null>(null);@@ -1569,20 +1605,24 @@ export const SphereColorPickerModal: React.FC<SphereColorPickerModalProps> = ({{...pickerProps}variant="floating"isPinned={false}+ isCollapsed={isCollapsed}+ onToggleCollapse={() => setIsCollapsed((c) => !c)}sphereSize={computedSphereSize}onClose={onClose}onHeaderDragStart={handleHeaderDragStart}className="w-full"/>- <div- onPointerDown={handleResizeStart}- title="Drag to resize"- className="absolute bottom-0.5 right-0.5 w-3 h-3 cursor-nwse-resize opacity-35 hover:opacity-80 transition-opacity"- style={{- background:- 'linear-gradient(135deg, transparent 45%, #8a8a8a 45%, #8a8a8a 58%, transparent 58%, transparent 72%, #8a8a8a 72%, #8a8a8a 85%, transparent 85%)',- }}- />+ {!isCollapsed && (+ <div+ onPointerDown={handleResizeStart}+ title="Drag to resize"+ className="absolute bottom-0.5 right-0.5 w-3 h-3 cursor-nwse-resize opacity-35 hover:opacity-80 transition-opacity"+ style={{+ background:+ 'linear-gradient(135deg, transparent 45%, #8a8a8a 45%, #8a8a8a 58%, transparent 58%, transparent 72%, #8a8a8a 72%, #8a8a8a 85%, transparent 85%)',+ }}+ />+ )}</div></div>);diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsxindex 227825d..790f70f 100644--- a/src/components/SubToolList.tsx+++ b/src/components/SubToolList.tsx@@ -105,7 +105,10 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(} catch (err: unknown) {const msg =err instanceof Error ? err.message : 'Failed to import brush file.';- alert(msg);+ void uiStoreActions.alertDialog({+ title: 'Brush Import Failed',+ message: msg,+ });} finally {setIsImportingSut(false);}@@ -119,16 +122,35 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(await exportBrushToInkbFile(brush);} catch (err: unknown) {const msg = err instanceof Error ? err.message : 'Failed to export brush.';- alert(msg);+ void uiStoreActions.alertDialog({+ title: 'Brush Export Failed',+ message: msg,+ });}};- const handleDeleteCustomBrush = async (e: React.MouseEvent, brushId: string) => {+ const handleDeleteCustomBrush = async (e: React.MouseEvent, brush: CspBrush) => {e.stopPropagation();- if (window.confirm('Delete this imported brush?')) {- await deleteCustomBrush(brushId);- setCustomBrushes((prev) => prev.filter((b) => b.id !== brushId));- if (activePreset === brushId) {+ const subtitle = brush.badge+ ? `${brush.badge} brush`+ : 'Imported custom brush';+ const confirmed = await uiStoreActions.confirmDialog({+ variant: 'danger',+ title: 'Delete Brush',+ message: 'Are you sure you want to delete this brush?',+ detail: 'This permanently removes the brush from your library and cannot be undone.',+ confirmLabel: 'Delete',+ cancelLabel: 'Cancel',+ preview: {+ imageUrl: brush.tipDataUrl,+ title: brush.name,+ subtitle,+ },+ });+ if (confirmed) {+ await deleteCustomBrush(brush.id);+ setCustomBrushes((prev) => prev.filter((b) => b.id !== brush.id));+ if (activePreset === brush.id) {handleSelectBrushPreset(DEFAULT_BRUSH_PRESET_ID);}}@@ -376,7 +398,7 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(</button><buttontype="button"- onClick={(e) => handleDeleteCustomBrush(e, brush.id)}+ onClick={(e) => void handleDeleteCustomBrush(e, brush)}title="Delete brush"className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer">diff --git a/src/components/TextEditorOverlay.tsx b/src/components/TextEditorOverlay.tsxindex dbb9e17..5019818 100644--- a/src/components/TextEditorOverlay.tsx+++ b/src/components/TextEditorOverlay.tsx@@ -128,7 +128,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({{/* Floating Tool Panel */}<div- className="w-80 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl overflow-hidden flex flex-col"+ className="w-80 bg-[#202020]/95 backdrop-blur-md border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] overflow-hidden flex flex-col"style={{transform: `scale(${(flipX ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)}, ${(flipY ? -1 : 1) * (zoom > 0 ? 1 / zoom : 1)})`,transformOrigin: 'top left',@@ -139,12 +139,13 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({onPointerDown={handleDragDown}onPointerMove={handleDragMove}onPointerUp={handleDragUp}- className="bg-[#1a1a1a] px-3 py-1.5 border-b border-white/[0.06] flex items-center justify-between cursor-move text-xs text-[#8a8a8a]"+ className="bg-[#161616] px-3 py-1.5 border-b border-[#2c2c2c] flex items-center justify-between cursor-move text-xs text-[#8a8a8a]"><span className="font-medium text-[#e5e5e5]">Text Tool</span><div className="flex items-center space-x-1"><button+ type="button"onClick={() => setActiveTab('text')}className={`px-2 py-0.5 rounded text-[11px] font-medium transition-colors cursor-pointer ${activeTab === 'text' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'@@ -153,6 +154,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({Content</button><button+ type="button"onClick={() => setActiveTab('style')}className={`px-2 py-0.5 rounded text-[11px] font-medium transition-colors cursor-pointer ${activeTab === 'style' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'@@ -172,7 +174,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}placeholder="Enter text (multiline supported)..."rows={3}- className="w-full bg-[#141517] text-white text-xs border border-[#383a40] rounded p-2 focus:border-cyan-500 focus:outline-none resize-none font-mono"+ className="w-full bg-[#161616] text-[#e5e5e5] text-xs border border-[#2c2c2c] rounded p-2 focus:border-[var(--accent-border)] focus:outline-none resize-none font-mono"onKeyDown={(e) => {if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {e.preventDefault();@@ -185,11 +187,11 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({/><div className="flex items-center space-x-2">- <label className="text-[11px] text-[#999999] w-16 shrink-0">Font:</label>+ <label className="text-[11px] text-[#8a8a8a] w-16 shrink-0">Font:</label><selectvalue={settings.fontFamily}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontFamily: e.target.value }))}- className="flex-1 bg-[#141517] text-white text-xs border border-[#383a40] rounded px-2 py-1 focus:border-cyan-500 focus:outline-none"+ className="flex-1 bg-[#161616] text-[#e5e5e5] text-xs border border-[#2c2c2c] rounded px-2 py-1 focus:border-[var(--accent-border)] focus:outline-none">{MANGA_FONTS.map((f) => (<option key={f.id} value={f.id}>@@ -200,19 +202,19 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({</div><div className="flex items-center space-x-2">- <label className="text-[11px] text-[#999999] w-16 shrink-0">Size: {settings.fontSize}px</label>+ <label className="text-[11px] text-[#8a8a8a] w-16 shrink-0">Size: {settings.fontSize}px</label><inputtype="range"min={10}max={160}value={settings.fontSize}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontSize: Number(e.target.value) }))}- className="flex-1 accent-cyan-400"+ className="flex-1"/></div><div className="flex items-center space-x-2">- <label className="text-[11px] text-[#999999] w-16 shrink-0">+ <label className="text-[11px] text-[#8a8a8a] w-16 shrink-0">Line: {(settings.lineSpacing ?? 1.25).toFixed(2)}</label><input@@ -222,17 +224,17 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({step={0.05}value={settings.lineSpacing ?? 1.25}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, lineSpacing: Number(e.target.value) }))}- className="flex-1 accent-cyan-400"+ className="flex-1"/></div><div className="flex items-center justify-between">- <span className="text-[11px] text-[#999999]">Text Color:</span>+ <span className="text-[11px] text-[#8a8a8a]">Text Color:</span><inputtype="color"value={settings.color || '#000000'}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, color: e.target.value }))}- className="w-6 h-5 bg-transparent cursor-pointer border border-[#383a40] rounded"+ className="w-6 h-5 bg-transparent cursor-pointer border border-[#2c2c2c] rounded"/></div></div>@@ -245,6 +247,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({<div className="flex items-center justify-between"><div className="flex items-center space-x-1"><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }))}title="Bold"className={`p-1.5 rounded transition-colors cursor-pointer ${@@ -256,6 +259,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({<Bold className="w-3.5 h-3.5" /></button><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }))}title="Italic"className={`p-1.5 rounded transition-colors cursor-pointer ${@@ -269,8 +273,9 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({</div>{/* Writing Direction (Horizontal vs Vertical Manga Tate-gaki) */}- <div className="flex items-center space-x-1 bg-[#161616] p-0.5 rounded border border-white/[0.06]">+ <div className="flex items-center space-x-1 bg-[#161616] p-0.5 rounded border border-[#2c2c2c]"><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'horizontal-tb' }))}title="Horizontal Layout (Left-to-Right)"className={`px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors cursor-pointer ${@@ -282,6 +287,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({Horiz</button><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'vertical-rl' }))}title="Vertical Layout (Manga Tate-gaki: Right-to-Left columns)"className={`px-1.5 py-0.5 rounded text-[10px] font-medium transition-colors cursor-pointer ${@@ -295,8 +301,9 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({</div>{/* Alignments */}- <div className="flex items-center space-x-1 bg-[#161616] p-0.5 rounded border border-white/[0.06]">+ <div className="flex items-center space-x-1 bg-[#161616] p-0.5 rounded border border-[#2c2c2c]"><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'left' }))}title="Align Left"className={`p-1 rounded cursor-pointer ${settings.align === 'left' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}@@ -304,6 +311,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({<AlignLeft className="w-3 h-3" /></button><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'center' }))}title="Align Center"className={`p-1 rounded cursor-pointer ${settings.align === 'center' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}@@ -311,6 +319,7 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({<AlignCenter className="w-3 h-3" /></button><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, align: 'right' }))}title="Align Right"className={`p-1 rounded cursor-pointer ${settings.align === 'right' ? 'bg-[#2c2c2c] text-[#e5e5e5]' : 'text-[#8a8a8a] hover:text-[#e5e5e5]'}`}@@ -321,41 +330,43 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({</div>{/* Manga Outline Option */}- <div className="space-y-1.5 border-t border-[#2b2d31] pt-2">+ <div className="space-y-1.5 border-t border-[#2c2c2c] pt-2"><div className="flex items-center justify-between">- <span className="text-[11px] text-[#cccccc] font-medium">Manga Speech Bubble Outline</span>+ <span className="text-[11px] text-[#e5e5e5] font-medium">Manga Speech Bubble Outline</span><inputtype="checkbox"checked={settings.outline}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, outline: e.target.checked }))}- className="rounded accent-cyan-400 cursor-pointer"+ className="cursor-pointer"/></div>{settings.outline && (<div className="space-y-2 pt-1"><div className="flex items-center justify-between text-xs">- <span className="text-[11px] text-[#999999]">Outline Width: {settings.outlineWidth}px</span>+ <span className="text-[11px] text-[#8a8a8a]">Outline Width: {settings.outlineWidth}px</span><inputtype="range"min={1}max={12}value={settings.outlineWidth}onChange={(e) => onUpdateSettings((prev) => ({ ...prev, outlineWidth: Number(e.target.value) }))}- className="w-32 accent-cyan-400"+ className="w-32"/></div><div className="flex items-center space-x-2">- <span className="text-[11px] text-[#999999]">Outline Color:</span>+ <span className="text-[11px] text-[#8a8a8a]">Outline Color:</span><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, outlineColor: '#ffffff' }))}- className={`w-5 h-5 rounded border ${settings.outlineColor === '#ffffff' ? 'border-cyan-400 ring-1 ring-cyan-400' : 'border-[#555555]'}`}+ className={`w-5 h-5 rounded border cursor-pointer ${settings.outlineColor === '#ffffff' ? 'border-[var(--accent)] ring-1 ring-[var(--accent-border)]' : 'border-[#3a3a3a]'}`}style={{ backgroundColor: '#ffffff' }}title="White outline"/><button+ type="button"onClick={() => onUpdateSettings((prev) => ({ ...prev, outlineColor: '#000000' }))}- className={`w-5 h-5 rounded border ${settings.outlineColor === '#000000' ? 'border-cyan-400 ring-1 ring-cyan-400' : 'border-[#555555]'}`}+ className={`w-5 h-5 rounded border cursor-pointer ${settings.outlineColor === '#000000' ? 'border-[var(--accent)] ring-1 ring-[var(--accent-border)]' : 'border-[#3a3a3a]'}`}style={{ backgroundColor: '#000000' }}title="Black outline"/>@@ -367,16 +378,18 @@ export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({)}{/* Footer Confirm / Cancel */}- <div className="px-3 py-2 bg-[#1a1a1a] border-t border-white/[0.06] flex items-center justify-between">+ <div className="px-3 py-2 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between"><span className="text-[10px] text-[#8a8a8a]">Ctrl+Enter to Apply</span>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><button+ type="button"onClick={onCancel}- className="px-2.5 py-1 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-xs transition-colors cursor-pointer"+ className="px-2.5 py-1 bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] rounded text-xs font-medium transition-colors cursor-pointer">Cancel</button><button+ type="button"onClick={onConfirm}className="px-3 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer">diff --git a/src/components/TimelapseExportModal.tsx b/src/components/TimelapseExportModal.tsxindex 8ecdde1..0f77e53 100644--- a/src/components/TimelapseExportModal.tsx+++ b/src/components/TimelapseExportModal.tsx@@ -115,6 +115,20 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({return () => window.clearInterval(timer);}, [isPlayingPreview, stats.frameCount]);+ // Escape key closes modal when not exporting+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && !isExporting) {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, isExporting, onClose]);+if (!isOpen) return null;const handleToggleRecording = () => {@@ -173,32 +187,45 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({const memMb = (stats.memoryBytes / (1024 * 1024)).toFixed(2);return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 select-none">- <div className="w-[540px] max-w-[95vw] bg-[#202020] border border-white/10 rounded-lg shadow-2xl overflow-hidden text-xs text-[#e5e5e5]">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="timelapse-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={() => {+ if (!isExporting) onClose();+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-[540px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] overflow-hidden text-xs text-[#e5e5e5]"+ >{/* Header */}- <div className="px-4 py-3 bg-[#181818] border-b border-white/10 flex items-center justify-between">- <div className="flex items-center gap-2 font-semibold">- <Film className="w-4 h-4 text-[var(--accent)]" />- <span>Time-lapse Recording & Export</span>+ <div className="h-10 px-4 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between">+ <div className="flex items-center gap-2 font-medium">+ <Film className="w-3.5 h-3.5 text-[var(--accent)]" />+ <span id="timelapse-modal-title">Time-lapse Recording & Export</span></div><buttontype="button"onClick={onClose}disabled={isExporting}- className="text-[#8a8a8a] hover:text-white cursor-pointer disabled:opacity-40"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer disabled:opacity-40">- <X className="w-4 h-4" />+ <X className="w-3.5 h-3.5" /></button></div><div className="p-4 space-y-4">{/* Status & Record Toggle */}- <div className="flex items-center justify-between bg-[#161616] rounded-md px-3 py-2.5 border border-white/[0.06]">+ <div className="flex items-center justify-between bg-[#161616] rounded-md px-3 py-2.5 border border-[#2c2c2c]"><div className="space-y-0.5"><div className="flex items-center gap-2 font-medium"><spanclassName={`w-2 h-2 rounded-full ${- stats.enabled ? 'bg-rose-500 animate-pulse' : 'bg-[#555555]'+ stats.enabled ? 'bg-red-500 animate-pulse' : 'bg-[#555555]'}`}/><span>{stats.enabled ? 'Recording Keyframes' : 'Recording Paused'}</span>@@ -214,10 +241,10 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({type="button"disabled={!documentId || isExporting}onClick={handleToggleRecording}- className={`px-2.5 py-1.5 rounded text-[11px] font-medium flex items-center gap-1.5 cursor-pointer disabled:opacity-40 ${+ className={`px-2.5 py-1.5 rounded text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 ${stats.enabled- ? 'bg-rose-600 hover:bg-rose-500 text-white'- : 'bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5]'+ ? 'bg-red-500/90 hover:bg-red-500 text-white'+ : 'bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5]'}`}>{stats.enabled ? (@@ -227,7 +254,7 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({</>) : (<>- <Circle className="w-3 h-3 text-rose-500 fill-rose-500" />+ <Circle className="w-3 h-3 text-red-400 fill-red-400" /><span>Record</span></>)}@@ -238,7 +265,7 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({disabled={!documentId || stats.frameCount === 0 || isExporting}onClick={handleClear}title="Clear recorded keyframes"- className="p-1.5 rounded bg-[#2c2c2c] hover:bg-rose-500/20 text-[#8a8a8a] hover:text-rose-400 cursor-pointer disabled:opacity-35"+ className="p-1.5 rounded bg-[#2a2a2a] hover:bg-red-500/20 text-[#8a8a8a] hover:text-red-400 transition-colors cursor-pointer disabled:opacity-35"><Trash2 className="w-3.5 h-3.5" /></button>@@ -246,8 +273,8 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({</div>{/* Preview Player */}- <div className="bg-[#121212] rounded-md border border-white/[0.06] p-2 space-y-2">- <div className="h-44 flex items-center justify-center overflow-hidden rounded bg-[#0c0c0c]">+ <div className="bg-[#161616] rounded-md border border-[#2c2c2c] p-2 space-y-2">+ <div className="h-44 flex items-center justify-center overflow-hidden rounded bg-[#121212]">{previewUrl ? (<imgsrc={previewUrl}@@ -410,12 +437,12 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({</div>{/* Footer */}- <div className="px-4 py-3 bg-[#181818] border-t border-white/10 flex items-center justify-end gap-2">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end gap-2"><buttontype="button"onClick={onClose}disabled={isExporting}- className="px-3 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[#cccccc] cursor-pointer disabled:opacity-40"+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] font-medium transition-colors cursor-pointer disabled:opacity-40">Close</button>@@ -423,7 +450,7 @@ export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({type="button"disabled={!documentId || stats.frameCount === 0 || isExporting}onClick={handleExport}- className="px-3.5 py-1.5 rounded bg-[#234b3e] hover:bg-[#2b604f] text-[#55eaab] border border-[#2e6e58] font-semibold flex items-center gap-1.5 cursor-pointer disabled:opacity-40"+ className="px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium flex items-center gap-1.5 transition-opacity cursor-pointer disabled:opacity-40">{isExporting ? (<>diff --git a/src/components/TonalCorrectionModal.tsx b/src/components/TonalCorrectionModal.tsxindex b349c1a..e063d97 100644--- a/src/components/TonalCorrectionModal.tsx+++ b/src/components/TonalCorrectionModal.tsx@@ -153,11 +153,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({maxCount = Math.max(maxCount, Math.min(counts[0], counts[255]));// Background gradient / subtle guide grid- ctx.fillStyle = '#18181a';+ ctx.fillStyle = '#161616';ctx.fillRect(0, 0, w, h);// Guide lines- ctx.strokeStyle = '#2b2b2e';+ ctx.strokeStyle = '#2c2c2c';ctx.lineWidth = 1;ctx.beginPath();ctx.moveTo(w * 0.25, 0);@@ -169,7 +169,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({ctx.stroke();// Bars- let barColor = '#5ce1e6';+ let barColor = '#b5b5b5';if (levels.channel === 'r') barColor = '#ff6b6b';if (levels.channel === 'g') barColor = '#51cf66';if (levels.channel === 'b') barColor = '#339af0';@@ -314,13 +314,18 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({};return (- <div className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="tonal-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"+ >{/* Semi-transparent backdrop that lets canvas stay visible */}- <div className="fixed inset-0 bg-black/40 pointer-events-auto" onClick={onClose} />+ <div className="fixed inset-0 bg-black/50 pointer-events-auto" onClick={onClose} />{/* Floating Dialog */}<div- className="relative pointer-events-auto w-[360px] bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl flex flex-col text-xs text-[#e5e5e5] select-none"+ className="relative pointer-events-auto w-[360px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] flex flex-col text-xs text-[#e5e5e5] select-none overflow-hidden"style={{transform: `translate(${pos.x}px, ${pos.y}px)`,}}@@ -330,13 +335,17 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onPointerDown={handleDragPointerDown}onPointerMove={handleDragPointerMove}onPointerUp={handleDragPointerUp}- className="h-9 px-3.5 bg-[#1a1a1a] border-b border-white/[0.06] flex items-center justify-between cursor-move rounded-t-lg"+ className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between cursor-move">- <span className="font-medium text-[#e5e5e5]">{getTitle()}</span>+ <span id="tonal-modal-title" className="font-medium text-[#e5e5e5]">+ {getTitle()}+ </span><buttontype="button"onClick={onClose}- className="p-1 rounded hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer"><X className="w-3.5 h-3.5" /></button>@@ -349,7 +358,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({<div className="space-y-4"><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Brightness:</span>+ <span className="text-[11px] text-[#8a8a8a]">Brightness</span><inputtype="number"min={-100}@@ -361,7 +370,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({brightness: Math.max(-100, Math.min(100, Number(e.target.value) || 0)),}))}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -372,13 +381,13 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setBc((prev) => ({ ...prev, brightness: Number(e.target.value) }))}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/></div><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Contrast:</span>+ <span className="text-[11px] text-[#8a8a8a]">Contrast</span><inputtype="number"min={-100}@@ -390,7 +399,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({contrast: Math.max(-100, Math.min(100, Number(e.target.value) || 0)),}))}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -401,7 +410,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setBc((prev) => ({ ...prev, contrast: Number(e.target.value) }))}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/></div></div>@@ -412,7 +421,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({<div className="space-y-4"><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Threshold:</span>+ <span className="text-[11px] text-[#8a8a8a]">Threshold</span><inputtype="number"min={1}@@ -423,7 +432,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({threshold: Math.max(1, Math.min(255, Number(e.target.value) || 1)),})}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -432,9 +441,9 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({max={255}value={bin.threshold}onChange={(e) => setBin({ threshold: Number(e.target.value) })}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/>- <div className="flex justify-between text-[10px] text-[#777777] mt-1">+ <div className="flex justify-between text-[10px] text-[#8a8a8a] mt-1"><span>Black (1)</span><span>Mid (128)</span><span>White (255)</span>@@ -448,7 +457,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({<div className="space-y-4"><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Hue:</span>+ <span className="text-[11px] text-[#8a8a8a]">Hue</span><inputtype="number"min={-180}@@ -460,7 +469,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({hue: Math.max(-180, Math.min(180, Number(e.target.value) || 0)),}))}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -471,13 +480,13 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setHs((prev) => ({ ...prev, hue: Number(e.target.value) }))}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/></div><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Saturation:</span>+ <span className="text-[11px] text-[#8a8a8a]">Saturation</span><inputtype="number"min={-100}@@ -489,7 +498,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({saturation: Math.max(-100, Math.min(100, Number(e.target.value) || 0)),}))}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -500,13 +509,13 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setHs((prev) => ({ ...prev, saturation: Number(e.target.value) }))}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/></div><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Luminosity:</span>+ <span className="text-[11px] text-[#8a8a8a]">Luminosity</span><inputtype="number"min={-100}@@ -518,7 +527,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({luminosity: Math.max(-100, Math.min(100, Number(e.target.value) || 0)),}))}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -529,7 +538,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setHs((prev) => ({ ...prev, luminosity: Number(e.target.value) }))}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/></div></div>@@ -540,7 +549,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({<div className="space-y-4"><div><div className="flex items-center justify-between mb-1">- <span className="text-[#a0a0a0]">Gradation Levels:</span>+ <span className="text-[11px] text-[#8a8a8a]">Gradation Levels</span><inputtype="number"min={2}@@ -551,7 +560,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({levels: Math.max(2, Math.min(32, Number(e.target.value) || 2)),})}- className="w-14 bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-right font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-14 bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-right font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><input@@ -560,9 +569,9 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({max={32}value={post.levels}onChange={(e) => setPost({ levels: Number(e.target.value) })}- className="w-full h-1.5 bg-[#1e1e1e] rounded-lg appearance-none cursor-pointer accent-[#5ce1e6]"+ className="w-full"/>- <div className="flex justify-between text-[10px] text-[#777777] mt-1">+ <div className="flex justify-between text-[10px] text-[#8a8a8a] mt-1"><span>2 (High Contrast)</span><span>16</span><span>32 (Smooth)</span>@@ -576,17 +585,17 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({<div className="space-y-3.5">{/* Channel Selector */}<div className="flex items-center justify-between">- <span className="text-[#a0a0a0]">Channel:</span>- <div className="flex space-x-1">+ <span className="text-[11px] text-[#8a8a8a]">Channel</span>+ <div className="flex gap-1">{(['rgb', 'r', 'g', 'b'] as const).map((ch) => (<buttonkey={ch}type="button"onClick={() => setLevels((prev) => ({ ...prev, channel: ch }))}- className={`px-2 py-0.5 rounded text-[11px] font-medium transition-colors ${+ className={`px-2 py-0.5 rounded text-[11px] font-medium transition-colors cursor-pointer ${levels.channel === ch- ? 'bg-[#007acc] text-white shadow-sm'- : 'bg-[#1e1e1e] border border-[#3e3e3e] text-[#888888] hover:text-[#cccccc]'+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'bg-[#161616] border border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5]'}`}>{ch.toUpperCase()}@@ -596,7 +605,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({</div>{/* Histogram Display Canvas */}- <div className="border border-[#3e3e3e] rounded overflow-hidden">+ <div className="border border-[#2c2c2c] rounded overflow-hidden"><canvasref={histogramCanvasRef}width={256}@@ -607,8 +616,8 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({{/* Input Levels */}<div>- <div className="flex items-center justify-between text-[11px] text-[#a0a0a0] mb-1">- <span>Input Levels (Shadow / Gamma / Highlight):</span>+ <div className="flex items-center justify-between text-[11px] text-[#8a8a8a] mb-1">+ <span>Input Levels (Shadow / Gamma / Highlight)</span><buttontype="button"onClick={handleAutoLevels}@@ -619,7 +628,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({</div><div className="grid grid-cols-3 gap-2"><div>- <label className="text-[10px] text-[#777777] block mb-0.5">Shadow</label>+ <label className="text-[10px] text-[#8a8a8a] block mb-0.5">Shadow</label><inputtype="number"min={0}@@ -634,11 +643,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({),}))}- className="w-full bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-center font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-full bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><div>- <label className="text-[10px] text-[#777777] block mb-0.5">Gamma</label>+ <label className="text-[10px] text-[#8a8a8a] block mb-0.5">Gamma</label><inputtype="number"step={0.05}@@ -651,11 +660,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({gamma: Math.max(0.1, Math.min(9.99, Number(e.target.value) || 1.0)),}))}- className="w-full bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-center font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-full bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><div>- <label className="text-[10px] text-[#777777] block mb-0.5">Highlight</label>+ <label className="text-[10px] text-[#8a8a8a] block mb-0.5">Highlight</label><inputtype="number"min={Math.min(255, levels.inputMin + 2)}@@ -670,7 +679,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({),}))}- className="w-full bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-center font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-full bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div></div>@@ -678,7 +687,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({{/* Range Slider for Shadows & Highlights */}<div className="mt-2 space-y-1.5"><div className="flex items-center space-x-2">- <span className="text-[10px] text-[#777777] w-12">Shadow:</span>+ <span className="text-[10px] text-[#8a8a8a] w-12">Shadow</span><inputtype="range"min={0}@@ -687,11 +696,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setLevels((prev) => ({ ...prev, inputMin: Number(e.target.value) }))}- className="flex-1 h-1.5 bg-[#1e1e1e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"+ className="flex-1"/></div><div className="flex items-center space-x-2">- <span className="text-[10px] text-[#777777] w-12">Highlight:</span>+ <span className="text-[10px] text-[#8a8a8a] w-12">Highlight</span><inputtype="range"min={Math.min(255, levels.inputMin + 2)}@@ -700,20 +709,20 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({onChange={(e) =>setLevels((prev) => ({ ...prev, inputMax: Number(e.target.value) }))}- className="flex-1 h-1.5 bg-[#1e1e1e] rounded appearance-none cursor-pointer accent-[#5ce1e6]"+ className="flex-1"/></div></div></div>{/* Output Levels */}- <div className="pt-2 border-t border-[#333333]">- <div className="flex items-center justify-between text-[11px] text-[#a0a0a0] mb-1">- <span>Output Levels:</span>+ <div className="pt-2 border-t border-[#2c2c2c]">+ <div className="flex items-center justify-between text-[11px] text-[#8a8a8a] mb-1">+ <span>Output Levels</span></div><div className="grid grid-cols-2 gap-2"><div>- <label className="text-[10px] text-[#777777] block mb-0.5">Min (Black)</label>+ <label className="text-[10px] text-[#8a8a8a] block mb-0.5">Min (Black)</label><inputtype="number"min={0}@@ -725,11 +734,11 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({outputMin: Math.max(0, Math.min(prev.outputMax, Number(e.target.value) || 0)),}))}- className="w-full bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-center font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-full bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div><div>- <label className="text-[10px] text-[#777777] block mb-0.5">Max (White)</label>+ <label className="text-[10px] text-[#8a8a8a] block mb-0.5">Max (White)</label><inputtype="number"min={levels.outputMin}@@ -741,7 +750,7 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({outputMax: Math.max(prev.outputMin, Math.min(255, Number(e.target.value) || 255)),}))}- className="w-full bg-[#1e1e1e] border border-[#3e3e3e] rounded px-1.5 py-0.5 text-center font-mono text-xs text-white focus:outline-none focus:border-[#007acc]"+ className="w-full bg-[#161616] border border-[#2c2c2c] rounded px-1.5 py-0.5 text-center font-mono text-xs text-[#e5e5e5] focus:border-[var(--accent-border)]"/></div></div>@@ -751,9 +760,9 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({</div>{/* Modal Footer Controls */}- <div className="px-3.5 py-2.5 bg-[#1a1a1a] border-t border-white/[0.06] flex items-center justify-between rounded-b-lg">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between"><div className="flex items-center space-x-3">- <label className="flex items-center space-x-1.5 cursor-pointer text-[#cccccc] hover:text-[#e5e5e5]">+ <label className="flex items-center space-x-1.5 cursor-pointer text-[#b5b5b5] hover:text-[#e5e5e5]"><inputtype="checkbox"checked={preview}@@ -771,18 +780,18 @@ export const TonalCorrectionModal: React.FC<TonalCorrectionModalProps> = ({</button></div>- <div className="flex items-center space-x-2">+ <div className="flex items-center gap-2"><buttontype="button"onClick={onClose}- className="px-3 py-1 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-xs transition-colors cursor-pointer"+ className="px-3.5 py-1.5 bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] rounded text-xs font-medium transition-colors cursor-pointer">Cancel</button><buttontype="button"onClick={() => onApply(type, currentParams)}- className="px-3.5 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer"+ className="px-4 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer">OK</button>diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsxindex 06d047f..16095f2 100644--- a/src/components/TransformOverlay.tsx+++ b/src/components/TransformOverlay.tsx@@ -476,7 +476,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({className="w-full h-full pointer-events-none block"style={{transform: `scale(${session.flipH ? -1 : 1}, ${session.flipV ? -1 : 1})`,- imageRendering: zoom > 1 ? 'pixelated' : 'auto',+ imageRendering: zoom >= 2 ? 'pixelated' : 'auto',}}/>@@ -558,7 +558,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({<canvasref={previewCanvasRef}className="w-full h-full block"- style={{ imageRendering: zoom > 1 ? 'pixelated' : 'auto' }}+ style={{ imageRendering: zoom >= 2 ? 'pixelated' : 'auto' }}/></div>diff --git a/src/components/WebtoonExportModal.tsx b/src/components/WebtoonExportModal.tsxindex 5b78cc2..2913a34 100644--- a/src/components/WebtoonExportModal.tsx+++ b/src/components/WebtoonExportModal.tsx@@ -1,5 +1,6 @@-import React, { useState } from 'react';+import React, { useEffect, useState } from 'react';import { X, Loader2 } from 'lucide-react';+import { uiStoreActions } from '../stores';import {exportWebtoonChapterZip,exportWebtoonChapterZipFromRenderer,@@ -32,6 +33,19 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({const [isExporting, setIsExporting] = useState(false);const [progress, setProgress] = useState<{ current: number; total: number; percent: number } | null>(null);+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && !isExporting) {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, isExporting, onClose]);+if (!isOpen) return null;const totalSlices = Math.max(1, Math.ceil(canvasHeight / sliceHeight));@@ -87,20 +101,40 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({console.error('Webtoon export error:', err);setIsExporting(false);setProgress(null);- alert('Failed to export webtoon slices.');+ void uiStoreActions.alertDialog({+ title: 'Webtoon Export Failed',+ message: 'Failed to export webtoon slices.',+ detail: err instanceof Error ? err.message : undefined,+ });}};return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/65 backdrop-blur-xs select-none">- <div className="w-[460px] bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl overflow-hidden flex flex-col text-[#e5e5e5] font-sans">+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="webtoon-export-modal-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4 select-none"+ onClick={() => {+ if (!isExporting) onClose();+ }}+ >+ <div+ onClick={(e) => e.stopPropagation()}+ className="w-[460px] max-w-[95vw] bg-[#202020] border border-[#2c2c2c] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] overflow-hidden flex flex-col text-[#e5e5e5] font-sans"+ >{/* Header */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.06] flex items-center justify-between">- <h2 className="text-xs font-medium text-[#e5e5e5]">Webtoon Chapter Slicer</h2>+ <div className="h-9 px-3.5 bg-[#161616] border-b border-[#2c2c2c] flex items-center justify-between">+ <h2 id="webtoon-export-modal-title" className="text-xs font-medium text-[#e5e5e5]">+ Webtoon Chapter Slicer+ </h2>{!isExporting && (<button+ type="button"onClick={onClose}- className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ aria-label="Close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"><X className="w-3.5 h-3.5" /></button>@@ -109,7 +143,7 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({{/* Content */}<div className="p-4 space-y-4 text-xs">- <div className="bg-[#161616] p-3 rounded border border-white/[0.06] space-y-1">+ <div className="bg-[#161616] p-3 rounded-md border border-[#2c2c2c] space-y-1"><div className="flex justify-between"><span className="text-[#8a8a8a]">Canvas Dimensions</span><span className="font-mono text-[#e5e5e5]">{canvasWidth} × {canvasHeight} px</span>@@ -129,15 +163,16 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({<label className="text-[11px] text-[#8a8a8a]">Slice Tile Height</label><span className="font-mono text-[#e5e5e5]">{sliceHeight}px</span></div>- <div className="flex space-x-1.5">+ <div className="flex gap-1.5">{[800, 1024, 1280, 1920].map((h) => (<buttonkey={h}+ type="button"onClick={() => setSliceHeight(h)}className={`flex-1 py-1 rounded text-xs border cursor-pointer transition-colors ${sliceHeight === h? 'bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-border)] font-medium'- : 'bg-[#161616] border-white/[0.06] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ : 'bg-[#161616] border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>{h}px@@ -150,21 +185,23 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({<label className="text-[11px] text-[#8a8a8a]">Output Format</label><div className="grid grid-cols-2 gap-1.5"><button+ type="button"onClick={() => setFormat('jpg')}className={`py-1.5 rounded text-xs border cursor-pointer transition-colors ${format === 'jpg'? 'bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-border)] font-medium'- : 'bg-[#161616] border-white/[0.06] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ : 'bg-[#161616] border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>JPEG (Standard)</button><button+ type="button"onClick={() => setFormat('png')}className={`py-1.5 rounded text-xs border cursor-pointer transition-colors ${format === 'png'? 'bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-border)] font-medium'- : 'bg-[#161616] border-white/[0.06] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ : 'bg-[#161616] border-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>PNG (Lossless)@@ -190,15 +227,15 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({)}{isExporting && progress && (- <div className="space-y-2 pt-2 border-t border-white/[0.06]">+ <div className="space-y-2 pt-2 border-t border-[#2c2c2c]"><div className="flex justify-between text-[11px]">- <span className="text-[#e5e5e5] flex items-center space-x-1.5">+ <span className="text-[#e5e5e5] flex items-center gap-1.5"><Loader2 className="w-3.5 h-3.5 animate-spin text-[var(--accent)]" /><span>Slicing tile {progress.current} of {progress.total}...</span></span><span className="font-mono text-[#e5e5e5]">{progress.percent}%</span></div>- <div className="w-full bg-[#161616] h-1.5 rounded-full overflow-hidden border border-white/[0.06]">+ <div className="w-full bg-[#161616] h-1.5 rounded-full overflow-hidden border border-[#2c2c2c]"><divclassName="bg-[var(--accent)] h-full transition-all duration-150"style={{ width: `${progress.percent}%` }}@@ -209,16 +246,18 @@ export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({</div>{/* Footer */}- <div className="px-4 py-2.5 bg-[#1a1a1a] border-t border-white/[0.06] flex items-center justify-end space-x-2">+ <div className="px-4 py-2.5 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end gap-2">{!isExporting && (<button+ type="button"onClick={onClose}- className="px-3 py-1.5 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-xs transition-colors cursor-pointer"+ className="px-3.5 py-1.5 bg-[#2a2a2a] hover:bg-[#363636] text-[#e5e5e5] rounded text-xs font-medium transition-colors cursor-pointer">Cancel</button>)}<button+ type="button"onClick={handleStartExport}disabled={isExporting}className="px-3.5 py-1.5 rounded text-xs font-medium bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 transition-opacity cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.tsindex 6b5f379..5bd5a7b 100644--- a/src/hooks/drawing/useSelectionTools.ts+++ b/src/hooks/drawing/useSelectionTools.ts@@ -45,6 +45,11 @@ import {getMeshSurfaceBounds,resolveTransformTargetLayers,getTransformPreviewLayerState,+ extractCanvasPixelBuffer,+ processAffineTransformChunks,+ processPerspectiveTransformChunks,+ processMeshWarpTransformChunks,+ type PixelBuffer,} from '../../utils/transformEngine';import { get2DContext, getCanvasCompositeOperation } from '../../utils/canvasUtils';import { useToolStore, toolStoreActions } from '../../stores';@@ -104,15 +109,98 @@ function compositeTransformedIntoTileGrid(grid: SparseTileGrid,layerId: string,sourceCanvas: HTMLCanvasElement,+ sourcePixels: PixelBuffer | undefined,session: TransformSession,dimensions: CanvasDimensions,targetFormat: TileFormat,- beforeSnapshot: Map<string, TileSnapshotEntry>+ beforeSnapshot: Map<string, TileSnapshotEntry>,+ monochromeOpts?: {+ threshold: number;+ expressBlack: boolean;+ expressWhite: boolean;+ }): DirtyRect | null {const destRect = computeTransformDestRect(session, dimensions.width, dimensions.height);if (!destRect) return null;const CHUNK = 1024;+ const commitChunk = (+ chunkData: Uint8ClampedArray,+ cx: number,+ cy: number,+ cw: number,+ ch: number+ ) => {+ grid.compositeStrokeToTiles({+ layerId,+ strokeData: { data: chunkData, width: cw, height: ch },+ destX: cx,+ destY: cy,+ format: targetFormat,+ compositeOp: 'source-over',+ opacity: 1.0,+ monochrome: monochromeOpts,+ snapshotOut: beforeSnapshot,+ suppressNotify: true,+ });+ };++ const resolvedPixels = sourcePixels ?? extractCanvasPixelBuffer(sourceCanvas);++ if (resolvedPixels) {+ if (session.mode === 'perspective' && session.perspectiveQuad) {+ if (+ processPerspectiveTransformChunks(+ resolvedPixels,+ session.perspectiveQuad,+ destRect,+ CHUNK,+ 32,+ commitChunk+ )+ ) {+ return destRect;+ }+ } else if (session.mode === 'mesh' && session.meshPoints) {+ const subPerCell = computeMeshSubdivisions(+ resolvedPixels.width,+ resolvedPixels.height,+ session.meshPoints,+ true+ );+ if (+ processMeshWarpTransformChunks(+ resolvedPixels,+ session.meshPoints,+ destRect,+ CHUNK,+ subPerCell,+ commitChunk+ )+ ) {+ return destRect;+ }+ } else {+ processAffineTransformChunks(+ resolvedPixels,+ {+ x: session.x,+ y: session.y,+ width: session.width,+ height: session.height,+ rotation: session.rotation,+ flipH: session.flipH,+ flipV: session.flipV,+ },+ destRect,+ CHUNK,+ commitChunk+ );+ return destRect;+ }+ }++ // Fallback path (e.g. Mesh Warp when WebGL2 is unavailable)const chunkCanvas = document.createElement('canvas');chunkCanvas.width = Math.min(CHUNK, destRect.width);chunkCanvas.height = Math.min(CHUNK, destRect.height);@@ -169,17 +257,7 @@ function compositeTransformedIntoTileGrid(cCtx.restore();const img = cCtx.getImageData(0, 0, cw, ch);- grid.compositeStrokeToTiles({- layerId,- strokeData: img,- destX: cx,- destY: cy,- format: targetFormat,- compositeOp: 'source-over',- opacity: 1.0,- snapshotOut: beforeSnapshot,- suppressNotify: true,- });+ commitChunk(img.data, cx, cy, cw, ch);}}} finally {@@ -1208,6 +1286,7 @@ export function useSelectionTools({const layerBeforeSnapshots = new Map<string, Map<string, TileSnapshotEntry>>();const layerSourceCanvases = new Map<string, HTMLCanvasElement>();+ const layerSourcePixels = new Map<string, { data: Uint8ClampedArray; width: number; height: number }>();const compositeCanvas = document.createElement('canvas');compositeCanvas.width = b.width;@@ -1219,7 +1298,9 @@ export function useSelectionTools({if (!grid.hasLayerTiles(lyr.id)) continue;const sCanvas = grid.createRegionCanvas(lyr.id, b);if (!sCanvas) continue;+ const sPixels = grid.readImageData(lyr.id, b.x, b.y, b.width, b.height);layerSourceCanvases.set(lyr.id, sCanvas);+ layerSourcePixels.set(lyr.id, sPixels);const previewState = getTransformPreviewLayerState(lyr, layerMap, selectedRootIds);if (compCtx && previewState.visible && previewState.opacity > 0.001) {@@ -1254,6 +1335,7 @@ export function useSelectionTools({layerId: primaryLayerId,layerIds: liftedLayerIds,layerSourceCanvases,+ layerSourcePixels,layerBeforeSnapshots,sourceCanvas: compositeCanvas,beforeTileSnapshot: layerBeforeSnapshots.get(primaryLayerId),@@ -1288,6 +1370,7 @@ export function useSelectionTools({const sourceCanvas = grid.createRegionCanvas(targetLayerId, b);if (!sourceCanvas) return;+ const sourcePixels = grid.readImageData(targetLayerId, b.x, b.y, b.width, b.height);const beforeTileSnapshot = new Map<string, TileSnapshotEntry>();grid.clearRectInLayer(targetLayerId, b, isBg, beforeTileSnapshot, false);@@ -1298,6 +1381,7 @@ export function useSelectionTools({active: true,layerId: targetLayerId,sourceCanvas,+ sourcePixels,beforeTileSnapshot,bounds: { x: b.x, y: b.y, width: b.width, height: b.height },x: b.x,@@ -1334,6 +1418,15 @@ export function useSelectionTools({const handleApplyTransform = useCallback(() => {if (!transformSession) return;const grid = getGrid();+ const resolveMonoOpts = (layerId: string, fmt: TileFormat) => {+ if (fmt !== 'monochrome-1bit') return undefined;+ const lyr = layers.find((l) => l.id === layerId);+ return {+ threshold: lyr?.monoThreshold ?? 128,+ expressBlack: lyr?.monoExpressBlack ?? true,+ expressWhite: lyr?.monoExpressWhite ?? true,+ };+ };if (transformSession.layerIds &&@@ -1346,6 +1439,7 @@ export function useSelectionTools({for (const lId of transformSession.layerIds) {const sCanvas = transformSession.layerSourceCanvases.get(lId);if (!sCanvas) continue;+ const sPixels = transformSession.layerSourcePixels?.get(lId);const targetFormat = resolveLayerFormat(lId);const beforeSnap = new Map<string, TileSnapshotEntry>(transformSession.layerBeforeSnapshots?.get(lId) ?? []@@ -1355,10 +1449,12 @@ export function useSelectionTools({grid,lId,sCanvas,+ sPixels,transformSession,dimensions,targetFormat,- beforeSnap+ beforeSnap,+ resolveMonoOpts(lId, targetFormat));if (destRect) {@@ -1402,7 +1498,7 @@ export function useSelectionTools({releaseTemporaryCanvas(transformSession.sourceCanvas);grid.notifyChange(true);setTransformSession(null);- toolStoreActions.setToolRaw('brush');+ toolStoreActions.selectTool('brush');return;}@@ -1416,10 +1512,12 @@ export function useSelectionTools({grid,targetLayerId,transformSession.sourceCanvas,+ transformSession.sourcePixels,transformSession,dimensions,targetFormat,- beforeSnap+ beforeSnap,+ resolveMonoOpts(targetLayerId, targetFormat));const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, targetLayerId);@@ -1439,10 +1537,11 @@ export function useSelectionTools({grid.notifyChange(true);updateLayerThumbnail(targetLayerId, true);setTransformSession(null);- toolStoreActions.setToolRaw('brush');+ toolStoreActions.selectTool('brush');}, [transformSession,getGrid,+ layers,resolveLayerFormat,dimensions,pushHistoryStep,@@ -1466,7 +1565,7 @@ export function useSelectionTools({releaseTemporaryCanvas(transformSession.sourceCanvas);grid.notifyChange(true);setTransformSession(null);- toolStoreActions.setToolRaw('brush');+ toolStoreActions.selectTool('brush');return;}@@ -1476,7 +1575,7 @@ export function useSelectionTools({}releaseTemporaryCanvas(transformSession.sourceCanvas);setTransformSession(null);- toolStoreActions.setToolRaw('brush');+ toolStoreActions.selectTool('brush');}, [transformSession, getGrid, updateLayerThumbnail]);const handleSelectionPointerDown = useCallback(diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsxindex 27ad199..8f95c77 100644--- a/src/hooks/useAppMenuSections.tsx+++ b/src/hooks/useAppMenuSections.tsx@@ -183,7 +183,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiotoggleLayerColor,handleConvertLayer,deleteLayer,- handleApplyFilter,+ handleApplyFilter: _handleApplyFilter,zoomIn,zoomOut,resetZoomAndCenter,@@ -874,57 +874,28 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiolabel: 'Gaussian Blur...',disabled:!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,- onClick: () => {- const r = window.prompt('Gaussian Blur Radius (px, 1-100):', '5');- if (r !== null) {- const radius = Math.max(1, Math.min(100, parseFloat(r) || 5));- handleApplyFilter('gaussian-blur', { radius });- }- },+ onClick: () => uiStoreActions.openFilterModal('gaussian-blur'),},{id: 'filter-motion-blur',label: 'Motion Blur...',disabled:!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,- onClick: () => {- const d = window.prompt('Motion Blur Distance (px, 1-100):', '15');- const a =- d !== null ? window.prompt('Motion Blur Angle (degrees, 0-360):', '0') : null;- if (d !== null && a !== null) {- const distance = Math.max(1, Math.min(100, parseFloat(d) || 15));- const angle = Math.max(0, Math.min(360, parseFloat(a) || 0));- handleApplyFilter('motion-blur', { distance, angle });- }- },+ onClick: () => uiStoreActions.openFilterModal('motion-blur'),},{id: 'filter-unsharp-mask',label: 'Unsharp Mask...',disabled:!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,- onClick: () => {- const r = window.prompt('Unsharp Mask Radius (px, 0.5-20):', '2');- const a = r !== null ? window.prompt('Amount factor (0.1-5.0):', '1.5') : null;- if (r !== null && a !== null) {- const radius = Math.max(0.5, Math.min(20, parseFloat(r) || 2));- const amount = Math.max(0.1, Math.min(5, parseFloat(a) || 1.5));- handleApplyFilter('unsharp-mask', { radius, amount, threshold: 0 });- }- },+ onClick: () => uiStoreActions.openFilterModal('unsharp-mask'),},{id: 'filter-film-grain',label: 'Film Grain...',disabled:!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,- onClick: () => {- const i = window.prompt('Film Grain Intensity (% 1-100):', '25');- if (i !== null) {- const intensity = Math.max(1, Math.min(100, parseFloat(i) || 25));- handleApplyFilter('film-grain', { intensity, size: 1, monochromatic: true });- }- },+ onClick: () => uiStoreActions.openFilterModal('film-grain'),},],},@@ -1465,7 +1436,6 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleAddAnimationCel,handleAddDefaultFrameFolder,handleAddLayer,- handleApplyFilter,handleApplyReverseGradient,handleClearActiveLayer,handleClearSelection,diff --git a/src/stores/index.ts b/src/stores/index.tsindex c08902e..b7cbddd 100644--- a/src/stores/index.ts+++ b/src/stores/index.ts@@ -21,14 +21,21 @@ export {uiStoreActions,selectIsAnyModalOpen,INITIAL_APP_CLOSE_PROMPT_STATE,+ INITIAL_APP_DIALOG_STATE,+ INITIAL_FILTER_MODAL_STATE,} from './useUiStore';export type {UiStoreState,TonalModalState,+ FilterModalState,AdjustmentModalState,LayerStylesModalState,AppClosePromptStep,AppClosePromptState,+ AppDialogVariant,+ AppDialogPreview,+ AppDialogOptions,+ AppDialogState,} from './useUiStore';export { useWorkspaceStore, workspaceStoreActions } from './useWorkspaceStore';diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.tsindex 000486e..db7d9f4 100644--- a/src/stores/useUiStore.ts+++ b/src/stores/useUiStore.ts@@ -1,4 +1,5 @@import { AppSettings, loadAppSettings, saveAppSettings } from '../types/settings';+import { FilterType } from '../types/editor';import { CrashedSessionInfo } from '../services/recoveryService';import { TonalCorrectionType, ProcessingBounds, TileHistogramMap } from '../utils/tonalEngine';import type { TileSnapshotEntry } from '../utils/tileEngine';@@ -7,6 +8,56 @@ import { safeLocalStorageSetItem, setStorageQuotaNotifier } from '../utils/safeSimport { createStore } from './createStore';import { useUpdaterStore } from './useUpdaterStore';+export type AppDialogVariant = 'confirm' | 'danger' | 'alert';++export interface AppDialogPreview {+ imageUrl?: string | null;+ title: string;+ subtitle?: string;+}++export interface AppDialogOptions {+ variant?: AppDialogVariant;+ title: string;+ message: string;+ detail?: string;+ confirmLabel?: string;+ cancelLabel?: string;+ preview?: AppDialogPreview | null;+}++export interface AppDialogState {+ isOpen: boolean;+ variant: AppDialogVariant;+ title: string;+ message: string;+ detail?: string;+ confirmLabel: string;+ cancelLabel: string;+ preview?: AppDialogPreview | null;+}++export const INITIAL_APP_DIALOG_STATE: AppDialogState = {+ isOpen: false,+ variant: 'confirm',+ title: 'Ink Studio',+ message: '',+ detail: undefined,+ confirmLabel: 'OK',+ cancelLabel: 'Cancel',+ preview: null,+};++export interface FilterModalState {+ isOpen: boolean;+ type: FilterType;+}++export const INITIAL_FILTER_MODAL_STATE: FilterModalState = {+ isOpen: false,+ type: 'gaussian-blur',+};+export interface TonalModalState {isOpen: boolean;type: TonalCorrectionType;@@ -70,9 +121,11 @@ export interface UiStoreState {isRecoveryModalOpen: boolean;crashedSessions: CrashedSessionInfo[];tonalModalState: TonalModalState;+ filterModalState: FilterModalState;adjustmentModalState: AdjustmentModalState;layerStylesModalState: LayerStylesModalState;appClosePrompt: AppClosePromptState;+ appDialog: AppDialogState;// Transient feedbackisLoadingFile: boolean;@@ -131,9 +184,11 @@ const createInitialUiState = (): UiStoreState => {isRecoveryModalOpen: false,crashedSessions: [],tonalModalState: { ...DEFAULT_TONAL_MODAL_STATE },+ filterModalState: { ...INITIAL_FILTER_MODAL_STATE },adjustmentModalState: { isOpen: false },layerStylesModalState: { isOpen: false },appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE },+ appDialog: { ...INITIAL_APP_DIALOG_STATE },isLoadingFile: false,loadingStatus: '',@@ -144,6 +199,7 @@ const createInitialUiState = (): UiStoreState => {export const useUiStore = createStore<UiStoreState>(createInitialUiState);let toastTimer: ReturnType<typeof setTimeout> | null = null;+let pendingDialogResolve: ((confirmed: boolean) => void) | null = null;export const uiStoreActions = {setAppView(appView: 'home' | 'workspace'): void {@@ -288,6 +344,57 @@ export const uiStoreActions = {useUiStore.setState({ appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE } });},+ openFilterModal(type: FilterType): void {+ useUiStore.setState({ filterModalState: { isOpen: true, type } });+ },++ closeFilterModal(): void {+ useUiStore.setState((prev) => ({+ filterModalState: { ...prev.filterModalState, isOpen: false },+ }));+ },++ confirmDialog(options: AppDialogOptions): Promise<boolean> {+ if (pendingDialogResolve) {+ const prevResolve = pendingDialogResolve;+ pendingDialogResolve = null;+ prevResolve(false);+ }+ const variant: AppDialogVariant = options.variant ?? 'confirm';+ return new Promise<boolean>((resolve) => {+ pendingDialogResolve = resolve;+ useUiStore.setState({+ appDialog: {+ isOpen: true,+ variant,+ title: options.title,+ message: options.message,+ detail: options.detail,+ confirmLabel: options.confirmLabel ?? (variant === 'danger' ? 'Delete' : 'OK'),+ cancelLabel: options.cancelLabel ?? 'Cancel',+ preview: options.preview ?? null,+ },+ });+ });+ },++ alertDialog(options: Omit<AppDialogOptions, 'variant' | 'cancelLabel'>): Promise<void> {+ return uiStoreActions+ .confirmDialog({+ ...options,+ variant: 'alert',+ confirmLabel: options.confirmLabel ?? 'OK',+ })+ .then(() => undefined);+ },++ resolveAppDialog(confirmed: boolean): void {+ const resolver = pendingDialogResolve;+ pendingDialogResolve = null;+ useUiStore.setState({ appDialog: { ...INITIAL_APP_DIALOG_STATE } });+ resolver?.(confirmed);+ },+setLoading(isLoadingFile: boolean, loadingStatus = ''): void {useUiStore.setState({ isLoadingFile, loadingStatus });},@@ -328,9 +435,11 @@ export function selectIsAnyModalOpen(state.isTimelapseExportModalOpen ||state.isRecoveryModalOpen ||state.tonalModalState.isOpen ||+ state.filterModalState.isOpen ||state.adjustmentModalState.isOpen ||state.layerStylesModalState.isOpen ||state.appClosePrompt.isOpen ||+ state.appDialog.isOpen ||isHostModalOpen ||isUpdateModalOpen);diff --git a/src/stores/useWorkspaceStore.ts b/src/stores/useWorkspaceStore.tsindex d08ff31..bb75621 100644--- a/src/stores/useWorkspaceStore.ts+++ b/src/stores/useWorkspaceStore.ts@@ -10,16 +10,27 @@ import {import {DEFAULT_COMMAND_BAR_IDS,DEFAULT_QUICK_ACCESS_ITEMS,+ DetachPanelOptions,MovePanelTarget,+ bringFloatingPanelToFrontInLayout,cloneLayout,+ closeFloatingPanelInLayout,+ detachPanelToFloatingInLayout,+ dockFloatingPanelInLayout,getPresetLayout,loadWorkspaceState,+ mergePanelIntoFloatingInLayout,+ moveFloatingPanelInLayout,movePanelInLayout,resizeColumnInLayout,+ resizeFloatingPanelInLayout,resizeGroupSplitInLayout,saveWorkspaceState,+ setFloatingActivePanelInLayout,setGroupActivePanelInLayout,toggleColumnCollapsedInLayout,+ toggleFloatingCollapsedInLayout,+ toggleGroupCollapsedInLayout,togglePanelInLayout,} from '../utils/workspacePresets';import { createStore } from './createStore';@@ -142,6 +153,136 @@ export const workspaceStoreActions = {persistCurrentWorkspace();},+ toggleGroupCollapsed(colId: string, groupId: string, forceValue?: boolean): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = toggleGroupCollapsedInLayout(prev.layout, colId, groupId, forceValue);+ return {+ layout: nextLayout,+ activePreset: 'custom',+ savedCustomLayout: cloneLayout(nextLayout),+ };+ });+ persistCurrentWorkspace();+ },++ detachPanel(panelId: DockPanelId, options?: DetachPanelOptions): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = detachPanelToFloatingInLayout(prev.layout, panelId, options);+ return {+ layout: nextLayout,+ activePreset: 'custom',+ savedCustomLayout: cloneLayout(nextLayout),+ openPopover: prev.openPopover?.panelId === panelId ? null : prev.openPopover,+ };+ });+ persistCurrentWorkspace();+ },++ dockFloatingPanel(floatingId: string, target?: MovePanelTarget): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = dockFloatingPanelInLayout(prev.layout, floatingId, target);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ activePreset: 'custom',+ savedCustomLayout: cloneLayout(nextLayout),+ openPopover: null,+ };+ });+ persistCurrentWorkspace();+ },++ mergePanelIntoFloating(panelId: DockPanelId, targetFloatingId: string): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = mergePanelIntoFloatingInLayout(prev.layout, panelId, targetFloatingId);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ activePreset: 'custom',+ savedCustomLayout: cloneLayout(nextLayout),+ openPopover: prev.openPopover?.panelId === panelId ? null : prev.openPopover,+ };+ });+ persistCurrentWorkspace();+ },++ moveFloatingPanel(floatingId: string, x: number, y: number, persist = true): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = moveFloatingPanelInLayout(prev.layout, floatingId, x, y);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ savedCustomLayout:+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,+ };+ });+ if (persist) persistCurrentWorkspace();+ },++ resizeFloatingPanel(+ floatingId: string,+ rect: { x?: number; y?: number; width: number; height: number },+ persist = true+ ): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = resizeFloatingPanelInLayout(prev.layout, floatingId, rect);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ savedCustomLayout:+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,+ };+ });+ if (persist) persistCurrentWorkspace();+ },++ toggleFloatingCollapsed(floatingId: string, forceValue?: boolean): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = toggleFloatingCollapsedInLayout(prev.layout, floatingId, forceValue);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ savedCustomLayout:+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,+ };+ });+ persistCurrentWorkspace();+ },++ setFloatingActivePanel(floatingId: string, panelId: DockPanelId): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = setFloatingActivePanelInLayout(prev.layout, floatingId, panelId);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ savedCustomLayout:+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,+ };+ });+ persistCurrentWorkspace();+ },++ bringFloatingPanelToFront(floatingId: string): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = bringFloatingPanelToFrontInLayout(prev.layout, floatingId);+ if (nextLayout === prev.layout) return prev;+ return { layout: nextLayout };+ });+ },++ closeFloatingPanel(floatingId: string): void {+ useWorkspaceStore.setState((prev) => {+ const nextLayout = closeFloatingPanelInLayout(prev.layout, floatingId);+ if (nextLayout === prev.layout) return prev;+ return {+ layout: nextLayout,+ activePreset: 'custom',+ savedCustomLayout: cloneLayout(nextLayout),+ };+ });+ persistCurrentWorkspace();+ },+toggleColumnCollapsed(colId: string, forceValue?: boolean): void {useWorkspaceStore.setState((prev) => {const nextLayout = toggleColumnCollapsedInLayout(prev.layout, colId, forceValue);diff --git a/src/types/editor.ts b/src/types/editor.tsindex e26b876..d24167e 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -728,6 +728,7 @@ export interface TransformSession {active: boolean;layerId: string;sourceCanvas: HTMLCanvasElement;+ sourcePixels?: { data: Uint8ClampedArray; width: number; height: number };beforeImageData?: ImageData;beforeTileSnapshot?: Map<string, TileSnapshotEntry>;bounds: { x: number; y: number; width: number; height: number };@@ -746,6 +747,7 @@ export interface TransformSession {meshPoints?: Point2D[][];layerIds?: string[];layerSourceCanvases?: Map<string, HTMLCanvasElement>;+ layerSourcePixels?: Map<string, { data: Uint8ClampedArray; width: number; height: number }>;layerBeforeImages?: Map<string, ImageData>;layerBeforeSnapshots?: Map<string, Map<string, TileSnapshotEntry>>;}diff --git a/src/types/workspace.ts b/src/types/workspace.tsindex 4a2a24b..eda2da3 100644--- a/src/types/workspace.ts+++ b/src/types/workspace.ts@@ -27,6 +27,8 @@ export interface DockGroup {panelIds: DockPanelId[];activePanelId: DockPanelId;heightRatio: number;+ /** When true, the docked group collapses to its header bar */+ collapsed?: boolean;}export interface DockColumn {@@ -36,9 +38,30 @@ export interface DockColumn {groups: DockGroup[];}+export interface FloatingPanelLastDock {+ side: DockSide;+ colId?: string;+ groupId?: string;+}++export interface FloatingPanelState {+ id: string;+ panelIds: DockPanelId[];+ activePanelId: DockPanelId;+ x: number;+ y: number;+ width: number;+ height: number;+ /** When true, hides the panel body leaving only the floating title bar (CSP shade mode) */+ collapsed: boolean;+ zIndex: number;+ lastDock?: FloatingPanelLastDock;+}+export interface WorkspaceLayout {leftDocks: DockColumn[];rightDocks: DockColumn[];+ floatingPanels?: FloatingPanelState[];}export type CommandActionId =@@ -96,6 +119,9 @@ export interface DockPanelMeta {defaultWidth: number;minWidth: number;maxWidth: number;+ defaultFloatWidth: number;+ defaultFloatHeight: number;+ minFloatHeight: number;}export const ALL_DOCK_PANEL_IDS: DockPanelId[] = [@@ -122,6 +148,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 46,minWidth: 44,maxWidth: 96,+ defaultFloatWidth: 108,+ defaultFloatHeight: 380,+ minFloatHeight: 160,},subtool: {id: 'subtool',@@ -131,6 +160,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 196,minWidth: 140,maxWidth: 340,+ defaultFloatWidth: 240,+ defaultFloatHeight: 340,+ minFloatHeight: 160,},'tool-property': {id: 'tool-property',@@ -140,6 +172,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 196,minWidth: 148,maxWidth: 340,+ defaultFloatWidth: 256,+ defaultFloatHeight: 380,+ minFloatHeight: 160,},'brush-size': {id: 'brush-size',@@ -149,6 +184,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 196,minWidth: 148,maxWidth: 340,+ defaultFloatWidth: 236,+ defaultFloatHeight: 280,+ minFloatHeight: 150,},navigator: {id: 'navigator',@@ -158,6 +196,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 176,maxWidth: 380,+ defaultFloatWidth: 268,+ defaultFloatHeight: 250,+ minFloatHeight: 170,},'sub-view': {id: 'sub-view',@@ -167,6 +208,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 176,maxWidth: 400,+ defaultFloatWidth: 320,+ defaultFloatHeight: 340,+ minFloatHeight: 180,},info: {id: 'info',@@ -176,6 +220,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 176,maxWidth: 380,+ defaultFloatWidth: 248,+ defaultFloatHeight: 220,+ minFloatHeight: 140,},color: {id: 'color',@@ -185,6 +232,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 168,maxWidth: 360,+ defaultFloatWidth: 264,+ defaultFloatHeight: 320,+ minFloatHeight: 200,},layers: {id: 'layers',@@ -194,6 +244,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 176,maxWidth: 380,+ defaultFloatWidth: 272,+ defaultFloatHeight: 420,+ minFloatHeight: 200,},history: {id: 'history',@@ -203,6 +256,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 160,maxWidth: 340,+ defaultFloatWidth: 248,+ defaultFloatHeight: 320,+ minFloatHeight: 160,},'quick-access': {id: 'quick-access',@@ -212,6 +268,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 184,minWidth: 136,maxWidth: 320,+ defaultFloatWidth: 228,+ defaultFloatHeight: 300,+ minFloatHeight: 150,},'auto-actions': {id: 'auto-actions',@@ -221,6 +280,9 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {defaultWidth: 224,minWidth: 176,maxWidth: 360,+ defaultFloatWidth: 256,+ defaultFloatHeight: 310,+ minFloatHeight: 160,},};diff --git a/src/utils/__tests__/appDialogAndFilterModal.test.tsx b/src/utils/__tests__/appDialogAndFilterModal.test.tsxnew file mode 100644index 0000000..165de69--- /dev/null+++ b/src/utils/__tests__/appDialogAndFilterModal.test.tsx@@ -0,0 +1,426 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ INITIAL_APP_DIALOG_STATE,+ INITIAL_FILTER_MODAL_STATE,+ selectIsAnyModalOpen,+ uiStoreActions,+ useUiStore,+} from '../../stores';+import { ConfirmDialogModal } from '../../components/ConfirmDialogModal';+import { FilterModal } from '../../components/FilterModal';++interface MiniNode {+ nodeType: number;+ nodeName: string;+ parentNode: MiniElement | null;+ ownerDocument: MiniDocument;+}++class MiniTextNode implements MiniNode {+ public nodeType = 3;+ public nodeName = '#text';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniCommentNode implements MiniNode {+ public nodeType = 8;+ public nodeName = '#comment';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniElement extends EventTarget implements MiniNode {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public ownerDocument: MiniDocument;+ public parentNode: MiniElement | null = null;+ public childNodes: MiniNode[] = [];+ public style: Record<string, string> = {};+ public disabled = false;+ public className = '';+ public isContentEditable = false;+ public value = '';+ public checked = false;+ private attrs = new Map<string, string>();++ constructor(tag: string, ownerDocument: MiniDocument) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ this.ownerDocument = ownerDocument;+ }++ get firstChild(): MiniNode | null {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];+ }++ appendChild<T extends MiniNode>(child: T): T {+ if (child.parentNode) {+ child.parentNode.removeChild(child);+ }+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {+ if (!ref) return this.appendChild(child);+ if (child.parentNode) {+ child.parentNode.removeChild(child);+ }+ const idx = this.childNodes.indexOf(ref);+ child.parentNode = this;+ if (idx === -1) {+ this.childNodes.push(child);+ } else {+ this.childNodes.splice(idx, 0, child);+ }+ return child;+ }++ removeChild<T extends MiniNode>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx !== -1) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ setAttribute(name: string, value: string): void {+ this.attrs.set(name, String(value));+ if (name === 'class') this.className = String(value);+ if (name === 'disabled') this.disabled = true;+ if (name === 'value') this.value = String(value);+ }++ getAttribute(name: string): string | null {+ return this.attrs.get(name) ?? null;+ }++ removeAttribute(name: string): void {+ this.attrs.delete(name);+ if (name === 'disabled') this.disabled = false;+ }++ hasAttribute(name: string): boolean {+ return this.attrs.has(name);+ }++ focus(): void {+ this.ownerDocument.activeElement = this;+ }++ blur(): void {+ if (this.ownerDocument.activeElement === this) {+ this.ownerDocument.activeElement = null;+ }+ }++ override dispatchEvent(event: Event): boolean {+ const path: EventTarget[] = [];+ let cur: MiniElement | null = this;+ while (cur) {+ path.push(cur);+ cur = cur.parentNode;+ }+ path.push(this.ownerDocument);+ if (this.ownerDocument.defaultView) {+ path.push(this.ownerDocument.defaultView);+ }++ Object.defineProperty(event, 'target', { value: this, configurable: true });+ for (const node of path) {+ Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });+ EventTarget.prototype.dispatchEvent.call(node, event);+ if (event.cancelBubble) break;+ }+ return !event.defaultPrevented;+ }+}++class MiniDocument extends EventTarget {+ public nodeType = 9;+ public nodeName = '#document';+ public defaultView: EventTarget | null = null;+ public documentElement: MiniElement;+ public body: MiniElement;+ public activeElement: MiniElement | null = null;++ constructor() {+ super();+ this.documentElement = new MiniElement('html', this);+ this.body = new MiniElement('body', this);+ this.documentElement.appendChild(this.body);+ }++ createElement(tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createElementNS(_ns: string, tag: string): MiniElement {+ return new MiniElement(tag, this);+ }++ createTextNode(text: string): MiniTextNode {+ return new MiniTextNode(text, this);+ }++ createComment(text: string): MiniCommentNode {+ return new MiniCommentNode(text, this);+ }+}++function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {+ const result: MiniElement[] = [];+ const walk = (el: MiniElement) => {+ if (pred(el)) result.push(el);+ for (const child of el.childNodes) {+ if (child instanceof MiniElement) walk(child);+ }+ };+ walk(root);+ return result;+}++function findButtonByText(root: MiniElement, label: string): MiniElement | undefined {+ return findElements(+ root,+ (el) => el.tagName === 'BUTTON' && el.textContent.trim() === label+ )[0];+}++function clickElement(el: MiniElement): void {+ const evt = new Event('click', { bubbles: true, cancelable: true });+ el.dispatchEvent(evt);+}++describe('ConfirmDialogModal & FilterModal', () => {+ let doc: MiniDocument;+ let win: EventTarget;+ let container: MiniElement;+ let root: Root;++ const prevWindow = (globalThis as Record<string, unknown>).window;+ const prevDocument = (globalThis as Record<string, unknown>).document;+ const prevHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;+ const prevHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;+ const prevElement = (globalThis as Record<string, unknown>).Element;+ const prevNode = (globalThis as Record<string, unknown>).Node;+ const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;++ beforeEach(() => {+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ const MockHTMLIFrameElement = class HTMLIFrameElement {};+ doc = new MiniDocument();+ win = Object.assign(new EventTarget(), {+ document: doc,+ HTMLElement: MiniElement,+ HTMLIFrameElement: MockHTMLIFrameElement,+ Element: MiniElement,+ Node: MiniElement,+ });+ doc.defaultView = win;+ container = doc.createElement('div');+ doc.body.appendChild(container);++ (globalThis as Record<string, unknown>).window = win;+ (globalThis as Record<string, unknown>).document = doc;+ (globalThis as Record<string, unknown>).HTMLElement = MiniElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = MockHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = MiniElement;+ (globalThis as Record<string, unknown>).Node = MiniElement;++ useUiStore.setState({+ appDialog: { ...INITIAL_APP_DIALOG_STATE },+ filterModalState: { ...INITIAL_FILTER_MODAL_STATE },+ });++ root = createRoot(container as unknown as Element);+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ useUiStore.setState({+ appDialog: { ...INITIAL_APP_DIALOG_STATE },+ filterModalState: { ...INITIAL_FILTER_MODAL_STATE },+ });+ (globalThis as Record<string, unknown>).window = prevWindow;+ (globalThis as Record<string, unknown>).document = prevDocument;+ (globalThis as Record<string, unknown>).HTMLElement = prevHTMLElement;+ (globalThis as Record<string, unknown>).HTMLIFrameElement = prevHTMLIFrameElement;+ (globalThis as Record<string, unknown>).Element = prevElement;+ (globalThis as Record<string, unknown>).Node = prevNode;+ (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;+ });++ it('renders brush delete confirmation with preview and resolves true on Delete click', async () => {+ act(() => {+ root.render(<ConfirmDialogModal />);+ });++ let confirmPromise!: Promise<boolean>;+ act(() => {+ confirmPromise = uiStoreActions.confirmDialog({+ variant: 'danger',+ title: 'Delete Brush',+ message: 'Are you sure you want to delete this brush?',+ detail: 'This permanently removes the brush from your library and cannot be undone.',+ confirmLabel: 'Delete',+ cancelLabel: 'Cancel',+ preview: {+ title: 'G-Pen Custom',+ subtitle: 'Imported custom brush',+ },+ });+ });++ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(true);+ expect(container.textContent).toContain('Delete Brush');+ expect(container.textContent).toContain('G-Pen Custom');+ expect(container.textContent).toContain('Imported custom brush');++ const deleteBtn = findButtonByText(container, 'Delete');+ expect(deleteBtn).toBeDefined();++ act(() => {+ clickElement(deleteBtn!);+ });++ const result = await confirmPromise;+ expect(result).toBe(true);+ expect(useUiStore.getState().appDialog.isOpen).toBe(false);+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(false);+ });++ it('resolves false on Cancel click or Escape key', async () => {+ act(() => {+ root.render(<ConfirmDialogModal />);+ });++ let p1!: Promise<boolean>;+ act(() => {+ p1 = uiStoreActions.confirmDialog({+ variant: 'danger',+ title: 'Delete Brush',+ message: 'Delete this brush?',+ confirmLabel: 'Delete',+ cancelLabel: 'Cancel',+ });+ });++ const cancelBtn = findButtonByText(container, 'Cancel');+ expect(cancelBtn).toBeDefined();+ act(() => {+ clickElement(cancelBtn!);+ });+ expect(await p1).toBe(false);++ let p2!: Promise<boolean>;+ act(() => {+ p2 = uiStoreActions.confirmDialog({+ variant: 'confirm',+ title: 'Confirm Action',+ message: 'Proceed?',+ });+ });++ act(() => {+ const esc = new Event('keydown', { cancelable: true }) as KeyboardEvent;+ Object.defineProperty(esc, 'key', { value: 'Escape' });+ win.dispatchEvent(esc);+ });+ expect(await p2).toBe(false);+ });++ it('renders alertDialog with a single OK button and cancels superseded dialogs', async () => {+ act(() => {+ root.render(<ConfirmDialogModal />);+ });++ let firstPromise!: Promise<boolean>;+ let alertPromise!: Promise<void>;+ act(() => {+ firstPromise = uiStoreActions.confirmDialog({+ title: 'First',+ message: 'First message',+ });+ alertPromise = uiStoreActions.alertDialog({+ title: 'Save Failed',+ message: 'Disk is full.',+ });+ });++ expect(await firstPromise).toBe(false);+ expect(container.textContent).toContain('Save Failed');+ expect(container.textContent).toContain('Disk is full.');+ expect(findButtonByText(container, 'Cancel')).toBeUndefined();++ const okBtn = findButtonByText(container, 'OK');+ expect(okBtn).toBeDefined();+ act(() => {+ clickElement(okBtn!);+ });+ await alertPromise;+ expect(useUiStore.getState().appDialog.isOpen).toBe(false);+ });++ it('opens FilterModal, marks modal open in store, and applies default Gaussian Blur params', () => {+ const onApply = vi.fn();+ const onClose = vi.fn(() => uiStoreActions.closeFilterModal());++ act(() => {+ uiStoreActions.openFilterModal('gaussian-blur');+ root.render(+ <FilterModal+ isOpen={useUiStore.getState().filterModalState.isOpen}+ type={useUiStore.getState().filterModalState.type}+ onClose={onClose}+ onApply={onApply}+ />+ );+ });++ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(true);+ expect(container.textContent).toContain('Gaussian Blur');++ const applyBtn = findButtonByText(container, 'Apply');+ expect(applyBtn).toBeDefined();+ act(() => {+ clickElement(applyBtn!);+ });++ expect(onApply).toHaveBeenCalledWith('gaussian-blur', { radius: 5 });+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(false);+ });+});diff --git a/src/utils/__tests__/transformQuality.test.ts b/src/utils/__tests__/transformQuality.test.tsnew file mode 100644index 0000000..6320512--- /dev/null+++ b/src/utils/__tests__/transformQuality.test.ts@@ -0,0 +1,359 @@+import { describe, it, expect } from 'vitest';+import {+ processAffineTransformChunks,+ processPerspectiveTransformChunks,+ resolveLosslessAffineSpec,+ type PixelBuffer,+} from '../transformEngine';+import { SparseTileGrid } from '../tileEngine';+import { ERASER_PRESET_ID } from '../brushPresetManager';+import { useToolStore, toolStoreActions } from '../../stores';++function makeBuffer(width: number, height: number): PixelBuffer {+ return {+ data: new Uint8ClampedArray(width * height * 4),+ width,+ height,+ };+}++function setPx(buf: PixelBuffer, x: number, y: number, r: number, g: number, b: number, a: number) {+ const off = (y * buf.width + x) * 4;+ buf.data[off] = r;+ buf.data[off + 1] = g;+ buf.data[off + 2] = b;+ buf.data[off + 3] = a;+}++function getPx(buf: PixelBuffer, x: number, y: number): [number, number, number, number] {+ const off = (y * buf.width + x) * 4;+ return [buf.data[off], buf.data[off + 1], buf.data[off + 2], buf.data[off + 3]];+}++function runAffineToBuffer(+ src: PixelBuffer,+ params: {+ x: number;+ y: number;+ width: number;+ height: number;+ rotation: number;+ flipH: boolean;+ flipV: boolean;+ },+ docW: number,+ docH: number,+ chunkSize = 64+): PixelBuffer {+ const out = makeBuffer(docW, docH);+ processAffineTransformChunks(+ src,+ params,+ { x: 0, y: 0, width: docW, height: docH },+ chunkSize,+ (chunk, cx, cy, cw, ch) => {+ for (let y = 0; y < ch; y++) {+ const srcOff = y * cw * 4;+ const dstOff = ((cy + y) * docW + cx) * 4;+ out.data.set(chunk.subarray(srcOff, srcOff + cw * 4), dstOff);+ }+ }+ );+ return out;+}++describe('Transform Brush Stroke Quality Pipeline', () => {+ it('preserves straight-alpha anti-aliased stroke edges bit-identically on integer translate', () => {+ const src = makeBuffer(16, 16);+ // Low-alpha anti-aliased colored stroke edge pixels that Canvas2D premultiplication would corrupt+ setPx(src, 4, 5, 235, 92, 148, 7);+ setPx(src, 5, 5, 235, 92, 148, 128);+ setPx(src, 6, 5, 235, 92, 148, 255);+ setPx(src, 7, 5, 19, 211, 87, 3);++ const out = runAffineToBuffer(+ src,+ { x: 10, y: 12, width: 16, height: 16, rotation: 0, flipH: false, flipV: false },+ 48,+ 48+ );++ expect(getPx(out, 14, 17)).toEqual([235, 92, 148, 7]);+ expect(getPx(out, 15, 17)).toEqual([235, 92, 148, 128]);+ expect(getPx(out, 16, 17)).toEqual([235, 92, 148, 255]);+ expect(getPx(out, 17, 17)).toEqual([19, 211, 87, 3]);+ expect(getPx(out, 4, 5)).toEqual([0, 0, 0, 0]);+ });++ it('performs bit-exact 90/180/270 rotations and flips on odd x even dimensions with zero 0.5px blur', () => {+ // Odd width (25) x even height (24): previously caused a 0.5px shift blur on 90/270 rotations+ const src = makeBuffer(25, 24);+ for (let x = 2; x <= 22; x++) {+ setPx(src, x, 10, 20, 40, 220, 255);+ }++ const spec90 = resolveLosslessAffineSpec(25, 24, {+ x: 10,+ y: 10,+ width: 25,+ height: 24,+ rotation: 90,+ flipH: false,+ flipV: false,+ });+ expect(spec90).not.toBeNull();+ expect(spec90!.destWidth).toBe(24);+ expect(spec90!.destHeight).toBe(25);++ const out90 = runAffineToBuffer(+ src,+ { x: 10, y: 10, width: 25, height: 24, rotation: 90, flipH: false, flipV: false },+ 64,+ 64+ );++ // Every single stroke pixel must remain crisp alpha=255 with zero partial-alpha blur pixels+ let opaqueCount = 0;+ let semiAlphaCount = 0;+ for (let i = 3; i < out90.data.length; i += 4) {+ if (out90.data[i] === 255) opaqueCount++;+ else if (out90.data[i] > 0) semiAlphaCount++;+ }+ expect(opaqueCount).toBe(21);+ expect(semiAlphaCount).toBe(0);++ // 4 consecutive 90-degree rotations around the same integer box must stay 100% lossless+ const out180 = runAffineToBuffer(+ src,+ { x: 10, y: 10, width: 25, height: 24, rotation: 180, flipH: true, flipV: false },+ 64,+ 64+ );+ let opaque180 = 0;+ let semi180 = 0;+ for (let i = 3; i < out180.data.length; i += 4) {+ if (out180.data[i] === 255) opaque180++;+ else if (out180.data[i] > 0) semi180++;+ }+ expect(opaque180).toBe(21);+ expect(semi180).toBe(0);+ });++ it('keeps rotated bright colored strokes crisp without dark premultiply fringing or alpha halos', () => {+ const src = makeBuffer(64, 64);+ // Crisp 4px-wide bright yellow brush stroke on transparent background+ for (let x = 12; x <= 52; x++) {+ for (let y = 30; y <= 33; y++) {+ setPx(src, x, y, 255, 240, 40, 255);+ }+ }++ const out = runAffineToBuffer(+ src,+ { x: 10, y: 10, width: 64, height: 64, rotation: 23, flipH: false, flipV: false },+ 96,+ 96+ );++ let peakAlpha = 0;+ let strongCorePixels = 0;+ let minYellowRedOnVisibleEdge = 255;++ for (let y = 0; y < 96; y++) {+ for (let x = 0; x < 96; x++) {+ const [r, g, b, a] = getPx(out, x, y);+ if (a > peakAlpha) peakAlpha = a;+ if (a >= 250) strongCorePixels++;+ if (a >= 20) {+ // Straight-alpha RGB on anti-aliased edges must NOT darken toward black+ if (r < minYellowRedOnVisibleEdge) minYellowRedOnVisibleEdge = r;+ expect(g).toBeGreaterThanOrEqual(230);+ expect(b).toBeLessThanOrEqual(50);+ }+ }+ }++ expect(peakAlpha).toBe(255);+ expect(strongCorePixels).toBeGreaterThan(70);+ expect(minYellowRedOnVisibleEdge).toBeGreaterThanOrEqual(245);+ });++ it('upscales high-contrast strokes cleanly with Anti-Ringing Lanczos-3 (zero overshoot halo)', () => {+ // Black stroke drawn over opaque white paper+ const src = makeBuffer(32, 32);+ for (let y = 0; y < 32; y++) {+ for (let x = 0; x < 32; x++) {+ const isStroke = x >= 14 && x <= 17 && y >= 6 && y <= 25;+ if (isStroke) setPx(src, x, y, 20, 20, 20, 255);+ else setPx(src, x, y, 240, 240, 240, 255);+ }+ }++ // 2.5x upscale (32 -> 80)+ const out = runAffineToBuffer(+ src,+ { x: 0, y: 0, width: 80, height: 80, rotation: 0, flipH: false, flipV: false },+ 80,+ 80+ );++ // Anti-ringing clamp ensures no pixel overshoots above 240 (white bg) or below 20 (ink)+ let minVal = 255;+ let maxVal = 0;+ for (let y = 10; y < 70; y++) {+ for (let x = 10; x < 70; x++) {+ const [r, , , a] = getPx(out, x, y);+ expect(a).toBe(255);+ if (r < minVal) minVal = r;+ if (r > maxVal) maxVal = r;+ }+ }+ expect(minVal).toBeGreaterThanOrEqual(20);+ expect(maxVal).toBeLessThanOrEqual(240);++ // Verify sharp transition across the stroke edge (center of stroke stays dark = 20)+ expect(getPx(out, 40, 40)[0]).toBe(20);+ // Surrounding paper stays clean = 240 (zero ringing dip!)+ expect(getPx(out, 20, 40)[0]).toBe(240);+ });++ it('preserves continuity of thin 2px brush strokes across heavy 4x and 6x downscaling', () => {+ const src = makeBuffer(240, 240);+ // Draw a crisp 2px-wide horizontal black line across y = 120..121+ for (let x = 16; x < 224; x++) {+ setPx(src, x, 120, 0, 0, 0, 255);+ setPx(src, x, 121, 0, 0, 0, 255);+ }++ // 4x downscale (240 -> 60)+ const out4x = runAffineToBuffer(+ src,+ { x: 0, y: 0, width: 60, height: 60, rotation: 0, flipH: false, flipV: false },+ 60,+ 60+ );+ // Every column along the scaled stroke (x = 8..52) must have continuous visible ink+ for (let x = 8; x <= 52; x++) {+ let colMaxAlpha = 0;+ for (let y = 26; y <= 34; y++) {+ colMaxAlpha = Math.max(colMaxAlpha, getPx(out4x, x, y)[3]);+ }+ expect(colMaxAlpha).toBeGreaterThanOrEqual(90);+ }++ // 6x downscale (240 -> 40, exercises separable 1D pre-downsampler)+ const out6x = runAffineToBuffer(+ src,+ { x: 0, y: 0, width: 40, height: 40, rotation: 0, flipH: false, flipV: false },+ 40,+ 40+ );+ for (let x = 6; x <= 34; x++) {+ let colMaxAlpha = 0;+ for (let y = 16; y <= 24; y++) {+ colMaxAlpha = Math.max(colMaxAlpha, getPx(out6x, x, y)[3]);+ }+ expect(colMaxAlpha).toBeGreaterThanOrEqual(60);+ }+ });++ it('commits Perspective Quad losslessly on identity shift and crisply on projective warp', () => {+ const src = makeBuffer(32, 32);+ for (let x = 6; x <= 26; x++) {+ setPx(src, x, 15, 255, 80, 120, 255);+ setPx(src, x, 16, 255, 80, 120, 15);+ }++ // Exact integer translation quad -> bit-exact lossless copy+ const outId = makeBuffer(64, 64);+ processPerspectiveTransformChunks(+ src,+ [+ { x: 10, y: 12 },+ { x: 42, y: 12 },+ { x: 42, y: 44 },+ { x: 10, y: 44 },+ ],+ { x: 0, y: 0, width: 64, height: 64 },+ 64,+ 16,+ (chunk, cx, cy, cw, ch) => {+ for (let y = 0; y < ch; y++) {+ outId.data.set(chunk.subarray(y * cw * 4, (y + 1) * cw * 4), ((cy + y) * 64 + cx) * 4);+ }+ }+ );+ expect(getPx(outId, 16, 27)).toEqual([255, 80, 120, 255]);+ expect(getPx(outId, 16, 28)).toEqual([255, 80, 120, 15]);++ // Projective perspective warp (keystone taper)+ const outPersp = makeBuffer(80, 80);+ processPerspectiveTransformChunks(+ src,+ [+ { x: 16, y: 10 },+ { x: 64, y: 14 },+ { x: 70, y: 66 },+ { x: 10, y: 62 },+ ],+ { x: 0, y: 0, width: 80, height: 80 },+ 64,+ 16,+ (chunk, cx, cy, cw, ch) => {+ for (let y = 0; y < ch; y++) {+ outPersp.data.set(chunk.subarray(y * cw * 4, (y + 1) * cw * 4), ((cy + y) * 80 + cx) * 4);+ }+ }+ );++ let peakA = 0;+ for (let i = 3; i < outPersp.data.length; i += 4) {+ if (outPersp.data[i] > peakA) peakA = outPersp.data[i];+ }+ expect(peakA).toBe(255);+ });++ it('restores the user brush preset cleanly when leaving Transform after Eraser', () => {+ toolStoreActions.selectTool('brush');+ const originalPreset = useToolStore.getState().brushSettings.preset;++ // Switch to eraser, then enter transform via setToolRaw('transform')+ toolStoreActions.selectTool('eraser');+ expect(useToolStore.getState().brushSettings.preset).toBe(ERASER_PRESET_ID);+ toolStoreActions.setToolRaw('transform');++ // Exiting transform via selectTool('brush') must restore the user's real brush preset+ toolStoreActions.selectTool('brush');+ expect(useToolStore.getState().tool).toBe('brush');+ expect(useToolStore.getState().brushSettings.preset).toBe(originalPreset);+ });++ it('commits lossless affine pixels directly to SparseTileGrid with exact straight alpha', () => {+ const grid = new SparseTileGrid();+ const src = makeBuffer(20, 20);+ setPx(src, 5, 5, 180, 60, 240, 11);+ setPx(src, 6, 5, 180, 60, 240, 255);++ processAffineTransformChunks(+ src,+ { x: 30, y: 40, width: 20, height: 20, rotation: 0, flipH: false, flipV: false },+ { x: 28, y: 38, width: 24, height: 24 },+ 64,+ (chunk, cx, cy, cw, ch) => {+ grid.compositeStrokeToTiles({+ layerId: 'layer-1',+ strokeData: { data: chunk, width: cw, height: ch },+ destX: cx,+ destY: cy,+ format: 'color-32bit',+ compositeOp: 'source-over',+ opacity: 1.0,+ suppressNotify: true,+ });+ }+ );++ expect(Array.from(grid.getPixelRGBA('layer-1', 35, 45))).toEqual([180, 60, 240, 11]);+ expect(Array.from(grid.getPixelRGBA('layer-1', 36, 45))).toEqual([180, 60, 240, 255]);+ });+});diff --git a/src/utils/__tests__/workspaceDock.test.tsx b/src/utils/__tests__/workspaceDock.test.tsxindex bd8d921..430b5c3 100644--- a/src/utils/__tests__/workspaceDock.test.tsx+++ b/src/utils/__tests__/workspaceDock.test.tsx@@ -3,15 +3,19 @@ import { createRoot, Root } from 'react-dom/client';import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import {WORKSPACE_STORAGE_KEY,+ findFloatingPanelLocation,findPanelLocation,+ listVisiblePanelIds,loadWorkspaceState,+ sanitizeLayout,} from '../workspacePresets';import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';import { useUiStore } from '../../stores/useUiStore';import { BrushSizePalette } from '../../components/BrushSizePalette';import { StatusBar } from '../../components/StatusBar';import { DocumentTabBar } from '../../components/DocumentTabBar';-import { DockGroupView } from '../../components/DockWorkspace';+import { DockGroupView, renderPanelIcon } from '../../components/DockWorkspace';+import { FloatingPanelWindow } from '../../components/FloatingPanelWindow';import { BrushSettings, DocumentTab } from '../../types/editor';function createMemoryStorage(): Storage {@@ -384,6 +388,125 @@ describe('CSP Dock Workspace, Presets & Persistence', () => {expect(safe.layout.leftDocks.length).toBeGreaterThan(0);expect(safe.layout.rightDocks.length).toBeGreaterThan(0);});++ it('detaches any panel to float freely, moves/resizes/collapses via "-", persists across reload, and reattaches to previous or custom dock location', () => {+ const origLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'sub-view');+ expect(origLoc).not.toBeNull();+ expect(origLoc?.side).toBe('right');++ // Detach Sub View to float freely+ workspaceStoreActions.detachPanel('sub-view', { x: 420, y: 180, width: 320, height: 340 });+ const afterDetach = useWorkspaceStore.getState().layout;+ expect(findPanelLocation(afterDetach, 'sub-view')).toBeNull();+ const floatLoc = findFloatingPanelLocation(afterDetach, 'sub-view');+ expect(floatLoc).not.toBeNull();+ expect(listVisiblePanelIds(afterDetach).has('sub-view')).toBe(true);++ // Move and resize floating panel+ workspaceStoreActions.moveFloatingPanel(floatLoc!.floatingId, 520, 240, true);+ workspaceStoreActions.resizeFloatingPanel(+ floatLoc!.floatingId,+ { width: 380, height: 400 },+ true+ );++ // Collapse floating panel with "-" button+ workspaceStoreActions.toggleFloatingCollapsed(floatLoc!.floatingId);+ let fp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(+ (p) => p.id === floatLoc!.floatingId+ );+ expect(fp?.x).toBe(520);+ expect(fp?.y).toBe(240);+ expect(fp?.width).toBe(380);+ expect(fp?.height).toBe(400);+ expect(fp?.collapsed).toBe(true);++ // Persist and reload from localStorage+ useWorkspaceStore.reset();+ const reloaded = useWorkspaceStore.getState().layout;+ const reloadedFp = (reloaded.floatingPanels ?? []).find((p) => p.panelIds.includes('sub-view'));+ expect(reloadedFp).toBeDefined();+ expect(reloadedFp?.x).toBe(520);+ expect(reloadedFp?.y).toBe(240);+ expect(reloadedFp?.collapsed).toBe(true);++ // Expand and 1-click reattach back to previous dock group+ workspaceStoreActions.toggleFloatingCollapsed(reloadedFp!.id, false);+ workspaceStoreActions.dockFloatingPanel(reloadedFp!.id);+ const afterReattach = useWorkspaceStore.getState().layout;+ expect(findFloatingPanelLocation(afterReattach, 'sub-view')).toBeNull();+ const reattachedLoc = findPanelLocation(afterReattach, 'sub-view');+ expect(reattachedLoc?.side).toBe(origLoc?.side);+ expect(reattachedLoc?.colId).toBe(origLoc?.colId);+ expect(reattachedLoc?.groupId).toBe(origLoc?.groupId);++ // Detach again and reattach to a completely different dock location (left dock new column)+ workspaceStoreActions.detachPanel('sub-view');+ const secondFloat = findFloatingPanelLocation(useWorkspaceStore.getState().layout, 'sub-view');+ expect(secondFloat).not.toBeNull();+ workspaceStoreActions.dockFloatingPanel(secondFloat!.floatingId, {+ side: 'left',+ insertColumnIndex: 0,+ });+ const movedLeft = findPanelLocation(useWorkspaceStore.getState().layout, 'sub-view');+ expect(movedLeft?.side).toBe('left');+ expect(useWorkspaceStore.getState().layout.leftDocks[0].groups[0].panelIds).toContain('sub-view');+ });++ it('supports grouping floating panels as tabs, closing floating panels, collapsing docked groups, and sanitizing floating-only layouts', () => {+ workspaceStoreActions.detachPanel('sub-view', { x: 300, y: 120 });+ workspaceStoreActions.detachPanel('info', { x: 360, y: 150 });++ const subViewFloat = findFloatingPanelLocation(useWorkspaceStore.getState().layout, 'sub-view');+ expect(subViewFloat).not.toBeNull();++ // Merge 'info' into 'sub-view' floating window as tabs+ workspaceStoreActions.mergePanelIntoFloating('info', subViewFloat!.floatingId);+ const mergedFp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(+ (f) => f.id === subViewFloat!.floatingId+ );+ expect(mergedFp?.panelIds).toEqual(['sub-view', 'info']);+ expect(mergedFp?.activePanelId).toBe('info');++ // Bring to front and close floating window+ workspaceStoreActions.closeFloatingPanel(subViewFloat!.floatingId);+ expect(listVisiblePanelIds(useWorkspaceStore.getState().layout).has('sub-view')).toBe(false);+ expect(listVisiblePanelIds(useWorkspaceStore.getState().layout).has('info')).toBe(false);++ // Collapsing a docked group with "-" persists cleanly+ const layerLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'layers')!;+ workspaceStoreActions.toggleGroupCollapsed(layerLoc.colId, layerLoc.groupId);+ const col = useWorkspaceStore+ .getState()+ .layout.rightDocks.find((c) => c.id === layerLoc.colId);+ const grp = col?.groups.find((g) => g.id === layerLoc.groupId);+ expect(grp?.collapsed).toBe(true);++ // Sanitize handles floating-only layout and deduplicates panels across dock & floating+ const floatingOnly = sanitizeLayout({+ leftDocks: [],+ rightDocks: [],+ floatingPanels: [+ {+ id: 'f-1',+ panelIds: ['sub-view', 'sub-view'],+ activePanelId: 'sub-view',+ x: -999,+ y: -50,+ width: 300,+ height: 300,+ collapsed: true,+ zIndex: 5,+ },+ ],+ });+ expect(floatingOnly).not.toBeNull();+ expect(floatingOnly?.floatingPanels).toHaveLength(1);+ expect(floatingOnly?.floatingPanels?.[0].panelIds).toEqual(['sub-view']);+ expect(floatingOnly?.floatingPanels?.[0].x).toBeGreaterThanOrEqual(8);+ expect(floatingOnly?.floatingPanels?.[0].y).toBeGreaterThanOrEqual(38);+ expect(floatingOnly?.floatingPanels?.[0].collapsed).toBe(true);+ });});describe('Activated Components (BrushSizePalette, StatusBar, DocumentTabBar) in Both Themes', () => {@@ -555,4 +678,105 @@ describe('Activated Components (BrushSizePalette, StatusBar, DocumentTabBar) inexpect(popoverInBody!.style.top).toBe('72px');expect(popoverInBody!.style.left).toBe('220px');});++ it('renders FloatingPanelWindow with collapse ("-"), pin/reattach, and close controls that toggle body visibility', () => {+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;+ Object.defineProperty(globalThis, 'localStorage', {+ value: createMemoryStorage(),+ configurable: true,+ writable: true,+ });+ useWorkspaceStore.reset();++ try {+ workspaceStoreActions.detachPanel('sub-view', { x: 260, y: 120, width: 320, height: 340 });+ const getFp = () =>+ (useWorkspaceStore.getState().layout.floatingPanels ?? []).find((f) =>+ f.panelIds.includes('sub-view')+ )!;++ const renderFloating = () => {+ const fp = getFp();+ act(() => {+ if (!root) root = createRoot(dom.container as unknown as Element);+ root.render(+ <FloatingPanelWindow+ panel={fp}+ renderPanelIcon={renderPanelIcon}+ renderPanelBody={(panelId) => (+ <div data-testid={`floating-inner-${panelId}`}>Sub View Body</div>+ )}+ onStartHeaderDrag={() => {}}+ onStartTabDrag={() => {}}+ />+ );+ });+ };++ renderFloating();++ const body = document.body as unknown as MiniEl;+ expect(body.findByAttr('data-testid', 'floating-panel-sub-view')).not.toBeNull();+ expect(body.findByAttr('data-testid', 'floating-panel-body-sub-view')).not.toBeNull();+ expect(body.findByAttr('data-testid', 'floating-inner-sub-view')?.textContent).toBe(+ 'Sub View Body'+ );++ // Tap "-" button in upper-right corner to collapse/hide the panel body+ const collapseBtn = body.findByAttr('data-testid', 'floating-collapse-btn-sub-view');+ expect(collapseBtn).not.toBeNull();+ const reactPropsKey = Object.keys(collapseBtn!).find((k) => k.startsWith('__reactProps'));+ const reactProps = (+ collapseBtn as unknown as Record<string, { onClick?: (e: unknown) => void }>+ )[reactPropsKey!];+ act(() => {+ reactProps.onClick?.({ stopPropagation: () => {}, preventDefault: () => {} });+ });++ expect(getFp().collapsed).toBe(true);+ renderFloating();++ // Title bar remains floating, body is hidden+ const collapsedPanel = body.findByAttr('data-testid', 'floating-panel-sub-view');+ expect(collapsedPanel?.getAttribute('data-collapsed')).toBe('true');+ expect(body.findByAttr('data-testid', 'floating-panel-body-sub-view')).toBeNull();++ // Tap "-" again to restore body+ const expandBtn = body.findByAttr('data-testid', 'floating-collapse-btn-sub-view');+ const expandKey = Object.keys(expandBtn!).find((k) => k.startsWith('__reactProps'));+ const expandProps = (+ expandBtn as unknown as Record<string, { onClick?: (e: unknown) => void }>+ )[expandKey!];+ act(() => {+ expandProps.onClick?.({ stopPropagation: () => {}, preventDefault: () => {} });+ });+ expect(getFp().collapsed).toBe(false);+ renderFloating();+ expect(body.findByAttr('data-testid', 'floating-panel-body-sub-view')).not.toBeNull();++ // Tap Pin button to reattach back to dock+ const pinBtn = body.findByAttr('data-testid', 'floating-pin-btn-sub-view');+ expect(pinBtn).not.toBeNull();+ const pinKey = Object.keys(pinBtn!).find((k) => k.startsWith('__reactProps'));+ const pinProps = (pinBtn as unknown as Record<string, { onClick?: (e: unknown) => void }>)[+ pinKey!+ ];+ act(() => {+ pinProps.onClick?.({ stopPropagation: () => {}, preventDefault: () => {} });+ });++ expect(findFloatingPanelLocation(useWorkspaceStore.getState().layout, 'sub-view')).toBeNull();+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'sub-view')).not.toBeNull();+ } finally {+ if (prevStorage === undefined) {+ delete (globalThis as unknown as Record<string, unknown>).localStorage;+ } else {+ Object.defineProperty(globalThis, 'localStorage', {+ value: prevStorage,+ configurable: true,+ writable: true,+ });+ }+ }+ });});diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.tsindex 13cd883..9b80478 100644--- a/src/utils/transformEngine.ts+++ b/src/utils/transformEngine.ts@@ -1,4 +1,22 @@-import { LayerItem, Point2D, isFolderLikeLayer } from '../types/editor';+import { DirtyRect, LayerItem, Point2D, isFolderLikeLayer } from '../types/editor';+import {+ PixelBuffer,+ isExactQuadTranslation,+ lanczos3Weight,+ renderLosslessAffineChunk,+} from './transformResampler';++export {+ type PixelBuffer,+ type AffineTransformParams,+ type LosslessAffineSpec,+ lanczos3Weight,+ resolveLosslessAffineSpec,+ renderLosslessAffineChunk,+ resampleAffineChunkCpu,+ extractCanvasPixelBuffer,+ processAffineTransformChunks,+} from './transformResampler';/*** Computes the 3x3 projective transformation (homography) parameters@@ -291,16 +309,19 @@ const MESH_FRAGMENT_SHADER_ES1 = `);}- vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize, vec2 maxIdx) {- float y = (clamp(base.y + dy, 0.0, maxIdx.y) + 0.5) * invSize.y;- float x0 = (clamp(base.x - 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x1 = (clamp(base.x, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x2 = (clamp(base.x + 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x3 = (clamp(base.x + 2.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- return texture2D(u_tex, vec2(x0, y)) * wx.x- + texture2D(u_tex, vec2(x1, y)) * wx.y- + texture2D(u_tex, vec2(x2, y)) * wx.z- + texture2D(u_tex, vec2(x3, y)) * wx.w;+ vec4 fetchTexel(float x, float y, vec2 invSize) {+ if (x < 0.0 || x >= u_texSize.x || y < 0.0 || y >= u_texSize.y) {+ return vec4(0.0);+ }+ return texture2D(u_tex, vec2((x + 0.5) * invSize.x, (y + 0.5) * invSize.y));+ }++ vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize) {+ float y = base.y + dy;+ return fetchTexel(base.x - 1.0, y, invSize) * wx.x+ + fetchTexel(base.x, y, invSize) * wx.y+ + fetchTexel(base.x + 1.0, y, invSize) * wx.z+ + fetchTexel(base.x + 2.0, y, invSize) * wx.w;}void main() {@@ -310,12 +331,19 @@ const MESH_FRAGMENT_SHADER_ES1 = `vec4 wx = cubicWeights(f.x);vec4 wy = cubicWeights(f.y);vec2 invSize = 1.0 / u_texSize;- vec2 maxIdx = u_texSize - 1.0;- vec4 c = fetchRow(base, -1.0, wx, invSize, maxIdx) * wy.x- + fetchRow(base, 0.0, wx, invSize, maxIdx) * wy.y- + fetchRow(base, 1.0, wx, invSize, maxIdx) * wy.z- + fetchRow(base, 2.0, wx, invSize, maxIdx) * wy.w;+ vec4 c = fetchRow(base, -1.0, wx, invSize) * wy.x+ + fetchRow(base, 0.0, wx, invSize) * wy.y+ + fetchRow(base, 1.0, wx, invSize) * wy.z+ + fetchRow(base, 2.0, wx, invSize) * wy.w;++ vec4 n00 = fetchTexel(base.x, base.y, invSize);+ vec4 n10 = fetchTexel(base.x + 1.0, base.y, invSize);+ vec4 n01 = fetchTexel(base.x, base.y + 1.0, invSize);+ vec4 n11 = fetchTexel(base.x + 1.0, base.y + 1.0, invSize);+ vec4 lo = min(min(n00, n10), min(n01, n11));+ vec4 hi = max(max(n00, n10), max(n01, n11));+ c = clamp(c, lo, hi);float a = clamp(c.a, 0.0, 1.0);vec3 rgb = clamp(c.rgb, vec3(0.0), vec3(a));@@ -328,10 +356,11 @@ const MESH_VERTEX_SHADER_ES3 = `#version 300 esin vec2 a_uv;uniform vec2 u_origin;uniform vec2 u_size;+ uniform float u_flipY;out vec2 v_uv;void main() {vec2 norm = (a_pos - u_origin) / u_size;- gl_Position = vec4(norm.x * 2.0 - 1.0, 1.0 - norm.y * 2.0, 0.0, 1.0);+ gl_Position = vec4(norm.x * 2.0 - 1.0, (norm.y * 2.0 - 1.0) * u_flipY, 0.0, 1.0);v_uv = a_uv;}`;@@ -340,66 +369,136 @@ const MESH_FRAGMENT_SHADER_ES3 = `#version 300 esprecision highp float;uniform sampler2D u_tex;uniform vec2 u_texSize;+ uniform int u_outputStraight;in vec2 v_uv;out vec4 outColor;- vec4 cubicWeights(float f) {- float f2 = f * f;- float f3 = f2 * f;- return vec4(- -0.5 * f + f2 - 0.5 * f3,- 1.0 - 2.5 * f2 + 1.5 * f3,- 0.5 * f + 2.0 * f2 - 1.5 * f3,- -0.5 * f2 + 0.5 * f3- );+ const float PI = 3.14159265358979323846;++ float lanczos3(float x) {+ float ax = abs(x);+ if (ax < 1e-5) return 1.0;+ if (ax >= 3.0) return 0.0;+ float pix = PI * ax;+ return (3.0 * sin(pix) * sin(pix * (1.0 / 3.0))) / (pix * pix);}- vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize, vec2 maxIdx) {- float y = (clamp(base.y + dy, 0.0, maxIdx.y) + 0.5) * invSize.y;- float x0 = (clamp(base.x - 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x1 = (clamp(base.x, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x2 = (clamp(base.x + 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- float x3 = (clamp(base.x + 2.0, 0.0, maxIdx.x) + 0.5) * invSize.x;- return texture(u_tex, vec2(x0, y)) * wx.x- + texture(u_tex, vec2(x1, y)) * wx.y- + texture(u_tex, vec2(x2, y)) * wx.z- + texture(u_tex, vec2(x3, y)) * wx.w;+ vec4 fetchPremul(int ix, int iy, ivec2 texSizeI) {+ if (ix < 0 || ix >= texSizeI.x || iy < 0 || iy >= texSizeI.y) {+ return vec4(0.0);+ }+ vec4 s = texelFetch(u_tex, ivec2(ix, iy), 0);+ return vec4(s.rgb * s.a, s.a);}- vec4 sampleBicubic(vec2 uv, vec2 invSize, vec2 maxIdx) {+ vec4 sampleBilinearPremul(vec2 texPos, ivec2 texSizeI) {+ vec2 base = floor(texPos);+ vec2 f = texPos - base;+ int bx = int(base.x);+ int by = int(base.y);+ vec4 c00 = fetchPremul(bx, by, texSizeI);+ vec4 c10 = fetchPremul(bx + 1, by, texSizeI);+ vec4 c01 = fetchPremul(bx, by + 1, texSizeI);+ vec4 c11 = fetchPremul(bx + 1, by + 1, texSizeI);+ return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y);+ }++ vec4 sampleLanczos3AR(vec2 uv, ivec2 texSizeI, bool antiRing) {vec2 texPos = uv * u_texSize - 0.5;vec2 base = floor(texPos);vec2 f = texPos - base;- vec4 wx = cubicWeights(f.x);- vec4 wy = cubicWeights(f.y);+ int bx = int(base.x);+ int by = int(base.y);++ float wx[6];+ float wy[6];+ float sumWx = 0.0;+ float sumWy = 0.0;+ for (int i = 0; i < 6; i++) {+ float offset = float(i - 2);+ float w1 = lanczos3(offset - f.x);+ float w2 = lanczos3(offset - f.y);+ wx[i] = w1;+ wy[i] = w2;+ sumWx += w1;+ sumWy += w2;+ }+ float invSumWx = abs(sumWx) > 1e-6 ? 1.0 / sumWx : 1.0;+ float invSumWy = abs(sumWy) > 1e-6 ? 1.0 / sumWy : 1.0;++ vec4 c = vec4(0.0);+ for (int j = 0; j < 6; j++) {+ int iy = by + j - 2;+ vec4 rowAcc = vec4(0.0);+ for (int i = 0; i < 6; i++) {+ rowAcc += fetchPremul(bx + i - 2, iy, texSizeI) * (wx[i] * invSumWx);+ }+ c += rowAcc * (wy[j] * invSumWy);+ }- vec4 c = fetchRow(base, -1.0, wx, invSize, maxIdx) * wy.x- + fetchRow(base, 0.0, wx, invSize, maxIdx) * wy.y- + fetchRow(base, 1.0, wx, invSize, maxIdx) * wy.z- + fetchRow(base, 2.0, wx, invSize, maxIdx) * wy.w;+ if (antiRing) {+ vec4 n00 = fetchPremul(bx, by, texSizeI);+ vec4 n10 = fetchPremul(bx + 1, by, texSizeI);+ vec4 n01 = fetchPremul(bx, by + 1, texSizeI);+ vec4 n11 = fetchPremul(bx + 1, by + 1, texSizeI);+ vec4 lo = min(min(n00, n10), min(n01, n11));+ vec4 hi = max(max(n00, n10), max(n01, n11));+ c = clamp(c, lo, hi);+ }float a = clamp(c.a, 0.0, 1.0);return vec4(clamp(c.rgb, vec3(0.0), vec3(a)), a);}void main() {- vec2 invSize = 1.0 / u_texSize;- vec2 maxIdx = u_texSize - 1.0;+ ivec2 texSizeI = ivec2(u_texSize + 0.5);vec2 du = dFdx(v_uv);vec2 dv = dFdy(v_uv);- float footprint = max(length(du * u_texSize), length(dv * u_texSize));-- if (footprint <= 1.35) {- outColor = sampleBicubic(v_uv, invSize, maxIdx);- } else {+ float footprintX = length(du * u_texSize);+ float footprintY = length(dv * u_texSize);+ float footprint = max(footprintX, footprintY);++ vec4 premul;+ if (footprint <= 1.25) {+ premul = sampleLanczos3AR(v_uv, texSizeI, true);+ } else if (footprint <= 2.25) {vec4 acc =- sampleBicubic(v_uv + du * -0.375 + dv * -0.125, invSize, maxIdx) +- sampleBicubic(v_uv + du * 0.125 + dv * -0.375, invSize, maxIdx) +- sampleBicubic(v_uv + du * 0.375 + dv * 0.125, invSize, maxIdx) +- sampleBicubic(v_uv + du * -0.125 + dv * 0.375, invSize, maxIdx);+ sampleLanczos3AR(v_uv + du * -0.375 + dv * -0.125, texSizeI, false) ++ sampleLanczos3AR(v_uv + du * 0.125 + dv * -0.375, texSizeI, false) ++ sampleLanczos3AR(v_uv + du * 0.375 + dv * 0.125, texSizeI, false) ++ sampleLanczos3AR(v_uv + du * -0.125 + dv * 0.375, texSizeI, false);vec4 res = acc * 0.25;float a = clamp(res.a, 0.0, 1.0);- outColor = vec4(clamp(res.rgb, vec3(0.0), vec3(a)), a);+ premul = vec4(clamp(res.rgb, vec3(0.0), vec3(a)), a);+ } else {+ // Adaptive Jacobian-scaled anisotropic supersampling for heavy downscaling (>2.25x)+ int nx = clamp(int(ceil(footprintX)), 2, 6);+ int ny = clamp(int(ceil(footprintY)), 2, 6);+ float invNx = 1.0 / float(nx);+ float invNy = 1.0 / float(ny);+ vec4 acc = vec4(0.0);+ for (int sy = 0; sy < 6; sy++) {+ if (sy >= ny) break;+ float fy = (float(sy) + 0.5) * invNy - 0.5;+ for (int sx = 0; sx < 6; sx++) {+ if (sx >= nx) break;+ float fx = (float(sx) + 0.5) * invNx - 0.5;+ vec2 sampleUv = v_uv + du * fx + dv * fy;+ acc += sampleBilinearPremul(sampleUv * u_texSize - 0.5, texSizeI);+ }+ }+ vec4 res = acc * (invNx * invNy);+ float a = clamp(res.a, 0.0, 1.0);+ premul = vec4(clamp(res.rgb, vec3(0.0), vec3(a)), a);+ }++ if (u_outputStraight == 1) {+ if (premul.a <= 1e-4) {+ discard;+ }+ outColor = vec4(clamp(premul.rgb / premul.a, 0.0, 1.0), premul.a);+ } else {+ outColor = premul;}}`;@@ -408,15 +507,22 @@ class WebGlMeshWarpRenderer {private static instance: WebGlMeshWarpRenderer | null = null;private canvas: HTMLCanvasElement | null = null;private gl: WebGLRenderingContext | null = null;+ private isWebGl2 = false;private program: WebGLProgram | null = null;private vertexBuffer: WebGLBuffer | null = null;private texture: WebGLTexture | null = null;+ private fbo: WebGLFramebuffer | null = null;+ private fboTexture: WebGLTexture | null = null;+ private fboW = 0;+ private fboH = 0;private posLoc = -1;private uvLoc = -1;private originLoc: WebGLUniformLocation | null = null;private sizeLoc: WebGLUniformLocation | null = null;private texSizeLoc: WebGLUniformLocation | null = null;private texLoc: WebGLUniformLocation | null = null;+ private flipYLoc: WebGLUniformLocation | null = null;+ private outputStraightLoc: WebGLUniformLocation | null = null;private maxDim = 0;private vertexData = new Float32Array(0);private ready = false;@@ -489,9 +595,8 @@ class WebGlMeshWarpRenderer {const gl = (gl2 || canvas.getContext('webgl', attrs)) as WebGLRenderingContext | null;if (!gl) return;- const program =- (gl2 ? this.compileProgram(gl, MESH_VERTEX_SHADER_ES3, MESH_FRAGMENT_SHADER_ES3) : null) ||- this.compileProgram(gl, MESH_VERTEX_SHADER_ES1, MESH_FRAGMENT_SHADER_ES1);+ const es3Prog = gl2 ? this.compileProgram(gl, MESH_VERTEX_SHADER_ES3, MESH_FRAGMENT_SHADER_ES3) : null;+ const program = es3Prog || this.compileProgram(gl, MESH_VERTEX_SHADER_ES1, MESH_FRAGMENT_SHADER_ES1);if (!program) return;const vertexBuffer = gl.createBuffer();@@ -511,15 +616,22 @@ class WebGlMeshWarpRenderer {this.canvas = canvas;this.gl = gl;+ this.isWebGl2 = Boolean(es3Prog && gl2);this.program = program;this.vertexBuffer = vertexBuffer;this.texture = texture;+ if (this.isWebGl2) {+ this.fbo = gl.createFramebuffer();+ this.fboTexture = gl.createTexture();+ }this.posLoc = posLoc;this.uvLoc = uvLoc;this.originLoc = gl.getUniformLocation(program, 'u_origin');this.sizeLoc = gl.getUniformLocation(program, 'u_size');this.texSizeLoc = gl.getUniformLocation(program, 'u_texSize');this.texLoc = gl.getUniformLocation(program, 'u_tex');+ this.flipYLoc = gl.getUniformLocation(program, 'u_flipY');+ this.outputStraightLoc = gl.getUniformLocation(program, 'u_outputStraight');this.maxDim = Math.min(maxTex || 4096, maxVpDim || 4096);this.ready = true;} catch {@@ -527,6 +639,68 @@ class WebGlMeshWarpRenderer {}}+ private fillGridVertices(grid: Point2D[][], totalRows: number, totalCols: number): number {+ const vertexCount = totalRows * totalCols * 6;+ const neededFloats = vertexCount * 4;+ if (this.vertexData.length < neededFloats) {+ this.vertexData = new Float32Array(neededFloats);+ }++ const buf = this.vertexData;+ let offset = 0;+ for (let j = 0; j < totalRows; j++) {+ const v0 = j / totalRows;+ const v1 = (j + 1) / totalRows;+ const row0 = grid[j];+ const row1 = grid[j + 1];+ for (let i = 0; i < totalCols; i++) {+ const u0 = i / totalCols;+ const u1 = (i + 1) / totalCols;+ const p00 = row0[i];+ const p10 = row0[i + 1];+ const p11 = row1[i + 1];+ const p01 = row1[i];++ // Triangle 1: (0,0) - (1,0) - (0,1)+ buf[offset++] = p00.x; buf[offset++] = p00.y; buf[offset++] = u0; buf[offset++] = v0;+ buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;+ buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;++ // Triangle 2: (1,0) - (1,1) - (0,1)+ buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;+ buf[offset++] = p11.x; buf[offset++] = p11.y; buf[offset++] = u1; buf[offset++] = v1;+ buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;+ }+ }+ return vertexCount;+ }++ private ensureFbo(gl: WebGL2RenderingContext, w: number, h: number): boolean {+ if (!this.fbo || !this.fboTexture) return false;+ if (this.fboW === w && this.fboH === h) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo);+ return true;+ }+ gl.bindTexture(gl.TEXTURE_2D, this.fboTexture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);++ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.fboTexture, 0);+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ this.fboW = 0;+ this.fboH = 0;+ return false;+ }+ this.fboW = w;+ this.fboH = h;+ return true;+ }+renderGrid(ctx: CanvasRenderingContext2D,sourceCanvas: HTMLCanvasElement,@@ -588,49 +762,21 @@ class WebGlMeshWarpRenderer {if (outW <= 0 || outH <= 0) return true;if (outW > this.maxDim || outH > this.maxDim) return false;- const vertexCount = totalRows * totalCols * 6;+ const vertexCount = this.fillGridVertices(grid, totalRows, totalCols);const neededFloats = vertexCount * 4;- if (this.vertexData.length < neededFloats) {- this.vertexData = new Float32Array(neededFloats);- }-- const buf = this.vertexData;- let offset = 0;- for (let j = 0; j < totalRows; j++) {- const v0 = j / totalRows;- const v1 = (j + 1) / totalRows;- const row0 = grid[j];- const row1 = grid[j + 1];- for (let i = 0; i < totalCols; i++) {- const u0 = i / totalCols;- const u1 = (i + 1) / totalCols;- const p00 = row0[i];- const p10 = row0[i + 1];- const p11 = row1[i + 1];- const p01 = row1[i];-- // Triangle 1: (0,0) - (1,0) - (0,1)- buf[offset++] = p00.x; buf[offset++] = p00.y; buf[offset++] = u0; buf[offset++] = v0;- buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;- buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;-- // Triangle 2: (1,0) - (1,1) - (0,1)- buf[offset++] = p10.x; buf[offset++] = p10.y; buf[offset++] = u1; buf[offset++] = v0;- buf[offset++] = p11.x; buf[offset++] = p11.y; buf[offset++] = u1; buf[offset++] = v1;- buf[offset++] = p01.x; buf[offset++] = p01.y; buf[offset++] = u0; buf[offset++] = v1;- }- }if (this.canvas.width !== outW) this.canvas.width = outW;if (this.canvas.height !== outH) this.canvas.height = outH;+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);gl.viewport(0, 0, outW, outH);gl.useProgram(this.program);gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, this.texture);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ // WebGL2 ES3 shader performs exact float premultiplication; ES1 expects premultiplied upload+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, !this.isWebGl2);gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);@@ -641,9 +787,11 @@ class WebGlMeshWarpRenderer {gl.uniform2f(this.originLoc, originX, originY);gl.uniform2f(this.sizeLoc, outW, outH);gl.uniform2f(this.texSizeLoc, sw, sh);+ if (this.flipYLoc) gl.uniform1f(this.flipYLoc, -1.0);+ if (this.outputStraightLoc) gl.uniform1i(this.outputStraightLoc, 0);gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);- gl.bufferData(gl.ARRAY_BUFFER, buf.subarray(0, neededFloats), gl.STREAM_DRAW);+ gl.bufferData(gl.ARRAY_BUFFER, this.vertexData.subarray(0, neededFloats), gl.STREAM_DRAW);gl.enableVertexAttribArray(this.posLoc);gl.vertexAttribPointer(this.posLoc, 2, gl.FLOAT, false, 16, 0);gl.enableVertexAttribArray(this.uvLoc);@@ -659,6 +807,122 @@ class WebGlMeshWarpRenderer {ctx.drawImage(this.canvas, originX, originY);return true;}++ /**+ * Renders a deformed mesh/perspective grid directly from straight-alpha pixels into straight-alpha+ * RGBA chunks via WebGL2 FBO + readPixels (zero Canvas 2D round-trip, single texture upload).+ */+ renderGridToChunks(+ source: PixelBuffer,+ grid: Point2D[][],+ totalRows: number,+ totalCols: number,+ destRect: DirtyRect,+ chunkSize: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void+ ): boolean {+ if (+ !this.ready ||+ !this.isWebGl2 ||+ !this.gl ||+ !this.program ||+ !this.vertexBuffer ||+ !this.texture ||+ !this.fbo ||+ !this.fboTexture+ ) {+ return false;+ }+ const gl = this.gl as WebGL2RenderingContext;+ if (gl.isContextLost()) {+ this.ready = false;+ return false;+ }++ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || sw > this.maxDim || sh > this.maxDim || chunkSize > this.maxDim) {+ return false;+ }++ for (let j = 0; j <= totalRows; j++) {+ const row = grid[j];+ for (let i = 0; i <= totalCols; i++) {+ if (!Number.isFinite(row[i].x) || !Number.isFinite(row[i].y)) return false;+ }+ }++ const vertexCount = this.fillGridVertices(grid, totalRows, totalCols);+ const neededFloats = vertexCount * 4;+ const srcBytes =+ source.data instanceof Uint8Array+ ? source.data+ : new Uint8Array(source.data.buffer, source.data.byteOffset, source.data.byteLength);++ // Upload source texture ONCE across all chunks (straight alpha, float premul in shader)+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.texture);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, sw, sh, 0, gl.RGBA, gl.UNSIGNED_BYTE, srcBytes);++ gl.useProgram(this.program);+ gl.uniform1i(this.texLoc, 0);+ gl.uniform2f(this.texSizeLoc, sw, sh);+ if (this.flipYLoc) gl.uniform1f(this.flipYLoc, 1.0);+ if (this.outputStraightLoc) gl.uniform1i(this.outputStraightLoc, 1);++ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, this.vertexData.subarray(0, neededFloats), gl.STREAM_DRAW);+ gl.enableVertexAttribArray(this.posLoc);+ gl.vertexAttribPointer(this.posLoc, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(this.uvLoc);+ gl.vertexAttribPointer(this.uvLoc, 2, gl.FLOAT, false, 16, 8);++ gl.disable(gl.CULL_FACE);+ gl.disable(gl.BLEND);++ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;++ try {+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ if (!this.ensureFbo(gl, cw, ch)) return false;++ gl.viewport(0, 0, cw, ch);+ gl.uniform2f(this.originLoc, cx, cy);+ gl.uniform2f(this.sizeLoc, cw, ch);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.texture);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);++ const rawBytes = new Uint8Array(cw * ch * 4);+ gl.readPixels(0, 0, cw, ch, gl.RGBA, gl.UNSIGNED_BYTE, rawBytes);+ const clamped = new Uint8ClampedArray(+ rawBytes.buffer,+ rawBytes.byteOffset,+ rawBytes.byteLength+ );+ onChunk(clamped, cx, cy, cw, ch);+ }+ }+ return true;+ } catch {+ return false;+ } finally {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ }+ }}function renderDeformedGrid(@@ -764,6 +1028,348 @@ export function renderMeshWarp(renderDeformedGrid(ctx, sourceCanvas, grid, totalRows, totalCols);}+/**+ * Checks if a Catmull-Rom mesh lattice is an exact unmodified integer translation of (sw x sh).+ */+function isExactMeshTranslation(+ meshPoints: Point2D[][],+ sw: number,+ sh: number+): { x: number; y: number } | null {+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (rows < 2 || cols < 2) return null;+ const originX = Math.round(meshPoints[0][0].x);+ const originY = Math.round(meshPoints[0][0].y);+ for (let r = 0; r < rows; r++) {+ const v = r / (rows - 1);+ const expectedY = originY + v * sh;+ for (let c = 0; c < cols; c++) {+ const u = c / (cols - 1);+ const expectedX = originX + u * sw;+ const p = meshPoints[r][c];+ if (Math.abs(p.x - expectedX) > 1e-4 || Math.abs(p.y - expectedY) > 1e-4) {+ return null;+ }+ }+ }+ return { x: originX, y: originY };+}++/**+ * High-precision CPU inverse-homography perspective chunk resampler using+ * float-premultiplied Anti-Ringing Lanczos-3 and footprint-scaled downsampling.+ */+function resamplePerspectiveChunkCpu(+ source: PixelBuffer,+ quad: [Point2D, Point2D, Point2D, Point2D],+ chunkX: number,+ chunkY: number,+ chunkW: number,+ chunkH: number+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(chunkW * chunkH * 4);+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0) return out;++ const H = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);+ // Adjugate of 3x3 homography H = [[a,b,c],[d,e,f],[g,h,1]]+ const ia = H.e - H.f * H.h;+ const ib = H.c * H.h - H.b;+ const ic = H.b * H.f - H.c * H.e;+ const id = H.f * H.g - H.d;+ const ie = H.a - H.c * H.g;+ const if_ = H.c * H.d - H.a * H.f;+ const ig = H.d * H.h - H.e * H.g;+ const ih = H.b * H.g - H.a * H.h;+ const ii = H.a * H.e - H.b * H.d;++ const srcData = source.data;+ const wxBuf = new Float32Array(20);+ const wyBuf = new Float32Array(20);++ for (let py = 0; py < chunkH; py++) {+ const docY = chunkY + py + 0.5;+ let dstOff = py * chunkW * 4;+ for (let px = 0; px < chunkW; px++, dstOff += 4) {+ const docX = chunkX + px + 0.5;+ const denom = ig * docX + ih * docY + ii;+ if (Math.abs(denom) < 1e-7) continue;++ const invDenom = 1.0 / denom;+ const numU = ia * docX + ib * docY + ic;+ const numV = id * docX + ie * docY + if_;+ const u = numU * invDenom;+ const v = numV * invDenom;+ if (u < -0.05 || u > 1.05 || v < -0.05 || v > 1.05) continue;++ const sx = u * sw - 0.5;+ const sy = v * sh - 0.5;++ // Exact analytical Jacobian of (sx, sy) with respect to (docX, docY)+ const invD2 = invDenom * invDenom;+ const dsx_dx = ((ia * denom - numU * ig) * invD2) * sw;+ const dsx_dy = ((ib * denom - numU * ih) * invD2) * sw;+ const dsy_dx = ((id * denom - numV * ig) * invD2) * sh;+ const dsy_dy = ((ie * denom - numV * ih) * invD2) * sh;++ const footX = Math.hypot(dsx_dx, dsx_dy);+ const footY = Math.hypot(dsy_dx, dsy_dy);+ const filterScaleX = Math.min(3.0, Math.max(1.0, footX));+ const filterScaleY = Math.min(3.0, Math.max(1.0, footY));+ const supportX = 3.0 * filterScaleX;+ const supportY = 3.0 * filterScaleY;++ if (sx < -supportX || sx > sw - 1 + supportX || sy < -supportY || sy > sh - 1 + supportY) {+ continue;+ }++ const invFX = 1.0 / filterScaleX;+ const invFY = 1.0 / filterScaleY;+ const xStart = Math.ceil(sx - supportX);+ const xEnd = Math.floor(sx + supportX);+ const yStart = Math.ceil(sy - supportY);+ const yEnd = Math.floor(sy + supportY);+ const countX = Math.min(20, Math.max(0, xEnd - xStart + 1));+ const countY = Math.min(20, Math.max(0, yEnd - yStart + 1));+ if (countX <= 0 || countY <= 0) continue;++ let sumWx = 0;+ for (let i = 0; i < countX; i++) {+ const w = lanczos3Weight((xStart + i - sx) * invFX);+ wxBuf[i] = w;+ sumWx += w;+ }+ if (Math.abs(sumWx) < 1e-6) continue;+ const invSumWx = 1.0 / sumWx;+ for (let i = 0; i < countX; i++) wxBuf[i] *= invSumWx;++ let sumWy = 0;+ for (let j = 0; j < countY; j++) {+ const w = lanczos3Weight((yStart + j - sy) * invFY);+ wyBuf[j] = w;+ sumWy += w;+ }+ if (Math.abs(sumWy) < 1e-6) continue;+ const invSumWy = 1.0 / sumWy;+ for (let j = 0; j < countY; j++) wyBuf[j] *= invSumWy;++ let accR = 0, accG = 0, accB = 0, accA = 0;+ for (let j = 0; j < countY; j++) {+ const iy = yStart + j;+ if (iy < 0 || iy >= sh) continue;+ const wy = wyBuf[j];+ if (wy === 0) continue;+ const rowBase = iy * sw;+ let rR = 0, rG = 0, rB = 0, rA = 0;+ for (let i = 0; i < countX; i++) {+ const ix = xStart + i;+ if (ix < 0 || ix >= sw) continue;+ const off = (rowBase + ix) << 2;+ const a = srcData[off + 3];+ if (a === 0) continue;+ const wa = wxBuf[i] * (a * (1 / 255));+ rR += srcData[off] * wa;+ rG += srcData[off + 1] * wa;+ rB += srcData[off + 2] * wa;+ rA += wa;+ }+ accR += rR * wy;+ accG += rG * wy;+ accB += rB * wy;+ accA += rA * wy;+ }++ if (filterScaleX <= 1.25 && filterScaleY <= 1.25) {+ const bx = Math.floor(sx);+ const by = Math.floor(sy);+ let loR = Infinity, hiR = -Infinity;+ let loG = Infinity, hiG = -Infinity;+ let loB = Infinity, hiB = -Infinity;+ let loA = Infinity, hiA = -Infinity;+ for (let ny = by; ny <= by + 1; ny++) {+ const yOk = ny >= 0 && ny < sh;+ const rowBase = ny * sw;+ for (let nx = bx; nx <= bx + 1; nx++) {+ let nr = 0, ng = 0, nb = 0, na = 0;+ if (yOk && nx >= 0 && nx < sw) {+ const o = (rowBase + nx) << 2;+ na = srcData[o + 3] * (1 / 255);+ nr = srcData[o] * na;+ ng = srcData[o + 1] * na;+ nb = srcData[o + 2] * na;+ }+ if (nr < loR) loR = nr; if (nr > hiR) hiR = nr;+ if (ng < loG) loG = ng; if (ng > hiG) hiG = ng;+ if (nb < loB) loB = nb; if (nb > hiB) hiB = nb;+ if (na < loA) loA = na; if (na > hiA) hiA = na;+ }+ }+ if (accR < loR) accR = loR; else if (accR > hiR) accR = hiR;+ if (accG < loG) accG = loG; else if (accG > hiG) accG = hiG;+ if (accB < loB) accB = loB; else if (accB > hiB) accB = hiB;+ if (accA < loA) accA = loA; else if (accA > hiA) accA = hiA;+ }++ if (accA <= 1e-4) continue;+ if (accA > 1.0) accA = 1.0;+ const maxRgb = accA * 255.0;+ if (accR < 0) accR = 0; else if (accR > maxRgb) accR = maxRgb;+ if (accG < 0) accG = 0; else if (accG > maxRgb) accG = maxRgb;+ if (accB < 0) accB = 0; else if (accB > maxRgb) accB = maxRgb;+ const invA = 1.0 / accA;+ out[dstOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dstOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dstOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dstOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255.0)));+ }+ }++ return out;+}++/**+ * High-precision chunked Perspective Quad commit pipeline (lossless identity -> WebGL2 -> CPU AR-Lanczos3).+ */+export function processPerspectiveTransformChunks(+ source: PixelBuffer,+ quad: [Point2D, Point2D, Point2D, Point2D],+ destRect: DirtyRect,+ chunkSize: number,+ subdivisions: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void+): boolean {+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || subdivisions <= 0) return false;++ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;++ const exactShift = isExactQuadTranslation(quad, sw, sh);+ if (exactShift) {+ const spec = {+ quarterTurn: 0 as const,+ flipH: false,+ flipV: false,+ destOriginX: exactShift.x,+ destOriginY: exactShift.y,+ destWidth: sw,+ destHeight: sh,+ };+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ onChunk(renderLosslessAffineChunk(source, spec, cx, cy, cw, ch), cx, cy, cw, ch);+ }+ }+ return true;+ }++ const homography = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);+ const grid: Point2D[][] = [];+ for (let j = 0; j <= subdivisions; j++) {+ const row: Point2D[] = [];+ const v = j / subdivisions;+ for (let i = 0; i <= subdivisions; i++) {+ const u = i / subdivisions;+ row.push(evaluateHomography(homography, u, v));+ }+ grid.push(row);+ }++ if (+ WebGlMeshWarpRenderer.getInstance().renderGridToChunks(+ source,+ grid,+ subdivisions,+ subdivisions,+ destRect,+ chunkSize,+ onChunk+ )+ ) {+ return true;+ }++ // Exact CPU inverse-homography Anti-Ringing Lanczos-3 fallback+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ onChunk(resamplePerspectiveChunkCpu(source, quad, cx, cy, cw, ch), cx, cy, cw, ch);+ }+ }+ return true;+}++/**+ * High-precision chunked Mesh Warp commit pipeline (lossless identity -> WebGL2 straight-alpha FBO).+ * Returns false if WebGL2 is unavailable so caller can fall back to Canvas 2D triangle slicing.+ */+export function processMeshWarpTransformChunks(+ source: PixelBuffer,+ meshPoints: Point2D[][],+ destRect: DirtyRect,+ chunkSize: number,+ subPerCell: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void+): boolean {+ const sw = source.width;+ const sh = source.height;+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (sw <= 0 || sh <= 0 || subPerCell <= 0 || rows < 2 || cols < 2) return false;++ const exactShift = isExactMeshTranslation(meshPoints, sw, sh);+ if (exactShift) {+ const spec = {+ quarterTurn: 0 as const,+ flipH: false,+ flipV: false,+ destOriginX: exactShift.x,+ destOriginY: exactShift.y,+ destWidth: sw,+ destHeight: sh,+ };+ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ onChunk(renderLosslessAffineChunk(source, spec, cx, cy, cw, ch), cx, cy, cw, ch);+ }+ }+ return true;+ }++ const totalCols = (cols - 1) * subPerCell;+ const totalRows = (rows - 1) * subPerCell;+ const grid: Point2D[][] = [];+ for (let j = 0; j <= totalRows; j++) {+ const row: Point2D[] = [];+ const v = j / totalRows;+ for (let i = 0; i <= totalCols; i++) {+ const u = i / totalCols;+ row.push(evaluateMeshSurface(meshPoints, u, v));+ }+ grid.push(row);+ }++ return WebGlMeshWarpRenderer.getInstance().renderGridToChunks(+ source,+ grid,+ totalRows,+ totalCols,+ destRect,+ chunkSize,+ onChunk+ );+}+/*** Creates default 4 perspective corner pins from bounds.* Order: [TL, TR, BR, BL]diff --git a/src/utils/transformResampler.ts b/src/utils/transformResampler.tsnew file mode 100644index 0000000..87e1072--- /dev/null+++ b/src/utils/transformResampler.ts@@ -0,0 +1,1198 @@+import { DirtyRect, Point2D } from '../types/editor';++export interface PixelBuffer {+ data: Uint8ClampedArray | Uint8Array;+ width: number;+ height: number;+}++export interface AffineTransformParams {+ x: number;+ y: number;+ width: number;+ height: number;+ rotation: number; // degrees+ flipH: boolean;+ flipV: boolean;+}++const PI = Math.PI;+const LANCZOS_A = 3;+const LANCZOS_LUT_RES = 1024;+const LANCZOS_LUT_SIZE = LANCZOS_A * LANCZOS_LUT_RES + 2;++const LANCZOS3_LUT = (() => {+ const lut = new Float32Array(LANCZOS_LUT_SIZE);+ lut[0] = 1.0;+ for (let i = 1; i < LANCZOS_LUT_SIZE; i++) {+ const x = i / LANCZOS_LUT_RES;+ if (x >= LANCZOS_A) {+ lut[i] = 0.0;+ } else {+ const pix = PI * x;+ lut[i] = (LANCZOS_A * Math.sin(pix) * Math.sin(pix / LANCZOS_A)) / (pix * pix);+ }+ }+ return lut;+})();++/**+ * Evaluates Lanczos-3 kernel weight for `x` (exact zero for |x| >= 3).+ */+export function lanczos3Weight(x: number): number {+ const ax = x < 0 ? -x : x;+ if (ax < 1e-6) return 1.0;+ if (ax >= LANCZOS_A) return 0.0;+ const fIdx = ax * LANCZOS_LUT_RES;+ const idx = fIdx | 0;+ const frac = fIdx - idx;+ return LANCZOS3_LUT[idx] + (LANCZOS3_LUT[idx + 1] - LANCZOS3_LUT[idx]) * frac;+}++/**+ * Normalizes an angle in degrees to [0, 360).+ */+export function normalizeRotationDeg(deg: number): number {+ const m = ((deg % 360) + 360) % 360;+ return Math.abs(m - 360) < 1e-6 ? 0 : m;+}++/**+ * Returns the exact orthogonal rotation step (0, 90, 180, 270) if `deg` is within epsilon, else null.+ */+export function getExactQuarterTurnDeg(deg: number): 0 | 90 | 180 | 270 | null {+ const m = normalizeRotationDeg(deg);+ if (Math.abs(m) < 1e-5 || Math.abs(m - 360) < 1e-5) return 0;+ if (Math.abs(m - 90) < 1e-5) return 90;+ if (Math.abs(m - 180) < 1e-5) return 180;+ if (Math.abs(m - 270) < 1e-5) return 270;+ return null;+}++export interface LosslessAffineSpec {+ quarterTurn: 0 | 90 | 180 | 270;+ flipH: boolean;+ flipV: boolean;+ destOriginX: number;+ destOriginY: number;+ destWidth: number;+ destHeight: number;+}++/**+ * Detects whether an affine transform is a 1:1 lossless integer pixel permutation+ * (pure move, flip H/V, and/or exact 90/180/270 rotation with unchanged dimensions).+ * For 90/270 rotations of odd x even layers, snaps the rotated origin to an integer+ * pixel grid so brush strokes never suffer a 0.5px subpixel blur.+ */+export function resolveLosslessAffineSpec(+ srcW: number,+ srcH: number,+ params: AffineTransformParams+): LosslessAffineSpec | null {+ if (srcW <= 0 || srcH <= 0) return null;+ if (+ Math.abs(params.width - srcW) > 1e-5 ||+ Math.abs(params.height - srcH) > 1e-5+ ) {+ return null;+ }++ const quarterTurn = getExactQuarterTurnDeg(params.rotation);+ if (quarterTurn === null) return null;++ if (quarterTurn === 0 || quarterTurn === 180) {+ const rx = Math.round(params.x);+ const ry = Math.round(params.y);+ if (Math.abs(params.x - rx) > 1e-5 || Math.abs(params.y - ry) > 1e-5) {+ return null;+ }+ return {+ quarterTurn,+ flipH: params.flipH,+ flipV: params.flipV,+ destOriginX: rx,+ destOriginY: ry,+ destWidth: srcW,+ destHeight: srcH,+ };+ }++ // 90 or 270 degree rotation: snap rotated top-left to integer grid to prevent+ // 0.5px half-pixel blurring when srcW and srcH have opposite parity.+ const midX = params.x + params.width * 0.5;+ const midY = params.y + params.height * 0.5;+ const rawOriginX = midX - srcH * 0.5;+ const rawOriginY = midY - srcW * 0.5;+ const snappedX = Math.round(rawOriginX);+ const snappedY = Math.round(rawOriginY);+ // Allow exact integer or half-integer (from odd/even parity)+ if (Math.abs(rawOriginX - snappedX) > 0.5001 || Math.abs(rawOriginY - snappedY) > 0.5001) {+ return null;+ }++ return {+ quarterTurn,+ flipH: params.flipH,+ flipV: params.flipV,+ destOriginX: snappedX,+ destOriginY: snappedY,+ destWidth: srcH,+ destHeight: srcW,+ };+}++/**+ * Performs a bit-exact lossless straight-alpha copy of a chunk of `source` under `spec`.+ */+export function renderLosslessAffineChunk(+ source: PixelBuffer,+ spec: LosslessAffineSpec,+ chunkX: number,+ chunkY: number,+ chunkW: number,+ chunkH: number+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(chunkW * chunkH * 4);+ const sw = source.width;+ const sh = source.height;+ const srcData = source.data;+ const { quarterTurn, flipH, flipV, destOriginX, destOriginY, destWidth, destHeight } = spec;++ const x0 = Math.max(0, destOriginX - chunkX);+ const y0 = Math.max(0, destOriginY - chunkY);+ const x1 = Math.min(chunkW, destOriginX + destWidth - chunkX);+ const y1 = Math.min(chunkH, destOriginY + destHeight - chunkY);+ if (x1 <= x0 || y1 <= y0) return out;++ // Ultra-fast row copy for pure integer translation (no flip, no rotation)+ if (quarterTurn === 0 && !flipH && !flipV) {+ const copyBytes = (x1 - x0) * 4;+ for (let cy = y0; cy < y1; cy++) {+ const sy = chunkY + cy - destOriginY;+ const sx = chunkX + x0 - destOriginX;+ const srcOff = (sy * sw + sx) * 4;+ const dstOff = (cy * chunkW + x0) * 4;+ out.set(srcData.subarray(srcOff, srcOff + copyBytes), dstOff);+ }+ return out;+ }++ for (let cy = y0; cy < y1; cy++) {+ const ly = chunkY + cy - destOriginY;+ let dstOff = (cy * chunkW + x0) * 4;+ for (let cx = x0; cx < x1; cx++, dstOff += 4) {+ const lx = chunkX + cx - destOriginX;+ let fx: number;+ let fy: number;+ if (quarterTurn === 0) {+ fx = lx;+ fy = ly;+ } else if (quarterTurn === 90) {+ // Forward: (fx, fy) -> (sh - 1 - fy, fx) => Inverse: fx = ly, fy = sh - 1 - lx+ fx = ly;+ fy = sh - 1 - lx;+ } else if (quarterTurn === 180) {+ fx = sw - 1 - lx;+ fy = sh - 1 - ly;+ } else {+ // 270 CW: Forward: (fx, fy) -> (fy, sw - 1 - fx) => Inverse: fx = sw - 1 - ly, fy = lx+ fx = sw - 1 - ly;+ fy = lx;+ }++ const sx = flipH ? sw - 1 - fx : fx;+ const sy = flipV ? sh - 1 - fy : fy;+ if (sx < 0 || sx >= sw || sy < 0 || sy >= sh) continue;++ const srcOff = (sy * sw + sx) * 4;+ out[dstOff] = srcData[srcOff];+ out[dstOff + 1] = srcData[srcOff + 1];+ out[dstOff + 2] = srcData[srcOff + 2];+ out[dstOff + 3] = srcData[srcOff + 3];+ }+ }++ return out;+}++/**+ * Separable 1D Lanczos-3 resample along X in float premultiplied RGBA.+ * Used both as a pre-downsampler for extreme >3x shrink ratios and for fast axis-aligned scaling.+ */+function resampleHorizontalLanczos3(+ src: PixelBuffer,+ targetW: number,+ flipH: boolean+): PixelBuffer {+ const sw = src.width;+ const sh = src.height;+ const dstW = Math.max(1, targetW);+ const out = new Uint8ClampedArray(dstW * sh * 4);+ const srcData = src.data;++ const scale = sw / dstW;+ const filterScale = scale > 1.0 ? scale : 1.0;+ const invFilterScale = 1.0 / filterScale;+ const support = LANCZOS_A * filterScale;+ const applyAntiRing = filterScale <= 1.25;++ // Precompute horizontal tap weights per destination column+ const maxTaps = Math.ceil(support * 2) + 3;+ const colStarts = new Int32Array(dstW);+ const colCounts = new Int32Array(dstW);+ const colCenterFloor = new Int32Array(dstW);+ const colWeights = new Float32Array(dstW * maxTaps);++ for (let dx = 0; dx < dstW; dx++) {+ const u = flipH ? dstW - 0.5 - dx : dx + 0.5;+ const srcX = u * scale - 0.5;+ colCenterFloor[dx] = Math.floor(srcX);+ const left = Math.ceil(srcX - support);+ const right = Math.floor(srcX + support);+ colStarts[dx] = left;+ const count = Math.max(0, right - left + 1);+ colCounts[dx] = count;++ let sumW = 0;+ const wBase = dx * maxTaps;+ for (let k = 0; k < count; k++) {+ const w = lanczos3Weight((left + k - srcX) * invFilterScale);+ colWeights[wBase + k] = w;+ sumW += w;+ }+ if (Math.abs(sumW) > 1e-6) {+ const invSum = 1.0 / sumW;+ for (let k = 0; k < count; k++) {+ colWeights[wBase + k] *= invSum;+ }+ }+ }++ for (let y = 0; y < sh; y++) {+ const srcRow = y * sw * 4;+ const dstRow = y * dstW * 4;+ for (let dx = 0; dx < dstW; dx++) {+ const left = colStarts[dx];+ const count = colCounts[dx];+ const wBase = dx * maxTaps;++ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;++ for (let k = 0; k < count; k++) {+ const ix = left + k;+ if (ix < 0 || ix >= sw) continue;+ const off = srcRow + (ix << 2);+ const a = srcData[off + 3];+ if (a === 0) continue;+ const w = colWeights[wBase + k];+ const af = a * (1 / 255);+ const wa = w * af;+ accR += srcData[off] * wa;+ accG += srcData[off + 1] * wa;+ accB += srcData[off + 2] * wa;+ accA += wa;+ }++ if (applyAntiRing) {+ const i0 = colCenterFloor[dx];+ const i1 = i0 + 1;+ let a0 = 0, r0 = 0, g0 = 0, b0 = 0;+ let a1 = 0, r1 = 0, g1 = 0, b1 = 0;+ if (i0 >= 0 && i0 < sw) {+ const o0 = srcRow + (i0 << 2);+ a0 = srcData[o0 + 3] * (1 / 255);+ r0 = srcData[o0] * a0;+ g0 = srcData[o0 + 1] * a0;+ b0 = srcData[o0 + 2] * a0;+ }+ if (i1 >= 0 && i1 < sw) {+ const o1 = srcRow + (i1 << 2);+ a1 = srcData[o1 + 3] * (1 / 255);+ r1 = srcData[o1] * a1;+ g1 = srcData[o1 + 1] * a1;+ b1 = srcData[o1 + 2] * a1;+ }+ const loR = r0 < r1 ? r0 : r1, hiR = r0 > r1 ? r0 : r1;+ const loG = g0 < g1 ? g0 : g1, hiG = g0 > g1 ? g0 : g1;+ const loB = b0 < b1 ? b0 : b1, hiB = b0 > b1 ? b0 : b1;+ const loA = a0 < a1 ? a0 : a1, hiA = a0 > a1 ? a0 : a1;+ if (accR < loR) accR = loR; else if (accR > hiR) accR = hiR;+ if (accG < loG) accG = loG; else if (accG > hiG) accG = hiG;+ if (accB < loB) accB = loB; else if (accB > hiB) accB = hiB;+ if (accA < loA) accA = loA; else if (accA > hiA) accA = hiA;+ }++ if (accA <= 1e-4) continue;+ if (accA > 1.0) accA = 1.0;+ const maxRgb = accA * 255.0;+ if (accR < 0) accR = 0; else if (accR > maxRgb) accR = maxRgb;+ if (accG < 0) accG = 0; else if (accG > maxRgb) accG = maxRgb;+ if (accB < 0) accB = 0; else if (accB > maxRgb) accB = maxRgb;++ const invA = 1.0 / accA;+ const dOff = dstRow + (dx << 2);+ out[dOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255.0)));+ }+ }++ return { data: out, width: dstW, height: sh };+}++/**+ * Separable 1D Lanczos-3 resample along Y in float premultiplied RGBA.+ */+function resampleVerticalLanczos3(+ src: PixelBuffer,+ targetH: number,+ flipV: boolean+): PixelBuffer {+ const sw = src.width;+ const sh = src.height;+ const dstH = Math.max(1, targetH);+ const out = new Uint8ClampedArray(sw * dstH * 4);+ const srcData = src.data;++ const scale = sh / dstH;+ const filterScale = scale > 1.0 ? scale : 1.0;+ const invFilterScale = 1.0 / filterScale;+ const support = LANCZOS_A * filterScale;+ const applyAntiRing = filterScale <= 1.25;++ const maxTaps = Math.ceil(support * 2) + 3;+ const rowWeights = new Float32Array(maxTaps);++ for (let dy = 0; dy < dstH; dy++) {+ const v = flipV ? dstH - 0.5 - dy : dy + 0.5;+ const srcY = v * scale - 0.5;+ const y0 = Math.floor(srcY);+ const y1 = y0 + 1;+ const top = Math.ceil(srcY - support);+ const bottom = Math.floor(srcY + support);+ const count = Math.max(0, bottom - top + 1);++ let sumW = 0;+ for (let k = 0; k < count; k++) {+ const w = lanczos3Weight((top + k - srcY) * invFilterScale);+ rowWeights[k] = w;+ sumW += w;+ }+ if (Math.abs(sumW) > 1e-6) {+ const invSum = 1.0 / sumW;+ for (let k = 0; k < count; k++) {+ rowWeights[k] *= invSum;+ }+ }++ const dstRow = dy * sw * 4;+ for (let x = 0; x < sw; x++) {+ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;++ for (let k = 0; k < count; k++) {+ const iy = top + k;+ if (iy < 0 || iy >= sh) continue;+ const off = (iy * sw + x) << 2;+ const a = srcData[off + 3];+ if (a === 0) continue;+ const w = rowWeights[k];+ const af = a * (1 / 255);+ const wa = w * af;+ accR += srcData[off] * wa;+ accG += srcData[off + 1] * wa;+ accB += srcData[off + 2] * wa;+ accA += wa;+ }++ if (applyAntiRing) {+ let a0 = 0, r0 = 0, g0 = 0, b0 = 0;+ let a1 = 0, r1 = 0, g1 = 0, b1 = 0;+ if (y0 >= 0 && y0 < sh) {+ const o0 = (y0 * sw + x) << 2;+ a0 = srcData[o0 + 3] * (1 / 255);+ r0 = srcData[o0] * a0;+ g0 = srcData[o0 + 1] * a0;+ b0 = srcData[o0 + 2] * a0;+ }+ if (y1 >= 0 && y1 < sh) {+ const o1 = (y1 * sw + x) << 2;+ a1 = srcData[o1 + 3] * (1 / 255);+ r1 = srcData[o1] * a1;+ g1 = srcData[o1 + 1] * a1;+ b1 = srcData[o1 + 2] * a1;+ }+ const loR = r0 < r1 ? r0 : r1, hiR = r0 > r1 ? r0 : r1;+ const loG = g0 < g1 ? g0 : g1, hiG = g0 > g1 ? g0 : g1;+ const loB = b0 < b1 ? b0 : b1, hiB = b0 > b1 ? b0 : b1;+ const loA = a0 < a1 ? a0 : a1, hiA = a0 > a1 ? a0 : a1;+ if (accR < loR) accR = loR; else if (accR > hiR) accR = hiR;+ if (accG < loG) accG = loG; else if (accG > hiG) accG = hiG;+ if (accB < loB) accB = loB; else if (accB > hiB) accB = hiB;+ if (accA < loA) accA = loA; else if (accA > hiA) accA = hiA;+ }++ if (accA <= 1e-4) continue;+ if (accA > 1.0) accA = 1.0;+ const maxRgb = accA * 255.0;+ if (accR < 0) accR = 0; else if (accR > maxRgb) accR = maxRgb;+ if (accG < 0) accG = 0; else if (accG > maxRgb) accG = maxRgb;+ if (accB < 0) accB = 0; else if (accB > maxRgb) accB = maxRgb;++ const invA = 1.0 / accA;+ const dOff = dstRow + (x << 2);+ out[dOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255.0)));+ }+ }++ return { data: out, width: sw, height: dstH };+}++/**+ * Ensures downscale ratios along X and Y stay <= 3.0 via exact separable 1D Lanczos-3+ * pre-downsampling, keeping the 2D filter footprint bounded and alias-free for arbitrary shrink ratios.+ */+function prepareSourceForScale(+ source: PixelBuffer,+ targetW: number,+ targetH: number+): PixelBuffer {+ let cur = source;+ const safeW = Math.max(1, targetW);+ const safeH = Math.max(1, targetH);++ if (cur.width / safeW > 3.0) {+ const midW = Math.max(1, Math.ceil(safeW * 2));+ cur = resampleHorizontalLanczos3(cur, midW, false);+ }+ if (cur.height / safeH > 3.0) {+ const midH = Math.max(1, Math.ceil(safeH * 2));+ cur = resampleVerticalLanczos3(cur, midH, false);+ }+ return cur;+}++/**+ * Exact CPU inverse-mapped affine resampler using float-premultiplied Anti-Ringing Lanczos-3+ * (upscaling/rotation) and anisotropic footprint-scaled Lanczos-3 (downscaling).+ */+export function resampleAffineChunkCpu(+ source: PixelBuffer,+ params: AffineTransformParams,+ chunkX: number,+ chunkY: number,+ chunkW: number,+ chunkH: number+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(chunkW * chunkH * 4);+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || params.width <= 0 || params.height <= 0) return out;++ const srcData = source.data;+ const midX = params.x + params.width * 0.5;+ const midY = params.y + params.height * 0.5;+ const rad = (params.rotation * PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const flipXSign = params.flipH ? -1 : 1;+ const flipYSign = params.flipV ? -1 : 1;+ const invDstW = 1.0 / params.width;+ const invDstH = 1.0 / params.height;++ // Incremental inverse affine matrix:+ // srcPos(docX, docY) = (srcX0 + dx*a00 + dy*a01, srcY0 + dx*a10 + dy*a11)+ const scaleX = sw * invDstW;+ const scaleY = sh * invDstH;+ const a00 = flipXSign * cos * scaleX;+ const a01 = flipXSign * sin * scaleX;+ const a10 = flipYSign * -sin * scaleY;+ const a11 = flipYSign * cos * scaleY;++ const filterScaleX = scaleX > 1.0 ? scaleX : 1.0;+ const filterScaleY = scaleY > 1.0 ? scaleY : 1.0;+ const invFilterX = 1.0 / filterScaleX;+ const invFilterY = 1.0 / filterScaleY;+ const supportX = LANCZOS_A * filterScaleX;+ const supportY = LANCZOS_A * filterScaleY;+ const applyAntiRing = filterScaleX <= 1.25 && filterScaleY <= 1.25;++ const minSrcX = -supportX;+ const maxSrcX = sw - 1 + supportX;+ const minSrcY = -supportY;+ const maxSrcY = sh - 1 + supportY;++ const maxTapsX = Math.ceil(supportX * 2) + 4;+ const maxTapsY = Math.ceil(supportY * 2) + 4;+ const wxBuf = new Float32Array(maxTapsX);+ const wyBuf = new Float32Array(maxTapsY);++ const rx0 = chunkX + 0.5 - midX;+ const ry0 = chunkY + 0.5 - midY;+ const baseSrcX = (flipXSign * (rx0 * cos + ry0 * sin) * invDstW + 0.5) * sw - 0.5;+ const baseSrcY = (flipYSign * (-rx0 * sin + ry0 * cos) * invDstH + 0.5) * sh - 0.5;++ for (let py = 0; py < chunkH; py++) {+ let sx = baseSrcX + py * a01;+ let sy = baseSrcY + py * a11;+ let dstOff = py * chunkW * 4;++ for (let px = 0; px < chunkW; px++, sx += a00, sy += a10, dstOff += 4) {+ if (sx < minSrcX || sx > maxSrcX || sy < minSrcY || sy > maxSrcY) {+ continue;+ }++ const xStart = Math.ceil(sx - supportX);+ const xEnd = Math.floor(sx + supportX);+ const yStart = Math.ceil(sy - supportY);+ const yEnd = Math.floor(sy + supportY);+ const countX = xEnd - xStart + 1;+ const countY = yEnd - yStart + 1;+ if (countX <= 0 || countY <= 0) continue;++ let sumWx = 0;+ for (let i = 0; i < countX; i++) {+ const w = lanczos3Weight((xStart + i - sx) * invFilterX);+ wxBuf[i] = w;+ sumWx += w;+ }+ if (Math.abs(sumWx) < 1e-6) continue;+ const invSumWx = 1.0 / sumWx;+ for (let i = 0; i < countX; i++) {+ wxBuf[i] *= invSumWx;+ }++ let sumWy = 0;+ for (let j = 0; j < countY; j++) {+ const w = lanczos3Weight((yStart + j - sy) * invFilterY);+ wyBuf[j] = w;+ sumWy += w;+ }+ if (Math.abs(sumWy) < 1e-6) continue;+ const invSumWy = 1.0 / sumWy;+ for (let j = 0; j < countY; j++) {+ wyBuf[j] *= invSumWy;+ }++ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;++ for (let j = 0; j < countY; j++) {+ const iy = yStart + j;+ if (iy < 0 || iy >= sh) continue;+ const wy = wyBuf[j];+ if (wy === 0) continue;+ const rowBase = iy * sw;++ let rR = 0;+ let rG = 0;+ let rB = 0;+ let rA = 0;++ for (let i = 0; i < countX; i++) {+ const ix = xStart + i;+ if (ix < 0 || ix >= sw) continue;+ const off = (rowBase + ix) << 2;+ const a = srcData[off + 3];+ if (a === 0) continue;+ const wa = wxBuf[i] * (a * (1 / 255));+ rR += srcData[off] * wa;+ rG += srcData[off + 1] * wa;+ rB += srcData[off + 2] * wa;+ rA += wa;+ }++ accR += rR * wy;+ accG += rG * wy;+ accB += rB * wy;+ accA += rA * wy;+ }++ if (applyAntiRing) {+ const bx = Math.floor(sx);+ const by = Math.floor(sy);+ let loR = Infinity, hiR = -Infinity;+ let loG = Infinity, hiG = -Infinity;+ let loB = Infinity, hiB = -Infinity;+ let loA = Infinity, hiA = -Infinity;++ for (let ny = by; ny <= by + 1; ny++) {+ const yValid = ny >= 0 && ny < sh;+ const rowBase = ny * sw;+ for (let nx = bx; nx <= bx + 1; nx++) {+ let nr = 0, ng = 0, nb = 0, na = 0;+ if (yValid && nx >= 0 && nx < sw) {+ const o = (rowBase + nx) << 2;+ na = srcData[o + 3] * (1 / 255);+ nr = srcData[o] * na;+ ng = srcData[o + 1] * na;+ nb = srcData[o + 2] * na;+ }+ if (nr < loR) loR = nr; if (nr > hiR) hiR = nr;+ if (ng < loG) loG = ng; if (ng > hiG) hiG = ng;+ if (nb < loB) loB = nb; if (nb > hiB) hiB = nb;+ if (na < loA) loA = na; if (na > hiA) hiA = na;+ }+ }++ if (accR < loR) accR = loR; else if (accR > hiR) accR = hiR;+ if (accG < loG) accG = loG; else if (accG > hiG) accG = hiG;+ if (accB < loB) accB = loB; else if (accB > hiB) accB = hiB;+ if (accA < loA) accA = loA; else if (accA > hiA) accA = hiA;+ }++ if (accA <= 1e-4) continue;+ if (accA > 1.0) accA = 1.0;+ const maxRgb = accA * 255.0;+ if (accR < 0) accR = 0; else if (accR > maxRgb) accR = maxRgb;+ if (accG < 0) accG = 0; else if (accG > maxRgb) accG = maxRgb;+ if (accB < 0) accB = 0; else if (accB > maxRgb) accB = maxRgb;++ const invA = 1.0 / accA;+ out[dstOff] = Math.min(255, Math.max(0, Math.round(accR * invA)));+ out[dstOff + 1] = Math.min(255, Math.max(0, Math.round(accG * invA)));+ out[dstOff + 2] = Math.min(255, Math.max(0, Math.round(accB * invA)));+ out[dstOff + 3] = Math.min(255, Math.max(0, Math.round(accA * 255.0)));+ }+ }++ return out;+}++const AFFINE_VERTEX_SHADER_ES3 = `#version 300 es+ in vec2 a_ndc;+ uniform vec2 u_chunkOrigin;+ uniform vec2 u_chunkSize;+ out vec2 v_docPos;+ void main() {+ // Map a_ndc in [0, 1]^2 so row 0 of readPixels corresponds directly to chunk top (chunkOrigin.y)+ vec2 uv = a_ndc;+ v_docPos = u_chunkOrigin + uv * u_chunkSize;+ gl_Position = vec4(uv.x * 2.0 - 1.0, uv.y * 2.0 - 1.0, 0.0, 1.0);+ }+`;++const AFFINE_FRAGMENT_SHADER_ES3 = `#version 300 es+ precision highp float;+ uniform sampler2D u_tex;+ uniform ivec2 u_srcSize;+ uniform vec2 u_mid;+ uniform vec2 u_dstSize;+ uniform vec2 u_rotCosSin;+ uniform vec2 u_flipSign;+ uniform vec2 u_filterScale;+ in vec2 v_docPos;+ out vec4 outColor;++ const float PI = 3.14159265358979323846;++ float lanczos3(float x) {+ float ax = abs(x);+ if (ax < 1e-5) return 1.0;+ if (ax >= 3.0) return 0.0;+ float pix = PI * ax;+ return (3.0 * sin(pix) * sin(pix * (1.0 / 3.0))) / (pix * pix);+ }++ vec4 fetchPremul(int ix, int iy) {+ if (ix < 0 || ix >= u_srcSize.x || iy < 0 || iy >= u_srcSize.y) {+ return vec4(0.0);+ }+ vec4 s = texelFetch(u_tex, ivec2(ix, iy), 0);+ return vec4(s.rgb * s.a, s.a);+ }++ void main() {+ vec2 r = v_docPos - u_mid;+ float cosA = u_rotCosSin.x;+ float sinA = u_rotCosSin.y;+ vec2 f = vec2(r.x * cosA + r.y * sinA, -r.x * sinA + r.y * cosA);+ vec2 l = f * u_flipSign;+ vec2 srcSizeF = vec2(u_srcSize);+ vec2 srcPos = (l / u_dstSize + 0.5) * srcSizeF - 0.5;++ vec2 support = 3.0 * u_filterScale;+ if (+ srcPos.x < -support.x || srcPos.x > (srcSizeF.x - 1.0) + support.x ||+ srcPos.y < -support.y || srcPos.y > (srcSizeF.y - 1.0) + support.y+ ) {+ outColor = vec4(0.0);+ return;+ }++ vec2 invFilter = 1.0 / u_filterScale;+ int xStart = int(ceil(srcPos.x - support.x));+ int xEnd = int(floor(srcPos.x + support.x));+ int yStart = int(ceil(srcPos.y - support.y));+ int yEnd = int(floor(srcPos.y + support.y));++ float wx[20];+ int countX = min(20, max(0, xEnd - xStart + 1));+ float sumWx = 0.0;+ for (int i = 0; i < 20; i++) {+ if (i >= countX) break;+ float w = lanczos3((float(xStart + i) - srcPos.x) * invFilter.x);+ wx[i] = w;+ sumWx += w;+ }+ if (abs(sumWx) < 1e-6) {+ outColor = vec4(0.0);+ return;+ }+ float invSumWx = 1.0 / sumWx;+ for (int i = 0; i < 20; i++) {+ if (i >= countX) break;+ wx[i] *= invSumWx;+ }++ vec4 acc = vec4(0.0);+ float sumWy = 0.0;+ int countY = min(20, max(0, yEnd - yStart + 1));+ for (int j = 0; j < 20; j++) {+ if (j >= countY) break;+ int iy = yStart + j;+ float wy = lanczos3((float(iy) - srcPos.y) * invFilter.y);+ sumWy += wy;+ if (iy < 0 || iy >= u_srcSize.y || abs(wy) < 1e-7) continue;++ vec4 rowAcc = vec4(0.0);+ for (int i = 0; i < 20; i++) {+ if (i >= countX) break;+ int ix = xStart + i;+ if (ix < 0 || ix >= u_srcSize.x) continue;+ rowAcc += fetchPremul(ix, iy) * wx[i];+ }+ acc += rowAcc * wy;+ }++ if (abs(sumWy) < 1e-6) {+ outColor = vec4(0.0);+ return;+ }+ acc /= sumWy;++ // Anti-ringing clamp for upscaling and rotation: eliminates Lanczos halos while preserving full edge sharpness+ if (u_filterScale.x <= 1.25 && u_filterScale.y <= 1.25) {+ int bx = int(floor(srcPos.x));+ int by = int(floor(srcPos.y));+ vec4 n00 = fetchPremul(bx, by);+ vec4 n10 = fetchPremul(bx + 1, by);+ vec4 n01 = fetchPremul(bx, by + 1);+ vec4 n11 = fetchPremul(bx + 1, by + 1);+ vec4 lo = min(min(n00, n10), min(n01, n11));+ vec4 hi = max(max(n00, n10), max(n01, n11));+ acc = clamp(acc, lo, hi);+ }++ float a = clamp(acc.a, 0.0, 1.0);+ if (a <= 1e-4) {+ outColor = vec4(0.0);+ return;+ }+ vec3 premulRgb = clamp(acc.rgb, vec3(0.0), vec3(a));+ vec3 straightRgb = clamp(premulRgb / a, 0.0, 1.0);+ outColor = vec4(straightRgb, a);+ }+`;++class WebGlAffineTransformRenderer {+ private static instance: WebGlAffineTransformRenderer | null = null;+ private gl: WebGL2RenderingContext | null = null;+ private program: WebGLProgram | null = null;+ private quadBuffer: WebGLBuffer | null = null;+ private srcTexture: WebGLTexture | null = null;+ private fbo: WebGLFramebuffer | null = null;+ private fboTexture: WebGLTexture | null = null;+ private fboW = 0;+ private fboH = 0;+ private ndcLoc = -1;+ private chunkOriginLoc: WebGLUniformLocation | null = null;+ private chunkSizeLoc: WebGLUniformLocation | null = null;+ private texLoc: WebGLUniformLocation | null = null;+ private srcSizeLoc: WebGLUniformLocation | null = null;+ private midLoc: WebGLUniformLocation | null = null;+ private dstSizeLoc: WebGLUniformLocation | null = null;+ private rotCosSinLoc: WebGLUniformLocation | null = null;+ private flipSignLoc: WebGLUniformLocation | null = null;+ private filterScaleLoc: WebGLUniformLocation | null = null;+ private maxDim = 0;+ private ready = false;++ static getInstance(): WebGlAffineTransformRenderer {+ if (!WebGlAffineTransformRenderer.instance) {+ WebGlAffineTransformRenderer.instance = new WebGlAffineTransformRenderer();+ }+ return WebGlAffineTransformRenderer.instance;+ }++ private constructor() {+ this.init();+ }++ private init(): void {+ this.ready = false;+ if (typeof document === 'undefined') return;+ try {+ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ const gl = canvas.getContext('webgl2', {+ alpha: true,+ premultipliedAlpha: false,+ antialias: false,+ depth: false,+ stencil: false,+ preserveDrawingBuffer: false,+ }) as WebGL2RenderingContext | null;+ if (!gl) return;++ const vs = gl.createShader(gl.VERTEX_SHADER);+ const fs = gl.createShader(gl.FRAGMENT_SHADER);+ if (!vs || !fs) return;+ gl.shaderSource(vs, AFFINE_VERTEX_SHADER_ES3);+ gl.compileShader(vs);+ gl.shaderSource(fs, AFFINE_FRAGMENT_SHADER_ES3);+ gl.compileShader(fs);+ if (+ !gl.getShaderParameter(vs, gl.COMPILE_STATUS) ||+ !gl.getShaderParameter(fs, gl.COMPILE_STATUS)+ ) {+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ return;+ }++ const program = gl.createProgram();+ if (!program) {+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ return;+ }+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ gl.deleteProgram(program);+ return;+ }++ const quadBuffer = gl.createBuffer();+ const srcTexture = gl.createTexture();+ const fbo = gl.createFramebuffer();+ const fboTexture = gl.createTexture();+ const ndcLoc = gl.getAttribLocation(program, 'a_ndc');+ if (!quadBuffer || !srcTexture || !fbo || !fboTexture || ndcLoc < 0) {+ if (quadBuffer) gl.deleteBuffer(quadBuffer);+ if (srcTexture) gl.deleteTexture(srcTexture);+ if (fbo) gl.deleteFramebuffer(fbo);+ if (fboTexture) gl.deleteTexture(fboTexture);+ gl.deleteProgram(program);+ return;+ }++ gl.bindBuffer(gl.ARRAY_BUFFER, quadBuffer);+ gl.bufferData(+ gl.ARRAY_BUFFER,+ new Float32Array([0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1]),+ gl.STATIC_DRAW+ );++ const maxTex = gl.getParameter(gl.MAX_TEXTURE_SIZE) as number;+ const maxVp = gl.getParameter(gl.MAX_VIEWPORT_DIMS) as Int32Array | number[] | null;+ const maxVpDim = maxVp ? Math.min(maxVp[0], maxVp[1]) : maxTex;++ this.gl = gl;+ this.program = program;+ this.quadBuffer = quadBuffer;+ this.srcTexture = srcTexture;+ this.fbo = fbo;+ this.fboTexture = fboTexture;+ this.ndcLoc = ndcLoc;+ this.chunkOriginLoc = gl.getUniformLocation(program, 'u_chunkOrigin');+ this.chunkSizeLoc = gl.getUniformLocation(program, 'u_chunkSize');+ this.texLoc = gl.getUniformLocation(program, 'u_tex');+ this.srcSizeLoc = gl.getUniformLocation(program, 'u_srcSize');+ this.midLoc = gl.getUniformLocation(program, 'u_mid');+ this.dstSizeLoc = gl.getUniformLocation(program, 'u_dstSize');+ this.rotCosSinLoc = gl.getUniformLocation(program, 'u_rotCosSin');+ this.flipSignLoc = gl.getUniformLocation(program, 'u_flipSign');+ this.filterScaleLoc = gl.getUniformLocation(program, 'u_filterScale');+ this.maxDim = Math.min(maxTex || 4096, maxVpDim || 4096);+ this.ready = true;+ } catch {+ this.ready = false;+ }+ }++ private ensureFbo(gl: WebGL2RenderingContext, w: number, h: number): boolean {+ if (!this.fbo || !this.fboTexture) return false;+ if (this.fboW === w && this.fboH === h) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo);+ return true;+ }+ gl.bindTexture(gl.TEXTURE_2D, this.fboTexture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);++ gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.fboTexture, 0);+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);+ if (status !== gl.FRAMEBUFFER_COMPLETE) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ this.fboW = 0;+ this.fboH = 0;+ return false;+ }+ this.fboW = w;+ this.fboH = h;+ return true;+ }++ renderChunks(+ source: PixelBuffer,+ params: AffineTransformParams,+ destRect: DirtyRect,+ chunkSize: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void+ ): boolean {+ if (!this.ready || !this.gl || !this.program || !this.quadBuffer || !this.srcTexture) {+ return false;+ }+ const gl = this.gl;+ if (gl.isContextLost()) {+ this.ready = false;+ return false;+ }+ const sw = source.width;+ const sh = source.height;+ if (sw <= 0 || sh <= 0 || sw > this.maxDim || sh > this.maxDim) return false;+ if (chunkSize > this.maxDim) return false;++ const srcBytes =+ source.data instanceof Uint8Array+ ? source.data+ : new Uint8Array(source.data.buffer, source.data.byteOffset, source.data.byteLength);++ // Upload source straight-alpha pixels ONCE for all chunks+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.srcTexture);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, sw, sh, 0, gl.RGBA, gl.UNSIGNED_BYTE, srcBytes);++ gl.useProgram(this.program);+ gl.uniform1i(this.texLoc, 0);+ gl.uniform2i(this.srcSizeLoc, sw, sh);+ gl.uniform2f(this.midLoc, params.x + params.width * 0.5, params.y + params.height * 0.5);+ gl.uniform2f(this.dstSizeLoc, params.width, params.height);+ const rad = (params.rotation * PI) / 180;+ gl.uniform2f(this.rotCosSinLoc, Math.cos(rad), Math.sin(rad));+ gl.uniform2f(this.flipSignLoc, params.flipH ? -1 : 1, params.flipV ? -1 : 1);+ const filterScaleX = Math.max(1.0, sw / Math.max(1, params.width));+ const filterScaleY = Math.max(1.0, sh / Math.max(1, params.height));+ gl.uniform2f(this.filterScaleLoc, filterScaleX, filterScaleY);++ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);+ gl.enableVertexAttribArray(this.ndcLoc);+ gl.vertexAttribPointer(this.ndcLoc, 2, gl.FLOAT, false, 0, 0);+ gl.disable(gl.BLEND);+ gl.disable(gl.CULL_FACE);++ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;++ try {+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ if (!this.ensureFbo(gl, cw, ch)) {+ return false;+ }+ gl.viewport(0, 0, cw, ch);+ gl.uniform2f(this.chunkOriginLoc, cx, cy);+ gl.uniform2f(this.chunkSizeLoc, cw, ch);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.srcTexture);+ gl.drawArrays(gl.TRIANGLES, 0, 6);++ const rawBytes = new Uint8Array(cw * ch * 4);+ gl.readPixels(0, 0, cw, ch, gl.RGBA, gl.UNSIGNED_BYTE, rawBytes);+ const clamped = new Uint8ClampedArray(+ rawBytes.buffer,+ rawBytes.byteOffset,+ rawBytes.byteLength+ );+ onChunk(clamped, cx, cy, cw, ch);+ }+ }+ return true;+ } catch {+ return false;+ } finally {+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ }+ }+}++/**+ * Extracts straight-alpha pixel data from an HTMLCanvasElement.+ */+export function extractCanvasPixelBuffer(canvas: HTMLCanvasElement): PixelBuffer | null {+ if (!canvas || canvas.width <= 0 || canvas.height <= 0) return null;+ const ctx = canvas.getContext('2d', { willReadFrequently: true });+ if (!ctx) return null;+ const img = ctx.getImageData(0, 0, canvas.width, canvas.height);+ return { data: img.data, width: img.width, height: img.height };+}++/**+ * High-precision chunked affine transform pipeline:+ * 1. Exact lossless straight-alpha copy for 1:1 translate / flip / 90/180/270 rotation+ * (eliminates Canvas 2D premultiplication loss and odd-dimension 0.5px rotation blur).+ * 2. Separable Lanczos-3 pre-downsampling for >3x shrink ratios (prevents aliasing/thinning).+ * 3. WebGL2 float-premultiplied Anti-Ringing Lanczos-3 (with exact CPU fallback) writing+ * straight-alpha RGBA chunks directly with zero Canvas 2D round-trip.+ */+export function processAffineTransformChunks(+ source: PixelBuffer,+ params: AffineTransformParams,+ destRect: DirtyRect,+ chunkSize: number,+ onChunk: (chunkData: Uint8ClampedArray, cx: number, cy: number, cw: number, ch: number) => void+): void {+ const x1 = destRect.x + destRect.width;+ const y1 = destRect.y + destRect.height;++ // 1. Exact lossless integer path (1:1 translate, flip, 90/180/270)+ const losslessSpec = resolveLosslessAffineSpec(source.width, source.height, params);+ if (losslessSpec) {+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ const chunkData = renderLosslessAffineChunk(source, losslessSpec, cx, cy, cw, ch);+ onChunk(chunkData, cx, cy, cw, ch);+ }+ }+ return;+ }++ // 2. Pre-downsample extreme >3x shrink ratios along X/Y independently via exact 1D Lanczos-3+ const preparedSource = prepareSourceForScale(source, params.width, params.height);++ // 3. GPU WebGL2 float-premultiplied Anti-Ringing Lanczos-3 (uploads texture once)+ if (+ WebGlAffineTransformRenderer.getInstance().renderChunks(+ preparedSource,+ params,+ destRect,+ chunkSize,+ onChunk+ )+ ) {+ return;+ }++ // 4. Fast separable 2-pass CPU Lanczos-3 when unrotated (0 or 180 deg) with integer destination placement+ const qTurn = getExactQuarterTurnDeg(params.rotation);+ if (+ (qTurn === 0 || qTurn === 180) &&+ Math.abs(params.x - Math.round(params.x)) < 1e-5 &&+ Math.abs(params.y - Math.round(params.y)) < 1e-5 &&+ Math.abs(params.width - Math.round(params.width)) < 1e-5 &&+ Math.abs(params.height - Math.round(params.height)) < 1e-5+ ) {+ const targetW = Math.max(1, Math.round(params.width));+ const targetH = Math.max(1, Math.round(params.height));+ const effFlipH = qTurn === 180 ? !params.flipH : params.flipH;+ const effFlipV = qTurn === 180 ? !params.flipV : params.flipV;+ const hPass =+ preparedSource.width === targetW && !effFlipH+ ? preparedSource+ : resampleHorizontalLanczos3(preparedSource, targetW, effFlipH);+ const fullRes =+ hPass.height === targetH && !effFlipV+ ? hPass+ : resampleVerticalLanczos3(hPass, targetH, effFlipV);++ const originX = Math.round(params.x);+ const originY = Math.round(params.y);+ const copySpec: LosslessAffineSpec = {+ quarterTurn: 0,+ flipH: false,+ flipV: false,+ destOriginX: originX,+ destOriginY: originY,+ destWidth: targetW,+ destHeight: targetH,+ };+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ const chunkData = renderLosslessAffineChunk(fullRes, copySpec, cx, cy, cw, ch);+ onChunk(chunkData, cx, cy, cw, ch);+ }+ }+ return;+ }++ // 5. General rotated CPU inverse-mapped Anti-Ringing Lanczos-3 fallback+ for (let cy = destRect.y; cy < y1; cy += chunkSize) {+ const ch = Math.min(chunkSize, y1 - cy);+ for (let cx = destRect.x; cx < x1; cx += chunkSize) {+ const cw = Math.min(chunkSize, x1 - cx);+ const chunkData = resampleAffineChunkCpu(preparedSource, params, cx, cy, cw, ch);+ onChunk(chunkData, cx, cy, cw, ch);+ }+ }+}++/**+ * Helper to check if a perspective quad or mesh grid matches an exact integer translation+ * of its source dimensions (for lossless identity/move detection).+ */+export function isExactQuadTranslation(+ quad: [Point2D, Point2D, Point2D, Point2D],+ sw: number,+ sh: number+): { x: number; y: number } | null {+ const x = Math.round(quad[0].x);+ const y = Math.round(quad[0].y);+ if (+ Math.abs(quad[0].x - x) < 1e-5 &&+ Math.abs(quad[0].y - y) < 1e-5 &&+ Math.abs(quad[1].x - (x + sw)) < 1e-5 &&+ Math.abs(quad[1].y - y) < 1e-5 &&+ Math.abs(quad[2].x - (x + sw)) < 1e-5 &&+ Math.abs(quad[2].y - (y + sh)) < 1e-5 &&+ Math.abs(quad[3].x - x) < 1e-5 &&+ Math.abs(quad[3].y - (y + sh)) < 1e-5+ ) {+ return { x, y };+ }+ return null;+}diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.tsindex 1d10ae3..6a372c8 100644--- a/src/utils/workspacePresets.ts+++ b/src/utils/workspacePresets.ts@@ -8,6 +8,8 @@ import {DockGroup,DockPanelId,DockSide,+ FloatingPanelLastDock,+ FloatingPanelState,PersistedWorkspaceState,QuickAccessItem,QuickAccessViewMode,@@ -271,6 +273,87 @@ export const DEFAULT_COMMAND_BAR_IDS: CommandActionId[] = ['toggle-palettes',];+export const FLOATING_MIN_X = 8;+export const FLOATING_MIN_Y = 38;+export const FLOATING_MAX_WIDTH = 720;+export const FLOATING_MAX_HEIGHT = 860;++export function getFloatingSizeBounds(panelIds: DockPanelId[]): {+ minWidth: number;+ maxWidth: number;+ minHeight: number;+ maxHeight: number;+} {+ if (panelIds.length === 1 && panelIds[0] === 'tools') {+ return {+ minWidth: 56,+ maxWidth: 220,+ minHeight: DOCK_PANEL_META.tools.minFloatHeight,+ maxHeight: FLOATING_MAX_HEIGHT,+ };+ }+ let minWidth = 176;+ let minHeight = 140;+ for (const pid of panelIds) {+ const meta = DOCK_PANEL_META[pid];+ if (!meta) continue;+ if (pid !== 'tools' && meta.minWidth > minWidth) minWidth = meta.minWidth;+ if (meta.minFloatHeight > minHeight) minHeight = meta.minFloatHeight;+ }+ return {+ minWidth,+ maxWidth: FLOATING_MAX_WIDTH,+ minHeight,+ maxHeight: FLOATING_MAX_HEIGHT,+ };+}++export function clampFloatingRect(+ x: number,+ y: number,+ width: number,+ height: number,+ panelIds: DockPanelId[],+ viewport?: { width: number; height: number }+): { x: number; y: number; width: number; height: number } {+ const bounds = getFloatingSizeBounds(panelIds);+ const vw = viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 1280);+ const vh = viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 800);++ const clampedW = Math.max(+ bounds.minWidth,+ Math.min(bounds.maxWidth, Math.min(Math.max(bounds.minWidth, vw - 16), Math.round(width)))+ );+ const clampedH = Math.max(+ bounds.minHeight,+ Math.min(+ bounds.maxHeight,+ Math.min(Math.max(bounds.minHeight, vh - FLOATING_MIN_Y - 12), Math.round(height))+ )+ );+ const maxX = Math.max(FLOATING_MIN_X, vw - Math.min(clampedW, 120));+ const maxY = Math.max(FLOATING_MIN_Y, vh - 36);+ const clampedX = Math.max(FLOATING_MIN_X, Math.min(maxX, Math.round(x)));+ const clampedY = Math.max(FLOATING_MIN_Y, Math.min(maxY, Math.round(y)));++ return { x: clampedX, y: clampedY, width: clampedW, height: clampedH };+}++function normalizeFloatingZIndices(panels: FloatingPanelState[]): FloatingPanelState[] {+ if (panels.length === 0) return [];+ const order = panels+ .map((p, idx) => ({ id: p.id, z: p.zIndex, idx }))+ .sort((a, b) => (a.z !== b.z ? a.z - b.z : a.idx - b.idx));+ const zMap = new Map<string, number>();+ order.forEach((item, rank) => {+ zMap.set(item.id, rank + 1);+ });+ return panels.map((p) => ({+ ...p,+ zIndex: zMap.get(p.id) ?? 1,+ }));+}+export function cloneLayout(layout: WorkspaceLayout): WorkspaceLayout {return {leftDocks: layout.leftDocks.map((col) => ({@@ -287,6 +370,11 @@ export function cloneLayout(layout: WorkspaceLayout): WorkspaceLayout {panelIds: [...g.panelIds],})),})),+ floatingPanels: (layout.floatingPanels ?? []).map((fp) => ({+ ...fp,+ panelIds: [...fp.panelIds],+ lastDock: fp.lastDock ? { ...fp.lastDock } : undefined,+ })),};}@@ -311,6 +399,11 @@ export function listVisiblePanelIds(layout: WorkspaceLayout): Set<DockPanelId> {}}}+ for (const fp of layout.floatingPanels ?? []) {+ for (const pid of fp.panelIds) {+ out.add(pid);+ }+ }return out;}@@ -331,6 +424,18 @@ export function findPanelLocation(return null;}+export function findFloatingPanelLocation(+ layout: WorkspaceLayout,+ panelId: DockPanelId+): { floatingId: string } | null {+ for (const fp of layout.floatingPanels ?? []) {+ if (fp.panelIds.includes(panelId)) {+ return { floatingId: fp.id };+ }+ }+ return null;+}+function pruneEmptyContainers(columns: DockColumn[]): DockColumn[] {return columns.map((col) => {@@ -353,6 +458,19 @@ function pruneEmptyContainers(columns: DockColumn[]): DockColumn[] {.filter((c): c is DockColumn => c !== null);}+function pruneEmptyFloatingPanels(panels: FloatingPanelState[]): FloatingPanelState[] {+ const nonEmpty = panels+ .map((fp) => {+ if (fp.panelIds.length === 0) return null;+ return {+ ...fp,+ activePanelId: fp.panelIds.includes(fp.activePanelId) ? fp.activePanelId : fp.panelIds[0],+ };+ })+ .filter((fp): fp is FloatingPanelState => fp !== null);+ return normalizeFloatingZIndices(nonEmpty);+}+export function removePanelFromLayout(layout: WorkspaceLayout,panelId: DockPanelId@@ -368,9 +486,17 @@ export function removePanelFromLayout(})));+ const nextFloating = pruneEmptyFloatingPanels(+ (layout.floatingPanels ?? []).map((fp) => ({+ ...fp,+ panelIds: fp.panelIds.filter((id) => id !== panelId),+ }))+ );+return {leftDocks: stripCols(layout.leftDocks),rightDocks: stripCols(layout.rightDocks),+ floatingPanels: nextFloating,};}@@ -496,7 +622,7 @@ export function setGroupActivePanelInLayout(groups: col.groups.map((g) =>g.id !== groupId || !g.panelIds.includes(panelId)? g- : { ...g, activePanelId: panelId }+ : { ...g, activePanelId: panelId, collapsed: false }),});@@ -504,6 +630,34 @@ export function setGroupActivePanelInLayout(return {leftDocks: mapCols(layout.leftDocks),rightDocks: mapCols(layout.rightDocks),+ floatingPanels: layout.floatingPanels ?? [],+ };+}++export function toggleGroupCollapsedInLayout(+ layout: WorkspaceLayout,+ colId: string,+ groupId: string,+ forceValue?: boolean+): WorkspaceLayout {+ const mapCols = (cols: DockColumn[]) =>+ cols.map((col) =>+ col.id !== colId+ ? col+ : {+ ...col,+ groups: col.groups.map((g) =>+ g.id !== groupId+ ? g+ : { ...g, collapsed: forceValue !== undefined ? forceValue : !g.collapsed }+ ),+ }+ );++ return {+ leftDocks: mapCols(layout.leftDocks),+ rightDocks: mapCols(layout.rightDocks),+ floatingPanels: layout.floatingPanels ?? [],};}@@ -522,6 +676,7 @@ export function toggleColumnCollapsedInLayout(return {leftDocks: mapCols(layout.leftDocks),rightDocks: mapCols(layout.rightDocks),+ floatingPanels: layout.floatingPanels ?? [],};}@@ -547,18 +702,25 @@ export function resizeColumnInLayout(colId: string,requestedWidth: number): WorkspaceLayout {+ let changed = false;const mapCols = (cols: DockColumn[]) =>cols.map((col) => {if (col.id !== colId) return col;const { min, max } = getColumnWidthBounds(col);const clamped = Math.max(min, Math.min(max, Math.round(requestedWidth)));if (clamped === col.width) return col;+ changed = true;return { ...col, width: clamped };});+ const leftDocks = mapCols(layout.leftDocks);+ const rightDocks = mapCols(layout.rightDocks);+ if (!changed) return layout;+return {- leftDocks: mapCols(layout.leftDocks),- rightDocks: mapCols(layout.rightDocks),+ leftDocks,+ rightDocks,+ floatingPanels: layout.floatingPanels ?? [],};}@@ -586,6 +748,325 @@ export function resizeGroupSplitInLayout(return {leftDocks: mapCols(layout.leftDocks),rightDocks: mapCols(layout.rightDocks),+ floatingPanels: layout.floatingPanels ?? [],+ };+}++export interface DetachPanelOptions {+ x?: number;+ y?: number;+ width?: number;+ height?: number;+ viewport?: { width: number; height: number };+}++export function detachPanelToFloatingInLayout(+ layout: WorkspaceLayout,+ panelId: DockPanelId,+ options?: DetachPanelOptions+): WorkspaceLayout {+ const dockedLoc = findPanelLocation(layout, panelId);+ const existingFloatingLoc = findFloatingPanelLocation(layout, panelId);+ const existingFloating = existingFloatingLoc+ ? (layout.floatingPanels ?? []).find((f) => f.id === existingFloatingLoc.floatingId)+ : undefined;++ const lastDock: FloatingPanelLastDock | undefined = dockedLoc+ ? { side: dockedLoc.side, colId: dockedLoc.colId, groupId: dockedLoc.groupId }+ : existingFloating?.lastDock+ ? { ...existingFloating.lastDock }+ : { side: DOCK_PANEL_META[panelId].defaultSide };++ const cleaned = removePanelFromLayout(layout, panelId);+ const next = cloneLayout(cleaned);+ const floatingPanels = next.floatingPanels ?? [];+ const meta = DOCK_PANEL_META[panelId];++ const vw = options?.viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 1280);+ const vh = options?.viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 800);++ const cascade = (floatingPanels.length % 6) * 26;+ const reqW = options?.width ?? meta.defaultFloatWidth;+ const reqH = options?.height ?? meta.defaultFloatHeight;+ const defaultX =+ meta.defaultSide === 'left'+ ? Math.round(vw * 0.24) + cascade+ : Math.round(vw * 0.68 - reqW * 0.5) - cascade;+ const defaultY = Math.round(vh * 0.16) + cascade;++ const rect = clampFloatingRect(+ options?.x ?? defaultX,+ options?.y ?? defaultY,+ reqW,+ reqH,+ [panelId],+ options?.viewport+ );++ const maxZ = floatingPanels.reduce((acc, p) => Math.max(acc, p.zIndex), 0);+ const newFloating: FloatingPanelState = {+ id: makeUid('float'),+ panelIds: [panelId],+ activePanelId: panelId,+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ collapsed: false,+ zIndex: maxZ + 1,+ lastDock,+ };++ next.floatingPanels = normalizeFloatingZIndices([...floatingPanels, newFloating]);+ return next;+}++export function mergePanelIntoFloatingInLayout(+ layout: WorkspaceLayout,+ panelId: DockPanelId,+ targetFloatingId: string+): WorkspaceLayout {+ const targetExists = (layout.floatingPanels ?? []).some((fp) => fp.id === targetFloatingId);+ if (!targetExists) return layout;++ const existingLoc = findFloatingPanelLocation(layout, panelId);+ if (existingLoc && existingLoc.floatingId === targetFloatingId) {+ return setFloatingActivePanelInLayout(layout, targetFloatingId, panelId);+ }++ const cleaned = removePanelFromLayout(layout, panelId);+ const next = cloneLayout(cleaned);+ const floatingPanels = next.floatingPanels ?? [];+ const target = floatingPanels.find((fp) => fp.id === targetFloatingId);+ if (!target) return layout;++ if (!target.panelIds.includes(panelId)) {+ target.panelIds.push(panelId);+ }+ target.activePanelId = panelId;+ target.collapsed = false;+ const bounds = getFloatingSizeBounds(target.panelIds);+ if (target.width < bounds.minWidth) {+ target.width = Math.max(bounds.minWidth, DOCK_PANEL_META[panelId].defaultFloatWidth);+ }+ if (target.height < bounds.minHeight) {+ target.height = Math.max(bounds.minHeight, DOCK_PANEL_META[panelId].defaultFloatHeight);+ }++ const maxZ = floatingPanels.reduce((acc, p) => Math.max(acc, p.zIndex), 0);+ target.zIndex = maxZ + 1;+ next.floatingPanels = normalizeFloatingZIndices(floatingPanels);+ return next;+}++export function dockFloatingPanelInLayout(+ layout: WorkspaceLayout,+ floatingId: string,+ target?: MovePanelTarget+): WorkspaceLayout {+ const fp = (layout.floatingPanels ?? []).find((f) => f.id === floatingId);+ if (!fp || fp.panelIds.length === 0) return layout;++ const panelsToDock = [...fp.panelIds];+ const preferredActive = fp.panelIds.includes(fp.activePanelId) ? fp.activePanelId : fp.panelIds[0];++ // Resolve target when 1-click reattaching without explicit drop target+ let resolvedTarget: MovePanelTarget;+ if (target) {+ resolvedTarget = target;+ } else {+ const last = fp.lastDock;+ const fallbackSide = last?.side ?? DOCK_PANEL_META[preferredActive].defaultSide;+ const sideCols = fallbackSide === 'left' ? layout.leftDocks : layout.rightDocks;+ const matchedCol = last?.colId ? sideCols.find((c) => c.id === last.colId) : undefined;+ const matchedGrp =+ matchedCol && last?.groupId+ ? matchedCol.groups.find((g) => g.id === last.groupId)+ : undefined;++ if (matchedCol && matchedGrp) {+ resolvedTarget = {+ side: fallbackSide,+ targetColId: matchedCol.id,+ targetGroupId: matchedGrp.id,+ };+ } else if (matchedCol) {+ resolvedTarget = {+ side: fallbackSide,+ targetColId: matchedCol.id,+ insertGroupIndex: matchedCol.groups.length,+ };+ } else {+ const preferredCol = sideCols.find(+ (c) =>+ !(+ c.groups.length === 1 &&+ c.groups[0].panelIds.length === 1 &&+ c.groups[0].panelIds[0] === 'tools'+ )+ );+ if (preferredCol && preferredActive !== 'tools') {+ resolvedTarget = {+ side: fallbackSide,+ targetColId: preferredCol.id,+ insertGroupIndex: preferredCol.groups.length,+ };+ } else {+ resolvedTarget = {+ side: fallbackSide,+ insertColumnIndex: fallbackSide === 'left' ? 0 : sideCols.length,+ };+ }+ }+ }++ let current = movePanelInLayout(layout, panelsToDock[0], resolvedTarget);+ const anchored = findPanelLocation(current, panelsToDock[0]);++ if (anchored && panelsToDock.length > 1) {+ for (let i = 1; i < panelsToDock.length; i++) {+ current = movePanelInLayout(current, panelsToDock[i], {+ side: anchored.side,+ targetColId: anchored.colId,+ targetGroupId: anchored.groupId,+ });+ }+ current = setGroupActivePanelInLayout(current, anchored.colId, anchored.groupId, preferredActive);+ }++ return current;+}++export function moveFloatingPanelInLayout(+ layout: WorkspaceLayout,+ floatingId: string,+ x: number,+ y: number,+ viewport?: { width: number; height: number }+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ const idx = existing.findIndex((f) => f.id === floatingId);+ if (idx < 0) return layout;++ const fp = existing[idx];+ const clamped = clampFloatingRect(x, y, fp.width, fp.height, fp.panelIds, viewport);+ if (clamped.x === fp.x && clamped.y === fp.y) return layout;++ const nextFloating = existing.map((f) =>+ f.id === floatingId ? { ...f, x: clamped.x, y: clamped.y } : f+ );+ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: nextFloating,+ };+}++export function resizeFloatingPanelInLayout(+ layout: WorkspaceLayout,+ floatingId: string,+ rect: { x?: number; y?: number; width: number; height: number },+ viewport?: { width: number; height: number }+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ const fp = existing.find((f) => f.id === floatingId);+ if (!fp) return layout;++ const clamped = clampFloatingRect(+ rect.x ?? fp.x,+ rect.y ?? fp.y,+ rect.width,+ rect.height,+ fp.panelIds,+ viewport+ );+ if (+ clamped.x === fp.x &&+ clamped.y === fp.y &&+ clamped.width === fp.width &&+ clamped.height === fp.height+ ) {+ return layout;+ }++ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: existing.map((f) => (f.id === floatingId ? { ...f, ...clamped } : f)),+ };+}++export function toggleFloatingCollapsedInLayout(+ layout: WorkspaceLayout,+ floatingId: string,+ forceValue?: boolean+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ if (!existing.some((f) => f.id === floatingId)) return layout;+ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: existing.map((f) =>+ f.id === floatingId+ ? { ...f, collapsed: forceValue !== undefined ? forceValue : !f.collapsed }+ : f+ ),+ };+}++export function setFloatingActivePanelInLayout(+ layout: WorkspaceLayout,+ floatingId: string,+ panelId: DockPanelId+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ const target = existing.find((f) => f.id === floatingId);+ if (!target || !target.panelIds.includes(panelId)) return layout;+ const maxZ = existing.reduce((acc, p) => Math.max(acc, p.zIndex), 0);+ const nextFloating = normalizeFloatingZIndices(+ existing.map((f) =>+ f.id === floatingId+ ? { ...f, activePanelId: panelId, collapsed: false, zIndex: maxZ + 1 }+ : f+ )+ );+ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: nextFloating,+ };+}++export function bringFloatingPanelToFrontInLayout(+ layout: WorkspaceLayout,+ floatingId: string+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ const target = existing.find((f) => f.id === floatingId);+ if (!target) return layout;+ const maxZ = existing.reduce((acc, p) => Math.max(acc, p.zIndex), 0);+ if (target.zIndex === maxZ && existing.filter((p) => p.zIndex === maxZ).length === 1) {+ return layout;+ }+ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: normalizeFloatingZIndices(+ existing.map((f) => (f.id === floatingId ? { ...f, zIndex: maxZ + 1 } : f))+ ),+ };+}++export function closeFloatingPanelInLayout(+ layout: WorkspaceLayout,+ floatingId: string+): WorkspaceLayout {+ const existing = layout.floatingPanels ?? [];+ if (!existing.some((f) => f.id === floatingId)) return layout;+ return {+ leftDocks: layout.leftDocks,+ rightDocks: layout.rightDocks,+ floatingPanels: normalizeFloatingZIndices(existing.filter((f) => f.id !== floatingId)),};}@@ -593,8 +1074,9 @@ export function togglePanelInLayout(layout: WorkspaceLayout,panelId: DockPanelId): WorkspaceLayout {- const existing = findPanelLocation(layout, panelId);- if (existing) {+ const existingDocked = findPanelLocation(layout, panelId);+ const existingFloating = findFloatingPanelLocation(layout, panelId);+ if (existingDocked || existingFloating) {return removePanelFromLayout(layout, panelId);}const meta = DOCK_PANEL_META[panelId];@@ -653,6 +1135,7 @@ function sanitizeColumns(raw: unknown, seenPanels: Set<DockPanelId>): DockColumnpanelIds,activePanelId,heightRatio,+ collapsed: Boolean(gRec.collapsed),});}if (groups.length === 0) continue;@@ -667,14 +1150,80 @@ function sanitizeColumns(raw: unknown, seenPanels: Set<DockPanelId>): DockColumnreturn pruneEmptyContainers(result);}+function sanitizeFloatingPanels(raw: unknown, seenPanels: Set<DockPanelId>): FloatingPanelState[] {+ if (!Array.isArray(raw)) return [];+ const result: FloatingPanelState[] = [];+ for (const item of raw) {+ if (!item || typeof item !== 'object') continue;+ const rec = item as Record<string, unknown>;+ const rawPids = Array.isArray(rec.panelIds) ? rec.panelIds : [];+ const panelIds: DockPanelId[] = [];+ for (const pid of rawPids) {+ if (typeof pid === 'string' && VALID_PANEL_SET.has(pid)) {+ const typedPid = pid as DockPanelId;+ if (!seenPanels.has(typedPid)) {+ seenPanels.add(typedPid);+ panelIds.push(typedPid);+ }+ }+ }+ if (panelIds.length === 0) continue;+ const activePanelId =+ typeof rec.activePanelId === 'string' && panelIds.includes(rec.activePanelId as DockPanelId)+ ? (rec.activePanelId as DockPanelId)+ : panelIds[0];+ const meta = DOCK_PANEL_META[activePanelId];+ const rawX = typeof rec.x === 'number' && Number.isFinite(rec.x) ? rec.x : 180;+ const rawY = typeof rec.y === 'number' && Number.isFinite(rec.y) ? rec.y : 120;+ const rawW =+ typeof rec.width === 'number' && Number.isFinite(rec.width)+ ? rec.width+ : meta.defaultFloatWidth;+ const rawH =+ typeof rec.height === 'number' && Number.isFinite(rec.height)+ ? rec.height+ : meta.defaultFloatHeight;+ const rect = clampFloatingRect(rawX, rawY, rawW, rawH, panelIds);+ const zIndex =+ typeof rec.zIndex === 'number' && Number.isFinite(rec.zIndex) && rec.zIndex > 0+ ? Math.round(rec.zIndex)+ : result.length + 1;+ let lastDock: FloatingPanelLastDock | undefined;+ if (rec.lastDock && typeof rec.lastDock === 'object') {+ const ld = rec.lastDock as Record<string, unknown>;+ if (ld.side === 'left' || ld.side === 'right') {+ lastDock = {+ side: ld.side,+ colId: typeof ld.colId === 'string' ? ld.colId : undefined,+ groupId: typeof ld.groupId === 'string' ? ld.groupId : undefined,+ };+ }+ }+ result.push({+ id: typeof rec.id === 'string' && rec.id.trim() ? rec.id : makeUid('float'),+ panelIds,+ activePanelId,+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ collapsed: Boolean(rec.collapsed),+ zIndex,+ lastDock,+ });+ }+ return normalizeFloatingZIndices(result);+}+export function sanitizeLayout(raw: unknown): WorkspaceLayout | null {if (!raw || typeof raw !== 'object') return null;const rec = raw as Record<string, unknown>;const seen = new Set<DockPanelId>();const leftDocks = sanitizeColumns(rec.leftDocks, seen);const rightDocks = sanitizeColumns(rec.rightDocks, seen);- if (leftDocks.length === 0 && rightDocks.length === 0) return null;- return { leftDocks, rightDocks };+ const floatingPanels = sanitizeFloatingPanels(rec.floatingPanels, seen);+ if (leftDocks.length === 0 && rightDocks.length === 0 && floatingPanels.length === 0) return null;+ return { leftDocks, rightDocks, floatingPanels };}function sanitizeQuickAccessItems(raw: unknown): QuickAccessItem[] {@@ -724,7 +1273,7 @@ function attachMigratedPanelToLayout(layout: WorkspaceLayout,panelId: DockPanelId): WorkspaceLayout {- if (findPanelLocation(layout, panelId)) return layout;+ if (findPanelLocation(layout, panelId) || findFloatingPanelLocation(layout, panelId)) return layout;const anchor =findPanelLocation(layout, 'navigator') ?? findPanelLocation(layout, 'sub-view');if (anchor) {