-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdoc_utils.ts
More file actions
1120 lines (1031 loc) · 34.1 KB
/
Copy pathdoc_utils.ts
File metadata and controls
1120 lines (1031 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Shared document utilities used by both Session and Transaction.
*
* These functions operate on the core document state (schema, doc, selection, config)
* without any history management or transaction tracking.
*/
import {
assert_path_string_segment,
is_path_string_segment_valid,
get_selection_range,
get_char_length,
serialize_path,
are_ranges_exclusive
} from './utils.js';
import type {
NodeId,
DocumentPath,
PrimitiveType,
PropertyDefinition,
NodeProperty,
NodeArrayProperty,
NodeSchema,
NodeKind,
DocumentSchema,
Selection,
Attachment,
Mark,
Annotation,
Document,
DocumentNode,
TextProperty,
Text,
ValidateDocumentSchema,
Inspection,
DocumentOperation,
SessionConfig
} from './types.js';
/**
* Identity function — keeps schema at runtime & makes IDE infer types.
* Similar to your define_schema pattern but for document schemas.
*/
export function define_document_schema<S extends Record<string, NodeSchema>>(
schema: S & ValidateDocumentSchema<S>
): S {
return schema;
}
/**
* Check if a string represents a valid primitive type.
*/
export function is_primitive_type(type: string): type is PrimitiveType {
return [
'string',
'number',
'boolean',
'integer',
'datetime',
'text',
'string_array',
'number_array',
'boolean_array',
'integer_array'
].includes(type);
}
/**
* Get the default node type for a property that references nodes.
* Returns null if none specified.
*/
export function get_default_node_type(
property_definition: NodeProperty | NodeArrayProperty
): string | null {
if (!property_definition || !property_definition.node_types) {
return null;
}
return (
property_definition.default_node_type ||
(property_definition.node_types.length === 1 ? property_definition.node_types[0] : null)
);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function get_property_default(property_definition: PropertyDefinition): any {
if ('default' in property_definition) return structuredClone(property_definition.default);
if (property_definition.type === 'string') return '';
if (property_definition.type === 'integer') return 0;
if (property_definition.type === 'number') return 0;
if (property_definition.type === 'boolean') return false;
if (property_definition.type === 'text') return { content: '', marks: [], annotations: [] };
if (property_definition.type === 'node_array') return { nodes: [], marks: [], annotations: [] };
if (
property_definition.type === 'string_array' ||
property_definition.type === 'number_array' ||
property_definition.type === 'boolean_array' ||
property_definition.type === 'integer_array'
) {
return [];
}
return undefined;
}
/**
* Fill omitted properties with schema defaults and Svedit's built-in type defaults.
*
* This is a convenience helper for schema evolution, not a complete document
* migration system. Callers are still responsible for proper migrations when
* schema changes cannot be represented by defaults, such as property renames or
* data transformations.
*
* @returns A shallow copy of the node with cloned default values filled in
*/
export function fill_node_defaults(node: DocumentNode, schema: DocumentSchema): DocumentNode {
const node_schema = schema[node.type];
if (!node_schema) return { ...node };
const node_with_defaults = { ...node };
for (const [property_name, property_definition] of Object.entries(node_schema.properties)) {
if (node_with_defaults[property_name] === undefined) {
const property_default = get_property_default(property_definition);
if (property_default !== undefined) node_with_defaults[property_name] = property_default;
}
}
return node_with_defaults;
}
/**
* Fill omitted properties with schema defaults and Svedit's built-in type defaults across a document.
*
* This does not infer values, rename fields, or make an invalid migration valid
* by itself. Call this as one step in an explicit document migration when it is
* appropriate.
*
* @returns A document copy with cloned default values filled in
*/
export function fill_document_defaults(doc: Document, schema: DocumentSchema): Document {
const nodes: Record<string, DocumentNode> = {};
for (const [node_id, node] of Object.entries(doc.nodes)) {
nodes[node_id] = fill_node_defaults(node, schema);
}
return {
...doc,
nodes
};
}
/**
* Validate a document schema to ensure all referenced node types exist.
* @throws {Error} Throws if the document schema is invalid
*/
export function validate_document_schema(document_schema: DocumentSchema): void {
// Check that all referenced node types exist
for (const [node_type, node_schema] of Object.entries(document_schema)) {
for (const [prop_name, prop_def] of Object.entries(node_schema.properties)) {
assert_path_string_segment(prop_name, `Property name "${prop_name}"`);
if (prop_def.type === 'string' && prop_def.values !== undefined) {
if (
!Array.isArray(prop_def.values) ||
prop_def.values.some((value) => typeof value !== 'string')
) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" values must be an array of strings.`
);
}
if (prop_def.values.length === 0) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" values must not be empty.`
);
}
if (new Set(prop_def.values).size !== prop_def.values.length) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" values must be unique.`
);
}
if (prop_def.default !== undefined && !prop_def.values.includes(prop_def.default)) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" default must be one of its allowed values.`
);
}
}
if (prop_def.type === 'integer') {
if (prop_def.default !== undefined && !Number.isInteger(prop_def.default)) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" default must be an integer.`
);
}
if (prop_def.min !== undefined && !Number.isInteger(prop_def.min)) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" min must be an integer.`
);
}
if (prop_def.max !== undefined && !Number.isInteger(prop_def.max)) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" max must be an integer.`
);
}
if (
prop_def.min !== undefined &&
prop_def.max !== undefined &&
prop_def.min > prop_def.max
) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" min must not be greater than max.`
);
}
if (
prop_def.default !== undefined &&
((prop_def.min !== undefined && prop_def.default < prop_def.min) ||
(prop_def.max !== undefined && prop_def.default > prop_def.max))
) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" default must be within its min/max range.`
);
}
}
if (prop_def.type === 'node' || prop_def.type === 'node_array') {
const missing_types = prop_def.node_types.filter(
(ref_type) => !(ref_type in document_schema)
);
if (missing_types.length > 0) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" references unknown node types: ${missing_types.join(', ')}. Available node types: ${Object.keys(document_schema).join(', ')}`
);
}
}
if (prop_def.type === 'text' || prop_def.type === 'node_array') {
// mark_types must reference kind 'mark', annotation_types kind 'annotation'
for (const [key, expected_kind] of [
['mark_types', 'mark'],
['annotation_types', 'annotation']
] as const) {
const invalid_types = (prop_def[key] ?? []).filter(
(ref_type) => document_schema[ref_type]?.kind !== expected_kind
);
if (invalid_types.length > 0) {
throw new Error(
`Node type "${node_type}" property "${prop_name}" ${key} must reference node types of kind '${expected_kind}', got: ${invalid_types.join(', ')}.`
);
}
}
}
}
}
}
/**
* Validate that no annotation node type has a registered component.
*
* Marks render in-place via components; annotations are data-only overlay
* ranges that must be interpreted by the app (via CSS classes or props).
*
* @throws {Error} Throws if a kind 'annotation' type has a registered component
*/
export function validate_config_components(schema: DocumentSchema, config: SessionConfig): void {
for (const [node_type, node_schema] of Object.entries(schema)) {
if (node_schema.kind === 'annotation' && config?.node_components?.[node_type]) {
throw new Error(
`Annotation type "${node_type}" must not have a registered component. Annotations are data-only; use kind 'mark' for in-place rendered ranges.`
);
}
}
}
/**
* Validate a primitive value against its schema type.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function validate_primitive_value(type: PrimitiveType, value: any): boolean {
switch (type) {
case 'string':
return typeof value === 'string';
case 'number':
return typeof value === 'number' && !isNaN(value);
case 'boolean':
return typeof value === 'boolean';
case 'integer':
return Number.isInteger(value);
case 'datetime':
return typeof value === 'string' && !isNaN(Date.parse(value));
case 'text':
return (
typeof value === 'object' &&
value !== null &&
typeof value.content === 'string' &&
Array.isArray(value.marks) &&
Array.isArray(value.annotations)
);
case 'string_array':
return Array.isArray(value) && value.every((v) => typeof v === 'string');
case 'number_array':
return Array.isArray(value) && value.every((v) => typeof v === 'number' && !isNaN(v));
case 'boolean_array':
return Array.isArray(value) && value.every((v) => typeof v === 'boolean');
case 'integer_array':
return Array.isArray(value) && value.every((v) => Number.isInteger(v));
default:
return false;
}
}
/**
* Validate ranges (marks or annotations) for bounds, references, and allowed types.
*
* @throws {Error} Throws if ranges are invalid
*/
function validate_range_array(
node_id: string,
prop_name: string,
label: 'mark' | 'annotation',
ranges: Array<Attachment>,
container_length: number,
allowed_types: Array<string> | null | undefined,
all_nodes: Record<string, DocumentNode>,
require_references: boolean
): void {
for (const [index, range] of ranges.entries()) {
if (
typeof range !== 'object' ||
range === null ||
!Number.isInteger(range.start_offset) ||
!Number.isInteger(range.end_offset) ||
!is_id_valid(range.node_id)
) {
throw new Error(
`Node ${node_id} property ${prop_name} has an invalid ${label} at index ${index}. Ranges must have integer start_offset/end_offset and a valid node_id.`
);
}
if (range.start_offset < 0 || range.end_offset > container_length) {
throw new Error(
`Node ${node_id} property ${prop_name} ${label} ${range.node_id} is out of bounds: ${range.start_offset}-${range.end_offset}, container length is ${container_length}.`
);
}
if (range.start_offset >= range.end_offset) {
throw new Error(
`Node ${node_id} property ${prop_name} ${label} ${range.node_id} must not be empty or reversed: ${range.start_offset}-${range.end_offset}.`
);
}
const referenced_node = all_nodes[range.node_id];
if (!referenced_node) {
if (require_references) {
throw new Error(
`Node ${node_id} property ${prop_name} ${label} references missing node ${range.node_id}.`
);
}
continue;
}
if (allowed_types?.length && !allowed_types.includes(referenced_node.type)) {
throw new Error(
`Node ${node_id} property ${prop_name} ${label} references node ${range.node_id} of type ${referenced_node.type}, but only types [${allowed_types.join(', ')}] are allowed.`
);
}
}
}
/**
* Validate marks and annotations of an annotated container (text or node array).
*
* Marks must be mutually exclusive; annotations may overlap.
*
* @throws {Error} Throws if marks or annotations are invalid
*/
function validate_marks_and_annotations(
node_id: string,
prop_name: string,
value: { marks: Array<Mark>; annotations: Array<Annotation> },
prop_def: { mark_types?: string[]; annotation_types?: string[] },
container_length: number,
all_nodes: Record<string, DocumentNode>,
require_references: boolean
): void {
validate_range_array(
node_id,
prop_name,
'mark',
value.marks,
container_length,
prop_def.mark_types,
all_nodes,
require_references
);
if (!are_ranges_exclusive(value.marks, container_length)) {
throw new Error(
`Node ${node_id} property ${prop_name} has overlapping marks. Marks must be mutually exclusive.`
);
}
validate_range_array(
node_id,
prop_name,
'annotation',
value.annotations,
container_length,
prop_def.annotation_types,
all_nodes,
require_references
);
}
/**
* Validate text property marks and annotations for bounds, references, allowed
* types, and mark exclusivity.
*
* @throws {Error} Throws if marks or annotations are invalid
*/
function validate_text_property(
node_id: string,
prop_name: string,
value: Text,
prop_def: TextProperty,
all_nodes: Record<string, DocumentNode>,
require_references: boolean
): void {
const char_length = get_char_length(value.content);
validate_marks_and_annotations(
node_id,
prop_name,
value,
prop_def,
char_length,
all_nodes,
require_references
);
}
export function is_id_valid(id: string): boolean {
return typeof id === 'string' && id.length > 0 && is_path_string_segment_valid(id);
}
/**
* Validate a node against its schema.
*
* @param node - The node to validate
* @param schema - The document schema
* @param all_nodes - All nodes in the document to check references
* @param options - Validation options
* @throws {Error} Throws if the node is invalid
*/
export function validate_node(
node: DocumentNode,
schema: DocumentSchema,
all_nodes: Record<string, DocumentNode> = {},
options: { require_references?: boolean } = {}
): void {
const require_references = options.require_references ?? true;
if (!is_id_valid(node.id)) {
throw new Error(`Node ${node.id} has an invalid id.`);
}
if (!node.type || !schema[node.type]) {
throw new Error(`Node ${node.id} has an invalid type: ${node.type}`);
}
const node_schema = schema[node.type];
for (const [prop_name, prop_def] of Object.entries(node_schema.properties)) {
const value = node[prop_name];
// Check primitive types
if (is_primitive_type(prop_def.type)) {
if (!validate_primitive_value(prop_def.type, value)) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must be of type ${prop_def.type}.`
);
}
if (prop_def.type === 'string' && prop_def.values && !prop_def.values.includes(value)) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must be one of [${prop_def.values.join(', ')}].`
);
}
if (
prop_def.type === 'integer' &&
((prop_def.min !== undefined && value < prop_def.min) ||
(prop_def.max !== undefined && value > prop_def.max))
) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must be between ${prop_def.min ?? '-Infinity'} and ${prop_def.max ?? 'Infinity'}.`
);
}
}
if (prop_def.type === 'text') {
validate_text_property(
node.id,
prop_name,
value,
prop_def as TextProperty,
all_nodes,
require_references
);
}
// Check node references
if (prop_def.type === 'node') {
if (!is_id_valid(value)) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must be a valid node id.`
);
}
// Check if referenced node exists and is of allowed type
const referenced_node = all_nodes[value];
if (!referenced_node) {
if (require_references) {
throw new Error(
`Node ${node.id} property ${prop_name} references missing node ${value}.`
);
}
continue;
}
if (!prop_def.node_types.includes(referenced_node.type)) {
throw new Error(
`Node ${node.id} property ${prop_name} references node ${value} of type ${referenced_node.type}, but only types [${(prop_def as NodeProperty).node_types.join(', ')}] are allowed.`
);
}
}
// Check node arrays
else if (prop_def.type === 'node_array') {
if (
!value ||
typeof value !== 'object' ||
!Array.isArray(value.nodes) ||
!Array.isArray(value.marks) ||
!Array.isArray(value.annotations)
) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must be an object with nodes, marks and annotations.`
);
}
const node_array_nodes = value.nodes;
if (!node_array_nodes.every((id: unknown) => typeof id === 'string' && is_id_valid(id))) {
throw new Error(
`Node ${node.id} has an invalid property: ${prop_name} must contain valid node ids.`
);
}
// Check if all referenced nodes exist and are of allowed types
for (const ref_id of node_array_nodes) {
const referenced_node = all_nodes[ref_id];
if (!referenced_node) {
if (require_references) {
throw new Error(
`Node ${node.id} property ${prop_name} references missing node ${ref_id}.`
);
}
continue;
}
if (!prop_def.node_types.includes(referenced_node.type)) {
throw new Error(
`Node ${node.id} property ${prop_name} references node ${ref_id} of type ${referenced_node.type}, but only types [${prop_def.node_types.join(', ')}] are allowed.`
);
}
}
validate_marks_and_annotations(
node.id,
prop_name,
value,
prop_def,
node_array_nodes.length,
all_nodes,
require_references
);
}
}
}
/**
* Validate a document against its schema.
*
* @throws {Error} Throws if the document is invalid
*/
export function validate_document(doc: Document, schema: DocumentSchema): void {
if (!is_id_valid(doc.document_id)) {
throw new Error(`Document ${doc.document_id} has an invalid id.`);
}
for (const [node_id, node] of Object.entries(doc.nodes)) {
if (!is_id_valid(node_id)) {
throw new Error(`Document node map contains an invalid id: ${node_id}.`);
}
if (node.id !== node_id) {
throw new Error(`Document node map key ${node_id} does not match node id ${node.id}.`);
}
validate_node(node, schema, doc.nodes);
}
}
/**
* Gets a value from the document at the specified path.
*
* @param schema - The document schema
* @param doc - The document containing nodes
* @param path - Array path to the value, or a string node ID
* @returns The value at the specified path
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function get(schema: DocumentSchema, doc: Document, path: DocumentPath | string): any {
if (typeof path === 'string') {
path = [path];
}
if (!(Array.isArray(path) && path.length >= 1)) {
throw new Error(`Invalid path provided ${JSON.stringify(path)}`);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let val: any = doc.nodes[path[0]];
let val_type = 'node';
for (let i = 1; i < path.length; i++) {
const path_segment = path[i];
const path_segment_str = String(path_segment);
if (val_type === 'node') {
if (property_type(schema, val.type, path_segment_str) === 'node_array') {
val = val[path_segment];
val_type = 'node_array';
} else if (property_type(schema, val.type, path_segment_str) === 'text') {
val = val[path_segment];
val_type = 'text';
} else if (property_type(schema, val.type, path_segment_str) === 'node') {
val = doc.nodes[val[path_segment]];
val_type = 'node';
} else if (
['string_array', 'integer_array'].includes(
property_type(schema, val.type, path_segment_str)
)
) {
val = val[path_segment];
val_type = 'value_array';
} else {
val = val[path_segment];
val_type = 'value';
}
} else if (val_type === 'node_array') {
if (path_segment === 'nodes') {
val = val.nodes;
val_type = 'node_id_array';
} else if (path_segment === 'marks') {
val = val.marks;
val_type = 'range_array';
} else if (path_segment === 'annotations') {
val = val.annotations;
val_type = 'range_array';
} else if (typeof path_segment === 'number' || /^\d+$/.test(String(path_segment))) {
val = doc.nodes[val.nodes[path_segment]];
val_type = 'node';
} else {
throw new Error(
`Invalid path segment "${path_segment}" for node_array. Use "nodes", "marks" or "annotations".`
);
}
} else if (val_type === 'node_id_array') {
val = doc.nodes[val[path_segment]];
val_type = 'node';
} else if (val_type === 'value_array') {
val = val[path_segment];
val_type = 'value';
} else if (val_type === 'text') {
if (path_segment === 'content') {
val = val.content;
val_type = 'value';
} else if (path_segment === 'marks') {
val = val.marks;
val_type = 'range_array';
} else if (path_segment === 'annotations') {
val = val.annotations;
val_type = 'range_array';
} else {
throw new Error(
`Invalid path segment "${path_segment}" for text. Use "content", "marks" or "annotations".`
);
}
} else if (val_type === 'range_array') {
val = val[path_segment];
val_type = 'range';
} else if (val_type === 'range') {
if (path_segment === 'node_id') {
val = doc.nodes[val.node_id];
val_type = 'node';
} else if (path_segment === 'start_offset') {
val = val.start_offset;
val_type = 'value';
} else if (path_segment === 'end_offset') {
val = val.end_offset;
val_type = 'value';
} else {
throw new Error(
`Invalid path segment "${path_segment}" for range. Use "start_offset", "end_offset", or "node_id".`
);
}
}
}
return val;
}
/**
* Gets the type of a property from the schema.
*/
export function property_type(schema: DocumentSchema, type: string, property: string): string {
if (typeof type !== 'string') throw new Error(`Invalid type ${type} provided`);
if (typeof property !== 'string') throw new Error(`Invalid property ${property} provided`);
if (property === 'type') return 'string';
if (property === 'id') return 'string';
if (!schema[type]) throw new Error(`Type ${type} not found in schema`);
if (!schema[type].properties[property])
throw new Error(`Property ${property} not found in type ${type}`);
return schema[type].properties[property].type;
}
/**
* Determines the kind of a node ('document', 'block', 'text', 'mark', or 'annotation').
*/
export function kind(schema: DocumentSchema, node: DocumentNode): NodeKind {
return schema[node.type].kind;
}
/**
* Inspects a path to get metadata about the value at that location.
*/
export function inspect(schema: DocumentSchema, doc: Document, path: DocumentPath): Inspection {
const parent = path.length > 1 ? get(schema, doc, path.slice(0, -1)) : undefined;
if (parent?.type) {
const property_name = path.at(-1) as string;
return {
kind: 'property',
name: property_name,
...schema[parent.type].properties[property_name]
};
} else {
const node = get(schema, doc, path);
return {
kind: 'node',
id: node.id,
type: node.type,
properties: schema[node.type]
};
}
}
/**
* Creates a mutable draft of a document: a new document object with a new
* nodes map, sharing the (immutable) node objects with the original.
*
* apply_op_to_draft mutates the draft's nodes map but copies node objects
* before changing them, so node identity is preserved for unchanged nodes
* (fine-grained rendering relies on this) and the original document is
* never touched.
*
* @returns A draft document safe to mutate via apply_op_to_draft
*/
export function create_document_draft(doc: Document): Document {
return {
...doc,
nodes: { ...doc.nodes }
};
}
/**
* Applies an operation to a document draft in place.
*
* The draft's nodes map is mutated, but node objects are copied on write —
* one nodes-map copy per draft (see create_document_draft) replaces the
* previous one-copy-per-op behavior, which made transactions with many ops
* (paste, cascade delete) O(N·ops).
*
* @param draft - A draft created via create_document_draft
* @param op - The operation to apply [type, ...args]
* @returns The same draft, for convenience
*/
export function apply_op_to_draft(draft: Document, op: DocumentOperation): Document {
const [type, ...args] = op;
if (type === 'set') {
const [node_id, property] = args[0];
draft.nodes[node_id] = {
...draft.nodes[node_id],
[property]: structuredClone(args[1])
};
} else if (type === 'create') {
draft.nodes[args[0].id] = structuredClone(args[0]);
} else if (type === 'delete') {
delete draft.nodes[args[0]];
}
return draft;
}
/**
* Applies an operation to a document and returns the new document.
* Uses copy-on-write semantics.
*
* @param doc - The document to apply the operation to
* @param op - The operation to apply [type, ...args]
* @returns The new document with the operation applied
*/
export function apply_op(doc: Document, op: DocumentOperation): Document {
return apply_op_to_draft(create_document_draft(doc), op);
}
/**
* Counts how many times a node is referenced in the document.
*/
export function count_references(schema: DocumentSchema, doc: Document, node_id: NodeId): number {
let count = 0;
for (const node of Object.values(doc.nodes)) {
for (const [property, value] of Object.entries(node)) {
if (property === 'id' || property === 'type') continue;
const prop_type = property_type(schema, node.type, property);
if (prop_type === 'node_array') {
count += value.nodes.filter((id: NodeId) => id === node_id).length;
} else if (prop_type === 'node' && value === node_id) {
count += 1;
}
if ((prop_type === 'text' || prop_type === 'node_array') && value) {
count += [...value.marks, ...value.annotations].filter(
(range) => range.node_id === node_id
).length;
}
}
}
return count;
}
/**
* Whether a mark can be switched between these types.
*/
export function can_switch_mark_type(
schema: DocumentSchema,
from_type: string,
to_type: string
): boolean {
const from_schema = schema[from_type];
const to_schema = schema[to_type];
return (
from_schema?.kind === 'mark' &&
to_schema?.kind === 'mark' &&
Object.keys(from_schema.properties ?? {}).length === 0 &&
Object.keys(to_schema.properties ?? {}).length === 0
);
}
/**
* An attachment (mark or annotation) enriched with its index in the parent
* attachment array and the resolved payload node.
*/
export type SelectedAttachment = Attachment & { index: number; node: DocumentNode };
/**
* Gets ranges of the given key ('marks' or 'annotations') touched by the
* current selection.
*
* Non-collapsed selections use strict half-open range intersection, so merely
* adjacent boundaries do not count as touching. Collapsed text carets are only
* inside a range when they are strictly between start and end; a caret at
* either boundary is not active.
*/
function get_selected_ranges(
schema: DocumentSchema,
doc: Document,
selection: Selection | null | undefined,
key: 'marks' | 'annotations'
): SelectedAttachment[] {
if (selection?.type !== 'text' && selection?.type !== 'node') return [];
const range = get_selection_range(selection);
if (!range) return [];
const annotated_prop = get(schema, doc, selection.path);
const ranges = annotated_prop?.[key] ?? [];
const is_collapsed = range.start_offset === range.end_offset;
return ranges
.map((attachment: Attachment, index: number) => {
const node = doc.nodes[attachment.node_id];
return {
...attachment,
index,
node
};
})
.filter(({ start_offset, end_offset }: SelectedAttachment) => {
if (is_collapsed) {
return start_offset < range.start_offset && end_offset > range.start_offset;
}
return start_offset < range.end_offset && end_offset > range.start_offset;
});
}
/**
* Gets marks touched by the current selection.
*/
export function get_selected_marks(
schema: DocumentSchema,
doc: Document,
selection?: Selection | null
): SelectedAttachment[] {
return get_selected_ranges(schema, doc, selection, 'marks');
}
/**
* Gets annotations touched by the current selection.
*/
export function get_selected_annotations(
schema: DocumentSchema,
doc: Document,
selection?: Selection | null
): SelectedAttachment[] {
return get_selected_ranges(schema, doc, selection, 'annotations');
}
/**
* Node types represented in the selected ranges.
*/
export function get_selected_range_types(selected_ranges: SelectedAttachment[]): Set<string> {
return new Set(
selected_ranges.map(({ node }) => node?.type).filter((type): type is string => Boolean(type))
);
}
/**
* Counts references to a node, excluding nodes marked for deletion.
*/
export function count_references_excluding_deleted(
schema: DocumentSchema,
doc: Document,
target_node_id: NodeId,
nodes_to_delete: Record<NodeId, boolean>
): number {
let count = 0;
for (const node of Object.values(doc.nodes)) {
if (nodes_to_delete[node.id]) continue;
for (const [property, value] of Object.entries(node)) {
if (property === 'id' || property === 'type') continue;
const prop_type = property_type(schema, node.type, property);
if (prop_type === 'node_array') {
count += value.nodes.filter((id: NodeId) => id === target_node_id).length;
} else if (prop_type === 'node' && value === target_node_id) {
count += 1;
}
if ((prop_type === 'text' || prop_type === 'node_array') && value) {
count += [...value.marks, ...value.annotations].filter(
(range) => range.node_id === target_node_id
).length;
}
}
}
return count;
}
/**
* Iterates all node references going out of a node, invoking the visitor
* once per occurrence (multiplicity matters for reference counting).
* Covers the same reference kinds as count_references_excluding_deleted:
* a `node` property, `node_array` .nodes ids, and the mark/annotation
* node_ids carried on `text` and `node_array` properties.
*/
export function visit_node_references(
schema: DocumentSchema,
node: DocumentNode,
visit: (referenced_id: NodeId) => void
): void {
const node_schema = schema[node.type];
if (!node_schema) return;
for (const [property, prop_def] of Object.entries(node_schema.properties)) {
const value = node[property];
if (value === undefined || value === null) continue;
const prop_type = prop_def.type;
if (prop_type === 'node_array') {
for (const id of value.nodes) visit(id);
} else if (prop_type === 'node' && typeof value === 'string') {
visit(value);
}
if ((prop_type === 'text' || prop_type === 'node_array') && value) {
for (const range of value.marks) visit(range.node_id);
for (const range of value.annotations) visit(range.node_id);
}