@coorax/core 0.0.0-canary.0 → 0.0.0-canary.1

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 (129) hide show
  1. package/dist/base/classes/component.class.d.ts +23 -0
  2. package/dist/base/classes/container.class.d.ts +17 -0
  3. package/dist/base/classes/field.class.d.ts +15 -0
  4. package/dist/base/classes/tnode.class.d.ts +14 -0
  5. package/{src/base/index.ts → dist/base/index.d.ts} +0 -4
  6. package/dist/base/types/components/components.d.ts +13 -0
  7. package/dist/base/types/container/container.d.ts +27 -0
  8. package/dist/base/types/container/division.types.d.ts +3 -0
  9. package/{src/base/types/container/section.types.ts → dist/base/types/container/section.types.d.ts} +2 -2
  10. package/{src/base/types/container/ul-list.types.ts → dist/base/types/container/ul-list.types.d.ts} +2 -2
  11. package/dist/base/types/css.types.d.ts +23 -0
  12. package/dist/base/types/field/divider.types.d.ts +3 -0
  13. package/{src/base/types/field/field.ts → dist/base/types/field/field.d.ts} +19 -26
  14. package/{src/base/types/field/field.media.types.ts → dist/base/types/field/field.media.types.d.ts} +2 -3
  15. package/{src/base/types/field/field.text.types.ts → dist/base/types/field/field.text.types.d.ts} +4 -5
  16. package/{src/base/types/field/heading.types.ts → dist/base/types/field/heading.types.d.ts} +2 -2
  17. package/{src/base/types/field/paragraph.types.ts → dist/base/types/field/paragraph.types.d.ts} +2 -2
  18. package/dist/base/types/global.types.d.ts +24 -0
  19. package/{src/base/types/node/span.types.ts → dist/base/types/node/link.types.d.ts} +2 -2
  20. package/{src/base/types/node/node.ts → dist/base/types/node/node.d.ts} +13 -17
  21. package/{src/base/types/node/link.types.ts → dist/base/types/node/span.types.d.ts} +2 -2
  22. package/dist/base/types/tree/tree.d.ts +23 -0
  23. package/{src/engine/engine.ts → dist/engine/engine.d.ts} +20 -24
  24. package/dist/engine/engine.test.d.ts +1 -0
  25. package/{src/index.ts → dist/index.d.ts} +0 -1
  26. package/dist/index.js +2466 -0
  27. package/dist/modules/editor/editor.module.d.ts +44 -0
  28. package/dist/modules/focus/focus.module.d.ts +54 -0
  29. package/dist/modules/history/history.module.d.ts +27 -0
  30. package/dist/modules/hover/hover.module.d.ts +53 -0
  31. package/dist/modules/insertion/insertion.module.d.ts +54 -0
  32. package/dist/modules/modules-manager.d.ts +41 -0
  33. package/{src/modules/modules.types.ts → dist/modules/modules.types.d.ts} +25 -30
  34. package/dist/modules/selection/selection.module.d.ts +60 -0
  35. package/dist/modules/selection/selection.test.d.ts +1 -0
  36. package/dist/modules/text-editing/text-editing.constants.d.ts +2 -0
  37. package/dist/modules/text-editing/text-editing.module.d.ts +83 -0
  38. package/dist/modules/text-editing/text-editing.utils.d.ts +6 -0
  39. package/dist/services/commandsbus/commandsbus.d.ts +53 -0
  40. package/dist/services/commandsbus/commandsbus.test.d.ts +17 -0
  41. package/dist/services/document/document.d.ts +45 -0
  42. package/dist/services/eventbus/eventbus.d.ts +86 -0
  43. package/dist/services/eventbus/eventbus.test.d.ts +8 -0
  44. package/dist/services/eventbus/subscriber.d.ts +18 -0
  45. package/dist/services/mutations/mutations.d.ts +38 -0
  46. package/dist/services/mutations/mutations.errors.d.ts +6 -0
  47. package/dist/services/mutations/mutations.test.d.ts +1 -0
  48. package/dist/services/shortcuts/shortcuts.d.ts +4 -0
  49. package/dist/services/state/state.d.ts +20 -0
  50. package/dist/services/state/state.errors.d.ts +6 -0
  51. package/dist/services/tasks/tasks.service.d.ts +106 -0
  52. package/dist/services/tasks/tasks.service.test.d.ts +7 -0
  53. package/{src/services/text-marks/marks.types.ts → dist/services/text-marks/marks.types.d.ts} +20 -23
  54. package/dist/services/text-marks/text-marks.d.ts +45 -0
  55. package/dist/services/ui/default-styles.d.ts +3 -0
  56. package/dist/services/ui/ui.d.ts +22 -0
  57. package/dist/services/ui/ui.errors.d.ts +3 -0
  58. package/dist/services/ui/ui.types.d.ts +113 -0
  59. package/dist/styles.css +537 -0
  60. package/dist/utils/components.utils.d.ts +10 -0
  61. package/dist/utils/container.utils.d.ts +13 -0
  62. package/dist/utils/fields.utils.d.ts +19 -0
  63. package/dist/utils/global.utils.d.ts +47 -0
  64. package/dist/utils/modules.utils.d.ts +11 -0
  65. package/dist/utils/tnode.utils.d.ts +9 -0
  66. package/dist/utils/tree.utils.d.ts +11 -0
  67. package/package.json +19 -6
  68. package/styles.css +1 -3
  69. package/src/base/classes/component.class.ts +0 -68
  70. package/src/base/classes/container.class.ts +0 -57
  71. package/src/base/classes/field.class.ts +0 -42
  72. package/src/base/classes/tnode.class.ts +0 -38
  73. package/src/base/types/components/components.ts +0 -21
  74. package/src/base/types/container/container.ts +0 -37
  75. package/src/base/types/container/division.types.ts +0 -3
  76. package/src/base/types/css.types.ts +0 -33
  77. package/src/base/types/field/divider.types.ts +0 -3
  78. package/src/base/types/global.types.ts +0 -45
  79. package/src/base/types/tree/tree.ts +0 -33
  80. package/src/engine/engine.test.ts +0 -27
  81. package/src/modules/editor/editor.module.ts +0 -119
  82. package/src/modules/focus/focus.module.ts +0 -185
  83. package/src/modules/history/history.module.ts +0 -60
  84. package/src/modules/hover/hover.module.ts +0 -121
  85. package/src/modules/insertion/insertion.module.ts +0 -140
  86. package/src/modules/modules-manager.ts +0 -132
  87. package/src/modules/selection/selection.module.ts +0 -174
  88. package/src/modules/selection/selection.test.ts +0 -1
  89. package/src/modules/text-editing/text-editing.constants.ts +0 -6
  90. package/src/modules/text-editing/text-editing.module.ts +0 -377
  91. package/src/modules/text-editing/text-editing.utils.ts +0 -27
  92. package/src/services/commandsbus/commandsbus.test.ts +0 -312
  93. package/src/services/commandsbus/commandsbus.ts +0 -360
  94. package/src/services/document/document.ts +0 -139
  95. package/src/services/eventbus/eventbus.test.ts +0 -144
  96. package/src/services/eventbus/eventbus.ts +0 -162
  97. package/src/services/eventbus/subscriber.ts +0 -46
  98. package/src/services/mutations/mutations.errors.ts +0 -12
  99. package/src/services/mutations/mutations.test.ts +0 -177
  100. package/src/services/mutations/mutations.ts +0 -457
  101. package/src/services/shortcuts/shortcuts.ts +0 -3
  102. package/src/services/state/state.errors.ts +0 -12
  103. package/src/services/state/state.ts +0 -64
  104. package/src/services/tasks/tasks.service.test.ts +0 -193
  105. package/src/services/tasks/tasks.service.ts +0 -288
  106. package/src/services/text-marks/text-marks.ts +0 -244
  107. package/src/services/ui/default-styles.ts +0 -93
  108. package/src/services/ui/ui.errors.ts +0 -6
  109. package/src/services/ui/ui.ts +0 -148
  110. package/src/services/ui/ui.types.ts +0 -197
  111. package/src/utils/components.utils.ts +0 -26
  112. package/src/utils/container.utils.ts +0 -59
  113. package/src/utils/fields.utils.ts +0 -118
  114. package/src/utils/global.utils.ts +0 -128
  115. package/src/utils/modules.utils.ts +0 -110
  116. package/src/utils/tnode.utils.ts +0 -48
  117. package/src/utils/tree.utils.ts +0 -120
  118. package/tsconfig.json +0 -9
  119. /package/{src/engine/index.ts → dist/engine/index.d.ts} +0 -0
  120. /package/{src/modules/index.ts → dist/modules/index.d.ts} +0 -0
  121. /package/{src/services/commandsbus/index.ts → dist/services/commandsbus/index.d.ts} +0 -0
  122. /package/{src/services/document/index.ts → dist/services/document/index.d.ts} +0 -0
  123. /package/{src/services/eventbus/index.ts → dist/services/eventbus/index.d.ts} +0 -0
  124. /package/{src/services/mutations/index.ts → dist/services/mutations/index.d.ts} +0 -0
  125. /package/{src/services/state/index.ts → dist/services/state/index.d.ts} +0 -0
  126. /package/{src/services/tasks/index.ts → dist/services/tasks/index.d.ts} +0 -0
  127. /package/{src/services/text-marks/index.ts → dist/services/text-marks/index.d.ts} +0 -0
  128. /package/{src/services/ui/index.ts → dist/services/ui/index.d.ts} +0 -0
  129. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
package/dist/index.js ADDED
@@ -0,0 +1,2466 @@
1
+ // src/base/classes/component.class.ts
2
+ class ComponentClass {
3
+ id;
4
+ name;
5
+ tag;
6
+ type;
7
+ props;
8
+ variant = "component";
9
+ order;
10
+ instanceId;
11
+ count;
12
+ updatedAt;
13
+ createdAt;
14
+ constructor(component) {
15
+ this.id = component.id;
16
+ this.name = component.name;
17
+ this.tag = component.tag;
18
+ this.type = component.type;
19
+ this.variant = component.variant;
20
+ this.order = component.order;
21
+ this.props = component.props;
22
+ this.count = component.count;
23
+ this.updatedAt = component.updatedAt;
24
+ this.createdAt = component.createdAt;
25
+ this.instanceId = component.instanceId;
26
+ }
27
+ isInstance() {
28
+ return !!this.instanceId;
29
+ }
30
+ getChildren(_tree) {
31
+ return new Set;
32
+ }
33
+ appendChild(tree) {
34
+ return tree;
35
+ }
36
+ removeChild(tree) {
37
+ return tree;
38
+ }
39
+ getCurrentComponentObject() {
40
+ return {
41
+ id: this.id,
42
+ name: this.name,
43
+ tag: this.tag,
44
+ type: this.type,
45
+ variant: this.variant,
46
+ order: this.order,
47
+ props: this.props,
48
+ count: this.count,
49
+ instanceId: this.instanceId,
50
+ createdAt: this.createdAt,
51
+ updatedAt: this.updatedAt
52
+ };
53
+ }
54
+ }
55
+ // src/base/classes/container.class.ts
56
+ class ContainerClass {
57
+ id;
58
+ name;
59
+ tag;
60
+ type;
61
+ props;
62
+ variant = "container";
63
+ order;
64
+ constructor(container) {
65
+ this.id = container.id;
66
+ this.name = container.name;
67
+ this.tag = container.tag;
68
+ this.type = container.type;
69
+ this.variant = container.variant;
70
+ this.order = container.order;
71
+ this.props = container.props;
72
+ }
73
+ getChildren(_tree) {
74
+ return new Set;
75
+ }
76
+ appendChild(tree) {
77
+ return tree;
78
+ }
79
+ removeChild(tree) {
80
+ return tree;
81
+ }
82
+ getCurrentContainerObject() {
83
+ return {
84
+ id: this.id,
85
+ name: this.name,
86
+ tag: this.tag,
87
+ type: this.type,
88
+ variant: this.variant,
89
+ order: this.order,
90
+ props: this.props
91
+ };
92
+ }
93
+ }
94
+ // src/base/classes/field.class.ts
95
+ class FieldClass {
96
+ id;
97
+ name;
98
+ tag;
99
+ type;
100
+ variant = "field";
101
+ containerId;
102
+ props;
103
+ constructor(field) {
104
+ this.id = field.id;
105
+ this.name = field.name;
106
+ this.tag = field.tag;
107
+ this.containerId = field.containerId;
108
+ this.props = field.props;
109
+ this.variant = field.variant;
110
+ this.type = field.type;
111
+ }
112
+ isContainerized() {
113
+ return !!this.containerId;
114
+ }
115
+ getCurrentFieldObject() {
116
+ return {
117
+ id: this.id,
118
+ name: this.name,
119
+ tag: this.tag,
120
+ containerId: this.containerId,
121
+ props: this.props,
122
+ variant: this.variant,
123
+ type: this.type
124
+ };
125
+ }
126
+ }
127
+ // src/base/classes/tnode.class.ts
128
+ class TNodeClass {
129
+ id;
130
+ tag;
131
+ type;
132
+ name;
133
+ variant;
134
+ fieldId;
135
+ props;
136
+ constructor(tnode) {
137
+ this.id = tnode.id;
138
+ this.name = tnode.name;
139
+ this.variant = tnode.variant;
140
+ this.tag = tnode.tag;
141
+ this.props = tnode.props;
142
+ this.type = tnode.type;
143
+ this.fieldId = tnode.fieldId;
144
+ }
145
+ getCurrentNodeObject() {
146
+ return {
147
+ id: this.id,
148
+ name: this.name,
149
+ variant: this.variant,
150
+ tag: this.tag,
151
+ type: this.type,
152
+ props: this.props,
153
+ fieldId: this.fieldId
154
+ };
155
+ }
156
+ }
157
+ // src/utils/global.utils.ts
158
+ function generateRandomId() {
159
+ return `${Date.now().toString(12)}:${crypto.randomUUID()}`;
160
+ }
161
+ function generateId(prefix) {
162
+ return `${prefix}:${crypto.randomUUID()}`;
163
+ }
164
+ function generateFieldId() {
165
+ return generateId("field");
166
+ }
167
+ function generateTNodeId() {
168
+ return generateId("tnode");
169
+ }
170
+ function generateContainerId() {
171
+ return generateId("container");
172
+ }
173
+ function generateComponentId() {
174
+ return generateId("component");
175
+ }
176
+ function generateTreeId() {
177
+ return generateId("tree");
178
+ }
179
+ function generateSubscriberId() {
180
+ return generateId("subscriber");
181
+ }
182
+ function Capitalize(value) {
183
+ return `${value[0].toUpperCase()}${value.slice(1)}`;
184
+ }
185
+ function ObjectEntries(obj) {
186
+ return Object.entries(obj);
187
+ }
188
+
189
+ class CustomObject {
190
+ obj;
191
+ constructor(obj) {
192
+ this.obj = obj;
193
+ }
194
+ filter(predicate) {
195
+ const entries = Object.entries(this.obj);
196
+ const filtered = entries.filter(([key, value]) => predicate(value, key));
197
+ return new CustomObject(Object.fromEntries(filtered));
198
+ }
199
+ pick(...keys) {
200
+ const picked = keys.reduce((acc, key) => {
201
+ acc[key] = this.obj[key];
202
+ return acc;
203
+ }, {});
204
+ return new CustomObject(picked);
205
+ }
206
+ get size() {
207
+ return Object.keys(this.obj).length;
208
+ }
209
+ has(key) {
210
+ return key in this.obj;
211
+ }
212
+ get keys() {
213
+ return Object.keys(this.obj);
214
+ }
215
+ get(key) {
216
+ return this.obj[key];
217
+ }
218
+ baseObject() {
219
+ return this.obj;
220
+ }
221
+ }
222
+ var isPlainObject = (v) => {
223
+ if (typeof v !== "object" || v === null)
224
+ return false;
225
+ const proto = Object.getPrototypeOf(v);
226
+ return proto === Object.prototype || proto === null;
227
+ };
228
+ function areObjectsTheSame(objA, objB) {
229
+ for (const key in objA) {
230
+ if (Object.prototype.hasOwnProperty.call(objA, key)) {
231
+ if (objA[key] !== objB[key]) {
232
+ return false;
233
+ }
234
+ }
235
+ }
236
+ return true;
237
+ }
238
+ var UTILS = {
239
+ generateRandomId,
240
+ generateId,
241
+ generateContainerId,
242
+ generateFieldId,
243
+ generateTreeId,
244
+ generateSubscriberId,
245
+ generateComponentId,
246
+ Capitalize,
247
+ generateTNodeId,
248
+ ObjectEntries,
249
+ isPlainObject
250
+ };
251
+
252
+ // src/utils/components.utils.ts
253
+ function NewComponent(container3, defaultValue) {
254
+ const now = Date.now();
255
+ return new ComponentClass({
256
+ ...container3,
257
+ id: UTILS.generateComponentId(),
258
+ variant: "component",
259
+ count: defaultValue?.count ?? 0,
260
+ createdAt: defaultValue?.createdAt ?? now,
261
+ updatedAt: defaultValue?.updatedAt ?? now
262
+ });
263
+ }
264
+ function DeserializeComponent(component2) {
265
+ return new ComponentClass(component2);
266
+ }
267
+ var ComponentsUtils = { NewComponent, DeserializeComponent };
268
+ // src/utils/container.utils.ts
269
+ function NewUlListContainer(defaultValue) {
270
+ return new ContainerClass({
271
+ id: UTILS.generateContainerId(),
272
+ name: "Ul list container",
273
+ type: "list",
274
+ tag: "ul",
275
+ variant: "container",
276
+ props: {},
277
+ order: new Set,
278
+ ...defaultValue
279
+ });
280
+ }
281
+ function NewSectionContainer(defaultValue) {
282
+ return new ContainerClass({
283
+ id: UTILS.generateContainerId(),
284
+ name: "Section container",
285
+ type: "section",
286
+ tag: "section",
287
+ variant: "container",
288
+ props: {},
289
+ order: new Set,
290
+ ...defaultValue
291
+ });
292
+ }
293
+ function NewContainer(type, defaultValue) {
294
+ switch (type) {
295
+ case "section":
296
+ return NewSectionContainer(defaultValue);
297
+ default:
298
+ return NewUlListContainer(defaultValue);
299
+ }
300
+ }
301
+ function DeserializeContainer(container3) {
302
+ return new ContainerClass(container3);
303
+ }
304
+ var ContainersUtils = {
305
+ NewContainer,
306
+ DeserializeContainer,
307
+ NewUlListContainer,
308
+ NewSectionContainer
309
+ };
310
+ // src/utils/fields.utils.ts
311
+ function isEditableField(block) {
312
+ return block.variant === "field" && (block.type === "heading" || block.type === "text");
313
+ }
314
+ function NewTextField(defaultValue) {
315
+ return new FieldClass({
316
+ id: UTILS.generateFieldId(),
317
+ name: "Text field",
318
+ type: "text",
319
+ tag: "p",
320
+ variant: "field",
321
+ props: {
322
+ children: { text: "", marks: [] },
323
+ "data-text-path": "props.children",
324
+ contentEditable: false
325
+ },
326
+ ...defaultValue
327
+ });
328
+ }
329
+ function NewHeadingField(defaultValue) {
330
+ return new FieldClass({
331
+ id: UTILS.generateFieldId(),
332
+ name: "Heading field",
333
+ type: "heading",
334
+ tag: "h1",
335
+ variant: "field",
336
+ props: {
337
+ children: { text: "", marks: [] },
338
+ "data-text-path": "props.children",
339
+ contentEditable: false
340
+ },
341
+ ...defaultValue
342
+ });
343
+ }
344
+ function NewImageField(defaultValue) {
345
+ return new FieldClass({
346
+ id: UTILS.generateFieldId(),
347
+ name: "Image field",
348
+ type: "image",
349
+ tag: "img",
350
+ variant: "field",
351
+ props: { src: "", alt: "image" },
352
+ ...defaultValue
353
+ });
354
+ }
355
+ function NewVideoField(defaultValue) {
356
+ return new FieldClass({
357
+ id: UTILS.generateFieldId(),
358
+ name: "Video field",
359
+ type: "video",
360
+ tag: "video",
361
+ variant: "field",
362
+ props: { src: "", alt: "video" },
363
+ ...defaultValue
364
+ });
365
+ }
366
+ function NewDividerField(defaultValue) {
367
+ return new FieldClass({
368
+ id: UTILS.generateFieldId(),
369
+ name: "Video field",
370
+ type: "divider",
371
+ tag: "hr",
372
+ variant: "field",
373
+ props: {},
374
+ ...defaultValue
375
+ });
376
+ }
377
+ function NewField(type, defaultValue) {
378
+ switch (type) {
379
+ case "text":
380
+ return NewTextField(defaultValue);
381
+ case "heading":
382
+ return NewHeadingField(defaultValue);
383
+ case "image":
384
+ return NewImageField(defaultValue);
385
+ case "video":
386
+ return NewVideoField(defaultValue);
387
+ case "divider":
388
+ return NewDividerField(defaultValue);
389
+ default:
390
+ return NewTextField(defaultValue);
391
+ }
392
+ }
393
+ function DeserializeField(field3) {
394
+ return new FieldClass(field3);
395
+ }
396
+ var FieldsUtils = {
397
+ NewField,
398
+ DeserializeField,
399
+ NewTextField,
400
+ NewHeadingField,
401
+ NewImageField,
402
+ NewDividerField
403
+ };
404
+ // src/utils/modules.utils.ts
405
+ function createScopedTCtx(engine, moduleName) {
406
+ const disposers = [];
407
+ function trackFn(disposer) {
408
+ let done = false;
409
+ const safe = () => {
410
+ if (!done) {
411
+ done = true;
412
+ disposer();
413
+ }
414
+ };
415
+ disposers.push(safe);
416
+ return disposer;
417
+ }
418
+ const ctx = {
419
+ events: {
420
+ on: (ev, handler) => trackFn(engine.events.on(ev, handler)),
421
+ emit: (ev, props) => engine.events.emit(ev, props),
422
+ batch: (evs) => engine.events.batch(evs)
423
+ },
424
+ commands: {
425
+ register: (cmd, handler) => trackFn(engine.commands.register(cmd, handler)),
426
+ registerAsync: (cmd, handler) => trackFn(engine.commands.registerAsync(cmd, handler)),
427
+ tryExecute: (cmd, payload) => engine.commands.tryExecute(cmd, payload),
428
+ tryExecuteAsync: (cmd, payload) => engine.commands.tryExecuteAsync(cmd, payload),
429
+ execute: (cmd, payload) => engine.commands.execute(cmd, payload),
430
+ executeAsync: (cmd, payload) => engine.commands.executeAsync(cmd, payload),
431
+ before: (cmd, next) => trackFn(engine.commands.before(cmd, next)),
432
+ beforeAsync: (cmd, next) => trackFn(engine.commands.beforeAsync(cmd, next)),
433
+ after: (cmd, callback) => trackFn(engine.commands.after(cmd, callback)),
434
+ afterAsync: (cmd, callback) => trackFn(engine.commands.afterAsync(cmd, callback)),
435
+ has: (cmd) => engine.commands.has(cmd)
436
+ },
437
+ state: {
438
+ defineSlice: (name2, initial) => {
439
+ return trackFn(engine.state.defineSlice(name2, initial));
440
+ },
441
+ get: (name2) => engine.state.get(name2),
442
+ set: (name2, next) => {
443
+ engine.state.set(name2, next);
444
+ },
445
+ subscribe: (name2, fn) => trackFn(engine.state.subscribe(name2, fn))
446
+ },
447
+ document: engine.document,
448
+ mutations: engine.mutations,
449
+ shortcuts: engine.shortcuts,
450
+ text: {
451
+ registerMark: (type, behavior) => trackFn(engine.text.registerMark(type, behavior)),
452
+ toggleMark: (c, o) => engine.text.toggleMark(c, o),
453
+ insertText: (c, at, t, o) => engine.text.insertText(c, at, t, o),
454
+ deleteRange: (c, s, e) => engine.text.deleteRange(c, s, e),
455
+ replaceRange: (c, s, e, t, o) => engine.text.replaceRange(c, s, e, t, o),
456
+ isInclusive: (t) => engine.text.isInclusive(t)
457
+ },
458
+ ui: {
459
+ contribute: (slotName, c) => trackFn(engine.ui.contribute(slotName, {
460
+ ...c,
461
+ id: `${moduleName}.${c.id}`,
462
+ when: c.when
463
+ })),
464
+ subscribe: (slotName, fn) => trackFn(engine.ui.subscribe(slotName, fn)),
465
+ getSlots: (slotName) => engine.ui.getSlots(slotName),
466
+ registerStyle: (styleName, css2) => trackFn(engine.ui.registerStyle(styleName, css2)),
467
+ patchStyle: (styleName, patch) => trackFn(engine.ui.patchStyle(styleName, patch)),
468
+ getStyle: (styleName) => engine.ui.getStyle(styleName),
469
+ interceptPayload: (id, fn) => trackFn(engine.ui.interceptPayload(id, fn)),
470
+ runContribution: (c, ui) => engine.ui.runContribution(c, ui)
471
+ },
472
+ tasks: {
473
+ schedule: (name2, delay, fn) => trackFn(engine.tasks.schedule(name2, delay, fn)),
474
+ cancel: (name2) => engine.tasks.cancel(name2),
475
+ isPending: (name2) => engine.tasks.isPending(name2),
476
+ isRunning: (name2) => engine.tasks.isRunning(name2),
477
+ getStatus: (name2) => engine.tasks.getStatus(name2),
478
+ getState: (name2) => engine.tasks.getState(name2),
479
+ subscribe: (name2, fn) => trackFn(engine.tasks.subscribe(name2, fn)),
480
+ flush: (name2) => engine.tasks.flush(name2),
481
+ cancelAll: () => engine.tasks.cancelAll(),
482
+ dispose: () => engine.tasks.dispose()
483
+ }
484
+ };
485
+ return {
486
+ ctx,
487
+ dispose: () => disposers.splice(0).reverse().forEach((dp) => dp())
488
+ };
489
+ }
490
+ var ModuleUtils = { createScopedTCtx };
491
+ // src/utils/tnode.utils.ts
492
+ function NewLinkTNode(defaultValue) {
493
+ return new TNodeClass({
494
+ id: UTILS.generateTNodeId(),
495
+ name: "Link tnode",
496
+ type: "link",
497
+ tag: "a",
498
+ variant: "tnode",
499
+ props: { style: {}, text: "" },
500
+ ...defaultValue
501
+ });
502
+ }
503
+ function NewSpanTNode(defaultValue) {
504
+ return new TNodeClass({
505
+ id: UTILS.generateTNodeId(),
506
+ name: "Sub-field tnode",
507
+ type: "sub-field",
508
+ tag: "span",
509
+ variant: "tnode",
510
+ props: { style: {}, text: "" },
511
+ ...defaultValue
512
+ });
513
+ }
514
+ function NewTNode(type, defaultValue) {
515
+ switch (type) {
516
+ case "link":
517
+ return NewLinkTNode(defaultValue);
518
+ default:
519
+ return NewSpanTNode(defaultValue);
520
+ }
521
+ }
522
+ function DeserializeTNode(tnode2) {
523
+ return new TNodeClass(tnode2);
524
+ }
525
+ var TNodesUtils = { NewTNode, DeserializeTNode };
526
+ // src/utils/tree.utils.ts
527
+ function SerializeTree(tree2) {
528
+ const newFields = Array.from(tree2.fields.entries()).reduce((prev, [id, currentField]) => {
529
+ prev[id] = currentField.getCurrentFieldObject();
530
+ return prev;
531
+ }, {});
532
+ const newContainers = Array.from(tree2.containers.entries()).reduce((prev, [id, currentContainer]) => {
533
+ prev[id] = currentContainer.getCurrentContainerObject();
534
+ return prev;
535
+ }, {});
536
+ const newComponents = Array.from(tree2.components.entries()).reduce((prev, [id, currentComponent]) => {
537
+ prev[id] = currentComponent.getCurrentComponentObject();
538
+ return prev;
539
+ }, {});
540
+ return {
541
+ id: tree2.id,
542
+ version: tree2.version,
543
+ order: tree2.order,
544
+ fields: newFields,
545
+ containers: newContainers,
546
+ components: newComponents
547
+ };
548
+ }
549
+ function DeserializeTree(tree2) {
550
+ const newFields = UTILS.ObjectEntries(tree2.fields).reduce((prev, [id, currentField]) => {
551
+ prev.set(id, FieldsUtils.DeserializeField(currentField));
552
+ return prev;
553
+ }, {});
554
+ const newContainers = UTILS.ObjectEntries(tree2.containers).reduce((prev, [id, currentContainer]) => {
555
+ prev.set(id, ContainersUtils.DeserializeContainer(currentContainer));
556
+ return prev;
557
+ }, {});
558
+ const newComponents = UTILS.ObjectEntries(tree2.components).reduce((prev, [id, currentComponent]) => {
559
+ prev.set(id, ComponentsUtils.DeserializeComponent(currentComponent));
560
+ return prev;
561
+ }, {});
562
+ return {
563
+ id: tree2.id,
564
+ version: tree2.version,
565
+ order: tree2.order,
566
+ fields: newFields,
567
+ containers: newContainers,
568
+ components: newComponents
569
+ };
570
+ }
571
+ function GetDefaultTree() {
572
+ return {
573
+ id: "root",
574
+ version: "0.0.0",
575
+ order: new Set,
576
+ fields: new Map,
577
+ containers: new Map,
578
+ components: new Map
579
+ };
580
+ }
581
+ var KINDS = ["fields", "containers", "components"];
582
+ function coraxTreeDiffing(prev, next) {
583
+ const added = new Set, removed = new Set, changed = new Set;
584
+ for (const kind of KINDS) {
585
+ const a = prev[kind];
586
+ const b = next[kind];
587
+ if (a === b)
588
+ continue;
589
+ const bKeys = b.keys();
590
+ for (const id of bKeys) {
591
+ if (!a.has(id))
592
+ added.add(id);
593
+ else if (a.get(id) !== b.get(id))
594
+ changed.add(id);
595
+ }
596
+ const aKeys = a.keys();
597
+ for (const id of aKeys)
598
+ if (!b.has(id))
599
+ removed.add(id);
600
+ }
601
+ return { added, removed, changed, orderChanged: prev.order !== next.order };
602
+ }
603
+ // src/modules/modules-manager.ts
604
+ class ModuleManager {
605
+ registry = new Map;
606
+ active = new Map;
607
+ engine;
608
+ constructor(engine) {
609
+ this.engine = engine;
610
+ }
611
+ register(modules2) {
612
+ for (const module of modules2) {
613
+ if (this.registry.has(module.name)) {
614
+ throw new Error(`Module "${module.name}" is already registered`);
615
+ }
616
+ this.registry.set(module.name, module);
617
+ }
618
+ }
619
+ isEnabled(name2) {
620
+ return this.active.has(name2);
621
+ }
622
+ enable(name2) {
623
+ this.enableRec(name2, []);
624
+ }
625
+ enableAll() {
626
+ for (const name2 of this.registry.keys())
627
+ this.enable(name2);
628
+ }
629
+ disabledAll() {
630
+ for (const name2 of this.registry.keys())
631
+ this.disable(name2, { cascade: true });
632
+ }
633
+ disable(name2, opts = {}) {
634
+ const cleanup = this.active.get(name2);
635
+ if (!cleanup)
636
+ return;
637
+ const dependents = this.activeDependentsOf(name2);
638
+ if (dependents.length > 0) {
639
+ if (!opts.cascade) {
640
+ throw new Error(`Cannot disable "${name2}": required by ${dependents.join(", ")}`);
641
+ }
642
+ dependents.forEach((d) => this.disable(d, { cascade: true }));
643
+ }
644
+ this.active.delete(name2);
645
+ cleanup();
646
+ }
647
+ unregister(name2) {
648
+ this.disable(name2, { cascade: true });
649
+ this.registry.delete(name2);
650
+ }
651
+ enableRec(name2, stack) {
652
+ if (this.active.has(name2))
653
+ return;
654
+ if (stack.includes(name2)) {
655
+ throw new Error(`Circular dependency: ${[...stack, name2].join(" -> ")}`);
656
+ }
657
+ const module = this.registry.get(name2);
658
+ if (!module) {
659
+ const needer = stack[stack.length - 1];
660
+ throw new Error(`Module "${name2}" is not registered` + (needer ? ` (required by "${needer}")` : ""));
661
+ }
662
+ for (const dep of module.requires ?? []) {
663
+ this.enableRec(dep, [...stack, name2]);
664
+ }
665
+ this.activate(module);
666
+ }
667
+ activate(module) {
668
+ const { ctx, dispose } = ModuleUtils.createScopedTCtx(this.engine, module.name);
669
+ try {
670
+ const custom = module.install(ctx);
671
+ this.active.set(module.name, () => {
672
+ try {
673
+ if (!custom)
674
+ return;
675
+ custom?.();
676
+ } finally {
677
+ dispose();
678
+ }
679
+ });
680
+ } catch (error) {
681
+ dispose();
682
+ throw error;
683
+ }
684
+ }
685
+ activeDependentsOf(name2) {
686
+ return [...this.active.keys()].filter((n) => this.registry.get(n)?.requires.includes(name2));
687
+ }
688
+ }
689
+
690
+ // src/services/commandsbus/commandsbus.ts
691
+ class CmdNotFoundError extends Error {
692
+ constructor(cmd) {
693
+ super(`Command ${cmd} is not registered (module disabled?)`);
694
+ }
695
+ }
696
+
697
+ class CommandsBusService {
698
+ handlers = new Map;
699
+ asyncHandlers = new Map;
700
+ afterHooks = new Map;
701
+ asyncAfterHooks = new Map;
702
+ nextFunctions = new Map;
703
+ asyncNextFunctions = new Map;
704
+ tryExecute(cmd, payload) {
705
+ try {
706
+ return this.execute(cmd, payload);
707
+ } catch (er) {
708
+ if (!(er instanceof CmdNotFoundError))
709
+ throw er;
710
+ console.error(er.message);
711
+ return null;
712
+ }
713
+ }
714
+ async tryExecuteAsync(cmd, payload) {
715
+ try {
716
+ return await this.executeAsync(cmd, payload);
717
+ } catch (er) {
718
+ if (!(er instanceof CmdNotFoundError))
719
+ throw er;
720
+ console.error(er.message);
721
+ return null;
722
+ }
723
+ }
724
+ execute(cmd, payload) {
725
+ const handler = this.handlers.get(cmd);
726
+ if (!handler) {
727
+ if (this.asyncHandlers.has(cmd)) {
728
+ throw new Error(`Command "${String(cmd)}" is asynchronous, use executeAsync instead`);
729
+ }
730
+ throw new CmdNotFoundError(cmd);
731
+ }
732
+ if (this.asyncNextFunctions.has(cmd) || this.asyncAfterHooks.has(cmd)) {
733
+ throw new Error(`Command "${String(cmd)}" has asynchronous hooks, use executeAsync instead`);
734
+ }
735
+ const nextFunctions = this.nextFunctions.get(cmd);
736
+ let transformedPayload = payload;
737
+ if (nextFunctions) {
738
+ for (const nextFn of nextFunctions) {
739
+ const result2 = nextFn(transformedPayload);
740
+ if (result2 === null) {
741
+ return null;
742
+ }
743
+ transformedPayload = result2;
744
+ }
745
+ }
746
+ const result = handler(transformedPayload);
747
+ const afterHooks = this.afterHooks.get(cmd);
748
+ if (afterHooks) {
749
+ for (const hook of afterHooks) {
750
+ hook(transformedPayload, result);
751
+ }
752
+ }
753
+ return result;
754
+ }
755
+ async executeAsync(cmd, payload) {
756
+ const asyncHandler = this.asyncHandlers.get(cmd);
757
+ const syncHandler = this.handlers.get(cmd);
758
+ const handler = asyncHandler ?? syncHandler;
759
+ if (!handler) {
760
+ throw new CmdNotFoundError(cmd);
761
+ }
762
+ const nextFunctions = this.nextFunctions.get(cmd);
763
+ let transformedPayload = payload;
764
+ if (nextFunctions) {
765
+ for (const nextFn of nextFunctions) {
766
+ const result2 = nextFn(transformedPayload);
767
+ if (result2 === null) {
768
+ return null;
769
+ }
770
+ transformedPayload = result2;
771
+ }
772
+ }
773
+ const asyncNextFunctions = this.asyncNextFunctions.get(cmd);
774
+ if (asyncNextFunctions) {
775
+ for (const nextFn of asyncNextFunctions) {
776
+ const result2 = await nextFn(transformedPayload);
777
+ if (result2 === null) {
778
+ return null;
779
+ }
780
+ transformedPayload = result2;
781
+ }
782
+ }
783
+ const result = await handler(transformedPayload);
784
+ const afterHooks = this.afterHooks.get(cmd);
785
+ if (afterHooks) {
786
+ for (const hook of afterHooks) {
787
+ hook(transformedPayload, result);
788
+ }
789
+ }
790
+ const asyncAfterHooks = this.asyncAfterHooks.get(cmd);
791
+ if (asyncAfterHooks) {
792
+ for (const hook of asyncAfterHooks) {
793
+ await hook(transformedPayload, result);
794
+ }
795
+ }
796
+ return result;
797
+ }
798
+ register(cmd, handler) {
799
+ if (this.handlers.has(cmd) || this.asyncHandlers.has(cmd)) {
800
+ throw new Error(`Command ${cmd} already registered`);
801
+ }
802
+ this.handlers.set(cmd, handler);
803
+ return () => {
804
+ if (this.handlers.get(cmd) === handler)
805
+ this.handlers.delete(cmd);
806
+ };
807
+ }
808
+ registerAsync(cmd, handler) {
809
+ if (this.handlers.has(cmd) || this.asyncHandlers.has(cmd)) {
810
+ throw new Error(`Command ${cmd} already registered`);
811
+ }
812
+ this.asyncHandlers.set(cmd, handler);
813
+ return () => {
814
+ if (this.asyncHandlers.get(cmd) === handler)
815
+ this.asyncHandlers.delete(cmd);
816
+ };
817
+ }
818
+ before(cmd, next) {
819
+ const nextFunctions = this.nextFunctions.get(cmd) ?? [];
820
+ nextFunctions.push(next);
821
+ this.nextFunctions.set(cmd, nextFunctions);
822
+ return () => {
823
+ const currentNextFunctions = this.nextFunctions.get(cmd);
824
+ if (currentNextFunctions) {
825
+ const index = currentNextFunctions.indexOf(next);
826
+ if (index !== -1) {
827
+ currentNextFunctions.splice(index, 1);
828
+ }
829
+ if (currentNextFunctions.length === 0) {
830
+ this.nextFunctions.delete(cmd);
831
+ }
832
+ }
833
+ };
834
+ }
835
+ beforeAsync(cmd, next) {
836
+ const asyncNextFunctions = this.asyncNextFunctions.get(cmd) ?? [];
837
+ asyncNextFunctions.push(next);
838
+ this.asyncNextFunctions.set(cmd, asyncNextFunctions);
839
+ return () => {
840
+ const currentAsyncNextFunctions = this.asyncNextFunctions.get(cmd);
841
+ if (currentAsyncNextFunctions) {
842
+ const index = currentAsyncNextFunctions.indexOf(next);
843
+ if (index !== -1) {
844
+ currentAsyncNextFunctions.splice(index, 1);
845
+ }
846
+ if (currentAsyncNextFunctions.length === 0) {
847
+ this.asyncNextFunctions.delete(cmd);
848
+ }
849
+ }
850
+ };
851
+ }
852
+ after(cmd, callback) {
853
+ const hooks = this.afterHooks.get(cmd) ?? [];
854
+ hooks.push(callback);
855
+ this.afterHooks.set(cmd, hooks);
856
+ return () => {
857
+ const currentHooks = this.afterHooks.get(cmd);
858
+ if (!currentHooks)
859
+ return;
860
+ const index = currentHooks.indexOf(callback);
861
+ if (index !== -1) {
862
+ currentHooks.splice(index, 1);
863
+ }
864
+ if (currentHooks.length === 0) {
865
+ this.afterHooks.delete(cmd);
866
+ }
867
+ };
868
+ }
869
+ afterAsync(cmd, callback) {
870
+ const hooks = this.asyncAfterHooks.get(cmd) ?? [];
871
+ hooks.push(callback);
872
+ this.asyncAfterHooks.set(cmd, hooks);
873
+ return () => {
874
+ const currentHooks = this.asyncAfterHooks.get(cmd);
875
+ if (!currentHooks)
876
+ return;
877
+ const index = currentHooks.indexOf(callback);
878
+ if (index !== -1) {
879
+ currentHooks.splice(index, 1);
880
+ }
881
+ if (currentHooks.length === 0) {
882
+ this.asyncAfterHooks.delete(cmd);
883
+ }
884
+ };
885
+ }
886
+ has(cmd) {
887
+ return this.handlers.has(cmd) || this.asyncHandlers.has(cmd);
888
+ }
889
+ }
890
+
891
+ // src/services/document/document.ts
892
+ class DocumentService {
893
+ state;
894
+ events;
895
+ blockListeners = new Map;
896
+ constructor(state, events) {
897
+ this.state = state;
898
+ this.events = events;
899
+ this.state.defineSlice("document", GetDefaultTree());
900
+ }
901
+ subscribeBlock(id, fn) {
902
+ const set = this.blockListeners.get(id) ?? new Set;
903
+ set.add(fn);
904
+ this.blockListeners.set(id, set);
905
+ return () => {
906
+ set.delete(fn);
907
+ if (!set.size)
908
+ this.blockListeners.delete(id);
909
+ };
910
+ }
911
+ bumpDocumentVersion(version) {
912
+ const parts = version.split(".").map((n) => parseInt(n, 10));
913
+ if (parts.length !== 3 || parts.some((n) => isNaN(n))) {
914
+ throw new Error(`Invalid document version format: ${version}`);
915
+ }
916
+ let [major, minor, patch] = parts;
917
+ patch++;
918
+ if (patch >= 100) {
919
+ patch = 0;
920
+ minor++;
921
+ }
922
+ if (minor >= 100) {
923
+ minor = 0;
924
+ major++;
925
+ }
926
+ const newVersion = `${major}.${minor}.${patch}`;
927
+ return newVersion;
928
+ }
929
+ get() {
930
+ return this.state.get("document");
931
+ }
932
+ apply(predicate, { shouldEmitEvent, origin } = {
933
+ shouldEmitEvent: true,
934
+ origin: "user"
935
+ }) {
936
+ const prev = this.get();
937
+ const next = predicate(prev);
938
+ if (next === prev)
939
+ return;
940
+ const diff = coraxTreeDiffing(prev, next);
941
+ if (!shouldEmitEvent) {
942
+ this.state.set("document", next);
943
+ for (const id of [...diff.changed, ...diff.added, ...diff.removed]) {
944
+ this.blockListeners.get(id)?.forEach((fn) => fn());
945
+ }
946
+ } else {
947
+ const versionnedTree = { ...next, version: this.bumpDocumentVersion(next.version) };
948
+ this.state.set("document", versionnedTree);
949
+ for (const id of [...diff.changed, ...diff.added, ...diff.removed]) {
950
+ this.blockListeners.get(id)?.forEach((fn) => fn());
951
+ }
952
+ this.events.emit("document:changed", {
953
+ prev,
954
+ next: versionnedTree,
955
+ origin: origin ?? "user",
956
+ diff
957
+ });
958
+ }
959
+ }
960
+ getBlock(id) {
961
+ const t = this.get();
962
+ return t.fields.get(id) ?? t.containers.get(id) ?? t.components.get(id);
963
+ }
964
+ has(id) {
965
+ return this.getBlock(id) !== undefined;
966
+ }
967
+ }
968
+
969
+ // src/services/eventbus/subscriber.ts
970
+ class Subscriber {
971
+ target;
972
+ event;
973
+ value = {};
974
+ constructor(target, event) {
975
+ this.target = target;
976
+ this.event = event;
977
+ }
978
+ with(props) {
979
+ const { event = "", ...restProps } = props;
980
+ return Object.assign(Object.create(Object.getPrototypeOf(this)), this, {
981
+ ...event.trim() ? { event } : null,
982
+ ..."value" in restProps ? restProps : { value: restProps }
983
+ });
984
+ }
985
+ }
986
+
987
+ // src/services/eventbus/eventbus.ts
988
+ class EventBusService {
989
+ handlers = new Map;
990
+ isRerenderEventActive = false;
991
+ cleanUpCallback(ev, blogHandler) {
992
+ const newHandlers = (this.handlers.get(ev) ?? []).filter((handler) => handler.id !== blogHandler.id);
993
+ this.handlers.set(ev, newHandlers);
994
+ }
995
+ on(ev, callback) {
996
+ const prevHandlers = this.handlers.get(ev) ?? [];
997
+ const newId = UTILS.generateSubscriberId();
998
+ const newTEvent = {
999
+ id: newId,
1000
+ callback,
1001
+ subscriber: new Subscriber(newId, ev)
1002
+ };
1003
+ this.handlers.set(ev, [...prevHandlers, newTEvent]);
1004
+ return this.cleanUpCallback.bind(this, ev, newTEvent);
1005
+ }
1006
+ async emit(ev, props, toAwaited = true) {
1007
+ if (ev === "re-render") {
1008
+ this.isRerenderEventActive = true;
1009
+ }
1010
+ const eventHandlers = this.handlers.get(ev) ?? [];
1011
+ const eventsPromises = Promise.all(eventHandlers.map((handler) => {
1012
+ const subscriber = props ? handler.subscriber.with(props) : handler.subscriber;
1013
+ return handler.callback(subscriber);
1014
+ }));
1015
+ if (toAwaited) {
1016
+ await eventsPromises.catch((err) => console.error("Error in event handlers:", err));
1017
+ } else {
1018
+ eventsPromises.then(() => console.log("All handlers resolved")).catch((err) => console.error("Error in event handlers:", err));
1019
+ }
1020
+ if (this.isRerenderEventActive) {
1021
+ this.isRerenderEventActive = false;
1022
+ }
1023
+ if (ev !== "changes") {
1024
+ await this.emit("changes", { ...props, event: ev });
1025
+ }
1026
+ }
1027
+ batch(evs) {
1028
+ return evs.map(([ev, props]) => this.emit(ev, props));
1029
+ }
1030
+ }
1031
+
1032
+ // src/services/mutations/mutations.errors.ts
1033
+ class MutationError extends Error {
1034
+ constructor(message) {
1035
+ super(`MutationError: ${message}`);
1036
+ this.name = "MutationError";
1037
+ }
1038
+ }
1039
+
1040
+ class MutationPrototypeError extends MutationError {
1041
+ constructor(name2) {
1042
+ super(`Trying to mutate '${name2}' who has lost his prototype`);
1043
+ }
1044
+ }
1045
+
1046
+ // src/services/mutations/mutations.ts
1047
+ var FORBIDDEN = new Set(["__proto__", "constructor", "prototype"]);
1048
+
1049
+ class MutationsService {
1050
+ insertField(tree3, _field, index) {
1051
+ const hasField = tree3.order.has(_field.id);
1052
+ if (hasField) {
1053
+ throw new MutationError(`Field ${_field.name} with ID (${_field.id}) already exists`);
1054
+ }
1055
+ const field3 = _field instanceof FieldClass ? _field : new FieldClass(_field);
1056
+ if (!(field3 instanceof FieldClass)) {
1057
+ throw new MutationPrototypeError(field3.name);
1058
+ }
1059
+ if (index === 0) {
1060
+ throw new MutationError(`Cannot delete the first field!`);
1061
+ }
1062
+ if (field3.containerId) {
1063
+ const hasContainer = tree3.containers.has(field3.containerId);
1064
+ const hasContainerInOrder = tree3.order.has(field3.containerId);
1065
+ if (!hasContainer || !hasContainerInOrder) {
1066
+ throw new MutationError(`Insert of Field ${field3.name} with ID (${field3.id}) failed. Container ${field3.containerId} does not exist`);
1067
+ }
1068
+ tree3 = this.mutateContainer(tree3, {
1069
+ id: field3.containerId,
1070
+ keyValuePairs: {
1071
+ order: new Set([field3.id])
1072
+ }
1073
+ });
1074
+ }
1075
+ let order;
1076
+ if (index !== undefined) {
1077
+ if (index < 0) {
1078
+ console.warn(`Mutation: negative index detected '${index}'`);
1079
+ }
1080
+ const orderArray = Array.from(tree3.order);
1081
+ orderArray.splice(index, 0, field3.id);
1082
+ order = new Set(orderArray);
1083
+ } else {
1084
+ order = new Set(tree3.order);
1085
+ order.add(field3.id);
1086
+ }
1087
+ const fields2 = new Map(tree3.fields);
1088
+ fields2.set(field3.id, field3);
1089
+ return {
1090
+ ...tree3,
1091
+ order,
1092
+ fields: fields2
1093
+ };
1094
+ }
1095
+ deleteField(tree3, fieldId) {
1096
+ const hasField = tree3.order.has(fieldId);
1097
+ if (!hasField) {
1098
+ throw new MutationError(`Field with ID (${fieldId}) not found`);
1099
+ }
1100
+ const field3 = tree3.fields.get(fieldId);
1101
+ const order = new Set(tree3.order);
1102
+ order.delete(fieldId);
1103
+ const fields2 = new Map(tree3.fields);
1104
+ fields2.delete(fieldId);
1105
+ let updatedTree = {
1106
+ ...tree3,
1107
+ order,
1108
+ fields: fields2
1109
+ };
1110
+ const hasContainer = field3?.containerId && updatedTree.containers.has(field3.containerId);
1111
+ if (hasContainer) {
1112
+ const container4 = updatedTree.containers.get(field3.containerId);
1113
+ const containerHasField = container4?.order.has(fieldId);
1114
+ if (container4 && containerHasField) {
1115
+ const containerOrder = new Set(container4.order);
1116
+ containerOrder.delete(fieldId);
1117
+ updatedTree = this.mutateContainer(updatedTree, {
1118
+ id: field3.containerId,
1119
+ keyValuePairs: {
1120
+ order: containerOrder
1121
+ },
1122
+ autoMerge: false
1123
+ });
1124
+ }
1125
+ }
1126
+ return updatedTree;
1127
+ }
1128
+ mutateField(tree3, { id, keyValuePairs, autoMerge }) {
1129
+ const hasFieldInOrder = tree3.order.has(id);
1130
+ if (!hasFieldInOrder) {
1131
+ throw new MutationError(`Field ${id} doesn't exist on the tree`);
1132
+ }
1133
+ const existingField = tree3.fields.get(id);
1134
+ if (!existingField || !(existingField instanceof FieldClass)) {
1135
+ throw new MutationPrototypeError(existingField?.name ?? id);
1136
+ }
1137
+ const currentField = existingField.getCurrentFieldObject();
1138
+ const updatedField = this.deepObjectUpdate(currentField, {
1139
+ keyValuePairs,
1140
+ autoMerge,
1141
+ id
1142
+ });
1143
+ if (updatedField === currentField)
1144
+ return tree3;
1145
+ const fields2 = new Map(tree3.fields);
1146
+ fields2.set(id, new FieldClass(updatedField));
1147
+ return {
1148
+ ...tree3,
1149
+ fields: fields2
1150
+ };
1151
+ }
1152
+ canMerge(autoMerge, value, current) {
1153
+ if (!autoMerge)
1154
+ return false;
1155
+ if (current === undefined || current === null)
1156
+ return false;
1157
+ if (Array.isArray(value))
1158
+ return Array.isArray(current);
1159
+ if (UTILS.isPlainObject(value))
1160
+ return UTILS.isPlainObject(current);
1161
+ return false;
1162
+ }
1163
+ mergeValues(current, value) {
1164
+ if (Array.isArray(current)) {
1165
+ const incoming = value;
1166
+ return incoming.length === 0 ? current : [...current, ...incoming];
1167
+ }
1168
+ const cur = current;
1169
+ const inc = value;
1170
+ const unchanged = Object.keys(inc).every((k) => Object.is(cur[k], inc[k]));
1171
+ return unchanged ? current : { ...cur, ...inc };
1172
+ }
1173
+ setIn(obj, path, value, autoMerge) {
1174
+ const [head, ...rest] = path;
1175
+ const current = obj?.[head];
1176
+ let next;
1177
+ if (rest.length === 0) {
1178
+ next = this.canMerge(autoMerge, value, current) ? this.mergeValues(current, value) : value;
1179
+ } else {
1180
+ next = this.setIn(UTILS.isPlainObject(current) ? current : {}, rest, value, autoMerge);
1181
+ }
1182
+ if (Object.is(next, current))
1183
+ return obj;
1184
+ return Array.isArray(obj) ? Object.assign([...obj], { [head]: next }) : { ...obj, [head]: next };
1185
+ }
1186
+ deepObjectUpdate(obj, { keyValuePairs, autoMerge = true }) {
1187
+ let result = obj;
1188
+ for (const [key, value] of UTILS.ObjectEntries(keyValuePairs)) {
1189
+ const path = key.split(".");
1190
+ if (path.some((p) => FORBIDDEN.has(p))) {
1191
+ throw new MutationError(`Forbidden key "${key}"`);
1192
+ }
1193
+ result = this.setIn(result, path, value, autoMerge);
1194
+ }
1195
+ return result;
1196
+ }
1197
+ mutateContainer(tree3, { keyValuePairs, id, autoMerge = true }) {
1198
+ if (!tree3.order.has(id)) {
1199
+ throw new MutationError(`Container ${id} doesn't exist on the tree`);
1200
+ }
1201
+ const existingContainer = tree3.containers.get(id);
1202
+ if (!existingContainer || !(existingContainer instanceof ContainerClass)) {
1203
+ throw new MutationPrototypeError(existingContainer?.name ?? "ContainerNotFound");
1204
+ }
1205
+ const currentContainer = existingContainer.getCurrentContainerObject();
1206
+ const updatedContainer = this.deepObjectUpdate(currentContainer, {
1207
+ keyValuePairs,
1208
+ autoMerge,
1209
+ id
1210
+ });
1211
+ if (currentContainer === updatedContainer)
1212
+ return tree3;
1213
+ const containers = new Map(tree3.containers);
1214
+ containers.set(id, new ContainerClass(updatedContainer));
1215
+ return {
1216
+ ...tree3,
1217
+ containers
1218
+ };
1219
+ }
1220
+ }
1221
+
1222
+ // src/services/shortcuts/shortcuts.ts
1223
+ class ShortcutsService {
1224
+ }
1225
+
1226
+ // src/services/state/state.errors.ts
1227
+ class StateError extends Error {
1228
+ constructor(msg) {
1229
+ super(`StateError: ${msg}`);
1230
+ this.name = "StateError";
1231
+ }
1232
+ }
1233
+
1234
+ class StateNotFoundError extends StateError {
1235
+ constructor(name2) {
1236
+ super(`State ${name2} not found`);
1237
+ }
1238
+ }
1239
+
1240
+ // src/services/state/state.ts
1241
+ class StateService {
1242
+ slices = new Map;
1243
+ listeners = new Map;
1244
+ defineSlice(name2, initialValue) {
1245
+ if (this.slices.has(name2)) {
1246
+ throw new StateError(`${name2} slice already defined`);
1247
+ }
1248
+ this.slices.set(name2, initialValue);
1249
+ return () => {
1250
+ this.slices.delete(name2);
1251
+ this.listeners.delete(name2);
1252
+ };
1253
+ }
1254
+ get(name2) {
1255
+ const state = this.slices.get(name2);
1256
+ if (!state)
1257
+ return;
1258
+ return state;
1259
+ }
1260
+ set(name2, value) {
1261
+ if (!this.slices.has(name2))
1262
+ throw new StateError(`Slice "${String(name2)}" is not defined`);
1263
+ if (value === this.slices.get(name2))
1264
+ return;
1265
+ this.slices.set(name2, value);
1266
+ this.listeners.get(name2)?.forEach((fn) => fn(value));
1267
+ }
1268
+ subscribe(name2, fn) {
1269
+ const set = this.listeners.get(name2) ?? new Set;
1270
+ set.add(fn);
1271
+ this.listeners.set(name2, set);
1272
+ return () => set.delete(fn);
1273
+ }
1274
+ }
1275
+
1276
+ // src/services/text-marks/text-marks.ts
1277
+ class TextMarksService {
1278
+ behaviors = new Map([
1279
+ ["bold", { inclusive: true }],
1280
+ ["italic", { inclusive: true }],
1281
+ ["underline", { inclusive: true }],
1282
+ ["code", { inclusive: true }],
1283
+ ["link", { inclusive: false }],
1284
+ ["initial", { inclusive: false }]
1285
+ ]);
1286
+ registerMark(type, behavior = { inclusive: true }) {
1287
+ if (this.behaviors.has(type))
1288
+ throw new Error(`Mark "${type}" is already registered`);
1289
+ this.behaviors.set(type, behavior);
1290
+ return () => {
1291
+ if (this.behaviors.get(type) === behavior)
1292
+ this.behaviors.delete(type);
1293
+ };
1294
+ }
1295
+ isInclusive(type) {
1296
+ return this.behaviors.get(type)?.inclusive ?? true;
1297
+ }
1298
+ attrsKey(attrs) {
1299
+ if (!attrs)
1300
+ return "";
1301
+ const keys = Object.keys(attrs).sort();
1302
+ return keys.length ? JSON.stringify(keys.map((k) => [k, attrs[k]])) : "";
1303
+ }
1304
+ sameMarks(a, b) {
1305
+ return a.length === b.length && a.every((mark, i) => mark.type === b[i].type && mark.start === b[i].start && mark.end === b[i].end && this.attrsKey(mark.attrs) === this.attrsKey(b[i].attrs));
1306
+ }
1307
+ normalizeMarks(marks, textLength) {
1308
+ const groups = new Map;
1309
+ for (const mark of marks) {
1310
+ const start = Math.max(0, Math.min(mark.start, textLength));
1311
+ const end = Math.max(0, Math.min(mark.end, textLength));
1312
+ if (!(start < end))
1313
+ continue;
1314
+ const key = `${mark.type}|${this.attrsKey(mark.attrs)}`;
1315
+ const list = groups.get(key) ?? [];
1316
+ list.push({ ...mark, start, end });
1317
+ groups.set(key, list);
1318
+ }
1319
+ const merged = [];
1320
+ for (const list of groups.values()) {
1321
+ list.sort((a, b) => a.start - b.start);
1322
+ let cur = list[0];
1323
+ for (let i = 1;i < list.length; i++) {
1324
+ const next = list[i];
1325
+ if (next.start <= cur.end) {
1326
+ if (next.end > cur.end)
1327
+ cur = { ...cur, end: next.end };
1328
+ } else {
1329
+ merged.push(cur);
1330
+ cur = next;
1331
+ }
1332
+ }
1333
+ merged.push(cur);
1334
+ }
1335
+ merged.sort((a, b) => a.start - b.start || a.type.localeCompare(b.type) || a.end - b.end);
1336
+ return this.sameMarks(marks, merged) ? marks : merged;
1337
+ }
1338
+ isFullyMarked(marks, start, end, spec) {
1339
+ const relevant = marks.filter((m) => m.type === spec.type).sort((a, b) => a.start - b.start);
1340
+ let covered = start;
1341
+ for (const mark of relevant) {
1342
+ if (mark.end <= covered)
1343
+ continue;
1344
+ if (mark.start > covered)
1345
+ return false;
1346
+ covered = mark.end;
1347
+ if (covered >= end)
1348
+ return true;
1349
+ }
1350
+ return covered >= end;
1351
+ }
1352
+ removeMark(marks, start, end, type) {
1353
+ const out = [];
1354
+ for (const mark of marks) {
1355
+ if (mark.type !== type || mark.end <= start || mark.start >= end) {
1356
+ out.push(mark);
1357
+ continue;
1358
+ }
1359
+ if (mark.start < start)
1360
+ out.push({ ...mark, end: start });
1361
+ if (mark.end > end)
1362
+ out.push({ ...mark, start: end });
1363
+ }
1364
+ return out;
1365
+ }
1366
+ toggleMark(content, { start, end, spec }) {
1367
+ const len = content.text.length;
1368
+ const s = Math.max(0, Math.min(start, end, len));
1369
+ const e = Math.min(len, Math.max(start, end));
1370
+ if (s >= e)
1371
+ return content;
1372
+ const next = this.isFullyMarked(content.marks, s, e, spec) ? this.removeMark(content.marks, s, e, spec.type) : [
1373
+ ...spec.type === "link" ? this.removeMark(content.marks, s, e, "link") : content.marks,
1374
+ { type: spec.type, start: s, end: e, ...spec.attrs && { attrs: spec.attrs } }
1375
+ ];
1376
+ const marks = this.normalizeMarks(next, len);
1377
+ return marks === content.marks ? content : { text: content.text, marks };
1378
+ }
1379
+ deleteRange(content, start, end) {
1380
+ const len = content.text.length;
1381
+ const _start = Math.max(0, Math.min(start, end, len));
1382
+ const _end = Math.min(len, Math.max(start, end));
1383
+ if (_start >= _end)
1384
+ return content;
1385
+ const diff = _end - _start;
1386
+ const map = (p) => p <= _start ? p : p >= _end ? p - diff : _end;
1387
+ const newText = content.text.slice(0, _start) + content.text.slice(_end);
1388
+ const marks = content.marks.map((mark) => ({
1389
+ ...mark,
1390
+ start: map(mark.start),
1391
+ end: map(mark.end)
1392
+ }));
1393
+ return { text: newText, marks: this.normalizeMarks(marks, newText.length) };
1394
+ }
1395
+ insertText(content, at, text, opts = {}) {
1396
+ if (text.length === 0)
1397
+ return content;
1398
+ const len = content.text.length;
1399
+ const pos = Math.max(0, Math.min(at, len));
1400
+ const n = text.length;
1401
+ let marks = content.marks.map((mark) => {
1402
+ if (mark.start >= pos)
1403
+ return { ...mark, start: mark.start + n, end: mark.end + n };
1404
+ if (mark.end > pos)
1405
+ return { ...mark, end: mark.end + n };
1406
+ if (mark.end === pos && this.isInclusive(mark.type))
1407
+ return { ...mark, end: mark.end + n };
1408
+ return mark;
1409
+ });
1410
+ if (opts.marks) {
1411
+ const types = new Set([
1412
+ ...marks.map((mark) => mark.type),
1413
+ ...opts.marks.map((spec) => spec.type)
1414
+ ]);
1415
+ for (const type of types)
1416
+ marks = this.removeMark(marks, pos, pos + n, type);
1417
+ for (const spec of opts.marks) {
1418
+ marks.push({
1419
+ type: spec.type,
1420
+ start: pos,
1421
+ end: pos + n,
1422
+ ...spec.attrs && { attrs: spec.attrs }
1423
+ });
1424
+ }
1425
+ }
1426
+ const newText = content.text.slice(0, pos) + text + content.text.slice(pos);
1427
+ return { text: newText, marks: this.normalizeMarks(marks, newText.length) };
1428
+ }
1429
+ replaceRange(content, start, end, text, opts) {
1430
+ const s = Math.min(start, end);
1431
+ return this.insertText(this.deleteRange(content, start, end), s, text, opts);
1432
+ }
1433
+ }
1434
+
1435
+ // src/services/ui/default-styles.ts
1436
+ var Text = {
1437
+ style: {
1438
+ width: "100%",
1439
+ color: "var(--text-foreground)",
1440
+ fontSize: "18px",
1441
+ minHeight: "32px",
1442
+ whiteSpace: "pre",
1443
+ fontWeight: 400,
1444
+ display: "block",
1445
+ alignItems: "center",
1446
+ outline: "none",
1447
+ border: "none",
1448
+ fieldSizing: "content",
1449
+ cursor: "default",
1450
+ paddingInline: 4,
1451
+ userSelect: "none"
1452
+ },
1453
+ className: "[&:empty:before]:content-[attr(data-placeholder)] [&:empty:before]:text-muted-foreground [&:empty:before]:pointer-events-none"
1454
+ };
1455
+ var Heading = {
1456
+ style: {
1457
+ width: "100%",
1458
+ maxWidth: "100%",
1459
+ color: "var(--text-foreground)",
1460
+ fontSize: "40px",
1461
+ minHeight: "48px",
1462
+ fontWeight: 400,
1463
+ whiteSpace: "pre",
1464
+ display: "block",
1465
+ alignItems: "center",
1466
+ outline: "none",
1467
+ border: "none",
1468
+ fieldSizing: "content",
1469
+ cursor: "default",
1470
+ paddingInline: 4,
1471
+ userSelect: "none"
1472
+ },
1473
+ className: "[&:empty:before]:content-[attr(data-placeholder)] [&:empty:before]:text-muted-foreground [&:empty:before]:pointer-events-none"
1474
+ };
1475
+ var Image = {
1476
+ style: {
1477
+ width: "100%",
1478
+ objectFit: "cover",
1479
+ display: "block",
1480
+ alignItems: "center",
1481
+ outline: "none",
1482
+ border: "none",
1483
+ fieldSizing: "content",
1484
+ cursor: "default",
1485
+ userSelect: "none"
1486
+ }
1487
+ };
1488
+ var Divider = {
1489
+ style: {
1490
+ width: "100%",
1491
+ borderTopWidth: 1,
1492
+ borderTopStyle: "solid",
1493
+ borderTopColor: "var(--color-muted-foreground)",
1494
+ marginBlock: 8,
1495
+ height: 1,
1496
+ position: "relative",
1497
+ overflow: "visible"
1498
+ },
1499
+ pseudoStyle: {
1500
+ ":before": {
1501
+ content: '""',
1502
+ position: "absolute",
1503
+ top: "-8px",
1504
+ bottom: "-8px",
1505
+ height: 16,
1506
+ left: 0,
1507
+ right: 0,
1508
+ pointerEvents: "auto",
1509
+ zIndex: 5
1510
+ }
1511
+ }
1512
+ };
1513
+ var STYLES = {
1514
+ text: Text,
1515
+ heading: Heading,
1516
+ image: Image,
1517
+ divider: Divider
1518
+ };
1519
+
1520
+ // src/services/ui/ui.errors.ts
1521
+ class UiError extends Error {
1522
+ constructor(message) {
1523
+ super(`UIError: ${message}`);
1524
+ this.name = "UIError";
1525
+ }
1526
+ }
1527
+
1528
+ // src/services/ui/ui.ts
1529
+ import { cn } from "cn";
1530
+
1531
+ // src/services/ui/ui.types.ts
1532
+ function createContribution(contribution) {
1533
+ return contribution;
1534
+ }
1535
+
1536
+ // src/services/ui/ui.ts
1537
+ class UiService {
1538
+ commands;
1539
+ styles = new Map;
1540
+ outdatedStyles = new Map;
1541
+ bySlot = new Map;
1542
+ listeners = new Map;
1543
+ interceptors = new Map;
1544
+ constructor(commands) {
1545
+ this.commands = commands;
1546
+ for (const [key, value] of UTILS.ObjectEntries(STYLES)) {
1547
+ this.styles.set(key, value);
1548
+ }
1549
+ }
1550
+ interceptPayload(contributionId, fn) {
1551
+ const list = this.interceptors.get(contributionId) ?? [];
1552
+ this.interceptors.set(contributionId, [...list, fn]);
1553
+ return () => this.interceptors.set(contributionId, (this.interceptors.get(contributionId) ?? []).filter((i) => i !== fn));
1554
+ }
1555
+ async runContribution(c, ui2) {
1556
+ let payload = c.getPayload(ui2);
1557
+ for (const intercept of this.interceptors.get(c.id) ?? []) {
1558
+ const next = await intercept(payload, ui2);
1559
+ if (next === null)
1560
+ return;
1561
+ payload = next;
1562
+ }
1563
+ this.commands.execute(c.command, payload);
1564
+ }
1565
+ contribute(slotName, c) {
1566
+ const prevContribution = this.bySlot.get(slotName) ?? [];
1567
+ if (prevContribution.some((x) => x.id === c.id)) {
1568
+ throw new UiError(`Contribution with id ${c.id} already exists`);
1569
+ }
1570
+ this.bySlot.set(slotName, [...prevContribution, c]);
1571
+ return () => {
1572
+ const current = this.bySlot.get(slotName) ?? [];
1573
+ this.bySlot.set(slotName, current.filter((x) => x.id !== c.id));
1574
+ this.notify(c.slot);
1575
+ };
1576
+ }
1577
+ getSlots(slot) {
1578
+ return this.bySlot.get(slot) ?? EMPTY;
1579
+ }
1580
+ subscribe(slot, fn) {
1581
+ const set = this.listeners.get(slot) ?? new Set;
1582
+ set.add(fn);
1583
+ this.listeners.set(slot, set);
1584
+ return () => set.delete(fn);
1585
+ }
1586
+ notify(slot) {
1587
+ this.listeners.get(slot)?.forEach((fn) => fn());
1588
+ }
1589
+ registerStyle(styleName, style) {
1590
+ const prevStyle = this.styles.get(styleName);
1591
+ if (prevStyle) {
1592
+ console.log(`[WARN]: Overwritting ${name} styles`);
1593
+ this.outdatedStyles.set(styleName, prevStyle);
1594
+ }
1595
+ this.styles.set(styleName, style);
1596
+ return () => {
1597
+ this.styles.set(styleName, this.outdatedStyles.get(styleName) ?? STYLES[styleName]);
1598
+ this.outdatedStyles.delete(styleName);
1599
+ };
1600
+ }
1601
+ patchStyle(styleName, style) {
1602
+ const prevStyle = this.styles.get(styleName) ?? { style: {}, pseudoStyle: {} };
1603
+ this.outdatedStyles.set(styleName, prevStyle);
1604
+ this.styles.set(styleName, {
1605
+ style: {
1606
+ ...prevStyle.style,
1607
+ ...style.style
1608
+ },
1609
+ pseudoStyle: {
1610
+ ...prevStyle.pseudoStyle,
1611
+ ...style.pseudoStyle
1612
+ },
1613
+ className: cn(prevStyle.className, style.className)
1614
+ });
1615
+ return () => {
1616
+ this.styles.set(styleName, this.outdatedStyles.get(styleName) ?? STYLES[styleName]);
1617
+ this.outdatedStyles.delete(styleName);
1618
+ };
1619
+ }
1620
+ getStyle(styleName) {
1621
+ return this.styles.get(styleName);
1622
+ }
1623
+ }
1624
+ var EMPTY = [];
1625
+
1626
+ // src/services/tasks/tasks.service.ts
1627
+ var DEFAULT_TASK_STATE = Object.freeze({
1628
+ status: "idle",
1629
+ isPending: false,
1630
+ isRunning: false,
1631
+ isIdle: true,
1632
+ lastExecutedAt: undefined,
1633
+ error: null,
1634
+ taskId: "default"
1635
+ });
1636
+
1637
+ class TasksService {
1638
+ pendingTasks = new Map;
1639
+ states = new Map;
1640
+ listeners = new Map;
1641
+ setState(name2, partial) {
1642
+ const key = name2;
1643
+ const prev = this.states.get(key) || DEFAULT_TASK_STATE;
1644
+ const status = partial.status ?? prev.status;
1645
+ const next = Object.freeze({
1646
+ ...prev,
1647
+ ...partial,
1648
+ status,
1649
+ isPending: status === "pending",
1650
+ isRunning: status === "running",
1651
+ isIdle: status === "idle"
1652
+ });
1653
+ this.states.set(key, next);
1654
+ this.notify(name2, next);
1655
+ }
1656
+ notify(name2, state) {
1657
+ const key = name2;
1658
+ const set = this.listeners.get(key);
1659
+ if (set) {
1660
+ for (const listener of set) {
1661
+ try {
1662
+ listener(state);
1663
+ } catch (err) {
1664
+ console.error(`[TasksService] Listener error for task "${key}":`, err);
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1669
+ getState(name2) {
1670
+ const key = name2;
1671
+ return this.states.get(key) || DEFAULT_TASK_STATE;
1672
+ }
1673
+ getStatus(name2) {
1674
+ return this.getState(name2).status;
1675
+ }
1676
+ isPending(name2) {
1677
+ return this.getState(name2).isPending;
1678
+ }
1679
+ isRunning(name2) {
1680
+ return this.getState(name2).isRunning;
1681
+ }
1682
+ subscribe(name2, fn) {
1683
+ const key = name2;
1684
+ let set = this.listeners.get(key);
1685
+ if (!set) {
1686
+ set = new Set;
1687
+ this.listeners.set(key, set);
1688
+ }
1689
+ set.add(fn);
1690
+ return () => {
1691
+ const currentSet = this.listeners.get(key);
1692
+ if (currentSet) {
1693
+ currentSet.delete(fn);
1694
+ if (currentSet.size === 0) {
1695
+ this.listeners.delete(key);
1696
+ }
1697
+ }
1698
+ };
1699
+ }
1700
+ schedule(name2, delay, fn, taskId) {
1701
+ const key = name2;
1702
+ const existing = this.pendingTasks.get(key);
1703
+ if (existing) {
1704
+ clearTimeout(existing.timerId);
1705
+ this.pendingTasks.delete(key);
1706
+ }
1707
+ this.setState(name2, {
1708
+ status: "pending",
1709
+ error: null
1710
+ });
1711
+ const timerId = setTimeout(async () => {
1712
+ this.pendingTasks.delete(key);
1713
+ await this.executeTask(name2, fn);
1714
+ }, delay);
1715
+ this.pendingTasks.set(key, {
1716
+ name: name2,
1717
+ fn,
1718
+ delay,
1719
+ timerId,
1720
+ taskId: taskId ?? UTILS.generateId("task")
1721
+ });
1722
+ return () => {
1723
+ const current = this.pendingTasks.get(key);
1724
+ if (current && current.timerId === timerId) {
1725
+ clearTimeout(timerId);
1726
+ this.pendingTasks.delete(key);
1727
+ this.setState(name2, { status: "idle" });
1728
+ }
1729
+ };
1730
+ }
1731
+ async executeTask(name2, fn) {
1732
+ this.setState(name2, {
1733
+ status: "running"
1734
+ });
1735
+ let executionError = null;
1736
+ try {
1737
+ await fn();
1738
+ } catch (err) {
1739
+ executionError = err instanceof Error ? err : new Error(String(err));
1740
+ console.error(`[TasksService] Error executing task "${String(name2)}":`, err);
1741
+ } finally {
1742
+ this.setState(name2, {
1743
+ status: "idle",
1744
+ lastExecutedAt: Date.now(),
1745
+ error: executionError
1746
+ });
1747
+ }
1748
+ }
1749
+ cancel(name2) {
1750
+ const key = name2;
1751
+ const existing = this.pendingTasks.get(key);
1752
+ if (!existing)
1753
+ return false;
1754
+ clearTimeout(existing.timerId);
1755
+ this.pendingTasks.delete(key);
1756
+ this.setState(name2, { status: "idle" });
1757
+ return true;
1758
+ }
1759
+ async flush(name2) {
1760
+ const key = name2;
1761
+ const existing = this.pendingTasks.get(key);
1762
+ if (!existing)
1763
+ return;
1764
+ clearTimeout(existing.timerId);
1765
+ this.pendingTasks.delete(key);
1766
+ await this.executeTask(name2, existing.fn);
1767
+ }
1768
+ cancelAll() {
1769
+ for (const record of this.pendingTasks.values()) {
1770
+ clearTimeout(record.timerId);
1771
+ this.setState(record.name, { status: "idle" });
1772
+ }
1773
+ this.pendingTasks.clear();
1774
+ }
1775
+ dispose() {
1776
+ this.cancelAll();
1777
+ this.listeners.clear();
1778
+ this.states.clear();
1779
+ }
1780
+ }
1781
+
1782
+ // src/engine/engine.ts
1783
+ class Engine {
1784
+ events = new EventBusService;
1785
+ state = new StateService;
1786
+ document = new DocumentService(this.state, this.events);
1787
+ commands = new CommandsBusService;
1788
+ shortcuts = new ShortcutsService;
1789
+ mutations = new MutationsService;
1790
+ ui = new UiService(this.commands);
1791
+ text = new TextMarksService;
1792
+ tasks = new TasksService;
1793
+ modules = new ModuleManager(this);
1794
+ }
1795
+ // src/modules/insertion/insertion.module.ts
1796
+ var ActionsOpenerContribution = {
1797
+ id: "insert-field",
1798
+ slot: "block-actions",
1799
+ order: 0,
1800
+ kind: "button",
1801
+ command: "actions.toggle",
1802
+ icon: "PlusIcon",
1803
+ getPayload: () => true,
1804
+ name: "BlockActionButton",
1805
+ getProps() {
1806
+ return { variant: "secondary", size: "icon-lg", isBaseButton: true };
1807
+ },
1808
+ when() {
1809
+ return true;
1810
+ }
1811
+ };
1812
+ var InsertionModule = {
1813
+ name: "insertion",
1814
+ version: "1.0.0",
1815
+ requires: [],
1816
+ install(ctx) {
1817
+ ctx.state.defineSlice("insertion", false);
1818
+ ctx.commands.register("actions.toggle", (isOpen) => {
1819
+ ctx.state.set("insertion", isOpen);
1820
+ ctx.events.emit("actions:toggle", isOpen);
1821
+ });
1822
+ ctx.commands.register("blocks.insert", ({ block, pos }) => {
1823
+ const isNotMedia = block.type !== "image" && block.type !== "video";
1824
+ const hasSrcInProps = "src" in block.props && !!block.props.src.trim();
1825
+ const shouldEmitEvent = isNotMedia || hasSrcInProps;
1826
+ ctx.document.apply((tree3) => {
1827
+ if (block.variant === "field") {
1828
+ return ctx.mutations.insertField(tree3, block, pos);
1829
+ }
1830
+ return tree3;
1831
+ }, { shouldEmitEvent });
1832
+ ctx.state.set("insertion", false);
1833
+ ctx.events.emit("blocks:insert", { block, pos });
1834
+ });
1835
+ ctx.commands.register("blocks.delete", ({ blockId }) => {
1836
+ const isFieldBlock = blockId.startsWith("field:");
1837
+ if (!isFieldBlock)
1838
+ return;
1839
+ ctx.document.apply((tree3) => ctx.mutations.deleteField(tree3, blockId));
1840
+ ctx.events.emit("blocks:delete", { blockId });
1841
+ });
1842
+ function actionButton(id, block, icon, order) {
1843
+ ctx.ui.contribute("block-actions", {
1844
+ id,
1845
+ order,
1846
+ icon,
1847
+ kind: "button",
1848
+ slot: "block-actions",
1849
+ command: "blocks.insert",
1850
+ name: "BlockActionButton",
1851
+ getProps() {
1852
+ return { variant: "outline", size: "icon" };
1853
+ },
1854
+ getPayload: () => ({ block }),
1855
+ when() {
1856
+ return true;
1857
+ }
1858
+ });
1859
+ }
1860
+ ctx.ui.contribute("block-actions", {
1861
+ ...ActionsOpenerContribution,
1862
+ getPayload: () => !ctx.state.get("insertion")
1863
+ });
1864
+ actionButton("insert-heading", FieldsUtils.NewHeadingField(), "HeadingIcon", 1);
1865
+ actionButton("insert-text", FieldsUtils.NewTextField(), "TextIcon", 2);
1866
+ actionButton("insert-image", FieldsUtils.NewImageField(), "ImagePlus", 3);
1867
+ actionButton("insert-divider", FieldsUtils.NewDividerField(), "DividerIcon", 4);
1868
+ }
1869
+ };
1870
+ // src/modules/editor/editor.module.ts
1871
+ var MIN_SIZE = 16;
1872
+ function overlayPositionFromBlockRects(rects, editorRect) {
1873
+ if (!editorRect || rects.length === 0)
1874
+ return null;
1875
+ const top = Math.min(...rects.map((rect) => rect.top));
1876
+ const left = Math.min(...rects.map((rect) => rect.left));
1877
+ const bottom = Math.max(...rects.map((rect) => rect.bottom));
1878
+ const right = Math.max(...rects.map((rect) => rect.right));
1879
+ const scrollTop = rects[0].parentScrollTop;
1880
+ const scrollLeft = rects[0].parentScrollLeft;
1881
+ const width = right - left;
1882
+ const height = bottom - top;
1883
+ return {
1884
+ top: top - editorRect.top - editorRect.clientTop + scrollTop - (height < MIN_SIZE ? MIN_SIZE / 2 : 0),
1885
+ left: left - editorRect.left - editorRect.clientLeft + scrollLeft - (width < MIN_SIZE ? MIN_SIZE / 2 : 0),
1886
+ width: width < MIN_SIZE ? MIN_SIZE : width,
1887
+ height: height < MIN_SIZE ? MIN_SIZE : height
1888
+ };
1889
+ }
1890
+ var EditorModule = {
1891
+ name: "editor",
1892
+ version: "1.0.0",
1893
+ requires: [],
1894
+ install(ctx) {
1895
+ ctx.state.defineSlice("editor", { editorRect: null });
1896
+ ctx.commands.register("editor.rect", ({ editorRect }) => {
1897
+ const prevState = ctx.state.get("editor");
1898
+ if (editorRect === null) {
1899
+ if (prevState?.editorRect === null)
1900
+ return;
1901
+ ctx.state.set("editor", { editorRect });
1902
+ ctx.events.emit("editor:rect", { editorRect });
1903
+ return;
1904
+ }
1905
+ if (!prevState) {
1906
+ return;
1907
+ }
1908
+ if (prevState.editorRect === null) {
1909
+ ctx.state.set("editor", { editorRect });
1910
+ ctx.events.emit("editor:rect", { editorRect });
1911
+ return;
1912
+ }
1913
+ const areSame = areObjectsTheSame(prevState.editorRect, editorRect);
1914
+ if (!areSame) {
1915
+ ctx.state.set("editor", { editorRect });
1916
+ ctx.events.emit("editor:rect", { editorRect });
1917
+ }
1918
+ });
1919
+ }
1920
+ };
1921
+
1922
+ // src/modules/selection/selection.module.ts
1923
+ function compute(prev, incoming, mode) {
1924
+ switch (mode) {
1925
+ case "replace":
1926
+ return new Map(incoming);
1927
+ case "add":
1928
+ return new Map([...prev, ...incoming]);
1929
+ case "remove": {
1930
+ const result = new Map(prev);
1931
+ for (const id of incoming.keys()) {
1932
+ result.delete(id);
1933
+ }
1934
+ return result;
1935
+ }
1936
+ case "toggle": {
1937
+ const result = new Map(prev);
1938
+ for (const [id, rect] of incoming) {
1939
+ if (result.has(id)) {
1940
+ result.delete(id);
1941
+ } else {
1942
+ result.set(id, rect);
1943
+ }
1944
+ }
1945
+ return result;
1946
+ }
1947
+ }
1948
+ }
1949
+ function sameBlocks(a, b) {
1950
+ if (a.size !== b.size)
1951
+ return false;
1952
+ for (const [id, rectA] of a.entries()) {
1953
+ const rectB = b.get(id);
1954
+ if (!rectB)
1955
+ return false;
1956
+ for (const key in rectA) {
1957
+ if (Object.prototype.hasOwnProperty.call(rectA, key)) {
1958
+ if (rectA[key] !== rectB[key]) {
1959
+ return false;
1960
+ }
1961
+ }
1962
+ }
1963
+ }
1964
+ return true;
1965
+ }
1966
+ function selectionOverlayPropsFromUICtx(ui2, editorRect, order) {
1967
+ const rects = Array.from(ui2?.selection?.blocks?.entries() ?? []).map(([id, rect]) => order.has(id) ? rect : null).filter(Boolean);
1968
+ return overlayPositionFromBlockRects(rects, editorRect);
1969
+ }
1970
+ var SelectionModule = {
1971
+ name: "selection",
1972
+ version: "1.0.0",
1973
+ requires: [],
1974
+ install(ctx) {
1975
+ ctx.state.defineSlice("selection", { blocks: new Map });
1976
+ ctx.ui.contribute("overlay", {
1977
+ id: "selection-overlay",
1978
+ slot: "overlay",
1979
+ order: 1000,
1980
+ kind: "component",
1981
+ name: "SelectionOverlay",
1982
+ when: (ui2) => ui2.selection.blocks.size > 0,
1983
+ getProps: (ui2) => {
1984
+ const editorState = ctx.state.get("editor") ?? { editorRect: null };
1985
+ const position = selectionOverlayPropsFromUICtx(ui2, editorState?.editorRect, ctx.document.get().order);
1986
+ return {
1987
+ position,
1988
+ hidden: !Array.from(ui2.selection.blocks.keys()).length || !position
1989
+ };
1990
+ }
1991
+ });
1992
+ const apply = (next) => {
1993
+ const previous = ctx.state.get("selection").blocks;
1994
+ if (sameBlocks(previous, next))
1995
+ return;
1996
+ ctx.state.set("selection", { blocks: next });
1997
+ ctx.events.emit("selection:changed", { blocks: next, previous });
1998
+ };
1999
+ ctx.commands.register("blocks.select", ({ blocks, mode = "replace" }) => {
2000
+ const validBlocks = new Map;
2001
+ for (const [id, rect] of blocks) {
2002
+ if (ctx.document.has(id)) {
2003
+ validBlocks.set(id, rect);
2004
+ }
2005
+ }
2006
+ const prev = ctx.state.get("selection").blocks;
2007
+ apply(compute(prev, validBlocks, mode));
2008
+ });
2009
+ ctx.commands.register("blocks.clearSelection", () => apply(new Map));
2010
+ }
2011
+ };
2012
+ // src/modules/focus/focus.module.ts
2013
+ import _ from "lodash";
2014
+ function focusOverlayPropsFromUICtx(ui2, editorRect) {
2015
+ const rect = ui2.focus?.rect;
2016
+ if (!rect)
2017
+ return null;
2018
+ return overlayPositionFromBlockRects([rect], editorRect);
2019
+ }
2020
+ var FocusModule = {
2021
+ name: "focus",
2022
+ version: "1.0.0",
2023
+ requires: ["selection"],
2024
+ install(ctx) {
2025
+ ctx.state.defineSlice("focus", null);
2026
+ ctx.state.defineSlice("focus_memory", { blocks: [], count: 3 });
2027
+ ctx.ui.contribute("overlay", {
2028
+ id: "focus-overlay",
2029
+ slot: "overlay",
2030
+ order: 1001,
2031
+ kind: "component",
2032
+ name: "FocusOverlay",
2033
+ when: (ui2) => !!ui2.focus?.id,
2034
+ getProps: (ui2) => {
2035
+ const editorState = ctx.state.get("editor") ?? { editorRect: null };
2036
+ const position = focusOverlayPropsFromUICtx(ui2, editorState?.editorRect);
2037
+ const document = ctx.state.get("document");
2038
+ return {
2039
+ position,
2040
+ hidden: !ui2.focus?.id || !position || !document?.order.has(ui2?.focus?.id)
2041
+ };
2042
+ }
2043
+ });
2044
+ ctx.commands.register("blocks.focus", (payload) => {
2045
+ if (payload && !isEditableField(ctx.document.getBlock(payload.id))) {
2046
+ ctx.commands.execute("blocks.select", {
2047
+ blocks: new Map().set(payload.id, payload.rect),
2048
+ mode: "replace"
2049
+ });
2050
+ return;
2051
+ }
2052
+ const { id: focusedId = null, rect = null } = payload ?? {};
2053
+ const prev = ctx.state.get("focus");
2054
+ if (focusedId !== null && !ctx.document.has(focusedId))
2055
+ return;
2056
+ if (focusedId === prev?.id && _.isEqual(rect, prev.rect))
2057
+ return;
2058
+ const prevFocusedId = prev?.id;
2059
+ const shouldUnfocusPrev = Boolean(prevFocusedId && prevFocusedId !== focusedId && (() => {
2060
+ const b = ctx.document.getBlock(prevFocusedId);
2061
+ return b && isEditableField(b);
2062
+ })());
2063
+ const shouldFocusCurrent = Boolean(focusedId && (() => {
2064
+ const b = ctx.document.getBlock(focusedId);
2065
+ return b && isEditableField(b);
2066
+ })());
2067
+ if (shouldUnfocusPrev || shouldFocusCurrent) {
2068
+ ctx.document.apply((tree3) => {
2069
+ let nextTree = tree3;
2070
+ if (shouldUnfocusPrev && prevFocusedId) {
2071
+ nextTree = ctx.mutations.mutateField(nextTree, {
2072
+ keyValuePairs: {
2073
+ "props.contentEditable": false
2074
+ },
2075
+ id: prevFocusedId
2076
+ });
2077
+ }
2078
+ if (shouldFocusCurrent && focusedId) {
2079
+ nextTree = ctx.mutations.mutateField(nextTree, {
2080
+ keyValuePairs: {
2081
+ "props.contentEditable": true
2082
+ },
2083
+ id: focusedId
2084
+ });
2085
+ }
2086
+ return nextTree;
2087
+ }, { shouldEmitEvent: false });
2088
+ }
2089
+ ctx.state.set("focus", payload);
2090
+ const selectedBlocks = ctx.state.get("selection");
2091
+ if (payload && !selectedBlocks?.blocks?.has(payload.id)) {
2092
+ ctx.commands.execute("blocks.select", {
2093
+ blocks: new Map().set(payload.id, payload.rect),
2094
+ mode: "replace"
2095
+ });
2096
+ } else if (!payload) {
2097
+ ctx.commands.execute("blocks.select", {
2098
+ blocks: new Map,
2099
+ mode: "replace"
2100
+ });
2101
+ }
2102
+ const { blocks: _memoBlocks, count } = ctx.state.get("focus_memory");
2103
+ if (focusedId && rect) {
2104
+ ctx.state.set("focus_memory", {
2105
+ blocks: [..._memoBlocks, { id: focusedId, rect }].slice(-count),
2106
+ count
2107
+ });
2108
+ }
2109
+ ctx.events.emit("blocks:focus", payload);
2110
+ });
2111
+ }
2112
+ };
2113
+ // src/modules/hover/hover.module.ts
2114
+ function hoverOverlayPropsFromUICtx(ui2, editorRect) {
2115
+ const rect = ui2.hover?.rect;
2116
+ if (!rect)
2117
+ return null;
2118
+ return overlayPositionFromBlockRects([rect], editorRect);
2119
+ }
2120
+ var HoverModule = {
2121
+ name: "hover",
2122
+ version: "1.0.0",
2123
+ requires: [],
2124
+ install(ctx) {
2125
+ ctx.state.defineSlice("hover", null);
2126
+ ctx.state.defineSlice("hover_memory", { blocks: [], count: 3 });
2127
+ ctx.ui.contribute("overlay", {
2128
+ id: "hover-overlay",
2129
+ slot: "overlay",
2130
+ order: 999,
2131
+ kind: "component",
2132
+ name: "HoverOverlay",
2133
+ when: (ui2) => !!ui2.hover?.id,
2134
+ getProps: (ui2) => {
2135
+ const editorState = ctx.state.get("editor") ?? { editorRect: null };
2136
+ const selection = ctx.state.get("selection");
2137
+ const document = ctx.state.get("document");
2138
+ const position = hoverOverlayPropsFromUICtx(ui2, editorState?.editorRect);
2139
+ return {
2140
+ position,
2141
+ hidden: !ui2.hover?.id || !position || !!selection && selection.blocks.has(ui2.hover?.id) || !document?.order.has(ui2.hover?.id)
2142
+ };
2143
+ }
2144
+ });
2145
+ ctx.commands.register("blocks.hover", (payload) => {
2146
+ if (!payload) {
2147
+ ctx.state.set("hover", null);
2148
+ ctx.events.emit("blocks:hover", null);
2149
+ return;
2150
+ }
2151
+ const { id, rect } = payload;
2152
+ const prev = ctx.state.get("hover");
2153
+ if (id !== null && !ctx.document.has(id))
2154
+ return;
2155
+ if (id === prev?.id)
2156
+ return;
2157
+ ctx.state.set("hover", payload);
2158
+ const { blocks: _memoBlocks, count } = ctx.state.get("hover_memory");
2159
+ if (id && rect) {
2160
+ ctx.state.set("hover_memory", {
2161
+ blocks: [..._memoBlocks, { id, rect }].slice(-count),
2162
+ count
2163
+ });
2164
+ }
2165
+ ctx.events.emit("blocks:hover", payload);
2166
+ });
2167
+ }
2168
+ };
2169
+ // src/modules/history/history.module.ts
2170
+ var HistoryModule = {
2171
+ name: "history",
2172
+ version: "1.0.0",
2173
+ requires: ["focus"],
2174
+ install(ctx) {
2175
+ const MAX = 100;
2176
+ let stack = [ctx.document.get()];
2177
+ let cursor = 0;
2178
+ ctx.state.defineSlice("history", { canUndo: false, canRedo: false });
2179
+ const sync = () => ctx.state.set("history", {
2180
+ canUndo: cursor > 0,
2181
+ canRedo: cursor < stack.length - 1
2182
+ });
2183
+ ctx.events.on("document:changed", ({ value }) => {
2184
+ if (value.origin === "history")
2185
+ return;
2186
+ stack = [...stack.slice(0, cursor + 1), value.next].slice(-MAX);
2187
+ cursor = stack.length - 1;
2188
+ sync();
2189
+ });
2190
+ const go = (to) => {
2191
+ if (to < 0 || to >= stack.length)
2192
+ return;
2193
+ cursor = to;
2194
+ ctx.document.apply(() => stack[cursor], { origin: "history" });
2195
+ sync();
2196
+ if (!ctx.state.get("focus"))
2197
+ ctx.commands.tryExecute("blocks.focus", null);
2198
+ };
2199
+ ctx.commands.register("history.undo", () => go(cursor - 1));
2200
+ ctx.commands.register("history.redo", () => go(cursor + 1));
2201
+ }
2202
+ };
2203
+ // src/modules/text-editing/text-editing.constants.ts
2204
+ var MARK_DEFAULT_ATTRS = {
2205
+ link: { href: "#" },
2206
+ initial: { style: { fontSize: 54 } }
2207
+ };
2208
+
2209
+ // src/modules/text-editing/text-editing.module.ts
2210
+ var isTextContent = (v) => typeof v === "object" && v !== null && typeof v.text === "string" && Array.isArray(v.marks);
2211
+ function splitString(str, delimiter) {
2212
+ return str.split(delimiter);
2213
+ }
2214
+ var getIn = (obj, path) => {
2215
+ if (!path)
2216
+ return null;
2217
+ return splitString(path, ".").reduce((o, k) => o?.[k], obj);
2218
+ };
2219
+ var TextEditingModule = {
2220
+ name: "text-editing",
2221
+ version: "1.0.0",
2222
+ requires: [],
2223
+ install(ctx) {
2224
+ ctx.state.defineSlice("textSelection", null);
2225
+ ctx.state.defineSlice("currentMarks", []);
2226
+ const currentMarks = (marks, sel) => {
2227
+ return marks.filter((mark) => mark.start === sel.start && mark.end === sel.end);
2228
+ };
2229
+ const current = () => {
2230
+ const sel = ctx.state.get("textSelection");
2231
+ if (!sel)
2232
+ return null;
2233
+ const block = ctx.document.getBlock(sel.blockId);
2234
+ if (!block || block.variant !== "field" || !["heading", "text"].includes(block.type))
2235
+ return null;
2236
+ const content = getIn(block, sel.path);
2237
+ if (!isTextContent(content))
2238
+ return null;
2239
+ return { sel, content };
2240
+ };
2241
+ const write = (sel, next) => {
2242
+ ctx.document.apply((tree3) => ctx.mutations.mutateField(tree3, {
2243
+ id: sel.blockId,
2244
+ keyValuePairs: { [sel.path]: next },
2245
+ autoMerge: false
2246
+ }));
2247
+ const curBlock = ctx.document.getBlock(sel.blockId);
2248
+ if (!curBlock || !["heading", "text"].includes(curBlock.type))
2249
+ return;
2250
+ ctx.state.set("currentMarks", currentMarks([...curBlock.props.children.marks], sel));
2251
+ };
2252
+ const setCaret = (sel, pos) => ctx.state.set("textSelection", {
2253
+ ...sel,
2254
+ start: pos,
2255
+ end: pos,
2256
+ pendingMarks: null
2257
+ });
2258
+ const activeAt = (content, pos) => content.marks.filter((m) => m.start < pos && m.end > pos || m.end === pos && m.start < pos && ctx.text.isInclusive(m.type)).map((m) => ({ type: m.type, ...m.attrs && { attrs: m.attrs } }));
2259
+ ctx.commands.register("text.setSelection", (next) => {
2260
+ if (!next) {
2261
+ ctx.state.set("textSelection", null);
2262
+ ctx.state.set("currentMarks", []);
2263
+ return;
2264
+ }
2265
+ const prev = ctx.state.get("textSelection");
2266
+ const samePlace = prev && prev.blockId === next.blockId && prev.path === next.path && prev.start === next.start && prev.end === next.end;
2267
+ if (samePlace)
2268
+ return;
2269
+ const curBlock = ctx.document.getBlock(next.blockId);
2270
+ if (!curBlock || !["heading", "text"].includes(curBlock.type))
2271
+ return;
2272
+ ctx.state.set("textSelection", { ...next, pendingMarks: null });
2273
+ ctx.state.set("currentMarks", currentMarks([...curBlock.props.children.marks], next));
2274
+ });
2275
+ ctx.commands.register("text.format", ({ format, attrs }) => {
2276
+ const cur = current();
2277
+ if (!cur)
2278
+ return;
2279
+ const { sel, content } = cur;
2280
+ if (sel.start === sel.end) {
2281
+ if (format === "initial") {
2282
+ const next2 = ctx.text.toggleMark(content, {
2283
+ start: 0,
2284
+ end: 1,
2285
+ spec: { type: format, ...attrs && { attrs } }
2286
+ });
2287
+ write(sel, next2);
2288
+ ctx.events.emit("text:format", { format, attrs });
2289
+ return;
2290
+ }
2291
+ const base = sel.pendingMarks ?? activeAt(content, sel.start);
2292
+ const pendingMarks = base.some((s) => s.type === format) ? base.filter((s) => s.type !== format) : [...base, { type: format, ...attrs && { attrs } }];
2293
+ ctx.state.set("textSelection", { ...sel, pendingMarks });
2294
+ ctx.events.emit("text:format", { format, attrs });
2295
+ return;
2296
+ }
2297
+ const next = ctx.text.toggleMark(content, {
2298
+ start: sel.start,
2299
+ end: sel.end,
2300
+ spec: { type: format, ...attrs && { attrs } }
2301
+ });
2302
+ if (next === content)
2303
+ return;
2304
+ write(sel, next);
2305
+ ctx.events.emit("text:format", { format, attrs });
2306
+ });
2307
+ ctx.commands.register("text.insert", ({ text }) => {
2308
+ const cur = current();
2309
+ if (!cur || text.length === 0)
2310
+ return;
2311
+ const { sel, content } = cur;
2312
+ const start = Math.min(sel.start, sel.end);
2313
+ const next = ctx.text.replaceRange(content, sel.start, sel.end, text, {
2314
+ marks: sel.pendingMarks ?? undefined
2315
+ });
2316
+ write(sel, next);
2317
+ setCaret(sel, start + text.length);
2318
+ });
2319
+ ctx.commands.register("text.delete", ({ direction = "backward", type = "character" }) => {
2320
+ const cur = current();
2321
+ if (!cur)
2322
+ return;
2323
+ const { sel, content } = cur;
2324
+ let start = Math.min(sel.start, sel.end);
2325
+ let end = Math.max(sel.start, sel.end);
2326
+ if (start === end) {
2327
+ if (direction === "backward")
2328
+ start -= 1;
2329
+ else
2330
+ end += 1;
2331
+ if (start < 0 || end > content.text.length)
2332
+ return;
2333
+ if (type === "word") {
2334
+ let chars = content.text.split("");
2335
+ chars = direction === "backward" ? chars.slice(0, sel.start) : chars.slice(sel.start);
2336
+ const sideWhiteSpacePos = direction === "backward" && chars[chars.length - 1] === " " ? "end" : direction === "forward" && chars[0] === " " ? "start" : "none";
2337
+ if (sideWhiteSpacePos === "start") {
2338
+ chars = chars.slice(1);
2339
+ } else if (sideWhiteSpacePos === "end") {
2340
+ chars = chars.slice(0, -1);
2341
+ }
2342
+ const firstWhiteSpaceIndex = chars.findIndex((char) => char === " ");
2343
+ const lastWhiteSpaceIndex = chars.findLastIndex((char) => char === " ");
2344
+ if (direction === "backward" && lastWhiteSpaceIndex !== -1) {
2345
+ start = lastWhiteSpaceIndex + 1;
2346
+ } else if (direction === "forward" && firstWhiteSpaceIndex !== -1) {
2347
+ end = firstWhiteSpaceIndex + (content.text.length - chars.length);
2348
+ }
2349
+ }
2350
+ }
2351
+ const next = ctx.text.deleteRange(content, start, end);
2352
+ if (next === content)
2353
+ return;
2354
+ write(sel, next);
2355
+ setCaret(sel, Math.max(0, start));
2356
+ });
2357
+ const formatButton = (format, icon, order) => ctx.ui.contribute("toolbar", {
2358
+ id: `format-${format}`,
2359
+ slot: "toolbar",
2360
+ order,
2361
+ kind: "button",
2362
+ icon,
2363
+ command: "text.format",
2364
+ name: "ToolBarButton",
2365
+ getPayload: () => ({ format, attrs: MARK_DEFAULT_ATTRS[format] ?? {} }),
2366
+ getProps(ui2) {
2367
+ const focusedBlock = ui2.focus;
2368
+ if (!focusedBlock?.id)
2369
+ return { isActive: false };
2370
+ const block = ctx.document.getBlock(focusedBlock.id);
2371
+ if (!block || !["heading", "text"].includes(block.type))
2372
+ return { isActive: false };
2373
+ const children = block.props.children;
2374
+ const curSel = ctx.state.get("textSelection");
2375
+ if (!curSel)
2376
+ return { isActive: false };
2377
+ const correspondingMark = children.marks?.find((mark) => mark.type === format);
2378
+ if (!correspondingMark)
2379
+ return { isActive: false };
2380
+ return {
2381
+ isActive: correspondingMark.start === curSel.start && correspondingMark.end === curSel.end
2382
+ };
2383
+ },
2384
+ when: (ui2) => {
2385
+ if (!ui2.focus?.id)
2386
+ return false;
2387
+ const block = ctx.document.getBlock(ui2.focus.id);
2388
+ if (!block)
2389
+ return false;
2390
+ const sel = ctx.state.get("textSelection");
2391
+ return isEditableField(block) && !!sel && sel.start !== sel.end;
2392
+ }
2393
+ });
2394
+ formatButton("bold", "BoldIcon", 10);
2395
+ formatButton("italic", "ItalicIcon", 20);
2396
+ formatButton("link", "LinkIcon", 30);
2397
+ formatButton("underline", "UnderlineIcon", 40);
2398
+ }
2399
+ };
2400
+ // src/modules/text-editing/text-editing.utils.ts
2401
+ function segments({ text, marks }) {
2402
+ if (!text)
2403
+ return [];
2404
+ const cuts = new Set([0, text.length]);
2405
+ for (const m of marks) {
2406
+ cuts.add(m.start);
2407
+ cuts.add(m.end);
2408
+ }
2409
+ const points = [...cuts].sort((a, b) => a - b);
2410
+ const out = [];
2411
+ for (let i = 0;i < points.length - 1; i++) {
2412
+ const [s, e] = [points[i], points[i + 1]];
2413
+ out.push({
2414
+ text: text.slice(s, e),
2415
+ marks: marks.filter((m) => m.start <= s && m.end >= e)
2416
+ });
2417
+ }
2418
+ return out;
2419
+ }
2420
+ export {
2421
+ segments,
2422
+ overlayPositionFromBlockRects,
2423
+ isEditableField,
2424
+ createContribution,
2425
+ coraxTreeDiffing,
2426
+ areObjectsTheSame,
2427
+ UiService,
2428
+ UiError,
2429
+ UTILS,
2430
+ TextMarksService,
2431
+ TextEditingModule,
2432
+ TasksService,
2433
+ TNodesUtils,
2434
+ TNodeClass,
2435
+ Subscriber,
2436
+ StateService,
2437
+ StateNotFoundError,
2438
+ StateError,
2439
+ SerializeTree,
2440
+ SelectionModule,
2441
+ STYLES,
2442
+ MutationsService,
2443
+ MutationPrototypeError,
2444
+ MutationError,
2445
+ ModuleUtils,
2446
+ ModuleManager,
2447
+ InsertionModule,
2448
+ HoverModule,
2449
+ HistoryModule,
2450
+ GetDefaultTree,
2451
+ FocusModule,
2452
+ FieldsUtils,
2453
+ FieldClass,
2454
+ EventBusService,
2455
+ Engine,
2456
+ EditorModule,
2457
+ DocumentService,
2458
+ DeserializeTree,
2459
+ CustomObject,
2460
+ ContainersUtils,
2461
+ ContainerClass,
2462
+ ComponentsUtils,
2463
+ ComponentClass,
2464
+ CommandsBusService,
2465
+ CmdNotFoundError
2466
+ };