svelte-rtf-editor 1.7.0 → 1.8.1

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 CHANGED
@@ -209,6 +209,7 @@ A `<p>` or `<div>` keeps its own indents, spacing and tab stops in the RTF, so a
209
209
  | HTML on the paragraph | RTF |
210
210
  |---|---|
211
211
  | `margin-left: 1.75in` | `\li2520` |
212
+ | `margin-right: 0.5in` | `\ri720` |
212
213
  | `text-indent: -1.75in` | `\fi-2520` |
213
214
  | `margin-top: 5pt` / `margin-bottom: 5pt` | `\sb100` / `\sa100` |
214
215
  | `break-after: avoid` or `page-break-after: avoid` | `\keepn` |
@@ -217,8 +218,10 @@ A `<p>` or `<div>` keeps its own indents, spacing and tab stops in the RTF, so a
217
218
  - 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
219
  - 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
220
  - `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.
221
+ - Inside a table cell the cell declares its own paragraph: only alignment and the left indent are written there, not the right or first-line indent, spacing, tab stops or keep-with-next.
222
+ - `rtfToHtml` reads the three indents back, in points: `\li720\ri720\fi-720` becomes `margin-left:36pt;margin-right:36pt;text-indent:-36pt`, and `RtfViewer` shows them. As in RTF, they hold from one paragraph to the next until `\pard`. Indents inside a table cell are not read.
223
+ - A heading outside a table cell also writes its right and first-line indents, so a heading read from RTF with a hanging number goes back as it came. A picture is read with a left margin only, where its line starts.
224
+ - `rtfToHtml` does not yet read spacing, keep-with-next or tab stops back.
222
225
 
223
226
  ## Theming
224
227
 
@@ -256,7 +259,39 @@ The components use CSS custom properties with sensible fallbacks, so they work o
256
259
  | `Shift+Tab` | Remove one tab from the start of the line. With several lines selected, decrease their indent |
257
260
  | `Esc`, then `Tab` / `Shift+Tab` | Move focus out of the editor |
258
261
 
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`.
262
+ 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.
263
+
264
+ Four more toolbar buttons set the other two RTF indents, 0.5 in per press, on a paragraph outside a table cell (not on a list, a heading, a quotation or a code block):
265
+
266
+ | Button | What moves | RTF per step |
267
+ |---|---|---|
268
+ | Increase / Decrease hanging indent | Every line but the first; the first line stays where it is | `\li720\fi-720` |
269
+ | Increase / Decrease right indent | The right edge of the paragraph | `\ri720` |
270
+
271
+ Decrease indent stops where the first line of a hanging paragraph reaches the left edge.
272
+
273
+ **Hang at caret** sets the hanging indent to any distance: put the caret where the later lines should begin, for example after `A. Pancreas: `, and press the button. The first line stays where it starts and the lines after it begin under the caret. With the caret at the start of the line, the hang is taken away. When a tab comes before the caret, the paragraph also gets a tab stop at the new indent (`tab-size` on screen, `data-rtf-tab-stops` for the RTF's `\tx`), so the text after the tab lines up with the lines below it. Tab stops the paragraph already has are kept. It works on a paragraph outside a table cell that is aligned left or justified.
274
+
275
+ ### Copy format
276
+
277
+ The **Copy format** button gives several paragraphs the same alignment and indents:
278
+
279
+ 1. Press the button. The pointer becomes a crosshair and a bar under the toolbar says what to click.
280
+ 2. Click the paragraph to copy from. A dashed frame marks it and the pointer becomes a brush.
281
+ 3. Click each paragraph that should get the format. The one under the pointer is highlighted.
282
+
283
+ It stays on until **Done** in the bar, `Esc`, or the button again. Each click is one Undo step.
284
+
285
+ - What is copied is the paragraph's alignment, indent, right indent and hanging indent, with the tab stop Hang at caret sets. Bold, italic, color and size are not.
286
+ - A click in the margin beside a paragraph, or in the empty space below the text, does nothing.
287
+ - Copying from a plain paragraph clears those from the paragraphs clicked.
288
+ - Each block takes what the RTF carries for it: a heading everything but the tab stop, and a heading or paragraph in a table cell the alignment and the indent only. Lists, code blocks and pictures are left alone.
289
+ - The frame, the highlight and the bar are not part of the text and never reach `getHTML()` or the RTF.
290
+
291
+ ### Pasted text
292
+
293
+ A browser copies a paragraph with its looks written out as inline styles, and repeats its `id`. After a paste, each element that came in loses its `id` and any margin or first-line indent that changes nothing on screen, so a copy pasted inside the editor is the same markup as its source. A line the browser makes as a `<div>` is spaced like a `<p>`; both are written to RTF as a paragraph.
294
+ Paragraph alignment (left, center, right, justify) is written to RTF as `\qc`, `\qr` or `\qj`.
260
295
 
261
296
  Tab stays in the editor so a line can be indented. To leave the editor from the keyboard, press
262
297
  `Esc` first. A readonly editor leaves Tab to the browser.
@@ -180,7 +180,7 @@
180
180
  export function setHTML(html: string): void {
181
181
  if (editorEl) {
182
182
  selectedImage = null;
183
- indentUndo = [];
183
+ documentReplaced();
184
184
  editorEl.innerHTML = html;
185
185
  updateCounts();
186
186
  if (autosave) scheduleAutoSave();
@@ -212,7 +212,7 @@
212
212
  export function clear(): void {
213
213
  if (editorEl) {
214
214
  selectedImage = null;
215
- indentUndo = [];
215
+ documentReplaced();
216
216
  editorEl.innerHTML = '<p></p>';
217
217
  try { localStorage.removeItem(storageKey); } catch (e) {}
218
218
  updateCounts();
@@ -251,6 +251,31 @@
251
251
  fileInputEl?.click();
252
252
  }
253
253
 
254
+ /**
255
+ * The whole document is about to be replaced (setHTML, clear, an RTF import): nothing that
256
+ * points into the old one may act on the new one. Indent steps no longer undo, the Copy format
257
+ * brush is put down, and a paste that inserted nothing is forgotten.
258
+ */
259
+ function documentReplaced(): void {
260
+ indentUndo = [];
261
+ pastedOver = null;
262
+ stopCopyFormat();
263
+ }
264
+
265
+ // The frame around the paragraph copied from follows it when the text reflows: typing is caught
266
+ // by the input handler, and a picture finishing loading or the editor changing width by this.
267
+ $effect(() => {
268
+ if (copyFormat !== 'apply' || !editorEl || typeof ResizeObserver === 'undefined') return;
269
+ const observer = new ResizeObserver(() => placeCopySourceBox());
270
+ observer.observe(editorEl);
271
+ return () => observer.disconnect();
272
+ });
273
+
274
+ // A read-only editor has no toolbar to put the brush down with.
275
+ $effect(() => {
276
+ if (readonly) stopCopyFormat();
277
+ });
278
+
254
279
  // ── Selection helpers ──
255
280
  function saveSelection(): void {
256
281
  const sel = window.getSelection();
@@ -278,10 +303,14 @@
278
303
  const sel = window.getSelection();
279
304
  if (!sel || sel.isCollapsed) return;
280
305
  }
281
- if (cmd === 'indent' || cmd === 'outdent') {
306
+ if (isIndentCommand(cmd)) {
282
307
  indentBlocks(cmd);
283
308
  return;
284
309
  }
310
+ if (cmd === 'hangAtCaret') {
311
+ hangAtCaret();
312
+ return;
313
+ }
285
314
  if (cmd === 'undo' && undoIndent()) return;
286
315
  document.execCommand(cmd, false, value ?? undefined);
287
316
  updateToolbarState();
@@ -294,7 +323,28 @@
294
323
  // browsers disagree on the markup. Only a style changes (and a line of loose text gets a
295
324
  // paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
296
325
  // these steps until the next edit.
326
+ //
327
+ // The right indent and the hanging indent move by the same step, on a paragraph (a <p>, or a
328
+ // <div> that holds text) outside a table cell, which is where the RTF writer sends them:
329
+ //
330
+ // | Command | Style on the paragraph | RTF |
331
+ // |----------------------------------|----------------------------------------|----------------|
332
+ // | indent / outdent | margin-left | \liN |
333
+ // | rightIndent / rightOutdent | margin-right | \riN |
334
+ // | hangingIndent / hangingOutdent | margin-left, and text-indent the other | \liN\fi-N |
335
+ // | | way, so the first line stays put | |
336
+ //
337
+ // Outdent stops where the first line of a hanging paragraph would reach the left edge.
297
338
  const INDENT_STEP_PX = 48;
339
+ const INDENT_COMMANDS = ['indent', 'outdent', 'rightIndent', 'rightOutdent', 'hangingIndent', 'hangingOutdent'] as const;
340
+ type IndentCommand = (typeof INDENT_COMMANDS)[number];
341
+ function isIndentCommand(cmd: string): cmd is IndentCommand {
342
+ return (INDENT_COMMANDS as readonly string[]).includes(cmd);
343
+ }
344
+ /** Commands that take an indent away: they never make a paragraph around loose text. */
345
+ function decreases(cmd: IndentCommand): boolean {
346
+ return cmd === 'outdent' || cmd === 'rightOutdent' || cmd === 'hangingOutdent';
347
+ }
298
348
  const INDENT_TARGETS = 'p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure';
299
349
  /** CSS lengths a margin is written in, in px. */
300
350
  const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
@@ -306,10 +356,12 @@
306
356
  after: string | null;
307
357
  /** The block is a paragraph this step made around loose text, and the <br> that ended it. */
308
358
  wrapped: { br: HTMLBRElement | null } | null;
359
+ /** The paragraph's data-rtf-tab-stops before a step that changed it. */
360
+ stops?: { before: string | null; after: string | null };
309
361
  }
310
362
  let indentUndo: IndentChange[][] = [];
311
363
 
312
- function indentBlocks(cmd: 'indent' | 'outdent'): void {
364
+ function indentBlocks(cmd: IndentCommand): void {
313
365
  if (readonly || !editorEl) return;
314
366
  editorEl.focus();
315
367
  const sel = window.getSelection();
@@ -324,11 +376,35 @@
324
376
  }
325
377
  const step: IndentChange[] = [];
326
378
  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
379
  const before = el.getAttribute('style');
331
- el.style.marginLeft = next > 0 ? `${Math.round(next * 100) / 100}px` : '';
380
+ const left = marginLeftPx(el);
381
+ const first = textIndentPx(el);
382
+ const setPx = (prop: 'marginLeft' | 'marginRight' | 'textIndent', px: number) => {
383
+ el.style[prop] = px !== 0 ? `${Math.round(px * 100) / 100}px` : '';
384
+ };
385
+ if (cmd === 'indent') {
386
+ setPx('marginLeft', left + INDENT_STEP_PX);
387
+ } else if (cmd === 'outdent') {
388
+ // A hanging paragraph's first line starts left of its margin: stop at the edge.
389
+ const next = Math.max(0, -first, left - INDENT_STEP_PX);
390
+ if (next === left) continue;
391
+ setPx('marginLeft', next);
392
+ } else if (cmd === 'rightIndent') {
393
+ setPx('marginRight', marginRightPx(el) + INDENT_STEP_PX);
394
+ } else if (cmd === 'rightOutdent') {
395
+ const right = marginRightPx(el);
396
+ if (right === 0) continue;
397
+ setPx('marginRight', Math.max(0, right - INDENT_STEP_PX));
398
+ } else if (cmd === 'hangingIndent') {
399
+ setPx('marginLeft', left + INDENT_STEP_PX);
400
+ setPx('textIndent', first - INDENT_STEP_PX);
401
+ } else {
402
+ // Only what hangs comes back: a paragraph with no hanging indent stays as it is.
403
+ const back = Math.min(INDENT_STEP_PX, -first, left);
404
+ if (back <= 0) continue;
405
+ setPx('marginLeft', left - back);
406
+ setPx('textIndent', first + back);
407
+ }
332
408
  if (!el.getAttribute('style')) el.removeAttribute('style');
333
409
  const br = wrapped.get(el);
334
410
  step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
@@ -340,11 +416,36 @@
340
416
 
341
417
  /** An element's left margin in px: its own, from the inline style, or 0. */
342
418
  function marginLeftPx(el: HTMLElement): number {
343
- const value = el.style.marginLeft.trim().toLowerCase();
419
+ return Math.max(0, stylePx(el, 'marginLeft'));
420
+ }
421
+
422
+ /** An element's right margin in px: its own, from the inline style, or 0. */
423
+ function marginRightPx(el: HTMLElement): number {
424
+ return Math.max(0, stylePx(el, 'marginRight'));
425
+ }
426
+
427
+ /** An element's first-line indent in px, from the inline style: negative when it hangs. */
428
+ function textIndentPx(el: HTMLElement): number {
429
+ return stylePx(el, 'textIndent');
430
+ }
431
+
432
+ /** A length from an element's inline style, in px, or 0 when it sets none. */
433
+ function stylePx(el: HTMLElement, prop: 'marginLeft' | 'marginRight' | 'textIndent'): number {
434
+ const value = el.style[prop].trim();
344
435
  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);
436
+ return (lengthPx(value) ?? parseFloat(getComputedStyle(el)[prop])) || 0;
437
+ }
438
+
439
+ /** A CSS length in px, or null when it is not a number in px, pt, in, cm or mm. */
440
+ function lengthPx(value: string): number | null {
441
+ const m = /^(-?\d*\.?\d+)(px|pt|in|cm|mm)$/.exec(value.trim().toLowerCase());
442
+ return m ? parseFloat(m[1]) * PX_PER_UNIT[m[2]] : null;
443
+ }
444
+
445
+ /** A <p>, or a <div> that holds text and no blocks: what a right or hanging indent is set on. */
446
+ function isPlainParagraph(el: HTMLElement): boolean {
447
+ if (el.tagName !== 'P' && el.tagName !== 'DIV') return false;
448
+ return !Array.from(el.children).some((c) => c.matches(`${INDENT_TARGETS}, table, hr`));
348
449
  }
349
450
 
350
451
  /**
@@ -355,6 +456,301 @@
355
456
  return el instanceof HTMLElement && el.tagName === 'BLOCKQUOTE' && el.style.borderLeftStyle === 'none';
356
457
  }
357
458
 
459
+ // ── Hang at caret ──
460
+ // Sets the hanging indent to where the caret is: the first line stays where it starts, and the
461
+ // lines after it begin under the caret. Put the caret after "A. Pancreas: " and the rest of the
462
+ // paragraph lines up under the diagnosis. With the caret at the start of the line the hang is
463
+ // taken away. Works on a paragraph (a <p>, or a <div> that holds text) outside a table cell,
464
+ // aligned left or justified, where a position measured from the left means something.
465
+ //
466
+ // When a tab comes before the caret, the tab has to end at the new indent for the first line to
467
+ // line up with the rest. The paragraph gets a tab stop there: tab-size on screen (stops are
468
+ // counted from the indent, so one hang's width puts a stop on it) and data-rtf-tab-stops for
469
+ // the writer's \tx.
470
+ const TAB_STOPS = 'data-rtf-tab-stops';
471
+
472
+ function hangAtCaret(): void {
473
+ if (readonly || !editorEl) return;
474
+ editorEl.focus();
475
+ const sel = window.getSelection();
476
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
477
+ const caret = sel.getRangeAt(0).cloneRange();
478
+ caret.collapse(true);
479
+ const node = caret.startContainer;
480
+ const offset = caret.startOffset;
481
+ const el = node instanceof Element ? node : node.parentElement;
482
+ if (!el || el.closest('td, th, li, pre, figure, h1, h2, h3, h4, h5, h6')) return;
483
+ const x = caretLeft(caret);
484
+ if (x === null) return;
485
+
486
+ const closest = el.closest(PAINT_BLOCKS);
487
+ let block = closest instanceof HTMLElement && closest !== editorEl && editorEl.contains(closest) ? closest : null;
488
+ let wrapped: { br: HTMLBRElement | null } | null = null;
489
+ if (block && !isPlainParagraph(block)) return;
490
+ if (!block) {
491
+ const made = wrapLooseLine(node);
492
+ if (!made) return;
493
+ block = made.p;
494
+ wrapped = { br: made.br };
495
+ // Wrapping moved the text the caret was in: put the caret back.
496
+ if (node.isConnected) sel.collapse(node, offset);
497
+ }
498
+ // A centered <div align="center"> computes to -webkit-center or -moz-center.
499
+ if (/(center|right)$|^end$/.test(getComputedStyle(block).textAlign)) {
500
+ if (wrapped) undoWrap(block, wrapped);
501
+ return;
502
+ }
503
+
504
+ const left = marginLeftPx(block);
505
+ // Where the first line starts, and where the caret is, both from the page's left edge.
506
+ const first = Math.max(0, left + textIndentPx(block));
507
+ const at = Math.round(x - (block.getBoundingClientRect().left - left));
508
+ const hang = at - first;
509
+ const before = wrapped ? null : block.getAttribute('style');
510
+ const stopsBefore = block.getAttribute(TAB_STOPS);
511
+ const before0 = document.createRange();
512
+ before0.setStart(block, 0);
513
+ before0.setEnd(node, offset);
514
+ const tabBefore = before0.toString().includes('\t');
515
+
516
+ // The stop an earlier hang put at the old indent goes with that hang. Any other stop the
517
+ // paragraph has (data-rtf-tab-stops="1.75in,3.5in") is not this command's to remove.
518
+ // A tab stop counts from the page margin, as \tx does, while the indents above count from the
519
+ // block around the paragraph: a quotation or a pasted indent moves the stop with it.
520
+ const outer = surroundingIndentPx(block);
521
+ const hung = textIndentPx(block) < 0;
522
+ const stops = (stopsBefore ?? '')
523
+ .split(',')
524
+ .map((v) => v.trim())
525
+ .filter((v) => v && !(hung && Math.abs((lengthPx(v) ?? NaN) - (outer + left)) < 0.5));
526
+ // tab-size shows one stop, the one at the hang: it goes when that stop does.
527
+ block.style.tabSize = '';
528
+ if (hang < 1) {
529
+ block.style.marginLeft = first > 0 ? `${first}px` : '';
530
+ block.style.textIndent = '';
531
+ } else {
532
+ block.style.marginLeft = `${at}px`;
533
+ block.style.textIndent = `${-hang}px`;
534
+ if (tabBefore) {
535
+ block.style.tabSize = `${hang}px`;
536
+ const stop = outer + at;
537
+ if (!stops.some((v) => Math.abs((lengthPx(v) ?? NaN) - stop) < 0.5)) stops.push(`${stop}px`);
538
+ }
539
+ }
540
+ if (stops.length > 0) block.setAttribute(TAB_STOPS, stops.join(','));
541
+ else block.removeAttribute(TAB_STOPS);
542
+ if (!block.getAttribute('style')) block.removeAttribute('style');
543
+ const after = block.getAttribute('style');
544
+ const stopsAfter = block.getAttribute(TAB_STOPS);
545
+ if (!wrapped && after === before && stopsAfter === stopsBefore) return;
546
+ indentUndo.push([{ el: block, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
547
+ indentChanged();
548
+ }
549
+
550
+ /**
551
+ * The left indent the RTF writer gives a paragraph from the blocks around it, in px: a pasted
552
+ * indent's margin, a <div>'s margin, and a quotation's margin plus the half inch every
553
+ * quotation is indented (rtf-writer's blockquote case).
554
+ */
555
+ function surroundingIndentPx(block: HTMLElement): number {
556
+ let px = 0;
557
+ for (let a = block.parentElement; a && a !== editorEl; a = a.parentElement) {
558
+ if (a.tagName === 'BLOCKQUOTE') px += marginLeftPx(a) + (isIndentBlockquote(a) ? 0 : INDENT_STEP_PX);
559
+ else if (a.tagName === 'DIV') px += marginLeftPx(a);
560
+ }
561
+ return px;
562
+ }
563
+
564
+ /** Take away the paragraph wrapLooseLine made, leaving the loose line as it was. */
565
+ function undoWrap(p: HTMLElement, wrapped: { br: HTMLBRElement | null }): void {
566
+ if (wrapped.br) p.after(wrapped.br);
567
+ p.replaceWith(...Array.from(p.childNodes));
568
+ }
569
+
570
+ /**
571
+ * The caret's distance from the left of the window. A caret between two pieces of text can have
572
+ * no box of its own, so the character after it, or the one before, stands in.
573
+ */
574
+ function caretLeft(caret: Range): number | null {
575
+ const own = caret.getClientRects()[0];
576
+ if (own && (own.height > 0 || own.width > 0)) return own.left;
577
+ const node = caret.startContainer;
578
+ if (!(node instanceof Text)) return null;
579
+ const probe = document.createRange();
580
+ if (caret.startOffset < node.length) {
581
+ probe.setStart(node, caret.startOffset);
582
+ probe.setEnd(node, caret.startOffset + 1);
583
+ const r = probe.getClientRects()[0];
584
+ if (r) return r.left;
585
+ }
586
+ if (caret.startOffset > 0) {
587
+ probe.setStart(node, caret.startOffset - 1);
588
+ probe.setEnd(node, caret.startOffset);
589
+ const rects = probe.getClientRects();
590
+ const r = rects[rects.length - 1];
591
+ if (r) return r.right;
592
+ }
593
+ return null;
594
+ }
595
+
596
+ // ── Copy format ──
597
+ // The toolbar's Copy format button turns the pointer into a format brush. The first click in
598
+ // the text picks the paragraph to copy from; each click after that gives the clicked paragraph
599
+ // the same alignment and indents. It stays on until Escape, Done, or the button again, so one
600
+ // format can go to as many paragraphs as needed.
601
+ //
602
+ // What is copied is the paragraph's own formatting, the part the RTF writer sends as \q, \li,
603
+ // \ri and \fi: text-align, margin-left, margin-right and text-indent, and with them the tab
604
+ // stop Hang at caret sets (tab-size, data-rtf-tab-stops). Each block takes what the writer
605
+ // sends for it: a heading all of it but the tab stop, and a heading or paragraph in a table
606
+ // cell the alignment and the left indent only. Lists, code blocks and pictures are left alone.
607
+ // Each click is one Undo step.
608
+ interface ParagraphFormat {
609
+ textAlign: string;
610
+ marginLeft: string;
611
+ marginRight: string;
612
+ textIndent: string;
613
+ /** The tab stop that goes with a hanging indent: tab-size on screen, \tx in the RTF. */
614
+ tabSize: string;
615
+ tabStops: string;
616
+ }
617
+ const NO_FORMAT: ParagraphFormat = { textAlign: '', marginLeft: '', marginRight: '', textIndent: '', tabSize: '', tabStops: '' };
618
+ const PAINT_BLOCKS = 'p, div, h1, h2, h3, h4, h5, h6';
619
+
620
+ /** 'pick': waiting for the paragraph to copy from. 'apply': each click applies the format. */
621
+ let copyFormat: 'off' | 'pick' | 'apply' = $state('off');
622
+ let copiedFormat: ParagraphFormat = NO_FORMAT;
623
+ let copySource: HTMLElement | null = null;
624
+ /** Where the frame around the paragraph copied from sits, inside the content wrapper. */
625
+ let copySourceBox: { top: number; left: number; width: number; height: number } | null = $state(null);
626
+
627
+ function toggleCopyFormat(): void {
628
+ if (copyFormat !== 'off') {
629
+ stopCopyFormat();
630
+ return;
631
+ }
632
+ if (readonly) return;
633
+ selectedImage = null;
634
+ copyFormat = 'pick';
635
+ }
636
+
637
+ function stopCopyFormat(): void {
638
+ copyFormat = 'off';
639
+ copiedFormat = NO_FORMAT;
640
+ copySource = null;
641
+ copySourceBox = null;
642
+ }
643
+
644
+ function placeCopySourceBox(): void {
645
+ if (!copySource?.isConnected || !contentWrapEl) {
646
+ copySourceBox = null;
647
+ return;
648
+ }
649
+ const wrap = contentWrapEl.getBoundingClientRect();
650
+ const r = copySource.getBoundingClientRect();
651
+ // A hanging first line starts left of the paragraph's own box: frame it too.
652
+ const hang = Math.max(0, -textIndentPx(copySource));
653
+ copySourceBox = { top: r.top - wrap.top, left: r.left - wrap.left - hang, width: r.width + hang, height: r.height };
654
+ }
655
+
656
+ function formatOf(el: HTMLElement): ParagraphFormat {
657
+ const align = (el.style.textAlign || el.getAttribute('align') || '').toLowerCase();
658
+ return {
659
+ textAlign: align === 'left' || align === 'start' ? '' : align,
660
+ marginLeft: el.style.marginLeft,
661
+ marginRight: el.style.marginRight,
662
+ textIndent: el.style.textIndent,
663
+ tabSize: el.style.tabSize,
664
+ tabStops: el.getAttribute(TAB_STOPS) ?? ''
665
+ };
666
+ }
667
+
668
+ /**
669
+ * The paragraph a click landed on: a <p>, a heading, or a <div> that holds text. A click on a
670
+ * line of loose text lands on the editor itself, so the caret the click placed says which line.
671
+ */
672
+ function paragraphAt(e: MouseEvent): { block: HTMLElement | null; loose: Node | null } {
673
+ const none = { block: null, loose: null };
674
+ if (!editorEl) return none;
675
+ const target = e.target instanceof Element ? e.target : null;
676
+ if (!target || !editorEl.contains(target)) return none;
677
+ if (target.closest('li, pre, figure')) return none;
678
+ const own = paintable(target);
679
+ if (own !== undefined) return own ? { block: own, loose: null } : none;
680
+ // The click landed on the editor itself, not on a paragraph: loose text, a margin, or the
681
+ // empty space below the text. Only loose text counts. The caret also lands in the nearest
682
+ // paragraph when its margin is clicked, and that paragraph was not what was clicked.
683
+ const anchor = window.getSelection()?.anchorNode ?? null;
684
+ if (!(anchor instanceof Text) || !anchor.data.trim() || !editorEl.contains(anchor)) return none;
685
+ const parent = anchor.parentElement;
686
+ if (!parent || parent.closest('li, pre, figure, blockquote') || paintable(parent) !== undefined) return none;
687
+ return { block: null, loose: anchor };
688
+ }
689
+
690
+ /**
691
+ * The paragraph an element is in that Copy format can read or set: a heading, a <p>, or a
692
+ * <div> that holds text. null when it is in a block that cannot take one (a <div> holding other
693
+ * blocks); undefined when it is in no block at all, which is loose text.
694
+ */
695
+ function paintable(el: Element): HTMLElement | null | undefined {
696
+ if (!editorEl) return undefined;
697
+ const block = el.closest(PAINT_BLOCKS);
698
+ const cell = el.closest('td, th');
699
+ if (!(block instanceof HTMLElement) || block === editorEl || !editorEl.contains(block)) return undefined;
700
+ if (cell && !cell.contains(block)) return undefined;
701
+ return /^H[1-6]$/.test(block.tagName) || isPlainParagraph(block) ? block : null;
702
+ }
703
+
704
+ function handleCopyFormatClick(e: MouseEvent): void {
705
+ const { block, loose } = paragraphAt(e);
706
+ if (!block && !loose) return;
707
+ if (copyFormat === 'pick') {
708
+ copiedFormat = block ? formatOf(block) : NO_FORMAT;
709
+ copySource = block;
710
+ copyFormat = 'apply';
711
+ placeCopySourceBox();
712
+ return;
713
+ }
714
+ if (block && block === copySource) return;
715
+ let target = block;
716
+ let wrapped: { br: HTMLBRElement | null } | null = null;
717
+ if (!target && loose) {
718
+ // A line of loose text has no format to take away, and needs a paragraph to carry one.
719
+ if (Object.values(copiedFormat).every((v) => !v)) return;
720
+ const made = wrapLooseLine(loose);
721
+ if (!made) return;
722
+ target = made.p;
723
+ wrapped = { br: made.br };
724
+ }
725
+ if (!target) return;
726
+ const before = wrapped ? null : target.getAttribute('style');
727
+ const stopsBefore = target.getAttribute(TAB_STOPS);
728
+ // What the writer sends decides what a block can take: a paragraph or a heading outside a
729
+ // table cell carries all three indents, and only a paragraph carries tab stops.
730
+ const outsideCell = !target.closest('td, th');
731
+ const whole = outsideCell && isPlainParagraph(target);
732
+ const indents = whole || (outsideCell && /^H[1-6]$/.test(target.tagName));
733
+ // align="center" (Firefox) outranks an empty style, so say left out loud over it.
734
+ target.style.textAlign = copiedFormat.textAlign || (target.hasAttribute('align') ? 'left' : '');
735
+ target.style.marginLeft = copiedFormat.marginLeft;
736
+ if (indents) {
737
+ target.style.marginRight = copiedFormat.marginRight;
738
+ target.style.textIndent = copiedFormat.textIndent;
739
+ }
740
+ if (whole) {
741
+ target.style.tabSize = copiedFormat.tabSize;
742
+ if (copiedFormat.tabStops) target.setAttribute(TAB_STOPS, copiedFormat.tabStops);
743
+ else target.removeAttribute(TAB_STOPS);
744
+ }
745
+ if (!target.getAttribute('style')) target.removeAttribute('style');
746
+ const after = target.getAttribute('style');
747
+ const stopsAfter = target.getAttribute(TAB_STOPS);
748
+ if (!wrapped && after === before && stopsAfter === stopsBefore) return;
749
+ indentUndo.push([{ el: target, before, after, wrapped, stops: { before: stopsBefore, after: stopsAfter } }]);
750
+ indentChanged();
751
+ placeCopySourceBox();
752
+ }
753
+
358
754
  /** Undo the last Indent or Outdent, if nothing has changed since. */
359
755
  function undoIndent(): boolean {
360
756
  const step = indentUndo.pop();
@@ -364,19 +760,21 @@
364
760
  indentUndo = [];
365
761
  return false;
366
762
  }
367
- for (const { el, before, wrapped } of step) {
763
+ for (const { el, before, wrapped, stops } of step) {
368
764
  if (before === null) el.removeAttribute('style');
369
765
  else el.setAttribute('style', before);
370
- if (wrapped) {
371
- if (wrapped.br) el.after(wrapped.br);
372
- el.replaceWith(...Array.from(el.childNodes));
766
+ if (stops) {
767
+ if (stops.before === null) el.removeAttribute(TAB_STOPS);
768
+ else el.setAttribute(TAB_STOPS, stops.before);
373
769
  }
770
+ if (wrapped) undoWrap(el, wrapped);
374
771
  }
375
772
  indentChanged();
376
773
  return true;
377
774
  }
378
775
 
379
776
  function indentChanged(): void {
777
+ placeCopySourceBox();
380
778
  updateToolbarState();
381
779
  fireChange();
382
780
  if (autosave) scheduleAutoSave();
@@ -386,11 +784,12 @@
386
784
  * The blocks Indent moves: each line's paragraph, and a list, a quotation or a picture as a
387
785
  * whole. A line of loose text (typed straight into the editor or a table cell) is first given a
388
786
  * 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.
787
+ * of its own moves the pasted indent around it (isIndentBlockquote) instead. A right or hanging
788
+ * indent moves paragraphs only (isPlainParagraph), and nothing inside a table cell.
390
789
  */
391
790
  function indentTargets(
392
791
  range: Range,
393
- cmd: 'indent' | 'outdent',
792
+ cmd: IndentCommand,
394
793
  wrapped: Map<HTMLElement, HTMLBRElement | null>
395
794
  ): HTMLElement[] {
396
795
  if (!editorEl) return [];
@@ -409,6 +808,14 @@
409
808
  const item = el.closest('li');
410
809
  const closest = el.closest(INDENT_TARGETS);
411
810
  const block = inScope(item) ? item.parentElement : inScope(closest) ? closest : null;
811
+ if (cmd !== 'indent' && cmd !== 'outdent') {
812
+ if (cell) return null;
813
+ if (inScope(block)) return isPlainParagraph(block) ? block : null;
814
+ if (decreases(cmd)) return null;
815
+ const made = wrapLooseLine(node);
816
+ if (made) wrapped.set(made.p, made.br);
817
+ return made?.p ?? null;
818
+ }
412
819
  if (cmd === 'outdent' && (!block || marginLeftPx(block) === 0)) {
413
820
  for (let a = (block ?? el).parentElement; inScope(a); a = a.parentElement) {
414
821
  if (isIndentBlockquote(a) && marginLeftPx(a) > 0) return a;
@@ -542,6 +949,11 @@
542
949
 
543
950
  // ── Input handler ──
544
951
  function handleInput(): void {
952
+ placeCopySourceBox();
953
+ if (pastedOver) {
954
+ tidyPasted(pastedOver);
955
+ pastedOver = null;
956
+ }
545
957
  indentUndo = [];
546
958
  updateToolbarState();
547
959
  // Typing means the user is editing text, not the picture. Dropping the
@@ -807,6 +1219,10 @@
807
1219
  // ── Image selection / editing ──
808
1220
  function handleContentClick(e: MouseEvent): void {
809
1221
  if (readonly) return;
1222
+ if (copyFormat !== 'off') {
1223
+ handleCopyFormatClick(e);
1224
+ return;
1225
+ }
810
1226
  const target = e.target as HTMLElement | null;
811
1227
  selectedImage = target?.tagName === 'IMG' ? (target as HTMLImageElement) : null;
812
1228
  }
@@ -903,7 +1319,7 @@
903
1319
  const html = await readRtfFile(file, { fontSize });
904
1320
  if (editorEl) {
905
1321
  selectedImage = null;
906
- indentUndo = [];
1322
+ documentReplaced();
907
1323
  editorEl.innerHTML = html;
908
1324
  updateCounts();
909
1325
  fireChange();
@@ -920,6 +1336,12 @@
920
1336
 
921
1337
  // ── Keyboard shortcuts ──
922
1338
  function handleKeydown(e: KeyboardEvent): void {
1339
+ // Escape puts the Copy format brush down, and does nothing else that press.
1340
+ if (copyFormat !== 'off' && e.key === 'Escape') {
1341
+ e.preventDefault();
1342
+ stopCopyFormat();
1343
+ return;
1344
+ }
923
1345
  const mod = e.ctrlKey || e.metaKey;
924
1346
  if (mod && e.key === 'b') { e.preventDefault(); exec('bold'); }
925
1347
  if (mod && e.key === 'i') { e.preventDefault(); exec('italic'); }
@@ -1100,6 +1522,47 @@
1100
1522
  e.preventDefault();
1101
1523
  const text = e.clipboardData?.getData('text/plain') || '';
1102
1524
  document.execCommand('insertText', false, text);
1525
+ return;
1526
+ }
1527
+ // The browser pastes next; the input event that follows tidies what came in.
1528
+ if (!readonly && editorEl) {
1529
+ const snapshot = new Set(editorEl.querySelectorAll('*'));
1530
+ pastedOver = snapshot;
1531
+ // A paste that inserts nothing (an empty clipboard, a host that cancels it) raises no
1532
+ // input event. Left set, the snapshot would make the next keystroke treat the whole
1533
+ // document as pasted.
1534
+ setTimeout(() => {
1535
+ if (pastedOver === snapshot) pastedOver = null;
1536
+ }, 0);
1537
+ }
1538
+ }
1539
+
1540
+ // ── Pasted formatting ──
1541
+ // A browser copies a paragraph with its looks written out: Chromium turns the editor's own
1542
+ // spacing into "margin: 0px 0px 0.2em 96px" on the copy, and repeats the id. Pasted back, the
1543
+ // copy looked the same until the writer or a later edit met those extra values, and two
1544
+ // elements shared one id. After a paste, each element that came in loses its id, and loses any
1545
+ // margin or first-line indent that changes nothing: one the editor's own style already gives,
1546
+ // or one on a piece of text inside a line, where neither has an effect.
1547
+ const PASTED_SPACING = ['margin-top', 'margin-right', 'margin-bottom', 'margin-left', 'text-indent'];
1548
+ /** The elements in the editor just before a paste; what is not in it came from the paste. */
1549
+ let pastedOver: Set<Element> | null = null;
1550
+
1551
+ function tidyPasted(before: Set<Element>): void {
1552
+ if (!editorEl) return;
1553
+ for (const el of Array.from(editorEl.querySelectorAll<HTMLElement>('*'))) {
1554
+ if (before.has(el)) continue;
1555
+ el.removeAttribute('id');
1556
+ if (!el.getAttribute('style')) continue;
1557
+ const inline = !el.matches(`${INDENT_TARGETS}, li, table, thead, tbody, tfoot, tr, td, th, figcaption, hr`);
1558
+ for (const prop of PASTED_SPACING) {
1559
+ const value = el.style.getPropertyValue(prop);
1560
+ if (!value) continue;
1561
+ const shown = getComputedStyle(el).getPropertyValue(prop);
1562
+ el.style.removeProperty(prop);
1563
+ if (!inline && getComputedStyle(el).getPropertyValue(prop) !== shown) el.style.setProperty(prop, value);
1564
+ }
1565
+ if (!el.getAttribute('style')) el.removeAttribute('style');
1103
1566
  }
1104
1567
  }
1105
1568
 
@@ -1146,6 +1609,13 @@
1146
1609
  onchange={handleImageFilesChosen}
1147
1610
  />
1148
1611
 
1612
+ <svelte:window
1613
+ onkeydown={(e) => {
1614
+ if (copyFormat !== 'off' && e.key === 'Escape') stopCopyFormat();
1615
+ }}
1616
+ onresize={placeCopySourceBox}
1617
+ />
1618
+
1149
1619
  <div
1150
1620
  class="ink-editor"
1151
1621
  style:--ink-min-height={minHeight}
@@ -1160,13 +1630,32 @@
1160
1630
  onblock={setBlock}
1161
1631
  oninsertlink={openLinkModal}
1162
1632
  oninsertimage={openImageModal}
1633
+ copyingFormat={copyFormat !== 'off'}
1634
+ oncopyformat={toggleCopyFormat}
1163
1635
  />
1164
1636
  {/if}
1165
1637
 
1638
+ {#if copyFormat !== 'off' && !readonly}
1639
+ <div class="ink-copy-format" role="status">
1640
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
1641
+ <span>
1642
+ {copyFormat === 'pick'
1643
+ ? 'Copy format: click the paragraph to copy from.'
1644
+ : 'Format copied. Click each paragraph that should get it.'}
1645
+ </span>
1646
+ <button type="button" class="ink-copy-format-done" onmousedown={(e) => e.preventDefault()} onclick={stopCopyFormat}>
1647
+ {copyFormat === 'pick' ? 'Cancel' : 'Done'}
1648
+ </button>
1649
+ <span class="ink-copy-format-key">or press Esc</span>
1650
+ </div>
1651
+ {/if}
1652
+
1166
1653
  <div class="ink-content-wrap" bind:this={contentWrapEl}>
1167
1654
  <!-- svelte-ignore a11y_no_static_element_interactions -->
1168
1655
  <div
1169
1656
  class="ink-content"
1657
+ class:copy-format-pick={copyFormat === 'pick'}
1658
+ class:copy-format-apply={copyFormat === 'apply'}
1170
1659
  contenteditable={!readonly}
1171
1660
  spellcheck="true"
1172
1661
  bind:this={editorEl}
@@ -1183,6 +1672,16 @@
1183
1672
  data-placeholder={placeholder}
1184
1673
  ></div>
1185
1674
 
1675
+ {#if copySourceBox}
1676
+ <div
1677
+ class="ink-copy-format-source"
1678
+ style:top="{copySourceBox.top}px"
1679
+ style:left="{copySourceBox.left}px"
1680
+ style:width="{copySourceBox.width}px"
1681
+ style:height="{copySourceBox.height}px"
1682
+ ></div>
1683
+ {/if}
1684
+
1186
1685
  {#if !readonly}
1187
1686
  <ImageOverlay
1188
1687
  bind:this={overlayRef}
@@ -1312,6 +1811,79 @@
1312
1811
  border-color: var(--border-active, #c4b5a0);
1313
1812
  }
1314
1813
 
1814
+ /* ── Copy format ── */
1815
+ /* The pointer says which step it is: a crosshair to pick the paragraph to copy from, then a
1816
+ brush that paints the format on. The paragraph under the pointer lights up, so it is clear
1817
+ what a click will act on. None of this is in the content, so none of it is exported. */
1818
+ .ink-content.copy-format-pick,
1819
+ .ink-content.copy-format-pick :global(*) {
1820
+ cursor: crosshair !important;
1821
+ }
1822
+
1823
+ .ink-content.copy-format-apply,
1824
+ .ink-content.copy-format-apply :global(*) {
1825
+ cursor:
1826
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='white' stroke='%231a1714' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='3' width='14' height='6' rx='1.5'/%3E%3Cpath d='M17 6h3v5h-9v3' fill='none'/%3E%3Crect x='9.5' y='14' width='3' height='7' rx='1'/%3E%3C/svg%3E")
1827
+ 4 4,
1828
+ copy !important;
1829
+ }
1830
+
1831
+ /* A <div> line counts as a paragraph (isPlainParagraph) unless it holds other blocks. */
1832
+ .ink-content.copy-format-pick :global(:is(p, h1, h2, h3, h4, h5, h6, div:not(:has(p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure, table, hr))):hover),
1833
+ .ink-content.copy-format-apply :global(:is(p, h1, h2, h3, h4, h5, h6, div:not(:has(p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure, table, hr))):hover) {
1834
+ background: var(--accent-soft, #ede9fe);
1835
+ border-radius: 3px;
1836
+ }
1837
+
1838
+ .ink-copy-format {
1839
+ display: flex;
1840
+ align-items: center;
1841
+ gap: 10px;
1842
+ margin: -8px 0 12px;
1843
+ padding: 8px 12px;
1844
+ border: 1px solid var(--accent, #6e56cf);
1845
+ border-radius: var(--radius-sm, 5px);
1846
+ background: var(--accent-soft, #ede9fe);
1847
+ color: var(--text, #2c2520);
1848
+ font-family: 'DM Sans', sans-serif;
1849
+ font-size: 13px;
1850
+ }
1851
+
1852
+ .ink-copy-format svg {
1853
+ flex-shrink: 0;
1854
+ color: var(--accent, #6e56cf);
1855
+ }
1856
+
1857
+ .ink-copy-format-done {
1858
+ margin-left: auto;
1859
+ padding: 4px 12px;
1860
+ border: 1px solid var(--accent, #6e56cf);
1861
+ border-radius: var(--radius-sm, 5px);
1862
+ background: white;
1863
+ color: var(--accent, #6e56cf);
1864
+ font: inherit;
1865
+ font-weight: 600;
1866
+ cursor: pointer;
1867
+ }
1868
+
1869
+ .ink-copy-format-done:hover {
1870
+ background: var(--accent, #6e56cf);
1871
+ color: white;
1872
+ }
1873
+
1874
+ .ink-copy-format-key {
1875
+ color: var(--text-muted, #8a7e72);
1876
+ font-size: 12px;
1877
+ }
1878
+
1879
+ .ink-copy-format-source {
1880
+ position: absolute;
1881
+ box-sizing: border-box;
1882
+ border: 1.5px dashed var(--accent, #6e56cf);
1883
+ border-radius: 3px;
1884
+ pointer-events: none;
1885
+ }
1886
+
1315
1887
  /* Placeholder */
1316
1888
  .ink-content:empty::before {
1317
1889
  content: attr(data-placeholder);
@@ -1348,7 +1920,10 @@
1348
1920
  margin-top: 24px;
1349
1921
  }
1350
1922
 
1351
- .ink-content :global(p) {
1923
+ /* A line the browser made as a <div> (after a paste, or Enter in loose text) is a paragraph
1924
+ like any other, and is written to RTF the same way: it gets the same spacing. */
1925
+ .ink-content :global(p),
1926
+ .ink-content :global(div) {
1352
1927
  margin: 0 0 0.2em;
1353
1928
  }
1354
1929
 
@@ -9,6 +9,9 @@
9
9
  onblock?: (tag: string) => void;
10
10
  oninsertlink?: () => void;
11
11
  oninsertimage?: () => void;
12
+ /** The Copy format brush is in hand: the button shows as pressed. */
13
+ copyingFormat?: boolean;
14
+ oncopyformat?: () => void;
12
15
  }
13
16
 
14
17
  let {
@@ -17,7 +20,9 @@
17
20
  onexec,
18
21
  onblock,
19
22
  oninsertlink,
20
- oninsertimage
23
+ oninsertimage,
24
+ copyingFormat = false,
25
+ oncopyformat
21
26
  }: Props = $props();
22
27
 
23
28
  function exec(cmd: string, value: string | null = null) {
@@ -104,6 +109,30 @@
104
109
  <ToolbarButton title="Increase indent (Ctrl+])" onclick={() => exec('indent')}>
105
110
  <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
111
  </ToolbarButton>
112
+ <ToolbarButton title="Decrease hanging indent" onclick={() => exec('hangingOutdent')}>
113
+ <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="11" y1="19" x2="21" y2="19"/><polyline points="7 11.5 4 14.5 7 17.5"/></svg>
114
+ </ToolbarButton>
115
+ <ToolbarButton title="Increase hanging indent" onclick={() => exec('hangingIndent')}>
116
+ <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="11" y1="19" x2="21" y2="19"/><polyline points="4 11.5 7 14.5 4 17.5"/></svg>
117
+ </ToolbarButton>
118
+ <ToolbarButton title="Hang at caret" onclick={() => exec('hangAtCaret')}>
119
+ <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="7" y2="5"/><line x1="14" y1="5" x2="21" y2="5"/><line x1="10.5" y1="2" x2="10.5" y2="8" stroke="var(--accent, currentColor)"/><line x1="10.5" y1="11" x2="21" y2="11"/><line x1="10.5" y1="15" x2="21" y2="15"/><line x1="10.5" y1="19" x2="21" y2="19"/></svg>
120
+ </ToolbarButton>
121
+ <ToolbarButton title="Decrease right indent" onclick={() => exec('rightOutdent')}>
122
+ <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="3" y1="10" x2="13" y2="10"/><line x1="3" y1="14" x2="13" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="17 9 20 12 17 15"/></svg>
123
+ </ToolbarButton>
124
+ <ToolbarButton title="Increase right indent" onclick={() => exec('rightIndent')}>
125
+ <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="3" y1="10" x2="13" y2="10"/><line x1="3" y1="14" x2="13" y2="14"/><line x1="3" y1="19" x2="21" y2="19"/><polyline points="20 9 17 12 20 15"/></svg>
126
+ </ToolbarButton>
127
+ </div>
128
+
129
+ <div class="toolbar-divider"></div>
130
+
131
+ <!-- Copy format -->
132
+ <div class="toolbar-group">
133
+ <ToolbarButton active={copyingFormat} title="Copy format" onclick={oncopyformat}>
134
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="6" rx="1.5"/><path d="M17 6h3v5h-9v3"/><rect x="9.5" y="14" width="3" height="7" rx="1"/></svg>
135
+ </ToolbarButton>
107
136
  </div>
108
137
 
109
138
  <div class="toolbar-divider"></div>
@@ -5,6 +5,9 @@ interface Props {
5
5
  onblock?: (tag: string) => void;
6
6
  oninsertlink?: () => void;
7
7
  oninsertimage?: () => void;
8
+ /** The Copy format brush is in hand: the button shows as pressed. */
9
+ copyingFormat?: boolean;
10
+ oncopyformat?: () => void;
8
11
  }
9
12
  declare const Toolbar: import("svelte").Component<Props, {}, "">;
10
13
  type Toolbar = ReturnType<typeof Toolbar>;
@@ -154,6 +154,18 @@ function renderPicture(group) {
154
154
  return `<img src="data:${mime};base64,${base64}"${style} alt="">`;
155
155
  }
156
156
  // ── Tokenizer ──
157
+ /**
158
+ * What \'80 to \'9f stand for in Windows-1252, the code page RTF's \ansi text is written in:
159
+ * curly quotes, dashes, the euro sign and the like, where Latin-1 has invisible control
160
+ * characters. \'92 is the apostrophe in "It's" as TextEdit and many Windows programs write it.
161
+ * The five bytes Windows-1252 leaves undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) keep their own value.
162
+ */
163
+ const WINDOWS_1252_C1 = [
164
+ 0x20ac, 0x81, 0x201a, 0x0192, 0x201e, 0x2026, 0x2020, 0x2021,
165
+ 0x02c6, 0x2030, 0x0160, 0x2039, 0x0152, 0x8d, 0x017d, 0x8f,
166
+ 0x90, 0x2018, 0x2019, 0x201c, 0x201d, 0x2022, 0x2013, 0x2014,
167
+ 0x02dc, 0x2122, 0x0161, 0x203a, 0x0153, 0x9d, 0x017e, 0x0178
168
+ ];
157
169
  function tokenize(rtf) {
158
170
  const tokens = [];
159
171
  let i = 0;
@@ -173,13 +185,16 @@ function tokenize(rtf) {
173
185
  if (i >= len)
174
186
  break;
175
187
  const next = rtf[i];
176
- // Hex escape \'xx
188
+ // Hex escape \'xx. One without two hex digits after it is damaged: it is dropped, and
189
+ // what follows it is read as usual, rather than turned into a NUL or a control character.
177
190
  if (next === "'") {
178
191
  i++;
179
192
  const hex = rtf.substring(i, i + 2);
180
- i += 2;
181
- const code = parseInt(hex, 16);
182
- tokens.push({ type: 'text', value: String.fromCharCode(code) });
193
+ if (/^[0-9a-fA-F]{2}$/.test(hex)) {
194
+ i += 2;
195
+ const code = parseInt(hex, 16);
196
+ tokens.push({ type: 'text', value: String.fromCharCode(WINDOWS_1252_C1[code - 0x80] ?? code) });
197
+ }
183
198
  }
184
199
  // Special escapes
185
200
  else if (next === '\\' || next === '{' || next === '}') {
@@ -361,6 +376,15 @@ const destinationWords = new Set([
361
376
  'latentstyles', 'datastore', 'mmathPr', 'author', 'operator',
362
377
  'title', 'subject', 'doccomm', 'company', 'category', 'keywords'
363
378
  ]);
379
+ /** Twips as a CSS length in points (20 twips), which the writer reads back as the same twips. */
380
+ function twipsToPt(twips) {
381
+ return `${Math.round(twips * 5) / 100}pt`;
382
+ }
383
+ function resetIndents(state) {
384
+ state.leftIndent = 0;
385
+ state.rightIndent = 0;
386
+ state.firstLineIndent = 0;
387
+ }
364
388
  export function rtfToHtml(rtfString, options = {}) {
365
389
  const tokens = tokenize(rtfString);
366
390
  const tree = buildTree(tokens);
@@ -369,6 +393,8 @@ export function rtfToHtml(rtfString, options = {}) {
369
393
  let currentParagraph = '';
370
394
  const paragraphs = [];
371
395
  const paragraphAligns = [];
396
+ const paragraphIndents = [];
397
+ const paragraphFigureIndents = [];
372
398
  const paragraphCaptions = [];
373
399
  let paragraphHasText = false;
374
400
  let paragraphHasListMarker = false;
@@ -377,10 +403,41 @@ export function rtfToHtml(rtfString, options = {}) {
377
403
  function pushParagraph(html, align, isCaption = false) {
378
404
  paragraphs.push(html);
379
405
  paragraphAligns.push(align);
406
+ const inTable = inTableCell || html.startsWith('<table');
407
+ paragraphIndents.push(inTable ? '' : indentStyle());
408
+ paragraphFigureIndents.push(inTable ? '' : figureIndentStyle());
380
409
  paragraphCaptions.push(isCaption);
381
410
  }
382
411
  // Paragraph alignment (reset by \pard, affects cells and paragraphs)
383
412
  let currentAlign = 'left';
413
+ /**
414
+ * The current indents as CSS, in points (20 twips), which the writer reads back as the same
415
+ * \li, \ri and \fi: "margin-left:36pt;text-indent:-36pt". A first line may not start left of
416
+ * the page margin, where a browser would clip it.
417
+ */
418
+ function indentStyle() {
419
+ const { leftIndent, rightIndent, firstLineIndent } = currentState();
420
+ const left = Math.max(0, leftIndent);
421
+ const first = Math.max(-left, firstLineIndent);
422
+ const parts = [];
423
+ if (left > 0)
424
+ parts.push(`margin-left:${twipsToPt(left)}`);
425
+ if (rightIndent > 0)
426
+ parts.push(`margin-right:${twipsToPt(rightIndent)}`);
427
+ if (first !== 0)
428
+ parts.push(`text-indent:${twipsToPt(first)}`);
429
+ return parts.join(';');
430
+ }
431
+ /**
432
+ * The indent of a picture's paragraph: where its one line starts, as a left margin. A figure
433
+ * is written back with a left indent only, and a first-line indent on it would be passed on to
434
+ * its caption.
435
+ */
436
+ function figureIndentStyle() {
437
+ const { leftIndent, firstLineIndent } = currentState();
438
+ const start = Math.max(0, leftIndent) + Math.max(-Math.max(0, leftIndent), firstLineIndent);
439
+ return start > 0 ? `margin-left:${twipsToPt(start)}` : '';
440
+ }
384
441
  // Table state
385
442
  let tableRows = [];
386
443
  let currentRowCells = [];
@@ -421,6 +478,9 @@ export function rtfToHtml(rtfString, options = {}) {
421
478
  fontIndex: 0,
422
479
  ucSkip: 1,
423
480
  inList: false,
481
+ leftIndent: 0,
482
+ rightIndent: 0,
483
+ firstLineIndent: 0,
424
484
  };
425
485
  }
426
486
  const stateStack = [defaultState()];
@@ -626,6 +686,15 @@ export function rtfToHtml(rtfString, options = {}) {
626
686
  case 'qj':
627
687
  currentAlign = 'justify';
628
688
  break;
689
+ case 'li':
690
+ state.leftIndent = p ?? 0;
691
+ break;
692
+ case 'ri':
693
+ state.rightIndent = p ?? 0;
694
+ break;
695
+ case 'fi':
696
+ state.firstLineIndent = p ?? 0;
697
+ break;
629
698
  case 'par':
630
699
  if (!inTableCell)
631
700
  flushParagraph();
@@ -682,6 +751,9 @@ export function rtfToHtml(rtfString, options = {}) {
682
751
  currentRowCellRights = [];
683
752
  currentRowCellAligns = [];
684
753
  inTableCell = false;
754
+ // The cell's indents end with the table, in whichever group set them:
755
+ // \row may sit in a group of its own ({\row}).
756
+ stateStack.forEach(resetIndents);
685
757
  break;
686
758
  case 'pard':
687
759
  state.bold = false;
@@ -689,6 +761,7 @@ export function rtfToHtml(rtfString, options = {}) {
689
761
  state.underline = false;
690
762
  state.strike = false;
691
763
  currentAlign = 'left';
764
+ resetIndents(state);
692
765
  break;
693
766
  case 'line':
694
767
  currentParagraph += '<br>';
@@ -812,6 +885,11 @@ export function rtfToHtml(rtfString, options = {}) {
812
885
  for (let i = 0; i < trimmedParagraphs.length; i++) {
813
886
  const trimmed = trimmedParagraphs[i];
814
887
  const align = paragraphAligns[i] ?? 'left';
888
+ // The paragraph's style attribute: its alignment, then its indents.
889
+ const blockStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphIndents[i] ?? '']
890
+ .filter(Boolean)
891
+ .join(';');
892
+ const styleAttr = blockStyle ? ` style="${blockStyle}"` : '';
815
893
  const prev = i > 0 ? trimmedParagraphs[i - 1] : '';
816
894
  const next = i + 1 < trimmedParagraphs.length ? trimmedParagraphs[i + 1] : '';
817
895
  if (!trimmed) {
@@ -844,8 +922,10 @@ export function rtfToHtml(rtfString, options = {}) {
844
922
  // A paragraph holding nothing but pictures becomes a figure, so it can carry
845
923
  // a caption and be aligned/resized as a unit in the editor.
846
924
  if (IMAGE_ONLY_PARAGRAPH.test(trimmed)) {
847
- const alignAttr = align !== 'left' ? ` style="text-align:${align}"` : '';
848
- rendered.push(`<figure${alignAttr}>${trimmed}</figure>`);
925
+ const figureStyle = [align !== 'left' ? `text-align:${align}` : '', paragraphFigureIndents[i] ?? '']
926
+ .filter(Boolean)
927
+ .join(';');
928
+ rendered.push(`<figure${figureStyle ? ` style="${figureStyle}"` : ''}>${trimmed}</figure>`);
849
929
  continue;
850
930
  }
851
931
  const sizeMatch = trimmed.match(/font-size:\s*([\d.]+)pt/);
@@ -853,27 +933,25 @@ export function rtfToHtml(rtfString, options = {}) {
853
933
  // Compared in half-points, rounded the way the writer rounds them, so
854
934
  // a heading written at any body size is read back as the same level.
855
935
  const halfPoints = Math.round(parseFloat(sizeMatch[1]) * 2);
856
- const alignAttr = align !== 'left' ? ` style="text-align:${align}"` : '';
857
936
  const atLeast = (scale) => halfPoints >= Math.round(bodySize * scale);
858
937
  // At the default 12 pt, size alone makes a heading, as it always has. At
859
938
  // another screen size, ordinary 12 pt text can be a step above the body,
860
939
  // so a heading must also be bold, as every heading the writer emits is.
861
940
  const looksLikeHeading = bodySize === 24 || /^<strong>/.test(trimmed);
862
941
  if (looksLikeHeading && atLeast(HEADING_SCALE.h1)) {
863
- rendered.push(`<h1${alignAttr}>${stripSizeSpan(trimmed)}</h1>`);
942
+ rendered.push(`<h1${styleAttr}>${stripSizeSpan(trimmed)}</h1>`);
864
943
  continue;
865
944
  }
866
945
  if (looksLikeHeading && atLeast(HEADING_SCALE.h2)) {
867
- rendered.push(`<h2${alignAttr}>${stripSizeSpan(trimmed)}</h2>`);
946
+ rendered.push(`<h2${styleAttr}>${stripSizeSpan(trimmed)}</h2>`);
868
947
  continue;
869
948
  }
870
949
  if (looksLikeHeading && atLeast(HEADING_SCALE.h3)) {
871
- rendered.push(`<h3${alignAttr}>${stripSizeSpan(trimmed)}</h3>`);
950
+ rendered.push(`<h3${styleAttr}>${stripSizeSpan(trimmed)}</h3>`);
872
951
  continue;
873
952
  }
874
953
  }
875
- const pStyle = align !== 'left' ? ` style="text-align:${align}"` : '';
876
- rendered.push(`<p${pStyle}>${trimmed}</p>`);
954
+ rendered.push(`<p${styleAttr}>${trimmed}</p>`);
877
955
  }
878
956
  const output = rendered.join('\n');
879
957
  // fontTable is parsed (for future font rendering) but not yet used in output
@@ -384,9 +384,14 @@ export function estimateRtfBytes(editorEl) {
384
384
  total += ((editorEl.textContent || '').match(/\t/g)?.length ?? 0) * 4;
385
385
  // A block's alignment (\qc, 3) and left indent (\liN, up to 7) are written per paragraph,
386
386
  // for every block inside an indented one too: count 12 for each block that could carry them.
387
+ // A paragraph's own right indent (\\riN) and first-line indent (\\fi-N) are up to 8 more each.
387
388
  for (const block of Array.from(editorEl.querySelectorAll('p, div, li, h1, h2, h3, h4, h5, h6, pre, blockquote'))) {
388
389
  if (block.closest('[style*="margin"], [style*="text-align"], [align]'))
389
390
  total += 12;
391
+ if (block.style?.marginRight)
392
+ total += 8;
393
+ if (block.style?.textIndent)
394
+ total += 8;
390
395
  }
391
396
  // Each paragraph's formatting, worked out once: a blank line looks at the one before it.
392
397
  const formatCache = new Map();
@@ -621,17 +626,17 @@ function walkChildren(parent, ctx) {
621
626
  // Heading sizes keep their ratio to the body (HEADING_SCALE).
622
627
  case 'h1': {
623
628
  const size = scaled(ctx, HEADING_SCALE.h1);
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 `;
629
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
625
630
  break;
626
631
  }
627
632
  case 'h2': {
628
633
  const size = scaled(ctx, HEADING_SCALE.h2);
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 `;
634
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
630
635
  break;
631
636
  }
632
637
  case 'h3': {
633
638
  const size = scaled(ctx, HEADING_SCALE.h3);
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 `;
639
+ rtf += `\\pard${inCell(ctx)}${headingLayout(el, ctx)}\\f0\\fs${size}\\b ${walkChildren(el, { ...ctx, bold: true, size })}${ctx.bold ? '' : '\\b0'}\\fs${ctx.size}\\par `;
635
640
  break;
636
641
  }
637
642
  case 'p':
@@ -940,7 +945,7 @@ function restateAfterBlock(node, ctx) {
940
945
  const tag = block.tagName.toLowerCase();
941
946
  const formatted = FORMATTED_BLOCK_TAGS.has(tag) ||
942
947
  (['p', 'div'].includes(tag) && (ctx.inTableCell ? paragraphLayout(block, ctx) : paragraphFormat(block, ctx)) !== '') ||
943
- (['h1', 'h2', 'h3'].includes(tag) && paragraphLayout(block, ctx) !== '') ||
948
+ (['h1', 'h2', 'h3'].includes(tag) && headingLayout(block, ctx) !== '') ||
944
949
  (tag === 'pre' && ctx.indent + leftMarginTwips(block) > 0);
945
950
  return formatted ? `\\pard${inCell(ctx)}${liControl(ctx.indent)} ` : '';
946
951
  }
@@ -1002,6 +1007,19 @@ function alignOf(el) {
1002
1007
  function paragraphLayout(el, ctx) {
1003
1008
  return `${alignOf(el)}${liControl(ctx.indent + leftMarginTwips(el))}`;
1004
1009
  }
1010
+ /**
1011
+ * A heading's layout: its alignment and left indent, and outside a table cell its right and
1012
+ * first-line indents too, so a heading read from RTF with a hanging number goes back as it came.
1013
+ */
1014
+ function headingLayout(el, ctx) {
1015
+ return `${paragraphLayout(el, ctx)}${ctx.inTableCell ? '' : edgeIndents(el)}`;
1016
+ }
1017
+ /** \\riN for margin-right and \\fiN for text-indent, or nothing where the element sets none. */
1018
+ function edgeIndents(el) {
1019
+ const ri = lengthTwips(el.style?.marginRight);
1020
+ const fi = lengthTwips(el.style?.textIndent, true);
1021
+ return `${ri ? `\\ri${ri}` : ''}${fi ? `\\fi${fi}` : ''}`;
1022
+ }
1005
1023
  /**
1006
1024
  * A <p> or <div>'s formatting outside a table cell: its alignment, then paragraphControls with the
1007
1025
  * indent of the blocks around it plus its own margin.
@@ -1016,6 +1034,7 @@ function paragraphFormat(el, ctx) {
1016
1034
  * |--------------------------------------------------|-------------------|
1017
1035
  * | data-rtf-tab-stops="1.75in" (comma-separated) | \tx2520 |
1018
1036
  * | margin-left: 1.75in (the left indent, given) | \li2520 |
1037
+ * | margin-right: 0.5in | \ri720 |
1019
1038
  * | text-indent: -1.75in | \fi-2520 |
1020
1039
  * | margin-top: 5pt / margin-bottom: 5pt | \sb100 / \sa100 |
1021
1040
  * | break-after: avoid, or page-break-after: avoid | \keepn |
@@ -1036,9 +1055,7 @@ function paragraphControls(el, leftTwips) {
1036
1055
  const style = el.style;
1037
1056
  if (!style)
1038
1057
  return out;
1039
- const fi = lengthTwips(style.textIndent, true);
1040
- if (fi)
1041
- out += `\\fi${fi}`;
1058
+ out += edgeIndents(el);
1042
1059
  const sb = lengthTwips(style.marginTop);
1043
1060
  if (sb)
1044
1061
  out += `\\sb${sb}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svelte-rtf-editor",
3
- "version": "1.7.0",
3
+ "version": "1.8.1",
4
4
  "description": "RTF viewer and rich-text editor components for Svelte 5",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/jcelano/svelte-rtf-editor#readme",