@coorax/react 0.0.0-canary.2 → 0.0.0-canary.4

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.
Files changed (170) hide show
  1. package/dist/components/commons/button.d.ts +8 -0
  2. package/dist/components/corax-context-provider.d.ts +6 -0
  3. package/dist/components/corax-flow.d.ts +4 -0
  4. package/dist/components/fallbacks/image.fallback.d.ts +3 -0
  5. package/dist/components/slots/buttons/block-actions-button.d.ts +3 -0
  6. package/dist/components/slots/buttons/toolbar-button.d.ts +3 -0
  7. package/dist/components/slots/maps/block-actions.d.ts +1 -0
  8. package/dist/components/slots/maps/overlays.d.ts +1 -0
  9. package/dist/components/slots/maps/text-inspector.d.ts +2 -0
  10. package/dist/components/slots/maps/toolbar.d.ts +1 -0
  11. package/dist/components/slots/overlays/focus-overlay.d.ts +3 -0
  12. package/dist/components/slots/overlays/hover-overlay.d.ts +3 -0
  13. package/dist/components/slots/overlays/selection-overlay.d.ts +3 -0
  14. package/dist/components/slots/slot-button.d.ts +6 -0
  15. package/dist/components/slots/slot-component.d.ts +5 -0
  16. package/dist/components/slots/slots.d.ts +4 -0
  17. package/dist/constants/field.constants.d.ts +2 -0
  18. package/dist/hooks/custom/use-custom-ref.d.ts +1 -0
  19. package/dist/hooks/custom/use-isomorphic-layout-effect.d.ts +2 -0
  20. package/{src/hooks/index.ts → dist/hooks/index.d.ts} +1 -0
  21. package/dist/hooks/use-block-entry.d.ts +2 -0
  22. package/dist/hooks/use-block.d.ts +2 -0
  23. package/dist/hooks/use-flow.d.ts +17 -0
  24. package/dist/hooks/use-keyboard.d.ts +10 -0
  25. package/dist/hooks/use-registry.d.ts +3 -0
  26. package/dist/hooks/use-renderer.d.ts +2 -0
  27. package/dist/hooks/use-slice.d.ts +2 -0
  28. package/dist/hooks/use-slots.d.ts +2 -0
  29. package/dist/hooks/use-tasks.d.ts +7 -0
  30. package/dist/hooks/use-text-input.d.ts +2 -0
  31. package/dist/hooks/use-ui-context.d.ts +2 -0
  32. package/dist/hooks/useSelection.d.ts +2 -0
  33. package/{src/index.ts → dist/index.d.ts} +7 -4
  34. package/dist/index.js +2774 -0
  35. package/dist/lib/comp.utils.d.ts +4 -0
  36. package/dist/lib/func.utils.d.ts +3 -0
  37. package/dist/lib/index.d.ts +4 -0
  38. package/dist/lib/selection.utils.d.ts +5 -0
  39. package/dist/lib/slots.utils.d.ts +4 -0
  40. package/dist/lifecycle/fields/focus.events/onbeforeinput.d.ts +3 -0
  41. package/dist/lifecycle/fields/focus.events/onblur.d.ts +3 -0
  42. package/dist/lifecycle/fields/focus.events/onfocus.d.ts +3 -0
  43. package/dist/lifecycle/fields/keyboard.events/onkeydown.d.ts +3 -0
  44. package/dist/lifecycle/fields/lifecycle.fields.d.ts +12 -0
  45. package/dist/lifecycle/fields/lifecycle.fields.types.d.ts +15 -0
  46. package/dist/lifecycle/fields/lifecycle.utils.d.ts +2 -0
  47. package/dist/lifecycle/fields/mouse.events/onclick.d.ts +3 -0
  48. package/dist/lifecycle/fields/mouse.events/ondoubleclick.d.ts +4 -0
  49. package/dist/lifecycle/fields/mouse.events/onmouseenter.d.ts +3 -0
  50. package/dist/lifecycle/fields/mouse.events/onmouseleave.d.ts +3 -0
  51. package/dist/lifecycle/fields/synthetic.events/onload.d.ts +3 -0
  52. package/dist/lifecycle/fields/synthetic.events/onselect.d.ts +3 -0
  53. package/dist/lifecycle/index.d.ts +3 -0
  54. package/dist/modules/autosave.module.d.ts +31 -0
  55. package/dist/modules/fallbacks.module.d.ts +7 -0
  56. package/dist/modules/slots.module.d.ts +7 -0
  57. package/dist/modules/ui-primitives.module.d.ts +7 -0
  58. package/dist/primitives/fields/field.primitives.d.ts +2 -0
  59. package/dist/primitives/index.d.ts +3 -0
  60. package/{src/registry/fallbacks.registry.tsx → dist/registry/fallbacks.registry.d.ts} +3 -4
  61. package/dist/registry/primitives.registry.d.ts +22 -0
  62. package/dist/registry/registry.d.ts +15 -0
  63. package/dist/registry/slots.registry.d.ts +4 -0
  64. package/{src/registry/ui.primitives.registry.tsx → dist/registry/ui.primitives.registry.d.ts} +3 -4
  65. package/dist/renderer/renderer.d.ts +23 -0
  66. package/dist/renderer/renderer.test.d.ts +1 -0
  67. package/{src/renderer/renderer.types.ts → dist/renderer/renderer.types.d.ts} +0 -1
  68. package/dist/renderer/renderer.utils.d.ts +14 -0
  69. package/dist/renderer/utils/divider.renderer.utils.d.ts +6 -0
  70. package/dist/services/index.d.ts +1 -0
  71. package/dist/services/localdb/db/db.d.ts +74 -0
  72. package/dist/services/localdb/db/db.test.d.ts +1 -0
  73. package/dist/services/localdb/lexer/lexer.d.ts +14 -0
  74. package/dist/services/localdb/lexer/lexer.test.d.ts +1 -0
  75. package/dist/services/localdb/lexer/lexer.types.d.ts +5 -0
  76. package/dist/services/localdb/operator/operator.d.ts +10 -0
  77. package/dist/services/localdb/parser/parser.constants.d.ts +3 -0
  78. package/dist/services/localdb/parser/parser.d.ts +14 -0
  79. package/dist/services/localdb/parser/parser.test.d.ts +1 -0
  80. package/dist/services/localdb/parser/parser.types.d.ts +43 -0
  81. package/dist/services/localdb/sheet/sheet.constants.d.ts +3 -0
  82. package/dist/services/localdb/sheet/sheet.d.ts +14 -0
  83. package/dist/services/localdb/sheet/sheet.types.d.ts +13 -0
  84. package/dist/styles.css +1094 -0
  85. package/package.json +29 -12
  86. package/.oxlintrc.json +0 -8
  87. package/src/components/commons/button.tsx +0 -59
  88. package/src/components/corax-context-provider.tsx +0 -47
  89. package/src/components/corax-flow.tsx +0 -44
  90. package/src/components/fallbacks/image.fallback.tsx +0 -23
  91. package/src/components/slots/buttons/block-actions-button.tsx +0 -85
  92. package/src/components/slots/buttons/toolbar-button.tsx +0 -40
  93. package/src/components/slots/maps/block-actions.tsx +0 -84
  94. package/src/components/slots/maps/overlays.tsx +0 -9
  95. package/src/components/slots/maps/text-inspector.tsx +0 -5
  96. package/src/components/slots/maps/toolbar.tsx +0 -79
  97. package/src/components/slots/overlays/focus-overlay.tsx +0 -30
  98. package/src/components/slots/overlays/hover-overlay.tsx +0 -18
  99. package/src/components/slots/overlays/selection-overlay.tsx +0 -20
  100. package/src/components/slots/slot-button.tsx +0 -20
  101. package/src/components/slots/slot-component.tsx +0 -17
  102. package/src/components/slots/slots.tsx +0 -29
  103. package/src/constants/field.constants.ts +0 -3
  104. package/src/hooks/custom/use-custom-ref.ts +0 -11
  105. package/src/hooks/use-block-entry.ts +0 -44
  106. package/src/hooks/use-block.ts +0 -11
  107. package/src/hooks/use-flow.ts +0 -83
  108. package/src/hooks/use-keyboard.ts +0 -66
  109. package/src/hooks/use-registry.ts +0 -18
  110. package/src/hooks/use-renderer.ts +0 -8
  111. package/src/hooks/use-slice.ts +0 -13
  112. package/src/hooks/use-slots.ts +0 -13
  113. package/src/hooks/use-tasks.ts +0 -33
  114. package/src/hooks/use-text-input.ts +0 -83
  115. package/src/hooks/use-ui-context.ts +0 -16
  116. package/src/hooks/useSelection.ts +0 -27
  117. package/src/lib/comp.utils.tsx +0 -44
  118. package/src/lib/func.utils.ts +0 -15
  119. package/src/lib/selection.utils.ts +0 -33
  120. package/src/lib/slots.utils.tsx +0 -23
  121. package/src/lifecycle/fields/focus.events/onbeforeinput.ts +0 -21
  122. package/src/lifecycle/fields/focus.events/onblur.ts +0 -19
  123. package/src/lifecycle/fields/focus.events/onfocus.ts +0 -16
  124. package/src/lifecycle/fields/keyboard.events/onkeydown.ts +0 -128
  125. package/src/lifecycle/fields/lifecycle.fields.ts +0 -116
  126. package/src/lifecycle/fields/lifecycle.fields.types.ts +0 -33
  127. package/src/lifecycle/fields/lifecycle.utils.ts +0 -26
  128. package/src/lifecycle/fields/mouse.events/onclick.ts +0 -79
  129. package/src/lifecycle/fields/mouse.events/ondoubleclick.ts +0 -27
  130. package/src/lifecycle/fields/mouse.events/onmouseenter.ts +0 -27
  131. package/src/lifecycle/fields/mouse.events/onmouseleave.ts +0 -21
  132. package/src/lifecycle/fields/synthetic.events/onload.ts +0 -16
  133. package/src/lifecycle/fields/synthetic.events/onselect.ts +0 -57
  134. package/src/lifecycle/index.ts +0 -1
  135. package/src/modules/autosave.module.ts +0 -238
  136. package/src/modules/fallbacks.module.tsx +0 -19
  137. package/src/modules/slots.module.tsx +0 -28
  138. package/src/modules/ui-primitives.module.tsx +0 -20
  139. package/src/primitives/fields/field.primitives.tsx +0 -86
  140. package/src/primitives/index.ts +0 -8
  141. package/src/registry/primitives.registry.tsx +0 -57
  142. package/src/registry/registry.ts +0 -44
  143. package/src/registry/slots.registry.tsx +0 -6
  144. package/src/renderer/renderer.test.ts +0 -34
  145. package/src/renderer/renderer.tsx +0 -164
  146. package/src/renderer/renderer.utils.tsx +0 -139
  147. package/src/renderer/utils/divider.renderer.utils.tsx +0 -53
  148. package/src/services/localdb/db/db.test.ts +0 -351
  149. package/src/services/localdb/db/db.ts +0 -628
  150. package/src/services/localdb/lexer/lexer.test.ts +0 -123
  151. package/src/services/localdb/lexer/lexer.ts +0 -173
  152. package/src/services/localdb/lexer/lexer.types.ts +0 -34
  153. package/src/services/localdb/operator/operator.ts +0 -16
  154. package/src/services/localdb/parser/parser.constants.ts +0 -23
  155. package/src/services/localdb/parser/parser.test.ts +0 -172
  156. package/src/services/localdb/parser/parser.ts +0 -427
  157. package/src/services/localdb/parser/parser.types.ts +0 -56
  158. package/src/services/localdb/sheet/sheet.constants.ts +0 -32
  159. package/src/services/localdb/sheet/sheet.ts +0 -47
  160. package/src/services/localdb/sheet/sheet.types.ts +0 -38
  161. package/tsconfig.app.json +0 -26
  162. package/tsconfig.json +0 -9
  163. package/tsconfig.node.json +0 -9
  164. package/tsconfig.tsbuildinfo +0 -1
  165. package/vite.config.ts +0 -9
  166. /package/{src/components/index.ts → dist/components/index.d.ts} +0 -0
  167. /package/{src/components/slots/index.ts → dist/components/slots/index.d.ts} +0 -0
  168. /package/{src/components/slots/maps/index.ts → dist/components/slots/maps/index.d.ts} +0 -0
  169. /package/{src/modules/index.ts → dist/modules/index.d.ts} +0 -0
  170. /package/{src/registry/index.ts → dist/registry/index.d.ts} +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,2774 @@
1
+ "use client";
2
+
3
+ // src/registry/registry.ts
4
+ class GenericRegistry {
5
+ items = new Map;
6
+ listeners = new Map;
7
+ notify(key) {
8
+ this.listeners.get(key)?.forEach((l) => l());
9
+ }
10
+ get(key) {
11
+ return this.items.get(key);
12
+ }
13
+ register(key, value) {
14
+ this.items.set(key, value);
15
+ this.notify(key);
16
+ return () => {
17
+ this.items.delete(key);
18
+ this.notify(key);
19
+ };
20
+ }
21
+ subscribe(key, fn) {
22
+ const set = this.listeners.get(key) ?? new Set;
23
+ set.add(fn);
24
+ this.listeners.set(key, set);
25
+ return () => {
26
+ set.delete(fn);
27
+ if (set.size === 0) {
28
+ this.listeners.delete(key);
29
+ }
30
+ };
31
+ }
32
+ }
33
+
34
+ // src/registry/slots.registry.tsx
35
+ var SlotsComponentRegistry = new GenericRegistry;
36
+
37
+ // src/components/commons/button.tsx
38
+ import { cva } from "class-variance-authority";
39
+ import { cn } from "cn";
40
+ import { jsxDEV } from "react/jsx-dev-runtime";
41
+ var buttonVariants = cva("group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", {
42
+ variants: {
43
+ variant: {
44
+ default: "bg-primary text-primary-foreground hover:bg-primary/80",
45
+ outline: "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
46
+ secondary: "bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
47
+ ghost: "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
48
+ destructive: "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
49
+ link: "text-primary underline-offset-4 hover:underline"
50
+ },
51
+ size: {
52
+ default: "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
53
+ xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
54
+ sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
55
+ lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
56
+ icon: "size-8",
57
+ "icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
58
+ "icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
59
+ "icon-lg": "size-9"
60
+ }
61
+ },
62
+ defaultVariants: {
63
+ variant: "default",
64
+ size: "default"
65
+ }
66
+ });
67
+ function Button({
68
+ className,
69
+ variant = "default",
70
+ size = "default",
71
+ ...props
72
+ }) {
73
+ return /* @__PURE__ */ jsxDEV("button", {
74
+ "data-slot": "button",
75
+ "data-variant": variant,
76
+ "data-size": size,
77
+ className: cn(buttonVariants({ variant, size, className })),
78
+ ...props
79
+ }, undefined, false, undefined, this);
80
+ }
81
+
82
+ // src/components/corax-context-provider.tsx
83
+ import {
84
+ EditorModule,
85
+ Engine,
86
+ FocusModule,
87
+ HistoryModule,
88
+ HoverModule,
89
+ InsertionModule,
90
+ SelectionModule,
91
+ TextEditingModule
92
+ } from "@coorax/core";
93
+ import { createContext, useContext, useMemo } from "react";
94
+
95
+ // src/registry/fallbacks.registry.tsx
96
+ var FallbackComponentsRegistry = new GenericRegistry;
97
+
98
+ // src/components/fallbacks/image.fallback.tsx
99
+ import { RefreshCw } from "lucide-react";
100
+ import { cn as cn2 } from "cn";
101
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
102
+ function ImageFallback({
103
+ className,
104
+ style,
105
+ ...props
106
+ }) {
107
+ return /* @__PURE__ */ jsxDEV2("div", {
108
+ className: cn2("w-full h-[360px] flex gap-2 items-center justify-center bg-amber-500/10", className),
109
+ style,
110
+ children: [
111
+ /* @__PURE__ */ jsxDEV2(RefreshCw, {
112
+ className: "animate-spin size-5"
113
+ }, undefined, false, undefined, this),
114
+ /* @__PURE__ */ jsxDEV2("span", {
115
+ className: "font-semibold",
116
+ children: props.name
117
+ }, undefined, false, undefined, this)
118
+ ]
119
+ }, undefined, true, undefined, this);
120
+ }
121
+
122
+ // src/modules/fallbacks.module.tsx
123
+ var FallbacksModule = {
124
+ name: "fallbacks",
125
+ version: "1.0.0",
126
+ requires: [],
127
+ install() {
128
+ FallbackComponentsRegistry.register("image", ImageFallback);
129
+ }
130
+ };
131
+
132
+ // src/components/corax-context-provider.tsx
133
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
134
+ "use client";
135
+ var CoraxEngineContext = createContext(null);
136
+ function CoraxEngineProvider({ children }) {
137
+ const engine = useMemo(() => {
138
+ const engine2 = new Engine;
139
+ engine2.modules.register([
140
+ HistoryModule,
141
+ AutoSaveModule,
142
+ EditorModule,
143
+ HoverModule,
144
+ InsertionModule,
145
+ FocusModule,
146
+ SelectionModule,
147
+ TextEditingModule,
148
+ SlotsModule,
149
+ FallbacksModule
150
+ ]);
151
+ engine2.modules.enableAll();
152
+ return engine2;
153
+ }, []);
154
+ return /* @__PURE__ */ jsxDEV3(CoraxEngineContext.Provider, {
155
+ value: engine,
156
+ children
157
+ }, undefined, false, undefined, this);
158
+ }
159
+ function useEngine() {
160
+ const engine = useContext(CoraxEngineContext);
161
+ if (!engine) {
162
+ throw new Error("useBlogEngine must be used within BlogEngineProvider");
163
+ }
164
+ return engine;
165
+ }
166
+
167
+ // src/hooks/use-slice.ts
168
+ import { useSyncExternalStore } from "react";
169
+ function useSlice(sliceName) {
170
+ const engine = useEngine();
171
+ const slice = useSyncExternalStore((fn) => engine.state.subscribe(sliceName, fn), () => engine.state.get(sliceName), () => engine.state.get(sliceName));
172
+ return slice;
173
+ }
174
+
175
+ // src/lib/slots.utils.tsx
176
+ import { cn as cn3 } from "cn";
177
+ function getBlockActionsProps(isOpen, index) {
178
+ return {
179
+ className: cn3("absolute cursor-pointer transition-all disabled:pointer-events-none disabled:opacity-50"),
180
+ style: {
181
+ "--index": isOpen ? 0 : index,
182
+ "--step": isOpen ? "0px" : "38px",
183
+ transform: "translateX(calc((36px*var(--index)) + var(--step))"
184
+ }
185
+ };
186
+ }
187
+
188
+ // src/components/slots/buttons/block-actions-button.tsx
189
+ import { cn as cn4 } from "cn";
190
+
191
+ // src/lib/comp.utils.tsx
192
+ import {
193
+ BoldIcon,
194
+ HeadingIcon,
195
+ ImagePlus,
196
+ ItalicIcon,
197
+ LinkIcon,
198
+ Minus,
199
+ PlusIcon,
200
+ Pointer,
201
+ PointerIcon,
202
+ TextCursor,
203
+ TextInitialIcon,
204
+ UnderlineIcon
205
+ } from "lucide-react";
206
+ import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
207
+ function CoraxIcon({ icon }) {
208
+ switch (icon) {
209
+ case "TextIcon":
210
+ return /* @__PURE__ */ jsxDEV4(TextCursor, {}, undefined, false, undefined, this);
211
+ case "CursorIcon":
212
+ return /* @__PURE__ */ jsxDEV4(PointerIcon, {}, undefined, false, undefined, this);
213
+ case "HeadingIcon":
214
+ return /* @__PURE__ */ jsxDEV4(HeadingIcon, {}, undefined, false, undefined, this);
215
+ case "PlusIcon":
216
+ return /* @__PURE__ */ jsxDEV4(PlusIcon, {}, undefined, false, undefined, this);
217
+ case "BoldIcon":
218
+ return /* @__PURE__ */ jsxDEV4(BoldIcon, {}, undefined, false, undefined, this);
219
+ case "ItalicIcon":
220
+ return /* @__PURE__ */ jsxDEV4(ItalicIcon, {}, undefined, false, undefined, this);
221
+ case "UnderlineIcon":
222
+ return /* @__PURE__ */ jsxDEV4(UnderlineIcon, {}, undefined, false, undefined, this);
223
+ case "LinkIcon":
224
+ return /* @__PURE__ */ jsxDEV4(LinkIcon, {}, undefined, false, undefined, this);
225
+ case "ImagePlus":
226
+ return /* @__PURE__ */ jsxDEV4(ImagePlus, {}, undefined, false, undefined, this);
227
+ case "TextInitial":
228
+ return /* @__PURE__ */ jsxDEV4(TextInitialIcon, {}, undefined, false, undefined, this);
229
+ case "DividerIcon":
230
+ return /* @__PURE__ */ jsxDEV4(Minus, {}, undefined, false, undefined, this);
231
+ default:
232
+ return /* @__PURE__ */ jsxDEV4(Pointer, {}, undefined, false, undefined, this);
233
+ }
234
+ }
235
+
236
+ // src/lifecycle/fields/lifecycle.utils.ts
237
+ function blockRectFromBlockId(id) {
238
+ const domElement = document.getElementById(id);
239
+ if (!domElement)
240
+ return null;
241
+ const parentElement = domElement.closest("#corax_flow_blocks_container");
242
+ if (!parentElement)
243
+ return null;
244
+ const rect = domElement.getBoundingClientRect();
245
+ return {
246
+ top: rect.top,
247
+ left: rect.left,
248
+ width: rect.width,
249
+ right: rect.right,
250
+ height: rect.height,
251
+ bottom: rect.bottom,
252
+ offsetTop: domElement.offsetTop,
253
+ offsetLeft: domElement.offsetLeft,
254
+ offsetHeight: domElement.offsetHeight,
255
+ offsetWidth: domElement.offsetWidth,
256
+ parentScrollLeft: parentElement.scrollLeft,
257
+ parentScrollTop: parentElement.scrollTop
258
+ };
259
+ }
260
+
261
+ // src/components/slots/buttons/block-actions-button.tsx
262
+ import React2 from "react";
263
+ import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
264
+ var BlockActionButton = React2.memo(function BlockActionButton2({
265
+ c,
266
+ ui,
267
+ ...rest
268
+ }) {
269
+ const engine = useEngine();
270
+ const isOpen = useSlice("insertion");
271
+ const focusMemory = useSlice("focus_memory");
272
+ const selection = useSlice("selection");
273
+ const { blocks = [] } = focusMemory ?? {};
274
+ const { blocks: _selectionBLocks = new Map } = selection ?? {};
275
+ const selectedBlocksIds = Array.from(_selectionBLocks?.keys() ?? []);
276
+ const focusedId = selectedBlocksIds[0] ?? blocks?.[blocks.length - 1]?.id;
277
+ if (c.name !== "BlockActionButton")
278
+ return null;
279
+ if (!c.when?.(ui) || c.kind !== "button")
280
+ return null;
281
+ const { variant, size, isBaseButton = false } = c.getProps(ui);
282
+ const enabled = engine.commands.has(c.command);
283
+ return /* @__PURE__ */ jsxDEV5(Button, {
284
+ ...rest,
285
+ variant,
286
+ size,
287
+ disabled: !enabled,
288
+ ...!isBaseButton ? getBlockActionsProps(!isOpen, c.order ? c.order - 1 : 0) : {
289
+ className: cn4("z-99 cursor-pointer transition-all", {
290
+ "rotate-45": isOpen
291
+ })
292
+ },
293
+ onClick: () => {
294
+ if (c.command === "blocks.insert") {
295
+ const payload2 = c.getPayload(ui);
296
+ const pos = [...engine.document.get().order].indexOf(focusedId);
297
+ engine.commands.tryExecute(c.command, {
298
+ ...payload2,
299
+ pos: pos === -1 ? undefined : pos + 1
300
+ });
301
+ setTimeout(() => {
302
+ const rect = blockRectFromBlockId(payload2.block.id);
303
+ if (!rect)
304
+ return;
305
+ engine.commands.tryExecute("blocks.focus", {
306
+ id: payload2.block.id,
307
+ rect
308
+ });
309
+ }, 0);
310
+ return;
311
+ }
312
+ const payload = c.getPayload(ui);
313
+ engine.commands.tryExecute(c.command, payload);
314
+ },
315
+ children: [
316
+ /* @__PURE__ */ jsxDEV5(CoraxIcon, {
317
+ icon: c.icon
318
+ }, undefined, false, undefined, this),
319
+ c.label
320
+ ]
321
+ }, undefined, true, undefined, this);
322
+ }, () => true);
323
+
324
+ // src/components/slots/buttons/toolbar-button.tsx
325
+ import React3 from "react";
326
+ import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
327
+ var ToolbarButton = React3.memo(function ToolbarButton2({
328
+ c,
329
+ ui
330
+ }) {
331
+ const engine = useEngine();
332
+ const marks = useSlice("currentMarks");
333
+ const isActive = !!c.getProps(ui)?.isActive || marks?.find((mark) => mark.type === c.getPayload(ui).format);
334
+ return /* @__PURE__ */ jsxDEV6(Button, {
335
+ onClick: () => {
336
+ engine.commands.tryExecute(c.command, c.getPayload(ui));
337
+ },
338
+ title: c.label,
339
+ size: "icon-xs",
340
+ className: "rounded-[8px] cursor-pointer",
341
+ variant: isActive ? "default" : "outline",
342
+ children: /* @__PURE__ */ jsxDEV6(CoraxIcon, {
343
+ icon: c.icon
344
+ }, undefined, false, undefined, this)
345
+ }, c.id, false, undefined, this);
346
+ }, (prev, next) => {
347
+ const prevActive = prev.c.getProps(prev.ui);
348
+ const nextActive = next.c.getProps(next.ui);
349
+ return prevActive === nextActive;
350
+ });
351
+
352
+ // src/components/slots/overlays/focus-overlay.tsx
353
+ import { useEffect } from "react";
354
+
355
+ // src/lib/func.utils.ts
356
+ function focusDomBLockById(engine, id) {
357
+ const disposer = engine.events.on("re-render", () => {
358
+ focusDomElement(id);
359
+ disposer();
360
+ });
361
+ }
362
+ function focusDomElement(id) {
363
+ const domElement = document.getElementById(id);
364
+ if (!domElement)
365
+ return;
366
+ domElement.focus();
367
+ }
368
+
369
+ // src/components/slots/overlays/focus-overlay.tsx
370
+ import { jsxDEV as jsxDEV7 } from "react/jsx-dev-runtime";
371
+ function FocusOverlay({ c, ui }) {
372
+ const { position, hidden } = c.getProps(ui);
373
+ const focusedId = ui.focus?.id;
374
+ useEffect(() => {
375
+ if (!focusedId)
376
+ return;
377
+ focusDomElement(focusedId);
378
+ }, [focusedId]);
379
+ if (hidden || !position)
380
+ return null;
381
+ return /* @__PURE__ */ jsxDEV7("div", {
382
+ style: position,
383
+ className: "absolute border border-blue-700 pointer-events-none flex justify-end"
384
+ }, undefined, false, undefined, this);
385
+ }
386
+
387
+ // src/components/slots/overlays/hover-overlay.tsx
388
+ import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
389
+ function HoverOverlay({ c, ui }) {
390
+ const { position, hidden } = c.getProps(ui);
391
+ if (hidden || !position)
392
+ return null;
393
+ return /* @__PURE__ */ jsxDEV8("div", {
394
+ style: position,
395
+ className: "absolute border-[0.5px] border-blue-400 pointer-events-none flex justify-end"
396
+ }, undefined, false, undefined, this);
397
+ }
398
+
399
+ // src/components/slots/overlays/selection-overlay.tsx
400
+ import { jsxDEV as jsxDEV9 } from "react/jsx-dev-runtime";
401
+ function SelectionOverlay({ c, ui }) {
402
+ const { position, hidden } = c.getProps(ui);
403
+ if (hidden || !position)
404
+ return null;
405
+ return /* @__PURE__ */ jsxDEV9("div", {
406
+ style: position,
407
+ className: "absolute border border-blue-500 pointer-events-none flex justify-end"
408
+ }, undefined, false, undefined, this);
409
+ }
410
+
411
+ // src/modules/slots.module.tsx
412
+ var SlotsModule = {
413
+ name: "slots",
414
+ version: "1.0.0",
415
+ requires: [],
416
+ install() {
417
+ SlotsComponentRegistry.register("BlockActionButton", BlockActionButton);
418
+ SlotsComponentRegistry.register("ToolBarButton", ToolbarButton);
419
+ SlotsComponentRegistry.register("SelectionOverlay", SelectionOverlay);
420
+ SlotsComponentRegistry.register("FocusOverlay", FocusOverlay);
421
+ SlotsComponentRegistry.register("HoverOverlay", HoverOverlay);
422
+ }
423
+ };
424
+ // src/modules/autosave.module.ts
425
+ import { SerializeTree } from "@coorax/core";
426
+
427
+ // src/services/localdb/lexer/lexer.ts
428
+ class Lexer {
429
+ pos = 0;
430
+ word = [];
431
+ tokensTypes = [
432
+ "SELECT",
433
+ "FROM",
434
+ "WHERE",
435
+ "JOIN",
436
+ "INNER",
437
+ "LEFT",
438
+ "RIGHT",
439
+ "FULL",
440
+ "CROSS",
441
+ "ON",
442
+ "AND",
443
+ "OR",
444
+ "AS",
445
+ "INSERT",
446
+ "INTO",
447
+ "VALUES",
448
+ "CREATE",
449
+ "TABLE"
450
+ ];
451
+ cleanWord() {
452
+ this.word = [];
453
+ }
454
+ bumpPos() {
455
+ this.pos++;
456
+ }
457
+ flushWord(tokens) {
458
+ if (this.word.length === 0)
459
+ return;
460
+ const currentWord = this.word.join("");
461
+ const upper = currentWord.toUpperCase();
462
+ if (this.tokensTypes.includes(upper)) {
463
+ tokens.push({
464
+ type: upper,
465
+ value: upper
466
+ });
467
+ } else {
468
+ tokens.push({
469
+ type: "IDENTIFIER",
470
+ value: currentWord
471
+ });
472
+ }
473
+ this.cleanWord();
474
+ }
475
+ lex(sql) {
476
+ const sqlString = sql.replace(/[\r\n]+/g, " ").trim();
477
+ const tokens = [];
478
+ if (!sqlString.endsWith(";")) {
479
+ throw new Error(`Failed to execute sql. ';' missing at the end`);
480
+ }
481
+ this.pos = 0;
482
+ this.cleanWord();
483
+ while (this.pos < sqlString.length) {
484
+ const currentChar = sqlString[this.pos];
485
+ if (currentChar === "'" || currentChar === '"') {
486
+ this.flushWord(tokens);
487
+ const quoteChar = currentChar;
488
+ this.bumpPos();
489
+ const strChars = [];
490
+ let closed = false;
491
+ while (this.pos < sqlString.length) {
492
+ const char = sqlString[this.pos];
493
+ if (char === "\\") {
494
+ this.bumpPos();
495
+ if (this.pos < sqlString.length) {
496
+ strChars.push(sqlString[this.pos]);
497
+ this.bumpPos();
498
+ }
499
+ continue;
500
+ }
501
+ if (char === quoteChar) {
502
+ this.bumpPos();
503
+ closed = true;
504
+ break;
505
+ }
506
+ strChars.push(char);
507
+ this.bumpPos();
508
+ }
509
+ if (!closed) {
510
+ throw new Error(`Unterminated string literal at ${this.pos}`);
511
+ }
512
+ tokens.push({
513
+ type: "STRING",
514
+ value: strChars.join("")
515
+ });
516
+ continue;
517
+ }
518
+ if (currentChar === " " || currentChar === "\t") {
519
+ this.flushWord(tokens);
520
+ this.bumpPos();
521
+ continue;
522
+ }
523
+ switch (currentChar) {
524
+ case ",":
525
+ this.flushWord(tokens);
526
+ tokens.push({ type: "COMMA", value: "," });
527
+ this.bumpPos();
528
+ continue;
529
+ case ";":
530
+ this.flushWord(tokens);
531
+ tokens.push({ type: "SEMICOLON", value: ";" });
532
+ this.bumpPos();
533
+ continue;
534
+ case "(":
535
+ this.flushWord(tokens);
536
+ tokens.push({ type: "BRACKETS", value: "(" });
537
+ this.bumpPos();
538
+ continue;
539
+ case ")":
540
+ this.flushWord(tokens);
541
+ tokens.push({ type: "BRACKETS", value: ")" });
542
+ this.bumpPos();
543
+ continue;
544
+ case "*":
545
+ this.flushWord(tokens);
546
+ tokens.push({ type: "STAR", value: "*" });
547
+ this.bumpPos();
548
+ continue;
549
+ case "=":
550
+ this.flushWord(tokens);
551
+ tokens.push({ type: "EQUALS", value: "=" });
552
+ this.bumpPos();
553
+ continue;
554
+ case "?":
555
+ this.flushWord(tokens);
556
+ tokens.push({ type: "QUESTION_MARK", value: "?" });
557
+ this.bumpPos();
558
+ continue;
559
+ default:
560
+ this.word.push(currentChar);
561
+ this.bumpPos();
562
+ continue;
563
+ }
564
+ }
565
+ this.flushWord(tokens);
566
+ this.pos = 0;
567
+ this.cleanWord();
568
+ return tokens;
569
+ }
570
+ }
571
+
572
+ // src/services/localdb/parser/parser.constants.ts
573
+ var TYPES_DEFS = [
574
+ "TEXT",
575
+ "DATETIME",
576
+ "INTEGER",
577
+ "UUID",
578
+ "OBJECT",
579
+ "ARRAY[STRING]",
580
+ "FILE",
581
+ "BLOB"
582
+ ];
583
+ var TYPES_DEFS_MAPPING = {
584
+ TEXT: "string",
585
+ INTEGER: "number",
586
+ DATETIME: "number",
587
+ UUID: "uuid",
588
+ OBJECT: "object",
589
+ "ARRAY[STRING]": "array.string",
590
+ FILE: "file",
591
+ BLOB: "blob"
592
+ };
593
+
594
+ // src/services/localdb/parser/parser.ts
595
+ class Parser {
596
+ statementTypes = ["SELECT", "INSERT", "CREATE"];
597
+ foundTable(tokens) {
598
+ return tokens.find((token, idx) => {
599
+ return token.type === "IDENTIFIER" && ["FROM", "INTO", "TABLE"].includes(tokens[idx - 1]?.type);
600
+ });
601
+ }
602
+ parseSelect(tokens) {
603
+ const fromIndex = tokens.findIndex((t) => t.type === "FROM");
604
+ if (fromIndex === -1) {
605
+ throw new Error("Invalid SELECT statement: missing FROM clause");
606
+ }
607
+ const isAllFieldsWanted = tokens.slice(0, fromIndex).some((t) => t.type === "STAR");
608
+ const columns = isAllFieldsWanted ? ["*"] : tokens.slice(1, fromIndex).filter((t) => t.type === "IDENTIFIER" || t.type === "STRING").map((t) => t.value);
609
+ const tableToken = tokens[fromIndex + 1];
610
+ if (!tableToken || tableToken.type !== "IDENTIFIER") {
611
+ throw new Error("Invalid SELECT statement: missing table name after FROM");
612
+ }
613
+ const mainTable = tableToken.value;
614
+ let cursor = fromIndex + 2;
615
+ let mainAlias;
616
+ if (cursor < tokens.length) {
617
+ if (tokens[cursor]?.type === "AS" && tokens[cursor + 1]?.type === "IDENTIFIER") {
618
+ mainAlias = tokens[cursor + 1].value;
619
+ cursor += 2;
620
+ } else if (tokens[cursor]?.type === "IDENTIFIER" && !["JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "WHERE", "SEMICOLON"].includes(tokens[cursor].type)) {
621
+ mainAlias = tokens[cursor].value;
622
+ cursor++;
623
+ }
624
+ }
625
+ const joins = [];
626
+ while (cursor < tokens.length) {
627
+ const currentToken = tokens[cursor];
628
+ if (!currentToken || currentToken.type === "SEMICOLON" || currentToken.type === "WHERE") {
629
+ break;
630
+ }
631
+ let joinType = "JOIN";
632
+ let hasJoin = false;
633
+ if (currentToken.type === "JOIN") {
634
+ joinType = "JOIN";
635
+ cursor++;
636
+ hasJoin = true;
637
+ } else if (["INNER", "LEFT", "RIGHT", "FULL", "CROSS"].includes(currentToken.type) && tokens[cursor + 1]?.type === "JOIN") {
638
+ joinType = currentToken.type;
639
+ cursor += 2;
640
+ hasJoin = true;
641
+ }
642
+ if (!hasJoin) {
643
+ break;
644
+ }
645
+ const joinTableToken = tokens[cursor];
646
+ if (!joinTableToken || joinTableToken.type !== "IDENTIFIER") {
647
+ throw new Error(`Expected table name after ${joinType} JOIN`);
648
+ }
649
+ const joinTable = joinTableToken.value;
650
+ cursor++;
651
+ let joinAlias;
652
+ if (cursor < tokens.length) {
653
+ if (tokens[cursor]?.type === "AS" && tokens[cursor + 1]?.type === "IDENTIFIER") {
654
+ joinAlias = tokens[cursor + 1].value;
655
+ cursor += 2;
656
+ } else if (tokens[cursor]?.type === "IDENTIFIER" && tokens[cursor].value.toUpperCase() !== "ON" && !["JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "WHERE", "SEMICOLON"].includes(tokens[cursor].type)) {
657
+ joinAlias = tokens[cursor].value;
658
+ cursor++;
659
+ }
660
+ }
661
+ let joinCondition;
662
+ if (tokens[cursor]?.type === "ON") {
663
+ cursor++;
664
+ const leftToken = tokens[cursor];
665
+ cursor++;
666
+ const opToken = tokens[cursor];
667
+ cursor++;
668
+ const rightToken = tokens[cursor];
669
+ cursor++;
670
+ if (!leftToken || !opToken || !rightToken || opToken.type !== "EQUALS" && opToken.value !== "=") {
671
+ throw new Error(`Invalid ON clause syntax in JOIN ${joinTable}`);
672
+ }
673
+ const leftParts = leftToken.value.split(".");
674
+ const rightParts = rightToken.value.split(".");
675
+ const leftTable = leftParts.length > 1 ? leftParts[0] : undefined;
676
+ const leftColumn = leftParts.length > 1 ? leftParts[1] : leftParts[0];
677
+ const rightTable = rightParts.length > 1 ? rightParts[0] : undefined;
678
+ const rightColumn = rightParts.length > 1 ? rightParts[1] : rightParts[0];
679
+ joinCondition = {
680
+ leftTable,
681
+ leftColumn,
682
+ operator: "=",
683
+ rightTable,
684
+ rightColumn
685
+ };
686
+ }
687
+ joins.push({
688
+ type: joinType,
689
+ table: joinTable,
690
+ alias: joinAlias,
691
+ on: joinCondition
692
+ });
693
+ }
694
+ const where = [];
695
+ if (tokens[cursor]?.type === "WHERE") {
696
+ cursor++;
697
+ while (cursor < tokens.length) {
698
+ const colToken = tokens[cursor];
699
+ if (!colToken || colToken.type === "SEMICOLON")
700
+ break;
701
+ cursor++;
702
+ const opToken = tokens[cursor];
703
+ cursor++;
704
+ const valToken = tokens[cursor];
705
+ cursor++;
706
+ if (colToken && opToken && valToken) {
707
+ const colParts = colToken.value.split(".");
708
+ const table = colParts.length > 1 ? colParts[0] : undefined;
709
+ const column = colParts.length > 1 ? colParts[1] : colParts[0];
710
+ where.push({
711
+ table,
712
+ column,
713
+ operator: opToken.value || "=",
714
+ value: valToken.value
715
+ });
716
+ }
717
+ if (tokens[cursor]?.type === "AND" || tokens[cursor]?.type === "OR") {
718
+ cursor++;
719
+ } else {
720
+ break;
721
+ }
722
+ }
723
+ }
724
+ return {
725
+ type: "SELECT",
726
+ columns,
727
+ table: mainTable,
728
+ alias: mainAlias,
729
+ joins: joins.length > 0 ? joins : undefined,
730
+ where: where.length > 0 ? where : undefined
731
+ };
732
+ }
733
+ parseInsert(tokens, params, paramState = { index: 0 }) {
734
+ const intoIndex = tokens.findIndex((t) => t.type === "INTO");
735
+ if (intoIndex === -1) {
736
+ throw new Error("Invalid INSERT statement: missing INTO keyword");
737
+ }
738
+ const tableToken = tokens[intoIndex + 1];
739
+ if (!tableToken || tableToken.type !== "IDENTIFIER") {
740
+ throw new Error("Invalid INSERT statement: missing table name");
741
+ }
742
+ const table = tableToken.value;
743
+ let cursor = intoIndex + 2;
744
+ let fields;
745
+ if (tokens[cursor]?.type === "BRACKETS" && tokens[cursor]?.value === "(") {
746
+ cursor++;
747
+ fields = [];
748
+ while (cursor < tokens.length) {
749
+ const t = tokens[cursor];
750
+ if (t.type === "BRACKETS" && t.value === ")") {
751
+ cursor++;
752
+ break;
753
+ }
754
+ if (t.type === "IDENTIFIER") {
755
+ fields.push(t.value);
756
+ }
757
+ cursor++;
758
+ }
759
+ }
760
+ const valuesIndex = tokens.slice(cursor).findIndex((t) => t.type === "VALUES");
761
+ if (valuesIndex === -1) {
762
+ throw new Error("Invalid INSERT statement: missing VALUES keyword");
763
+ }
764
+ cursor += valuesIndex + 1;
765
+ const statements = [];
766
+ while (cursor < tokens.length) {
767
+ if (tokens[cursor]?.type === "SEMICOLON")
768
+ break;
769
+ if (tokens[cursor]?.type === "BRACKETS" && tokens[cursor]?.value === "(") {
770
+ cursor++;
771
+ const values = [];
772
+ while (cursor < tokens.length) {
773
+ const t = tokens[cursor];
774
+ if (t.type === "BRACKETS" && t.value === ")") {
775
+ cursor++;
776
+ break;
777
+ }
778
+ if (t.type === "COMMA") {
779
+ cursor++;
780
+ continue;
781
+ }
782
+ if (t.type === "QUESTION_MARK") {
783
+ if (params && paramState.index < params.length) {
784
+ values.push(params[paramState.index++]);
785
+ } else {
786
+ values.push(null);
787
+ }
788
+ } else if (t.type === "STRING") {
789
+ values.push(t.value);
790
+ } else if (t.type === "NUMBER" || /^-?\d+(\.\d+)?$/.test(t.value)) {
791
+ values.push(Number(t.value));
792
+ } else {
793
+ values.push(t.value);
794
+ }
795
+ cursor++;
796
+ }
797
+ statements.push({
798
+ type: "INSERT",
799
+ table,
800
+ fields,
801
+ columns: values.map((v) => typeof v === "object" ? JSON.stringify(v) : String(v ?? "")),
802
+ values
803
+ });
804
+ } else {
805
+ cursor++;
806
+ }
807
+ }
808
+ return statements;
809
+ }
810
+ parseCreate(tokens) {
811
+ const statements = [];
812
+ let cursor = 0;
813
+ while (cursor < tokens.length) {
814
+ const createIdx = tokens.slice(cursor).findIndex((t) => t.type === "CREATE");
815
+ if (createIdx === -1)
816
+ break;
817
+ const startIdx = cursor + createIdx;
818
+ const semiIdx = tokens.slice(startIdx).findIndex((t) => t.type === "SEMICOLON");
819
+ if (semiIdx === -1) {
820
+ throw new Error("Invalid CREATE statement: missing ';' at end");
821
+ }
822
+ const currentTokens = tokens.slice(startIdx, startIdx + semiIdx + 1);
823
+ cursor = startIdx + semiIdx + 1;
824
+ const nextToken = currentTokens[1];
825
+ if (!nextToken || !["TABLE", "INDEX"].includes(nextToken.type)) {
826
+ throw new Error(`Invalid statement at near ${nextToken?.value}. Should be TABLE or INDEX!`);
827
+ }
828
+ const currentTable = this.foundTable(currentTokens);
829
+ if (!currentTable) {
830
+ throw new Error("Cannot find table name in CREATE TABLE statement");
831
+ }
832
+ const openBracketIndex = currentTokens.findIndex((t) => t.type === "BRACKETS" && t.value === "(");
833
+ const closeBracketIndex = currentTokens.findIndex((t) => t.type === "BRACKETS" && t.value === ")");
834
+ if (openBracketIndex === -1 || closeBracketIndex === -1) {
835
+ throw new Error("Invalid statement. '(' or ')' is missing in CREATE TABLE!");
836
+ }
837
+ const creationColumns = [];
838
+ const innerTokens = currentTokens.slice(openBracketIndex + 1, closeBracketIndex);
839
+ const isTypeDefOrDecorators = (token) => TYPES_DEFS.includes(token.value.toUpperCase()) || token.type !== "IDENTIFIER";
840
+ for (let i = 0;i < innerTokens.length; i++) {
841
+ const token = innerTokens[i];
842
+ if (isTypeDefOrDecorators(token))
843
+ continue;
844
+ const tokenTypeDef = innerTokens[i + 1];
845
+ if (!tokenTypeDef)
846
+ continue;
847
+ const mappedType = TYPES_DEFS_MAPPING[tokenTypeDef.value.toUpperCase()];
848
+ if (!mappedType) {
849
+ throw new Error(`Unknown type at near ${tokenTypeDef.value}`);
850
+ }
851
+ creationColumns.push(`${token.value}:${mappedType}`);
852
+ }
853
+ statements.push({
854
+ type: "CREATE",
855
+ table: currentTable.value,
856
+ columns: creationColumns
857
+ });
858
+ }
859
+ return statements;
860
+ }
861
+ parse(tokens, params) {
862
+ if (tokens.length < 5) {
863
+ throw new Error(`Invalid tokens array with missing elements!`);
864
+ }
865
+ const firstStatement = tokens[0];
866
+ if (!this.statementTypes.includes(firstStatement.type)) {
867
+ throw new Error(`Invalid statement at near ${firstStatement.value}`);
868
+ }
869
+ const paramState = { index: 0 };
870
+ if (firstStatement.type === "CREATE") {
871
+ return this.parseCreate(tokens);
872
+ }
873
+ if (firstStatement.type === "SELECT") {
874
+ return [this.parseSelect(tokens)];
875
+ }
876
+ if (firstStatement.type === "INSERT") {
877
+ const stmtChunks = [];
878
+ let currentChunk = [];
879
+ for (const t of tokens) {
880
+ currentChunk.push(t);
881
+ if (t.type === "SEMICOLON") {
882
+ stmtChunks.push(currentChunk);
883
+ currentChunk = [];
884
+ }
885
+ }
886
+ if (currentChunk.length > 0)
887
+ stmtChunks.push(currentChunk);
888
+ const results = [];
889
+ for (const chunk of stmtChunks) {
890
+ if (chunk.some((t) => t.type === "INSERT")) {
891
+ results.push(...this.parseInsert(chunk, params, paramState));
892
+ }
893
+ }
894
+ return results;
895
+ }
896
+ throw new Error(`Unsupported statement type: ${firstStatement.type}`);
897
+ }
898
+ }
899
+
900
+ // src/services/localdb/operator/operator.ts
901
+ class DBClient {
902
+ lexer = new Lexer;
903
+ parser = new Parser;
904
+ NewRequest(query, params) {
905
+ return this.parser.parse(this.lexer.lex(query), params);
906
+ }
907
+ }
908
+
909
+ // src/services/localdb/sheet/sheet.ts
910
+ class TablesSheet {
911
+ tables = [];
912
+ constructor() {}
913
+ statementToTable(stm) {
914
+ const fields = {};
915
+ const order = [];
916
+ for (const [key, value] of stm.columns.map((cl) => cl.split(":"))) {
917
+ const fieldType = value;
918
+ const newField = fieldType;
919
+ fields[key] = newField;
920
+ if (order.includes(key)) {
921
+ throw new Error(`Duplicate field at statement near ${key}`);
922
+ }
923
+ order.push(key);
924
+ }
925
+ return {
926
+ name: stm.table,
927
+ fields,
928
+ order
929
+ };
930
+ }
931
+ async RegisterSheet(statements) {
932
+ const tables = statements.map((stm) => this.statementToTable(stm));
933
+ this.tables = tables;
934
+ return tables;
935
+ }
936
+ GetTables() {
937
+ return this.tables;
938
+ }
939
+ }
940
+
941
+ // src/services/localdb/sheet/sheet.constants.ts
942
+ import z from "zod";
943
+ var DEFAULT_FIELDS_SCHEMA = new Map([
944
+ ["string", z.string()],
945
+ ["number", z.number()],
946
+ ["bigint", z.bigint()],
947
+ ["symbol", z.symbol()],
948
+ ["undefined", z.undefined()],
949
+ ["boolean", z.boolean()],
950
+ ["object", z.record(z.string(), z.any()).or(z.object({}))],
951
+ ["uuid", z.string()],
952
+ ["array.string", z.array(z.string())],
953
+ [
954
+ "file",
955
+ z.custom((val) => {
956
+ if (typeof Blob !== "undefined" && val instanceof Blob)
957
+ return true;
958
+ if (typeof File !== "undefined" && val instanceof File)
959
+ return true;
960
+ if (typeof val === "object" && val !== null)
961
+ return true;
962
+ return false;
963
+ })
964
+ ],
965
+ [
966
+ "blob",
967
+ z.custom((val) => {
968
+ if (typeof Blob !== "undefined" && val instanceof Blob)
969
+ return true;
970
+ if (typeof File !== "undefined" && val instanceof File)
971
+ return true;
972
+ if (typeof val === "object" && val !== null)
973
+ return true;
974
+ return false;
975
+ })
976
+ ]
977
+ ]);
978
+
979
+ // src/services/localdb/db/db.ts
980
+ class LocalDB {
981
+ DBName = "MYDB";
982
+ DBVersion = 1;
983
+ defaultStores = [];
984
+ DBTypesStoreName = "__db.types";
985
+ isAvailable;
986
+ isError = null;
987
+ db = null;
988
+ client = new DBClient;
989
+ sheet = new TablesSheet;
990
+ constructor(DbName) {
991
+ if (DbName)
992
+ this.DBName = DbName;
993
+ this.isAvailable = typeof window !== "undefined" && !!window?.indexedDB;
994
+ }
995
+ onDBError(cb, ev) {
996
+ console.error("[ERROR] IndexedDB error:", ev);
997
+ this.isError = new Error(ev.target?.error?.name ?? ev.type);
998
+ cb(new Error(ev.target?.error?.name ?? ev.type));
999
+ }
1000
+ onDBSuccess(cb, ev) {
1001
+ this.db = ev.target.result;
1002
+ this.isError = null;
1003
+ cb(null);
1004
+ }
1005
+ closeConnection() {
1006
+ if (this.db) {
1007
+ this.db.close();
1008
+ this.db = null;
1009
+ }
1010
+ }
1011
+ ensureObjectStores(db, storeNames = this.defaultStores) {
1012
+ for (const name of storeNames) {
1013
+ if (db.objectStoreNames.contains(name))
1014
+ continue;
1015
+ db.createObjectStore(name, { keyPath: "id" });
1016
+ }
1017
+ }
1018
+ bumpVersion(value) {
1019
+ this.DBVersion = value ?? this.DBVersion + 1;
1020
+ }
1021
+ async DeleteDB() {
1022
+ if (!this.isAvailable) {
1023
+ console.warn("[WARN] IndexDB not available in this browser!");
1024
+ return new Error("[ERROR] IndexDB not available in this browser!");
1025
+ }
1026
+ this.closeConnection();
1027
+ return new Promise((resolve) => {
1028
+ const request = window.indexedDB.deleteDatabase(this.DBName);
1029
+ request.onsuccess = () => {
1030
+ this.db = null;
1031
+ resolve(null);
1032
+ };
1033
+ request.onerror = () => {
1034
+ console.error("[ERROR] Failed to delete database", request.error);
1035
+ resolve(request.error ?? new Error("Failed to delete database"));
1036
+ };
1037
+ request.onblocked = () => {
1038
+ console.warn("[WARN] Database deletion blocked. Close all open connections first.");
1039
+ resolve(new Error("[WARN] Database deletion blocked. Close all open connections first."));
1040
+ };
1041
+ });
1042
+ }
1043
+ async init() {
1044
+ return new Promise((resolve, reject) => {
1045
+ if (!this.isAvailable) {
1046
+ console.warn("[WARN] IndexDB not available in this browser!");
1047
+ return;
1048
+ }
1049
+ if (this.db)
1050
+ resolve(true);
1051
+ const request = window.indexedDB.open(this.DBName, this.DBVersion !== 1 ? this.DBVersion : undefined);
1052
+ request.onupgradeneeded = () => {
1053
+ this.ensureObjectStores(request.result, this.defaultStores);
1054
+ };
1055
+ request.onerror = this.onDBError.bind(this, reject);
1056
+ request.onsuccess = (ev) => {
1057
+ this.bumpVersion(request.result.version);
1058
+ this.onDBSuccess(() => resolve(true), ev);
1059
+ };
1060
+ });
1061
+ }
1062
+ async retrieveData(objectStore, columns) {
1063
+ return new Promise((resolve) => {
1064
+ const data = [];
1065
+ const cursorReq = objectStore.openCursor();
1066
+ cursorReq.onsuccess = (ev) => {
1067
+ const cursor = ev.target.result;
1068
+ if (cursor) {
1069
+ const value = cursor.value;
1070
+ if (typeof value !== "object" || value === null) {
1071
+ cursor.continue();
1072
+ return;
1073
+ }
1074
+ const row = { ...value };
1075
+ if (!columns.includes("*")) {
1076
+ for (const key of Object.keys(row)) {
1077
+ if (!columns.includes(key)) {
1078
+ delete row[key];
1079
+ }
1080
+ }
1081
+ }
1082
+ data.push(row);
1083
+ cursor.continue();
1084
+ } else {
1085
+ resolve(data);
1086
+ }
1087
+ };
1088
+ cursorReq.onerror = (ev) => {
1089
+ console.error(`Cursor error: ${ev.target.error?.message}`);
1090
+ resolve([]);
1091
+ };
1092
+ });
1093
+ }
1094
+ async retrieveById(objectStore, id, columns) {
1095
+ return new Promise((resolve) => {
1096
+ const request = objectStore.get(id);
1097
+ request.onsuccess = () => {
1098
+ const value = request.result;
1099
+ if (!value) {
1100
+ resolve(null);
1101
+ return;
1102
+ }
1103
+ if (typeof value !== "object") {
1104
+ console.error(`Expected an object, received ${typeof value}`);
1105
+ resolve(null);
1106
+ return;
1107
+ }
1108
+ const row = { ...value };
1109
+ if (!columns.includes("*")) {
1110
+ for (const key of Object.keys(row)) {
1111
+ if (!columns.includes(key)) {
1112
+ delete row[key];
1113
+ }
1114
+ }
1115
+ }
1116
+ resolve(row);
1117
+ };
1118
+ request.onerror = (ev) => {
1119
+ console.error(`Retrieve by ID error: ${ev.target.error?.message}`);
1120
+ resolve(null);
1121
+ };
1122
+ });
1123
+ }
1124
+ async insertData(objectStore, data) {
1125
+ return new Promise((resolve) => {
1126
+ if (Array.isArray(data)) {
1127
+ throw new Error("Oops! you provide an array...");
1128
+ }
1129
+ const request = objectStore.put(data);
1130
+ request.onsuccess = () => {
1131
+ resolve(null);
1132
+ };
1133
+ request.onerror = (ev) => {
1134
+ resolve(new Error(`Insert error: ${ev.target.error?.message}`));
1135
+ };
1136
+ });
1137
+ }
1138
+ openTx(tableNames, reject, mode = "readwrite") {
1139
+ const rawNames = Array.isArray(tableNames) ? tableNames : [tableNames];
1140
+ const uniqueNames = [...new Set(rawNames.filter(Boolean))];
1141
+ for (const name of uniqueNames) {
1142
+ if (!this.db?.objectStoreNames.contains(name)) {
1143
+ throw new Error(`Table ${name} does not exist!`);
1144
+ }
1145
+ }
1146
+ const tx = this.db.transaction([this.DBTypesStoreName, ...uniqueNames], mode);
1147
+ tx.onerror = this.onDBError.bind(this, reject);
1148
+ return [tx, tx.objectStore(uniqueNames[0])];
1149
+ }
1150
+ convertFieldValueType(value, type) {
1151
+ switch (type) {
1152
+ case "number":
1153
+ if (typeof value === "number")
1154
+ return value;
1155
+ if (!/^-?\d+$/.test(String(value).trim())) {
1156
+ throw new Error(`Invalid number expr. Got ${value}`);
1157
+ }
1158
+ return parseInt(String(value).trim(), 10);
1159
+ case "boolean":
1160
+ if (typeof value === "boolean")
1161
+ return value;
1162
+ if (!["true", "false"].includes(String(value).trim())) {
1163
+ throw new Error(`Invalid boolean expr. Got ${value}`);
1164
+ }
1165
+ return String(value).trim() === "true";
1166
+ case "bigint":
1167
+ return BigInt(value);
1168
+ case "symbol":
1169
+ return typeof value === "symbol" ? value : Symbol.for(String(value));
1170
+ case "object":
1171
+ if (typeof value === "object" && value !== null)
1172
+ return value;
1173
+ if (typeof value === "string") {
1174
+ try {
1175
+ return JSON.parse(value);
1176
+ } catch {
1177
+ return {};
1178
+ }
1179
+ }
1180
+ return {};
1181
+ case "array.string":
1182
+ if (Array.isArray(value))
1183
+ return value.map(String);
1184
+ if (value instanceof Set)
1185
+ return Array.from(value).map(String);
1186
+ if (typeof value === "string") {
1187
+ try {
1188
+ const parsed = JSON.parse(value);
1189
+ if (Array.isArray(parsed))
1190
+ return parsed.map(String);
1191
+ } catch {}
1192
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
1193
+ }
1194
+ return [];
1195
+ case "file":
1196
+ case "blob":
1197
+ return value;
1198
+ default:
1199
+ return typeof value === "string" ? value.trim() : String(value ?? "");
1200
+ }
1201
+ }
1202
+ async executeQuery(requests) {
1203
+ this.isError = null;
1204
+ let lastResult = [];
1205
+ for (const request of requests) {
1206
+ try {
1207
+ switch (request.type) {
1208
+ case "SELECT": {
1209
+ const selectReq = request;
1210
+ const joinTables = (selectReq.joins ?? []).map((j) => j.table);
1211
+ const allTables = [selectReq.table, ...joinTables];
1212
+ const [tx, primaryStore] = this.openTx(allTables, (err) => {
1213
+ this.isError = err;
1214
+ }, "readonly");
1215
+ let mainRows = await this.retrieveData(primaryStore, ["*"]);
1216
+ if (selectReq.where && selectReq.where.length > 0) {
1217
+ mainRows = mainRows.filter((row) => {
1218
+ return selectReq.where.every((cond) => {
1219
+ if (cond.table && cond.table !== selectReq.table && cond.table !== selectReq.alias) {
1220
+ return true;
1221
+ }
1222
+ const val = row[cond.column];
1223
+ if (cond.operator === "=") {
1224
+ return String(val) === String(cond.value);
1225
+ }
1226
+ if (cond.operator === "!=") {
1227
+ return String(val) !== String(cond.value);
1228
+ }
1229
+ return true;
1230
+ });
1231
+ });
1232
+ }
1233
+ if (selectReq.joins && selectReq.joins.length > 0) {
1234
+ for (const join of selectReq.joins) {
1235
+ const joinStore = tx.objectStore(join.table);
1236
+ let joinRows = await this.retrieveData(joinStore, ["*"]);
1237
+ if (selectReq.where && selectReq.where.length > 0) {
1238
+ joinRows = joinRows.filter((row) => {
1239
+ return selectReq.where.every((cond) => {
1240
+ if (cond.table && cond.table !== join.table && cond.table !== join.alias) {
1241
+ return true;
1242
+ }
1243
+ const val = row[cond.column];
1244
+ if (cond.operator === "=") {
1245
+ return String(val) === String(cond.value);
1246
+ }
1247
+ if (cond.operator === "!=") {
1248
+ return String(val) !== String(cond.value);
1249
+ }
1250
+ return true;
1251
+ });
1252
+ });
1253
+ }
1254
+ let leftCol = "id";
1255
+ let rightCol = `${selectReq.table.replace(/s$/, "")}_id`;
1256
+ if (join.on) {
1257
+ leftCol = join.on.leftColumn;
1258
+ rightCol = join.on.rightColumn;
1259
+ }
1260
+ const survivingRows = [];
1261
+ for (const mainRow of mainRows) {
1262
+ const mainVal = mainRow[leftCol];
1263
+ const matched = joinRows.filter((child) => String(child[rightCol]) === String(mainVal));
1264
+ if (join.type === "INNER" && matched.length === 0) {
1265
+ continue;
1266
+ }
1267
+ const collection = {};
1268
+ let allHaveId = matched.length > 0;
1269
+ for (const child of matched) {
1270
+ if (!child.id)
1271
+ allHaveId = false;
1272
+ const cleanChild = { ...child };
1273
+ delete cleanChild[rightCol];
1274
+ collection[child.id] = cleanChild;
1275
+ }
1276
+ if (allHaveId || matched.length === 0) {
1277
+ mainRow[join.table] = collection;
1278
+ } else {
1279
+ mainRow[join.table] = matched;
1280
+ }
1281
+ survivingRows.push(mainRow);
1282
+ }
1283
+ mainRows = survivingRows;
1284
+ }
1285
+ }
1286
+ if (!selectReq.columns.includes("*")) {
1287
+ mainRows = mainRows.map((row) => {
1288
+ const filtered = {};
1289
+ for (const col of selectReq.columns) {
1290
+ if (col in row) {
1291
+ filtered[col] = row[col];
1292
+ }
1293
+ }
1294
+ return filtered;
1295
+ });
1296
+ }
1297
+ lastResult = mainRows;
1298
+ break;
1299
+ }
1300
+ case "INSERT": {
1301
+ const insertReq = request;
1302
+ const [tx, objectStore] = this.openTx(insertReq.table, (err) => {
1303
+ this.isError = err;
1304
+ }, "readwrite");
1305
+ const table = await this.retrieveById(tx.objectStore(this.DBTypesStoreName), insertReq.table, ["*"]);
1306
+ if (!table) {
1307
+ return new Error(`Table ${insertReq.table} types not found. Please try Migrate your DB`);
1308
+ }
1309
+ const newData = {};
1310
+ const fieldsToUse = insertReq.fields?.length ? insertReq.fields : table.order;
1311
+ const valuesToUse = insertReq.values?.length ? insertReq.values : insertReq.columns;
1312
+ for (let idx = 0;idx < fieldsToUse.length; idx++) {
1313
+ const fieldId = fieldsToUse[idx];
1314
+ const LocalDBDataType = table.fields[fieldId];
1315
+ const typeSchema = DEFAULT_FIELDS_SCHEMA.get(LocalDBDataType);
1316
+ if (!typeSchema) {
1317
+ return new Error(`Unknown table type ${LocalDBDataType}`);
1318
+ }
1319
+ const correspondingValue = valuesToUse[idx];
1320
+ if (correspondingValue === undefined) {
1321
+ continue;
1322
+ }
1323
+ const convertedValue = this.convertFieldValueType(correspondingValue, LocalDBDataType);
1324
+ const safeValue = typeSchema.safeParse(convertedValue);
1325
+ if (!safeValue.success) {
1326
+ return new Error(`Mismatch field type at ${fieldId}. Must be ${LocalDBDataType}. Stack: ${safeValue.error.message}`);
1327
+ }
1328
+ newData[fieldId] = convertedValue;
1329
+ }
1330
+ await this.insertData(objectStore, newData);
1331
+ break;
1332
+ }
1333
+ default:
1334
+ break;
1335
+ }
1336
+ } catch (error) {
1337
+ return error instanceof Error ? error : new Error(JSON.stringify(error));
1338
+ }
1339
+ }
1340
+ return lastResult;
1341
+ }
1342
+ async QueryDB(query, params) {
1343
+ if (!this.db)
1344
+ await this.init();
1345
+ const req = this.client.NewRequest(query, params);
1346
+ return this.executeQuery(req);
1347
+ }
1348
+ async MigrateDB(query) {
1349
+ const statements = this.client.NewRequest(query);
1350
+ const isBadReq = statements.some((s) => s.type !== "CREATE");
1351
+ if (isBadReq) {
1352
+ return new Error(`Bad request at migration. All must be CREATE statement!`);
1353
+ }
1354
+ const tables = await this.sheet.RegisterSheet(statements);
1355
+ const uniqueNames = [...new Set(tables.map((table) => table.name))];
1356
+ if (uniqueNames.includes(this.DBTypesStoreName)) {
1357
+ return new Error(`Reserved store name ${this.DBTypesStoreName}!`);
1358
+ }
1359
+ if (!this.isAvailable) {
1360
+ return new Error("[WARN] IndexDB not available in this browser!");
1361
+ }
1362
+ if (!this.db)
1363
+ await this.init();
1364
+ const namesToCreate = uniqueNames.filter((name) => !this.db?.objectStoreNames.contains(name));
1365
+ if (!namesToCreate.length) {
1366
+ return null;
1367
+ }
1368
+ this.closeConnection();
1369
+ this.bumpVersion();
1370
+ return new Promise((resolve) => {
1371
+ const request = window.indexedDB.open(this.DBName, this.DBVersion);
1372
+ request.onupgradeneeded = () => {
1373
+ const db = request.result;
1374
+ this.ensureObjectStores(db, [this.DBTypesStoreName, ...namesToCreate]);
1375
+ };
1376
+ request.onsuccess = async (ev) => {
1377
+ const db = request.result;
1378
+ const objectStore = db.transaction([this.DBTypesStoreName], "readwrite").objectStore(this.DBTypesStoreName);
1379
+ await Promise.all(tables.map((table) => this.insertData(objectStore, { ...table, id: table.name })));
1380
+ this.onDBSuccess.call(this, resolve, ev);
1381
+ };
1382
+ request.onerror = this.onDBError.bind(this, resolve);
1383
+ request.onblocked = () => {
1384
+ console.warn("[WARN] Migration blocked because another IndexedDB connection is still open.");
1385
+ resolve(new Error("IndexedDB migration blocked"));
1386
+ };
1387
+ });
1388
+ }
1389
+ }
1390
+
1391
+ // src/modules/autosave.module.ts
1392
+ async function loadCompleteDocument(db, documentId) {
1393
+ const result = await db.QueryDB(`
1394
+ SELECT * FROM documents
1395
+ JOIN fields ON documents.id = fields.document_id
1396
+ JOIN containers ON documents.id = containers.document_id
1397
+ JOIN components ON documents.id = components.document_id
1398
+ LEFT JOIN medias ON documents.id = medias.document_id
1399
+ WHERE documents.id = '${documentId}';
1400
+ `);
1401
+ if (result instanceof Error) {
1402
+ throw result;
1403
+ }
1404
+ if (Array.isArray(result) && result.length > 0) {
1405
+ return result[0];
1406
+ }
1407
+ return null;
1408
+ }
1409
+ var AutoSaveModule = {
1410
+ name: "autosave",
1411
+ version: "1.0.0",
1412
+ requires: [],
1413
+ install(ctx) {
1414
+ ctx.state.defineSlice("localdbState", { isDBReady: false });
1415
+ if (typeof window === "undefined" || !("indexedDB" in window)) {
1416
+ console.error("[WARN] indexedDB not supported or SSR");
1417
+ return;
1418
+ }
1419
+ const db = new LocalDB("coraxdb");
1420
+ db.DeleteDB().then((err) => {
1421
+ if (err) {
1422
+ console.error(err);
1423
+ return;
1424
+ }
1425
+ db.MigrateDB(`
1426
+ CREATE TABLE documents (
1427
+ id TEXT,
1428
+ version TEXT,
1429
+ order ARRAY[STRING],
1430
+ created_at DATETIME
1431
+ );
1432
+ CREATE TABLE fields (
1433
+ id TEXT,
1434
+ document_id TEXT,
1435
+ name TEXT,
1436
+ tag TEXT,
1437
+ type TEXT,
1438
+ variant TEXT,
1439
+ containerId TEXT,
1440
+ props OBJECT
1441
+ );
1442
+ CREATE TABLE containers (
1443
+ id TEXT,
1444
+ document_id TEXT,
1445
+ name TEXT,
1446
+ tag TEXT,
1447
+ type TEXT,
1448
+ variant TEXT,
1449
+ order ARRAY[STRING],
1450
+ props OBJECT
1451
+ );
1452
+ CREATE TABLE components (
1453
+ id TEXT,
1454
+ document_id TEXT,
1455
+ name TEXT,
1456
+ tag TEXT,
1457
+ type TEXT,
1458
+ variant TEXT,
1459
+ order ARRAY[STRING],
1460
+ count INTEGER,
1461
+ updatedAt DATETIME,
1462
+ createdAt DATETIME,
1463
+ props OBJECT
1464
+ );
1465
+ CREATE TABLE medias (
1466
+ id TEXT,
1467
+ document_id TEXT,
1468
+ name TEXT,
1469
+ type TEXT,
1470
+ size INTEGER,
1471
+ data FILE,
1472
+ created_at DATETIME
1473
+ );
1474
+ `).then((error) => {
1475
+ if (error) {
1476
+ console.error("Failed to migrate database:", error);
1477
+ return;
1478
+ }
1479
+ ctx.state.set("localdbState", { isDBReady: true });
1480
+ }).catch((r) => {
1481
+ console.error(r);
1482
+ });
1483
+ }).catch((e) => {
1484
+ console.error(e);
1485
+ });
1486
+ ctx.commands.before("blocks.insert", (p) => {
1487
+ const dbState = ctx.state.get("localdbState");
1488
+ if (!dbState || !dbState.isDBReady)
1489
+ return null;
1490
+ return p;
1491
+ });
1492
+ ctx.events.on("document:changed", (sbc) => {
1493
+ const dbState = ctx.state.get("localdbState");
1494
+ if (!dbState || !dbState.isDBReady)
1495
+ return;
1496
+ const jsonDocument = SerializeTree(sbc.value.next);
1497
+ const saveDocument = async () => {
1498
+ const documentId = jsonDocument.id;
1499
+ const now = Date.now();
1500
+ await db.QueryDB(`INSERT INTO documents (id, version, order, created_at) VALUES (?, ?, ?, ?);`, [documentId, jsonDocument.version, Array.from(jsonDocument.order ?? []), now]);
1501
+ for (const [fieldId, field] of Object.entries(jsonDocument.fields ?? {})) {
1502
+ await db.QueryDB(`INSERT INTO fields (id, document_id, name, tag, type, variant, containerId, props) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, [
1503
+ field.id || fieldId,
1504
+ documentId,
1505
+ field.name ?? "",
1506
+ field.tag ?? "p",
1507
+ field.type ?? "text",
1508
+ field.variant ?? "field",
1509
+ field.containerId ?? "",
1510
+ field.props ?? {}
1511
+ ]);
1512
+ const fieldProps = field.props ?? {};
1513
+ if (fieldProps.file && (fieldProps.file instanceof Blob || typeof File !== "undefined" && fieldProps.file instanceof File)) {
1514
+ const file = fieldProps.file;
1515
+ await db.QueryDB(`INSERT INTO medias (id, document_id, name, type, size, data, created_at) VALUES (?, ?, ?, ?, ?, ?, ?);`, [
1516
+ `media:${field.id || fieldId}`,
1517
+ documentId,
1518
+ file.name ?? "unnamed",
1519
+ file.type ?? "application/octet-stream",
1520
+ file.size ?? 0,
1521
+ file,
1522
+ now
1523
+ ]);
1524
+ }
1525
+ }
1526
+ for (const [containerId, container] of Object.entries(jsonDocument.containers ?? {})) {
1527
+ await db.QueryDB(`INSERT INTO containers (id, document_id, name, tag, type, variant, order, props) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, [
1528
+ container.id || containerId,
1529
+ documentId,
1530
+ container.name ?? "",
1531
+ container.tag ?? "div",
1532
+ container.type ?? "division",
1533
+ container.variant ?? "container",
1534
+ Array.from(container.order ?? []),
1535
+ container.props ?? {}
1536
+ ]);
1537
+ }
1538
+ for (const [componentId, component] of Object.entries(jsonDocument.components ?? {})) {
1539
+ await db.QueryDB(`INSERT INTO components (id, document_id, name, tag, type, variant, order, count, updatedAt, createdAt, props) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, [
1540
+ component.id || componentId,
1541
+ documentId,
1542
+ component.name ?? "",
1543
+ component.tag ?? "div",
1544
+ component.type ?? "division",
1545
+ component.variant ?? "component",
1546
+ Array.from(component.order ?? []),
1547
+ component.count ?? 0,
1548
+ component.updatedAt ?? now,
1549
+ component.createdAt ?? now,
1550
+ component.props ?? {}
1551
+ ]);
1552
+ }
1553
+ };
1554
+ ctx.tasks.schedule("autosave:persist", 1000, saveDocument);
1555
+ });
1556
+ }
1557
+ };
1558
+ // src/components/slots/maps/block-actions.tsx
1559
+ import { useEffect as useEffect2, useMemo as useMemo2, useRef } from "react";
1560
+
1561
+ // src/hooks/use-slots.ts
1562
+ import { useSyncExternalStore as useSyncExternalStore2 } from "react";
1563
+ function useSlots(slotName) {
1564
+ const engine = useEngine();
1565
+ const items = useSyncExternalStore2((fn) => engine.ui.subscribe(slotName, fn), () => engine.ui.getSlots(slotName), () => engine.ui.getSlots(slotName));
1566
+ return items;
1567
+ }
1568
+
1569
+ // src/hooks/use-registry.ts
1570
+ import { useSyncExternalStore as useSyncExternalStore3 } from "react";
1571
+
1572
+ // src/registry/ui.primitives.registry.tsx
1573
+ var UIPrimitivesRegistry = new GenericRegistry;
1574
+
1575
+ // src/hooks/use-registry.ts
1576
+ function useRegistryComponent(name) {
1577
+ return useSyncExternalStore3((fn) => SlotsComponentRegistry.subscribe(name, fn), () => SlotsComponentRegistry.get(name), () => SlotsComponentRegistry.get(name));
1578
+ }
1579
+
1580
+ // src/components/slots/slot-button.tsx
1581
+ import React4 from "react";
1582
+ function SlotButton({ c, ui }) {
1583
+ const Comp = useRegistryComponent(c.name);
1584
+ if (!Comp) {
1585
+ console.warn(`No component registered for slot key "${c.name}"`);
1586
+ return null;
1587
+ }
1588
+ return React4.createElement(Comp, {
1589
+ c,
1590
+ ui,
1591
+ ...{
1592
+ "data-slot-type": "slot-button"
1593
+ }
1594
+ });
1595
+ }
1596
+
1597
+ // src/hooks/use-ui-context.ts
1598
+ function useUIContext() {
1599
+ const selection = useSlice("selection") ?? { blocks: new Map };
1600
+ const focus = useSlice("focus") ?? null;
1601
+ const hover = useSlice("hover") ?? null;
1602
+ const textSelection = useSlice("textSelection") ?? null;
1603
+ return {
1604
+ selection,
1605
+ focus,
1606
+ hover,
1607
+ textSelection
1608
+ };
1609
+ }
1610
+
1611
+ // src/components/slots/slot-component.tsx
1612
+ import { createElement } from "react";
1613
+ function SlotComponent({ c, ui }) {
1614
+ const Comp = useRegistryComponent(c.name);
1615
+ if (!Comp) {
1616
+ console.warn(`No component registered for slot key "${c.name}"`);
1617
+ return null;
1618
+ }
1619
+ const props = c.getProps(ui);
1620
+ if (!props)
1621
+ return null;
1622
+ return createElement(Comp, { ui, c });
1623
+ }
1624
+
1625
+ // src/components/slots/slots.tsx
1626
+ import { jsxDEV as jsxDEV10, Fragment } from "react/jsx-dev-runtime";
1627
+ function Slots({ slotName }) {
1628
+ const items = useSlots(slotName);
1629
+ const ui = useUIContext();
1630
+ return /* @__PURE__ */ jsxDEV10(Fragment, {
1631
+ children: items.map((c) => /* @__PURE__ */ jsxDEV10(SlotItem, {
1632
+ c,
1633
+ ui
1634
+ }, c.id, false, undefined, this))
1635
+ }, undefined, false, undefined, this);
1636
+ }
1637
+ function SlotItem({ c, ui }) {
1638
+ if (c.when && !c.when(ui))
1639
+ return null;
1640
+ switch (c.kind) {
1641
+ case "button":
1642
+ return /* @__PURE__ */ jsxDEV10(SlotButton, {
1643
+ c,
1644
+ ui
1645
+ }, undefined, false, undefined, this);
1646
+ case "component":
1647
+ return /* @__PURE__ */ jsxDEV10(SlotComponent, {
1648
+ c,
1649
+ ui
1650
+ }, undefined, false, undefined, this);
1651
+ }
1652
+ }
1653
+
1654
+ // src/components/slots/maps/block-actions.tsx
1655
+ import { cn as cn5 } from "cn";
1656
+ import { jsxDEV as jsxDEV11 } from "react/jsx-dev-runtime";
1657
+ function BlockActions({ className, children, ...rest }) {
1658
+ const selection = useSlice("selection");
1659
+ const documentSlice = useSlice("document");
1660
+ const { blocks = new Map } = selection ?? {};
1661
+ const { order = new Set } = documentSlice ?? {};
1662
+ const keys = [...blocks.keys()];
1663
+ const firstSelectionId = keys[0];
1664
+ const engine = useEngine();
1665
+ const lastPositionRef = useRef({ active: false, top: 0, left: 0 });
1666
+ const blockRect = blocks.get(firstSelectionId);
1667
+ const position = useMemo2(() => {
1668
+ if (!firstSelectionId || !blockRect) {
1669
+ return { active: false, top: 0, left: 0 };
1670
+ }
1671
+ const container = document.getElementById("corax_flow_blocks_container");
1672
+ if (!container)
1673
+ return { active: false, top: 0, left: 0 };
1674
+ const containerRect = container.getBoundingClientRect();
1675
+ const block = engine.document.getBlock(firstSelectionId);
1676
+ if (!block || block.variant !== "field")
1677
+ return { active: false, top: 0, left: 0 };
1678
+ const domElement = document.getElementById(firstSelectionId);
1679
+ if (!domElement)
1680
+ return { active: false, top: 0, left: 0 };
1681
+ const heightDiff = 36 - blockRect.height;
1682
+ const toSubstract = heightDiff / 2;
1683
+ const top = blockRect.top - (-toSubstract > 32 ? -8 : toSubstract) - containerRect.top - container.clientTop + blockRect.parentScrollTop;
1684
+ return {
1685
+ active: true,
1686
+ top,
1687
+ left: 0
1688
+ };
1689
+ }, [firstSelectionId, engine, blockRect]);
1690
+ useEffect2(() => {
1691
+ if (position.active) {
1692
+ lastPositionRef.current = position;
1693
+ }
1694
+ }, [position]);
1695
+ const _position = position.active ? position : lastPositionRef.current;
1696
+ return /* @__PURE__ */ jsxDEV11("div", {
1697
+ style: {
1698
+ top: _position.top,
1699
+ left: _position.left
1700
+ },
1701
+ className: cn5("absolute top-0 left-0 gap-1 flex items-center transition-opacity", className, {
1702
+ "opacity-0 pointer-events-none": !_position.active || keys.length > 1 || firstSelectionId && !order?.has(firstSelectionId)
1703
+ }),
1704
+ ...rest,
1705
+ children: [
1706
+ /* @__PURE__ */ jsxDEV11(Slots, {
1707
+ slotName: "block-actions"
1708
+ }, undefined, false, undefined, this),
1709
+ children
1710
+ ]
1711
+ }, undefined, true, undefined, this);
1712
+ }
1713
+ // src/components/slots/maps/overlays.tsx
1714
+ import { jsxDEV as jsxDEV12, Fragment as Fragment2 } from "react/jsx-dev-runtime";
1715
+ function Overlays() {
1716
+ return /* @__PURE__ */ jsxDEV12(Fragment2, {
1717
+ children: /* @__PURE__ */ jsxDEV12(Slots, {
1718
+ slotName: "overlay"
1719
+ }, undefined, false, undefined, this)
1720
+ }, undefined, false, undefined, this);
1721
+ }
1722
+ // src/components/slots/maps/text-inspector.tsx
1723
+ import { jsxDEV as jsxDEV13 } from "react/jsx-dev-runtime";
1724
+ function TextInspector({ blockId }) {
1725
+ return /* @__PURE__ */ jsxDEV13("div", {
1726
+ children: blockId
1727
+ }, undefined, false, undefined, this);
1728
+ }
1729
+ // src/components/slots/maps/toolbar.tsx
1730
+ import { cn as cn6 } from "cn";
1731
+ import { useRef as useRef2, useMemo as useMemo3, useEffect as useEffect3 } from "react";
1732
+
1733
+ // src/lib/selection.utils.ts
1734
+ function rangeToOffsets(root, range) {
1735
+ const measure = (node, offset) => {
1736
+ const r = document.createRange();
1737
+ r.selectNodeContents(root);
1738
+ r.setEnd(node, offset);
1739
+ return r.toString().length;
1740
+ };
1741
+ return {
1742
+ start: measure(range.startContainer, range.startOffset),
1743
+ end: measure(range.endContainer, range.endOffset)
1744
+ };
1745
+ }
1746
+ function offsetsToRange(root, start, end) {
1747
+ const range = document.createRange();
1748
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
1749
+ let pos = 0, startSet = false;
1750
+ for (let n = walker.nextNode();n; n = walker.nextNode()) {
1751
+ const next = pos + n.length;
1752
+ if (!startSet && start <= next) {
1753
+ range.setStart(n, start - pos);
1754
+ startSet = true;
1755
+ }
1756
+ if (startSet && end <= next) {
1757
+ range.setEnd(n, end - pos);
1758
+ return range;
1759
+ }
1760
+ pos = next;
1761
+ }
1762
+ return null;
1763
+ }
1764
+
1765
+ // src/components/slots/maps/toolbar.tsx
1766
+ import { jsxDEV as jsxDEV14 } from "react/jsx-dev-runtime";
1767
+ var TOOLBAR_OFFSET = 8;
1768
+ var DEFAULT_STATE = { active: false, top: 0, left: 0 };
1769
+ function Toolbar({ className, children, ...rest }) {
1770
+ const textSel = useSlice("textSelection");
1771
+ const currentBlockId = textSel?.blockId;
1772
+ const documentSlice = useSlice("document");
1773
+ const { order = new Set } = documentSlice ?? {};
1774
+ const engine = useEngine();
1775
+ const lastPositionRef = useRef2(DEFAULT_STATE);
1776
+ const toolbarRef = useRef2(null);
1777
+ const position = useMemo3(() => {
1778
+ const toolbarElement = toolbarRef.current;
1779
+ if (!currentBlockId || !toolbarElement) {
1780
+ return DEFAULT_STATE;
1781
+ }
1782
+ const el = document.getElementById(textSel.blockId);
1783
+ if (!el)
1784
+ return DEFAULT_STATE;
1785
+ const range = offsetsToRange(el, textSel.start, textSel.end);
1786
+ if (!range)
1787
+ return DEFAULT_STATE;
1788
+ const selRect = range.getBoundingClientRect();
1789
+ const block = engine.document.getBlock(currentBlockId);
1790
+ if (!block)
1791
+ return { active: false, top: 0, left: 0 };
1792
+ const blockRect = blockRectFromBlockId(currentBlockId);
1793
+ if (!blockRect)
1794
+ return { active: false, top: 0, left: 0 };
1795
+ return {
1796
+ active: true,
1797
+ top: blockRect.top - toolbarElement.offsetHeight - TOOLBAR_OFFSET,
1798
+ left: selRect.left - (toolbarElement.offsetWidth - selRect.width) / 2
1799
+ };
1800
+ }, [currentBlockId, engine, textSel]);
1801
+ useEffect3(() => {
1802
+ if (position.active) {
1803
+ lastPositionRef.current = position;
1804
+ }
1805
+ }, [position]);
1806
+ const _position = position.active ? position : lastPositionRef.current;
1807
+ return /* @__PURE__ */ jsxDEV14("div", {
1808
+ ref: toolbarRef,
1809
+ style: {
1810
+ top: _position.top,
1811
+ left: _position.left
1812
+ },
1813
+ className: cn6("fixed top-0 left-0 gap-1 flex items-center transition-all", className, {
1814
+ "opacity-0 pointer-events-none": !_position.active || currentBlockId && !order?.has(currentBlockId)
1815
+ }),
1816
+ ...rest,
1817
+ children: [
1818
+ /* @__PURE__ */ jsxDEV14(Slots, {
1819
+ slotName: "toolbar"
1820
+ }, undefined, false, undefined, this),
1821
+ children
1822
+ ]
1823
+ }, undefined, true, undefined, this);
1824
+ }
1825
+
1826
+ // src/components/slots/maps/index.ts
1827
+ "use client";
1828
+ // src/components/corax-flow.tsx
1829
+ import { useEffect as useEffect9, useReducer } from "react";
1830
+
1831
+ // src/hooks/use-renderer.ts
1832
+ import { useMemo as useMemo4 } from "react";
1833
+
1834
+ // src/renderer/renderer.tsx
1835
+ import React5 from "react";
1836
+ import {
1837
+ UTILS as UTILS3,
1838
+ segments
1839
+ } from "@coorax/core";
1840
+
1841
+ // src/registry/primitives.registry.tsx
1842
+ class PrimitivesComponentsRegistry {
1843
+ components = new Map;
1844
+ get(name) {
1845
+ const sid = Symbol.for(name);
1846
+ const foundCOmp = this.components.get(sid);
1847
+ if (foundCOmp) {
1848
+ return foundCOmp;
1849
+ }
1850
+ return null;
1851
+ }
1852
+ getAll(names) {
1853
+ return names.map((name) => this.get(name));
1854
+ }
1855
+ post(name, comp) {
1856
+ if (comp.length < 1) {
1857
+ throw new Error("Components arguments must be greater than 1");
1858
+ }
1859
+ const sid = Symbol.for(name);
1860
+ this.components.set(sid, comp);
1861
+ }
1862
+ delete(name) {
1863
+ const sid = Symbol.for(name);
1864
+ this.components.delete(sid);
1865
+ }
1866
+ batch(comps) {
1867
+ for (const [key, value] of Object.entries(comps)) {
1868
+ const sid = Symbol.for(key);
1869
+ this.components.set(sid, value);
1870
+ }
1871
+ }
1872
+ }
1873
+
1874
+ // src/hooks/use-block.ts
1875
+ import { useSyncExternalStore as useSyncExternalStore4 } from "react";
1876
+ function useBlock(id) {
1877
+ const engine = useEngine();
1878
+ return useSyncExternalStore4((fn) => engine.document.subscribeBlock(id, fn), () => engine.document.getBlock(id), () => engine.document.getBlock(id));
1879
+ }
1880
+
1881
+ // src/primitives/fields/field.primitives.tsx
1882
+ import { useCallback, useEffect as useEffect5, useRef as useRef3 } from "react";
1883
+
1884
+ // src/hooks/custom/use-isomorphic-layout-effect.ts
1885
+ import { useEffect as useEffect4, useLayoutEffect } from "react";
1886
+ var useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect4;
1887
+
1888
+ // src/primitives/fields/field.primitives.tsx
1889
+ import { jsxDEV as jsxDEV15 } from "react/jsx-dev-runtime";
1890
+ function FieldPrimitive({ blockId }) {
1891
+ const blockRef = useRef3(null);
1892
+ const engine = useEngine();
1893
+ const renderer = useRenderer();
1894
+ const block = useBlock(blockId);
1895
+ const sel = useSlice("textSelection");
1896
+ const updateRange = useCallback(() => {
1897
+ if (!sel)
1898
+ return;
1899
+ const root = document.querySelector(`[id="${CSS.escape(sel.blockId)}"][data-text-path="${CSS.escape(sel.path)}"]`);
1900
+ if (!root || !root.contains(document.activeElement))
1901
+ return;
1902
+ const domSel = document.getSelection();
1903
+ if (!domSel)
1904
+ return;
1905
+ if (domSel.rangeCount) {
1906
+ const cur = rangeToOffsets(root, domSel.getRangeAt(0));
1907
+ if (cur.start === sel.start && cur.end === sel.end)
1908
+ return;
1909
+ }
1910
+ const range = offsetsToRange(root, sel.start, sel.end);
1911
+ if (!range)
1912
+ return;
1913
+ domSel.removeAllRanges();
1914
+ domSel.addRange(range);
1915
+ }, [sel]);
1916
+ useIsomorphicLayoutEffect(() => {
1917
+ updateRange();
1918
+ }, [updateRange, engine]);
1919
+ useIsomorphicLayoutEffect(() => {
1920
+ if (!sel)
1921
+ return;
1922
+ const root = document.querySelector(`[id="${CSS.escape(sel.blockId)}"][data-text-path="${CSS.escape(sel.path)}"]`);
1923
+ if (!root)
1924
+ return;
1925
+ const range = offsetsToRange(root, sel.start, sel.end);
1926
+ if (!range)
1927
+ return;
1928
+ root.focus({ preventScroll: true });
1929
+ const domSel = document.getSelection();
1930
+ domSel.removeAllRanges();
1931
+ domSel.addRange(range);
1932
+ });
1933
+ useEffect5(() => {
1934
+ const domEl = blockRef.current;
1935
+ if (!domEl)
1936
+ return;
1937
+ const observer = new ResizeObserver(() => {
1938
+ const rect = blockRectFromBlockId(blockId);
1939
+ if (!rect || !!engine.document.get().order.size)
1940
+ return;
1941
+ engine.commands.tryExecute("blocks.focus", { id: blockId, rect });
1942
+ });
1943
+ observer.observe(domEl);
1944
+ return () => {
1945
+ observer.unobserve(domEl);
1946
+ observer.disconnect();
1947
+ };
1948
+ }, [engine, blockId]);
1949
+ if (!blockId.startsWith("field") || !block)
1950
+ return null;
1951
+ return /* @__PURE__ */ jsxDEV15("div", {
1952
+ ref: blockRef,
1953
+ children: renderer.renderField(block)
1954
+ }, undefined, false, undefined, this);
1955
+ }
1956
+
1957
+ // src/primitives/index.ts
1958
+ var FieldsPrimitives = {
1959
+ field: FieldPrimitive
1960
+ };
1961
+
1962
+ // src/renderer/renderer.utils.tsx
1963
+ import {
1964
+ UTILS as UTILS2
1965
+ } from "@coorax/core";
1966
+
1967
+ // src/lifecycle/fields/lifecycle.fields.ts
1968
+ import {
1969
+ UTILS
1970
+ } from "@coorax/core";
1971
+
1972
+ // src/lifecycle/fields/mouse.events/onclick.ts
1973
+ var createOnClick = async (engine, block, ev) => {
1974
+ ev.stopPropagation();
1975
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
1976
+ if (!fieldInfo)
1977
+ return;
1978
+ const isOnControl = ev.ctrlKey || ev.metaKey;
1979
+ const selection = engine.state.get("selection");
1980
+ if (!selection)
1981
+ return;
1982
+ const keys = Array.from(selection.blocks.keys());
1983
+ const blockRect = blockRectFromBlockId(block.id);
1984
+ if (!blockRect)
1985
+ return;
1986
+ if (!ev.shiftKey || keys.includes(block.id)) {
1987
+ const blocks = new Map;
1988
+ blocks.set(block.id, blockRect);
1989
+ engine.commands.tryExecute("blocks.select", {
1990
+ blocks,
1991
+ mode: isOnControl ? "toggle" : "replace"
1992
+ });
1993
+ } else {
1994
+ const treeOrder = [...engine.document.get().order];
1995
+ const currentBlockIndex = treeOrder.indexOf(block.id);
1996
+ const orderMap = new Map(treeOrder.map((id, index) => [id, index]));
1997
+ const { minIndexKey, maxIndexKey } = keys.reduce((acc, key) => {
1998
+ const currPos = orderMap.get(key) ?? Infinity;
1999
+ const minPos = orderMap.get(acc.minIndexKey) ?? Infinity;
2000
+ const maxPos = orderMap.get(acc.maxIndexKey) ?? -Infinity;
2001
+ return {
2002
+ minIndexKey: currPos < minPos ? key : acc.minIndexKey,
2003
+ maxIndexKey: currPos > maxPos ? key : acc.maxIndexKey
2004
+ };
2005
+ }, { minIndexKey: keys[0], maxIndexKey: keys[0] });
2006
+ const lowestIndex = treeOrder.indexOf(minIndexKey);
2007
+ const greatestIndex = treeOrder.indexOf(maxIndexKey);
2008
+ const toSelect = (() => {
2009
+ if (currentBlockIndex > lowestIndex) {
2010
+ return treeOrder.slice(lowestIndex, currentBlockIndex + 1);
2011
+ }
2012
+ return treeOrder.slice(currentBlockIndex, greatestIndex + 1);
2013
+ })();
2014
+ const blocks = new Map;
2015
+ for (const id of toSelect) {
2016
+ const rect = blockRectFromBlockId(id);
2017
+ if (rect) {
2018
+ blocks.set(id, rect);
2019
+ }
2020
+ }
2021
+ engine.commands.tryExecute("blocks.select", {
2022
+ blocks,
2023
+ mode: "replace"
2024
+ });
2025
+ }
2026
+ await fieldInfo.emit();
2027
+ };
2028
+
2029
+ // src/lifecycle/fields/mouse.events/ondoubleclick.ts
2030
+ var createOnDoubleClick = async (engine, block, ev) => {
2031
+ ev.stopPropagation();
2032
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2033
+ if (!fieldInfo)
2034
+ return;
2035
+ const rect = blockRectFromBlockId(block.id);
2036
+ if (!rect)
2037
+ return;
2038
+ const focus = engine.state.get("focus");
2039
+ if (focus?.id === block.id) {
2040
+ return;
2041
+ }
2042
+ engine.commands.tryExecute("blocks.focus", { id: block.id, rect });
2043
+ await fieldInfo.emit();
2044
+ };
2045
+
2046
+ // src/lifecycle/fields/focus.events/onfocus.ts
2047
+ var createOnFocus = async (engine, block, ev) => {
2048
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2049
+ if (!fieldInfo)
2050
+ return;
2051
+ await fieldInfo.emit();
2052
+ };
2053
+
2054
+ // src/lifecycle/fields/focus.events/onblur.ts
2055
+ var createOnBlur = async (engine, block, ev) => {
2056
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2057
+ if (!fieldInfo)
2058
+ return;
2059
+ const textSel = engine.state.get("textSelection");
2060
+ if (textSel && textSel.start !== textSel.end)
2061
+ return;
2062
+ engine.commands.tryExecute("blocks.focus", null);
2063
+ await fieldInfo.emit();
2064
+ };
2065
+
2066
+ // src/lifecycle/fields/mouse.events/onmouseleave.ts
2067
+ var createOnMouseLeave = async (engine, block, ev) => {
2068
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2069
+ if (!fieldInfo)
2070
+ return;
2071
+ const state = engine.state.get("hover");
2072
+ if (!state)
2073
+ return;
2074
+ if (state === null)
2075
+ return;
2076
+ engine.commands.tryExecute("blocks.hover", null);
2077
+ await fieldInfo.emit();
2078
+ };
2079
+
2080
+ // src/lifecycle/fields/mouse.events/onmouseenter.ts
2081
+ var createOnMouseEnter = async (engine, block, ev) => {
2082
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2083
+ if (!fieldInfo)
2084
+ return;
2085
+ const selection = engine.state.get("selection");
2086
+ if (selection && selection.blocks.has(block.id)) {
2087
+ return;
2088
+ }
2089
+ const rect = blockRectFromBlockId(block.id);
2090
+ if (!rect)
2091
+ return;
2092
+ engine.commands.tryExecute("blocks.hover", { id: block.id, rect });
2093
+ await fieldInfo.emit();
2094
+ };
2095
+
2096
+ // src/lifecycle/fields/keyboard.events/onkeydown.ts
2097
+ import {
2098
+ FieldsUtils,
2099
+ isEditableField
2100
+ } from "@coorax/core";
2101
+ var createOnKeyDown = async (engine, block, ev) => {
2102
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2103
+ if (!fieldInfo)
2104
+ return;
2105
+ if (ev.ctrlKey || ev.metaKey)
2106
+ return;
2107
+ const tree = engine.document.get();
2108
+ const normalizedTarget = fieldInfo.target;
2109
+ const hasCurrentElement = engine.document.has(normalizedTarget);
2110
+ if (!hasCurrentElement) {
2111
+ console.warn(`Ignoring stale field target: ${normalizedTarget}`);
2112
+ return;
2113
+ }
2114
+ const targetIndex = [...tree.order].indexOf(normalizedTarget);
2115
+ const index = targetIndex + 1;
2116
+ const currentTarget = ev.currentTarget;
2117
+ if (ev.key === "Enter" && !ev.shiftKey) {
2118
+ ev.preventDefault();
2119
+ currentTarget.blur();
2120
+ const newField = FieldsUtils.NewField("text");
2121
+ engine.commands.tryExecute("blocks.insert", { block: newField, pos: index });
2122
+ await fieldInfo.emit();
2123
+ const blockRect = blockRectFromBlockId(newField.id);
2124
+ if (!blockRect)
2125
+ return;
2126
+ engine.commands.tryExecute("blocks.focus", { id: newField.id, rect: blockRect });
2127
+ }
2128
+ if (ev.key === "ArrowUp" || ev.key === "ArrowDown" || ev.key === "Tab") {
2129
+ ev.preventDefault();
2130
+ const mustBeNegativeDelta = ev.key === "ArrowUp" || ev.key === "Tab" && ev.shiftKey;
2131
+ const delta = mustBeNegativeDelta ? -1 : 1;
2132
+ const currentTree = engine.document.get();
2133
+ const blockIndex = Array.from(currentTree.order).indexOf(block.id);
2134
+ if (blockIndex === -1)
2135
+ return;
2136
+ if (blockIndex === 0 && delta < 0)
2137
+ return;
2138
+ if (blockIndex === currentTree.order.size - 1 && delta > 0)
2139
+ return;
2140
+ const rectId = [...currentTree.order][blockIndex + delta];
2141
+ const rect = blockRectFromBlockId(rectId);
2142
+ if (!rect) {
2143
+ return;
2144
+ }
2145
+ currentTarget.blur();
2146
+ engine.commands.tryExecute("blocks.focus", { id: rectId, rect });
2147
+ }
2148
+ if (ev.key === "Escape") {
2149
+ ev.preventDefault();
2150
+ currentTarget.blur();
2151
+ if (!isEditableField(block)) {
2152
+ engine.commands.tryExecute("blocks.select", { blocks: new Map, mode: "replace" });
2153
+ }
2154
+ }
2155
+ if (ev.key === "Backspace") {
2156
+ if (isEditableField(block)) {
2157
+ const textContent = block.props.children.text;
2158
+ if (textContent.length === 0) {
2159
+ const order = [...engine.document.get().order];
2160
+ const curBlockIndex = order.findIndex((id) => id === block.id);
2161
+ const prevSiblingBlock = engine.document.getBlock(order[curBlockIndex - 1]);
2162
+ if (prevSiblingBlock) {
2163
+ const blockRect = blockRectFromBlockId(prevSiblingBlock.id);
2164
+ if (!blockRect) {
2165
+ engine.commands.tryExecute("blocks.focus", null);
2166
+ return;
2167
+ }
2168
+ if (isEditableField(prevSiblingBlock)) {
2169
+ engine.commands.tryExecute("blocks.focus", {
2170
+ id: prevSiblingBlock.id,
2171
+ rect: blockRect
2172
+ });
2173
+ } else {
2174
+ engine.commands.tryExecute("blocks.select", {
2175
+ blocks: new Map().set(prevSiblingBlock.id, blockRect),
2176
+ mode: "replace"
2177
+ });
2178
+ }
2179
+ } else {
2180
+ engine.commands.tryExecute("blocks.focus", null);
2181
+ }
2182
+ engine.commands.tryExecute("blocks.delete", { blockId: block.id });
2183
+ }
2184
+ }
2185
+ }
2186
+ };
2187
+
2188
+ // src/lifecycle/fields/synthetic.events/onselect.ts
2189
+ var createOnSelect = async (engine, block, ev) => {
2190
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2191
+ if (!fieldInfo)
2192
+ return;
2193
+ const target = ev.currentTarget;
2194
+ if (!target)
2195
+ return;
2196
+ const documentSel = document.getSelection();
2197
+ if (!documentSel)
2198
+ return;
2199
+ const range = documentSel.getRangeAt(0);
2200
+ const el = range.commonAncestorContainer;
2201
+ const root = (el instanceof Element ? el : el.parentElement)?.closest("[data-text-path]");
2202
+ if (!root)
2203
+ return;
2204
+ const blockId = root.getAttribute("id");
2205
+ const path = root.dataset.textPath;
2206
+ const { start, end } = rangeToOffsets(root, range);
2207
+ engine.commands.tryExecute("text.setSelection", { blockId, path, start, end });
2208
+ const sel = {
2209
+ blockId: block.id,
2210
+ path: "props.children",
2211
+ start: Math.min(start, end),
2212
+ end: Math.max(start, end)
2213
+ };
2214
+ engine.commands.tryExecute("text.setSelection", sel);
2215
+ await fieldInfo.emit();
2216
+ };
2217
+
2218
+ // src/lifecycle/fields/synthetic.events/onload.ts
2219
+ var createOnLoad = async (engine, block, ev) => {
2220
+ const fieldInfo = getFieldTypeAndTargetId(engine, ev, block);
2221
+ if (!fieldInfo)
2222
+ return;
2223
+ console.log("Loaded");
2224
+ await fieldInfo.emit();
2225
+ };
2226
+
2227
+ // src/lifecycle/fields/lifecycle.fields.ts
2228
+ function getFieldTypeAndTargetId(engine, ev, block) {
2229
+ const target = block?.id ?? ev.currentTarget?.getAttribute("id") ?? null;
2230
+ const fieldType = block?.type ?? ev.currentTarget?.getAttribute("data-block-type") ?? null;
2231
+ if (!fieldType || !target) {
2232
+ console.warn(`Failed to continue event at ${ev.type}`);
2233
+ ev.preventDefault();
2234
+ ev.stopPropagation();
2235
+ return null;
2236
+ }
2237
+ const safeTarget = target;
2238
+ const safeFieldType = fieldType;
2239
+ function emit() {
2240
+ return engine.events.emit("field:lifecycle", {
2241
+ type: ev?._reactName || `on${UTILS.Capitalize(ev.type)}`,
2242
+ target: safeTarget,
2243
+ fieldType: safeFieldType,
2244
+ cycleEvent: ev
2245
+ });
2246
+ }
2247
+ return { fieldType: safeFieldType, target: safeTarget, emit };
2248
+ }
2249
+ function getAllLifeCycleEvents(engine, block) {
2250
+ function getCommonHandlers(tag) {
2251
+ switch (tag) {
2252
+ case "h1":
2253
+ case "p":
2254
+ return {
2255
+ onClick: createOnClick.bind(null, engine, block),
2256
+ onKeyDown: createOnKeyDown.bind(null, engine, block),
2257
+ onFocus: createOnFocus.bind(null, engine, block),
2258
+ onBlur: createOnBlur.bind(null, engine, block),
2259
+ onDoubleClick: createOnDoubleClick.bind(null, engine, block),
2260
+ onMouseEnter: createOnMouseEnter.bind(null, engine, block),
2261
+ onMouseLeave: createOnMouseLeave.bind(null, engine, block),
2262
+ onSelect: createOnSelect.bind(null, engine, block)
2263
+ };
2264
+ case "img":
2265
+ case "video":
2266
+ return {
2267
+ onClick: createOnClick.bind(null, engine, block),
2268
+ onKeyDown: createOnKeyDown.bind(null, engine, block),
2269
+ onFocus: createOnFocus.bind(null, engine, block),
2270
+ onMouseEnter: createOnMouseEnter.bind(null, engine, block),
2271
+ onMouseLeave: createOnMouseLeave.bind(null, engine, block),
2272
+ onLoad: createOnLoad.bind(null, engine, block)
2273
+ };
2274
+ case "hr":
2275
+ return {
2276
+ onClick: createOnClick.bind(null, engine, block),
2277
+ onMouseEnter: createOnMouseEnter.bind(null, engine, block),
2278
+ onMouseLeave: createOnMouseLeave.bind(null, engine, block)
2279
+ };
2280
+ default:
2281
+ return {};
2282
+ }
2283
+ }
2284
+ return {
2285
+ h1: { ...getCommonHandlers("h1") },
2286
+ p: { ...getCommonHandlers("p") },
2287
+ img: { ...getCommonHandlers("img") },
2288
+ video: { ...getCommonHandlers("video") },
2289
+ hr: { ...getCommonHandlers("hr") }
2290
+ };
2291
+ }
2292
+ function getFieldLifeCycleEvents(engine, tag, block) {
2293
+ return getAllLifeCycleEvents(engine, block)[tag];
2294
+ }
2295
+ var FLC = { getFieldLifeCycleEvents };
2296
+
2297
+ // src/renderer/renderer.utils.tsx
2298
+ import { cn as cn7 } from "cn";
2299
+ import { css } from "@emotion/css";
2300
+ function getTextFieldProps(engine, block) {
2301
+ const ui = engine.ui;
2302
+ const { style, pseudoStyle, className, children: _, placeholder, ...rest } = block.props;
2303
+ const uiStyles = ui.getStyle(block.type);
2304
+ const _pseudoStyle = {
2305
+ ...uiStyles.pseudoStyle,
2306
+ ...pseudoStyle
2307
+ };
2308
+ const pseudoClassName = resolveCoraxPseudoStyle(_pseudoStyle);
2309
+ const baseProps = {
2310
+ id: block.id,
2311
+ key: block.id,
2312
+ "data-block-type": block.type,
2313
+ style: {
2314
+ ...uiStyles.style,
2315
+ ...style,
2316
+ ...block.props?.contentEditable ? { cursor: "auto", userSelect: "auto" } : null
2317
+ },
2318
+ className: cn7(uiStyles.className, className, pseudoClassName)
2319
+ };
2320
+ const containerProps = block.isContainerized() ? { "data-containerId": block.containerId } : {};
2321
+ const editableProps = {
2322
+ spellCheck: false,
2323
+ suppressContentEditableWarning: true,
2324
+ "data-placeholder": placeholder || "Tell the news here",
2325
+ ...rest,
2326
+ contentEditable: !!rest?.contentEditable,
2327
+ autoFocus: true
2328
+ };
2329
+ return {
2330
+ ...baseProps,
2331
+ ...containerProps,
2332
+ ...editableProps,
2333
+ ...FLC.getFieldLifeCycleEvents(engine, block.tag, block)
2334
+ };
2335
+ }
2336
+ function getMediaFieldProps(engine, block) {
2337
+ const ui = engine.ui;
2338
+ const { style, pseudoStyle, className, ...rest } = block.props;
2339
+ const uiStyles = ui.getStyle(block.type);
2340
+ const _pseudoStyle = {
2341
+ ...uiStyles.pseudoStyle,
2342
+ ...pseudoStyle
2343
+ };
2344
+ const pseudoClassName = resolveCoraxPseudoStyle(_pseudoStyle);
2345
+ const baseProps = {
2346
+ id: block.id,
2347
+ key: block.id,
2348
+ "data-block-type": block.type,
2349
+ style: {
2350
+ ...uiStyles.style,
2351
+ ...style
2352
+ },
2353
+ className: cn7(uiStyles.className, className, pseudoClassName)
2354
+ };
2355
+ const containerProps = block.isContainerized() ? { "data-containerId": block.containerId } : {};
2356
+ return {
2357
+ ...baseProps,
2358
+ ...containerProps,
2359
+ ...rest,
2360
+ ...FLC.getFieldLifeCycleEvents(engine, block.tag, block)
2361
+ };
2362
+ }
2363
+ function resolveCoraxPseudoStyle(style) {
2364
+ if (!style || Object.keys(style).length === 0)
2365
+ return;
2366
+ return css(style);
2367
+ }
2368
+
2369
+ // src/renderer/utils/divider.renderer.utils.tsx
2370
+ import { cn as cn8 } from "cn";
2371
+ function getDividerFieldProps(engine, block) {
2372
+ const ui = engine.ui;
2373
+ const { style, pseudoStyle, className, ...rest } = block.props;
2374
+ const uiStyles = ui.getStyle(block.type);
2375
+ const _pseudoStyle = {
2376
+ ...uiStyles.pseudoStyle,
2377
+ ...pseudoStyle
2378
+ };
2379
+ const pseudoClassName = resolveCoraxPseudoStyle(_pseudoStyle);
2380
+ const baseProps = {
2381
+ id: block.id,
2382
+ key: block.id,
2383
+ "data-block-type": block.type,
2384
+ style: {
2385
+ ...uiStyles.style,
2386
+ ...style
2387
+ },
2388
+ className: cn8(uiStyles.className, className, pseudoClassName)
2389
+ };
2390
+ const containerProps = block.isContainerized() ? { "data-containerId": block.containerId } : {};
2391
+ const handlers = FLC.getFieldLifeCycleEvents(engine, block.tag, block);
2392
+ return {
2393
+ ...baseProps,
2394
+ ...containerProps,
2395
+ ...rest,
2396
+ ...handlers
2397
+ };
2398
+ }
2399
+
2400
+ // src/renderer/renderer.tsx
2401
+ import { jsxDEV as jsxDEV16, Fragment as Fragment3 } from "react/jsx-dev-runtime";
2402
+ var defaults = {
2403
+ bold: "strong",
2404
+ italic: "em",
2405
+ underline: "u",
2406
+ code: "code",
2407
+ link: "span",
2408
+ initial: "span"
2409
+ };
2410
+ var RANK = {
2411
+ link: 0,
2412
+ bold: 1,
2413
+ italic: 2,
2414
+ underline: 3,
2415
+ code: 4,
2416
+ initial: 5
2417
+ };
2418
+ function formatText(text) {
2419
+ return text;
2420
+ }
2421
+
2422
+ class ReactRenderer {
2423
+ engine;
2424
+ primitives = new PrimitivesComponentsRegistry;
2425
+ constructor(engine) {
2426
+ this.engine = engine;
2427
+ for (const [type, comp] of UTILS3.ObjectEntries(FieldsPrimitives)) {
2428
+ this.primitives.post(type, comp);
2429
+ }
2430
+ }
2431
+ renderContainer(contanier) {
2432
+ throw new Error("Method not implemented." + contanier.name);
2433
+ }
2434
+ renderTree(key = 0) {
2435
+ const children = Array.from(this.engine.document.get().order).map((id) => {
2436
+ const block = this.engine.document.getBlock(id);
2437
+ if (!block)
2438
+ return /* @__PURE__ */ jsxDEV16(Fragment3, {}, undefined, false, undefined, this);
2439
+ const Comp = this.primitives.get(block.variant);
2440
+ if (!Comp)
2441
+ return /* @__PURE__ */ jsxDEV16(Fragment3, {}, undefined, false, undefined, this);
2442
+ return /* @__PURE__ */ jsxDEV16(Comp, {
2443
+ blockId: id
2444
+ }, id, false, undefined, this);
2445
+ });
2446
+ return React5.createElement(React5.Fragment, { key }, ...children);
2447
+ }
2448
+ renderTextField(field, key = null) {
2449
+ const children = field.props.children;
2450
+ return React5.createElement(field.tag, {
2451
+ ...getTextFieldProps(this.engine, field),
2452
+ key: key !== null ? key : field.id
2453
+ }, this.renderTextContent(children));
2454
+ }
2455
+ renderMediaField(field, key = null) {
2456
+ const isMediaReady = !!field.props.src.trim();
2457
+ if (!isMediaReady) {
2458
+ const Fallback = FallbackComponentsRegistry.get(field.type);
2459
+ if (Fallback)
2460
+ return /* @__PURE__ */ jsxDEV16(Fallback, {
2461
+ ...field
2462
+ }, undefined, false, undefined, this);
2463
+ }
2464
+ return React5.createElement(field.tag, {
2465
+ ...getMediaFieldProps(this.engine, field),
2466
+ key: key !== null ? key : field.id
2467
+ });
2468
+ }
2469
+ renderDividerField(field, key = null) {
2470
+ return React5.createElement(field.tag, {
2471
+ ...getDividerFieldProps(this.engine, field),
2472
+ key: key !== null ? key : field.id
2473
+ });
2474
+ }
2475
+ renderField(_field, key = null) {
2476
+ const field = typeof _field === "string" ? this.engine.document.getBlock(_field) : _field;
2477
+ if (!field || field.variant !== "field")
2478
+ return /* @__PURE__ */ jsxDEV16(Fragment3, {}, undefined, false, undefined, this);
2479
+ switch (field.type) {
2480
+ case "text":
2481
+ case "heading":
2482
+ return this.renderTextField(field, key);
2483
+ case "video":
2484
+ case "image":
2485
+ return this.renderMediaField(field, key);
2486
+ case "divider":
2487
+ return this.renderDividerField(field);
2488
+ default:
2489
+ return /* @__PURE__ */ jsxDEV16(Fragment3, {}, undefined, false, undefined, this);
2490
+ }
2491
+ }
2492
+ renderSegment(seg, key) {
2493
+ const marks = [...seg.marks].sort((a, b) => (RANK[a.type] ?? 9) - (RANK[b.type] ?? 9));
2494
+ const node = marks.reduceRight((child, mark) => {
2495
+ const Comp = defaults[mark.type];
2496
+ return Comp ? /* @__PURE__ */ jsxDEV16(Comp, {
2497
+ ...mark.attrs,
2498
+ children: child
2499
+ }, undefined, false, undefined, this) : child;
2500
+ }, formatText(seg.text));
2501
+ return /* @__PURE__ */ jsxDEV16(React5.Fragment, {
2502
+ children: node
2503
+ }, key, false, undefined, this);
2504
+ }
2505
+ renderTextContent(text) {
2506
+ if (!text?.text)
2507
+ return "";
2508
+ return segments(text).map(this.renderSegment);
2509
+ }
2510
+ renderNode(node, key = null) {
2511
+ return React5.createElement(node.tag, {
2512
+ style: node.props.style,
2513
+ className: node.props.className,
2514
+ key: key ?? node.id
2515
+ }, node.props.text);
2516
+ }
2517
+ }
2518
+
2519
+ // src/hooks/use-renderer.ts
2520
+ function useRenderer() {
2521
+ const engine = useEngine();
2522
+ return useMemo4(() => new ReactRenderer(engine), [engine]);
2523
+ }
2524
+
2525
+ // src/hooks/use-flow.ts
2526
+ import { useEffect as useEffect7 } from "react";
2527
+
2528
+ // src/hooks/custom/use-custom-ref.ts
2529
+ import { useEffect as useEffect6, useRef as useRef4 } from "react";
2530
+ function useCustomRef(factory) {
2531
+ const isServer = typeof window === "undefined";
2532
+ const getInitialValue = () => {
2533
+ if (isServer)
2534
+ return null;
2535
+ try {
2536
+ return typeof factory === "function" ? factory() : factory;
2537
+ } catch {
2538
+ return null;
2539
+ }
2540
+ };
2541
+ const ref = useRef4(getInitialValue());
2542
+ useEffect6(() => {
2543
+ try {
2544
+ ref.current = typeof factory === "function" ? factory() : factory;
2545
+ } catch {}
2546
+ }, [factory]);
2547
+ return ref;
2548
+ }
2549
+
2550
+ // src/hooks/use-flow.ts
2551
+ function editorRectFromDomElement(domElement) {
2552
+ const containerRect = domElement.getBoundingClientRect();
2553
+ return {
2554
+ scrollTop: domElement.scrollTop,
2555
+ scrollLeft: domElement.scrollLeft,
2556
+ clientLeft: domElement.clientLeft,
2557
+ clientTop: domElement.clientTop,
2558
+ top: containerRect.top,
2559
+ left: containerRect.left,
2560
+ bottom: containerRect.bottom,
2561
+ right: containerRect.right,
2562
+ width: containerRect.width,
2563
+ height: containerRect.height,
2564
+ offsetTop: domElement.offsetTop,
2565
+ offsetLeft: domElement.offsetLeft,
2566
+ offsetWidth: domElement.offsetWidth,
2567
+ offsetHeight: domElement.offsetHeight
2568
+ };
2569
+ }
2570
+ function useFlow() {
2571
+ const engine = useEngine();
2572
+ const coraxFlowEditorRef = useCustomRef(() => {
2573
+ if (typeof document === "undefined")
2574
+ return null;
2575
+ const flowEditor = document.getElementById("corax_flow_blocks_container");
2576
+ if (!flowEditor)
2577
+ return null;
2578
+ engine.commands.tryExecute("editor.rect", { editorRect: editorRectFromDomElement(flowEditor) });
2579
+ return flowEditor;
2580
+ });
2581
+ useEffect7(() => {
2582
+ function handleKeyDown(ev) {
2583
+ if (!ev.ctrlKey || ev.key.toLocaleLowerCase() !== "z")
2584
+ return;
2585
+ engine.commands.tryExecute(ev.shiftKey ? "history.redo" : "history.undo", {});
2586
+ }
2587
+ const flowEditor = coraxFlowEditorRef.current;
2588
+ function handleClick(ev) {
2589
+ const target = ev.target;
2590
+ if (!(target instanceof Element))
2591
+ return;
2592
+ if (target.closest("[data-block-type]") || target.closest("[data-slot-type]"))
2593
+ return;
2594
+ engine.commands.tryExecute("blocks.select", { blocks: new Map, mode: "replace" });
2595
+ }
2596
+ if (flowEditor) {
2597
+ flowEditor.addEventListener("click", handleClick);
2598
+ }
2599
+ document.addEventListener("keydown", handleKeyDown);
2600
+ return () => {
2601
+ document.removeEventListener("keydown", handleKeyDown);
2602
+ if (flowEditor) {
2603
+ flowEditor.removeEventListener("click", handleClick);
2604
+ }
2605
+ };
2606
+ }, [engine, coraxFlowEditorRef]);
2607
+ useEffect7(() => {
2608
+ const element = coraxFlowEditorRef.current;
2609
+ if (!element)
2610
+ return;
2611
+ const publishEditorRect = () => {
2612
+ engine.commands.tryExecute("editor.rect", { editorRect: editorRectFromDomElement(element) });
2613
+ };
2614
+ const observer = new ResizeObserver(publishEditorRect);
2615
+ observer.observe(element);
2616
+ element.addEventListener("scroll", publishEditorRect, { passive: true });
2617
+ return () => {
2618
+ observer.disconnect();
2619
+ element.removeEventListener("scroll", publishEditorRect);
2620
+ };
2621
+ }, [engine, coraxFlowEditorRef]);
2622
+ }
2623
+
2624
+ // src/hooks/use-text-input.ts
2625
+ import { useEffect as useEffect8 } from "react";
2626
+ function useTextInput(engine) {
2627
+ useEffect8(() => {
2628
+ let composing = false;
2629
+ const rootOf = (t) => ((t instanceof Element ? t : t?.parentElement) ?? null)?.closest("[data-text-path]") ?? null;
2630
+ const onBeforeInput = (e) => {
2631
+ const root = rootOf(e.target);
2632
+ if (!root || composing || e.isComposing)
2633
+ return;
2634
+ const tr = e.getTargetRanges()[0];
2635
+ if (tr) {
2636
+ const r = document.createRange();
2637
+ r.setStart(tr.startContainer, tr.startOffset);
2638
+ r.setEnd(tr.endContainer, tr.endOffset);
2639
+ engine.commands.tryExecute("text.setSelection", {
2640
+ blockId: root.dataset.blockId,
2641
+ path: root.dataset.textPath,
2642
+ ...rangeToOffsets(root, r)
2643
+ });
2644
+ }
2645
+ switch (e.inputType) {
2646
+ case "insertText":
2647
+ if (e.data)
2648
+ engine.commands.tryExecute("text.insert", { text: e.data });
2649
+ break;
2650
+ case "insertParagraph":
2651
+ case "insertLineBreak":
2652
+ engine.commands.tryExecute("text.insert", { text: `
2653
+ ` });
2654
+ break;
2655
+ case "insertFromPaste": {
2656
+ const text = e.dataTransfer?.getData("text/plain");
2657
+ if (text)
2658
+ engine.commands.tryExecute("text.insert", { text });
2659
+ break;
2660
+ }
2661
+ case "deleteContentBackward":
2662
+ engine.commands.tryExecute("text.delete", { direction: "backward" });
2663
+ break;
2664
+ case "deleteWordBackward":
2665
+ engine.commands.tryExecute("text.delete", { direction: "backward", type: "word" });
2666
+ break;
2667
+ case "deleteContentForward":
2668
+ engine.commands.tryExecute("text.delete", { direction: "forward" });
2669
+ break;
2670
+ case "deleteWordForward":
2671
+ engine.commands.tryExecute("text.delete", { direction: "forward", type: "word" });
2672
+ break;
2673
+ case "historyUndo":
2674
+ engine.commands.tryExecute("history.undo", undefined);
2675
+ break;
2676
+ case "historyRedo":
2677
+ engine.commands.tryExecute("history.redo", undefined);
2678
+ break;
2679
+ default:
2680
+ break;
2681
+ }
2682
+ e.preventDefault();
2683
+ };
2684
+ const start = () => {
2685
+ composing = true;
2686
+ };
2687
+ const end = () => {
2688
+ composing = false;
2689
+ };
2690
+ document.addEventListener("beforeinput", onBeforeInput);
2691
+ document.addEventListener("compositionstart", start);
2692
+ document.addEventListener("compositionend", end);
2693
+ return () => {
2694
+ document.removeEventListener("beforeinput", onBeforeInput);
2695
+ document.removeEventListener("compositionstart", start);
2696
+ document.removeEventListener("compositionend", end);
2697
+ };
2698
+ }, [engine]);
2699
+ }
2700
+
2701
+ // src/components/corax-flow.tsx
2702
+ import { cn as cn9 } from "cn";
2703
+ import { jsxDEV as jsxDEV17 } from "react/jsx-dev-runtime";
2704
+ "use client";
2705
+ function CoraxFlow({
2706
+ children,
2707
+ className
2708
+ }) {
2709
+ const [count, forceUpdate] = useReducer((x) => x + 1, 0);
2710
+ const engine = useEngine();
2711
+ const renderer = useRenderer();
2712
+ useFlow();
2713
+ useTextInput(engine);
2714
+ useEffect9(() => {
2715
+ const disposer = engine.events.on("blocks:insert", () => {
2716
+ forceUpdate();
2717
+ });
2718
+ return () => disposer();
2719
+ }, [engine]);
2720
+ return /* @__PURE__ */ jsxDEV17("div", {
2721
+ id: "corax_flow_editor",
2722
+ className: "relative flex flex-col w-full max-w-200 h-full",
2723
+ children: [
2724
+ "CoraxFlow",
2725
+ /* @__PURE__ */ jsxDEV17("div", {
2726
+ id: "corax_flow_blocks_container",
2727
+ className: cn9("relative w-full h-full flex flex-col overflow-auto scrollbar-none pl-10 gap-1", className),
2728
+ children: [
2729
+ renderer.renderTree(count),
2730
+ children
2731
+ ]
2732
+ }, undefined, true, undefined, this)
2733
+ ]
2734
+ }, undefined, true, undefined, this);
2735
+ }
2736
+
2737
+ // src/components/index.ts
2738
+ "use client";
2739
+ // src/services/index.ts
2740
+ var CORAX_INDEXED_DB = "coraxdb";
2741
+ // src/index.ts
2742
+ export * from "@coorax/core";
2743
+ "use client";
2744
+ export {
2745
+ useUIContext,
2746
+ useSlice,
2747
+ useIsomorphicLayoutEffect,
2748
+ useEngine,
2749
+ rangeToOffsets,
2750
+ offsetsToRange,
2751
+ loadCompleteDocument,
2752
+ getFieldTypeAndTargetId,
2753
+ getBlockActionsProps,
2754
+ focusDomElement,
2755
+ focusDomBLockById,
2756
+ blockRectFromBlockId,
2757
+ UIPrimitivesRegistry,
2758
+ Toolbar,
2759
+ TextInspector,
2760
+ SlotsModule,
2761
+ SlotsComponentRegistry,
2762
+ PrimitivesComponentsRegistry,
2763
+ Overlays,
2764
+ GenericRegistry,
2765
+ FallbacksModule,
2766
+ FallbackComponentsRegistry,
2767
+ FLC,
2768
+ CoraxIcon,
2769
+ CoraxFlow,
2770
+ CoraxEngineProvider,
2771
+ CORAX_INDEXED_DB,
2772
+ BlockActions,
2773
+ AutoSaveModule
2774
+ };