-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
4413 lines (4388 loc) · 175 KB
/
Copy pathmain.js
File metadata and controls
4413 lines (4388 loc) · 175 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => RichEditorPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian10 = require("obsidian");
// src/commands/FormattingCommands.ts
function registerFormattingCommands(plugin) {
const marks = [
{ id: "style-suite-toggle-bold", name: "OW-Tools: Toggle bold", mark: "bold", icon: "bold" },
{ id: "style-suite-toggle-italic", name: "OW-Tools: Toggle italic", mark: "italic", icon: "italic" },
{ id: "style-suite-toggle-underline", name: "OW-Tools: Toggle underline", mark: "underline", icon: "underline" },
{
id: "style-suite-toggle-strikethrough",
name: "OW-Tools: Toggle strikethrough",
mark: "strikethrough",
icon: "strikethrough"
},
{ id: "style-suite-toggle-highlight", name: "OW-Tools: Toggle highlight", mark: "highlight", icon: "highlighter" }
];
marks.forEach(({ id, name, mark, icon }) => {
plugin.addCommand({
id,
name,
icon,
editorCallback: (editor) => plugin.formattingController.toggleMark(editor, mark)
});
});
plugin.addCommand({
id: "style-suite-toggle-bullet-list",
name: "OW-Tools: Toggle bullet list",
icon: "list",
editorCallback: (editor) => plugin.formattingController.toggleBulletList(editor)
});
plugin.addCommand({
id: "style-suite-toggle-numbered-list",
name: "OW-Tools: Toggle numbered list",
icon: "list-ordered",
editorCallback: (editor) => plugin.formattingController.toggleNumberedList(editor)
});
plugin.addCommand({
id: "style-suite-toggle-blockquote",
name: "OW-Tools: Toggle blockquote",
icon: "quote",
editorCallback: (editor) => plugin.formattingController.toggleBlockquote(editor)
});
plugin.addCommand({
id: "style-suite-heading-1",
name: "OW-Tools: Heading 1",
icon: "heading-1",
editorCallback: (editor) => plugin.formattingController.setHeading(editor, 1)
});
plugin.addCommand({
id: "style-suite-heading-2",
name: "OW-Tools: Heading 2",
icon: "heading-2",
editorCallback: (editor) => plugin.formattingController.setHeading(editor, 2)
});
plugin.addCommand({
id: "style-suite-heading-3",
name: "OW-Tools: Heading 3",
icon: "heading-3",
editorCallback: (editor) => plugin.formattingController.setHeading(editor, 3)
});
plugin.addCommand({
id: "style-suite-normal-text",
name: "OW-Tools: Normal text",
icon: "pilcrow",
editorCallback: (editor) => plugin.formattingController.setHeading(editor, 0)
});
plugin.addCommand({
id: "style-suite-color-passage",
name: "OW-Tools: Text and highlight color",
icon: "palette",
editorCallback: (editor) => plugin.openColorPicker(editor)
});
plugin.addCommand({
id: "style-suite-style-passage",
name: "OW-Tools: Passage font and size",
icon: "type",
editorCallback: (editor) => plugin.openPassageAppearance(editor)
});
plugin.addCommand({
id: "style-suite-clear-formatting",
name: "OW-Tools: Clear formatting",
icon: "eraser",
editorCallback: (editor) => plugin.formattingController.clearFormatting(editor)
});
plugin.addCommand({
id: "style-suite-open-document-appearance",
name: "OW-Tools: Document appearance",
icon: "sliders-horizontal",
callback: () => plugin.openAppearanceForActiveDocument()
});
plugin.addCommand({
id: "style-suite-choose-document-font",
name: "OW-Tools: Choose document font",
icon: "type",
callback: () => void plugin.chooseFontForActiveDocument()
});
plugin.addCommand({
id: "style-suite-clear-document-font",
name: "OW-Tools: Clear document font",
icon: "rotate-ccw",
callback: () => void plugin.clearFontForActiveDocument()
});
plugin.addCommand({
id: "style-suite-toggle-style-markup",
name: "OW-Tools: Show or hide generated style markup",
icon: "code-xml",
callback: () => void plugin.toggleInlineStyleMarkup()
});
plugin.addCommand({
id: "style-suite-clear-document-appearance",
name: "OW-Tools: Clear document appearance",
icon: "trash-2",
callback: () => void plugin.clearAppearanceForActiveDocument()
});
}
// src/editor/BidiGuard.ts
var DIRECTION_CONTROLS = /[\u200E\u200F]/g;
var RTL_STRONG_RE = /[\u0590-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;
var LTR_STRONG_RE = /[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AF\u0370-\u03FF\u0400-\u04FF]/;
var BLOCK_PREFIX_RE = /^(?:\s*#{1,6}\s+|\s*>\s?|\s*[-*+]\s+|\s*\d+[.)]\s+)*/;
function detectContentDirection(text) {
for (const character of visibleText(text)) {
if (RTL_STRONG_RE.test(character)) return "rtl";
if (LTR_STRONG_RE.test(character)) return "ltr";
}
return null;
}
function stripDirectionControls(text) {
return text.replace(DIRECTION_CONTROLS, "");
}
function stripLeadingDirectionControls(text) {
let index = 0;
while (index < text.length && isDirectionControl(text[index])) index += 1;
return index > 0 ? text.slice(index) : text;
}
function isDirectionControl(character) {
return character === "\u200E" || character === "\u200F";
}
function getLeadingDirectionControlStart(text, position) {
let start = Math.max(0, Math.min(position, text.length));
while (start > 0 && isDirectionControl(text[start - 1] ?? "")) start -= 1;
return start;
}
var GENERATED_DIRECTION_CONTROL_LINE_RE = /^((?:\s*#{1,6}\s+|\s*>\s?|\s*[-*+]\s+|\s*\d+[.)]\s+)*)[\u200E\u200F]+(?=<(?:span|mark|u)\b)/i;
function stripGeneratedDirectionControls(text) {
return text.split("\n").map((line) => line.replace(GENERATED_DIRECTION_CONTROL_LINE_RE, "$1")).join("\n");
}
function visibleText(text) {
return stripDirectionControls(text).replace(/<[^>]+>/g, "");
}
function getBlockPrefixLength(lineText) {
return BLOCK_PREFIX_RE.exec(lineText)?.[0].length ?? 0;
}
function clampSegmentToBlockContent(lineText, fromCh, toCh) {
const prefixLength = getBlockPrefixLength(lineText);
if (prefixLength <= 0 || prefixLength >= lineText.length) return { fromCh, toCh };
if (toCh <= prefixLength) return { fromCh: prefixLength, toCh: prefixLength };
return { fromCh: Math.max(fromCh, prefixLength), toCh };
}
// src/editor/RichEditorExtensions.ts
var import_state2 = require("@codemirror/state");
var import_view4 = require("@codemirror/view");
// src/editor/BidiLineDirection.ts
var import_view = require("@codemirror/view");
var RTL_LINE_CLASS = "rich-editor-rtl-line";
var BidiLineDirectionValue = class {
constructor(view) {
this.view = view;
this.decorations = this.buildDecorations();
}
decorations;
update(update) {
if (update.docChanged) {
this.decorations = this.buildDecorations();
}
}
buildDecorations() {
const lines = [];
for (let lineNumber = 1; lineNumber <= this.view.state.doc.lines; lineNumber += 1) {
const line = this.view.state.doc.line(lineNumber);
if (detectContentDirection(line.text) !== "rtl") continue;
lines.push(
import_view.Decoration.line({
class: RTL_LINE_CLASS,
attributes: { dir: "rtl" }
}).range(line.from)
);
}
return lines.length > 0 ? import_view.Decoration.set(lines, true) : import_view.Decoration.none;
}
};
function createBidiLineDirectionExtension() {
const plugin = import_view.ViewPlugin.define((view) => new BidiLineDirectionValue(view), {
decorations: (value) => value.decorations
});
return [import_view.EditorView.perLineTextDirection.of(true), plugin];
}
// src/editor/InlineStyleDecorations.ts
var import_view2 = require("@codemirror/view");
var import_state = require("@codemirror/state");
// src/editor/DocumentAppearance.ts
var DOCUMENT_FONT_KEY = "rich-editor-font";
var DOCUMENT_FONT_SIZE_KEY = "rich-editor-font-size";
var DOCUMENT_LINE_HEIGHT_KEY = "rich-editor-line-height";
var DOCUMENT_ALIGNMENT_KEY = "rich-editor-alignment";
var SAFE_CSS_VALUE_RE = /^[\p{L}\p{N}_\s.,'"()#%+-]+$/u;
var CSS_LENGTH_RE = /^(?:\d+(?:\.\d+)?)(?:px|pt|em|rem|%)$/;
var LINE_HEIGHT_RE = /^(?:\d+(?:\.\d+)?)(?:px|pt|em|rem|%)?$/;
function normalizeString(value) {
if (typeof value !== "string") return void 0;
const trimmed = value.trim();
return trimmed.length > 0 && SAFE_CSS_VALUE_RE.test(trimmed) ? trimmed : void 0;
}
function normalizeFontFamily(value) {
return normalizeString(value);
}
function normalizeFontSize(value) {
const normalized = normalizeString(value);
if (!normalized) return void 0;
return CSS_LENGTH_RE.test(normalized) ? normalized : void 0;
}
var CSS_COLOR_RE = /^(?:#(?:[\da-f]{3}|[\da-f]{6}|[\da-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\)|[a-z]+)$/i;
function normalizeColor(value) {
if (typeof value !== "string") return void 0;
const normalized = value.trim();
if (normalized.length === 0 || normalized.length > 50) return void 0;
return CSS_COLOR_RE.test(normalized) ? normalized.toLowerCase() : void 0;
}
function normalizeLineHeight(value) {
const normalized = normalizeString(value);
if (!normalized) return void 0;
return LINE_HEIGHT_RE.test(normalized) ? normalized : void 0;
}
function normalizeAlignment(value) {
const normalized = normalizeString(value)?.toLowerCase();
if (normalized === "left" || normalized === "center" || normalized === "right" || normalized === "justify") {
return normalized;
}
return void 0;
}
function readDocumentAppearanceFromFrontmatter(frontmatter) {
if (!frontmatter) return {};
return {
fontFamily: normalizeFontFamily(frontmatter[DOCUMENT_FONT_KEY]),
fontSize: normalizeFontSize(frontmatter[DOCUMENT_FONT_SIZE_KEY]),
lineHeight: normalizeLineHeight(frontmatter[DOCUMENT_LINE_HEIGHT_KEY]),
alignment: normalizeAlignment(frontmatter[DOCUMENT_ALIGNMENT_KEY])
};
}
function applyDocumentAppearanceToElement(element, appearance) {
element.classList.add("rich-editor-document-surface");
setCssVariable(element, "--rich-editor-font-family", appearance.fontFamily);
setCssVariable(element, "--rich-editor-font-size", appearance.fontSize);
setCssVariable(element, "--rich-editor-line-height", appearance.lineHeight);
setCssVariable(element, "--rich-editor-text-align", appearance.alignment);
}
function setCssVariable(element, name, value) {
if (value) {
element.setCssProps({ [name]: value });
} else {
element.style.removeProperty(name);
}
}
// src/editor/InlineTypography.ts
function normalizeInlineTypography(updates) {
return {
fontFamily: normalizeFontFamily(updates.fontFamily),
fontSize: normalizeFontSize(updates.fontSize),
textColor: normalizeColor(updates.textColor),
backgroundColor: normalizeColor(updates.backgroundColor)
};
}
function mergeInlineTypography(current, updates) {
const next = { ...current };
if (Object.prototype.hasOwnProperty.call(updates, "fontFamily")) {
next.fontFamily = normalizeFontFamily(updates.fontFamily) ?? void 0;
}
if (Object.prototype.hasOwnProperty.call(updates, "fontSize")) {
next.fontSize = normalizeFontSize(updates.fontSize) ?? void 0;
}
if (Object.prototype.hasOwnProperty.call(updates, "textColor")) {
next.textColor = normalizeColor(updates.textColor) ?? void 0;
}
if (Object.prototype.hasOwnProperty.call(updates, "backgroundColor")) {
next.backgroundColor = normalizeColor(updates.backgroundColor) ?? void 0;
}
return next;
}
function inlineTypographyToCss(typography) {
const normalized = normalizeInlineTypography(typography);
const declarations = [];
if (normalized.fontFamily) declarations.push(`font-family: ${normalized.fontFamily}`);
if (normalized.fontSize) declarations.push(`font-size: ${normalized.fontSize}`);
if (normalized.textColor) declarations.push(`color: ${normalized.textColor}`);
if (normalized.backgroundColor) declarations.push(`background-color: ${normalized.backgroundColor}`);
return declarations.join("; ");
}
function getInlineTypographyTagType(typography) {
const norm = normalizeInlineTypography(typography);
return norm.backgroundColor ? "mark" : "span";
}
function createInlineTypographyOpenTag(typography) {
const css = inlineTypographyToCss(typography);
if (!css) return "";
const tagType = getInlineTypographyTagType(typography);
return `<${tagType} style="${escapeHtmlAttribute(css)}">`;
}
function wrapInlineTypography(text, typography) {
if (!text) return { text, contentOffset: 0 };
const openTag = createInlineTypographyOpenTag(typography);
if (!openTag) return { text, contentOffset: 0 };
const tagType = getInlineTypographyTagType(typography);
return {
text: `${openTag}${text}</${tagType}>`,
contentOffset: openTag.length
};
}
function stripAllInlineTypographyTags(text) {
const regions = findAllInlineTypographyRegions(text);
let accumulated = {};
for (const r of regions) {
accumulated = mergeInlineTypography(accumulated, r.typography);
}
const cleanText = text.replace(/<mark\b[^>]*>/gi, "").replace(/<\/mark\s*>/gi, "").replace(/<span\b[^>]*>/gi, "").replace(/<\/span\s*>/gi, "");
return { cleanText, accumulatedTypography: accumulated };
}
function findInlineTypographyRegion(text, fromCh, toCh) {
let best = null;
for (const region of findAllInlineTypographyRegions(text)) {
if (fromCh < region.openEnd || toCh > region.close) continue;
if (!best || region.closeEnd - region.open < best.closeEnd - best.open) best = region;
}
return best;
}
function findEnclosingOrOverlappingRegion(text, fromCh, toCh) {
const regions = findAllInlineTypographyRegions(text);
if (regions.length === 0) return null;
if (regions.length === 1 && fromCh >= regions[0].openEnd && toCh <= regions[0].close) {
const r = regions[0];
return {
rangeFrom: r.open,
rangeTo: r.closeEnd,
openEnd: r.openEnd,
close: r.close,
typography: r.typography,
isFullEnclosure: true
};
}
const overlapping = regions.filter((r) => Math.max(fromCh, r.open) < Math.min(toCh, r.closeEnd));
if (overlapping.length > 0) {
const rangeFrom = Math.min(fromCh, ...overlapping.map((r) => r.open));
const rangeTo = Math.max(toCh, ...overlapping.map((r) => r.closeEnd));
let typography = {};
for (const r of overlapping) {
typography = mergeInlineTypography(typography, r.typography);
}
return {
rangeFrom,
rangeTo,
openEnd: rangeFrom,
close: rangeTo,
typography,
isFullEnclosure: false
};
}
return null;
}
function findAllInlineTypographyRegions(text) {
const tagPattern = /<(?:mark|span)\b[^>]*>|<\/(?:mark|span)\s*>/gi;
const stack = [];
const regions = [];
let match;
while ((match = tagPattern.exec(text)) !== null) {
const tag = match[0];
const isClosing = /^<\//.test(tag);
const tagType = (/^<\/?([a-z0-9]+)/i.exec(tag)?.[1] ?? "").toLowerCase();
if (!isClosing) {
stack.push({
tagType,
open: match.index,
openEnd: match.index + tag.length,
typography: parseInlineTypographyTag(tag)
});
continue;
}
let openingIndex = -1;
for (let i = stack.length - 1; i >= 0; i--) {
if (stack[i].tagType === tagType) {
openingIndex = i;
break;
}
}
if (openingIndex === -1) continue;
const [opening] = stack.splice(openingIndex, 1);
if (!opening?.typography) continue;
regions.push({
open: opening.open,
openEnd: opening.openEnd,
close: match.index,
closeEnd: match.index + tag.length,
typography: opening.typography
});
}
return regions.sort((a, b) => a.open - b.open);
}
function parseStyleDeclarations(style) {
const typography = {};
for (const declaration of style.split(";")) {
const separator = declaration.indexOf(":");
if (separator === -1) continue;
const property = declaration.slice(0, separator).trim().toLowerCase();
const value = declaration.slice(separator + 1).trim();
if (property === "font-family") typography.fontFamily = normalizeFontFamily(value);
if (property === "font-size") typography.fontSize = normalizeFontSize(value);
if (property === "color") typography.textColor = normalizeColor(value);
if (property === "background-color" || property === "background") typography.backgroundColor = normalizeColor(value);
}
return typography;
}
function parseInlineTypographyTag(tag) {
const style = readHtmlAttribute(tag, "style");
if (style !== null) {
const parsed = parseStyleDeclarations(decodeHtmlAttribute(style));
if (parsed.fontFamily || parsed.fontSize || parsed.textColor || parsed.backgroundColor) {
return parsed;
}
}
const typography = {};
const textColor = readHtmlAttribute(tag, "c");
if (textColor !== null) typography.textColor = normalizeColor(decodeHtmlAttribute(textColor));
const backgroundColor = readHtmlAttribute(tag, "b");
if (backgroundColor !== null) typography.backgroundColor = normalizeColor(decodeHtmlAttribute(backgroundColor));
const fontFamily = readHtmlAttribute(tag, "f");
if (fontFamily !== null) typography.fontFamily = normalizeFontFamily(decodeHtmlAttribute(fontFamily));
const fontSize = readHtmlAttribute(tag, "s");
if (fontSize !== null) typography.fontSize = normalizeFontSize(decodeHtmlAttribute(fontSize));
if (/^<mark\b/i.test(tag) && !tag.includes("=")) {
typography.backgroundColor = "#fef08a";
}
return typography.fontFamily || typography.fontSize || typography.textColor || typography.backgroundColor ? typography : null;
}
function readHtmlAttribute(tag, name) {
const match = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, "i").exec(tag);
if (!match) return null;
return match[1] ?? match[2] ?? "";
}
function escapeHtmlAttribute(value) {
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
}
function decodeHtmlAttribute(value) {
return value.replace(/"/gi, '"').replace(/</gi, "<").replace(/>/gi, ">").replace(/&/gi, "&");
}
// src/editor/InlineStyleDecorations.ts
var INLINE_STYLE_VISIBILITY_EVENT = "rich-editor-inline-style-visibility";
var HIDDEN_INLINE_MARKUP_PATTERN = /<\/?(?:b|strong|i|em|u|s|strike|del)\b[^>]*>/gi;
var SEMANTIC_MARKUP_PATTERN = /<\/?(b|strong|i|em|u|s|strike|del)\b[^>]*>/gi;
var SEMANTIC_FORMAT_BY_TAG = {
b: "bold",
strong: "bold",
i: "italic",
em: "italic",
u: "underline",
s: "strikethrough",
strike: "strikethrough",
del: "strikethrough"
};
var SEMANTIC_TAG_BY_FORMAT = {
bold: "strong",
italic: "em",
underline: "u",
strikethrough: "s"
};
var InlineStyleDecorationValue = class {
constructor(view, deps) {
this.view = view;
this.deps = deps;
this.decorations = this.buildDecorations();
this.ownerWindow.addEventListener(INLINE_STYLE_VISIBILITY_EVENT, this.handleVisibilityChange);
this.scheduleLegacyDirectionCleanup();
}
decorations;
destroyed = false;
legacyCleanupScheduled = false;
update(update) {
if (update.docChanged || update.viewportChanged) {
this.decorations = this.buildDecorations();
if (update.docChanged) {
const boundaries = computeTagBoundariesFromDoc(update.state.doc);
const emptyTags = boundaries.filter((b) => b.openEnd === b.close);
if (emptyTags.length > 0) {
void Promise.resolve().then(() => {
const currentBoundaries = computeTagBoundariesFromDoc(this.view.state.doc);
const currentEmpty = currentBoundaries.filter((b) => b.openEnd === b.close);
if (currentEmpty.length > 0) {
const changes = currentEmpty.map((b) => ({ from: b.open, to: b.closeEnd }));
this.view.dispatch({ changes, userEvent: "delete.emptyTag" });
}
}).catch(() => void 0);
}
}
}
}
destroy() {
this.destroyed = true;
this.ownerWindow.removeEventListener(INLINE_STYLE_VISIBILITY_EVENT, this.handleVisibilityChange);
}
/**
* One-time migration for notes written by the old source-anchor engine.
* New formatting never creates these controls, and this deliberately does
* not run as a document normalizer on every transaction.
*/
scheduleLegacyDirectionCleanup() {
if (this.legacyCleanupScheduled) return;
this.legacyCleanupScheduled = true;
void Promise.resolve().then(() => {
if (this.destroyed) return;
const changes = [];
for (let lineNumber = 1; lineNumber <= this.view.state.doc.lines; lineNumber += 1) {
const line = this.view.state.doc.line(lineNumber);
const cleaned = stripGeneratedDirectionControls(line.text);
if (cleaned !== line.text) {
changes.push({ from: line.from, to: line.to, insert: cleaned });
}
}
if (changes.length > 0) {
this.view.dispatch({ changes, userEvent: "input" });
}
}).catch(() => void 0);
}
get ownerWindow() {
return this.view.dom.ownerDocument.defaultView ?? window;
}
handleVisibilityChange = () => {
this.decorations = this.buildDecorations();
this.view.dispatch({});
};
buildDecorations() {
const ranges = [];
const hideMarkup = this.deps.isMarkupHidden();
for (let lineNumber = 1; lineNumber <= this.view.state.doc.lines; lineNumber += 1) {
const line = this.view.state.doc.line(lineNumber);
for (const region of findAllInlineTypographyRegions(line.text)) {
const openEnd = line.from + region.openEnd;
const close = line.from + region.close;
const isHighlight = Boolean(region.typography.backgroundColor);
const markClass = isHighlight ? "rich-editor-inline-styled-text rich-editor-inline-highlight" : "rich-editor-inline-styled-text";
if (openEnd < close) {
let css = inlineTypographyToEditorCss(region.typography);
if (isHighlight) {
css += "; vertical-align: baseline !important; line-height: inherit !important; border-radius: var(--rich-editor-highlight-radius, 6px); padding: 0.12em 0.42em; margin: 0 0.08em;";
}
ranges.push(
import_view2.Decoration.mark({
class: markClass,
attributes: { style: css }
}).range(openEnd, close)
);
}
}
for (const mark of findSemanticMarkRanges(line.text)) {
const from = line.from + mark.openEnd;
const to = line.from + mark.close;
if (from >= to) continue;
ranges.push(
import_view2.Decoration.mark({
class: `rich-editor-inline-format rich-editor-inline-${mark.format}`,
tagName: SEMANTIC_TAG_BY_FORMAT[mark.format]
}).range(from, to)
);
}
}
if (hideMarkup) {
for (const hidden of computeHiddenMarkupRangesFromDoc(this.view.state.doc)) {
ranges.push(import_view2.Decoration.replace({ inclusive: false }).range(hidden.from, hidden.to));
}
}
ranges.sort((a, b) => a.from - b.from || a.to - b.to);
return import_view2.Decoration.set(ranges, true);
}
};
function inlineTypographyToEditorCss(typography) {
return inlineTypographyToCss(typography).split(";").map((declaration) => declaration.trim()).filter(Boolean).map((declaration) => `${declaration.replace(/\s*!important\s*$/i, "")} !important`).join("; ");
}
function findSemanticMarkRanges(text) {
const stack = [];
const ranges = [];
SEMANTIC_MARKUP_PATTERN.lastIndex = 0;
let match;
while ((match = SEMANTIC_MARKUP_PATTERN.exec(text)) !== null) {
const tagText = match[0];
const tag = match[1].toLowerCase();
const format = SEMANTIC_FORMAT_BY_TAG[tag];
if (!format) continue;
if (!tagText.startsWith("</")) {
stack.push({ tag, format, open: match.index, openEnd: match.index + tagText.length });
continue;
}
let openingIndex = -1;
for (let index = stack.length - 1; index >= 0; index -= 1) {
if (stack[index].tag === tag) {
openingIndex = index;
break;
}
}
if (openingIndex === -1) continue;
const [opening] = stack.splice(openingIndex, 1);
if (!opening) continue;
ranges.push({
open: opening.open,
openEnd: opening.openEnd,
close: match.index,
closeEnd: match.index + tagText.length,
format: opening.format
});
}
return ranges;
}
function computeHiddenMarkupRangesFromDoc(doc) {
const ranges = [];
for (let lineNumber = 1; lineNumber <= doc.lines; lineNumber += 1) {
const line = doc.line(lineNumber);
for (const region of findAllInlineTypographyRegions(line.text)) {
ranges.push({ from: line.from + region.open, to: line.from + region.openEnd });
ranges.push({ from: line.from + region.close, to: line.from + region.closeEnd });
}
HIDDEN_INLINE_MARKUP_PATTERN.lastIndex = 0;
let match;
while ((match = HIDDEN_INLINE_MARKUP_PATTERN.exec(line.text)) !== null) {
ranges.push({ from: line.from + match.index, to: line.from + match.index + match[0].length });
}
}
const seen = /* @__PURE__ */ new Set();
const uniqueRanges = ranges.filter((range) => {
const key = `${range.from}:${range.to}`;
if (seen.has(key)) return false;
seen.add(key);
return range.from < range.to;
}).sort((a, b) => a.from - b.from || a.to - b.to);
const mergedRanges = [];
for (const range of uniqueRanges) {
const previous = mergedRanges[mergedRanges.length - 1];
if (previous && range.from <= previous.to) {
previous.to = Math.max(previous.to, range.to);
} else {
mergedRanges.push({ ...range });
}
}
return mergedRanges;
}
function selectionOutsideHiddenMarkup(selection, ranges) {
let changed = false;
const snap = (position) => {
for (const range of ranges) {
if (position <= range.from || position >= range.to) continue;
changed = true;
return position - range.from <= range.to - position ? range.from : range.to;
}
return position;
};
const nextRanges = selection.ranges.map(
(range) => import_state.EditorSelection.range(snap(range.anchor), snap(range.head))
);
return changed ? import_state.EditorSelection.create(nextRanges, selection.mainIndex) : null;
}
function computeTagBoundariesFromDoc(doc) {
const boundaries = [];
for (let lineNumber = 1; lineNumber <= doc.lines; lineNumber++) {
const line = doc.line(lineNumber);
for (const region of findAllInlineTypographyRegions(line.text)) {
boundaries.push({
open: line.from + region.open,
openEnd: line.from + region.openEnd,
close: line.from + region.close,
closeEnd: line.from + region.closeEnd
});
}
}
return boundaries;
}
function createInlineStyleDecorationExtension(deps) {
const selectionGuard = import_state.EditorState.transactionFilter.of((tr) => {
const ranges = deps.isMarkupHidden() ? computeHiddenMarkupRangesFromDoc(tr.newDoc) : [];
const selection = selectionOutsideHiddenMarkup(
tr.newSelection,
ranges
);
return selection ? [tr, { selection }] : tr;
});
const safeDeletionFilter = import_state.EditorState.transactionFilter.of((tr) => {
if (!deps.isMarkupHidden() || !tr.docChanged || !tr.isUserEvent("delete")) return tr;
const boundaries = computeTagBoundariesFromDoc(tr.startState.doc);
if (boundaries.length === 0) return tr;
let needsRemap = false;
const remappedChanges = [];
tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
let handled = false;
for (const tag of boundaries) {
if (fromA <= tag.openEnd && toA >= tag.close) {
needsRemap = true;
handled = true;
remappedChanges.push({ from: tag.open, to: tag.closeEnd, insert: inserted.toString() });
break;
}
if (fromA >= tag.open && toA === tag.openEnd && inserted.length === 0) {
needsRemap = true;
handled = true;
if (tag.open > 0) {
remappedChanges.push({ from: tag.open - 1, to: tag.open, insert: "" });
}
break;
}
if (fromA === tag.close && toA <= tag.closeEnd && inserted.length === 0) {
needsRemap = true;
handled = true;
if (tag.closeEnd < tr.startState.doc.length) {
remappedChanges.push({ from: tag.closeEnd, to: tag.closeEnd + 1, insert: "" });
}
break;
}
if (fromA < tag.openEnd && toA > tag.open && fromA >= tag.open && toA <= tag.openEnd) {
needsRemap = true;
handled = true;
break;
}
if (fromA < tag.closeEnd && toA > tag.close && fromA >= tag.close && toA <= tag.closeEnd) {
needsRemap = true;
handled = true;
break;
}
}
if (!handled) {
remappedChanges.push({ from: fromA, to: toA, insert: inserted.toString() });
}
});
if (!needsRemap) return tr;
return {
changes: remappedChanges,
selection: tr.selection,
scrollIntoView: true
};
});
const handleBackspace = (view) => {
if (!deps.isMarkupHidden()) return false;
const state = view.state;
const sel = state.selection.main;
if (!sel.empty) return false;
const pos = sel.head;
const boundaries = computeTagBoundariesFromDoc(state.doc);
if (boundaries.length === 0) return false;
for (const tag of boundaries) {
if (pos === tag.openEnd) {
if (tag.open > 0) {
view.dispatch({
changes: { from: tag.open - 1, to: tag.open },
selection: import_state.EditorSelection.cursor(tag.openEnd - 1),
scrollIntoView: true,
userEvent: "delete.backward"
});
return true;
}
return false;
}
if (pos === tag.open) {
if (tag.open > 0) {
view.dispatch({
changes: { from: tag.open - 1, to: tag.open },
selection: import_state.EditorSelection.cursor(tag.open - 1),
scrollIntoView: true,
userEvent: "delete.backward"
});
return true;
}
return false;
}
if (pos === tag.closeEnd) {
if (tag.close > tag.openEnd) {
if (tag.close === tag.openEnd + 1) {
view.dispatch({
changes: { from: tag.open, to: tag.closeEnd },
selection: import_state.EditorSelection.cursor(tag.open),
scrollIntoView: true,
userEvent: "delete.backward"
});
return true;
}
view.dispatch({
changes: { from: tag.close - 1, to: tag.close },
selection: import_state.EditorSelection.cursor(tag.closeEnd - 1),
scrollIntoView: true,
userEvent: "delete.backward"
});
return true;
}
}
if (pos === tag.openEnd + 1 && tag.close === tag.openEnd + 1) {
view.dispatch({
changes: { from: tag.open, to: tag.closeEnd },
selection: import_state.EditorSelection.cursor(tag.open),
scrollIntoView: true,
userEvent: "delete.backward"
});
return true;
}
}
return false;
};
const handleDelete = (view) => {
if (!deps.isMarkupHidden()) return false;
const state = view.state;
const sel = state.selection.main;
if (!sel.empty) return false;
const pos = sel.head;
const boundaries = computeTagBoundariesFromDoc(state.doc);
if (boundaries.length === 0) return false;
for (const tag of boundaries) {
if (pos === tag.close) {
if (tag.closeEnd < state.doc.length) {
view.dispatch({
changes: { from: tag.closeEnd, to: tag.closeEnd + 1 },
selection: import_state.EditorSelection.cursor(tag.close),
scrollIntoView: true,
userEvent: "delete.forward"
});
return true;
}
return false;
}
if (pos === tag.closeEnd) {
if (tag.closeEnd < state.doc.length) {
view.dispatch({
changes: { from: tag.closeEnd, to: tag.closeEnd + 1 },
selection: import_state.EditorSelection.cursor(tag.closeEnd),
scrollIntoView: true,
userEvent: "delete.forward"
});
return true;
}
return true;
}
if (pos === tag.open) {
if (tag.openEnd < tag.close) {
if (tag.openEnd + 1 === tag.close) {
view.dispatch({
changes: { from: tag.open, to: tag.closeEnd },
selection: import_state.EditorSelection.cursor(tag.open),
scrollIntoView: true,
userEvent: "delete.forward"
});
return true;
}
view.dispatch({
changes: { from: tag.openEnd, to: tag.openEnd + 1 },
selection: import_state.EditorSelection.cursor(tag.open),
scrollIntoView: true,
userEvent: "delete.forward"
});
return true;
}
}
}
return false;
};
const richEditorKeymap = import_state.Prec.highest(
import_view2.keymap.of([
{ key: "Backspace", run: handleBackspace },
{ key: "Delete", run: handleDelete }
])
);
const plugin = import_view2.ViewPlugin.define((view) => new InlineStyleDecorationValue(view, deps), {
decorations: (value) => value.decorations
});
const atomicRangesExtension = import_view2.EditorView.atomicRanges.of((view) => {
const ranges = (deps.isMarkupHidden() ? computeHiddenMarkupRangesFromDoc(view.state.doc) : []).map(
(range) => import_view2.Decoration.replace({ inclusive: false }).range(range.from, range.to)
);
return ranges.length > 0 ? import_view2.Decoration.set(ranges, true) : import_view2.Decoration.none;
});
return [
richEditorKeymap,
import_state.Prec.highest(selectionGuard),
import_state.Prec.highest(safeDeletionFilter),
atomicRangesExtension,
plugin
];
}
// src/ui/toolbar/SelectionToolbar.ts
var import_obsidian = require("obsidian");
var import_view3 = require("@codemirror/view");
var SelectionToolbarValue = class {
constructor(view, deps) {
this.view = view;
this.deps = deps;
this.toolbarEl = this.buildToolbar();
}
toolbarEl;
scheduled = false;
activeFormats = null;
update(update) {
if (update.selectionSet || update.docChanged || update.geometryChanged || update.focusChanged) {
this.schedulePosition();
}
}
destroy() {
this.toolbarEl.remove();
}
schedulePosition() {
if (this.scheduled) return;
this.scheduled = true;
this.ownerWindow.requestAnimationFrame(() => {
this.scheduled = false;
this.position();
});
}
position() {
const selection = this.view.state.selection.main;
if (!this.deps.isEnabled() || selectionShouldHide(selection.empty, this.view.hasFocus, this.toolbarEl)) {
this.hide();
return;
}
const head = this.view.coordsAtPos(selection.from);
if (!head) {
this.hide();
return;
}
const editorRect = this.view.dom.getBoundingClientRect();
this.toolbarEl.addClass("is-visible");
const toolbarRect = this.toolbarEl.getBoundingClientRect();
let left = head.left - editorRect.left;
let top = head.top - editorRect.top - toolbarRect.height - 8;
left = Math.max(8, Math.min(left, editorRect.width - toolbarRect.width - 8));
if (top < 4) top = head.bottom - editorRect.top + 8;
this.toolbarEl.setCssProps({
left: `${left}px`,
top: `${top}px`
});
this.updateActiveStates();
}
hide() {
this.toolbarEl.removeClass("is-visible");
}
buildToolbar() {
const toolbar = this.view.dom.createDiv({ cls: "rich-editor-selection-toolbar" });
toolbar.addEventListener("mousedown", (event) => {
event.preventDefault();
});
this.addIconButton(toolbar, "bold", "Bold (Ctrl/Cmd+B)", () => this.mark("bold"), "bold");
this.addIconButton(toolbar, "italic", "Italic (Ctrl/Cmd+I)", () => this.mark("italic"), "italic");
this.addIconButton(toolbar, "underline", "Underline (Ctrl/Cmd+U)", () => this.mark("underline"), "underline");
this.addIconButton(toolbar, "strikethrough", "Strikethrough", () => this.mark("strikethrough"), "strikethrough");
this.divider(toolbar);
this.addIconButton(toolbar, "heading", "Heading", (event) => this.openHeadingMenu(event));
this.addIconButton(toolbar, "list", "Bullet list", () => this.withEditor((editor) => this.deps.controller.toggleBulletList(editor)));
this.addIconButton(toolbar, "list-ordered", "Numbered list", () => this.withEditor((editor) => this.deps.controller.toggleNumberedList(editor)));
this.addIconButton(toolbar, "quote", "Blockquote", () => this.withEditor((editor) => this.deps.controller.toggleBlockquote(editor)));
this.divider(toolbar);
this.addIconButton(toolbar, "eraser", "Clear formatting", () => this.withEditor((editor) => this.deps.controller.clearFormatting(editor)));
return toolbar;
}
get ownerWindow() {
return this.view.dom.ownerDocument.defaultView ?? window;
}
addIconButton(parent, icon, label, onClick, stateId) {
const button = parent.createEl("button", {
cls: "rich-editor-selection-btn clickable-icon",
attr: { "aria-label": label, ...stateId ? { "data-state-id": stateId } : {} }
});
(0, import_obsidian.setIcon)(button, icon);