svelte-rtf-editor 1.6.0 → 1.8.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.
@@ -180,6 +180,7 @@
180
180
  export function setHTML(html: string): void {
181
181
  if (editorEl) {
182
182
  selectedImage = null;
183
+ documentReplaced();
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
+ documentReplaced();
214
216
  editorEl.innerHTML = '<p></p>';
215
217
  try { localStorage.removeItem(storageKey); } catch (e) {}
216
218
  updateCounts();
@@ -249,6 +251,31 @@
249
251
  fileInputEl?.click();
250
252
  }
251
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
+
252
279
  // ── Selection helpers ──
253
280
  function saveSelection(): void {
254
281
  const sel = window.getSelection();
@@ -276,10 +303,581 @@
276
303
  const sel = window.getSelection();
277
304
  if (!sel || sel.isCollapsed) return;
278
305
  }
306
+ if (isIndentCommand(cmd)) {
307
+ indentBlocks(cmd);
308
+ return;
309
+ }
310
+ if (cmd === 'hangAtCaret') {
311
+ hangAtCaret();
312
+ return;
313
+ }
314
+ if (cmd === 'undo' && undoIndent()) return;
279
315
  document.execCommand(cmd, false, value ?? undefined);
280
316
  updateToolbarState();
281
317
  }
282
318
 
319
+ // ── Indent ──
320
+ // Indent and Outdent move the paragraphs the selection touches by half an inch (48px, written
321
+ // to RTF as \li720) per press, as margin-left on each paragraph. The browser's own commands are
322
+ // not used: Chromium's Outdent strips the first paragraph to loose text ("one<br>"), and the
323
+ // browsers disagree on the markup. Only a style changes (and a line of loose text gets a
324
+ // paragraph of its own), so earlier typing stays undoable; the editor keeps its own undo for
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.
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
+ }
348
+ const INDENT_TARGETS = 'p, div, h1, h2, h3, h4, h5, h6, pre, ul, ol, blockquote, figure';
349
+ /** CSS lengths a margin is written in, in px. */
350
+ const PX_PER_UNIT: Record<string, number> = { px: 1, pt: 96 / 72, in: 96, cm: 96 / 2.54, mm: 96 / 25.4 };
351
+
352
+ /** One block an Indent or Outdent changed, and how to put it back. */
353
+ interface IndentChange {
354
+ el: HTMLElement;
355
+ before: string | null;
356
+ after: string | null;
357
+ /** The block is a paragraph this step made around loose text, and the <br> that ended it. */
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 };
361
+ }
362
+ let indentUndo: IndentChange[][] = [];
363
+
364
+ function indentBlocks(cmd: IndentCommand): void {
365
+ if (readonly || !editorEl) return;
366
+ editorEl.focus();
367
+ const sel = window.getSelection();
368
+ if (!sel || sel.rangeCount === 0 || !sel.anchorNode || !editorEl.contains(sel.anchorNode)) return;
369
+ const { anchorNode, anchorOffset, focusNode, focusOffset } = sel;
370
+ const wrapped = new Map<HTMLElement, HTMLBRElement | null>();
371
+ const targets = indentTargets(sel.getRangeAt(0), cmd, wrapped);
372
+ // Wrapping loose text moves the selected text nodes, which collapses the selection; put it
373
+ // back so the next press moves the same lines.
374
+ if (wrapped.size > 0 && anchorNode instanceof Text && focusNode instanceof Text && anchorNode.isConnected && focusNode.isConnected) {
375
+ sel.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
376
+ }
377
+ const step: IndentChange[] = [];
378
+ for (const el of targets) {
379
+ const before = el.getAttribute('style');
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
+ }
408
+ if (!el.getAttribute('style')) el.removeAttribute('style');
409
+ const br = wrapped.get(el);
410
+ step.push({ el, before, after: el.getAttribute('style'), wrapped: br === undefined ? null : { br } });
411
+ }
412
+ if (step.length === 0) return;
413
+ indentUndo.push(step);
414
+ indentChanged();
415
+ }
416
+
417
+ /** An element's left margin in px: its own, from the inline style, or 0. */
418
+ function marginLeftPx(el: HTMLElement): number {
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();
435
+ if (!value) return 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`));
449
+ }
450
+
451
+ /**
452
+ * The indent shape Chromium, WebKit and Gmail paste: a blockquote with a left margin and
453
+ * border: none. A quotation keeps its border. The RTF writer reads it the same way.
454
+ */
455
+ function isIndentBlockquote(el: Element): el is HTMLElement {
456
+ return el instanceof HTMLElement && el.tagName === 'BLOCKQUOTE' && el.style.borderLeftStyle === 'none';
457
+ }
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
+
754
+ /** Undo the last Indent or Outdent, if nothing has changed since. */
755
+ function undoIndent(): boolean {
756
+ const step = indentUndo.pop();
757
+ if (!step) return false;
758
+ // Content replaced or edited since (setHTML, an import, a link): the step no longer applies.
759
+ if (step.some(({ el, after }) => !el.isConnected || el.getAttribute('style') !== after)) {
760
+ indentUndo = [];
761
+ return false;
762
+ }
763
+ for (const { el, before, wrapped, stops } of step) {
764
+ if (before === null) el.removeAttribute('style');
765
+ else el.setAttribute('style', before);
766
+ if (stops) {
767
+ if (stops.before === null) el.removeAttribute(TAB_STOPS);
768
+ else el.setAttribute(TAB_STOPS, stops.before);
769
+ }
770
+ if (wrapped) undoWrap(el, wrapped);
771
+ }
772
+ indentChanged();
773
+ return true;
774
+ }
775
+
776
+ function indentChanged(): void {
777
+ placeCopySourceBox();
778
+ updateToolbarState();
779
+ fireChange();
780
+ if (autosave) scheduleAutoSave();
781
+ }
782
+
783
+ /**
784
+ * The blocks Indent moves: each line's paragraph, and a list, a quotation or a picture as a
785
+ * whole. A line of loose text (typed straight into the editor or a table cell) is first given a
786
+ * paragraph of its own, so the margin moves that line only. Outdent on a line with no margin
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.
789
+ */
790
+ function indentTargets(
791
+ range: Range,
792
+ cmd: IndentCommand,
793
+ wrapped: Map<HTMLElement, HTMLBRElement | null>
794
+ ): HTMLElement[] {
795
+ if (!editorEl) return [];
796
+ const root = editorEl;
797
+ const found: HTMLElement[] = [];
798
+ const add = (el: HTMLElement | null) => {
799
+ if (el && !found.includes(el)) found.push(el);
800
+ };
801
+ const blockFor = (node: Node): HTMLElement | null => {
802
+ if (node === root || !root.contains(node)) return null;
803
+ const el = node instanceof Element ? node : node.parentElement;
804
+ if (!el) return null;
805
+ const cell = el.closest('td, th');
806
+ const inScope = (b: Element | null | undefined): b is HTMLElement =>
807
+ b instanceof HTMLElement && b !== root && root.contains(b) && (!cell || cell.contains(b));
808
+ const item = el.closest('li');
809
+ const closest = el.closest(INDENT_TARGETS);
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
+ }
819
+ if (cmd === 'outdent' && (!block || marginLeftPx(block) === 0)) {
820
+ for (let a = (block ?? el).parentElement; inScope(a); a = a.parentElement) {
821
+ if (isIndentBlockquote(a) && marginLeftPx(a) > 0) return a;
822
+ }
823
+ return block;
824
+ }
825
+ if (inScope(block)) return block;
826
+ if (cmd === 'outdent') return null;
827
+ const made = wrapLooseLine(node);
828
+ if (made) wrapped.set(made.p, made.br);
829
+ return made?.p ?? null;
830
+ };
831
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
832
+ const texts: Text[] = [];
833
+ for (let n = walker.nextNode() as Text | null; n; n = walker.nextNode() as Text | null) {
834
+ if (!n.data.trim() || !range.intersectsNode(n)) continue;
835
+ // A selection that only touches a line's edge (dragged to the start of the next line)
836
+ // does not move that line.
837
+ if (n === range.endContainer && range.endOffset === 0 && !range.collapsed) continue;
838
+ if (n === range.startContainer && range.startOffset === n.length && !range.collapsed) continue;
839
+ texts.push(n);
840
+ }
841
+ if (texts.length === 0) add(blockFor(range.startContainer));
842
+ for (const t of texts) add(blockFor(t));
843
+ return found;
844
+ }
845
+
846
+ /**
847
+ * Put the run of loose text and inline elements around a node into a <p>, and return it with
848
+ * the <br> that ended the run, which the paragraph replaces.
849
+ */
850
+ function wrapLooseLine(node: Node): { p: HTMLElement; br: HTMLBRElement | null } | null {
851
+ if (!editorEl || node === editorEl || !editorEl.contains(node)) return null;
852
+ let start: Node = node;
853
+ while (start.parentNode && start.parentNode !== editorEl && !(start.parentNode as Element).matches?.('td, th')) {
854
+ start = start.parentNode;
855
+ }
856
+ const parent = start.parentNode;
857
+ if (!parent || !editorEl.contains(parent)) return null;
858
+ const isBreak = (n: Node | null) =>
859
+ !n || (n instanceof Element && (n.matches(INDENT_TARGETS) || n.matches('br, table, hr')));
860
+ if (isBreak(start)) return null;
861
+ let first: Node = start;
862
+ while (!isBreak(first.previousSibling)) first = first.previousSibling!;
863
+ let last: Node = start;
864
+ while (!isBreak(last.nextSibling)) last = last.nextSibling!;
865
+ const p = document.createElement('p');
866
+ parent.insertBefore(p, first);
867
+ let n: Node | null = first;
868
+ while (n) {
869
+ const next: Node | null = n === last ? null : n.nextSibling;
870
+ p.appendChild(n);
871
+ n = next;
872
+ }
873
+ let br: HTMLBRElement | null = null;
874
+ if (p.nextSibling instanceof HTMLBRElement) {
875
+ br = p.nextSibling;
876
+ br.remove();
877
+ }
878
+ return { p, br };
879
+ }
880
+
283
881
  // ── Block type ──
284
882
  function setBlock(tag: string): void {
285
883
  restoreSelection();
@@ -351,6 +949,12 @@
351
949
 
352
950
  // ── Input handler ──
353
951
  function handleInput(): void {
952
+ placeCopySourceBox();
953
+ if (pastedOver) {
954
+ tidyPasted(pastedOver);
955
+ pastedOver = null;
956
+ }
957
+ indentUndo = [];
354
958
  updateToolbarState();
355
959
  // Typing means the user is editing text, not the picture. Dropping the
356
960
  // selection here keeps Backspace editing that text instead of deleting a
@@ -379,6 +983,8 @@
379
983
  return;
380
984
  }
381
985
  linkError = '';
986
+ // Inserting changes the document outside an input event: earlier indent steps no longer undo.
987
+ indentUndo = [];
382
988
  restoreSelection();
383
989
  editorEl?.focus();
384
990
 
@@ -504,6 +1110,7 @@
504
1110
  caption: string
505
1111
  ): { img: HTMLImageElement; after: HTMLElement } | null {
506
1112
  if (!editorEl) return null;
1113
+ indentUndo = [];
507
1114
 
508
1115
  const figure = document.createElement('figure');
509
1116
  const img = document.createElement('img');
@@ -612,6 +1219,10 @@
612
1219
  // ── Image selection / editing ──
613
1220
  function handleContentClick(e: MouseEvent): void {
614
1221
  if (readonly) return;
1222
+ if (copyFormat !== 'off') {
1223
+ handleCopyFormatClick(e);
1224
+ return;
1225
+ }
615
1226
  const target = e.target as HTMLElement | null;
616
1227
  selectedImage = target?.tagName === 'IMG' ? (target as HTMLImageElement) : null;
617
1228
  }
@@ -708,6 +1319,7 @@
708
1319
  const html = await readRtfFile(file, { fontSize });
709
1320
  if (editorEl) {
710
1321
  selectedImage = null;
1322
+ documentReplaced();
711
1323
  editorEl.innerHTML = html;
712
1324
  updateCounts();
713
1325
  fireChange();
@@ -724,12 +1336,21 @@
724
1336
 
725
1337
  // ── Keyboard shortcuts ──
726
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
+ }
727
1345
  const mod = e.ctrlKey || e.metaKey;
728
1346
  if (mod && e.key === 'b') { e.preventDefault(); exec('bold'); }
729
1347
  if (mod && e.key === 'i') { e.preventDefault(); exec('italic'); }
730
1348
  if (mod && e.key === 'u') { e.preventDefault(); exec('underline'); }
731
1349
  if (mod && e.key === 'k') { e.preventDefault(); openLinkModal(); }
732
1350
  if (mod && e.key === 's') { e.preventDefault(); autoSaveNow(); }
1351
+ if (mod && !e.shiftKey && e.key.toLowerCase() === 'z' && undoIndent()) { e.preventDefault(); return; }
1352
+ if (mod && e.key === ']') { e.preventDefault(); indentBlocks('indent'); return; }
1353
+ if (mod && e.key === '[') { e.preventDefault(); indentBlocks('outdent'); return; }
733
1354
 
734
1355
  // Moving the caret leaves the picture behind, so drop its selection frame.
735
1356
  // Deliberately falls through: these keys still have their normal meaning,
@@ -771,6 +1392,12 @@
771
1392
  if (!e.shiftKey) document.execCommand('insertText', false, ' ');
772
1393
  return;
773
1394
  }
1395
+ // Several lines selected: Tab and Shift+Tab indent and outdent them all, as a word
1396
+ // processor does. Within one line, Tab types a tab.
1397
+ if (selectionSpansLines(sel)) {
1398
+ indentBlocks(e.shiftKey ? 'outdent' : 'indent');
1399
+ return;
1400
+ }
774
1401
  if (!e.shiftKey) {
775
1402
  insertTab(sel);
776
1403
  return;
@@ -810,6 +1437,16 @@
810
1437
  return range.toString();
811
1438
  }
812
1439
 
1440
+ /** Whether a selection runs across more than one paragraph or line. */
1441
+ function selectionSpansLines(sel: Selection): boolean {
1442
+ if (sel.isCollapsed || sel.rangeCount === 0 || !editorEl) return false;
1443
+ const range = sel.getRangeAt(0);
1444
+ const blockOf = (n: Node) =>
1445
+ (n instanceof Element ? n : n.parentElement)?.closest(LINE_BLOCKS) ?? editorEl;
1446
+ if (blockOf(range.startContainer) !== blockOf(range.endContainer)) return true;
1447
+ return range.cloneContents().querySelector('br') !== null;
1448
+ }
1449
+
813
1450
  const LINE_BLOCKS = 'p, div, li, td, th, h1, h2, h3, h4, h5, h6, blockquote';
814
1451
 
815
1452
  /** The first tab of the caret's line, if the line starts with one: its text node and offset. */
@@ -885,6 +1522,47 @@
885
1522
  e.preventDefault();
886
1523
  const text = e.clipboardData?.getData('text/plain') || '';
887
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');
888
1566
  }
889
1567
  }
890
1568
 
@@ -931,6 +1609,13 @@
931
1609
  onchange={handleImageFilesChosen}
932
1610
  />
933
1611
 
1612
+ <svelte:window
1613
+ onkeydown={(e) => {
1614
+ if (copyFormat !== 'off' && e.key === 'Escape') stopCopyFormat();
1615
+ }}
1616
+ onresize={placeCopySourceBox}
1617
+ />
1618
+
934
1619
  <div
935
1620
  class="ink-editor"
936
1621
  style:--ink-min-height={minHeight}
@@ -945,13 +1630,32 @@
945
1630
  onblock={setBlock}
946
1631
  oninsertlink={openLinkModal}
947
1632
  oninsertimage={openImageModal}
1633
+ copyingFormat={copyFormat !== 'off'}
1634
+ oncopyformat={toggleCopyFormat}
948
1635
  />
949
1636
  {/if}
950
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
+
951
1653
  <div class="ink-content-wrap" bind:this={contentWrapEl}>
952
1654
  <!-- svelte-ignore a11y_no_static_element_interactions -->
953
1655
  <div
954
1656
  class="ink-content"
1657
+ class:copy-format-pick={copyFormat === 'pick'}
1658
+ class:copy-format-apply={copyFormat === 'apply'}
955
1659
  contenteditable={!readonly}
956
1660
  spellcheck="true"
957
1661
  bind:this={editorEl}
@@ -968,6 +1672,16 @@
968
1672
  data-placeholder={placeholder}
969
1673
  ></div>
970
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
+
971
1685
  {#if !readonly}
972
1686
  <ImageOverlay
973
1687
  bind:this={overlayRef}
@@ -1097,6 +1811,79 @@
1097
1811
  border-color: var(--border-active, #c4b5a0);
1098
1812
  }
1099
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
+
1100
1887
  /* Placeholder */
1101
1888
  .ink-content:empty::before {
1102
1889
  content: attr(data-placeholder);
@@ -1133,7 +1920,10 @@
1133
1920
  margin-top: 24px;
1134
1921
  }
1135
1922
 
1136
- .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) {
1137
1927
  margin: 0 0 0.2em;
1138
1928
  }
1139
1929
 
@@ -1147,6 +1937,18 @@
1147
1937
  border-radius: 0 var(--radius-sm, 5px) var(--radius-sm, 5px) 0;
1148
1938
  }
1149
1939
 
1940
+ /* The indent Chromium, WebKit and Gmail paste (border: none) is an indent, not a quotation:
1941
+ the RTF writes it plain, so it shows plain here too. */
1942
+ .ink-content :global(blockquote[style*='border: none']),
1943
+ .ink-content :global(blockquote[style*='border:none']),
1944
+ .ink-content :global(blockquote[style*='border-style: none']),
1945
+ .ink-content :global(blockquote[style*='border-left: none']) {
1946
+ font-style: normal;
1947
+ color: inherit;
1948
+ background: none;
1949
+ border-radius: 0;
1950
+ }
1951
+
1150
1952
  .ink-content :global(pre) {
1151
1953
  background: var(--ink, #1a1714);
1152
1954
  color: #e8e2da;