-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.js
More file actions
1407 lines (1402 loc) · 62.8 KB
/
main.js
File metadata and controls
1407 lines (1402 loc) · 62.8 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
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);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => AnnotationPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");
var import_view = require("@codemirror/view");
var import_state = require("@codemirror/state");
// annotation-normalization.ts
var COMMENT_REGEX = /<span class="ob-comment(?:\s+([\w-]+))?" data-note="([\s\S]*?)">([\s\S]*?)<\/span>/g;
function buildAnnotationClass(color) {
return color ? "ob-comment " + color : "ob-comment";
}
function escapeDataNote(note) {
return note.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "'").replace(/`/g, "`").replace(/\|/g, "|").replace(/\r?\n/g, " ");
}
function decodeDataNote(note) {
return note.replace(/ /g, "\n").replace(/ /g, "\r").replace(/`/g, "`").replace(/'/g, "'").replace(/"/g, '"').replace(/>/g, ">").replace(/</g, "<").replace(/|/g, "|").replace(/&/g, "&");
}
function normalizeAnnotationsInText(text) {
const { text: normalizedText, changed } = normalizeTextWithCursor(text, text.length);
return { text: normalizedText, changed };
}
function findAnnotationRangeAtOffset(text, offset) {
COMMENT_REGEX.lastIndex = 0;
let match;
while ((match = COMMENT_REGEX.exec(text)) !== null) {
const start = match.index;
const end = start + match[0].length;
if (offset >= start && offset <= end) {
return { from: start, to: end };
}
}
return null;
}
function getAutoNormalizeAction(args) {
if (!args.selectionEmpty) return "cancel";
if (args.currentRange) return "cancel";
const exitedAnnotation = args.selectionSet && args.previousRange !== null;
if (exitedAnnotation) return "schedule";
const keepWaitingOutside = args.hasPendingTimer && (args.selectionSet || args.docChanged);
if (keepWaitingOutside) return "schedule";
return "noop";
}
function normalizeCursorInsideRawNote(rawNote, relativeOffset) {
const prefix = rawNote.slice(0, relativeOffset);
return escapeDataNote(decodeDataNote(prefix)).length;
}
function normalizeTextWithCursor(text, cursorOffset) {
COMMENT_REGEX.lastIndex = 0;
let result = "";
let lastIndex = 0;
let changed = false;
let nextCursorOffset = cursorOffset;
let match;
while ((match = COMMENT_REGEX.exec(text)) !== null) {
const fullMatch = match[0];
const colorClass = match[1] || "";
const rawNote = match[2];
const visibleText = match[3];
const safeNote = escapeDataNote(decodeDataNote(rawNote));
const replacement = `<span class="${buildAnnotationClass(colorClass)}" data-note="${safeNote}">${visibleText}</span>`;
const matchStart = match.index;
const matchEnd = matchStart + fullMatch.length;
const delta = replacement.length - fullMatch.length;
if (cursorOffset > matchEnd) {
nextCursorOffset += delta;
} else if (cursorOffset >= matchStart && cursorOffset <= matchEnd) {
const openingPrefix = fullMatch.indexOf('data-note="') + 'data-note="'.length;
const noteStart = openingPrefix;
const noteEnd = noteStart + rawNote.length;
const relativeOffset = cursorOffset - matchStart;
if (relativeOffset > noteStart && relativeOffset <= noteEnd) {
const noteRelativeOffset = relativeOffset - noteStart;
nextCursorOffset = matchStart + openingPrefix + normalizeCursorInsideRawNote(rawNote, noteRelativeOffset);
} else if (relativeOffset > noteEnd) {
nextCursorOffset += delta;
}
}
result += text.slice(lastIndex, matchStart) + replacement;
lastIndex = matchStart + fullMatch.length;
if (replacement !== fullMatch) changed = true;
}
result += text.slice(lastIndex);
return {
text: changed ? result : text,
changed,
cursorOffset: changed ? nextCursorOffset : cursorOffset
};
}
// modal-shortcuts.ts
var VALID_SHORTCUTS = ["", "enter", "shift-enter", "ctrl-enter"];
var DEFAULT_NEWLINE_SHORTCUT = "enter";
var DEFAULT_SUBMIT_SHORTCUT = "";
function isValidShortcut(value) {
return typeof value === "string" && VALID_SHORTCUTS.includes(value);
}
function normalizeShortcutSettings(input) {
const originalSubmit = input.submitShortcut;
const originalNewline = input.newlineShortcut;
const submitShortcut = isValidShortcut(originalSubmit) ? originalSubmit : DEFAULT_SUBMIT_SHORTCUT;
let newlineShortcut = isValidShortcut(originalNewline) && originalNewline !== "" ? originalNewline : DEFAULT_NEWLINE_SHORTCUT;
let nextSubmit = submitShortcut;
if (nextSubmit !== "" && nextSubmit === newlineShortcut) {
nextSubmit = DEFAULT_SUBMIT_SHORTCUT;
}
if (newlineShortcut === "") {
newlineShortcut = DEFAULT_NEWLINE_SHORTCUT;
}
return {
submitShortcut: nextSubmit,
newlineShortcut,
changed: nextSubmit !== originalSubmit || newlineShortcut !== originalNewline
};
}
function getShortcutLabel(t, shortcut) {
switch (shortcut) {
case "enter":
return t("modalShortcutEnter");
case "shift-enter":
return t("modalShortcutShiftEnter");
case "ctrl-enter":
return t("modalShortcutCtrlEnter");
default:
return t("modalShortcutNone");
}
}
function formatModalKeyHint(t, submitShortcut, newlineShortcut) {
const parts = [];
if (submitShortcut) {
parts.push(`${t("modalHintSubmitPrefix")}${getShortcutLabel(t, submitShortcut)}`);
}
parts.push(`${t("modalHintNewlinePrefix")}${getShortcutLabel(t, newlineShortcut)}`);
return parts.join(t("modalHintSeparator"));
}
function isShortcutEvent(evt, shortcut) {
if (!shortcut || evt.key !== "Enter" || evt.altKey) return false;
const shiftKey = !!evt.shiftKey;
const ctrlLike = !!evt.ctrlKey || !!evt.metaKey;
switch (shortcut) {
case "enter":
return !shiftKey && !ctrlLike;
case "shift-enter":
return shiftKey && !ctrlLike;
case "ctrl-enter":
return !shiftKey && ctrlLike;
default:
return false;
}
}
// main.ts
var COMMENT_REGEX2 = /<span class="ob-comment(?:\s+([\w-]+))?" data-note="([\s\S]*?)">([\s\S]*?)<\/span>/g;
var DEFAULT_COLOR = "";
var AUTO_NORMALIZE_IDLE_MS = 1e3;
var STRINGS = {
en: {
settingLanguageName: "Language",
settingLanguageDesc: "Choose plugin UI language (default: English).",
settingLanguageEn: "English",
settingLanguageZh: "Simplified Chinese",
colorRed: "Red",
colorDefault: "Orange (default)",
colorYellow: "Yellow",
colorGreen: "Green",
colorCyan: "Cyan",
colorBlue: "Blue",
colorPurple: "Purple",
colorGray: "Gray",
cmdAddDefault: "Add Annotation (Default)",
cmdAddWithColor: (color) => `Add Annotation (${color})`,
cmdToggleVisibility: "Show/Hide Annotation Styles",
cmdEditCurrent: "Edit Current Annotation",
cmdDeleteCurrent: "Delete Current Annotation",
cmdNormalizeCurrent: "Fix Current File Annotation data-note",
cmdNormalizeVault: "Fix All Markdown Annotation data-note",
noticeHidden: "Annotation styles are now hidden",
noticeShown: "Annotation styles are now visible",
noticeNoAnnotation: "No annotation at cursor",
noticeNeedSelection: "Please select some text first",
noticeNoNested: "Nested annotations are not supported; remove the old one first",
noticeNoFixNeeded: "No annotations need fixing",
noticeFixedCurrent: "Annotations in this file are now safe-formatted",
noticeScanStart: "Scanning vault, please wait...",
noticeFixedVault: (count) => `Successfully fixed annotations in ${count} Markdown file(s)`,
noticeNeedSelectionAdd: "Please select text to add a new annotation",
noticeCopied: "Annotations copied to clipboard!",
noticeOpenDoc: "Please open a Markdown document first",
noticeShortcutConflict: "Submit shortcut can't match newline shortcut. Submit shortcut has been reset to None.",
ctxAdd: "Add Annotation",
ctxEdit: "Edit Annotation",
ctxChangeColor: " - Change Color",
ctxDelete: "Delete Annotation",
modalTitleEdit: "Edit Annotation",
modalTitleNew: "Enter Annotation Content",
modalColorLabel: "Annotation Color",
modalCancel: "Cancel",
modalConfirm: "Confirm",
modalColorCurrent: "Current color: ",
modalShortcutNone: "None",
modalShortcutEnter: "Enter",
modalShortcutShiftEnter: "Shift+Enter",
modalShortcutCtrlEnter: "Ctrl+Enter",
modalHintSubmitPrefix: "Submit: ",
modalHintNewlinePrefix: "Newline: ",
modalHintSeparator: "; ",
batchTitle: "\u26A0\uFE0F Batch fix confirmation",
batchSummary: (count) => `Found ${count} file(s) with legacy or unsafe annotations.`,
batchWarning: "Fixing will update HTML (data-note escaping). Please back up your vault first.",
batchConfirm: (count) => `Confirm fix (${count} files)`,
batchCancel: "Cancel",
settingsGeneral: "General settings",
settingsAppearance: "Appearance",
settingsInteraction: "Interaction",
settingsAdvanced: "Advanced & maintenance",
settingDefaultColorName: "Default annotation color",
settingDefaultColorDesc: "Initial color when creating a new annotation.",
settingHideDefaultName: "Hide annotations by default",
settingHideDefaultDesc: "On app launch, hide all annotation styling for a clean reading mode.",
settingUnderlineName: "Show underline",
settingUnderlineDesc: "Add a colored underline to annotated text.",
settingBackgroundName: "Show background highlight",
settingBackgroundDesc: "Add a translucent background highlight to annotated text.",
settingIconName: "Show end icon",
settingIconDesc: 'Append a small "\u{1F4DD}" icon (pseudo-element) to annotated text.',
settingIconTriggerName: "End icon trigger",
settingIconTriggerDesc: "Only in icon-only mode: show tooltip on hover, or require click first.",
settingIconHover: "Hover to show",
settingIconClick: "Click to show",
settingLightOpacityName: "Light theme opacity",
settingLightOpacityDesc: "Adjust highlight depth for light themes (0% - 100%).",
settingDarkOpacityName: "Dark theme opacity",
settingDarkOpacityDesc: "Adjust highlight depth for dark themes (0% - 100%).",
settingTooltipWidthName: "Tooltip max width",
settingTooltipWidthDesc: "Limit tooltip width (px).",
settingSubmitShortcutName: "Submit shortcut",
settingSubmitShortcutDesc: "Keyboard shortcut to submit the annotation modal. None means confirm by button only.",
settingNewlineShortcutName: "Newline shortcut",
settingNewlineShortcutDesc: "Keyboard shortcut to insert a newline inside the annotation modal.",
settingAutoNormalizeAfterExitName: "Auto-normalize after leaving annotation source",
settingAutoNormalizeAfterExitDesc: "About 1 second after the cursor leaves annotation source, convert unsafe raw newlines inside annotation data-note values to .",
settingFontAdjustName: "Adjust font size",
settingFontAdjustDescPrefix: "Adjust annotation font by steps (max \xB13). Current: ",
settingFontStepDefault: "Default",
settingFontStep: (step) => `${step > 0 ? "+" : ""}${step} step`,
settingFontStepPlural: (step) => `${step > 0 ? "+" : ""}${step} steps`,
settingFontSmaller: "Smaller",
settingFontLarger: "Larger",
settingMarkdownName: "Enable Markdown rendering",
settingMarkdownDesc: "Render annotation content as Markdown. Off = show plain text.",
settingFixDataName: "One-click repair",
settingFixDataDesc: "Scan all files and fix legacy annotation format issues.",
settingFixDataButton: "Start scan & fix",
settingExportName: "Export annotations (current file)",
settingExportDesc: "Extract all annotations from the current document to clipboard.",
settingExportButton: "Copy to clipboard",
exportHeading: "## Annotations Export\n\n",
exportOriginal: "Original",
exportAnnotation: "Annotation",
menuAddTitle: "Add Annotation"
},
zh: {
settingLanguageName: "\u8BED\u8A00",
settingLanguageDesc: "\u9009\u62E9\u63D2\u4EF6\u754C\u9762\u8BED\u8A00\uFF08\u9ED8\u8BA4\uFF1A\u82F1\u6587\uFF09\u3002",
settingLanguageEn: "\u82F1\u8BED",
settingLanguageZh: "\u7B80\u4F53\u4E2D\u6587",
colorRed: "\u7EA2\u8272",
colorDefault: "\u6A59\u8272\uFF08\u9ED8\u8BA4\uFF09",
colorYellow: "\u9EC4\u8272",
colorGreen: "\u7EFF\u8272",
colorCyan: "\u9752\u8272",
colorBlue: "\u84DD\u8272",
colorPurple: "\u7D2B\u8272",
colorGray: "\u7070\u8272",
cmdAddDefault: "\u6DFB\u52A0\u6279\u6CE8\uFF08\u9ED8\u8BA4\uFF09",
cmdAddWithColor: (color) => `\u6DFB\u52A0\u6279\u6CE8\uFF08${color}\uFF09`,
cmdToggleVisibility: "\u663E\u793A/\u9690\u85CF\u6279\u6CE8\u6837\u5F0F",
cmdEditCurrent: "\u7F16\u8F91\u5F53\u524D\u6279\u6CE8",
cmdDeleteCurrent: "\u5220\u9664\u5F53\u524D\u6279\u6CE8",
cmdNormalizeCurrent: "\u4FEE\u590D\u5F53\u524D\u6587\u4EF6\u7684\u6279\u6CE8 data-note",
cmdNormalizeVault: "\u4FEE\u590D\u6240\u6709 Markdown \u6587\u4EF6\u7684\u6279\u6CE8 data-note",
noticeHidden: "\u6279\u6CE8\u6837\u5F0F\u5DF2\u9690\u85CF",
noticeShown: "\u6279\u6CE8\u6837\u5F0F\u5DF2\u663E\u793A",
noticeNoAnnotation: "\u5149\u6807\u5904\u6CA1\u6709\u6279\u6CE8",
noticeNeedSelection: "\u8BF7\u5148\u9009\u62E9\u4E00\u6BB5\u6587\u672C",
noticeNoNested: "\u4E0D\u652F\u6301\u5728\u5DF2\u6709\u6279\u6CE8\u4E0A\u5D4C\u5957\u6279\u6CE8\uFF0C\u8BF7\u5148\u5220\u9664\u65E7\u6279\u6CE8",
noticeNoFixNeeded: "\u672A\u53D1\u73B0\u9700\u8981\u4FEE\u590D\u7684\u6279\u6CE8",
noticeFixedCurrent: "\u5F53\u524D\u6587\u4EF6\u7684\u6279\u6CE8\u5DF2\u8F6C\u6362\u4E3A\u5B89\u5168\u683C\u5F0F",
noticeScanStart: "\u5F00\u59CB\u626B\u63CF\u5E93\u6587\u4EF6\uFF0C\u8BF7\u7A0D\u5019...",
noticeFixedVault: (count) => `\u5DF2\u6210\u529F\u4FEE\u590D ${count} \u4E2A Markdown \u6587\u4EF6\u7684\u6279\u6CE8`,
noticeNeedSelectionAdd: "\u8BF7\u5148\u9009\u62E9\u6587\u672C\u4EE5\u6DFB\u52A0\u65B0\u6279\u6CE8",
noticeCopied: "\u6279\u6CE8\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\uFF01",
noticeOpenDoc: "\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u6863",
noticeShortcutConflict: "\u5B8C\u6210\u6279\u6CE8\u5FEB\u6377\u952E\u4E0D\u80FD\u4E0E\u6362\u884C\u5FEB\u6377\u952E\u76F8\u540C\uFF0C\u5DF2\u81EA\u52A8\u91CD\u7F6E\u4E3A\u201C\u65E0\u201D\u3002",
ctxAdd: "\u6DFB\u52A0\u6279\u6CE8",
ctxEdit: "\u7F16\u8F91\u6279\u6CE8",
ctxChangeColor: " - \u4FEE\u6539\u989C\u8272",
ctxDelete: "\u5220\u9664\u6279\u6CE8",
modalTitleEdit: "\u7F16\u8F91\u6279\u6CE8",
modalTitleNew: "\u8F93\u5165\u6279\u6CE8\u5185\u5BB9",
modalColorLabel: "\u6279\u6CE8\u989C\u8272",
modalCancel: "\u53D6\u6D88",
modalConfirm: "\u786E\u5B9A",
modalColorCurrent: "\u5F53\u524D\u989C\u8272\uFF1A",
modalShortcutNone: "\u65E0",
modalShortcutEnter: "Enter",
modalShortcutShiftEnter: "Shift+Enter",
modalShortcutCtrlEnter: "Ctrl+Enter",
modalHintSubmitPrefix: "\u5B8C\u6210\u6279\u6CE8\uFF1A",
modalHintNewlinePrefix: "\u6362\u884C\uFF1A",
modalHintSeparator: "\uFF1B",
batchTitle: "\u26A0\uFE0F \u6279\u91CF\u4FEE\u590D\u786E\u8BA4",
batchSummary: (count) => `\u626B\u63CF\u53D1\u73B0\u5171\u6709 ${count} \u4E2A\u6587\u4EF6\u5305\u542B\u65E7\u683C\u5F0F\u6216\u9700\u8981\u89C4\u8303\u5316\u7684\u6279\u6CE8\u3002`,
batchWarning: "\u6267\u884C\u4FEE\u590D\u5C06\u66F4\u65B0\u8FD9\u4E9B\u6587\u4EF6\u4E2D\u7684 HTML \u7ED3\u6784\uFF08\u4E3B\u8981\u662F data-note \u7684\u5B89\u5168\u8F6C\u4E49\uFF09\u3002\u5EFA\u8BAE\u5148\u5907\u4EFD\u4F60\u7684 vault\u3002",
batchConfirm: (count) => `\u786E\u8BA4\u4FEE\u590D\uFF08${count} \u4E2A\u6587\u4EF6\uFF09`,
batchCancel: "\u53D6\u6D88",
settingsGeneral: "\u57FA\u7840\u8BBE\u7F6E",
settingsAppearance: "\u5916\u89C2\u6837\u5F0F",
settingsInteraction: "\u4EA4\u4E92\u4F53\u9A8C",
settingsAdvanced: "\u9AD8\u7EA7\u4E0E\u7EF4\u62A4",
settingDefaultColorName: "\u9ED8\u8BA4\u6279\u6CE8\u989C\u8272",
settingDefaultColorDesc: "\u65B0\u5EFA\u6279\u6CE8\u65F6\u7684\u521D\u59CB\u9009\u4E2D\u989C\u8272\u3002",
settingHideDefaultName: "\u9ED8\u8BA4\u9690\u85CF\u6279\u6CE8",
settingHideDefaultDesc: "Obsidian \u542F\u52A8\u65F6\u81EA\u52A8\u9690\u85CF\u6240\u6709\u6279\u6CE8\u6837\u5F0F\uFF08\u7EAF\u51C0\u9605\u8BFB\u6A21\u5F0F\uFF09\u3002",
settingUnderlineName: "\u663E\u793A\u4E0B\u5212\u7EBF",
settingUnderlineDesc: "\u4E3A\u6279\u6CE8\u6587\u672C\u6DFB\u52A0\u5E95\u90E8\u5F69\u8272\u4E0B\u5212\u7EBF\u3002",
settingBackgroundName: "\u663E\u793A\u80CC\u666F\u8272",
settingBackgroundDesc: "\u4E3A\u6279\u6CE8\u6587\u672C\u6DFB\u52A0\u534A\u900F\u660E\u80CC\u666F\u9AD8\u4EAE\u3002",
settingIconName: "\u663E\u793A\u6587\u672B\u56FE\u6807",
settingIconDesc: "\u5728\u6279\u6CE8\u6587\u672C\u672B\u5C3E\u8FFD\u52A0\u4E00\u4E2A\u5C0F\u7684\u201C\u{1F4DD}\u201D\u56FE\u6807\uFF08\u4F2A\u5143\u7D20\uFF09\u3002",
settingIconTriggerName: "\u6587\u672B\u56FE\u6807\u89E6\u53D1\u65B9\u5F0F",
settingIconTriggerDesc: "\u4EC5\u5728\u201C\u4EC5\u56FE\u6807\u201D\u6A21\u5F0F\u4E0B\u751F\u6548\uFF1A\u60AC\u6D6E\u81EA\u52A8\u663E\u793A\u6216\u9700\u70B9\u51FB\u540E\u663E\u793A\u6279\u6CE8\u3002",
settingIconHover: "\u79FB\u52A8\u5230\u56FE\u6807\u81EA\u52A8\u60AC\u6D6E",
settingIconClick: "\u70B9\u51FB\u56FE\u6807\u540E\u518D\u60AC\u6D6E",
settingLightOpacityName: "\u6D45\u8272\u6A21\u5F0F\u4E0D\u900F\u660E\u5EA6",
settingLightOpacityDesc: "\u8C03\u6574\u6D45\u8272\u4E3B\u9898\u4E0B\u9AD8\u4EAE\u80CC\u666F\u7684\u6DF1\u6D45 (0% - 100%)\u3002",
settingDarkOpacityName: "\u6DF1\u8272\u6A21\u5F0F\u4E0D\u900F\u660E\u5EA6",
settingDarkOpacityDesc: "\u8C03\u6574\u6DF1\u8272\u4E3B\u9898\u4E0B\u9AD8\u4EAE\u80CC\u666F\u7684\u6DF1\u6D45 (0% - 100%)\u3002",
settingTooltipWidthName: "Tooltip \u6700\u5927\u5BBD\u5EA6",
settingTooltipWidthDesc: "\u9650\u5236\u60AC\u6D6E\u6C14\u6CE1\u7684\u6700\u5927\u5BBD\u5EA6 (px)\u3002",
settingSubmitShortcutName: "\u5B8C\u6210\u6279\u6CE8\u5FEB\u6377\u952E",
settingSubmitShortcutDesc: "\u4E3A\u6279\u6CE8\u5F39\u7A97\u8BBE\u7F6E\u5B8C\u6210\u5FEB\u6377\u952E\uFF1B\u9009\u62E9\u201C\u65E0\u201D\u65F6\u9700\u70B9\u51FB\u201C\u786E\u5B9A\u201D\u3002",
settingNewlineShortcutName: "\u6362\u884C\u5FEB\u6377\u952E",
settingNewlineShortcutDesc: "\u4E3A\u6279\u6CE8\u5F39\u7A97\u8BBE\u7F6E\u6362\u884C\u5FEB\u6377\u952E\u3002",
settingAutoNormalizeAfterExitName: "\u79FB\u51FA\u6279\u6CE8\u6E90\u7801\u540E\u81EA\u52A8\u89C4\u8303\u5316",
settingAutoNormalizeAfterExitDesc: "\u5728\u5149\u6807\u79FB\u51FA\u6279\u6CE8\u6E90\u7801\u7EA6 1 \u79D2\u540E\uFF0C\u5C06\u6279\u6CE8 data-note \u4E2D\u4E0D\u5B89\u5168\u7684\u539F\u59CB\u6362\u884C\u8F6C\u6362\u4E3A \u3002",
settingFontAdjustName: "\u8C03\u8282\u5B57\u4F53\u5927\u5C0F",
settingFontAdjustDescPrefix: "\u6279\u6CE8\u5185\u5BB9\u5B57\u4F53\u6309\u6863\u4F4D\u8C03\u6574\uFF08\u6700\u591A \xB13 \u6863\uFF09\u3002 \u5F53\u524D\uFF1A",
settingFontStepDefault: "\u9ED8\u8BA4",
settingFontStep: (step) => `${step > 0 ? "+" : ""}${step} \u6863`,
settingFontStepPlural: (step) => `${step > 0 ? "+" : ""}${step} \u6863`,
settingFontSmaller: "\u51CF\u5C0F\u4E00\u53F7",
settingFontLarger: "\u52A0\u5927\u4E00\u53F7",
settingMarkdownName: "\u542F\u7528 Markdown \u6E32\u67D3",
settingMarkdownDesc: "\u5F00\u542F\u540E\uFF0C\u6279\u6CE8\u5185\u5BB9\u652F\u6301 Markdown\uFF1B\u5173\u95ED\u5219\u663E\u793A\u7EAF\u6587\u672C\u3002",
settingFixDataName: "\u4E00\u952E\u4FEE\u590D\u6570\u636E",
settingFixDataDesc: "\u626B\u63CF\u5E93\u4E2D\u6587\u4EF6\u5E76\u4FEE\u590D\u65E7\u7248\u6279\u6CE8\u7684\u683C\u5F0F\u95EE\u9898\u3002",
settingFixDataButton: "\u5F00\u59CB\u626B\u63CF\u4FEE\u590D",
settingExportName: "\u5BFC\u51FA\u6240\u6709\u6279\u6CE8\uFF08\u5F53\u524D\u6587\u4EF6\uFF09",
settingExportDesc: "\u5C06\u5F53\u524D\u6587\u6863\u7684\u6240\u6709\u6279\u6CE8\u63D0\u53D6\u5230\u526A\u8D34\u677F\u3002",
settingExportButton: "\u590D\u5236\u5230\u526A\u8D34\u677F",
exportHeading: "## \u6279\u6CE8\u5BFC\u51FA\n\n",
exportOriginal: "\u539F\u6587",
exportAnnotation: "\u6279\u6CE8",
menuAddTitle: "\u6DFB\u52A0\u6279\u6CE8"
}
};
var COLOR_OPTIONS = [
{ value: "red", labelKey: "colorRed", hex: "#e5484d" },
{ value: "", labelKey: "colorDefault", hex: "#ff9900" },
// Orange is default (empty class)
{ value: "yellow", labelKey: "colorYellow", hex: "#e6c229" },
{ value: "green", labelKey: "colorGreen", hex: "#2f9d62" },
{ value: "cyan", labelKey: "colorCyan", hex: "#1abc9c" },
{ value: "blue", labelKey: "colorBlue", hex: "#3498db" },
{ value: "purple", labelKey: "colorPurple", hex: "#9b59b6" },
{ value: "gray", labelKey: "colorGray", hex: "#95a5a6" }
];
var DEFAULT_SETTINGS = {
defaultColor: DEFAULT_COLOR,
hideAnnotations: false,
enableUnderline: true,
enableBackground: true,
enableIcon: false,
iconTooltipTrigger: "hover",
lightOpacity: 20,
darkOpacity: 25,
tooltipWidth: 800,
tooltipFontScale: 100,
submitShortcut: "",
newlineShortcut: "enter",
autoNormalizeAfterExit: true,
enableMarkdown: true,
language: "en"
};
function buildAnnotationClass2(color) {
return color ? "ob-comment " + color : "ob-comment";
}
var forcedExpandedAnnotationRange = null;
var autoNormalizeAfterExitEnabled = true;
function setForcedExpandedAnnotationRange(range) {
forcedExpandedAnnotationRange = range;
}
function setAutoNormalizeAfterExitEnabled(enabled) {
autoNormalizeAfterExitEnabled = enabled;
}
function isSelectionInsideRange(from, to, range) {
return from >= range.from && to <= range.to;
}
function getCollapsedCursorAnnotationRange(view) {
const selection = view.state.selection.main;
if (!selection.empty) return null;
return findAnnotationRangeAtOffset(view.state.doc.toString(), selection.head);
}
var _AnnotationPlugin = class _AnnotationPlugin extends import_obsidian.Plugin {
constructor() {
super(...arguments);
this.tooltipEl = null;
this.tooltipRenderComponent = null;
this.tooltipRenderId = 0;
this.tooltipLastRenderKey = null;
this.locale = "en";
}
// 记忆上次使用的颜色
t(key, params) {
const entry = STRINGS[this.locale][key];
if (typeof entry === "function") {
return entry(params);
}
return entry;
}
getColorLabel(key) {
return this.t(key);
}
getCommandRegistry() {
var _a;
return (_a = this.app.commands) == null ? void 0 : _a.commands;
}
setCommandName(id, name) {
const registry = this.getCommandRegistry();
if (!registry) return;
const fullId = `${this.manifest.id}:${id}`;
if (registry[fullId]) registry[fullId].name = name;
}
updateCommandNames() {
this.setCommandName("add-annotation-html", this.t("cmdAddDefault"));
COLOR_OPTIONS.forEach((opt) => {
if (opt.value === "") return;
const colorLabel = this.getColorLabel(opt.labelKey);
this.setCommandName(`add-annotation-${opt.value}`, this.t("cmdAddWithColor", colorLabel));
});
this.setCommandName("toggle-annotation-visibility", this.t("cmdToggleVisibility"));
this.setCommandName("edit-current-annotation", this.t("cmdEditCurrent"));
this.setCommandName("delete-current-annotation", this.t("cmdDeleteCurrent"));
this.setCommandName("normalize-annotation-data-note-current", this.t("cmdNormalizeCurrent"));
this.setCommandName("normalize-annotation-data-note-vault", this.t("cmdNormalizeVault"));
}
async onload() {
var _a;
await this.loadSettings();
this.locale = (_a = this.settings.language) != null ? _a : "en";
setAutoNormalizeAfterExitEnabled(this.settings.autoNormalizeAfterExit);
_AnnotationPlugin.lastUsedColor = this.settings.defaultColor;
this.updateStyles();
this.addSettingTab(new AnnotationSettingTab(this.app, this));
COLOR_OPTIONS.forEach((opt) => {
const iconId = opt.value ? `ob-annotation-icon-${opt.value}` : `ob-annotation-icon-default`;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="66" height="66" viewBox="0 0 24 24" style="overflow: visible"><circle cx="12" cy="20" r="10" style="fill:${opt.hex};stroke:${opt.hex};stroke-width:1;" /></svg>`;
(0, import_obsidian.addIcon)(iconId, svg);
});
this.addCommand({
id: "add-annotation-html",
name: this.t("cmdAddDefault"),
editorCallback: (editor, view) => {
this.handleAddCommand(editor);
}
});
COLOR_OPTIONS.forEach((opt) => {
if (opt.value === "") return;
const colorLabel = this.getColorLabel(opt.labelKey);
this.addCommand({
id: `add-annotation-${opt.value}`,
name: this.t("cmdAddWithColor", colorLabel),
editorCallback: (editor) => {
this.handleAddCommand(editor, opt.value);
}
});
});
this.addCommand({
id: "toggle-annotation-visibility",
name: this.t("cmdToggleVisibility"),
callback: async () => {
this.settings.hideAnnotations = !this.settings.hideAnnotations;
this.updateStyles();
await this.saveSettings();
if (this.settings.hideAnnotations) {
new import_obsidian.Notice(this.t("noticeHidden"));
} else {
new import_obsidian.Notice(this.t("noticeShown"));
}
}
});
this.addCommand({
id: "edit-current-annotation",
name: this.t("cmdEditCurrent"),
editorCallback: (editor) => {
this.handleEditCommand(editor);
}
});
this.addCommand({
id: "delete-current-annotation",
name: this.t("cmdDeleteCurrent"),
editorCallback: (editor) => {
this.handleDeleteCommand(editor);
}
});
this.addCommand({
id: "normalize-annotation-data-note-current",
name: this.t("cmdNormalizeCurrent"),
editorCallback: (editor) => {
this.normalizeCurrentFileAnnotations(editor);
}
});
this.addCommand({
id: "normalize-annotation-data-note-vault",
name: this.t("cmdNormalizeVault"),
callback: async () => {
await this.normalizeAllMarkdownFiles();
}
});
this.registerEditorExtension(livePreviewAnnotationPlugin);
this.createTooltipElement();
this.registerDomEvent(document, "mouseover", (evt) => {
if (document.body.classList.contains("ob-hide-annotations")) return;
const target = evt.target;
if (this.shouldShowTooltipOnHover(evt, target)) {
const note = target.getAttribute("data-note");
if (note) this.showTooltip(evt, note);
}
});
this.registerDomEvent(document, "mousemove", (evt) => {
if (!this.isIconOnlyMode()) return;
if (this.settings.iconTooltipTrigger !== "hover") return;
if (document.body.classList.contains("ob-hide-annotations")) return;
const target = evt.target;
if (target && target.hasClass && target.hasClass("ob-comment")) {
const note = target.getAttribute("data-note");
if (note && this.isEventOnIcon(evt, target)) {
this.showTooltip(evt, note);
return;
}
}
this.hideTooltip();
});
this.registerDomEvent(document, "mouseout", (evt) => {
const target = evt.target;
if (target && target.hasClass && target.hasClass("ob-comment")) {
this.hideTooltip();
}
});
this.registerDomEvent(document, "click", (evt) => {
if (document.body.classList.contains("ob-hide-annotations")) return;
const target = evt.target;
if (target && target.hasClass && target.hasClass("ob-comment")) {
if (this.shouldShowTooltipOnClick(evt, target)) {
const note = target.getAttribute("data-note");
if (note) this.showTooltip(evt, note);
}
} else {
if (this.tooltipEl && !this.tooltipEl.contains(target)) {
this.hideTooltip();
}
}
});
this.registerDomEvent(document, "mousedown", (evt) => {
const target = evt.target;
if (target && target.hasClass && target.hasClass("ob-comment")) {
return;
}
this.hideTooltip();
});
this.registerDomEvent(document, "keydown", () => {
this.hideTooltip();
});
this.registerEvent(
this.app.workspace.on("editor-menu", (menu, editor, view) => {
this.handleContextMenu(menu, editor);
})
);
this.registerEvent(
this.app.workspace.on("file-open", () => {
setForcedExpandedAnnotationRange(null);
})
);
}
onunload() {
setAutoNormalizeAfterExitEnabled(false);
setForcedExpandedAnnotationRange(null);
this.unloadTooltipRenderComponent();
if (this.tooltipEl) {
this.tooltipEl.remove();
}
document.body.classList.remove("ob-show-underline", "ob-show-background", "ob-show-icon", "ob-hide-annotations", "ob-icon-only-mode");
const rootStyle = document.documentElement.style;
rootStyle.removeProperty("--ob-annotation-bg-opacity-light");
rootStyle.removeProperty("--ob-annotation-bg-opacity-dark");
rootStyle.removeProperty("--ob-annotation-tooltip-width");
rootStyle.removeProperty("--ob-annotation-tooltip-font-scale");
}
async loadSettings() {
const data = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, data != null ? data : {});
if (data && typeof data.autoNormalizeNewlines === "boolean") {
if (data.autoNormalizeAfterExit === void 0) {
this.settings.autoNormalizeAfterExit = data.autoNormalizeNewlines;
}
}
const changed = this.enforceShortcutSettings();
if (changed) {
await this.saveData(this.settings);
}
}
async saveSettings() {
this.enforceShortcutSettings();
await this.saveData(this.settings);
}
enforceShortcutSettings(showNotice = false) {
const normalized = normalizeShortcutSettings({
submitShortcut: this.settings.submitShortcut,
newlineShortcut: this.settings.newlineShortcut
});
this.settings.submitShortcut = normalized.submitShortcut;
this.settings.newlineShortcut = normalized.newlineShortcut;
if (normalized.changed && showNotice) {
new import_obsidian.Notice(this.t("noticeShortcutConflict"));
}
return normalized.changed;
}
isIconOnlyMode() {
return this.settings.enableIcon && !this.settings.enableUnderline && !this.settings.enableBackground;
}
isEventOnIcon(evt, target) {
const rects = target.getClientRects();
if (!rects.length) return false;
const lastRect = rects[rects.length - 1];
const style = getComputedStyle(target, "::after");
const iconWidth = parseFloat(style.width || "") || 14;
const iconMarginLeft = parseFloat(style.marginLeft || "") || 2;
const hitboxStartX = lastRect.right - iconWidth - iconMarginLeft;
const x = evt.clientX;
const y = evt.clientY;
return x >= hitboxStartX && x <= lastRect.right && y >= lastRect.top && y <= lastRect.bottom;
}
shouldShowTooltipOnHover(evt, target) {
if (!target || !target.hasClass || !target.hasClass("ob-comment")) return false;
if (this.isIconOnlyMode()) {
if (this.settings.iconTooltipTrigger !== "hover") return false;
return this.isEventOnIcon(evt, target);
}
return true;
}
shouldShowTooltipOnClick(evt, target) {
if (!target || !target.hasClass || !target.hasClass("ob-comment")) return false;
if (this.isIconOnlyMode()) {
return this.isEventOnIcon(evt, target);
}
return true;
}
/**
* 根据当前设置更新全局样式(body class + CSS 变量),即时生效。
*/
updateStyles() {
var _a, _b;
const iconOnlyMode = this.isIconOnlyMode();
document.body.classList.toggle("ob-show-underline", this.settings.enableUnderline);
document.body.classList.toggle("ob-show-background", this.settings.enableBackground);
document.body.classList.toggle("ob-show-icon", this.settings.enableIcon);
document.body.classList.toggle("ob-hide-annotations", this.settings.hideAnnotations);
document.body.classList.toggle("ob-icon-only-mode", iconOnlyMode);
const clampOpacity = (value) => Math.min(Math.max(value, 0), 100) / 100;
const rootStyle = document.documentElement.style;
const lightAlpha = clampOpacity((_a = this.settings.lightOpacity) != null ? _a : DEFAULT_SETTINGS.lightOpacity);
const darkAlpha = clampOpacity((_b = this.settings.darkOpacity) != null ? _b : DEFAULT_SETTINGS.darkOpacity);
const tooltipWidth = this.settings.tooltipWidth > 0 ? this.settings.tooltipWidth : DEFAULT_SETTINGS.tooltipWidth;
const fontScale = this.settings.tooltipFontScale > 0 ? this.settings.tooltipFontScale : DEFAULT_SETTINGS.tooltipFontScale;
rootStyle.setProperty("--ob-annotation-bg-opacity-light", lightAlpha.toString());
rootStyle.setProperty("--ob-annotation-bg-opacity-dark", darkAlpha.toString());
rootStyle.setProperty("--ob-annotation-tooltip-width", `${tooltipWidth}px`);
rootStyle.setProperty("--ob-annotation-tooltip-font-scale", `${fontScale / 100}`);
}
// --- 核心逻辑区 ---
/**
* 命令触发:编辑当前批注
*/
handleEditCommand(editor) {
const existing = this.findAnnotationAtCursor(editor);
if (existing) {
new AnnotationModal(this.app, existing.note, existing.color || DEFAULT_COLOR, (newNote, newColor) => {
const safeNote = escapeDataNote(newNote);
const replacement = `<span class="${buildAnnotationClass2(newColor)}" data-note="${safeNote}">${existing.text}</span>`;
editor.replaceRange(replacement, existing.from, existing.to);
}, this.locale, this.t.bind(this), this.settings.submitShortcut, this.settings.newlineShortcut).open();
} else {
new import_obsidian.Notice(this.t("noticeNoAnnotation"));
}
}
/**
* 命令触发:删除当前批注
*/
handleDeleteCommand(editor) {
const existing = this.findAnnotationAtCursor(editor);
if (existing) {
editor.replaceRange(existing.text, existing.from, existing.to);
} else {
new import_obsidian.Notice(this.t("noticeNoAnnotation"));
}
}
/**
* 处理右键菜单逻辑
*/
handleContextMenu(menu, editor) {
const existingAnnotation = this.findAnnotationAtCursor(editor);
if (existingAnnotation) {
menu.addSeparator();
menu.addItem((item) => {
item.setTitle(this.t("ctxAdd")).setIcon("highlighter").onClick(() => {
const selection = editor.getSelection();
if (selection) this.performAddAnnotation(editor, selection);
else new import_obsidian.Notice(this.t("noticeNeedSelectionAdd"));
});
});
menu.addItem((item) => {
item.setTitle(this.t("ctxEdit")).setIcon("pencil").onClick(() => {
this.handleEditCommand(editor);
});
});
menu.addItem((item) => {
var _a;
item.setTitle(this.t("ctxChangeColor")).setIcon("palette");
const subMenu = (_a = item.setSubmenu) == null ? void 0 : _a.call(item);
if (!subMenu) return;
COLOR_OPTIONS.forEach((opt) => {
const iconId = opt.value ? `ob-annotation-icon-${opt.value}` : `ob-annotation-icon-default`;
const colorLabel = this.getColorLabel(opt.labelKey);
subMenu.addItem((subItem) => {
subItem.setTitle(colorLabel).setIcon(iconId).onClick(() => {
const replacement = `<span class="${buildAnnotationClass2(opt.value)}" data-note="${escapeDataNote(existingAnnotation.note)}">${existingAnnotation.text}</span>`;
editor.replaceRange(replacement, existingAnnotation.from, existingAnnotation.to);
});
});
});
});
menu.addItem((item) => {
item.setTitle(this.t("ctxDelete")).setIcon("trash").onClick(() => {
this.handleDeleteCommand(editor);
});
});
} else {
const selection = editor.getSelection();
if (selection && selection.trim().length > 0) {
menu.addSeparator();
menu.addItem((item) => {
item.setTitle(this.t("ctxAdd")).setIcon("highlighter").onClick(() => {
this.performAddAnnotation(editor, selection);
});
});
}
}
}
/**
* 命令触发的添加逻辑
*/
handleAddCommand(editor, forcedColor = null) {
const selection = editor.getSelection();
if (!selection) {
new import_obsidian.Notice(this.t("noticeNeedSelection"));
return;
}
if (selection.includes('<span class="ob-comment"')) {
new import_obsidian.Notice(this.t("noticeNoNested"));
return;
}
this.performAddAnnotation(editor, selection, forcedColor);
}
/**
* 执行添加批注动作
*/
performAddAnnotation(editor, selectionText, forcedColor = null) {
const initialColor = forcedColor !== null ? forcedColor : _AnnotationPlugin.lastUsedColor;
new AnnotationModal(this.app, "", initialColor, (noteContent, colorChoice) => {
_AnnotationPlugin.lastUsedColor = colorChoice;
const safeNote = escapeDataNote(noteContent);
const replacement = `<span class="${buildAnnotationClass2(colorChoice)}" data-note="${safeNote}">${selectionText}</span>`;
editor.replaceSelection(replacement);
}, this.locale, this.t.bind(this), this.settings.submitShortcut, this.settings.newlineShortcut).open();
}
/**
* [辅助算法] 扫描全文,判断光标是否位于某个批注 HTML 标签内部
*/
findAnnotationAtCursor(editor) {
const cursor = editor.getCursor();
const cursorOffset = editor.posToOffset(cursor);
const docText = editor.getValue();
COMMENT_REGEX2.lastIndex = 0;
let match;
while ((match = COMMENT_REGEX2.exec(docText)) !== null) {
const fullMatch = match[0];
const colorClass = match[1] || "";
const noteContent = match[2];
const innerText = match[3];
const startOffset = match.index;
const endOffset = startOffset + fullMatch.length;
if (cursorOffset >= startOffset && cursorOffset <= endOffset) {
return {
from: editor.offsetToPos(startOffset),
to: editor.offsetToPos(endOffset),
text: innerText,
// 原文
note: decodeDataNote(noteContent),
// 笔记内容(解码后)
color: colorClass
};
}
}
return null;
}
// --- Tooltip 相关逻辑 ---
createTooltipElement() {
this.tooltipEl = document.body.createDiv({ cls: "ob-annotation-tooltip" });
}
unloadTooltipRenderComponent() {
var _a;
(_a = this.tooltipRenderComponent) == null ? void 0 : _a.unload();
this.tooltipRenderComponent = null;
}
updateTooltipPosition(evt) {
if (!this.tooltipEl) return;
const x = evt.pageX;
const y = evt.pageY - 40;
this.tooltipEl.style.left = `${x}px`;
this.tooltipEl.style.top = `${y}px`;
}
showTooltip(evt, text) {
var _a;
if (!this.tooltipEl) return;
this.tooltipEl.addClass("is-visible");
this.updateTooltipPosition(evt);
const decodedText = decodeDataNote(text);
const sourcePath = ((_a = this.app.workspace.getActiveFile()) == null ? void 0 : _a.path) || "";
const renderKey = `${this.settings.enableMarkdown ? "md" : "text"}|${sourcePath}|${decodedText}`;
if (renderKey === this.tooltipLastRenderKey) return;
this.tooltipLastRenderKey = renderKey;
this.tooltipEl.empty();
this.unloadTooltipRenderComponent();
if (this.settings.enableMarkdown) {
const renderId = ++this.tooltipRenderId;
const component = new import_obsidian.Component();
component.load();
this.tooltipRenderComponent = component;
const renderContainer = document.createElement("div");
void import_obsidian.MarkdownRenderer.render(this.app, decodedText, renderContainer, sourcePath, component).then(() => {
if (!this.tooltipEl) return;
if (renderId !== this.tooltipRenderId) return;
this.tooltipEl.empty();
this.tooltipEl.appendChild(renderContainer);
}).catch((err) => {
console.error("[hover-annotations] Failed to render tooltip markdown", err);
});
} else {
this.tooltipEl.createEl("pre", { text: decodedText, cls: "ob-annotation-tooltip-plain" });
}
}
hideTooltip() {
if (!this.tooltipEl) return;
this.tooltipEl.removeClass("is-visible");
this.tooltipRenderId++;
this.tooltipLastRenderKey = null;
this.unloadTooltipRenderComponent();
this.tooltipEl.empty();
}
/**
* 修复当前文件中所有批注的 data-note(处理旧版直接换行/特殊字符未转义的情况)
*/
normalizeCurrentFileAnnotations(editor) {
const docText = editor.getValue();
const cursorOffset = editor.posToOffset(editor.getCursor());
const { text, changed, cursorOffset: nextCursorOffset } = normalizeTextWithCursor(docText, cursorOffset);
if (!changed) {
new import_obsidian.Notice(this.t("noticeNoFixNeeded"));
return;
}
const lastLine = editor.lastLine();
const lastLineLen = editor.getLine(lastLine).length;
setForcedExpandedAnnotationRange(findAnnotationRangeAtOffset(text, nextCursorOffset));
editor.replaceRange(text, { line: 0, ch: 0 }, { line: lastLine, ch: lastLineLen });
editor.setCursor(editor.offsetToPos(nextCursorOffset));
new import_obsidian.Notice(this.t("noticeFixedCurrent"));
}
/**
* 扫描并修复库内所有 Markdown 文件的批注 data-note
*/
async normalizeAllMarkdownFiles() {
new import_obsidian.Notice(this.t("noticeScanStart"));
const files = this.app.vault.getMarkdownFiles();
const filesToFix = [];
for (const file of files) {
const original = await this.app.vault.read(file);
const { changed } = normalizeAnnotationsInText(original);
if (changed) {
filesToFix.push(file);
}
}
if (filesToFix.length === 0) {
new import_obsidian.Notice(this.t("noticeNoFixNeeded"));
return;
}
new BatchFixConfirmModal(this.app, filesToFix, () => {
void this.applyNormalizationToFiles(filesToFix);
}, this.t.bind(this)).open();
}
async applyNormalizationToFiles(filesToFix) {
let fixedCount = 0;
for (const file of filesToFix) {
const original = await this.app.vault.read(file);
const { text, changed } = normalizeAnnotationsInText(original);
if (changed) {
await this.app.vault.modify(file, text);
fixedCount++;
}
}
new import_obsidian.Notice(this.t("noticeFixedVault", fixedCount));
}
};
_AnnotationPlugin.lastUsedColor = DEFAULT_COLOR;
var AnnotationPlugin = _AnnotationPlugin;
var AnnotationSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
let iconTriggerSetting = null;
const t = this.plugin.t.bind(this.plugin);
new import_obsidian.Setting(containerEl).setName(t("settingsGeneral")).setHeading();
new import_obsidian.Setting(containerEl).setName(t("settingLanguageName")).setDesc(t("settingLanguageDesc")).addDropdown((dropdown) => {
var _a;
dropdown.addOption("en", t("settingLanguageEn"));
dropdown.addOption("zh", t("settingLanguageZh"));
dropdown.setValue((_a = this.plugin.settings.language) != null ? _a : "en").onChange(async (value) => {
const nextLocale = value === "zh" ? "zh" : "en";
this.plugin.settings.language = nextLocale;
this.plugin.locale = nextLocale;
await this.plugin.saveSettings();
this.plugin.updateCommandNames();
this.display();
});
});
new import_obsidian.Setting(containerEl).setName(t("settingDefaultColorName")).setDesc(t("settingDefaultColorDesc")).addDropdown((dropdown) => {
COLOR_OPTIONS.forEach((opt) => {
dropdown.addOption(opt.value, t(opt.labelKey));
});
dropdown.setValue(this.plugin.settings.defaultColor).onChange(async (value) => {
this.plugin.settings.defaultColor = value;
AnnotationPlugin.lastUsedColor = value;
await this.plugin.saveSettings();
});
});
new import_obsidian.Setting(containerEl).setName(t("settingHideDefaultName")).setDesc(t("settingHideDefaultDesc")).addToggle((toggle) => toggle.setValue(this.plugin.settings.hideAnnotations).onChange(async (value) => {
this.plugin.settings.hideAnnotations = value;
this.plugin.updateStyles();
await this.plugin.saveSettings();
}));