svelte-rtf-editor 1.12.0 → 1.15.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.
@@ -0,0 +1,329 @@
1
+ /**
2
+ * The editor's own Undo and Redo.
3
+ *
4
+ * A browser's history knows what its own commands and the keyboard changed. It knows nothing
5
+ * of what the editor changes in the document itself: a picture or a table put in, a picture
6
+ * moved, an indent. Its Undo skipped those and took back the typing before them, and what
7
+ * the editor then changed behind it could leave it unable to undo at all. So the editor
8
+ * keeps the history: the document as it was before each step, and Undo puts that back.
9
+ *
10
+ * A step is whatever changed between two calls of `step()`, however it was changed: by a
11
+ * key, by a browser command, or by the editor. The editor calls `step()` before each thing it
12
+ * does, and `typing()` before each key's worth of input, which keeps a run of typing as one
13
+ * step. Nothing has to be said after a change: a MutationObserver knows there was one.
14
+ *
15
+ * What is kept is the document's HTML, with each embedded picture kept once, and the
16
+ * selection. Putting a step back replaces only the blocks that differ, so a picture in a
17
+ * part of the document that did not change is not read again.
18
+ */
19
+ const DEFAULT_LIMIT = 200;
20
+ const DEFAULT_PAUSE = 1000;
21
+ export function createHistory(root, options = {}) {
22
+ const limit = options.limit ?? DEFAULT_LIMIT;
23
+ const pause = options.pause ?? DEFAULT_PAUSE;
24
+ const doc = root.ownerDocument;
25
+ const view = doc.defaultView;
26
+ // ── Pictures ──
27
+ // A picture is in the HTML as its bytes, and a report has megabytes of them. Each step
28
+ // would keep them all again: so a picture is kept once, and the HTML of a step has a mark
29
+ // where it goes. (The mark has a part no document has, so that nothing a writer typed is
30
+ // taken for one.)
31
+ const mark = `ink-kept-${Math.random().toString(36).slice(2)}-`;
32
+ const pictures = [];
33
+ const pictureIds = new Map();
34
+ const pack = (html) => html.replace(/(\ssrc=")(data:[^"]{64,})(")/g, (_all, before, picture, after) => {
35
+ let id = pictureIds.get(picture);
36
+ if (id === undefined) {
37
+ id = pictures.length;
38
+ pictures.push(picture);
39
+ pictureIds.set(picture, id);
40
+ }
41
+ return `${before}${mark}${id}${after}`;
42
+ });
43
+ const unpack = (html) => html.replace(new RegExp(`(\\ssrc=")${mark}(\\d+)(")`, 'g'), (all, before, id, after) => pictures[Number(id)] === undefined ? all : `${before}${pictures[Number(id)]}${after}`);
44
+ // ── The selection ──
45
+ // A place is said as the HTML will have it when it is read again: text nodes that are side
46
+ // by side are one there, and one with nothing in it is not there at all.
47
+ const isText = (node) => node?.nodeType === 3;
48
+ /** Where a child is among its parent's children as read again, and for text how far into the run of text it begins. */
49
+ function placeOf(parent, child, upTo = parent.childNodes.length) {
50
+ let index = -1;
51
+ let run = 0;
52
+ let inText = false;
53
+ for (let i = 0; i < parent.childNodes.length; i++) {
54
+ const at = parent.childNodes[i];
55
+ if (child === null && i === upTo)
56
+ break;
57
+ if (isText(at)) {
58
+ if (at === child || at.length > 0) {
59
+ if (!inText) {
60
+ index++;
61
+ run = 0;
62
+ inText = true;
63
+ }
64
+ if (at === child)
65
+ return { index, shift: run };
66
+ run += at.length;
67
+ }
68
+ }
69
+ else {
70
+ inText = false;
71
+ index++;
72
+ if (at === child)
73
+ return { index, shift: 0 };
74
+ }
75
+ }
76
+ return { index: index + 1, shift: 0 };
77
+ }
78
+ function pointOf(node, offset) {
79
+ const path = [];
80
+ let at = node;
81
+ // (In an element, the offset counts its children: as they will be read again.)
82
+ let within = isText(node) ? offset : placeOf(node, null, offset).index;
83
+ while (at !== root) {
84
+ const parent = at.parentNode;
85
+ if (!parent)
86
+ return null;
87
+ const { index, shift } = placeOf(parent, at);
88
+ if (at === node)
89
+ within += shift;
90
+ path.unshift(index);
91
+ at = parent;
92
+ }
93
+ return { path, offset: within };
94
+ }
95
+ /** The child that is the `index`th when read again: for text, the first piece of it. */
96
+ function childAt(parent, index) {
97
+ let at = -1;
98
+ let inText = false;
99
+ for (let i = 0; i < parent.childNodes.length; i++) {
100
+ const child = parent.childNodes[i];
101
+ if (isText(child)) {
102
+ if (child.length === 0 || inText)
103
+ continue;
104
+ inText = true;
105
+ }
106
+ else {
107
+ inText = false;
108
+ }
109
+ if (++at === index)
110
+ return child;
111
+ }
112
+ return null;
113
+ }
114
+ /** The place in the document as it is now: its text may be in pieces, or in one. */
115
+ function nodeAt(point) {
116
+ let node = root;
117
+ for (const index of point.path) {
118
+ const child = childAt(node, index);
119
+ if (!child)
120
+ return null;
121
+ node = child;
122
+ }
123
+ if (isText(node)) {
124
+ let text = node;
125
+ let offset = point.offset;
126
+ while (offset > text.length && isText(text.nextSibling)) {
127
+ offset -= text.length;
128
+ text = text.nextSibling;
129
+ }
130
+ return { node: text, offset: Math.min(offset, text.length) };
131
+ }
132
+ const before = childAt(node, point.offset);
133
+ return { node, offset: before ? Array.prototype.indexOf.call(node.childNodes, before) : node.childNodes.length };
134
+ }
135
+ function selectionNow() {
136
+ const sel = view?.getSelection();
137
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !sel.focusNode)
138
+ return null;
139
+ if (!root.contains(sel.anchorNode) || !root.contains(sel.focusNode))
140
+ return null;
141
+ const anchor = pointOf(sel.anchorNode, sel.anchorOffset);
142
+ const focus = pointOf(sel.focusNode, sel.focusOffset);
143
+ return anchor && focus ? { anchor, focus } : null;
144
+ }
145
+ function select(kept) {
146
+ const sel = view?.getSelection();
147
+ if (!sel || !kept)
148
+ return;
149
+ const anchor = nodeAt(kept.anchor);
150
+ const focus = nodeAt(kept.focus);
151
+ if (!anchor || !focus)
152
+ return;
153
+ try {
154
+ sel.setBaseAndExtent(anchor.node, anchor.offset, focus.node, focus.offset);
155
+ }
156
+ catch {
157
+ // A place that is no longer one: the selection stays where the browser left it.
158
+ }
159
+ }
160
+ // ── What is kept ──
161
+ const take = () => ({ html: pack(root.innerHTML), selection: selectionNow() });
162
+ /** The documents before each step, oldest first; and those after each step undone. */
163
+ let before = [];
164
+ let after = [];
165
+ /** The document as it was when the last step ended. */
166
+ let base = take();
167
+ // ── Whether anything changed ──
168
+ // (Without a MutationObserver, every step compares the HTML, which says the same.)
169
+ let dirty = false;
170
+ const own = (record) => !(record.type === 'attributes' && record.target === root);
171
+ const Observer = view?.MutationObserver ?? (typeof MutationObserver !== 'undefined' ? MutationObserver : null);
172
+ const observer = Observer
173
+ ? new Observer((records) => {
174
+ if (records.some(own))
175
+ dirty = true;
176
+ })
177
+ : null;
178
+ observer?.observe(root, { childList: true, subtree: true, characterData: true, attributes: true });
179
+ function changed() {
180
+ if (!observer)
181
+ return true;
182
+ if (observer.takeRecords().some(own))
183
+ dirty = true;
184
+ return dirty;
185
+ }
186
+ function settled() {
187
+ observer?.takeRecords();
188
+ dirty = false;
189
+ }
190
+ // ── Steps ──
191
+ let run = null;
192
+ let caret = null;
193
+ let last = 0;
194
+ let timer;
195
+ let inComposition = false;
196
+ function step() {
197
+ clearTimeout(timer);
198
+ run = null;
199
+ caret = null;
200
+ if (!changed()) {
201
+ // Where the next step begins is where its Undo puts the caret back.
202
+ base = { html: base.html, selection: selectionNow() ?? base.selection };
203
+ return;
204
+ }
205
+ settled();
206
+ const now = take();
207
+ if (now.html === base.html) {
208
+ base = now;
209
+ return;
210
+ }
211
+ before.push(base);
212
+ if (before.length > limit)
213
+ before.shift();
214
+ after = [];
215
+ base = now;
216
+ }
217
+ function caretIsWhereLeft() {
218
+ const sel = view?.getSelection();
219
+ return !!caret && !!sel && sel.isCollapsed && sel.anchorNode === caret.node && sel.anchorOffset === caret.offset;
220
+ }
221
+ function typing(kind) {
222
+ const now = Date.now();
223
+ // What an input method composes is one run of typing, from its first input to its
224
+ // last: its text is replaced as it is composed, and the caret goes where the method
225
+ // puts it, neither of which ends a step in the middle of a word.
226
+ if (inComposition && run === 'insert') {
227
+ last = now;
228
+ return;
229
+ }
230
+ if (kind === null || kind !== run || now - last > pause || !caretIsWhereLeft())
231
+ step();
232
+ run = kind;
233
+ last = now;
234
+ }
235
+ function typed() {
236
+ const sel = view?.getSelection();
237
+ caret = sel?.anchorNode ? { node: sel.anchorNode, offset: sel.anchorOffset } : null;
238
+ last = Date.now();
239
+ clearTimeout(timer);
240
+ if (run === null)
241
+ return;
242
+ // A pause ends the step: it is kept while nothing is being typed.
243
+ const end = () => {
244
+ if (inComposition)
245
+ timer = setTimeout(end, pause);
246
+ else
247
+ step();
248
+ };
249
+ timer = setTimeout(end, pause);
250
+ }
251
+ // ── Putting a step back ──
252
+ function show(kept) {
253
+ const holder = doc.createElement('template');
254
+ holder.innerHTML = unpack(kept.html);
255
+ const wanted = Array.from(holder.content.childNodes);
256
+ const shown = Array.from(root.childNodes);
257
+ let same = 0;
258
+ while (same < wanted.length && same < shown.length && shown[same].isEqualNode(wanted[same]))
259
+ same++;
260
+ let wantedEnd = wanted.length;
261
+ let shownEnd = shown.length;
262
+ while (wantedEnd > same && shownEnd > same && shown[shownEnd - 1].isEqualNode(wanted[wantedEnd - 1])) {
263
+ wantedEnd--;
264
+ shownEnd--;
265
+ }
266
+ const next = shown[shownEnd] ?? null;
267
+ for (let i = same; i < shownEnd; i++)
268
+ root.removeChild(shown[i]);
269
+ for (let i = same; i < wantedEnd; i++)
270
+ root.insertBefore(wanted[i], next);
271
+ select(kept.selection);
272
+ }
273
+ function back(undo, then) {
274
+ // (Not while an input method composes: the document put back would be taken from under
275
+ // the text it holds, which it then writes somewhere that is no longer there.)
276
+ if (inComposition)
277
+ return false;
278
+ // (What changed since the last step is a step first: and then there is nothing to redo.)
279
+ step();
280
+ const kept = (undo ? before : after).pop();
281
+ if (!kept)
282
+ return false;
283
+ (undo ? after : before).push(base);
284
+ base = kept;
285
+ show(kept);
286
+ then?.();
287
+ // (What `then` made of it is the document that was put back: a check that took
288
+ // something out of it is no step to undo.)
289
+ if (changed())
290
+ base = { html: pack(root.innerHTML), selection: base.selection };
291
+ settled();
292
+ return true;
293
+ }
294
+ return {
295
+ step,
296
+ typing,
297
+ typed,
298
+ undo: (then) => back(true, then),
299
+ redo: (then) => back(false, then),
300
+ canUndo: () => before.length > 0 || changed(),
301
+ canRedo: () => after.length > 0 && !changed(),
302
+ quietly(change) {
303
+ const open = changed();
304
+ change();
305
+ if (open || !changed())
306
+ return;
307
+ settled();
308
+ base = { html: pack(root.innerHTML), selection: base.selection };
309
+ },
310
+ reset() {
311
+ clearTimeout(timer);
312
+ settled();
313
+ before = [];
314
+ after = [];
315
+ pictures.length = 0;
316
+ pictureIds.clear();
317
+ run = null;
318
+ caret = null;
319
+ base = take();
320
+ },
321
+ composing(on) {
322
+ inComposition = on;
323
+ },
324
+ destroy() {
325
+ clearTimeout(timer);
326
+ observer?.disconnect();
327
+ }
328
+ };
329
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The marker a numbered list item shows: "3.", "C.", "iii.".
3
+ *
4
+ * A browser numbers the items of an <ol> by the list's `type` or `list-style-type`, the list's
5
+ * `start` and an item's own `value`. The RTF and the Markdown carry a marker as text, so what is
6
+ * written is worked out here, once, the way a browser shows it: a list lettered A, B, C that was
7
+ * written 1, 2, 3 left "see part B" pointing at an item labelled "2.".
8
+ */
9
+ /** The ways a numbered list counts that are written as they show. Any other is written in digits. */
10
+ export type NumberStyle = 'decimal' | 'upper-alpha' | 'lower-alpha' | 'upper-roman' | 'lower-roman';
11
+ /** The `type` attribute that shows a style: 'A' for upper-alpha. */
12
+ export declare function listTypeAttribute(style: NumberStyle): string;
13
+ /**
14
+ * How an item of a numbered list counts: its own `list-style-type` or `type` (Google Docs puts
15
+ * the style on each item), then the list's. A style that is none of NumberStyle counts in digits.
16
+ */
17
+ export declare function numberStyleOf(list: Element, item?: Element | null): NumberStyle;
18
+ /** The number a list starts at: its `start`, or 1. */
19
+ export declare function listStart(list: Element): number;
20
+ /** The number of an item: its own `value` where it has one, else the count so far. */
21
+ export declare function itemNumber(item: Element, counter: number): number;
22
+ /**
23
+ * A number as a list of that style shows it, without the period: 3, "C", "iii". A number the
24
+ * style cannot write (letters below 1, Roman numerals below 1 or above 3999) is shown in digits,
25
+ * as a browser shows it.
26
+ */
27
+ export declare function markerText(n: number, style: NumberStyle): string;
28
+ /** A marker written in letters, read as a number: by which style, and which number. */
29
+ export interface LetterReading {
30
+ style: NumberStyle;
31
+ number: number;
32
+ }
33
+ /**
34
+ * What a marker written in letters can mean: "C" is the third letter and the Roman 100; "IV" is
35
+ * a Roman 4; "ab" is the 28th item of a lettered list. Empty for letters that are no marker: of
36
+ * mixed case, more than two letters that are no Roman numeral.
37
+ */
38
+ export declare function letterReadings(letters: string): LetterReading[];
39
+ /** The least gap there is, in twips: 6 pt. Closer, a number runs into its text. */
40
+ export declare const LEAST_MARKER_GAP = 120;
41
+ /** The most, in twips: two inches. */
42
+ export declare const MOST_MARKER_GAP = 2880;
43
+ /**
44
+ * The gap a list sets after its markers, in twips, or null where it sets none: no
45
+ * `padding-left` of its own, or one out of the range above (a page's `padding-left: 0`).
46
+ */
47
+ export declare function markerGapTwips(list: Element): number | null;
48
+ /**
49
+ * Where the editor writes, for the screen, the marker an item of a list with a gap shows. A
50
+ * browser draws its own markers against the item's text, and cannot be told how far before
51
+ * it; so for such a list the editor draws them itself, at the list's edge (see the editor's
52
+ * style), from this. It is worked out here, as the RTF writer works it out: a browser's own
53
+ * count does not see an item's `value` in every browser. It is no part of the document, and
54
+ * the editor takes it out of what it gives (getHTML, onsave, the draft).
55
+ */
56
+ export declare const MARKER_ATTRIBUTE = "data-ink-marker";
57
+ /**
58
+ * Write the marker of each item of each list with a gap under `root`, and take it off the
59
+ * items of every other list. Only what differs is written, so that a document that has not
60
+ * changed is not changed by this either.
61
+ */
62
+ export declare function markItems(root: Element): void;
63
+ /** Take the editor's markers out of a copy of a document. */
64
+ export declare function withoutMarkers(root: Element): void;
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The marker a numbered list item shows: "3.", "C.", "iii.".
3
+ *
4
+ * A browser numbers the items of an <ol> by the list's `type` or `list-style-type`, the list's
5
+ * `start` and an item's own `value`. The RTF and the Markdown carry a marker as text, so what is
6
+ * written is worked out here, once, the way a browser shows it: a list lettered A, B, C that was
7
+ * written 1, 2, 3 left "see part B" pointing at an item labelled "2.".
8
+ */
9
+ /** The `type` attribute of an <ol> for each style, and back. */
10
+ const TYPE_OF_STYLE = {
11
+ decimal: '1',
12
+ 'upper-alpha': 'A',
13
+ 'lower-alpha': 'a',
14
+ 'upper-roman': 'I',
15
+ 'lower-roman': 'i'
16
+ };
17
+ const STYLE_OF_TYPE = new Map(Object.entries(TYPE_OF_STYLE).map(([style, type]) => [type, style]));
18
+ /** What CSS calls each style; `upper-latin` is another name for `upper-alpha`. */
19
+ const STYLE_OF_CSS = new Map([
20
+ ['decimal', 'decimal'],
21
+ ['upper-alpha', 'upper-alpha'],
22
+ ['upper-latin', 'upper-alpha'],
23
+ ['lower-alpha', 'lower-alpha'],
24
+ ['lower-latin', 'lower-alpha'],
25
+ ['upper-roman', 'upper-roman'],
26
+ ['lower-roman', 'lower-roman']
27
+ ]);
28
+ /** The `type` attribute that shows a style: 'A' for upper-alpha. */
29
+ export function listTypeAttribute(style) {
30
+ return TYPE_OF_STYLE[style];
31
+ }
32
+ /** The style an element asks for by itself, or null: its `list-style-type`, then its `type`. */
33
+ function ownStyle(el) {
34
+ if (!el)
35
+ return null;
36
+ const css = (el.style?.listStyleType ?? '').trim().toLowerCase();
37
+ if (css)
38
+ return STYLE_OF_CSS.get(css) ?? 'decimal';
39
+ // (The attribute tells "A" from "a": it is not lowercased.)
40
+ return STYLE_OF_TYPE.get((el.getAttribute('type') ?? '').trim()) ?? null;
41
+ }
42
+ /**
43
+ * How an item of a numbered list counts: its own `list-style-type` or `type` (Google Docs puts
44
+ * the style on each item), then the list's. A style that is none of NumberStyle counts in digits.
45
+ */
46
+ export function numberStyleOf(list, item) {
47
+ return ownStyle(item) ?? ownStyle(list) ?? 'decimal';
48
+ }
49
+ /** The number a list starts at: its `start`, or 1. */
50
+ export function listStart(list) {
51
+ const start = parseInt(list.getAttribute('start') ?? '', 10);
52
+ return Number.isFinite(start) ? start : 1;
53
+ }
54
+ /** The number of an item: its own `value` where it has one, else the count so far. */
55
+ export function itemNumber(item, counter) {
56
+ if (!item.hasAttribute('value'))
57
+ return counter;
58
+ const value = parseInt(item.getAttribute('value') ?? '', 10);
59
+ return Number.isFinite(value) ? value : counter;
60
+ }
61
+ const ROMAN = [
62
+ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'],
63
+ [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']
64
+ ];
65
+ function roman(n) {
66
+ let out = '';
67
+ for (const [value, letters] of ROMAN) {
68
+ while (n >= value) {
69
+ out += letters;
70
+ n -= value;
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+ /** A, B, … Z, AA, AB, …: the letters count as a browser's do. */
76
+ function alpha(n) {
77
+ let out = '';
78
+ for (; n > 0; n = Math.floor((n - 1) / 26))
79
+ out = String.fromCharCode(65 + ((n - 1) % 26)) + out;
80
+ return out;
81
+ }
82
+ /**
83
+ * A number as a list of that style shows it, without the period: 3, "C", "iii". A number the
84
+ * style cannot write (letters below 1, Roman numerals below 1 or above 3999) is shown in digits,
85
+ * as a browser shows it.
86
+ */
87
+ export function markerText(n, style) {
88
+ if (style === 'decimal' || !Number.isInteger(n) || n < 1)
89
+ return String(n);
90
+ if (style === 'upper-alpha')
91
+ return alpha(n);
92
+ if (style === 'lower-alpha')
93
+ return alpha(n).toLowerCase();
94
+ if (n > 3999)
95
+ return String(n);
96
+ return style === 'upper-roman' ? roman(n) : roman(n).toLowerCase();
97
+ }
98
+ /**
99
+ * What a marker written in letters can mean: "C" is the third letter and the Roman 100; "IV" is
100
+ * a Roman 4; "ab" is the 28th item of a lettered list. Empty for letters that are no marker: of
101
+ * mixed case, more than two letters that are no Roman numeral.
102
+ */
103
+ export function letterReadings(letters) {
104
+ const upper = letters.toUpperCase();
105
+ const isUpper = letters === upper;
106
+ if (!/^[A-Z]+$/.test(upper) || (!isUpper && letters !== letters.toLowerCase()))
107
+ return [];
108
+ const readings = [];
109
+ if (upper.length <= 2) {
110
+ let number = 0;
111
+ for (const letter of upper)
112
+ number = number * 26 + (letter.charCodeAt(0) - 64);
113
+ readings.push({ style: isUpper ? 'upper-alpha' : 'lower-alpha', number });
114
+ }
115
+ if (/^[MDCLXVI]+$/.test(upper)) {
116
+ let number = 0;
117
+ let rest = upper;
118
+ for (const [value, numeral] of ROMAN) {
119
+ while (rest.startsWith(numeral)) {
120
+ number += value;
121
+ rest = rest.slice(numeral.length);
122
+ }
123
+ }
124
+ // (Only a numeral as it is written: "IIII" and "VX" are letters.)
125
+ if (number >= 1 && number <= 3999 && roman(number) === upper)
126
+ readings.push({ style: isUpper ? 'upper-roman' : 'lower-roman', number });
127
+ }
128
+ return readings;
129
+ }
130
+ // ── The gap after the marker ──
131
+ // How far an item's text starts from its bullet or number is the list's text indent, as Word
132
+ // has it: the marker starts where the list does, and the text that far further in. In the HTML
133
+ // it is the list's own `padding-left`, which is that distance in CSS too: from the list's edge
134
+ // to its items' text. The editor draws the marker at the list's edge (see markItems), and the
135
+ // RTF has it as the hang of each item (\fi-N). A list with no padding of its own has the gap
136
+ // the writer always gave one: a quarter inch, \fi-360.
137
+ /** The least gap there is, in twips: 6 pt. Closer, a number runs into its text. */
138
+ export const LEAST_MARKER_GAP = 120;
139
+ /** The most, in twips: two inches. */
140
+ export const MOST_MARKER_GAP = 2880;
141
+ const TWIPS_PER = { px: 15, pt: 20, in: 1440, cm: 1440 / 2.54, mm: 144 / 2.54 };
142
+ /**
143
+ * The gap a list sets after its markers, in twips, or null where it sets none: no
144
+ * `padding-left` of its own, or one out of the range above (a page's `padding-left: 0`).
145
+ */
146
+ export function markerGapTwips(list) {
147
+ const value = (list.style?.paddingLeft ?? '').trim().toLowerCase();
148
+ const m = value.match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|in|cm|mm)$/);
149
+ if (!m)
150
+ return null;
151
+ const twips = Math.round(parseFloat(m[1]) * TWIPS_PER[m[2]]);
152
+ return twips >= LEAST_MARKER_GAP && twips <= MOST_MARKER_GAP ? twips : null;
153
+ }
154
+ /**
155
+ * Where the editor writes, for the screen, the marker an item of a list with a gap shows. A
156
+ * browser draws its own markers against the item's text, and cannot be told how far before
157
+ * it; so for such a list the editor draws them itself, at the list's edge (see the editor's
158
+ * style), from this. It is worked out here, as the RTF writer works it out: a browser's own
159
+ * count does not see an item's `value` in every browser. It is no part of the document, and
160
+ * the editor takes it out of what it gives (getHTML, onsave, the draft).
161
+ */
162
+ export const MARKER_ATTRIBUTE = 'data-ink-marker';
163
+ /** The bullets of a list in a list, as the browser draws them: disc, circle, square. */
164
+ const BULLETS = { disc: '•', circle: '◦', square: '▪' };
165
+ /**
166
+ * Write the marker of each item of each list with a gap under `root`, and take it off the
167
+ * items of every other list. Only what differs is written, so that a document that has not
168
+ * changed is not changed by this either.
169
+ */
170
+ export function markItems(root) {
171
+ for (const list of Array.from(root.querySelectorAll('ul, ol'))) {
172
+ const gapped = markerGapTwips(list) !== null;
173
+ const ordered = list.tagName === 'OL';
174
+ let counter = ordered ? listStart(list) : 1;
175
+ let bullet = '';
176
+ if (gapped && !ordered) {
177
+ const own = (list.style?.listStyleType ?? '').trim().toLowerCase();
178
+ let depth = 0;
179
+ for (let up = list.parentElement?.closest('ul, ol'); up && root.contains(up); up = up.parentElement?.closest('ul, ol'))
180
+ depth++;
181
+ bullet = BULLETS[own] ?? (depth === 0 ? BULLETS.disc : depth === 1 ? BULLETS.circle : BULLETS.square);
182
+ }
183
+ for (const item of Array.from(list.children)) {
184
+ if (item.tagName !== 'LI')
185
+ continue;
186
+ let marker = null;
187
+ if (gapped) {
188
+ if (ordered) {
189
+ counter = itemNumber(item, counter);
190
+ marker = `${markerText(counter, numberStyleOf(list, item))}.`;
191
+ counter++;
192
+ }
193
+ else {
194
+ marker = bullet;
195
+ }
196
+ }
197
+ if (marker === null) {
198
+ if (item.hasAttribute(MARKER_ATTRIBUTE))
199
+ item.removeAttribute(MARKER_ATTRIBUTE);
200
+ }
201
+ else if (item.getAttribute(MARKER_ATTRIBUTE) !== marker) {
202
+ item.setAttribute(MARKER_ATTRIBUTE, marker);
203
+ }
204
+ }
205
+ }
206
+ }
207
+ /** Take the editor's markers out of a copy of a document. */
208
+ export function withoutMarkers(root) {
209
+ for (const item of Array.from(root.querySelectorAll(`[${MARKER_ATTRIBUTE}]`)))
210
+ item.removeAttribute(MARKER_ATTRIBUTE);
211
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Lists, as the editor makes them.
3
+ *
4
+ * The browsers' own list commands each make something else of the same click. Chromium and
5
+ * Safari leave the list inside the paragraph it was made from, which no HTML can say;
6
+ * Firefox starts a new list beside the one a line is next to, so that every line made an item
7
+ * one at a time is numbered 1; Chromium puts the caret at the start of the line. None of
8
+ * them nests an item under the one before it. So the document is changed here, the same way
9
+ * in every browser, and the editor's own history (history.ts) undoes it.
10
+ *
11
+ * The shape made is the one the RTF reader writes and the writer reads: a <ul> or <ol> of
12
+ * <li>, and a list inside a list as the last thing in the item it is under.
13
+ *
14
+ * <ol><li>Skin, left arm<ul><li>margins clear</li></ul></li><li>Lymph node</li></ol>
15
+ *
16
+ * Every function takes the editor's element and the selection, changes the document where
17
+ * there is something to change, puts the selection back in the words it was in, and returns
18
+ * whether it changed anything.
19
+ */
20
+ export type ListKind = 'ul' | 'ol';
21
+ /**
22
+ * The toolbar's list button. The lines the selection touches are made items of a list of
23
+ * this kind, and one list with a list of that kind they are next to. Where they are all
24
+ * items of such a list already, they are paragraphs again. Where they are items of the
25
+ * other kind: with a caret, the list the caret is in is made this kind; with words
26
+ * selected, the items selected are.
27
+ */
28
+ export declare function toggleList(root: HTMLElement, sel: Selection | null, kind: ListKind): boolean;
29
+ /** Which kind of list the selection is in: the innermost list of the line it begins in. */
30
+ export declare function listKindAt(root: HTMLElement, sel: Selection | null): ListKind | null;
31
+ /**
32
+ * Put the items the selection touches one list further in, each under the item before it.
33
+ * Returns false, with nothing changed, where the selection is not all items, or the first of
34
+ * them has no item before it to be under.
35
+ */
36
+ export declare function nestItems(root: HTMLElement, sel: Selection | null): boolean;
37
+ /** Put the items the selection touches that are in a list within a list one list further out. Returns false where none is. */
38
+ export declare function unnestItems(root: HTMLElement, sel: Selection | null): boolean;
39
+ /**
40
+ * The item the caret is in leaves its list by one step: one list further out, or, from a
41
+ * list that is in no other, a paragraph. (What Enter does in an item with nothing in it, and
42
+ * Backspace at the start of one.)
43
+ */
44
+ export declare function leaveList(root: HTMLElement, sel: Selection | null): boolean;
45
+ /** Whether the caret is in an item with nothing in it: no words, no picture. (One with a list under it has that.) */
46
+ export declare function inEmptyItem(root: HTMLElement, sel: Selection | null): boolean;
47
+ /** Whether the caret is at the very start of an item: nothing of the item before it. */
48
+ export declare function atItemStart(root: HTMLElement, sel: Selection | null): boolean;