@folijs/core 0.1.0 → 0.2.0

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 (133) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/document.d.ts +5 -4
  3. package/dist/document.d.ts.map +1 -1
  4. package/dist/document.js +30 -8
  5. package/dist/document.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/model/attrs.d.ts +5 -0
  11. package/dist/model/attrs.d.ts.map +1 -1
  12. package/dist/model/attrs.js +17 -0
  13. package/dist/model/attrs.js.map +1 -1
  14. package/dist/model/content.d.ts +10 -0
  15. package/dist/model/content.d.ts.map +1 -1
  16. package/dist/model/content.js +44 -0
  17. package/dist/model/content.js.map +1 -1
  18. package/dist/model/fragment.d.ts +2 -0
  19. package/dist/model/fragment.d.ts.map +1 -1
  20. package/dist/model/fragment.js +8 -0
  21. package/dist/model/fragment.js.map +1 -1
  22. package/dist/model/index.d.ts +1 -1
  23. package/dist/model/index.d.ts.map +1 -1
  24. package/dist/model/index.js +1 -1
  25. package/dist/model/index.js.map +1 -1
  26. package/dist/model/mark.d.ts.map +1 -1
  27. package/dist/model/mark.js +4 -3
  28. package/dist/model/mark.js.map +1 -1
  29. package/dist/model/node.d.ts +12 -0
  30. package/dist/model/node.d.ts.map +1 -1
  31. package/dist/model/node.js +35 -3
  32. package/dist/model/node.js.map +1 -1
  33. package/dist/model/resolvedpos.d.ts +26 -2
  34. package/dist/model/resolvedpos.d.ts.map +1 -1
  35. package/dist/model/resolvedpos.js +54 -2
  36. package/dist/model/resolvedpos.js.map +1 -1
  37. package/dist/model/schema.d.ts +25 -0
  38. package/dist/model/schema.d.ts.map +1 -1
  39. package/dist/model/schema.js +23 -0
  40. package/dist/model/schema.js.map +1 -1
  41. package/dist/model/slice.d.ts +7 -0
  42. package/dist/model/slice.d.ts.map +1 -1
  43. package/dist/model/slice.js +53 -0
  44. package/dist/model/slice.js.map +1 -1
  45. package/dist/schema.d.ts +62 -7
  46. package/dist/schema.d.ts.map +1 -1
  47. package/dist/schema.js +82 -8
  48. package/dist/schema.js.map +1 -1
  49. package/dist/state/attempt.d.ts +4 -0
  50. package/dist/state/attempt.d.ts.map +1 -0
  51. package/dist/state/attempt.js +19 -0
  52. package/dist/state/attempt.js.map +1 -0
  53. package/dist/state/commands.d.ts +18 -3
  54. package/dist/state/commands.d.ts.map +1 -1
  55. package/dist/state/commands.js +199 -44
  56. package/dist/state/commands.js.map +1 -1
  57. package/dist/state/editor.d.ts +24 -0
  58. package/dist/state/editor.d.ts.map +1 -1
  59. package/dist/state/editor.js +14 -1
  60. package/dist/state/editor.js.map +1 -1
  61. package/dist/state/format.d.ts +27 -0
  62. package/dist/state/format.d.ts.map +1 -0
  63. package/dist/state/format.js +144 -0
  64. package/dist/state/format.js.map +1 -0
  65. package/dist/state/history.js +2 -2
  66. package/dist/state/history.js.map +1 -1
  67. package/dist/state/index.d.ts +5 -2
  68. package/dist/state/index.d.ts.map +1 -1
  69. package/dist/state/index.js +5 -2
  70. package/dist/state/index.js.map +1 -1
  71. package/dist/state/links.d.ts +42 -0
  72. package/dist/state/links.d.ts.map +1 -0
  73. package/dist/state/links.js +186 -0
  74. package/dist/state/links.js.map +1 -0
  75. package/dist/state/lists.d.ts +36 -0
  76. package/dist/state/lists.d.ts.map +1 -0
  77. package/dist/state/lists.js +383 -0
  78. package/dist/state/lists.js.map +1 -0
  79. package/dist/state/selection.d.ts +18 -2
  80. package/dist/state/selection.d.ts.map +1 -1
  81. package/dist/state/selection.js +63 -2
  82. package/dist/state/selection.js.map +1 -1
  83. package/dist/state/state.d.ts.map +1 -1
  84. package/dist/state/state.js +12 -2
  85. package/dist/state/state.js.map +1 -1
  86. package/dist/transform/index.d.ts +2 -1
  87. package/dist/transform/index.d.ts.map +1 -1
  88. package/dist/transform/index.js +2 -1
  89. package/dist/transform/index.js.map +1 -1
  90. package/dist/transform/stepmap.d.ts +8 -6
  91. package/dist/transform/stepmap.d.ts.map +1 -1
  92. package/dist/transform/stepmap.js +18 -15
  93. package/dist/transform/stepmap.js.map +1 -1
  94. package/dist/transform/steps.d.ts +27 -2
  95. package/dist/transform/steps.d.ts.map +1 -1
  96. package/dist/transform/steps.js +115 -4
  97. package/dist/transform/steps.js.map +1 -1
  98. package/dist/transform/structure.d.ts +26 -0
  99. package/dist/transform/structure.d.ts.map +1 -0
  100. package/dist/transform/structure.js +116 -0
  101. package/dist/transform/structure.js.map +1 -0
  102. package/dist/transform/transform.d.ts +34 -11
  103. package/dist/transform/transform.d.ts.map +1 -1
  104. package/dist/transform/transform.js +145 -18
  105. package/dist/transform/transform.js.map +1 -1
  106. package/package.json +1 -1
  107. package/src/document.ts +34 -8
  108. package/src/index.ts +14 -0
  109. package/src/model/attrs.ts +19 -0
  110. package/src/model/content.ts +56 -0
  111. package/src/model/fragment.ts +7 -0
  112. package/src/model/index.ts +1 -1
  113. package/src/model/mark.ts +3 -2
  114. package/src/model/node.ts +42 -2
  115. package/src/model/resolvedpos.ts +55 -2
  116. package/src/model/schema.ts +43 -0
  117. package/src/model/slice.ts +81 -1
  118. package/src/schema.ts +135 -12
  119. package/src/state/attempt.ts +22 -0
  120. package/src/state/commands.ts +209 -47
  121. package/src/state/editor.ts +38 -2
  122. package/src/state/format.ts +133 -0
  123. package/src/state/history.ts +3 -3
  124. package/src/state/index.ts +31 -0
  125. package/src/state/links.ts +185 -0
  126. package/src/state/lists.ts +427 -0
  127. package/src/state/selection.ts +72 -3
  128. package/src/state/state.ts +11 -2
  129. package/src/transform/index.ts +8 -0
  130. package/src/transform/stepmap.ts +18 -12
  131. package/src/transform/steps.ts +126 -3
  132. package/src/transform/structure.ts +135 -0
  133. package/src/transform/transform.ts +165 -16
@@ -19,6 +19,13 @@ export interface NodeSpec {
19
19
  */
20
20
  marks?: string;
21
21
  attrs?: AttributeSpecs;
22
+ /**
23
+ * Edited as one unit: the caret never enters it. Leaf nodes are atoms whatever this says;
24
+ * set it on a non-leaf node whose content is managed by code.
25
+ */
26
+ atom?: boolean;
27
+ /** Whether a NodeSelection may select this node (default true; text is never selectable). */
28
+ selectable?: boolean;
22
29
  }
23
30
 
24
31
  export interface MarkSpec {
@@ -30,6 +37,11 @@ export interface MarkSpec {
30
37
  * Defaults to the mark itself (at most one mark of a type per node).
31
38
  */
32
39
  excludes?: string;
40
+ /**
41
+ * Whether text typed at the end of this mark gets it too (default true). A link is not
42
+ * inclusive: typing right after it continues as plain text.
43
+ */
44
+ inclusive?: boolean;
33
45
  }
34
46
 
35
47
  export interface SchemaSpec {
@@ -77,6 +89,16 @@ export class NodeType {
77
89
  return this.isBlock && this.inlineContent;
78
90
  }
79
91
 
92
+ /** Edited as one unit (leaf nodes, and nodes whose spec says `atom`). */
93
+ get isAtom(): boolean {
94
+ return this.isLeaf || !!this.spec.atom;
95
+ }
96
+
97
+ /** True when some attribute has no default (the type cannot be created without attrs). */
98
+ hasRequiredAttrs(): boolean {
99
+ return Object.values(this.spec.attrs ?? {}).some((spec) => !("default" in spec));
100
+ }
101
+
80
102
  /** Creates a validated node. Throws FoliDocumentError on bad attrs or content. */
81
103
  create(
82
104
  attrs?: Attrs | null,
@@ -94,6 +116,23 @@ export class NodeType {
94
116
  );
95
117
  }
96
118
 
119
+ /**
120
+ * Creates a node without checking its content. Attributes are still validated.
121
+ * @internal For transforms whose node ends up complete: a wrapper the wrapped blocks fill
122
+ * (validated when they are inserted) or the open half of a split (validated when the replace
123
+ * joins it). Steps do not validate closed nodes inside a slice: a node left incomplete here
124
+ * would make an invalid document.
125
+ */
126
+ createOpen(attrs?: Attrs | null, content?: Fragment | Node | readonly Node[] | null): Node {
127
+ if (this.isText) throw new RangeError("Use Schema.text to create text nodes");
128
+ return new Node(
129
+ this,
130
+ computeAttrs(this.spec.attrs, attrs ?? undefined, `${this.name}.attrs`),
131
+ Fragment.from(content),
132
+ Mark.none,
133
+ );
134
+ }
135
+
97
136
  /** True if `content` matches the content expression and only carries allowed marks. */
98
137
  validContent(content: Fragment): boolean {
99
138
  if (!this.contentMatch.matchFragment(content)?.validEnd) return false;
@@ -159,6 +198,10 @@ export class MarkType {
159
198
  return new Mark(this, computeAttrs(this.spec.attrs, attrs ?? undefined, `${this.name}.attrs`));
160
199
  }
161
200
 
201
+ get inclusive(): boolean {
202
+ return this.spec.inclusive ?? true;
203
+ }
204
+
162
205
  excludes(other: MarkType): boolean {
163
206
  return this.excluded.includes(other);
164
207
  }
@@ -1,5 +1,5 @@
1
1
  import { Fragment } from "./fragment.js";
2
- import type { NodeJSON } from "./node.js";
2
+ import type { Node, NodeJSON } from "./node.js";
3
3
 
4
4
  export interface SliceJSON {
5
5
  content: NodeJSON[];
@@ -26,6 +26,31 @@ export class Slice {
26
26
  return this.content.size - this.openStart - this.openEnd;
27
27
  }
28
28
 
29
+ /**
30
+ * This slice with `fragment` inserted at `pos` (in slice positions): into the node that holds
31
+ * `pos`, which must accept it. Null when the content would not be valid there.
32
+ */
33
+ insertAt(pos: number, fragment: Fragment): Slice | null {
34
+ const content = insertInto(this.content, pos + this.openStart, fragment, {
35
+ parent: null,
36
+ level: 0,
37
+ onStart: true,
38
+ onEnd: true,
39
+ openStart: this.openStart,
40
+ openEnd: this.openEnd,
41
+ });
42
+ return content && new Slice(content, this.openStart, this.openEnd);
43
+ }
44
+
45
+ /** This slice without the flat range `from..to` (slice positions). */
46
+ removeBetween(from: number, to: number): Slice {
47
+ return new Slice(
48
+ removeRange(this.content, from + this.openStart, to + this.openStart),
49
+ this.openStart,
50
+ this.openEnd,
51
+ );
52
+ }
53
+
29
54
  eq(other: Slice): boolean {
30
55
  return (
31
56
  this.content.eq(other.content) &&
@@ -38,3 +63,58 @@ export class Slice {
38
63
  return { content: this.content.toJSON(), openStart: this.openStart, openEnd: this.openEnd };
39
64
  }
40
65
  }
66
+
67
+ interface InsertPath {
68
+ /** The node holding `content`, null at the top of the slice. */
69
+ parent: Node | null;
70
+ /** Depth of `parent` in the slice (1 for a top-level node). */
71
+ level: number;
72
+ /** Whether `parent` is on the slice's first-child chain, and on its last-child chain. */
73
+ onStart: boolean;
74
+ onEnd: boolean;
75
+ openStart: number;
76
+ openEnd: number;
77
+ }
78
+
79
+ function insertInto(
80
+ content: Fragment,
81
+ dist: number,
82
+ insert: Fragment,
83
+ path: InsertPath,
84
+ ): Fragment | null {
85
+ const { index, offset } = content.findIndex(dist);
86
+ const child = content.maybeChild(index);
87
+ if (offset === dist || !child || child.isText) {
88
+ const result = content.cut(0, dist).append(insert).append(content.cut(dist));
89
+ const { parent, level } = path;
90
+ // An open node of the slice is completed by the document around the replaced range;
91
+ // replace validates it once joined. Checking it here would reject valid content.
92
+ const open = (path.onStart && level <= path.openStart) || (path.onEnd && level <= path.openEnd);
93
+ return parent && !open && !parent.type.validContent(result) ? null : result;
94
+ }
95
+ const inner = insertInto(child.content, dist - offset - 1, insert, {
96
+ ...path,
97
+ parent: child,
98
+ level: path.level + 1,
99
+ onStart: path.onStart && index === 0,
100
+ onEnd: path.onEnd && index === content.childCount - 1,
101
+ });
102
+ return inner && content.replaceChild(index, child.copy(inner));
103
+ }
104
+
105
+ function removeRange(content: Fragment, from: number, to: number): Fragment {
106
+ const { index, offset } = content.findIndex(from);
107
+ const child = content.maybeChild(index);
108
+ const { index: indexTo, offset: offsetTo } = content.findIndex(to);
109
+ if (offset === from || !child || child.isText) {
110
+ if (offsetTo !== to && !content.child(indexTo).isText) {
111
+ throw new RangeError("Removing a non-flat range");
112
+ }
113
+ return content.cut(0, from).append(content.cut(to));
114
+ }
115
+ if (index !== indexTo) throw new RangeError("Removing a non-flat range");
116
+ return content.replaceChild(
117
+ index,
118
+ child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)),
119
+ );
120
+ }
package/src/schema.ts CHANGED
@@ -1,21 +1,68 @@
1
1
  import { Schema } from "./model/index.js";
2
2
 
3
3
  /**
4
- * Schema v1: the node and mark types a Foli document may contain, defined through the same
5
- * spec API third-party extensions use. The JSON types below describe the persisted shape of v1
6
- * content ({type, attrs, content, text, marks}); that shape is permanent.
4
+ * Schema v2: the node and mark types a Foli document may contain, defined through the same spec
5
+ * API third-party extensions use. The JSON types below describe the persisted shape of v2
6
+ * content ({type, attrs, content, text, marks}); that shape is permanent. v1 content (0.1.0) is
7
+ * valid v2 content: v2 only adds types and attributes with defaults.
7
8
  */
8
9
 
9
- export const MARK_TYPES = ["bold", "italic", "underline", "strike"] as const;
10
+ /** Marks without attributes. */
11
+ export const SIMPLE_MARK_TYPES = ["bold", "italic", "underline", "strike"] as const;
12
+ export type SimpleMarkName = (typeof SIMPLE_MARK_TYPES)[number];
13
+
14
+ /** Every mark type, in canonical order (the order of mark sets and of nesting when rendered). */
15
+ export const MARK_TYPES = ["link", ...SIMPLE_MARK_TYPES, "textColor", "highlight"] as const;
10
16
  export type MarkName = (typeof MARK_TYPES)[number];
11
17
 
12
18
  export const HEADING_LEVELS = [1, 2, 3, 4, 5, 6] as const;
13
19
  export type HeadingLevel = (typeof HEADING_LEVELS)[number];
14
20
 
21
+ /** `start` and `end` follow the text direction (left and right in left-to-right text). */
22
+ export const ALIGNMENTS = ["start", "center", "end", "justify"] as const;
23
+ export type Alignment = (typeof ALIGNMENTS)[number];
24
+
25
+ /** URL schemes a link may use; anything else (javascript:, data:, file:…) is rejected. */
26
+ export const SAFE_LINK_PROTOCOLS = ["http:", "https:", "mailto:", "tel:"] as const;
27
+
28
+ /**
29
+ * Whether `href` may be stored in a link: an absolute URL with a safe protocol, or a relative
30
+ * URL (path, `?query`, `#fragment`, `//host`). Rejects control characters and spaces anywhere
31
+ * (browsers strip tabs and newlines inside schemes, so `java\tscript:` would run) and
32
+ * backslashes (some browsers read `\\` as `//`).
33
+ */
34
+ export function isSafeHref(href: unknown): href is string {
35
+ if (typeof href !== "string" || !href || href.length > 8192) return false;
36
+ // Control characters, spaces and backslashes are never part of a URL we keep.
37
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is the point.
38
+ if (/[\u0000- \u007f-\u009f\\]/.test(href)) return false;
39
+ const scheme = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(href);
40
+ if (!scheme) return true; // relative
41
+ return (SAFE_LINK_PROTOCOLS as readonly string[]).includes(`${scheme[1]?.toLowerCase()}:`);
42
+ }
43
+
44
+ /** Whether `color` is a canonical color value: `#rrggbb`, lowercase. */
45
+ export function isColor(color: unknown): color is string {
46
+ return typeof color === "string" && /^#[0-9a-f]{6}$/.test(color);
47
+ }
48
+
49
+ const align = {
50
+ default: "start",
51
+ validate: (value: unknown) =>
52
+ (ALIGNMENTS as readonly unknown[]).includes(value)
53
+ ? undefined
54
+ : `align must be one of ${ALIGNMENTS.join(", ")}`,
55
+ };
56
+
57
+ const color = {
58
+ validate: (value: unknown) =>
59
+ isColor(value) ? undefined : "color must be a lowercase #rrggbb value",
60
+ };
61
+
15
62
  export const schema = new Schema({
16
63
  nodes: {
17
64
  doc: { content: "block+" },
18
- paragraph: { group: "block", content: "inline*" },
65
+ paragraph: { group: "block", content: "inline*", attrs: { align } },
19
66
  heading: {
20
67
  group: "block",
21
68
  content: "inline*",
@@ -26,21 +73,70 @@ export const schema = new Schema({
26
73
  ? undefined
27
74
  : "heading level must be an integer from 1 to 6",
28
75
  },
76
+ align,
29
77
  },
30
78
  },
79
+ bulletList: { group: "block", content: "listItem+" },
80
+ orderedList: {
81
+ group: "block",
82
+ content: "listItem+",
83
+ attrs: {
84
+ start: {
85
+ default: 1,
86
+ validate: (value) =>
87
+ Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 99_999
88
+ ? undefined
89
+ : "start must be an integer from 0 to 99999",
90
+ },
91
+ },
92
+ },
93
+ // A list item starts with a paragraph; nested lists and other blocks may follow.
94
+ listItem: { content: "paragraph block*" },
95
+ horizontalRule: { group: "block" },
31
96
  text: { group: "inline" },
32
- hardBreak: { group: "inline", inline: true },
97
+ hardBreak: { group: "inline", inline: true, selectable: false },
33
98
  // An explicit page break: inline like a hard break (as in DOCX, `<w:br w:type="page"/>`);
34
99
  // the line it ends is the last on its page.
35
- pageBreak: { group: "inline", inline: true },
100
+ pageBreak: { group: "inline", inline: true, selectable: false },
101
+ },
102
+ marks: {
103
+ // First, so a link wraps the formatting inside it when rendered.
104
+ link: {
105
+ attrs: {
106
+ href: {
107
+ validate: (value) =>
108
+ isSafeHref(value)
109
+ ? undefined
110
+ : "href must be a relative URL or use http, https, mailto or tel",
111
+ },
112
+ },
113
+ inclusive: false,
114
+ },
115
+ bold: {},
116
+ italic: {},
117
+ underline: {},
118
+ strike: {},
119
+ textColor: { attrs: { color } },
120
+ highlight: { attrs: { color } },
36
121
  },
37
- marks: Object.fromEntries(MARK_TYPES.map((name) => [name, {}])),
38
122
  });
39
123
 
40
- export interface MarkNameJSON {
41
- type: MarkName;
124
+ export interface SimpleMarkJSON {
125
+ type: SimpleMarkName;
126
+ }
127
+
128
+ export interface LinkMarkJSON {
129
+ type: "link";
130
+ attrs: { href: string };
131
+ }
132
+
133
+ export interface ColorMarkJSON {
134
+ type: "textColor" | "highlight";
135
+ attrs: { color: string };
42
136
  }
43
137
 
138
+ export type MarkNameJSON = SimpleMarkJSON | LinkMarkJSON | ColorMarkJSON;
139
+
44
140
  export interface TextJSON {
45
141
  type: "text";
46
142
  text: string;
@@ -59,18 +155,45 @@ export interface PageBreakJSON {
59
155
 
60
156
  export type InlineJSON = TextJSON | HardBreakJSON | PageBreakJSON;
61
157
 
158
+ /** Attributes equal to their default (`align: "start"`, `start: 1`) are omitted. */
62
159
  export interface ParagraphJSON {
63
160
  type: "paragraph";
161
+ attrs?: { align?: Alignment };
64
162
  content?: InlineJSON[];
65
163
  }
66
164
 
67
165
  export interface HeadingJSON {
68
166
  type: "heading";
69
- attrs: { level: HeadingLevel };
167
+ attrs: { level: HeadingLevel; align?: Alignment };
70
168
  content?: InlineJSON[];
71
169
  }
72
170
 
73
- export type BlockJSON = ParagraphJSON | HeadingJSON;
171
+ export interface ListItemJSON {
172
+ type: "listItem";
173
+ content: [ParagraphJSON, ...BlockJSON[]];
174
+ }
175
+
176
+ export interface BulletListJSON {
177
+ type: "bulletList";
178
+ content: ListItemJSON[];
179
+ }
180
+
181
+ export interface OrderedListJSON {
182
+ type: "orderedList";
183
+ attrs?: { start?: number };
184
+ content: ListItemJSON[];
185
+ }
186
+
187
+ export interface HorizontalRuleJSON {
188
+ type: "horizontalRule";
189
+ }
190
+
191
+ export type BlockJSON =
192
+ | ParagraphJSON
193
+ | HeadingJSON
194
+ | BulletListJSON
195
+ | OrderedListJSON
196
+ | HorizontalRuleJSON;
74
197
 
75
198
  export interface DocJSON {
76
199
  type: "doc";
@@ -0,0 +1,22 @@
1
+ import { TransformError } from "../transform/transform.js";
2
+ import type { EditorState, Transaction } from "./state.js";
3
+
4
+ /** @internal Runs `build`; a TransformError, or a transaction that changes nothing, does not apply. */
5
+ export function attempt(
6
+ state: EditorState,
7
+ dispatch: ((tr: Transaction) => void) | undefined,
8
+ build: (tr: Transaction) => void,
9
+ ): boolean {
10
+ const tr = state.tr;
11
+ try {
12
+ build(tr);
13
+ } catch (error) {
14
+ if (error instanceof TransformError) return false;
15
+ throw error;
16
+ }
17
+ if (!tr.docChanged && tr.selection.eq(state.selection) && tr.storedMarks === state.storedMarks) {
18
+ return false;
19
+ }
20
+ dispatch?.(tr);
21
+ return true;
22
+ }