@skalar-os/canvas 0.0.0-stage → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Skalar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # @skalar-os/canvas
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Grid-based canvas con drag & drop, pan, zoom y navegación programática.
4
+
5
+ ## Instalación
6
+
7
+ ```bash
8
+ pnpm add @skalar-os/canvas
9
+ pnpm add @dnd-kit/core react react-dom # peer dependencies
10
+ ```
11
+
12
+ Paquete público bajo licencia MIT. No necesita token ni credenciales.
13
+
14
+ ## Publicar
15
+
16
+ Nunca a mano — siempre por el workflow, que hace `install → build → bump → publish → commit`:
17
+
18
+ ```bash
19
+ gh workflow run release.yml -f bump=patch # patch | minor | major
20
+ ```
21
+
22
+ Necesita el secret `NPM_TOKEN` de tipo **Automation** (uno normal falla en CI por el 2FA), con
23
+ permiso de lectura y escritura.
24
+
25
+ La visibilidad en npm la fija la primera publicación y se hereda después. La mantienen pública
26
+ el `--access public` del workflow y el `publishConfig` del `package.json`; conviene no tocar
27
+ ninguno de los dos.
28
+
29
+ ## Uso Básico
30
+
31
+ ```tsx
32
+ import { Canvas, type Widget, type CanvasHandle } from '@skalar-os/canvas';
33
+
34
+ const widgets: Widget[] = [
35
+ { id: '1', type: 'chart', position: { x: 0, y: 0 }, size: { width: 2, height: 2 }, title: 'Sales' },
36
+ ];
37
+
38
+ function App() {
39
+ const canvasRef = useRef<CanvasHandle>(null);
40
+
41
+ return (
42
+ <Canvas
43
+ ref={canvasRef}
44
+ widgets={widgets}
45
+ onWidgetMove={(id, pos) => updateWidget(id, pos)}
46
+ onWidgetSelect={(id) => setSelected(id)}
47
+ renderWidget={(widget, isSelected) => <MyWidget data={widget} />}
48
+ />
49
+ );
50
+ }
51
+ ```
52
+
53
+ ## API
54
+
55
+ ### CanvasProps
56
+
57
+ | Prop | Tipo | Descripción |
58
+ |------|------|-------------|
59
+ | `widgets` | `Widget[]` | Array de widgets a renderizar |
60
+ | `selectedWidgetId` | `string` | ID del widget seleccionado |
61
+ | `tool` | `'select' \| 'hand'` | Herramienta activa |
62
+ | `onWidgetMove` | `(id, position) => void` | Callback cuando widget se mueve |
63
+ | `onWidgetSelect` | `(id \| null) => void` | Callback cuando widget se selecciona |
64
+ | `onWidgetAdd` | `(widget) => void` | Callback cuando se agrega widget |
65
+ | `onToolChange` | `(tool) => void` | Callback cuando cambia herramienta |
66
+ | `onUndo` | `() => void` | Callback para Ctrl+Z |
67
+ | `onRedo` | `() => void` | Callback para Ctrl+Shift+Z |
68
+ | `renderWidget` | `(widget, isSelected) => ReactNode` | Render custom de widgets |
69
+
70
+ ### CanvasHandle (ref)
71
+
72
+ ```tsx
73
+ const canvasRef = useRef<CanvasHandle>(null);
74
+
75
+ // Navegar a un widget
76
+ canvasRef.current?.navigateToWidget('widget-id', { animate: true, select: true });
77
+
78
+ // Ajustar vista a todos los widgets
79
+ canvasRef.current?.fitToContent();
80
+
81
+ // Resetear vista
82
+ canvasRef.current?.resetView();
83
+
84
+ // Get/Set pan y zoom
85
+ canvasRef.current?.getPanZoom();
86
+ canvasRef.current?.setPanZoom({ x: 0, y: 0, zoom: 1 });
87
+ ```
88
+
89
+ ### Keyboard Shortcuts
90
+
91
+ | Tecla | Acción |
92
+ |-------|--------|
93
+ | `V` | Select tool |
94
+ | `H` | Hand tool |
95
+ | `Space` (hold) | Hand tool temporal |
96
+ | `Escape` | Cancelar placement |
97
+ | `Ctrl+Z` | Undo |
98
+ | `Ctrl+Shift+Z` | Redo |
99
+
100
+ ## Arquitectura
101
+
102
+ ```
103
+ src/
104
+ ├── components/
105
+ │ ├── Canvas.tsx # Componente principal con forwardRef
106
+ │ └── Grid.tsx # Grid con drop zone
107
+ ├── layers/ # Sistema de capas (z-index)
108
+ │ ├── GridLines.tsx # z-1: líneas del grid
109
+ │ ├── CellNumbers.tsx # z-2: números de celda
110
+ │ ├── CellHighlight.tsx # z-3: highlight de hover
111
+ │ ├── WidgetPlaceholder.tsx # z-4: preview de drop
112
+ │ ├── WidgetLayer.tsx # z-5: widgets
113
+ │ └── DragOverlayLayer.tsx # z-6: widget siendo arrastrado
114
+ ├── hooks/
115
+ │ ├── useGridSnap.ts # Tracking de posición en grid
116
+ │ └── useKeyboardShortcuts.ts # Atajos de teclado
117
+ ├── utils/
118
+ │ ├── gridUtils.ts # Cálculos de grid y colisiones
119
+ │ └── navigationUtils.ts # Cálculos de navegación
120
+ └── constants/
121
+ └── shortcuts.ts # Configuración de atajos
122
+ ```
123
+
124
+ ## Development
125
+
126
+ ```bash
127
+ pnpm install # Instalar dependencias
128
+ pnpm build # Build producción
129
+ pnpm dev # Watch mode
130
+ pnpm dev:playground # Playground local
131
+ ```
@@ -0,0 +1,15 @@
1
+ import React, { ReactNode } from 'react';
2
+ import type { ToolType } from './types';
3
+ interface ToolContextType {
4
+ selectedTool: ToolType;
5
+ setSelectedTool: (tool: ToolType) => void;
6
+ toggleHandTool: () => void;
7
+ }
8
+ declare const ToolContext: React.Context<ToolContextType | undefined>;
9
+ interface ToolProviderProps {
10
+ children: ReactNode;
11
+ defaultTool?: ToolType;
12
+ }
13
+ export declare const ToolProvider: React.FC<ToolProviderProps>;
14
+ export declare const useTool: () => ToolContextType;
15
+ export { ToolContext };
@@ -0,0 +1,22 @@
1
+ import React from 'react';
2
+ import type { CanvasProps, CanvasHandle } from '../types';
3
+ /**
4
+ * Canvas Component
5
+ *
6
+ * Main canvas for rendering and managing widgets on a grid.
7
+ * Wrapped with ToolProvider for tool state management.
8
+ *
9
+ * @example
10
+ * ```tsx
11
+ * const canvasRef = useRef<CanvasHandle>(null);
12
+ *
13
+ * // Navigate to a widget
14
+ * canvasRef.current?.navigateToWidget('widget-123');
15
+ *
16
+ * // Fit all widgets in view
17
+ * canvasRef.current?.fitToContent();
18
+ *
19
+ * <Canvas ref={canvasRef} widgets={widgets} />
20
+ * ```
21
+ */
22
+ export declare const Canvas: React.ForwardRefExoticComponent<CanvasProps & React.RefAttributes<CanvasHandle>>;
@@ -0,0 +1,48 @@
1
+ import React from 'react';
2
+ import type { GridConfig } from '../types';
3
+ import type { GridPosition, PreviewState, InternalDragState, PanZoomState } from '../types';
4
+ interface GridProps {
5
+ /** Grid content (widgets) */
6
+ children?: React.ReactNode;
7
+ /** Additional class name */
8
+ className?: string;
9
+ /** Click handler for the canvas background */
10
+ onCanvasClick?: (event: React.MouseEvent) => void;
11
+ /** Callback when mouse grid position changes */
12
+ onGridPositionChange?: (position: GridPosition | null) => void;
13
+ /** Show cell highlight on hover */
14
+ showGridHighlight?: boolean;
15
+ /** Show the grid chrome (lines, cell numbers, border). Off in live mode. */
16
+ showGrid?: boolean;
17
+ /** Additional inline styles */
18
+ style?: React.CSSProperties;
19
+ /** Preview state for placement/drag */
20
+ previewState?: PreviewState;
21
+ /** Current pan and zoom state */
22
+ panZoom?: PanZoomState;
23
+ /** Current tool */
24
+ selectedTool?: 'select' | 'hand';
25
+ /** Mouse down handler (for panning) */
26
+ onMouseDown?: (event: React.MouseEvent) => void;
27
+ /** Whether currently dragging a widget */
28
+ isDragging?: boolean;
29
+ /** Internal drag state */
30
+ dragState?: InternalDragState;
31
+ /** Viewport of the canvas this grid lives in, for measuring pointer coordinates. */
32
+ containerRef: React.RefObject<HTMLElement | null>;
33
+ /** Grid configuration */
34
+ config: GridConfig;
35
+ }
36
+ /**
37
+ * Grid Component
38
+ *
39
+ * Container for all canvas layers. Renders:
40
+ * - Background
41
+ * - GridLines (z-1)
42
+ * - CellNumbers (z-2)
43
+ * - CellHighlight (z-3) - when hovering
44
+ * - WidgetPlaceholder (z-4) - when placing/dragging
45
+ * - Children/Widgets (z-5)
46
+ */
47
+ export declare const Grid: React.FC<GridProps>;
48
+ export {};
@@ -0,0 +1,2 @@
1
+ export { Canvas } from './Canvas';
2
+ export { Grid } from './Grid';
@@ -0,0 +1,2 @@
1
+ export { KEYBOARD_SHORTCUTS, matchesModifiers, findMatchingShortcut, } from './shortcuts';
2
+ export type { ShortcutAction, ShortcutModifiers, ShortcutDefinition, } from './shortcuts';
@@ -0,0 +1,55 @@
1
+ import type { ToolType } from '../types';
2
+ /**
3
+ * Keyboard shortcut action types
4
+ */
5
+ export type ShortcutAction = {
6
+ type: 'SET_TOOL';
7
+ tool: ToolType;
8
+ } | {
9
+ type: 'CANCEL_PLACEMENT';
10
+ } | {
11
+ type: 'TEMPORARY_TOOL_START';
12
+ tool: ToolType;
13
+ } | {
14
+ type: 'TEMPORARY_TOOL_END';
15
+ } | {
16
+ type: 'UNDO';
17
+ } | {
18
+ type: 'REDO';
19
+ };
20
+ /**
21
+ * Modifier keys for shortcuts
22
+ */
23
+ export interface ShortcutModifiers {
24
+ ctrl?: boolean;
25
+ shift?: boolean;
26
+ alt?: boolean;
27
+ }
28
+ /**
29
+ * Shortcut definition with key and modifiers
30
+ */
31
+ export interface ShortcutDefinition {
32
+ /** The key to listen for (lowercase) */
33
+ key: string;
34
+ /** Required modifier keys */
35
+ modifiers?: ShortcutModifiers;
36
+ /** Action to perform on keydown */
37
+ action: ShortcutAction;
38
+ /** Action to perform on keyup (for hold-to-activate shortcuts) */
39
+ onRelease?: ShortcutAction;
40
+ /** Description for documentation/UI */
41
+ description: string;
42
+ }
43
+ /**
44
+ * All keyboard shortcuts for the canvas
45
+ * Centralized configuration for easy maintenance
46
+ */
47
+ export declare const KEYBOARD_SHORTCUTS: ShortcutDefinition[];
48
+ /**
49
+ * Check if event modifiers match shortcut modifiers
50
+ */
51
+ export declare const matchesModifiers: (event: KeyboardEvent, modifiers?: ShortcutModifiers) => boolean;
52
+ /**
53
+ * Find matching shortcut for a keyboard event
54
+ */
55
+ export declare const findMatchingShortcut: (event: KeyboardEvent) => ShortcutDefinition | undefined;
@@ -0,0 +1,4 @@
1
+ export { useGridSnap } from './useGridSnap';
2
+ export { useKeyboardShortcuts } from './useKeyboardShortcuts';
3
+ export { useWidgetVisibility } from './useWidgetVisibility';
4
+ export type { UseWidgetVisibilityOptions, UseWidgetVisibilityReturn } from './useWidgetVisibility';
@@ -0,0 +1,37 @@
1
+ import type { GridPosition, Widget } from '../types';
2
+ interface UseGridSnapProps {
3
+ enabled?: boolean;
4
+ onGridPositionChange?: (position: GridPosition | null) => void;
5
+ workspaceSize: {
6
+ width: number;
7
+ height: number;
8
+ };
9
+ panZoom?: {
10
+ x: number;
11
+ y: number;
12
+ zoom: number;
13
+ };
14
+ dragState?: {
15
+ isDragging: boolean;
16
+ draggedWidget: Widget | null;
17
+ initialOffset?: {
18
+ x: number;
19
+ y: number;
20
+ };
21
+ };
22
+ /**
23
+ * The canvas viewport this grid belongs to. Every pointer coordinate is measured against its
24
+ * rect, so it has to be *this* canvas — not whichever one the document happens to hold first.
25
+ */
26
+ containerRef: React.RefObject<HTMLElement | null>;
27
+ }
28
+ export declare const useGridSnap: ({ enabled, onGridPositionChange, workspaceSize, panZoom, dragState, containerRef, }: UseGridSnapProps) => {
29
+ currentGridPosition: GridPosition | null;
30
+ visualGridPosition: GridPosition | null;
31
+ handlers: {
32
+ onMouseMove: (event: React.MouseEvent) => void;
33
+ onMouseLeave: () => void;
34
+ };
35
+ getGridPositionFromMouse: (mouseX: number, mouseY: number) => GridPosition | null;
36
+ };
37
+ export {};
@@ -0,0 +1,33 @@
1
+ import type { ToolType } from '../types';
2
+ interface UseKeyboardShortcutsProps {
3
+ /** Current tool */
4
+ currentTool: ToolType;
5
+ /** Callback to change tool */
6
+ onToolChange: (tool: ToolType) => void;
7
+ /** Whether placement mode is active */
8
+ isPlacementActive: boolean;
9
+ /** Callback to cancel placement */
10
+ onCancelPlacement?: () => void;
11
+ /** Callback for undo action */
12
+ onUndo?: () => void;
13
+ /** Callback for redo action */
14
+ onRedo?: () => void;
15
+ /** Whether shortcuts are enabled */
16
+ enabled?: boolean;
17
+ }
18
+ interface UseKeyboardShortcutsReturn {
19
+ /** Whether spacebar is currently held */
20
+ isSpaceHeld: boolean;
21
+ }
22
+ /**
23
+ * Hook for managing keyboard shortcuts in the canvas
24
+ *
25
+ * Features:
26
+ * - Centralized shortcut handling
27
+ * - Support for modifier keys (Ctrl/Cmd, Shift, Alt)
28
+ * - Support for hold-to-activate shortcuts (spacebar → hand tool)
29
+ * - Ignores shortcuts when typing in inputs
30
+ * - Handles window blur to reset held keys
31
+ */
32
+ export declare const useKeyboardShortcuts: ({ currentTool, onToolChange, isPlacementActive, onCancelPlacement, onUndo, onRedo, enabled, }: UseKeyboardShortcutsProps) => UseKeyboardShortcutsReturn;
33
+ export {};
@@ -0,0 +1,54 @@
1
+ /**
2
+ * useWidgetVisibility Hook
3
+ *
4
+ * Manages widget visibility detection based on viewport and pan/zoom state.
5
+ * Provides optimized tracking with throttling to prevent excessive updates.
6
+ */
7
+ import type { Widget, PanZoomState, ViewportDimensions } from '../types';
8
+ /**
9
+ * Configuration for the visibility hook
10
+ */
11
+ export interface UseWidgetVisibilityOptions {
12
+ /** Widgets to track */
13
+ widgets: Widget[];
14
+ /** Current pan/zoom state */
15
+ panZoom: PanZoomState;
16
+ /** Function to get viewport dimensions */
17
+ getViewport: () => ViewportDimensions;
18
+ /** Number of buffer cells around viewport (default: 1) */
19
+ bufferZone?: number;
20
+ /** Throttle interval in ms (default: 100) */
21
+ throttleMs?: number;
22
+ /** Callback when visibility changes */
23
+ onVisibilityChange?: (visibleIds: string[]) => void;
24
+ /** Whether visibility tracking is enabled (default: true) */
25
+ enabled?: boolean;
26
+ }
27
+ /**
28
+ * Return type for the visibility hook
29
+ */
30
+ export interface UseWidgetVisibilityReturn {
31
+ /** Get current visible widget IDs (includes buffer zone) */
32
+ getVisibleIds: () => string[];
33
+ /** Check if a specific widget is visible */
34
+ isWidgetVisible: (widgetId: string) => boolean;
35
+ /** Force recalculation and callback */
36
+ recalculate: () => void;
37
+ }
38
+ /**
39
+ * Hook for tracking widget visibility in the canvas viewport
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * const { getVisibleIds, isWidgetVisible } = useWidgetVisibility({
44
+ * widgets,
45
+ * panZoom: { x: panPosition.x, y: panPosition.y, zoom: zoomLevel },
46
+ * getViewport: () => ({ width: container.clientWidth, height: container.clientHeight }),
47
+ * bufferZone: 1,
48
+ * onVisibilityChange: (ids) => {
49
+ * // Update subscriptions
50
+ * },
51
+ * });
52
+ * ```
53
+ */
54
+ export declare const useWidgetVisibility: ({ widgets, panZoom, getViewport, bufferZone, throttleMs, onVisibilityChange, enabled, }: UseWidgetVisibilityOptions) => UseWidgetVisibilityReturn;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @skalar-app/canvas
3
+ *
4
+ * Grid-based canvas with drag and drop widgets
5
+ */
6
+ export type { GridPosition, WidgetSize, Widget, ToolType, CanvasMode, GridConfig, WidgetTemplate, PreviewState, InternalDragState, PanZoomState, CanvasState, CanvasProps, CanvasHandle, NavigateToWidgetOptions, ViewportDimensions, WidgetVisibilityState, WidgetVisibilityInfo, } from './types';
7
+ export { GRID_CONFIG } from './types';
8
+ export { Canvas } from './components/Canvas';
9
+ export { Grid } from './components/Grid';
10
+ export { GridLines, CellNumbers, CellHighlight, WidgetPlaceholder, WidgetLayer, DragOverlayLayer, LAYER_Z_INDEX, } from './layers';
11
+ export type { LayerZIndex } from './layers';
12
+ export { ToolProvider, useTool, ToolContext } from './ToolContext';
13
+ export { useGridSnap, useKeyboardShortcuts, useWidgetVisibility } from './hooks';
14
+ export type { UseWidgetVisibilityOptions, UseWidgetVisibilityReturn } from './hooks';
15
+ export { KEYBOARD_SHORTCUTS, matchesModifiers, findMatchingShortcut, } from './constants';
16
+ export type { ShortcutAction, ShortcutModifiers, ShortcutDefinition } from './constants';
17
+ export { isValidGridPosition, getConflictingWidgets, doWidgetsOverlap, getWidgetPlacementPosition, calculateCenteredPanPosition, clampPanPosition, calculateWidgetsBoundingBox, calculateFitToContent, interpolatePanZoom, calculateViewportGridBounds, widgetIntersectsBounds, expandBoundsWithBuffer, calculateWidgetVisibility, calculateAllWidgetsVisibility, getVisibleWidgetIds, areVisibleIdsEqual, } from './utils';
18
+ export type { ViewportGridBounds } from './utils';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use client";"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react/jsx-runtime"),l=require("react"),at=require("@dnd-kit/core"),Ge=e=>e&&e.__esModule?e:{default:e},It=Ge(l),B={cellSize:400,gap:20,workspaceSize:{width:10,height:10},padding:{top:40,right:40,bottom:40,left:40},zoomLimits:{min:.25,max:2,step:.25}};function ie(e){var t,n,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=ie(e[t]))&&(s&&(s+=" "),s+=n)}else for(n in e)e[n]&&(s&&(s+=" "),s+=n);return s}function se(){for(var e,t,n=0,s="",i=arguments.length;n<i;n++)(e=arguments[n])&&(t=ie(e))&&(s&&(s+=" "),s+=t);return s}const ne=({enabled:e=!0,onGridPositionChange:t,workspaceSize:n,panZoom:s={x:0,y:0,zoom:1},dragState:i,containerRef:a})=>{const[o,c]=l.useState(null),[u,f]=l.useState(null),h=l.useRef(null),x=l.useRef(null),{cellSize:k,gap:m}=B,b=l.useMemo(()=>{const D=k+m,E=n.width*k+n.width*m,y=n.height*k+n.height*m;return{totalCellSize:D,workspaceWidth:E,workspaceHeight:y,cellSize:k,gap:m}},[k,m,n]),I=l.useRef(void 0),U=l.useCallback(D=>{I.current||(I.current=requestAnimationFrame(()=>{D(),I.current=void 0}))},[]),C=l.useCallback((D,E,y=!1)=>{let O=(D-s.x)/s.zoom,Y=(E-s.y)/s.zoom;return y&&(i!=null&&i.isDragging)&&i.initialOffset&&(O-=i.initialOffset.x,Y-=i.initialOffset.y),{mouseX:O,mouseY:Y}},[s,i]),J=l.useCallback((D,E)=>{const{totalCellSize:y,cellSize:O,gap:Y}=b;if(D<0||E<0||D>=b.workspaceWidth||E>=b.workspaceHeight)return null;const S=D-Y,$=E-Y;if(S<0||$<0)return null;const z=Math.floor(S/y),R=Math.floor($/y),V=z*y,w=R*y;return S>=V&&S<V+O&&$>=w&&$<w+O?{x:z,y:R}:null},[b]),Z=l.useCallback(D=>{if(!e)return;const E=a.current;if(!E)return;const y=!!(i!=null&&i.isDragging&&i.initialOffset);let O;y&&x.current===E&&h.current?O=h.current:(O=E.getBoundingClientRect(),x.current=E,h.current=O);const Y=D.clientX-O.left,S=D.clientY-O.top,{mouseX:$,mouseY:z}=C(Y,S,y),{mouseX:R,mouseY:V}=C(Y,S,!1);if($<0||z<0||$>b.workspaceWidth||z>b.workspaceHeight){(o!==null||u!==null)&&(c(null),f(null),t==null||t(null));return}const w=J($,z),N=y?J(R,V):w;w!==null&&(w.x!==(o==null?void 0:o.x)||w.y!==(o==null?void 0:o.y))&&(c(w),t==null||t(w)),N!==null&&(N.x!==(u==null?void 0:u.x)||N.y!==(u==null?void 0:u.y))&&f(N)},[e,J,t,o,u,C,b,i,a]),nt=l.useCallback(D=>{(i==null?void 0:i.isDragging)&&i.draggedWidget?U(()=>Z(D)):Z(D)},[U,Z,i]);l.useEffect(()=>{i!=null&&i.isDragging?(c(null),f(null)):(h.current=null,x.current=null)},[i==null?void 0:i.isDragging]),l.useEffect(()=>{h.current=null},[s.x,s.y,s.zoom]);const ot=l.useCallback(()=>{e&&(c(null),f(null),t==null||t(null))},[e,t]);return{currentGridPosition:o,visualGridPosition:u,handlers:{onMouseMove:nt,onMouseLeave:ot},getGridPositionFromMouse:J}},lt={BACKGROUND:0,GRID_LINES:1,CELL_NUMBERS:2,CELL_HIGHLIGHT:3,WIDGET_PLACEHOLDER:4,WIDGETS:5,DRAG_OVERLAY:6},st=e=>{const{cellSize:t,gap:n,workspaceSize:s}=e;return{width:s.width*t+(s.width+1)*n,height:s.height*t+(s.height+1)*n}},mt=(e,t,n,s=B.workspaceSize)=>e.x<0||e.y<0||e.x+t.width>s.width||e.y+t.height>s.height?!1:ft(e,t,n).length===0,ft=(e,t,n)=>{const s=[];for(const i of n)oe(e,t,i.position,i.size)&&s.push(i.id);return s},oe=(e,t,n,s)=>{const i=e.x,a=e.x+t.width-1,o=e.y,c=e.y+t.height-1,u=n.x,f=n.x+s.width-1,h=n.y,x=n.y+s.height-1;return!(a<u||i>f||c<h||o>x)},pt=(e,t)=>{const{cellSize:n,gap:s}=B;return{left:s+e.x*(n+s),top:s+e.y*(n+s),width:t.width*n+(t.width-1)*s,height:t.height*n+(t.height-1)*s}},re=({config:e,lineColor:t="var(--canvas-grid-line, #E5E7EB)",centerLineColor:n="var(--canvas-grid-center-line, #F3F4F6)"})=>{const{cellSize:s,gap:i,workspaceSize:a}=e,{width:o,height:c}=st(e);return d.jsxs("div",{"data-layer":"grid-lines",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:lt.GRID_LINES},children:[d.jsx("div",{style:{position:"absolute",left:0,top:0,width:1,height:c,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:i-1,top:0,width:1,height:c,backgroundColor:t}}),Array.from({length:a.width-1},(u,f)=>{const h=i+(f+1)*s+f*i;return d.jsxs(It.default.Fragment,{children:[d.jsx("div",{style:{position:"absolute",left:h,top:0,width:1,height:c,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:h+i-1,top:0,width:1,height:c,backgroundColor:t}})]},`v-double-${f}`)}),d.jsx("div",{style:{position:"absolute",left:o-i+1,top:0,width:1,height:c,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:o-2,top:0,width:1,height:c,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:0,top:0,width:o,height:1,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:0,top:i-1,width:o,height:1,backgroundColor:t}}),Array.from({length:a.height-1},(u,f)=>{const h=i+(f+1)*s+f*i;return d.jsxs(It.default.Fragment,{children:[d.jsx("div",{style:{position:"absolute",left:0,top:h,width:o,height:1,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:0,top:h+i-1,width:o,height:1,backgroundColor:t}})]},`h-double-${f}`)}),d.jsx("div",{style:{position:"absolute",left:0,top:c-i+1,width:o,height:1,backgroundColor:t}}),d.jsx("div",{style:{position:"absolute",left:0,top:c-2,width:o,height:1,backgroundColor:t}}),Array.from({length:a.width},(u,f)=>{const h=i+f*(s+i)+s/2;return d.jsx("div",{style:{position:"absolute",left:h,top:0,width:1,height:c,backgroundColor:n}},`v-center-${f}`)}),Array.from({length:a.height},(u,f)=>{const h=i+f*(s+i)+s/2;return d.jsx("div",{style:{position:"absolute",left:0,top:h,width:o,height:1,backgroundColor:n}},`h-center-${f}`)})]})},le=({config:e,color:t="var(--canvas-grid-number, #9CA3AF)",fontSize:n=48,opacity:s=.4})=>{const{cellSize:i,gap:a,workspaceSize:o}=e;return d.jsx("div",{"data-layer":"cell-numbers",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:lt.CELL_NUMBERS},children:Array.from({length:o.height},(c,u)=>Array.from({length:o.width},(f,h)=>{const x=u*o.width+h+1;return d.jsx("div",{style:{position:"absolute",display:"flex",alignItems:"flex-start",justifyContent:"flex-start",fontSize:`${n}px`,fontWeight:300,color:t,left:a+h*(i+a)+8,top:a+u*(i+a)+8,width:i,height:i,opacity:s,userSelect:"none"},children:x},`cell-number-${u}-${h}`)}))})},Ke={hover:{borderColor:"rgba(96, 165, 250, 0.4)",backgroundColor:"rgba(96, 165, 250, 0.05)"},selected:{borderColor:"rgba(37, 99, 235, 1)",backgroundColor:"rgba(37, 99, 235, 0.2)"},preview:{borderColor:"rgba(74, 222, 128, 1)",backgroundColor:"rgba(74, 222, 128, 0.2)"}},ce=({position:e,type:t="hover",size:n={width:1,height:1}})=>{const{cellSize:s,gap:i}=B,a=n.width*s+(n.width-1)*i,o=n.height*s+(n.height-1)*i,c=Ke[t];return d.jsx("div",{"data-layer":"cell-highlight","data-highlight-type":t,style:{position:"absolute",left:i+e.x*(s+i),top:i+e.y*(s+i),width:a,height:o,border:`2px solid ${c.borderColor}`,backgroundColor:c.backgroundColor,borderRadius:"8px",pointerEvents:"none",zIndex:lt.CELL_HIGHLIGHT,transition:"all 150ms ease"}})},ae=({position:e,size:t,mode:n,isValidPosition:s,conflictingWidgets:i=[],label:a=""})=>{const{cellSize:o,gap:c}=B,u=t.width*o+(t.width-1)*c,f=t.height*o+(t.height-1)*c,h=s?"#93C5FD":"#FCA5A5",x=s?"rgba(96, 165, 250, 0.15)":"#FEE2E2",m=s?n==="placement"?{backgroundColor:"#3B82F6",color:"white"}:{backgroundColor:"#10B981",color:"white"}:{backgroundColor:"#EF4444",color:"white"},b=()=>`${s?"✓":"✗"} ${n==="placement"?"Place":"Moving"}: ${a}`;return d.jsxs("div",{"data-layer":"widget-placeholder","data-mode":n,"data-valid":s,style:{position:"absolute",left:c+e.x*(o+c),top:c+e.y*(o+c),pointerEvents:"none",zIndex:lt.WIDGET_PLACEHOLDER,transition:"left 150ms ease, top 150ms ease"},children:[d.jsxs("div",{style:{width:u,height:f,border:`2px dashed ${h}`,backgroundColor:x,borderRadius:"12px",transition:"background-color 150ms, border-color 150ms",position:"relative",padding:"8px",boxSizing:"border-box"},children:[d.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center"},children:d.jsx("div",{style:{padding:"4px 8px",borderRadius:"4px",fontSize:"14px",fontWeight:500,...m},children:b()})}),(t.width>1||t.height>1)&&d.jsx("div",{style:{position:"absolute",top:"4px",right:"4px"},children:d.jsxs("div",{style:{backgroundColor:"rgba(0, 0, 0, 0.6)",color:"white",fontSize:"12px",padding:"2px 4px",borderRadius:"4px"},children:[t.width,"×",t.height]})})]}),!s&&i.length>0&&d.jsx("div",{style:{position:"absolute",bottom:"-32px",left:"50%",transform:"translateX(-50%)"},children:d.jsxs("div",{style:{backgroundColor:"#FEE2E2",border:"1px solid #FCA5A5",borderRadius:"4px",padding:"4px 8px",fontSize:"12px",color:"#B91C1C",whiteSpace:"nowrap"},children:["Conflicts with ",i.length," widget",i.length!==1?"s":""]})})]})},qe=It.default.memo(function({widget:t,isSelected:n,isHidden:s,isDraggable:i,editable:a,onWidgetClick:o,renderWidget:c}){const u=pt(t.position,t.size),{attributes:f,listeners:h,setNodeRef:x,isDragging:k}=at.useDraggable({id:t.id,disabled:!i}),m={position:"absolute",left:u.left,top:u.top,width:u.width,height:u.height,backfaceVisibility:"hidden",opacity:s?0:1,cursor:i?"move":o?"pointer":"default"},b=I=>{I.stopPropagation(),o==null||o(t.id,I)};return c?d.jsx("div",{ref:x,"data-widget-id":t.id,style:m,onClick:b,...i?{...h,...f}:{},children:d.jsx("div",{style:{width:"100%",height:"100%",pointerEvents:a?"none":"auto"},children:c(t,n)})}):d.jsxs("div",{ref:x,"data-widget-id":t.id,style:{...m,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"8px",backgroundColor:n?"#2563EB":"#3B82F6",borderWidth:"2px",borderStyle:k?"dashed":"solid",borderColor:n?"#93C5FD":"#2563EB",color:"white",fontWeight:500,fontSize:"14px",boxShadow:n?"0 10px 25px rgba(0,0,0,0.2)":"0 4px 6px rgba(0,0,0,0.1)",transition:"background-color 150ms ease, border-color 150ms ease, box-shadow 150ms ease",...k&&{zIndex:50}},onClick:b,...i?{...h,...f}:{},children:[t.title,n&&d.jsx("div",{style:{position:"absolute",top:"-8px",right:"-8px",width:"16px",height:"16px",backgroundColor:"#60A5FA",borderRadius:"50%",border:"2px solid white"}})]})},(e,t)=>e.widget.id===t.widget.id&&e.widget.position.x===t.widget.position.x&&e.widget.position.y===t.widget.position.y&&e.widget.size.width===t.widget.size.width&&e.widget.size.height===t.widget.size.height&&e.isSelected===t.isSelected&&e.isHidden===t.isHidden&&e.isDraggable===t.isDraggable&&e.editable===t.editable),de=({widgets:e,selectedWidgetId:t,draggingWidgetId:n,currentTool:s,editable:i=!0,onWidgetClick:a,renderWidget:o})=>{const c=i&&s==="select";return d.jsx("div",{"data-layer":"widgets",style:{position:"absolute",inset:0,zIndex:lt.WIDGETS},children:e.map(u=>d.jsx(qe,{widget:u,isSelected:t===u.id,isHidden:n===u.id,isDraggable:c,editable:i,onWidgetClick:a,renderWidget:o},u.id))})},ue=({draggedWidget:e,zoomLevel:t,renderDraggedWidget:n})=>{if(!e)return d.jsx(at.DragOverlay,{dropAnimation:null});const{cellSize:s,gap:i}=B,a=(e.size.width*(s+i)-i)*t,o=(e.size.height*(s+i)-i)*t;return n?d.jsx(at.DragOverlay,{dropAnimation:null,children:d.jsx("div",{style:{width:a,height:o,opacity:.7},children:n(e)})}):d.jsx(at.DragOverlay,{dropAnimation:null,children:d.jsx("div",{"data-layer":"drag-overlay",style:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"12px",backgroundColor:"#3B82F6",border:"2px dashed #93C5FD",color:"white",fontWeight:500,boxShadow:"0 25px 50px rgba(0,0,0,0.25)",width:a,height:o,cursor:"move",fontSize:`${14*t}px`,padding:"8px",boxSizing:"border-box"},children:e.title})})},he=({children:e,className:t,onCanvasClick:n,onGridPositionChange:s,showGridHighlight:i=!0,showGrid:a=!0,style:o,previewState:c,panZoom:u,selectedTool:f="select",onMouseDown:h,isDragging:x=!1,dragState:k,config:m,containerRef:b})=>{const{workspaceSize:I}=m,{width:U,height:C}=st(m),{setNodeRef:J}=at.useDroppable({id:"canvas-drop-zone"}),{currentGridPosition:Z,handlers:nt}=ne({enabled:i&&f==="select"&&!x,onGridPositionChange:s,workspaceSize:I,panZoom:u,dragState:k,containerRef:b});return d.jsxs("div",{ref:J,"data-canvas":!0,className:se(t),style:{...o,position:"relative",backgroundColor:a?"var(--canvas-grid-bg, #FAFAFA)":"transparent",border:a?"1px solid var(--canvas-grid-line, #E5E7EB)":"none",width:U,height:C},onClick:n,onMouseDown:h,...f==="select"||c!=null&&c.isActive?nt:{},children:[a&&d.jsxs(d.Fragment,{children:[d.jsx(re,{config:m}),d.jsx(le,{config:m})]}),i&&Z&&d.jsx(ce,{position:Z,type:"hover"}),(c==null?void 0:c.isActive)&&c.position&&c.size&&d.jsx(ae,{position:c.position,size:c.size,mode:c.mode||"placement",isValidPosition:c.isValidPosition,conflictingWidgets:c.conflictingWidgets,label:c.label}),d.jsx("div",{"data-layer":"widgets-container",style:{position:"absolute",inset:0,zIndex:lt.WIDGETS},children:e})]})},Lt=l.createContext(void 0),ge=({children:e,defaultTool:t="select"})=>{const[n,s]=l.useState(t),i=l.useCallback(c=>{s(c)},[]),a=l.useCallback(()=>{s(c=>c==="hand"?"select":"hand")},[]),o={selectedTool:n,setSelectedTool:i,toggleHandTool:a};return d.jsx(Lt.Provider,{value:o,children:e})},fe=()=>{const e=l.useContext(Lt);if(e===void 0)throw new Error("useTool must be used within a ToolProvider");return e},pe=[{key:"v",action:{type:"SET_TOOL",tool:"select"},description:"Switch to Select tool"},{key:"h",action:{type:"SET_TOOL",tool:"hand"},description:"Switch to Hand tool"},{key:"escape",action:{type:"CANCEL_PLACEMENT"},description:"Cancel widget placement"},{key:" ",action:{type:"TEMPORARY_TOOL_START",tool:"hand"},onRelease:{type:"TEMPORARY_TOOL_END"},description:"Hold to temporarily use Hand tool"},{key:"z",modifiers:{ctrl:!0},action:{type:"UNDO"},description:"Undo last action"},{key:"z",modifiers:{ctrl:!0,shift:!0},action:{type:"REDO"},description:"Redo last action"}],me=(e,t)=>{const n=e.ctrlKey||e.metaKey;if(!t)return!n&&!e.shiftKey&&!e.altKey;const s=t.ctrl?n:!n,i=t.shift?e.shiftKey:!e.shiftKey,a=t.alt?e.altKey:!e.altKey;return s&&i&&a},Tt=e=>{const t=e.key.toLowerCase();return pe.find(n=>n.key===t&&me(e,n.modifiers))},ye=({currentTool:e,onToolChange:t,isPlacementActive:n,onCancelPlacement:s,onUndo:i,onRedo:a,enabled:o=!0})=>{const c=l.useRef(null),u=l.useRef(!1),f=l.useCallback(m=>{switch(m.type){case"SET_TOOL":u.current||t(m.tool);break;case"CANCEL_PLACEMENT":n&&(s==null||s());break;case"TEMPORARY_TOOL_START":u.current||(u.current=!0,c.current=e,t(m.tool));break;case"TEMPORARY_TOOL_END":u.current&&c.current&&(t(c.current),c.current=null,u.current=!1);break;case"UNDO":i==null||i();break;case"REDO":a==null||a();break}},[e,n,s,t,i,a]),h=l.useCallback(m=>{var I;if(!o||m.target instanceof HTMLInputElement||m.target instanceof HTMLTextAreaElement||(I=m.target)!=null&&I.isContentEditable)return;const b=Tt(m);b&&((m.key===" "||b.action.type==="UNDO"||b.action.type==="REDO")&&m.preventDefault(),!m.repeat&&f(b.action))},[o,f]),x=l.useCallback(m=>{if(!o)return;const b=Tt(m);b!=null&&b.onRelease&&f(b.onRelease)},[o,f]),k=l.useCallback(()=>{u.current&&c.current&&(t(c.current),c.current=null,u.current=!1)},[t]);return l.useEffect(()=>{if(o)return document.addEventListener("keydown",h),document.addEventListener("keyup",x),window.addEventListener("blur",k),()=>{document.removeEventListener("keydown",h),document.removeEventListener("keyup",x),window.removeEventListener("blur",k)}},[o,h,x,k]),{isSpaceHeld:u.current}},Yt=(e,t)=>{const{cellSize:n,gap:s}=B,i=n+s,a=(0-t.x)/t.zoom,o=(0-t.y)/t.zoom,c=(e.width-t.x)/t.zoom,u=(e.height-t.y)/t.zoom,f=Math.floor((a-s)/i),h=Math.floor((o-s)/i),x=Math.ceil((c-s)/i),k=Math.ceil((u-s)/i);return{startX:f,startY:h,endX:x,endY:k}},yt=(e,t)=>{const n=e.position.x+e.size.width,s=e.position.y+e.size.height;return e.position.x<t.endX&&n>t.startX&&e.position.y<t.endY&&s>t.startY},Xt=(e,t)=>({startX:e.startX-t,startY:e.startY-t,endX:e.endX+t,endY:e.endY+t}),xe=(e,t,n=1)=>{if(yt(e,t))return"visible";const s=Xt(t,n);return yt(e,s)?"buffer":"hidden"},Ue=(e,t,n,s=1)=>{const i=Yt(t,n);return e.map(a=>({id:a.id,state:xe(a,i,s)}))},be=(e,t,n,s=1)=>{const i=Yt(t,n),a=Xt(i,s);return e.filter(o=>yt(o,a)).map(o=>o.id)},we=(e,t)=>{if(e.length!==t.length)return!1;const n=new Set(e);return t.every(s=>n.has(s))},ve=({widgets:e,panZoom:t,getViewport:n,bufferZone:s=1,throttleMs:i=100,onVisibilityChange:a,enabled:o=!0})=>{const c=l.useRef([]),u=l.useRef(null),f=l.useRef(!1),h=l.useCallback(()=>{if(!o)return[];const C=n();return C.width===0||C.height===0?[]:be(e,C,t,s)},[e,t,s,n,o]),x=l.useCallback(()=>{if(!a||!o)return;const C=h();we(C,c.current)||(c.current=C,a(C))},[h,a,o]),k=l.useRef(x);k.current=x;const m=l.useCallback(()=>{if(o){if(u.current){f.current=!0;return}k.current(),u.current=setTimeout(()=>{u.current=null,f.current&&(f.current=!1,k.current())},i)}},[i,o]);l.useEffect(()=>{m()},[m,t.x,t.y,t.zoom,e.length]),l.useEffect(()=>{if(o&&a){const C=setTimeout(()=>{k.current()},0);return()=>clearTimeout(C)}},[o]),l.useEffect(()=>()=>{u.current&&(clearTimeout(u.current),u.current=null)},[]);const b=l.useCallback(()=>h(),[h]),I=l.useCallback(C=>h().includes(C),[h]),U=l.useCallback(()=>{x()},[x]);return{getVisibleIds:b,isWidgetVisible:I,recalculate:U}},ke=(e,t,n)=>{const s=pt(e.position,e.size),i=s.left+s.width/2,a=s.top+s.height/2,o=t.width/2-i*n,c=t.height/2-a*n;return{x:o,y:c}},xt=(e,t,n)=>{const{workspaceSize:s,cellSize:i,gap:a}=B,o=s.width*i+(s.width+1)*a,c=s.height*i+(s.height+1)*a,u=o*n,f=c*n,h=Math.min(0,t.width-u),x=0,k=Math.min(0,t.height-f);return{x:Math.max(h,Math.min(x,e.x)),y:Math.max(k,Math.min(0,e.y))}},Ce=e=>{if(e.length===0)return null;let t=1/0,n=1/0,s=-1/0,i=-1/0;for(const a of e){const o=pt(a.position,a.size);t=Math.min(t,o.left),n=Math.min(n,o.top),s=Math.max(s,o.left+o.width),i=Math.max(i,o.top+o.height)}return{minX:t,minY:n,maxX:s,maxY:i,width:s-t,height:i-n}},Ee=(e,t,n=50,s=!0)=>{const i=Ce(e);if(!i)return null;const{zoomLimits:a}=B,o=t.width-n*2,c=t.height-n*2,u=o/i.width,f=c/i.height;let h=Math.min(u,f);h=Math.max(a.min,Math.min(a.max,h));const x=i.minX+i.width/2,k=i.minY+i.height/2,m=t.width/2-x*h,b=t.height/2-k*h;if(!s)return{x:m,y:b,zoom:h};const I=xt({x:m,y:b},t,h);return{x:I.x,y:I.y,zoom:h}},ze=(e,t,n)=>{const s=1-Math.pow(1-n,3);return{x:e.x+(t.x-e.x)*s,y:e.y+(t.y-e.y)*s,zoom:e.zoom+(t.zoom-e.zoom)*s}};function Je(e,t,n,s){let i=e instanceof Element?e:null;for(;i&&i!==t;){const a=getComputedStyle(i);if(s!==0){const o=a.overflowY;if((o==="auto"||o==="scroll")&&i.scrollHeight>i.clientHeight)return!0}if(n!==0){const o=a.overflowX;if((o==="auto"||o==="scroll")&&i.scrollWidth>i.clientWidth)return!0}i=i.parentElement}return!1}const Me=l.forwardRef(({widgets:e,config:t,selectedWidgetId:n,tool:s,mode:i="edit",widgetPlacementMode:a,onWidgetSelect:o,onWidgetMove:c,onWidgetAdd:u,onWidgetPlacementEnd:f,onToolChange:h,onUndo:x,onRedo:k,renderWidget:m,className:b,onVisibilityChange:I,bufferZone:U=1,clampPan:C=!0,debug:J=!1},Z)=>{var $t,Gt;const{selectedTool:nt,setSelectedTool:ot}=fe(),D=i!=="edit",E=i==="page",y=l.useMemo(()=>({...B,...t,workspaceSize:{...B.workspaceSize,...t==null?void 0:t.workspaceSize},padding:{...B.padding,...t==null?void 0:t.padding},zoomLimits:{...B.zoomLimits,...t==null?void 0:t.zoomLimits}}),[t]),O=l.useMemo(()=>{if(!E)return y;const r=e.reduce((g,p)=>Math.max(g,p.position.y+p.size.height),0);return{...y,workspaceSize:{...y.workspaceSize,height:Math.max(y.workspaceSize.height,r+1)}}},[E,y,e]),Y=s??nt;l.useEffect(()=>{s&&s!==nt&&ot(s)},[s,nt,ot]);const[S,$]=l.useState({gridPosition:null,visualPosition:null}),z=a?{isActive:a.isActive,widgetTemplate:a.selectedTemplate,isValidPosition:!0,conflictingWidgets:[]}:{isActive:!1,widgetTemplate:null,isValidPosition:!0,conflictingWidgets:[]},[R,V]=l.useState({isActive:!1,mode:null,position:null,size:null,label:"",isValidPosition:!0,conflictingWidgets:[],template:null}),[w,N]=l.useState({x:0,y:0}),[bt,Re]=l.useState(C),[Q,St]=l.useState(!1),[wt,Wt]=l.useState({x:0,y:0}),[M,vt]=l.useState(1),[je,Ht]=l.useState(!1),rt=l.useRef(null),[A,Ot]=l.useState({isDragging:!1,draggedWidget:null,initialWidgetPosition:{x:0,y:0}}),[tt,Pt]=l.useState(null),G=l.useRef(null),dt=l.useCallback(()=>{const r=G.current;return r?{width:r.clientWidth,height:r.clientHeight}:{width:800,height:600}},[]),[kt,Ae]=l.useState(1);l.useEffect(()=>{if(!E)return;const r=G.current;if(!r)return;const{width:g}=st(y),p=()=>{r.clientWidth>0&&Ae(r.clientWidth/g)};p();const v=new ResizeObserver(p);return v.observe(r),()=>v.disconnect()},[E,y]),l.useEffect(()=>{if(!C&&!bt&&G.current){const{width:r}=st(y),g=G.current.clientWidth;N({x:(g-r)/2,y:0}),Re(!0)}},[C,bt,y]);const{getVisibleIds:Ft,isWidgetVisible:Bt}=ve({widgets:e,panZoom:{x:w.x,y:w.y,zoom:M},getViewport:dt,bufferZone:U,onVisibilityChange:I,enabled:!!I}),ut=l.useCallback((r,g=300)=>new Promise(p=>{rt.current&&cancelAnimationFrame(rt.current);const v={x:w.x,y:w.y,zoom:M},j=performance.now();Ht(!0);const T=L=>{const X=L-j,P=Math.min(X/g,1),W=ze(v,r,P);N({x:W.x,y:W.y}),vt(W.zoom),P<1?rt.current=requestAnimationFrame(T):(Ht(!1),rt.current=null,p())};rt.current=requestAnimationFrame(T)}),[w,M]),ht=l.useCallback(r=>{(r.x!==void 0||r.y!==void 0)&&N(g=>({x:r.x??g.x,y:r.y??g.y})),r.zoom!==void 0&&vt(r.zoom)},[]);l.useImperativeHandle(Z,()=>({navigateToWidget:(r,g={})=>{const{animate:p=!0,duration:v=300,select:j=!1,zoom:T}=g,L=e.find(F=>F.id===r);if(!L)return console.warn(`[Canvas] Widget not found: ${r}`),!1;const X=dt(),P=T??M,W=ke(L,X,P),_=C?xt(W,X,P):W,H={x:_.x,y:_.y,zoom:P};return p?ut(H,v):ht(H),j&&o&&o(r),!0},getPanZoom:()=>({x:w.x,y:w.y,zoom:M}),setPanZoom:(r,g=!0)=>{const p=dt(),v=r.zoom??M,j={x:r.x??w.x,y:r.y??w.y},T=C?xt(j,p,v):j,L={x:T.x,y:T.y,zoom:v};g?ut(L):ht(L)},resetView:(r=!0)=>{const g={x:0,y:0,zoom:1};r?ut(g):ht(g)},fitToContent:(r=!0)=>{const g=dt(),p=Ee(e,g,50,C);if(!p){console.warn("[Canvas] No widgets to fit");return}r?ut(p):ht(p)},getVisibleWidgets:()=>Ft(),isWidgetVisible:r=>Bt(r)}),[e,w,M,dt,ut,ht,o,Ft,Bt]),l.useEffect(()=>()=>{rt.current&&cancelAnimationFrame(rt.current)},[]),l.useEffect(()=>{if(!tt)return;const r=e.find(g=>g.id===tt.widgetId);r&&r.position.x===tt.targetPosition.x&&r.position.y===tt.targetPosition.y&&Pt(null)},[tt,e]);const Ie=l.useCallback(r=>{if($(g=>({...g,gridPosition:r})),R.isActive&&R.mode==="placement"&&r){const g=R.template;if(g){const p=mt(r,g.size,e,y.workspaceSize),v=ft(r,g.size,e);V(j=>({...j,position:r,isValidPosition:p,conflictingWidgets:v}))}}},[R.isActive,R.mode,R.template,e]);l.useEffect(()=>{const r=S.gridPosition;if(z.isActive&&z.widgetTemplate&&r){const g=mt(r,z.widgetTemplate.size,e,y.workspaceSize),p=ft(r,z.widgetTemplate.size,e);V({isActive:!0,mode:"placement",position:r,size:z.widgetTemplate.size,label:z.widgetTemplate.label,isValidPosition:g,conflictingWidgets:p,template:z.widgetTemplate})}else A.isDragging||V(g=>({...g,isActive:!1,mode:null,position:null}))},[S.gridPosition,z.isActive,z.widgetTemplate,e,A.isDragging]);const Te=l.useCallback(()=>{if(z.isActive&&z.widgetTemplate&&S.gridPosition){if(R.isValidPosition){const r={id:`widget-${Date.now()}`,type:z.widgetTemplate.type,position:S.gridPosition,size:z.widgetTemplate.size,title:z.widgetTemplate.label};u==null||u(r),f==null||f()}return}o==null||o(null)},[z,R,S.gridPosition,f,u,o]),Le=l.useCallback((r,g)=>{g.stopPropagation(),o==null||o(r)},[o]),Ct=l.useMemo(()=>!A.isDragging||!A.draggedWidget?[]:e.filter(r=>r.id!==A.draggedWidget.id),[A.isDragging,A.draggedWidget,e]),Ye=l.useCallback(r=>{const{active:g}=r,p=e.find(v=>v.id===g.id);if(p&&r.activatorEvent){const v=r.activatorEvent,j={x:v.clientX,y:v.clientY},T=G.current;if(!T)return;const L=T.getBoundingClientRect(),X=j.x-L.left,P=j.y-L.top,W=(X-w.x)/M,_=(P-w.y)/M,H=pt(p.position,p.size),F={x:W-H.left,y:_-H.top},{cellSize:K,gap:q}=y,et=K+q,it={x:p.position.x*et,y:p.position.y*et};Ot({isDragging:!0,draggedWidget:p,initialOffset:F,startZoomLevel:M,startPanPosition:{...w},initialMousePosition:j,initialWidgetPosition:it}),V({isActive:!0,mode:"drag",position:p.position,size:p.size,label:p.title||`Widget ${p.id}`,isValidPosition:!0,conflictingWidgets:[],template:null})}},[e,w,M,y]),Xe=l.useCallback(r=>{var g,p;if(!(!A.isDragging||!A.draggedWidget))try{const v=r.delta.x/M,j=r.delta.y/M,T=A.initialWidgetPosition.x+v,L=A.initialWidgetPosition.y+j,{cellSize:X,gap:P,workspaceSize:W}=y,_=X+P,H=Math.round(T/_),F=Math.round(L/_),K={x:H,y:F};if(((g=R.position)==null?void 0:g.x)===H&&((p=R.position)==null?void 0:p.y)===F)return;const q=H>=0&&F>=0&&H+A.draggedWidget.size.width<=W.width&&F+A.draggedWidget.size.height<=W.height,et=q&&mt(K,A.draggedWidget.size,Ct,y.workspaceSize),it=q?ft(K,A.draggedWidget.size,Ct):[];V(ct=>({...ct,position:K,isValidPosition:et,conflictingWidgets:it}))}catch(v){console.error("Error in handleDragMove:",v)}},[A,Ct,R.position,M,y]),Se=l.useCallback(r=>{const{active:g,over:p}=r,v=g.id;if(p&&p.id==="canvas-drop-zone"&&R.isActive&&R.position&&R.isValidPosition&&R.position){const T=R.position;Pt({widgetId:v,targetPosition:T}),c==null||c(v,T)}Ot({isDragging:!1,draggedWidget:null,initialOffset:void 0,startZoomLevel:void 0,startPanPosition:void 0,initialMousePosition:void 0,initialWidgetPosition:{x:0,y:0}}),V({isActive:!1,mode:null,position:null,size:null,label:"",isValidPosition:!0,conflictingWidgets:[],template:null})},[R,c]),We=l.useCallback(r=>{var g,p;if(!E&&Y==="hand"){if(D&&((p=(g=r.target)==null?void 0:g.closest)!=null&&p.call(g,"[data-widget-id]")))return;St(!0),Wt({x:r.clientX,y:r.clientY})}},[Y,D,E]),Et=l.useCallback(r=>{if(Q&&Y==="hand"){const g=r.clientX-wt.x,p=r.clientY-wt.y;N(v=>{const j=G.current;if(!j)return v;const T=j.clientWidth,L=j.clientHeight,{width:X,height:P}=st(y),W=X*M,_=P*M;let H,F,K,q;if(C)H=Math.min(0,T-W),F=0;else{const ct=(T-W)/2;H=ct,F=ct}K=Math.min(0,L-_),q=0;const et=Math.max(H,Math.min(F,v.x+g)),it=Math.max(K,Math.min(q,v.y+p));return{x:et,y:it}}),Wt({x:r.clientX,y:r.clientY})}},[Q,wt,Y,M,y]),zt=l.useCallback(()=>{Q&&St(!1)},[Q]),Mt=l.useCallback(r=>{const g=G.current;if(!g)return;if(!r.ctrlKey&&!r.metaKey){if(Je(r.target,g,r.deltaX,r.deltaY))return;r.preventDefault();const gt=1,Fe=r.deltaX*gt,Be=r.deltaY*gt;N(Ut=>{const{width:Ve,height:Ne}=st(y),Jt=Ve*M,_e=Ne*M,Qt=g.clientWidth,$e=g.clientHeight;let jt,At,Zt,te;if(C)jt=Math.min(0,Qt-Jt),At=0;else{const ee=(Qt-Jt)/2;jt=ee,At=ee}return Zt=Math.min(0,$e-_e),te=0,{x:Math.max(jt,Math.min(At,Ut.x-Fe)),y:Math.max(Zt,Math.min(te,Ut.y-Be))}});return}r.preventDefault();const p=g.getBoundingClientRect(),v=r.clientX-p.left,j=r.clientY-p.top,T=-r.deltaY*.001,L=M,X=Math.max(.7,Math.min(1.5,L+T*.5));if(X===L)return;const P=(v-w.x)/L,W=(j-w.y)/L,_=v-P*X,H=j-W*X,{width:F,height:K}=st(y),q=F*X,et=K*X,it=g.clientWidth,ct=g.clientHeight;let Dt,Rt,Kt,qt;if(C)Dt=Math.min(0,it-q),Rt=0;else{const gt=(it-q)/2;Dt=gt,Rt=gt}Kt=Math.min(0,ct-et),qt=0,vt(X),N({x:Math.max(Dt,Math.min(Rt,_)),y:Math.max(Kt,Math.min(qt,H))})},[M,w,y]);l.useEffect(()=>{const r=G.current;return r&&!E&&r.addEventListener("wheel",Mt,{passive:!1}),Q&&(document.addEventListener("mousemove",Et),document.addEventListener("mouseup",zt)),()=>{r&&r.removeEventListener("wheel",Mt),Q&&(document.removeEventListener("mousemove",Et),document.removeEventListener("mouseup",zt))}},[Q,Et,zt,Mt,E]);const He=l.useCallback(r=>{ot(r),h==null||h(r)},[ot,h]);ye({currentTool:Y,onToolChange:He,isPlacementActive:z.isActive,onCancelPlacement:f,onUndo:x,onRedo:k});const{workspaceSize:Vt}=y,Nt=d.jsx(he,{config:O,showGrid:!D,onCanvasClick:Te,onGridPositionChange:Ie,showGridHighlight:!D&&(Y==="select"||z.isActive)&&!A.isDragging,previewState:R,selectedTool:Y,onMouseDown:We,panZoom:E?{x:0,y:0,zoom:kt}:{x:w.x,y:w.y,zoom:M},isDragging:A.isDragging,dragState:A,containerRef:G,children:d.jsx(de,{widgets:e,selectedWidgetId:n,draggingWidgetId:(($t=A.draggedWidget)==null?void 0:$t.id)??(tt==null?void 0:tt.widgetId),currentTool:Y,editable:!D,onWidgetClick:D?void 0:Le,renderWidget:m})}),{width:Oe,height:Pe}=st(O),_t=d.jsxs("div",{className:se(b),style:{position:"relative",width:"100%",height:E?"auto":"100%",backgroundColor:"var(--canvas-container-bg, #F3F4F6)"},children:[d.jsx("div",{ref:G,"data-canvas-container":!0,style:{backgroundColor:"var(--canvas-bg, #F9FAFB)",...E?{position:"relative",width:"100%"}:{position:"absolute",inset:0,overflow:"hidden"},cursor:E?"default":Y==="hand"?Q?"grabbing":"grab":"default"},children:E?d.jsx("div",{style:{width:"100%",height:Pe*kt,overflow:"hidden"},children:d.jsx("div",{style:{width:Oe,transform:`scale(${kt})`,transformOrigin:"top left"},children:Nt})}):d.jsx("div",{style:{transform:`translate(${w.x}px, ${w.y}px) scale(${M})`,transition:Q||je?"none":"transform 0.1s ease-out",transformOrigin:"top left",visibility:bt?"visible":"hidden"},children:Nt})}),J&&d.jsxs("div",{style:{position:"absolute",bottom:"8px",right:"8px",backgroundColor:"rgba(0, 0, 0, 0.8)",color:"white",fontSize:"12px",padding:"8px",borderRadius:"4px",fontFamily:"monospace"},children:["Widgets: ",e.length," |",S.gridPosition&&d.jsxs(d.Fragment,{children:[" ","Grid:"," ",d.jsxs("span",{style:{color:"#86EFAC"},children:["(",S.gridPosition.x,", ",S.gridPosition.y,")"]})," ","|"]}),z.isActive&&d.jsxs(d.Fragment,{children:[" ","Placing: ",d.jsx("span",{style:{color:"#93C5FD"},children:(Gt=z.widgetTemplate)==null?void 0:Gt.label})," ","|"]}),"Zoom: ",d.jsxs("span",{style:{color:"#FDE047"},children:[Math.round(M*100),"%"]})," | Workspace:"," ",Vt.width,"x",Vt.height," cells"]})]});return D?_t:d.jsxs(at.DndContext,{onDragStart:Ye,onDragMove:Xe,onDragEnd:Se,children:[_t,d.jsx(ue,{draggedWidget:A.draggedWidget,zoomLevel:M,renderDraggedWidget:m?r=>m(r,!1):void 0})]})});Me.displayName="CanvasInternal";const De=l.forwardRef((e,t)=>d.jsx(ge,{defaultTool:e.tool??"select",children:d.jsx(Me,{ref:t,...e})}));De.displayName="Canvas";exports.Canvas=De;exports.CellHighlight=ce;exports.CellNumbers=le;exports.DragOverlayLayer=ue;exports.GRID_CONFIG=B;exports.Grid=he;exports.GridLines=re;exports.KEYBOARD_SHORTCUTS=pe;exports.LAYER_Z_INDEX=lt;exports.ToolContext=Lt;exports.ToolProvider=ge;exports.WidgetLayer=de;exports.WidgetPlaceholder=ae;exports.areVisibleIdsEqual=we;exports.calculateAllWidgetsVisibility=Ue;exports.calculateCenteredPanPosition=ke;exports.calculateFitToContent=Ee;exports.calculateViewportGridBounds=Yt;exports.calculateWidgetVisibility=xe;exports.calculateWidgetsBoundingBox=Ce;exports.clampPanPosition=xt;exports.doWidgetsOverlap=oe;exports.expandBoundsWithBuffer=Xt;exports.findMatchingShortcut=Tt;exports.getConflictingWidgets=ft;exports.getVisibleWidgetIds=be;exports.getWidgetPlacementPosition=pt;exports.interpolatePanZoom=ze;exports.isValidGridPosition=mt;exports.matchesModifiers=me;exports.useGridSnap=ne;exports.useKeyboardShortcuts=ye;exports.useTool=fe;exports.useWidgetVisibility=ve;exports.widgetIntersectsBounds=yt;