svelte-rtf-editor 1.5.3 → 1.7.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.
- package/README.md +28 -0
- package/dist/components/InkEditor.svelte +345 -5
- package/dist/components/Toolbar.svelte +12 -0
- package/dist/rtf-parser.js +9 -1
- package/dist/rtf-writer.js +262 -21
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -202,6 +202,24 @@ The font has to be installed on the machine that displays the document. The RTF
|
|
|
202
202
|
|
|
203
203
|
---
|
|
204
204
|
|
|
205
|
+
## Paragraph formatting
|
|
206
|
+
|
|
207
|
+
A `<p>` or `<div>` keeps its own indents, spacing and tab stops in the RTF, so a layout made of ordinary paragraphs, such as a bold label, a tab, and text in a column with later lines hanging under it, reaches the receiving system:
|
|
208
|
+
|
|
209
|
+
| HTML on the paragraph | RTF |
|
|
210
|
+
|---|---|
|
|
211
|
+
| `margin-left: 1.75in` | `\li2520` |
|
|
212
|
+
| `text-indent: -1.75in` | `\fi-2520` |
|
|
213
|
+
| `margin-top: 5pt` / `margin-bottom: 5pt` | `\sb100` / `\sa100` |
|
|
214
|
+
| `break-after: avoid` or `page-break-after: avoid` | `\keepn` |
|
|
215
|
+
| `data-rtf-tab-stops="1.75in"` (comma-separated) | `\tx2520` |
|
|
216
|
+
|
|
217
|
+
- Lengths in `in`, `pt`, `cm`, `mm` or `px` (15 twips per px), rounded to whole twips. Only `text-indent` may be negative. A value the writer cannot read, or zero, writes nothing.
|
|
218
|
+
- CSS has no absolute tab stop, hence the `data-` attribute. On screen, `white-space: pre-wrap; tab-size: 1.75in` with that hanging indent puts the browser's first stop at the same place, and `pre-wrap` makes the writer send the tab as `\tab`.
|
|
219
|
+
- `margin-left` adds to the indent of the blocks around the paragraph (an indent pasted from a browser, or a `<div>` with a margin that holds paragraphs), and is written as one `\li`.
|
|
220
|
+
- Inside a table cell the cell declares its own paragraph: only alignment and the left indent are written there, not spacing, tab stops or keep-with-next.
|
|
221
|
+
- `rtfToHtml` does not yet read them back, so `RtfViewer` shows such a document without its indents.
|
|
222
|
+
|
|
205
223
|
## Theming
|
|
206
224
|
|
|
207
225
|
The components use CSS custom properties with sensible fallbacks, so they work out of the box but are easy to customise. Override these in your own CSS:
|
|
@@ -232,6 +250,16 @@ The components use CSS custom properties with sensible fallbacks, so they work o
|
|
|
232
250
|
| `Ctrl+K` | Insert link |
|
|
233
251
|
| `Ctrl+S` | Save (fires `onsave`) |
|
|
234
252
|
| `Backspace` / `Delete` | Remove the selected image |
|
|
253
|
+
| `Ctrl+]` / `Cmd+]` | Increase indent of the selected paragraphs by 0.5 in (RTF `\li720` per step) |
|
|
254
|
+
| `Ctrl+[` / `Cmd+[` | Decrease indent |
|
|
255
|
+
| `Tab` | Insert a tab (sent to RTF as `\tab`); two spaces in a code block. With several lines selected, increase their indent |
|
|
256
|
+
| `Shift+Tab` | Remove one tab from the start of the line. With several lines selected, decrease their indent |
|
|
257
|
+
| `Esc`, then `Tab` / `Shift+Tab` | Move focus out of the editor |
|
|
258
|
+
|
|
259
|
+
The toolbar's Increase indent and Decrease indent buttons do the same as `Ctrl+]` and `Ctrl+[`. Undo reverses an indent step until the next edit. Paragraph alignment (left, center, right, justify) is written to RTF as `\qc`, `\qr` or `\qj`.
|
|
260
|
+
|
|
261
|
+
Tab stays in the editor so a line can be indented. To leave the editor from the keyboard, press
|
|
262
|
+
`Esc` first. A readonly editor leaves Tab to the browser.
|
|
235
263
|
|
|
236
264
|
---
|
|
237
265
|
|
|
@@ -180,6 +180,7 @@
|
|
|
180
180
|
export function setHTML(html: string): void {
|
|
181
181
|
if (editorEl) {
|
|
182
182
|
selectedImage = null;
|
|
183
|
+
indentUndo = [];
|
|
183
184
|
editorEl.innerHTML = html;
|
|
184
185
|
updateCounts();
|
|
185
186
|
if (autosave) scheduleAutoSave();
|
|
@@ -211,6 +212,7 @@
|
|
|
211
212
|
export function clear(): void {
|
|
212
213
|
if (editorEl) {
|
|
213
214
|
selectedImage = null;
|
|
215
|
+
indentUndo = [];
|
|
214
216
|
editorEl.innerHTML = '<p></p>';
|
|
215
217
|
try { localStorage.removeItem(storageKey); } catch (e) {}
|
|
216
218
|
updateCounts();
|
|
@@ -276,10 +278,199 @@
|
|
|
276
278
|
const sel = window.getSelection();
|
|
277
279
|
if (!sel || sel.isCollapsed) return;
|
|
278
280
|
}
|
|
281
|
+
if (cmd === 'indent' || cmd === 'outdent') {
|
|
282
|
+
indentBlocks(cmd);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (cmd === 'undo' && undoIndent()) return;
|
|
279
286
|
document.execCommand(cmd, false, value ?? undefined);
|
|
280
287
|
updateToolbarState();
|
|
281
288
|
}
|
|
282
289
|
|
|
290
|
+
// ── Indent ──
|
|
291
|
+
// Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
|
|
292
|
+
// to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
|
|
293
|
+
// not used: Chromium's Outdent strips the first paragraph to loose text ("one<br>"), and the
|
|
294
|
+
// browsers disagree on the markup. Only a style changes (and a line of loose text gets a
|
|
295
|
+
// paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
|
|
296
|
+
// these steps until the next edit.
|
|
297
|
+
const INDENT_STEP_PX = 48;
|
|
298
|
+
const INDENT_TARGETS = 'p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure';
|
|
299
|
+
/** CSS lengths a margin is written in, in px. */
|
|
300
|
+
const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
|
|
301
|
+
|
|
302
|
+
/** One block an Indent or Outdent changed, and how to put it back. */
|
|
303
|
+
interface IndentChange {
|
|
304
|
+
el: HTMLElement;
|
|
305
|
+
before: string | null;
|
|
306
|
+
after: string | null;
|
|
307
|
+
/** The block is a paragraph this step made around loose text, and the <br> that ended it. */
|
|
308
|
+
wrapped: { br: HTMLBRElement | null } | null;
|
|
309
|
+
}
|
|
310
|
+
let indentUndo: IndentChange[][] = [];
|
|
311
|
+
|
|
312
|
+
function indentBlocks(cmd: 'indent' | 'outdent'): void {
|
|
313
|
+
if (readonly || !editorEl) return;
|
|
314
|
+
editorEl.focus();
|
|
315
|
+
const sel = window.getSelection();
|
|
316
|
+
if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
|
|
317
|
+
const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
|
|
318
|
+
const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
|
|
319
|
+
const targets = indentTargets(sel.getRangeAt(0), cmd, wrapped);
|
|
320
|
+
// Wrapping loose text moves the selected text nodes, which collapses the selection; put it
|
|
321
|
+
// back so the next press moves the same lines.
|
|
322
|
+
if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
|
|
323
|
+
sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
|
|
324
|
+
}
|
|
325
|
+
const step: IndentChange[] = [];
|
|
326
|
+
for (const el of targets) {
|
|
327
|
+
const current = marginLeftPx(el);
|
|
328
|
+
const next = cmd === 'indent' ? current + INDENT_STEP_PX : Math.max(0, current - INDENT_STEP_PX);
|
|
329
|
+
if (next === current) continue;
|
|
330
|
+
const before = el.getAttribute('style');
|
|
331
|
+
el.style.marginLeft = next > 0 ? `${Math.round(next * 100) / 100}px` : '';
|
|
332
|
+
if (!el.getAttribute('style')) el.removeAttribute('style');
|
|
333
|
+
const br = wrapped.get(el);
|
|
334
|
+
step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
|
|
335
|
+
}
|
|
336
|
+
if (step.length === 0) return;
|
|
337
|
+
indentUndo.push(step);
|
|
338
|
+
indentChanged();
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** An element's left margin in px: its own, from the inline style, or 0. */
|
|
342
|
+
function marginLeftPx(el: HTMLElement): number {
|
|
343
|
+
const value = el.style.marginLeft.trim().toLowerCase();
|
|
344
|
+
if (!value) return 0;
|
|
345
|
+
const m = /^(-?\d*\.?\d+)(px|pt|in|cm|mm)$/.exec(value);
|
|
346
|
+
const px = m ? parseFloat(m[1]) * PX_PER_UNIT[m[2]] : parseFloat(getComputedStyle(el).marginLeft);
|
|
347
|
+
return Math.max(0, px || 0);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The indent shape Chromium, WebKit and Gmail paste: a blockquote with a left margin and
|
|
352
|
+
* border: none. A quotation keeps its border. The RTF writer reads it the same way.
|
|
353
|
+
*/
|
|
354
|
+
function isIndentBlockquote(el: Element): el is HTMLElement {
|
|
355
|
+
return el instanceof HTMLElement && el.tagName === 'BLOCKQUOTE' && el.style.borderLeftStyle === 'none';
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Undo the last Indent or Outdent, if nothing has changed since. */
|
|
359
|
+
function undoIndent(): boolean {
|
|
360
|
+
const step = indentUndo.pop();
|
|
361
|
+
if (!step) return false;
|
|
362
|
+
// Content replaced or edited since (setHTML, an import, a link): the step no longer applies.
|
|
363
|
+
if (step.some(({ el, after }) => !el.isConnected || el.getAttribute('style') !== after)) {
|
|
364
|
+
indentUndo = [];
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
for (const { el, before, wrapped } of step) {
|
|
368
|
+
if (before === null) el.removeAttribute('style');
|
|
369
|
+
else el.setAttribute('style', before);
|
|
370
|
+
if (wrapped) {
|
|
371
|
+
if (wrapped.br) el.after(wrapped.br);
|
|
372
|
+
el.replaceWith(...Array.from(el.childNodes));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
indentChanged();
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function indentChanged(): void {
|
|
380
|
+
updateToolbarState();
|
|
381
|
+
fireChange();
|
|
382
|
+
if (autosave) scheduleAutoSave();
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* The blocks Indent moves: each line's paragraph, and a list, a quotation or a picture as a
|
|
387
|
+
* whole. A line of loose text (typed straight into the editor or a table cell) is first given a
|
|
388
|
+
* paragraph of its own, so the margin moves that line only. Outdent on a line with no margin
|
|
389
|
+
* of its own moves the pasted indent around it (isIndentBlockquote) instead.
|
|
390
|
+
*/
|
|
391
|
+
function indentTargets(
|
|
392
|
+
range: Range,
|
|
393
|
+
cmd: 'indent' | 'outdent',
|
|
394
|
+
wrapped: Map<HTMLElement, HTMLBRElement | null>
|
|
395
|
+
): HTMLElement[] {
|
|
396
|
+
if (!editorEl) return [];
|
|
397
|
+
const root = editorEl;
|
|
398
|
+
const found: HTMLElement[] = [];
|
|
399
|
+
const add = (el: HTMLElement | null) => {
|
|
400
|
+
if (el && !found.includes(el)) found.push(el);
|
|
401
|
+
};
|
|
402
|
+
const blockFor = (node: Node): HTMLElement | null => {
|
|
403
|
+
if (node === root || !root.contains(node)) return null;
|
|
404
|
+
const el = node instanceof Element ? node : node.parentElement;
|
|
405
|
+
if (!el) return null;
|
|
406
|
+
const cell = el.closest('td, th');
|
|
407
|
+
const inScope = (b: Element | null | undefined): b is HTMLElement =>
|
|
408
|
+
b instanceof HTMLElement && b !== root && root.contains(b) && (!cell || cell.contains(b));
|
|
409
|
+
const item = el.closest('li');
|
|
410
|
+
const closest = el.closest(INDENT_TARGETS);
|
|
411
|
+
const block = inScope(item) ? item.parentElement : inScope(closest) ? closest : null;
|
|
412
|
+
if (cmd === 'outdent' && (!block || marginLeftPx(block) === 0)) {
|
|
413
|
+
for (let a = (block ?? el).parentElement; inScope(a); a = a.parentElement) {
|
|
414
|
+
if (isIndentBlockquote(a) && marginLeftPx(a) > 0) return a;
|
|
415
|
+
}
|
|
416
|
+
return block;
|
|
417
|
+
}
|
|
418
|
+
if (inScope(block)) return block;
|
|
419
|
+
if (cmd === 'outdent') return null;
|
|
420
|
+
const made = wrapLooseLine(node);
|
|
421
|
+
if (made) wrapped.set(made.p, made.br);
|
|
422
|
+
return made?.p ?? null;
|
|
423
|
+
};
|
|
424
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
425
|
+
const texts: Text[] = [];
|
|
426
|
+
for (let n = walker.nextNode() as Text | null; n; n = walker.nextNode() as Text | null) {
|
|
427
|
+
if (!n.data.trim() || !range.intersectsNode(n)) continue;
|
|
428
|
+
// A selection that only touches a line's edge (dragged to the start of the next line)
|
|
429
|
+
// does not move that line.
|
|
430
|
+
if (n === range.endContainer && range.endOffset === 0 && !range.collapsed) continue;
|
|
431
|
+
if (n === range.startContainer && range.startOffset === n.length && !range.collapsed) continue;
|
|
432
|
+
texts.push(n);
|
|
433
|
+
}
|
|
434
|
+
if (texts.length === 0) add(blockFor(range.startContainer));
|
|
435
|
+
for (const t of texts) add(blockFor(t));
|
|
436
|
+
return found;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Put the run of loose text and inline elements around a node into a <p>, and return it with
|
|
441
|
+
* the <br> that ended the run, which the paragraph replaces.
|
|
442
|
+
*/
|
|
443
|
+
function wrapLooseLine(node: Node): { p: HTMLElement; br: HTMLBRElement | null } | null {
|
|
444
|
+
if (!editorEl || node === editorEl || !editorEl.contains(node)) return null;
|
|
445
|
+
let start: Node = node;
|
|
446
|
+
while (start.parentNode && start.parentNode !== editorEl && !(start.parentNode as Element).matches?.('td, th')) {
|
|
447
|
+
start = start.parentNode;
|
|
448
|
+
}
|
|
449
|
+
const parent = start.parentNode;
|
|
450
|
+
if (!parent || !editorEl.contains(parent)) return null;
|
|
451
|
+
const isBreak = (n: Node | null) =>
|
|
452
|
+
!n || (n instanceof Element && (n.matches(INDENT_TARGETS) || n.matches('br, table, hr')));
|
|
453
|
+
if (isBreak(start)) return null;
|
|
454
|
+
let first: Node = start;
|
|
455
|
+
while (!isBreak(first.previousSibling)) first = first.previousSibling!;
|
|
456
|
+
let last: Node = start;
|
|
457
|
+
while (!isBreak(last.nextSibling)) last = last.nextSibling!;
|
|
458
|
+
const p = document.createElement('p');
|
|
459
|
+
parent.insertBefore(p, first);
|
|
460
|
+
let n: Node | null = first;
|
|
461
|
+
while (n) {
|
|
462
|
+
const next: Node | null = n === last ? null : n.nextSibling;
|
|
463
|
+
p.appendChild(n);
|
|
464
|
+
n = next;
|
|
465
|
+
}
|
|
466
|
+
let br: HTMLBRElement | null = null;
|
|
467
|
+
if (p.nextSibling instanceof HTMLBRElement) {
|
|
468
|
+
br = p.nextSibling;
|
|
469
|
+
br.remove();
|
|
470
|
+
}
|
|
471
|
+
return { p, br };
|
|
472
|
+
}
|
|
473
|
+
|
|
283
474
|
// ── Block type ──
|
|
284
475
|
function setBlock(tag: string): void {
|
|
285
476
|
restoreSelection();
|
|
@@ -351,6 +542,7 @@
|
|
|
351
542
|
|
|
352
543
|
// ── Input handler ──
|
|
353
544
|
function handleInput(): void {
|
|
545
|
+
indentUndo = [];
|
|
354
546
|
updateToolbarState();
|
|
355
547
|
// Typing means the user is editing text, not the picture. Dropping the
|
|
356
548
|
// selection here keeps Backspace editing that text instead of deleting a
|
|
@@ -379,6 +571,8 @@
|
|
|
379
571
|
return;
|
|
380
572
|
}
|
|
381
573
|
linkError = '';
|
|
574
|
+
// Inserting changes the document outside an input event: earlier indent steps no longer undo.
|
|
575
|
+
indentUndo = [];
|
|
382
576
|
restoreSelection();
|
|
383
577
|
editorEl?.focus();
|
|
384
578
|
|
|
@@ -504,6 +698,7 @@
|
|
|
504
698
|
caption: string
|
|
505
699
|
): { img: HTMLImageElement; after: HTMLElement } | null {
|
|
506
700
|
if (!editorEl) return null;
|
|
701
|
+
indentUndo = [];
|
|
507
702
|
|
|
508
703
|
const figure = document.createElement('figure');
|
|
509
704
|
const img = document.createElement('img');
|
|
@@ -708,6 +903,7 @@
|
|
|
708
903
|
const html = await readRtfFile(file, { fontSize });
|
|
709
904
|
if (editorEl) {
|
|
710
905
|
selectedImage = null;
|
|
906
|
+
indentUndo = [];
|
|
711
907
|
editorEl.innerHTML = html;
|
|
712
908
|
updateCounts();
|
|
713
909
|
fireChange();
|
|
@@ -730,6 +926,9 @@
|
|
|
730
926
|
if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
|
|
731
927
|
if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
|
|
732
928
|
if (mod && e.key === 's') { e.preventDefault(); autoSaveNow(); }
|
|
929
|
+
if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && undoIndent()) { e.preventDefault(); return; }
|
|
930
|
+
if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
|
|
931
|
+
if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
|
|
733
932
|
|
|
734
933
|
// Moving the caret leaves the picture behind, so drop its selection frame.
|
|
735
934
|
// Deliberately falls through: these keys still have their normal meaning,
|
|
@@ -747,13 +946,140 @@
|
|
|
747
946
|
return;
|
|
748
947
|
}
|
|
749
948
|
|
|
750
|
-
if (e.key === 'Tab')
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
949
|
+
if (e.key === 'Tab') handleTab(e);
|
|
950
|
+
else tabLeavesEditor = e.key === 'Escape';
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// ── Tab ──
|
|
954
|
+
// Tab types a tab, as in a word processor, so a pathologist can indent a line; before this it
|
|
955
|
+
// left the editor for the next control on the page. Escape, then Tab or Shift+Tab, still moves
|
|
956
|
+
// focus on, so the keyboard is never trapped here. A readonly editor keeps the browser's Tab.
|
|
957
|
+
let tabLeavesEditor = false;
|
|
958
|
+
|
|
959
|
+
function handleTab(e: KeyboardEvent): void {
|
|
960
|
+
if (readonly || e.ctrlKey || e.metaKey || e.altKey) return;
|
|
961
|
+
if (tabLeavesEditor) {
|
|
962
|
+
tabLeavesEditor = false;
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
const sel = window.getSelection();
|
|
966
|
+
if (!sel || !sel.anchorNode || !editorEl?.contains(sel.anchorNode)) return;
|
|
967
|
+
e.preventDefault();
|
|
968
|
+
|
|
969
|
+
if (sel.anchorNode.parentElement?.closest?.('pre')) {
|
|
970
|
+
if (!e.shiftKey) document.execCommand('insertText', false, ' ');
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
// Several lines selected: Tab and Shift+Tab indent and outdent them all, as a word
|
|
974
|
+
// processor does. Within one line, Tab types a tab.
|
|
975
|
+
if (selectionSpansLines(sel)) {
|
|
976
|
+
indentBlocks(e.shiftKey ? 'outdent' : 'indent');
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
if (!e.shiftKey) {
|
|
980
|
+
insertTab(sel);
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
// Shift+Tab takes one tab off the start of the line the caret is on, wherever the caret is
|
|
984
|
+
// on it, as a word processor outdents.
|
|
985
|
+
if (sel.isCollapsed) removeLeadingTab(sel);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Type a tab, on the undo stack. Chromium and WebKit wrap it in <span style="white-space:pre">,
|
|
990
|
+
* which the RTF writer sends as \tab. Firefox types spaces instead, so there the typing is
|
|
991
|
+
* undone and the same span is inserted, with the caret put after it so the text that follows
|
|
992
|
+
* is not typed inside it.
|
|
993
|
+
*/
|
|
994
|
+
function insertTab(sel: Selection): void {
|
|
995
|
+
document.execCommand('insertText', false, '\t');
|
|
996
|
+
if (textBeforeCaret(sel).endsWith('\t')) return;
|
|
997
|
+
document.execCommand('undo');
|
|
998
|
+
document.execCommand('insertHTML', false, '<span style="white-space:pre">\t</span>');
|
|
999
|
+
const node = sel.anchorNode;
|
|
1000
|
+
const span = (node instanceof Element ? node : node?.parentElement)?.closest('span');
|
|
1001
|
+
if (span && span.textContent === '\t' && editorEl?.contains(span)) {
|
|
1002
|
+
const after = document.createRange();
|
|
1003
|
+
after.setStartAfter(span);
|
|
1004
|
+
after.collapse(true);
|
|
1005
|
+
sel.removeAllRanges();
|
|
1006
|
+
sel.addRange(after);
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function textBeforeCaret(sel: Selection): string {
|
|
1011
|
+
if (!editorEl || sel.rangeCount === 0) return '';
|
|
1012
|
+
const range = sel.getRangeAt(0).cloneRange();
|
|
1013
|
+
range.collapse(true);
|
|
1014
|
+
range.setStart(editorEl, 0);
|
|
1015
|
+
return range.toString();
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** Whether a selection runs across more than one paragraph or line. */
|
|
1019
|
+
function selectionSpansLines(sel: Selection): boolean {
|
|
1020
|
+
if (sel.isCollapsed || sel.rangeCount === 0 || !editorEl) return false;
|
|
1021
|
+
const range = sel.getRangeAt(0);
|
|
1022
|
+
const blockOf = (n: Node) =>
|
|
1023
|
+
(n instanceof Element ? n : n.parentElement)?.closest(LINE_BLOCKS) ?? editorEl;
|
|
1024
|
+
if (blockOf(range.startContainer) !== blockOf(range.endContainer)) return true;
|
|
1025
|
+
return range.cloneContents().querySelector('br') !== null;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const LINE_BLOCKS = 'p, div, li, td, th, h1, h2, h3, h4, h5, h6, blockquote';
|
|
1029
|
+
|
|
1030
|
+
/** The first tab of the caret's line, if the line starts with one: its text node and offset. */
|
|
1031
|
+
function leadingTab(sel: Selection): { node: Text; offset: number } | null {
|
|
1032
|
+
if (!editorEl || !sel.anchorNode) return null;
|
|
1033
|
+
const anchorEl = sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode.parentElement;
|
|
1034
|
+
const found = anchorEl?.closest(LINE_BLOCKS);
|
|
1035
|
+
const block = found && editorEl.contains(found) && found !== editorEl ? found : editorEl;
|
|
1036
|
+
const caret = sel.getRangeAt(0);
|
|
1037
|
+
|
|
1038
|
+
// Walk the block's text and line breaks up to the caret. A <br>, or text in a different
|
|
1039
|
+
// block from the text before it, starts a new line.
|
|
1040
|
+
const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
|
1041
|
+
let lineStart: { node: Text; offset: number } | null = null;
|
|
1042
|
+
let lineHasText = false;
|
|
1043
|
+
let lastBlock: Element | null = null;
|
|
1044
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
1045
|
+
if (caret.comparePoint(n, 0) > 0) break;
|
|
1046
|
+
if (n.nodeName === 'BR') {
|
|
1047
|
+
lineStart = null;
|
|
1048
|
+
lineHasText = false;
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
if (n.nodeType !== Node.TEXT_NODE) continue;
|
|
1052
|
+
const textBlock = n.parentElement?.closest(LINE_BLOCKS) ?? block;
|
|
1053
|
+
if (textBlock !== lastBlock) {
|
|
1054
|
+
lastBlock = textBlock;
|
|
1055
|
+
lineStart = null;
|
|
1056
|
+
lineHasText = false;
|
|
1057
|
+
}
|
|
1058
|
+
if (!lineHasText) {
|
|
1059
|
+
const text = (n as Text).data;
|
|
1060
|
+
if (text.length === 0) continue;
|
|
1061
|
+
lineHasText = true;
|
|
1062
|
+
lineStart = text[0] === '\t' ? { node: n as Text, offset: 0 } : null;
|
|
755
1063
|
}
|
|
756
1064
|
}
|
|
1065
|
+
return lineStart;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function removeLeadingTab(sel: Selection): void {
|
|
1069
|
+
const tab = leadingTab(sel);
|
|
1070
|
+
if (!tab) return;
|
|
1071
|
+
const caret = sel.getRangeAt(0).cloneRange();
|
|
1072
|
+
const range = document.createRange();
|
|
1073
|
+
range.setStart(tab.node, tab.offset);
|
|
1074
|
+
range.setEnd(tab.node, tab.offset + 1);
|
|
1075
|
+
// Delete through execCommand so Ctrl+Z puts the tab back, then return the caret.
|
|
1076
|
+
sel.removeAllRanges();
|
|
1077
|
+
sel.addRange(range);
|
|
1078
|
+
document.execCommand('delete');
|
|
1079
|
+
if (caret.startContainer.isConnected) {
|
|
1080
|
+
sel.removeAllRanges();
|
|
1081
|
+
sel.addRange(caret);
|
|
1082
|
+
}
|
|
757
1083
|
}
|
|
758
1084
|
|
|
759
1085
|
function handlePaste(e: ClipboardEvent): void {
|
|
@@ -848,6 +1174,8 @@
|
|
|
848
1174
|
onmouseup={updateToolbarState}
|
|
849
1175
|
onkeyup={updateToolbarState}
|
|
850
1176
|
onkeydown={handleKeydown}
|
|
1177
|
+
onmousedown={() => (tabLeavesEditor = false)}
|
|
1178
|
+
onblur={() => (tabLeavesEditor = false)}
|
|
851
1179
|
onpaste={handlePaste}
|
|
852
1180
|
onclick={handleContentClick}
|
|
853
1181
|
ondragover={handleDragOver}
|
|
@@ -1034,6 +1362,18 @@
|
|
|
1034
1362
|
border-radius: 0 var(--radius-sm, 5px) var(--radius-sm, 5px) 0;
|
|
1035
1363
|
}
|
|
1036
1364
|
|
|
1365
|
+
/* The indent Chromium, WebKit and Gmail paste (border: none) is an indent, not a quotation:
|
|
1366
|
+
the RTF writes it plain, so it shows plain here too. */
|
|
1367
|
+
.ink-content :global(blockquote[style*='border: none']),
|
|
1368
|
+
.ink-content :global(blockquote[style*='border:none']),
|
|
1369
|
+
.ink-content :global(blockquote[style*='border-style: none']),
|
|
1370
|
+
.ink-content :global(blockquote[style*='border-left: none']) {
|
|
1371
|
+
font-style: normal;
|
|
1372
|
+
color: inherit;
|
|
1373
|
+
background: none;
|
|
1374
|
+
border-radius: 0;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1037
1377
|
.ink-content :global(pre) {
|
|
1038
1378
|
background: var(--ink, #1a1714);
|
|
1039
1379
|
color: #e8e2da;
|
|
@@ -96,6 +96,18 @@
|
|
|
96
96
|
|
|
97
97
|
<div class="toolbar-divider"></div>
|
|
98
98
|
|
|
99
|
+
<!-- Indent -->
|
|
100
|
+
<div class="toolbar-group">
|
|
101
|
+
<ToolbarButton title="Decrease indent (Ctrl+[)" onclick={() => exec('outdent')}>
|
|
102
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="7 9 4 12 7 15"/></svg>
|
|
103
|
+
</ToolbarButton>
|
|
104
|
+
<ToolbarButton title="Increase indent (Ctrl+])" onclick={() => exec('indent')}>
|
|
105
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="5" x2="21" y2="5"/><line x1="11" y1="10" x2="21" y2="10"/><line x1="11" y1="14" x2="21" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="4 9 7 12 4 15"/></svg>
|
|
106
|
+
</ToolbarButton>
|
|
107
|
+
</div>
|
|
108
|
+
|
|
109
|
+
<div class="toolbar-divider"></div>
|
|
110
|
+
|
|
99
111
|
<!-- Insert -->
|
|
100
112
|
<div class="toolbar-group">
|
|
101
113
|
<ToolbarButton title="Insert link (Ctrl+K)" onclick={oninsertlink}>
|
package/dist/rtf-parser.js
CHANGED
|
@@ -47,6 +47,10 @@ const HEX_NIBBLE = (() => {
|
|
|
47
47
|
}
|
|
48
48
|
return table;
|
|
49
49
|
})();
|
|
50
|
+
/** A tab as the editor's Tab key inserts it (Chromium's own shape for a typed tab). */
|
|
51
|
+
const TAB_HTML = '<span style="white-space:pre">\t</span>';
|
|
52
|
+
/** A paragraph so far holding only a list marker: a bullet, or a number and a period. */
|
|
53
|
+
const LIST_MARKER = /^(?:<[^>]+>)*\s*(?:\u2022|\d+\.)\s*(?:<\/[^>]+>)*$/;
|
|
50
54
|
/** Hex picture data → base64, without depending on btoa/Buffer. */
|
|
51
55
|
function hexToBase64(hex) {
|
|
52
56
|
const byteCount = hex.length >> 1;
|
|
@@ -691,7 +695,11 @@ export function rtfToHtml(rtfString, options = {}) {
|
|
|
691
695
|
paragraphHasText = true;
|
|
692
696
|
break;
|
|
693
697
|
case 'tab':
|
|
694
|
-
|
|
698
|
+
// A real tab, in the shape the editor's Tab key inserts, so it shows as
|
|
699
|
+
// one and is written back as \tab (an em space came back as \u8195).
|
|
700
|
+
// After a list marker ("\bullet\tab", "1.\tab") the gap stays an em
|
|
701
|
+
// space: lists are read as plain lines, and a full tab there is too wide.
|
|
702
|
+
currentParagraph += LIST_MARKER.test(currentParagraph) ? ' ' : TAB_HTML;
|
|
695
703
|
paragraphHasText = true;
|
|
696
704
|
break;
|
|
697
705
|
case 'pntext':
|
package/dist/rtf-writer.js
CHANGED
|
@@ -97,6 +97,30 @@ function escapeRtf(text) {
|
|
|
97
97
|
}
|
|
98
98
|
return out;
|
|
99
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* Text with its tabs written as RTF's \tab when the screen shows them as tabs. Any other tab is
|
|
102
|
+
* passed through as before (1.5.3), unchanged by this.
|
|
103
|
+
*/
|
|
104
|
+
function escapeTabs(text, tabsShow) {
|
|
105
|
+
if (!tabsShow || !text.includes('\t'))
|
|
106
|
+
return escapeRtf(text);
|
|
107
|
+
return text.split('\t').map(escapeRtf).join('\\tab ');
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Whether a text node's tabs show as tabs: it sits inside an element whose inline white-space
|
|
111
|
+
* keeps them. That is what the editor's Tab key inserts (Chromium's
|
|
112
|
+
* <span style="white-space:pre">\t</span>) and Safari's older Apple-tab-span.
|
|
113
|
+
*/
|
|
114
|
+
function showsTabs(node) {
|
|
115
|
+
for (let el = node.parentElement; el; el = el.parentElement) {
|
|
116
|
+
const ws = el.style?.whiteSpace;
|
|
117
|
+
if (ws)
|
|
118
|
+
return ws === 'pre' || ws === 'pre-wrap' || ws === 'break-spaces';
|
|
119
|
+
if (el.classList?.contains('Apple-tab-span'))
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
100
124
|
// ── Image helpers ──
|
|
101
125
|
const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
|
102
126
|
const B64_LOOKUP = (() => {
|
|
@@ -263,9 +287,10 @@ function imageBody(el) {
|
|
|
263
287
|
const label = el.getAttribute('alt') || el.getAttribute('src') || 'image';
|
|
264
288
|
return `\\i [Image: ${escapeRtf(label)}]\\i0 `;
|
|
265
289
|
}
|
|
266
|
-
/** \ql / \qc / \qr for a
|
|
290
|
+
/** \ql / \qc / \qr / \qj for a block's text-align. */
|
|
267
291
|
function alignControl(el) {
|
|
268
|
-
|
|
292
|
+
// Firefox's Center writes <p align="center">, not a style.
|
|
293
|
+
const align = (el.style?.textAlign || el.getAttribute?.('align') || '').toLowerCase();
|
|
269
294
|
if (align === 'center')
|
|
270
295
|
return '\\qc';
|
|
271
296
|
if (align === 'right')
|
|
@@ -354,6 +379,25 @@ export function estimateRtfBytes(editorEl) {
|
|
|
354
379
|
// Text at its escaped length: a character outside ASCII costs its \uN\'3f escape,
|
|
355
380
|
// six to nine bytes rather than one.
|
|
356
381
|
total += escapeRtf(editorEl.textContent || '').length;
|
|
382
|
+
// A tab that shows is written as "\tab " (5) and counted as 1; counting every tab that way
|
|
383
|
+
// can only overestimate.
|
|
384
|
+
total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
|
|
385
|
+
// A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
|
|
386
|
+
// for every block inside an indented one too: count 12 for each block that could carry them.
|
|
387
|
+
for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
|
|
388
|
+
if (block.closest('[style*="margin"], [style*="text-align"], [align]'))
|
|
389
|
+
total += 12;
|
|
390
|
+
}
|
|
391
|
+
// Each paragraph's formatting, worked out once: a blank line looks at the one before it.
|
|
392
|
+
const formatCache = new Map();
|
|
393
|
+
const ownFormat = (el) => {
|
|
394
|
+
let format = formatCache.get(el);
|
|
395
|
+
if (format === undefined) {
|
|
396
|
+
format = `${alignOf(el)}${paragraphControls(el, leftMarginTwips(el))}`;
|
|
397
|
+
formatCache.set(el, format);
|
|
398
|
+
}
|
|
399
|
+
return format;
|
|
400
|
+
};
|
|
357
401
|
for (const el of Array.from(editorEl.querySelectorAll('*'))) {
|
|
358
402
|
const tag = el.tagName.toLowerCase();
|
|
359
403
|
total += BLOCK_OVERHEAD_BYTES[tag] ?? 0;
|
|
@@ -369,6 +413,15 @@ export function estimateRtfBytes(editorEl) {
|
|
|
369
413
|
// writes one paragraph per item, so the item is counted, not the list.
|
|
370
414
|
if (CELL_PARAGRAPH_TAGS.has(tag) && el.closest('td, th'))
|
|
371
415
|
total += 6;
|
|
416
|
+
// A paragraph's own formatting costs its controls, and a blank line after one restates
|
|
417
|
+
// \pard (5); counting both on every such paragraph can only overestimate. The indent of
|
|
418
|
+
// the blocks around it is counted above.
|
|
419
|
+
if ((tag === 'p' || tag === 'div') && !el.closest('td, th')) {
|
|
420
|
+
const para = ownFormat(el);
|
|
421
|
+
const prev = el.previousElementSibling;
|
|
422
|
+
if (para || (prev && formatCache.get(prev)))
|
|
423
|
+
total += para.length + 6;
|
|
424
|
+
}
|
|
372
425
|
// Every cell in a row with a header cell carries \clbrdrb\brdrs.
|
|
373
426
|
if (tag === 'td' && el.parentElement?.querySelector(':scope > th'))
|
|
374
427
|
total += 14;
|
|
@@ -500,7 +553,8 @@ export function htmlToRtf(editorEl, options = {}) {
|
|
|
500
553
|
size: bodySize,
|
|
501
554
|
color: 0,
|
|
502
555
|
script: null,
|
|
503
|
-
mono: false
|
|
556
|
+
mono: false,
|
|
557
|
+
indent: 0
|
|
504
558
|
});
|
|
505
559
|
const rtf = '{\\rtf1\\ansi\\ansicpg1252\\deff0' +
|
|
506
560
|
fontTable +
|
|
@@ -540,16 +594,19 @@ function walkChildren(parent, ctx) {
|
|
|
540
594
|
// Whitespace between two blocks (the newline in "</p>\n<p>") shows as
|
|
541
595
|
// nothing in a browser. Written out, it became a space at the start of
|
|
542
596
|
// the next paragraph.
|
|
543
|
-
|
|
597
|
+
const tabsShow = ctx.inPre || showsTabs(node);
|
|
598
|
+
if (!tabsShow && COLLAPSIBLE_WHITESPACE.test(text) && besideBlock(node))
|
|
544
599
|
continue;
|
|
600
|
+
if (!ctx.inPre)
|
|
601
|
+
rtf += restateAfterBlock(node, ctx);
|
|
545
602
|
if (ctx.inPre) {
|
|
546
603
|
// Split before escaping — escapeRtf collapses newlines, so the
|
|
547
604
|
// line structure a <pre> block depends on has to become \line
|
|
548
605
|
// first. Handles CR, LF and CRLF alike.
|
|
549
|
-
rtf += text.split(/\r\n|\r|\n/).map(
|
|
606
|
+
rtf += text.split(/\r\n|\r|\n/).map((line) => escapeTabs(line, true)).join('\\line ');
|
|
550
607
|
}
|
|
551
608
|
else {
|
|
552
|
-
rtf +=
|
|
609
|
+
rtf += escapeTabs(text, tabsShow);
|
|
553
610
|
}
|
|
554
611
|
continue;
|
|
555
612
|
}
|
|
@@ -557,21 +614,24 @@ function walkChildren(parent, ctx) {
|
|
|
557
614
|
continue;
|
|
558
615
|
const el = node;
|
|
559
616
|
const tag = el.tagName.toLowerCase();
|
|
617
|
+
// A picture directly under the root writes its own paragraph.
|
|
618
|
+
if (!isBlock(el) && !(tag === 'img' && el.parentNode === ctx.root))
|
|
619
|
+
rtf += restateAfterBlock(el, ctx);
|
|
560
620
|
switch (tag) {
|
|
561
621
|
// Heading sizes keep their ratio to the body (HEADING_SCALE).
|
|
562
622
|
case 'h1': {
|
|
563
623
|
const size = scaled(ctx, HEADING_SCALE.h1);
|
|
564
|
-
rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
624
|
+
rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
565
625
|
break;
|
|
566
626
|
}
|
|
567
627
|
case 'h2': {
|
|
568
628
|
const size = scaled(ctx, HEADING_SCALE.h2);
|
|
569
|
-
rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
629
|
+
rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
570
630
|
break;
|
|
571
631
|
}
|
|
572
632
|
case 'h3': {
|
|
573
633
|
const size = scaled(ctx, HEADING_SCALE.h3);
|
|
574
|
-
rtf += `\\pard${inCell(ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
634
|
+
rtf += `\\pard${inCell(ctx)}${paragraphLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
|
|
575
635
|
break;
|
|
576
636
|
}
|
|
577
637
|
case 'p':
|
|
@@ -585,9 +645,11 @@ function walkChildren(parent, ctx) {
|
|
|
585
645
|
// the two lines run together.
|
|
586
646
|
const afterLooseText = followsInlineContent(el);
|
|
587
647
|
if (ctx.inTableCell) {
|
|
648
|
+
// Alignment or an indent needs a paragraph of its own, even as the cell's first.
|
|
649
|
+
const layout = paragraphLayout(el, ctx);
|
|
588
650
|
const restate = afterLooseText
|
|
589
|
-
?
|
|
590
|
-
: el.previousElementSibling ?
|
|
651
|
+
? `\\par \\pard\\intbl${layout} `
|
|
652
|
+
: el.previousElementSibling || layout ? `\\pard\\intbl${layout} ` : '';
|
|
591
653
|
if (isBlankLine(el)) {
|
|
592
654
|
rtf += `${restate}\\par `;
|
|
593
655
|
break;
|
|
@@ -599,17 +661,38 @@ function walkChildren(parent, ctx) {
|
|
|
599
661
|
: `${restate}${inner}\\par `;
|
|
600
662
|
break;
|
|
601
663
|
}
|
|
664
|
+
// A <div> that holds blocks (pasted content wraps paragraphs in one) is not a
|
|
665
|
+
// paragraph itself: each block inside writes its own \\pard, which would drop the
|
|
666
|
+
// div's indent, and the div's own \\par would add a blank line. Its left margin is
|
|
667
|
+
// carried into the blocks instead, and loose text in it gets a paragraph.
|
|
668
|
+
if (tag === 'div' && Array.from(el.children).some(isBlock)) {
|
|
669
|
+
const indent = ctx.indent + leftMarginTwips(el);
|
|
670
|
+
const colorIdx = colorIndexOf(el, ctx);
|
|
671
|
+
const inner = { ...ctx, indent, color: colorIdx ?? ctx.color };
|
|
672
|
+
const lead = startsWithInline(el) ? `\\pard${liControl(indent)} ` : '';
|
|
673
|
+
const tail = endsWithInline(el) ? '\\par ' : '';
|
|
674
|
+
const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
|
|
675
|
+
const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
|
|
676
|
+
rtf += `${afterLooseText ? '\\par ' : ''}${lead}${colorPrefix}${walkChildren(el, inner)}${colorSuffix}${tail}`;
|
|
677
|
+
break;
|
|
678
|
+
}
|
|
679
|
+
// The paragraph's alignment, indents, spacing, keep-with-next and tab stops, if it
|
|
680
|
+
// sets any.
|
|
681
|
+
const para = paragraphFormat(el, ctx);
|
|
602
682
|
// A <p> with no children or only a single <br> is a blank line —
|
|
603
683
|
// emit a bare \par rather than \pard \line\par, which adds an extra line.
|
|
684
|
+
// A bare \par keeps the formatting of the paragraph before it, so a blank line after a
|
|
685
|
+
// formatted paragraph, or with formatting of its own, restates \pard.
|
|
604
686
|
if (isBlankLine(el)) {
|
|
605
|
-
|
|
687
|
+
const reset = para || followsFormattedParagraph(el, ctx) ? `\\pard${para} ` : '';
|
|
688
|
+
rtf += `${afterLooseText ? '\\par ' : ''}${reset}\\par `;
|
|
606
689
|
break;
|
|
607
690
|
}
|
|
608
691
|
const colorIdx = colorIndexOf(el, ctx);
|
|
609
692
|
const inlineRtf = walkChildren(el, colorIdx != null ? { ...ctx, color: colorIdx } : ctx);
|
|
610
693
|
const colorPrefix = colorIdx != null ? `\\cf${colorIdx} ` : '';
|
|
611
694
|
const colorSuffix = colorIdx != null ? `\\cf${ctx.color} ` : '';
|
|
612
|
-
rtf += `${afterLooseText ? '\\par ' : ''}\\pard ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
|
|
695
|
+
rtf += `${afterLooseText ? '\\par ' : ''}\\pard${para} ${colorPrefix}${inlineRtf}${colorSuffix}\\par `;
|
|
613
696
|
break;
|
|
614
697
|
}
|
|
615
698
|
case 'table': {
|
|
@@ -649,12 +732,25 @@ function walkChildren(parent, ctx) {
|
|
|
649
732
|
}
|
|
650
733
|
break;
|
|
651
734
|
}
|
|
652
|
-
case 'blockquote':
|
|
653
|
-
|
|
735
|
+
case 'blockquote': {
|
|
736
|
+
// The browser's Indent wraps the lines in a blockquote with a left margin and
|
|
737
|
+
// border: none (Chromium, WebKit, Gmail): that is an indent, not a quotation, so it
|
|
738
|
+
// is not italic. A quotation is indented half an inch, plus any margin of its own.
|
|
739
|
+
// Either way the blocks inside carry the indent, and loose text gets a paragraph.
|
|
740
|
+
const quote = !isIndentBlockquote(el);
|
|
741
|
+
const indent = ctx.indent + leftMarginTwips(el) + (quote ? 720 : 0);
|
|
742
|
+
const inner = { ...ctx, indent, italic: ctx.italic || quote };
|
|
743
|
+
const lead = startsWithInline(el) ? `\\pard${inCell(ctx)}${liControl(indent)}` : '';
|
|
744
|
+
const tail = endsWithInline(el) ? '\\par ' : '';
|
|
745
|
+
const content = walkChildren(el, inner);
|
|
746
|
+
const italicOn = quote && !ctx.italic;
|
|
747
|
+
const italicOff = italicOn ? (tail ? '\\i0' : '\\i0 ') : '';
|
|
748
|
+
rtf += `${lead}${italicOn ? '\\i ' : lead ? ' ' : ''}${content}${italicOff}${tail}`;
|
|
654
749
|
break;
|
|
750
|
+
}
|
|
655
751
|
case 'pre': {
|
|
656
752
|
const size = scaled(ctx, PRE_SCALE);
|
|
657
|
-
rtf += `\\pard${inCell(ctx)}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
|
|
753
|
+
rtf += `\\pard${inCell(ctx)}${liControl(ctx.indent + leftMarginTwips(el))}\\f1\\fs${size} ${walkChildren(el, { ...ctx, inPre: true, size })}\\f0\\fs${ctx.size}\\par `;
|
|
658
754
|
break;
|
|
659
755
|
}
|
|
660
756
|
case 'hr':
|
|
@@ -662,16 +758,18 @@ function walkChildren(parent, ctx) {
|
|
|
662
758
|
break;
|
|
663
759
|
case 'ul': {
|
|
664
760
|
const items = el.querySelectorAll(':scope > li');
|
|
665
|
-
|
|
666
|
-
|
|
761
|
+
const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
|
|
762
|
+
items.forEach((item) => {
|
|
763
|
+
rtf += `\\pard${inCell(ctx)}${li}\\fi-360\\bullet\\tab ${walkChildren(item, ctx)}\\par `;
|
|
667
764
|
});
|
|
668
765
|
break;
|
|
669
766
|
}
|
|
670
767
|
case 'ol': {
|
|
671
768
|
let counter = 1;
|
|
672
769
|
const items = el.querySelectorAll(':scope > li');
|
|
673
|
-
|
|
674
|
-
|
|
770
|
+
const li = liControl(ctx.indent + leftMarginTwips(el) + 720);
|
|
771
|
+
items.forEach((item) => {
|
|
772
|
+
rtf += `\\pard${inCell(ctx)}${li}\\fi-360 ${counter}.\\tab ${walkChildren(item, ctx)}\\par `;
|
|
675
773
|
counter++;
|
|
676
774
|
});
|
|
677
775
|
break;
|
|
@@ -736,7 +834,7 @@ function walkChildren(parent, ctx) {
|
|
|
736
834
|
case 'figure': {
|
|
737
835
|
const img = el.querySelector('img');
|
|
738
836
|
const caption = (el.querySelector('figcaption')?.textContent || '').trim();
|
|
739
|
-
const align = alignControl(el)
|
|
837
|
+
const align = `${alignControl(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
|
|
740
838
|
if (img)
|
|
741
839
|
rtf += `\\pard${inCell(ctx)}${align} ${imageBody(img)}\\par `;
|
|
742
840
|
else
|
|
@@ -823,6 +921,29 @@ function followsInlineContent(el) {
|
|
|
823
921
|
return true;
|
|
824
922
|
return prev.nodeType === Node.ELEMENT_NODE && !isBlock(prev);
|
|
825
923
|
}
|
|
924
|
+
/** Blocks whose last paragraph always carries an indent or alignment of its own. */
|
|
925
|
+
const FORMATTED_BLOCK_TAGS = new Set(['ul', 'ol', 'blockquote', 'figure', 'hr']);
|
|
926
|
+
/**
|
|
927
|
+
* Loose text or an inline element right after a block has no paragraph of its own, and would
|
|
928
|
+
* keep that block's alignment and indent (a centered line's \qc, a list's \li). Start a plain
|
|
929
|
+
* one, at the indent of the blocks around it. After a block with no formatting of its own,
|
|
930
|
+
* nothing is written, as before.
|
|
931
|
+
*/
|
|
932
|
+
function restateAfterBlock(node, ctx) {
|
|
933
|
+
let prev = node.previousSibling;
|
|
934
|
+
while (prev && prev.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(prev.textContent || '')) {
|
|
935
|
+
prev = prev.previousSibling;
|
|
936
|
+
}
|
|
937
|
+
if (!isBlock(prev))
|
|
938
|
+
return '';
|
|
939
|
+
const block = prev;
|
|
940
|
+
const tag = block.tagName.toLowerCase();
|
|
941
|
+
const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
|
|
942
|
+
(['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '') ||
|
|
943
|
+
(['h1', 'h2', 'h3'].includes(tag) && paragraphLayout(block, ctx) !== '') ||
|
|
944
|
+
(tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
|
|
945
|
+
return formatted ? `\\pard${inCell(ctx)}${liControl(ctx.indent)} ` : '';
|
|
946
|
+
}
|
|
826
947
|
/**
|
|
827
948
|
* The cell's own \par ends its last paragraph, so that paragraph's mark is dropped. Only a
|
|
828
949
|
* real control word: "\par " preceded by an odd run of backslashes is escaped text.
|
|
@@ -835,6 +956,126 @@ function withoutTrailingPar(content) {
|
|
|
835
956
|
slashes++;
|
|
836
957
|
return slashes % 2 === 0 ? content.slice(0, -5) : content;
|
|
837
958
|
}
|
|
959
|
+
// ── Paragraph formatting ──
|
|
960
|
+
const TWIPS_PER_UNIT = { in: 1440, pt: 20, cm: 1440 / 2.54, mm: 144 / 2.54, px: TWIPS_PER_PX };
|
|
961
|
+
/**
|
|
962
|
+
* A CSS length in whole twips, or null when it cannot be read: a unit other than in, pt, cm, mm or
|
|
963
|
+
* px, a percentage, a keyword, or a negative value where one is not allowed.
|
|
964
|
+
*/
|
|
965
|
+
function lengthTwips(value, allowNegative = false) {
|
|
966
|
+
const m = (value ?? '').trim().toLowerCase().match(/^(-?\d+(?:\.\d+)?|-?\.\d+)(in|pt|cm|mm|px)$/);
|
|
967
|
+
if (!m)
|
|
968
|
+
return null;
|
|
969
|
+
const twips = Math.round(parseFloat(m[1]) * TWIPS_PER_UNIT[m[2]]);
|
|
970
|
+
if (twips < 0 && !allowNegative)
|
|
971
|
+
return null;
|
|
972
|
+
return twips;
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* An element's own left margin in twips, from its inline style: what the browser's Indent sets
|
|
976
|
+
* (Firefox puts margin-left on the paragraph; Chromium and WebKit on a wrapping blockquote).
|
|
977
|
+
* Units a reader cannot pin to a length (%, em) count as none.
|
|
978
|
+
*/
|
|
979
|
+
function leftMarginTwips(el) {
|
|
980
|
+
return lengthTwips(el.style?.marginLeft) ?? 0;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* The indent shape Chromium, WebKit and Gmail write: a blockquote with border: none, where a
|
|
984
|
+
* quotation keeps its border. The editor's Indent reads it the same way.
|
|
985
|
+
*/
|
|
986
|
+
function isIndentBlockquote(el) {
|
|
987
|
+
return el.style?.borderLeftStyle === 'none';
|
|
988
|
+
}
|
|
989
|
+
/** \liN for a left indent in twips, or nothing when there is none. */
|
|
990
|
+
function liControl(twips) {
|
|
991
|
+
return twips > 0 ? `\\li${twips}` : '';
|
|
992
|
+
}
|
|
993
|
+
/** \qc, \qr or \qj; left is the default and is not written. */
|
|
994
|
+
function alignOf(el) {
|
|
995
|
+
const align = alignControl(el);
|
|
996
|
+
return align === '\\ql' ? '' : align;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* A heading's, or a paragraph's inside a table cell: its alignment, and \liN for the indent of
|
|
1000
|
+
* the blocks around it plus its own margin.
|
|
1001
|
+
*/
|
|
1002
|
+
function paragraphLayout(el, ctx) {
|
|
1003
|
+
return `${alignOf(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* A <p> or <div>'s formatting outside a table cell: its alignment, then paragraphControls with the
|
|
1007
|
+
* indent of the blocks around it plus its own margin.
|
|
1008
|
+
*/
|
|
1009
|
+
function paragraphFormat(el, ctx) {
|
|
1010
|
+
return `${alignOf(el)}${paragraphControls(el, ctx.indent + leftMarginTwips(el))}`;
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* The RTF paragraph controls for a <p> or <div>'s own formatting, or '' when it sets none:
|
|
1014
|
+
*
|
|
1015
|
+
* | HTML | RTF |
|
|
1016
|
+
* |--------------------------------------------------|-------------------|
|
|
1017
|
+
* | data-rtf-tab-stops="1.75in" (comma-separated) | \tx2520 |
|
|
1018
|
+
* | margin-left: 1.75in (the left indent, given) | \li2520 |
|
|
1019
|
+
* | text-indent: -1.75in | \fi-2520 |
|
|
1020
|
+
* | margin-top: 5pt / margin-bottom: 5pt | \sb100 / \sa100 |
|
|
1021
|
+
* | break-after: avoid, or page-break-after: avoid | \keepn |
|
|
1022
|
+
*
|
|
1023
|
+
* CSS has no absolute tab stop, hence the data- attribute. A value that cannot be read writes
|
|
1024
|
+
* nothing, and so does zero, which is what \pard already sets. Not written inside a table cell,
|
|
1025
|
+
* where the cell declares its own paragraph.
|
|
1026
|
+
*/
|
|
1027
|
+
function paragraphControls(el, leftTwips) {
|
|
1028
|
+
let out = '';
|
|
1029
|
+
const stops = (el.getAttribute('data-rtf-tab-stops') ?? '')
|
|
1030
|
+
.split(',')
|
|
1031
|
+
.map((v) => lengthTwips(v))
|
|
1032
|
+
.filter((t) => t != null && t > 0);
|
|
1033
|
+
for (const t of Array.from(new Set(stops)).sort((a, b) => a - b))
|
|
1034
|
+
out += `\\tx${t}`;
|
|
1035
|
+
out += liControl(leftTwips);
|
|
1036
|
+
const style = el.style;
|
|
1037
|
+
if (!style)
|
|
1038
|
+
return out;
|
|
1039
|
+
const fi = lengthTwips(style.textIndent, true);
|
|
1040
|
+
if (fi)
|
|
1041
|
+
out += `\\fi${fi}`;
|
|
1042
|
+
const sb = lengthTwips(style.marginTop);
|
|
1043
|
+
if (sb)
|
|
1044
|
+
out += `\\sb${sb}`;
|
|
1045
|
+
const sa = lengthTwips(style.marginBottom);
|
|
1046
|
+
if (sa)
|
|
1047
|
+
out += `\\sa${sa}`;
|
|
1048
|
+
const keep = (prop) => style.getPropertyValue(prop).trim() === 'avoid';
|
|
1049
|
+
if (keep('break-after') || keep('page-break-after'))
|
|
1050
|
+
out += '\\keepn';
|
|
1051
|
+
return out;
|
|
1052
|
+
}
|
|
1053
|
+
/** Whether the nearest element before this one is a <p> or <div> with formatting of its own. */
|
|
1054
|
+
function followsFormattedParagraph(el, ctx) {
|
|
1055
|
+
const prev = el.previousElementSibling;
|
|
1056
|
+
if (!prev)
|
|
1057
|
+
return false;
|
|
1058
|
+
const tag = prev.tagName.toLowerCase();
|
|
1059
|
+
return (tag === 'p' || tag === 'div') && paragraphFormat(prev, ctx) !== '';
|
|
1060
|
+
}
|
|
1061
|
+
/** Whether a container's first (or last) content is loose text or an inline element, not a block. */
|
|
1062
|
+
function startsWithInline(el) {
|
|
1063
|
+
return edgeIsInline(el, 'first');
|
|
1064
|
+
}
|
|
1065
|
+
function endsWithInline(el) {
|
|
1066
|
+
return edgeIsInline(el, 'last');
|
|
1067
|
+
}
|
|
1068
|
+
function edgeIsInline(el, edge) {
|
|
1069
|
+
const nodes = Array.from(el.childNodes);
|
|
1070
|
+
if (edge === 'last')
|
|
1071
|
+
nodes.reverse();
|
|
1072
|
+
for (const n of nodes) {
|
|
1073
|
+
if (n.nodeType === Node.TEXT_NODE && COLLAPSIBLE_WHITESPACE.test(n.textContent || ''))
|
|
1074
|
+
continue;
|
|
1075
|
+
return !isBlock(n);
|
|
1076
|
+
}
|
|
1077
|
+
return false;
|
|
1078
|
+
}
|
|
838
1079
|
/** \intbl for a paragraph a block writes inside a table cell, so it stays in the cell. */
|
|
839
1080
|
function inCell(ctx) {
|
|
840
1081
|
return ctx.inTableCell ? '\\intbl' : '';
|
package/package.json
CHANGED