@folijs/core 0.1.0 → 0.3.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 (189) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/dist/document.d.ts +10 -15
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +41 -19
  6. package/dist/document.js.map +1 -1
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/model/attrs.d.ts +5 -0
  12. package/dist/model/attrs.d.ts.map +1 -1
  13. package/dist/model/attrs.js +17 -0
  14. package/dist/model/attrs.js.map +1 -1
  15. package/dist/model/content.d.ts +10 -0
  16. package/dist/model/content.d.ts.map +1 -1
  17. package/dist/model/content.js +44 -0
  18. package/dist/model/content.js.map +1 -1
  19. package/dist/model/fragment.d.ts +7 -2
  20. package/dist/model/fragment.d.ts.map +1 -1
  21. package/dist/model/fragment.js +13 -2
  22. package/dist/model/fragment.js.map +1 -1
  23. package/dist/model/index.d.ts +1 -1
  24. package/dist/model/index.d.ts.map +1 -1
  25. package/dist/model/index.js +1 -1
  26. package/dist/model/index.js.map +1 -1
  27. package/dist/model/mark.d.ts.map +1 -1
  28. package/dist/model/mark.js +4 -3
  29. package/dist/model/mark.js.map +1 -1
  30. package/dist/model/node.d.ts +13 -1
  31. package/dist/model/node.d.ts.map +1 -1
  32. package/dist/model/node.js +35 -3
  33. package/dist/model/node.js.map +1 -1
  34. package/dist/model/resolvedpos.d.ts +26 -2
  35. package/dist/model/resolvedpos.d.ts.map +1 -1
  36. package/dist/model/resolvedpos.js +54 -2
  37. package/dist/model/resolvedpos.js.map +1 -1
  38. package/dist/model/schema.d.ts +25 -0
  39. package/dist/model/schema.d.ts.map +1 -1
  40. package/dist/model/schema.js +23 -0
  41. package/dist/model/schema.js.map +1 -1
  42. package/dist/model/slice.d.ts +7 -0
  43. package/dist/model/slice.d.ts.map +1 -1
  44. package/dist/model/slice.js +53 -0
  45. package/dist/model/slice.js.map +1 -1
  46. package/dist/schema.d.ts +72 -8
  47. package/dist/schema.d.ts.map +1 -1
  48. package/dist/schema.js +93 -9
  49. package/dist/schema.js.map +1 -1
  50. package/dist/state/attempt.d.ts +4 -0
  51. package/dist/state/attempt.d.ts.map +1 -0
  52. package/dist/state/attempt.js +19 -0
  53. package/dist/state/attempt.js.map +1 -0
  54. package/dist/state/commands.d.ts +21 -5
  55. package/dist/state/commands.d.ts.map +1 -1
  56. package/dist/state/commands.js +260 -68
  57. package/dist/state/commands.js.map +1 -1
  58. package/dist/state/editor.d.ts +41 -7
  59. package/dist/state/editor.d.ts.map +1 -1
  60. package/dist/state/editor.js +51 -10
  61. package/dist/state/editor.js.map +1 -1
  62. package/dist/state/format.d.ts +13 -0
  63. package/dist/state/format.d.ts.map +1 -0
  64. package/dist/state/format.js +20 -0
  65. package/dist/state/format.js.map +1 -0
  66. package/dist/state/history.js +2 -2
  67. package/dist/state/history.js.map +1 -1
  68. package/dist/state/index.d.ts +10 -3
  69. package/dist/state/index.d.ts.map +1 -1
  70. package/dist/state/index.js +10 -3
  71. package/dist/state/index.js.map +1 -1
  72. package/dist/state/links.d.ts +42 -0
  73. package/dist/state/links.d.ts.map +1 -0
  74. package/dist/state/links.js +194 -0
  75. package/dist/state/links.js.map +1 -0
  76. package/dist/state/lists.d.ts +23 -0
  77. package/dist/state/lists.d.ts.map +1 -0
  78. package/dist/state/lists.js +34 -0
  79. package/dist/state/lists.js.map +1 -0
  80. package/dist/state/mark.d.ts +25 -0
  81. package/dist/state/mark.d.ts.map +1 -0
  82. package/dist/state/mark.js +40 -0
  83. package/dist/state/mark.js.map +1 -0
  84. package/dist/state/selection.d.ts +18 -2
  85. package/dist/state/selection.d.ts.map +1 -1
  86. package/dist/state/selection.js +63 -2
  87. package/dist/state/selection.js.map +1 -1
  88. package/dist/state/state.d.ts.map +1 -1
  89. package/dist/state/state.js +23 -2
  90. package/dist/state/state.js.map +1 -1
  91. package/dist/state/word.d.ts +72 -0
  92. package/dist/state/word.d.ts.map +1 -0
  93. package/dist/state/word.js +173 -0
  94. package/dist/state/word.js.map +1 -0
  95. package/dist/state/wordclip.d.ts +43 -0
  96. package/dist/state/wordclip.d.ts.map +1 -0
  97. package/dist/state/wordclip.js +412 -0
  98. package/dist/state/wordclip.js.map +1 -0
  99. package/dist/state/wordformat.d.ts +136 -0
  100. package/dist/state/wordformat.d.ts.map +1 -0
  101. package/dist/state/wordformat.js +846 -0
  102. package/dist/state/wordformat.js.map +1 -0
  103. package/dist/transform/index.d.ts +2 -1
  104. package/dist/transform/index.d.ts.map +1 -1
  105. package/dist/transform/index.js +2 -1
  106. package/dist/transform/index.js.map +1 -1
  107. package/dist/transform/stepmap.d.ts +8 -6
  108. package/dist/transform/stepmap.d.ts.map +1 -1
  109. package/dist/transform/stepmap.js +18 -15
  110. package/dist/transform/stepmap.js.map +1 -1
  111. package/dist/transform/steps.d.ts +27 -2
  112. package/dist/transform/steps.d.ts.map +1 -1
  113. package/dist/transform/steps.js +115 -4
  114. package/dist/transform/steps.js.map +1 -1
  115. package/dist/transform/structure.d.ts +26 -0
  116. package/dist/transform/structure.d.ts.map +1 -0
  117. package/dist/transform/structure.js +116 -0
  118. package/dist/transform/structure.js.map +1 -0
  119. package/dist/transform/transform.d.ts +34 -11
  120. package/dist/transform/transform.d.ts.map +1 -1
  121. package/dist/transform/transform.js +145 -18
  122. package/dist/transform/transform.js.map +1 -1
  123. package/dist/v3/check.d.ts +33 -0
  124. package/dist/v3/check.d.ts.map +1 -0
  125. package/dist/v3/check.js +90 -0
  126. package/dist/v3/check.js.map +1 -0
  127. package/dist/v3/document.d.ts +217 -0
  128. package/dist/v3/document.d.ts.map +1 -0
  129. package/dist/v3/document.js +225 -0
  130. package/dist/v3/document.js.map +1 -0
  131. package/dist/v3/index.d.ts +6 -0
  132. package/dist/v3/index.d.ts.map +1 -0
  133. package/dist/v3/index.js +6 -0
  134. package/dist/v3/index.js.map +1 -0
  135. package/dist/v3/migrate.d.ts +19 -0
  136. package/dist/v3/migrate.d.ts.map +1 -0
  137. package/dist/v3/migrate.js +227 -0
  138. package/dist/v3/migrate.js.map +1 -0
  139. package/dist/v3/resolve.d.ts +129 -0
  140. package/dist/v3/resolve.d.ts.map +1 -0
  141. package/dist/v3/resolve.js +534 -0
  142. package/dist/v3/resolve.js.map +1 -0
  143. package/dist/v3/schema.d.ts +27 -0
  144. package/dist/v3/schema.d.ts.map +1 -0
  145. package/dist/v3/schema.js +429 -0
  146. package/dist/v3/schema.js.map +1 -0
  147. package/dist/v3/units.d.ts +16 -0
  148. package/dist/v3/units.d.ts.map +1 -0
  149. package/dist/v3/units.js +28 -0
  150. package/dist/v3/units.js.map +1 -0
  151. package/package.json +1 -1
  152. package/src/document.ts +49 -23
  153. package/src/index.ts +17 -6
  154. package/src/model/attrs.ts +19 -0
  155. package/src/model/content.ts +56 -0
  156. package/src/model/fragment.ts +18 -3
  157. package/src/model/index.ts +1 -1
  158. package/src/model/mark.ts +3 -2
  159. package/src/model/node.ts +48 -3
  160. package/src/model/resolvedpos.ts +55 -2
  161. package/src/model/schema.ts +43 -0
  162. package/src/model/slice.ts +81 -1
  163. package/src/schema.ts +148 -13
  164. package/src/state/attempt.ts +22 -0
  165. package/src/state/commands.ts +287 -69
  166. package/src/state/editor.ts +103 -21
  167. package/src/state/format.ts +35 -0
  168. package/src/state/history.ts +3 -3
  169. package/src/state/index.ts +63 -1
  170. package/src/state/links.ts +193 -0
  171. package/src/state/lists.ts +50 -0
  172. package/src/state/mark.ts +47 -0
  173. package/src/state/selection.ts +72 -3
  174. package/src/state/state.ts +22 -2
  175. package/src/state/word.ts +245 -0
  176. package/src/state/wordclip.ts +445 -0
  177. package/src/state/wordformat.ts +982 -0
  178. package/src/transform/index.ts +8 -0
  179. package/src/transform/stepmap.ts +18 -12
  180. package/src/transform/steps.ts +126 -3
  181. package/src/transform/structure.ts +135 -0
  182. package/src/transform/transform.ts +165 -16
  183. package/src/v3/check.ts +119 -0
  184. package/src/v3/document.ts +456 -0
  185. package/src/v3/index.ts +33 -0
  186. package/src/v3/migrate.ts +267 -0
  187. package/src/v3/resolve.ts +646 -0
  188. package/src/v3/schema.ts +479 -0
  189. package/src/v3/units.ts +34 -0
@@ -1,12 +1,14 @@
1
+ import type { DocumentSettings, FoliDocumentV2 } from "../document.js";
2
+ import type { Attrs, Node } from "../model/index.js";
3
+ import type { Alignment } from "../schema.js";
1
4
  import {
2
5
  createDocument,
3
- type DocumentSettings,
4
6
  type FoliDocument,
5
7
  parseContent,
6
- SCHEMA_VERSION,
7
- } from "../document.js";
8
- import type { Attrs } from "../model/index.js";
9
- import type { DocJSON } from "../schema.js";
8
+ parseDocument,
9
+ type SectionJSON,
10
+ } from "../v3/document.js";
11
+ import { twipsToMm as mm } from "../v3/units.js";
10
12
  import {
11
13
  baseKeymap,
12
14
  type DeleteUnit,
@@ -24,13 +26,24 @@ import {
24
26
  splitBlock,
25
27
  toggleMark,
26
28
  } from "./commands.js";
29
+ import { setAlign, setHighlight, setTextColor } from "./format.js";
27
30
  import { history, redo, undo } from "./history.js";
31
+ import { removeLink, setLink } from "./links.js";
32
+ import { liftListItem, listKeymap, sinkListItem, toggleList, wrapInList } from "./lists.js";
28
33
  import { TextSelection } from "./selection.js";
29
34
  import { type Command, EditorState, type Plugin, type Transaction } from "./state.js";
35
+ import { type WordEnvelope, wordContext, wordPlugin } from "./word.js";
36
+ import type { ListKind } from "./wordformat.js";
37
+
38
+ /**
39
+ * A document an editor loads: schema v3 (Word's model), or one saved by 0.1.0 or 0.2.0, migrated
40
+ * to v3 when loaded (`parseDocument`).
41
+ */
42
+ export type EditorDocument = FoliDocument | FoliDocumentV2;
30
43
 
31
44
  export interface EditorOptions {
32
- /** Trusted or not, it is validated (`parseContent`) before use. Defaults to an empty document. */
33
- document?: FoliDocument;
45
+ /** Trusted or not, it is validated (and migrated: `parseDocument`). Default: an empty one. */
46
+ document?: EditorDocument;
34
47
  /** Run before the built-in plugins, so their keymaps take precedence. */
35
48
  plugins?: readonly Plugin[];
36
49
  }
@@ -40,7 +53,10 @@ export type EditorListener = (state: EditorState, transactions: readonly Transac
40
53
  /** A headless editor: state, commands, history and change notifications, no DOM. */
41
54
  export interface Editor {
42
55
  readonly state: EditorState;
43
- /** Page size and margins of the current document. */
56
+ /**
57
+ * Page size and margins of the current document. For a schema v3 document, its last
58
+ * section's (the view lays each section out with its own).
59
+ */
44
60
  readonly settings: DocumentSettings;
45
61
  dispatch(tr: Transaction): void;
46
62
  /** Runs a command; returns whether it applied. */
@@ -66,22 +82,81 @@ export interface Editor {
66
82
  selectAll(): boolean;
67
83
  undo(): boolean;
68
84
  redo(): boolean;
85
+ /** Numbers the selected paragraphs as a list ("bulletList" or "orderedList"). */
86
+ wrapInList(kind: ListKind): boolean;
87
+ /** The list buttons: removes the selection's numbering when it is a list of `kind`, else numbers it. */
88
+ toggleList(kind: ListKind): boolean;
89
+ /** Tab in a list: one level deeper. */
90
+ indentListItem(): boolean;
91
+ /** Shift+Tab in a list: one level up (out of the list at the top). */
92
+ outdentListItem(): boolean;
93
+ /**
94
+ * Links the selection to `href` (normalized, then validated: unsafe hrefs do not apply); at
95
+ * a caret in a link, changes it; elsewhere inserts the href as linked text.
96
+ */
97
+ setLink(href: string): boolean;
98
+ /** Removes the links in the selection, or the link around the caret. */
99
+ removeLink(): boolean;
100
+ /** Aligns the selected paragraphs and headings ("start", "center", "end", "justify"). */
101
+ setAlign(align: Alignment): boolean;
102
+ /** Text color (lowercase `#rrggbb`) of the selected or next typed text; null removes it. */
103
+ setTextColor(color: string | null): boolean;
104
+ /** Highlight (`#rrggbb`) of the selected or next typed text; null removes it. */
105
+ setHighlight(color: string | null): boolean;
69
106
  };
70
107
  isMarkActive(type: string): boolean;
71
- /** The current document as a persisted FoliDocument. */
108
+ /** The current document (schema v3). */
72
109
  getDocument(): FoliDocument;
73
- /** Replaces the whole document and resets history. */
74
- setDocument(document: FoliDocument): void;
110
+ /** Replaces the whole document (an older one migrated) and resets history. */
111
+ setDocument(document: EditorDocument): void;
75
112
  subscribe(listener: EditorListener): () => void;
76
113
  }
77
114
 
115
+ /** Word's page when a section leaves it out: Letter, 1 inch margins. */
116
+ const LETTER = { width: 12240, height: 15840, margin: 1440 };
117
+
118
+ /** A section's page setup as page settings (mm; the gutter added to the left margin, as Word does). */
119
+ export function sectionSettings(section: SectionJSON): DocumentSettings {
120
+ const m = section.margins ?? {};
121
+ return {
122
+ pageSize: {
123
+ width: mm(section.pageSize?.width ?? LETTER.width),
124
+ height: mm(section.pageSize?.height ?? LETTER.height),
125
+ },
126
+ margins: {
127
+ top: mm(Math.abs(m.top ?? LETTER.margin)),
128
+ right: mm(m.right ?? LETTER.margin),
129
+ bottom: mm(Math.abs(m.bottom ?? LETTER.margin)),
130
+ left: mm((m.left ?? LETTER.margin) + (m.gutter ?? 0)),
131
+ },
132
+ };
133
+ }
134
+
135
+ interface Loaded {
136
+ doc: Node;
137
+ settings: DocumentSettings;
138
+ envelope: WordEnvelope;
139
+ }
140
+
141
+ /** Validates (and migrates) a document and reads what the editor keeps of it. */
142
+ function load(document: EditorDocument): Loaded {
143
+ const { content, ...envelope } = parseDocument(document);
144
+ return { doc: parseContent(content), settings: sectionSettings(envelope.section), envelope };
145
+ }
146
+
78
147
  export function createEditor({
79
148
  document = createDocument(),
80
149
  plugins = [],
81
150
  }: EditorOptions = {}): Editor {
82
- let settings = document.settings;
83
- const allPlugins = [...plugins, history(), baseKeymap()];
84
- let state = EditorState.create({ doc: parseContent(document.content), plugins: allPlugins });
151
+ let loaded = load(document);
152
+ const pluginsFor = ({ envelope }: Loaded) => [
153
+ ...plugins,
154
+ history(),
155
+ wordPlugin(envelope),
156
+ listKeymap(),
157
+ baseKeymap(),
158
+ ];
159
+ let state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
85
160
  const listeners = new Set<EditorListener>();
86
161
 
87
162
  const notify = (transactions: readonly Transaction[]) => {
@@ -96,7 +171,7 @@ export function createEditor({
96
171
 
97
172
  return {
98
173
  get settings() {
99
- return settings;
174
+ return loaded.settings;
100
175
  },
101
176
  get state() {
102
177
  return state;
@@ -130,17 +205,24 @@ export function createEditor({
130
205
  selectAll: () => run(selectAll),
131
206
  undo: () => run(undo),
132
207
  redo: () => run(redo),
208
+ wrapInList: (kind) => run(wrapInList(kind)),
209
+ toggleList: (kind) => run(toggleList(kind)),
210
+ indentListItem: () => run(sinkListItem),
211
+ outdentListItem: () => run(liftListItem),
212
+ setLink: (href) => run(setLink(href)),
213
+ removeLink: () => run(removeLink),
214
+ setAlign: (align) => run(setAlign(align)),
215
+ setTextColor: (color) => run(setTextColor(color)),
216
+ setHighlight: (color) => run(setHighlight(color)),
133
217
  },
134
218
  isMarkActive: (type) => isMarkActive(state, type),
135
219
  getDocument: () => ({
136
- schemaVersion: SCHEMA_VERSION,
137
- settings,
138
- content: state.doc.toJSON() as DocJSON,
220
+ ...structuredClone(wordContext(state)?.envelope ?? loaded.envelope),
221
+ content: state.doc.toJSON(),
139
222
  }),
140
223
  setDocument(next) {
141
- const doc = parseContent(next.content);
142
- settings = next.settings;
143
- state = EditorState.create({ doc, plugins: allPlugins });
224
+ loaded = load(next);
225
+ state = EditorState.create({ doc: loaded.doc, plugins: pluginsFor(loaded) });
144
226
  notify([]);
145
227
  },
146
228
  subscribe(listener) {
@@ -0,0 +1,35 @@
1
+ import { type Alignment, isColor } from "../schema.js";
2
+ import type { Command, EditorState } from "./state.js";
3
+ import {
4
+ setWordAlign,
5
+ setWordHighlight,
6
+ setWordTextColor,
7
+ wordAlignAt,
8
+ wordHighlightAt,
9
+ wordTextColorAt,
10
+ } from "./wordformat.js";
11
+
12
+ /** The alignment all selected paragraphs show, or null (mixed, or no paragraph). */
13
+ export const alignAt: (state: EditorState) => Alignment | null = wordAlignAt;
14
+
15
+ /** Aligns the selected paragraphs (`start` is the default). */
16
+ export const setAlign: (align: Alignment) => Command = setWordAlign;
17
+
18
+ /** Colors are lowercase `#rrggbb` (an uppercase one is lowered); others do not apply. */
19
+ const colored =
20
+ (set: (color: string | null) => Command) =>
21
+ (color: string | null): Command => {
22
+ const value = color?.toLowerCase() ?? null;
23
+ return value !== null && !isColor(value) ? () => false : set(value);
24
+ };
25
+
26
+ /** Text color (`#rrggbb`) for the selected or next typed text; `null` is Word's Automatic. */
27
+ export const setTextColor = colored(setWordTextColor);
28
+
29
+ /** Highlight (`#rrggbb`) for the selected or next typed text; `null` removes it. */
30
+ export const setHighlight = colored(setWordHighlight);
31
+
32
+ /** The text color or highlight all selected text shows (at a caret, typing's), or null. */
33
+ export function colorAt(state: EditorState, name: "textColor" | "highlight"): string | null {
34
+ return name === "highlight" ? wordHighlightAt(state) : wordTextColorAt(state);
35
+ }
@@ -172,9 +172,9 @@ class RebaseMapping implements Mappable {
172
172
  // Which side of each original step's changed range the position was on. Content deleted
173
173
  // outside history can collapse that distinction; the rebased step's map must restore it, or a
174
174
  // position left of re-inserted content ends up right of it (and vice versa).
175
- const sides: number[] = [];
175
+ const sides: number[][] = [];
176
176
  for (let i = this.inverted.length - 1; i >= 0; i--) {
177
- sides[i] = (this.inverted[i] as StepMap).side(pos);
177
+ sides[i] = (this.inverted[i] as StepMap).sides(pos);
178
178
  const result = (this.inverted[i] as StepMap).mapResult(pos, assoc);
179
179
  const mirror = this.rebased[i];
180
180
  if (result.recover !== null && mirror) {
@@ -192,7 +192,7 @@ class RebaseMapping implements Mappable {
192
192
  pos = result.pos;
193
193
  }
194
194
  for (let i = from; i < this.rebased.length; i++) {
195
- const result = this.rebased[i]?.mapResult(pos, sides[i] || assoc);
195
+ const result = this.rebased[i]?.mapResult(pos, assoc, sides[i]);
196
196
  if (!result) continue;
197
197
  deleted ||= result.deleted;
198
198
  pos = result.pos;
@@ -1,4 +1,5 @@
1
1
  export {
2
+ arrowAcrossLeaf,
2
3
  baseKeymap,
3
4
  type DeleteUnit,
4
5
  deleteBackward,
@@ -6,6 +7,7 @@ export {
6
7
  deleteSelection,
7
8
  insertHardBreak,
8
9
  insertPageBreak,
10
+ insertTab,
9
11
  insertText,
10
12
  isMarkActive,
11
13
  joinBackward,
@@ -15,7 +17,21 @@ export {
15
17
  splitBlock,
16
18
  toggleMark,
17
19
  } from "./commands.js";
18
- export { createEditor, type Editor, type EditorListener, type EditorOptions } from "./editor.js";
20
+ export {
21
+ createEditor,
22
+ type Editor,
23
+ type EditorDocument,
24
+ type EditorListener,
25
+ type EditorOptions,
26
+ sectionSettings,
27
+ } from "./editor.js";
28
+ export {
29
+ alignAt,
30
+ colorAt,
31
+ setAlign,
32
+ setHighlight,
33
+ setTextColor,
34
+ } from "./format.js";
19
35
  export {
20
36
  closeHistory,
21
37
  type HistoryOptions,
@@ -25,9 +41,32 @@ export {
25
41
  undo,
26
42
  undoDepth,
27
43
  } from "./history.js";
44
+ export {
45
+ autolinkHref,
46
+ insertLink,
47
+ linkAt,
48
+ linkEditorRequest,
49
+ normalizeHref,
50
+ openLinkEditor,
51
+ removeLink,
52
+ requestsLinkEditor,
53
+ setLink,
54
+ } from "./links.js";
55
+ export {
56
+ liftListItem,
57
+ liftListItemAtStart,
58
+ listKeymap,
59
+ listKindAt,
60
+ sinkListItem,
61
+ splitListItem,
62
+ toggleList,
63
+ wrapInList,
64
+ } from "./lists.js";
65
+ export { typedMarks } from "./mark.js";
28
66
  export {
29
67
  AllSelection,
30
68
  marksAt,
69
+ NodeSelection,
31
70
  Selection,
32
71
  type SelectionJSON,
33
72
  TextSelection,
@@ -42,3 +81,26 @@ export {
42
81
  type PluginSpec,
43
82
  Transaction,
44
83
  } from "./state.js";
84
+ export { type WordContext, type WordEnvelope, withEnvelope, wordContext } from "./word.js";
85
+ export {
86
+ copiedDefinitions,
87
+ fitPaste,
88
+ fitPastedV2,
89
+ type WordDefinitions,
90
+ } from "./wordclip.js";
91
+ export {
92
+ canOutdent,
93
+ changeIndent,
94
+ fontFamilyAt,
95
+ fontSizeAt,
96
+ HIGHLIGHT_HEX,
97
+ type ListKind,
98
+ lineSpacingAt,
99
+ paragraphStyleAt,
100
+ paragraphStyles,
101
+ setFontFamily,
102
+ setFontSize,
103
+ setLineSpacing,
104
+ setParagraphSpacing,
105
+ setParagraphStyle,
106
+ } from "./wordformat.js";
@@ -0,0 +1,193 @@
1
+ import type { Mark, MarkType, ResolvedPos } from "../model/index.js";
2
+ import { isSafeHref } from "../schema.js";
3
+ import { TransformError } from "../transform/transform.js";
4
+ import { attempt } from "./attempt.js";
5
+ import { AllSelection, marksAt, TextSelection } from "./selection.js";
6
+ import type { Command, EditorState, Transaction } from "./state.js";
7
+ import { styleLink, unstyleLink } from "./wordformat.js";
8
+
9
+ const EMAIL = /^[^\s@/:]+@[^\s@/:]+\.\p{L}{2,}$/iu;
10
+ /**
11
+ * A host name with a dot and a letter TLD (`www.` alone is enough; letters in any script), then a
12
+ * port, path or end.
13
+ */
14
+ const DOMAIN = /^(?:www\.|(?:[\p{L}\p{N}-]+\.)+\p{L}{2,}(?:[:/?#]|$))/iu;
15
+ const AUTOLINK = /^(?:https?:\/\/|mailto:|www\.)\S+$/i;
16
+
17
+ /**
18
+ * Cleans up a typed or pasted URL before validation (`isSafeHref`): trims it, turns `\` into
19
+ * `/`, percent-encodes spaces, and adds the scheme people leave out: `mailto:` for an email
20
+ * address, `https://` for a host name (`example.com/page`, `www.example.com`). A relative
21
+ * file name that looks like a host (`page.html`) becomes one too: write `./page.html`.
22
+ */
23
+ export function normalizeHref(input: string): string {
24
+ const href = input.trim().replace(/\\/g, "/").replace(/ /g, "%20");
25
+ if (EMAIL.test(href)) return `mailto:${href}`;
26
+ if (DOMAIN.test(href)) return `https://${href}`;
27
+ return href;
28
+ }
29
+
30
+ /**
31
+ * The href for pasted plain text that is one URL (`http(s)://…`, `mailto:…`, `www.…`), or null:
32
+ * pasting it makes a link.
33
+ */
34
+ export function autolinkHref(text: string): string | null {
35
+ const trimmed = text.trim();
36
+ if (!AUTOLINK.test(trimmed)) return null;
37
+ const href = normalizeHref(trimmed);
38
+ return isSafeHref(href) ? href : null;
39
+ }
40
+
41
+ const linkType = (state: EditorState): MarkType | undefined => state.schema.marks.link;
42
+
43
+ /**
44
+ * The link around a caret (touching it at either edge, so a caret just after a link edits that
45
+ * link), with its extent, or null.
46
+ */
47
+ function linkAround(
48
+ $pos: ResolvedPos,
49
+ type: MarkType,
50
+ ): { from: number; to: number; mark: Mark } | null {
51
+ const parent = $pos.parent;
52
+ if (!parent.inlineContent) return null;
53
+ const index = $pos.index();
54
+ for (const i of $pos.textOffset ? [index] : [index - 1, index]) {
55
+ const mark = type.isInSet(parent.maybeChild(i)?.marks ?? []);
56
+ if (!mark) continue;
57
+ let start = i;
58
+ let end = i + 1;
59
+ while (start > 0 && mark.isInSet(parent.child(start - 1).marks)) start--;
60
+ while (end < parent.childCount && mark.isInSet(parent.child(end).marks)) end++;
61
+ let from = $pos.start();
62
+ let to = from;
63
+ for (let c = 0; c < end; c++) {
64
+ const size = parent.child(c).nodeSize;
65
+ if (c < start) from += size;
66
+ to += size;
67
+ }
68
+ return { from, to, mark };
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /** Whether the selection is in (or holds) text that can take a link. */
74
+ function canLink(state: EditorState, type: MarkType): boolean {
75
+ const { selection } = state;
76
+ if (selection.empty) {
77
+ const { parent } = selection.$from;
78
+ return parent.inlineContent && parent.type.allowsMarkType(type);
79
+ }
80
+ let found = false;
81
+ state.doc.nodesBetween(selection.from, selection.to, (node) => {
82
+ if (node.isTextblock && node.type.allowsMarkType(type)) found = true;
83
+ return !found;
84
+ });
85
+ return found;
86
+ }
87
+
88
+ /**
89
+ * The href of the link at the selection: around a caret, or the one link all selected text has
90
+ * (null when text has no link or different ones).
91
+ */
92
+ export function linkAt(state: EditorState): string | null {
93
+ const type = linkType(state);
94
+ if (!type) return null;
95
+ const { selection } = state;
96
+ if (selection.empty)
97
+ return (linkAround(selection.$from, type)?.mark.attrs.href as string) ?? null;
98
+ // undefined: no text seen yet; null: text without a link, or with another one.
99
+ let href = undefined as string | null | undefined;
100
+ state.doc.nodesBetween(selection.from, selection.to, (node, _pos, parent) => {
101
+ if (href === null) return false;
102
+ if (!node.isInline || !parent?.type.allowsMarkType(type)) return undefined;
103
+ const value = (type.isInSet(node.marks)?.attrs.href as string | undefined) ?? null;
104
+ href = href === undefined || href === value ? value : null;
105
+ return false;
106
+ });
107
+ return href ?? null;
108
+ }
109
+
110
+ /**
111
+ * Replaces the selection with `text` (default: the href) linked to `href` (normalized, then
112
+ * validated: an unsafe href does not apply). The text keeps the marks typing would get there.
113
+ */
114
+ export function insertLink(href: string, text?: string): Command {
115
+ return (state, dispatch) => {
116
+ const type = linkType(state);
117
+ const normalized = normalizeHref(href);
118
+ const label = text ?? normalized;
119
+ const { selection } = state;
120
+ if (!type || !label || !isSafeHref(normalized)) return false;
121
+ if (!(selection instanceof AllSelection) && !canLink(state, type)) return false;
122
+ const link = type.create({ href: normalized });
123
+ return attempt(state, dispatch, (tr) => {
124
+ const marks = state.storedMarks ?? marksAt(selection.$from);
125
+ tr.deleteSelection();
126
+ const pos = tr.selection.from;
127
+ const parent = tr.doc.resolve(pos).parent;
128
+ if (!parent.inlineContent || !parent.type.allowsMarkType(type)) {
129
+ throw new TransformError("No link here");
130
+ }
131
+ const allowed = marks.filter((mark) => parent.type.allowsMarkType(mark.type));
132
+ tr.insertText(label, pos, pos, link.addToSet(allowed));
133
+ styleLink(tr, state, pos, pos + label.length);
134
+ tr.setSelection(TextSelection.create(tr.doc, pos + label.length));
135
+ });
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Links the selected text to `href` (normalized, then validated: an unsafe href does not apply),
141
+ * replacing other links there. At a caret in (or at the edge of) a link, changes that link's
142
+ * href; elsewhere inserts the href as linked text.
143
+ */
144
+ export function setLink(href: string): Command {
145
+ return (state, dispatch) => {
146
+ const type = linkType(state);
147
+ const normalized = normalizeHref(href);
148
+ if (!type || !isSafeHref(normalized) || !canLink(state, type)) return false;
149
+ const mark = type.create({ href: normalized });
150
+ const { selection } = state;
151
+ if (!selection.empty) {
152
+ return attempt(state, dispatch, (tr) => {
153
+ tr.addMark(selection.from, selection.to, mark);
154
+ styleLink(tr, state, selection.from, selection.to);
155
+ });
156
+ }
157
+ const around = linkAround(selection.$from, type);
158
+ if (!around) return insertLink(normalized)(state, dispatch);
159
+ return attempt(state, dispatch, (tr) => tr.addMark(around.from, around.to, mark));
160
+ };
161
+ }
162
+
163
+ /** Removes the links in the selection; at a caret, the whole link around it. */
164
+ export const removeLink: Command = (state, dispatch) => {
165
+ const type = linkType(state);
166
+ if (!type) return false;
167
+ const { selection } = state;
168
+ const range = selection.empty ? linkAround(selection.$from, type) : selection;
169
+ if (!range) return false;
170
+ return attempt(state, dispatch, (tr) => {
171
+ tr.removeMark(range.from, range.to, type);
172
+ unstyleLink(tr, state, range.from, range.to);
173
+ });
174
+ };
175
+
176
+ /** Transaction metadata set by `openLinkEditor`; a link editing UI listens for it. */
177
+ export const linkEditorRequest = "linkEditorRequest";
178
+
179
+ /**
180
+ * Mod-K: asks the UI to open its link editor (the React toolbar's link dialog), with a
181
+ * transaction that changes nothing and carries `linkEditorRequest`. Does not apply where text
182
+ * cannot take a link. Without such a UI, Mod-K does nothing.
183
+ */
184
+ export const openLinkEditor: Command = (state, dispatch) => {
185
+ const type = linkType(state);
186
+ if (!type || !canLink(state, type)) return false;
187
+ dispatch?.(state.tr.setMeta(linkEditorRequest, true));
188
+ return true;
189
+ };
190
+
191
+ /** Whether `tr` asks for the link editor (`openLinkEditor`). */
192
+ export const requestsLinkEditor = (tr: Transaction): boolean =>
193
+ tr.getMeta(linkEditorRequest) === true;
@@ -0,0 +1,50 @@
1
+ import { type Command, Plugin } from "./state.js";
2
+ import {
3
+ endWordList,
4
+ type ListKind,
5
+ liftWordList,
6
+ removeWordListNumber,
7
+ sinkWordList,
8
+ toggleWordList,
9
+ wordListKindAt,
10
+ wrapInWordList,
11
+ } from "./wordformat.js";
12
+
13
+ /** The kind of list all selected paragraphs are in ("bulletList", "orderedList"), or null. */
14
+ export const listKindAt = wordListKindAt;
15
+
16
+ /** Numbers the selected paragraphs as a list of `kind` (one right before goes on). */
17
+ export const wrapInList: (kind: ListKind) => Command = wrapInWordList;
18
+
19
+ /** The list buttons: removes the selection's numbering when it is a list of `kind`, else numbers it. */
20
+ export const toggleList: (kind: ListKind) => Command = toggleWordList;
21
+
22
+ /** Enter in an empty numbered paragraph: one level up, or at the top level ends the list. */
23
+ export const splitListItem: Command = endWordList;
24
+
25
+ /** Tab at the start of a numbered paragraph, or over several paragraphs: one level deeper. */
26
+ export const sinkListItem: Command = sinkWordList;
27
+
28
+ /** Shift+Tab in a list: one level up (out of the list at the top). */
29
+ export const liftListItem: Command = liftWordList;
30
+
31
+ /** Backspace at the start of a numbered paragraph: removes its number, keeping the text in place. */
32
+ export const liftListItemAtStart: Command = removeWordListNumber;
33
+
34
+ /**
35
+ * The list key bindings, as Word's: Enter and Backspace in a numbered paragraph, Tab and
36
+ * Shift+Tab for levels (elsewhere Tab types a tab), Mod-Shift-7 / Mod-Shift-8 toggle a
37
+ * numbered / bulleted list.
38
+ */
39
+ export function listKeymap(): Plugin {
40
+ return new Plugin({
41
+ keymap: {
42
+ Enter: splitListItem,
43
+ Backspace: liftListItemAtStart,
44
+ Tab: sinkListItem,
45
+ "Shift-Tab": liftListItem,
46
+ "Mod-Shift-7": toggleList("orderedList"),
47
+ "Mod-Shift-8": toggleList("bulletList"),
48
+ },
49
+ });
50
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * What Word keeps on a paragraph's mark, and the marks typed text must not take: shared by the
3
+ * transaction (deleting across paragraphs) and the commands. No imports from the state module
4
+ * (it is imported by it).
5
+ */
6
+ import type { Mark, Node } from "../model/index.js";
7
+ import type { Transform } from "../transform/transform.js";
8
+
9
+ /**
10
+ * Attributes the paragraph mark carries in Word (schema v3): the section break, the mark's
11
+ * tracked change and the paragraph's own attributes (`w14:paraId`). Whichever paragraph keeps
12
+ * the mark keeps them.
13
+ */
14
+ export const MARK_ATTRS = ["section", "revision", "formatChange", "attributes"] as const;
15
+
16
+ /**
17
+ * After a join, or a deletion across paragraphs, the merged paragraph at `pos` ends with the
18
+ * last paragraph's mark, as in Word: it takes that paragraph's mark attributes (deleting a
19
+ * section break merges its section into the next one). Nothing for a schema without them (v2).
20
+ */
21
+ export function keepLastMark(tr: Transform, pos: number, last: Node): void {
22
+ const merged = tr.doc.nodeAt(pos);
23
+ if (!merged?.isTextblock) return;
24
+ const attrs = { ...merged.attrs };
25
+ let changed = false;
26
+ for (const key of MARK_ATTRS) {
27
+ // Schema v2 has none of them: both sides null, nothing changes.
28
+ const value = last.attrs[key] ?? null;
29
+ if (JSON.stringify(attrs[key] ?? null) === JSON.stringify(value)) continue;
30
+ attrs[key] = value;
31
+ changed = true;
32
+ }
33
+ if (changed) tr.setNodeMarkup(pos, merged.type, attrs);
34
+ }
35
+
36
+ /** Tracked-change marks: typed or pasted text is not part of someone's recorded change. */
37
+ const REVIEW_MARKS = new Set(["insertion", "deletion", "formatChange"]);
38
+
39
+ /**
40
+ * The marks text typed among `marks` gets: without tracked-change marks.
41
+ * shortcut: until Phase 9 records changes, typed text is never marked as one.
42
+ */
43
+ export function typedMarks(marks: readonly Mark[]): readonly Mark[] {
44
+ return marks.some((m) => REVIEW_MARKS.has(m.type.name))
45
+ ? marks.filter((m) => !REVIEW_MARKS.has(m.type.name))
46
+ : marks;
47
+ }