-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1789 lines (1614 loc) · 58.8 KB
/
main.js
File metadata and controls
1789 lines (1614 loc) · 58.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const obsidian_1 = require("obsidian");
// Settings interface
const DEFAULT_SETTINGS = {
snippets_local: "cssclasses",
snippets_global: "chisel",
enableTypography: false,
enableColor: false,
enableRhythm: false,
startupSnapshot: {
cssClasses: [],
snippetNames: [],
},
};
class ChiselPlugin extends obsidian_1.Plugin {
constructor() {
super(...arguments);
this.appliedClasses = new Set();
this.appliedSnippetViewClasses = new Set();
this.hasAppliedStartupSnapshot = false;
this.chiselFrontmatterElement = null; // Renamed from styleElement
this.chiselNoteElement = null; // Renamed
this.autoloadedSnippets = new Map();
this.concatenatedAutoloadCss = "";
this.lastAppliedCustomCss = "";
this.lastAppliedChiselNoteCss = "";
this.chiselGlobalElement = null; // New property for chisel-global
this.frontmatterUpdateTimeout = null; // Timeout for debouncing frontmatter updates
// Performance optimization caches
this.fileCache = new Map(); // Cache file metadata
this.autoloadFileCache = new Map(); // Cache autoloaded files
this.lastVaultScan = 0; // Timestamp of last vault scan
this.autoloadedSnippetsInitialized = false; // Track if autoloaded snippets have been processed
this.startupRetryCount = 0; // Track startup snapshot retry attempts
}
async onload() {
document.body.classList.add("chisel");
await this.loadSettings();
// Create style elements efficiently in a single batch
this.createStyleElements();
// Add settings tab
this.addSettingTab(new ChiselSettingTab(this.app, this));
// Update classes when active note changes
this.registerEvent(
this.app.workspace.on("active-leaf-change", () => {
this.updateBodyClasses();
this.updateModeClasses();
}),
);
// Update classes when frontmatter changes
this.registerEvent(
this.app.metadataCache.on("changed", (file) => {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile && file === activeFile) {
this.updateBodyClasses();
}
const fm = this.app.metadataCache.getFileCache(file)?.frontmatter;
// Invalidate cache for this file
const cacheKey = `${file.path}-${file.stat.mtime}`;
if (this.autoloadFileCache.has(cacheKey)) {
this.autoloadFileCache.delete(cacheKey);
}
if (
this.autoloadedSnippets.has(file.path) ||
this.hasAutoloadFlag(fm)
) {
// Reset initialization flag to trigger refresh
this.autoloadedSnippetsInitialized = false;
this.updateAutoloadedSnippets();
}
}),
);
// Also listen for frontmatter resolve events
this.registerEvent(
this.app.metadataCache.on("resolve", (file) => {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile && file === activeFile) {
this.updateBodyClasses();
}
// Try applying startup snapshot if still idle and not yet applied
if (!this.hasAppliedStartupSnapshot) this.applyStartupSnapshotIfIdle();
}),
);
// Update classes when mode changes
this.registerEvent(
this.app.workspace.on("layout-change", () => {
this.updateModeClasses();
}),
);
// Add more immediate response to editor changes
this.registerEvent(
this.app.workspace.on("editor-change", (editor, info) => {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile && info.file === activeFile) {
// Debounce the update to avoid excessive calls
clearTimeout(this.frontmatterUpdateTimeout);
this.frontmatterUpdateTimeout = setTimeout(() => {
this.updateBodyClasses();
}, 50);
}
}),
);
// Listen for file modifications (immediate response)
this.registerEvent(
this.app.vault.on("modify", (file) => {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile && file === activeFile) {
// Immediate response for file modifications
clearTimeout(this.frontmatterUpdateTimeout);
this.frontmatterUpdateTimeout = setTimeout(() => {
this.updateBodyClasses();
}, 25);
}
}),
);
this.updateModeClasses();
this.updateBodyClasses();
// Defer heavy operations with lazy loading
this.scheduleHeavyOperations();
// Also attempt once the workspace layout is ready
// (ensures vault files are available)
if (this.app?.workspace?.onLayoutReady) {
this.app.workspace.onLayoutReady(() => {
this.onWorkspaceReady();
});
} else {
// Fallback for older Obsidian versions
this.app.workspace.on("layout-ready", () => {
this.onWorkspaceReady();
});
}
this.addCommand({
id: "open-chisel-cheatsheet-modal",
name: "Open Cheatsheet",
callback: () => {
new ChiselCheatsheetModal(this.app).open();
},
});
}
onunload() {
// Clear any pending timeouts
if (this.frontmatterUpdateTimeout) {
clearTimeout(this.frontmatterUpdateTimeout);
}
if (this.heavyOperationsTimeout) {
clearTimeout(this.heavyOperationsTimeout);
}
if (this.workspaceReadyTimeout) {
clearTimeout(this.workspaceReadyTimeout);
}
document.body.classList.remove("chisel");
this.cleanup();
this.clearModeClasses();
}
scheduleHeavyOperations() {
// Schedule heavy operations with progressive delays
// This allows the UI to remain responsive during startup
// Quick startup snapshot first (if no file is open)
this.applyStartupSnapshotIfIdle();
// Then schedule autoloaded snippets after a small delay
// this.heavyOperationsTimeout = setTimeout(() => {
// this.updateAutoloadedSnippets();
// }, 100); // 100ms delay allows UI to settle
}
onWorkspaceReady() {
// This runs when the workspace is fully loaded
// Apply startup snapshot again in case files are now available
this.workspaceReadyTimeout = setTimeout(() => {
this.applyStartupSnapshotIfIdle();
// Ensure a fresh scan for autoloaded snippets on workspace ready
this.autoloadedSnippetsInitialized = false;
this.updateAutoloadedSnippets();
}, 50);
}
createStyleElements() {
// Batch DOM operations for style element creation
const fragment = document.createDocumentFragment();
const elementsToCreate = [
{ id: "chisel-global", prop: "chiselGlobalElement" },
{ id: "chisel-note", prop: "chiselNoteElement" },
{ id: "chisel-frontmatter", prop: "chiselFrontmatterElement" },
];
let needsAppend = false;
elementsToCreate.forEach(({ id, prop }) => {
let element = document.getElementById(id);
if (!element) {
element = document.createElement("style");
element.id = id;
fragment.appendChild(element);
needsAppend = true;
}
this[prop] = element;
});
// Single DOM append operation
if (needsAppend) {
document.head.appendChild(fragment);
}
}
// Async utility methods for consistent patterns
async delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async scheduleTask(task, delayMs = 0) {
await this.delay(delayMs);
return await task();
}
cleanup() {
this.clearAllClasses();
this.clearSnippetViewClasses();
this.clearFrontmatterProperties();
this.clearChiselNote();
}
async loadSettings() {
const data = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
}
async saveSettings() {
await this.saveData(this.settings);
}
// Helper method to parse frontmatter directly from editor content
async parseCurrentFrontmatter(file) {
try {
// Try to get content from active editor first (most up-to-date)
const activeView = this.app.workspace.getActiveViewOfType(
obsidian_1.MarkdownView,
);
let content;
if (activeView && activeView.file === file) {
// Get content from editor (immediate, no cache delay)
content = activeView.editor.getValue();
} else {
// Fallback to file read
content = await this.app.vault.read(file);
}
// Simple frontmatter parsing
const frontmatterMatch = content.match(/^---\s*([\s\S]*?)\n---/);
if (frontmatterMatch) {
const frontmatterText = frontmatterMatch[1];
const result = {};
// Parse cssclasses (both cssclasses and cssClasses)
const cssclassesMatch = frontmatterText.match(/^cssclasses?:\s*(.*)$/m);
if (cssclassesMatch) {
const value = cssclassesMatch[1].trim();
let cssclasses;
// Handle different formats: [item1, item2] or "item" or item
if (value.startsWith("[") && value.endsWith("]")) {
// Array format
cssclasses = value
.slice(1, -1)
.split(",")
.map((item) => item.trim().replace(/["']/g, ""))
.filter(Boolean);
} else if (value) {
// Single value format
cssclasses = value.replace(/["']/g, "");
}
if (cssclasses) {
result.cssclasses = cssclasses;
}
}
// Parse chisel properties (for snippets)
const chiselMatch = frontmatterText.match(/^chisel:\s*(.*)$/m);
if (chiselMatch) {
const value = chiselMatch[1].trim();
let chisel;
if (value.startsWith("[") && value.endsWith("]")) {
chisel = value
.slice(1, -1)
.split(",")
.map((item) => item.trim().replace(/["']/g, ""))
.filter(Boolean);
} else if (value) {
chisel = value.replace(/["']/g, "");
}
if (chisel) {
result.chisel = chisel;
}
}
// Parse any chisel- properties
const chiselPropMatches = frontmatterText.matchAll(
/^(chisel-[^:]+):\s*(.*)$/gm,
);
for (const match of chiselPropMatches) {
const propName = match[1];
const propValue = match[2].trim().replace(/["']/g, "");
if (propValue) {
result[propName] = propValue;
}
}
return Object.keys(result).length > 0 ? result : null;
}
} catch (error) {
// Silently fail and return null to use cache
console.log("Frontmatter parsing error:", error);
}
return null;
}
async updateBodyClasses() {
const activeFile = this.app.workspace.getActiveFile();
const newClasses = new Set();
let frontmatter = null;
// Global settings classes
if (this.settings.enableTypography) newClasses.add("chisel-typography");
if (this.settings.enableColor) newClasses.add("chisel-color");
if (this.settings.enableRhythm) newClasses.add("chisel-vertical-rhythm");
if (activeFile) {
// Always try direct parsing first for immediate response, then fallback to cache
frontmatter = await this.parseCurrentFrontmatter(activeFile);
// Fallback to cache if direct parsing failed
if (!frontmatter) {
const meta = this.app.metadataCache.getFileCache(activeFile);
if (meta?.frontmatter) {
frontmatter = meta.frontmatter;
}
}
if (frontmatter) {
const cssclasses = frontmatter.cssclasses || frontmatter.cssClasses;
if (cssclasses) {
const classList = Array.isArray(cssclasses)
? cssclasses
: [cssclasses];
classList.forEach((cls) => {
if (typeof cls === "string" && cls.trim().length > 0) {
const sanitizedClass = cls.trim().replace(/\s+/g, "-");
if (sanitizedClass) {
newClasses.add("cssclass-" + sanitizedClass);
}
}
});
}
}
}
// Batch DOM updates for better performance
const classesToAdd = [...newClasses].filter(
(cls) => !this.appliedClasses.has(cls),
);
const classesToRemove = [...this.appliedClasses].filter(
(cls) => !newClasses.has(cls),
);
// Only update DOM if there are changes
if (classesToAdd.length > 0 || classesToRemove.length > 0) {
// Batch DOM operations
const bodyClassList = document.body.classList;
classesToAdd.forEach((cls) => {
try {
bodyClassList.add(cls);
} catch (e) {
if (e instanceof DOMException) {
new obsidian_1.Notice(
`Chisel: Invalid CSS class found: "${cls}". Check your frontmatter for classes with spaces or special characters.`,
);
} else {
throw e;
}
}
});
classesToRemove.forEach((cls) => bodyClassList.remove(cls));
}
this.appliedClasses = newClasses;
if (activeFile && frontmatter) {
// Handle snippets and other properties using the direct frontmatter
const meta = { frontmatter };
this.updateSnippetsAndProperties(meta);
}
}
async updateSnippetsAndProperties(meta) {
if (!meta?.frontmatter) return;
// Collect snippet names from both global and local properties
let snippetNames = [];
// Check global snippets property (default: "chisel")
const globalSnippetProp = meta.frontmatter[this.settings.snippets_global];
if (
typeof globalSnippetProp === "string" &&
globalSnippetProp.trim().length > 0
) {
snippetNames.push(globalSnippetProp.trim());
} else if (Array.isArray(globalSnippetProp)) {
snippetNames = snippetNames.concat(
globalSnippetProp
.filter((s) => typeof s === "string")
.map((s) => s.trim())
.filter(Boolean),
);
}
// Check local snippets property (default: "cssclasses")
const localSnippetProp = meta.frontmatter[this.settings.snippets_local];
if (
typeof localSnippetProp === "string" &&
localSnippetProp.trim().length > 0
) {
snippetNames.push(localSnippetProp.trim());
} else if (Array.isArray(localSnippetProp)) {
snippetNames = snippetNames.concat(
localSnippetProp
.filter((s) => typeof s === "string")
.map((s) => s.trim())
.filter(Boolean),
);
}
// Remove duplicates
snippetNames = [...new Set(snippetNames)];
// Also add snippet names as classes to active markdown view containers
// Save snapshot for startup when no file is open
try {
this.settings.startupSnapshot = {
cssClasses: this.appliedClasses
? Array.from(this.appliedClasses).map((c) =>
c.replace("cssclass-", ""),
)
: [],
snippetNames: snippetNames,
};
await this.saveSettings();
} catch (e) {}
// Batch snippet view class updates
const newSnippetClasses = new Set();
if (snippetNames.length > 0) {
snippetNames.forEach((name) => {
const slug = name
.trim()
.toLowerCase()
.replace(/[^a-z0-9_\-\s]/g, "")
.replace(/\s+/g, "-");
if (slug.length > 0) {
newSnippetClasses.add(slug);
}
});
}
// Only update DOM if classes have changed
const oldClasses = this.appliedSnippetViewClasses || new Set();
const classesChanged =
newSnippetClasses.size !== oldClasses.size ||
[...newSnippetClasses].some((cls) => !oldClasses.has(cls)) ||
[...oldClasses].some((cls) => !newSnippetClasses.has(cls));
if (classesChanged) {
const activeLeaf = document.querySelector(
".mod-root .workspace-leaf.mod-active .workspace-leaf-content",
);
if (activeLeaf) {
const viewEls = activeLeaf.querySelectorAll(
".markdown-source-view, .markdown-preview-view",
);
if (viewEls.length > 0) {
// Remove old classes
oldClasses.forEach((cls) => {
if (!newSnippetClasses.has(cls)) {
viewEls.forEach((el) => el.classList.remove(cls));
}
});
// Add new classes
newSnippetClasses.forEach((cls) => {
if (!oldClasses.has(cls)) {
viewEls.forEach((el) => el.classList.add(cls));
}
});
}
}
this.appliedSnippetViewClasses = newSnippetClasses;
}
if (snippetNames.length > 0) {
await this.applyChiselNote(snippetNames);
} else {
this.clearChiselNote();
}
this.clearFrontmatterProperties();
this.applyFrontmatter(meta.frontmatter);
}
clearAllClasses() {
this.appliedClasses.forEach((className) => {
document.body.classList.remove(className);
});
this.appliedClasses.clear();
}
clearSnippetViewClasses() {
if (
!this.appliedSnippetViewClasses ||
this.appliedSnippetViewClasses.size === 0
)
return;
const activeLeaf = document.querySelector(
".mod-root .workspace-leaf.mod-active .workspace-leaf-content",
);
if (!activeLeaf) {
this.appliedSnippetViewClasses.clear();
return;
}
const viewEls = activeLeaf.querySelectorAll(
".markdown-source-view, .markdown-preview-view",
);
this.appliedSnippetViewClasses.forEach((cls) => {
viewEls.forEach((el) => el.classList.remove(cls));
});
this.appliedSnippetViewClasses.clear();
}
addClassToViews(className) {
const activeLeaf = document.querySelector(
".mod-root .workspace-leaf.mod-active .workspace-leaf-content",
);
if (!activeLeaf) return;
const viewEls = activeLeaf.querySelectorAll(
".markdown-source-view, .markdown-preview-view",
);
viewEls.forEach((el) => el.classList.add(className));
this.appliedSnippetViewClasses.add(className);
}
async applyStartupSnapshotIfIdle() {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) return;
if (this.hasAppliedStartupSnapshot) return;
const snap = this.settings?.startupSnapshot;
if (!snap) {
this.hasAppliedStartupSnapshot = true;
return;
}
// Check if vault is ready without polling
const files = this.app.vault.getMarkdownFiles();
if (!files || files.length === 0) {
// Use exponential backoff instead of fixed delay
const delay = Math.min(100, (this.startupRetryCount || 0) * 20 + 20);
this.startupRetryCount = (this.startupRetryCount || 0) + 1;
// Don't retry forever
if (this.startupRetryCount < 10) {
setTimeout(() => this.applyStartupSnapshotIfIdle(), delay);
} else {
this.hasAppliedStartupSnapshot = true;
}
return;
}
// Batch all DOM operations
const classesToAdd = new Set(this.appliedClasses);
// Apply saved cssclasses
if (Array.isArray(snap.cssClasses)) {
snap.cssClasses.forEach((cls) => {
if (typeof cls === "string" && cls.trim().length > 0) {
const className = "cssclass-" + cls.trim();
classesToAdd.add(className);
}
});
}
// Apply global settings classes
if (this.settings.enableTypography) {
classesToAdd.add("chisel-typography");
}
if (this.settings.enableColor) {
classesToAdd.add("chisel-color");
}
if (this.settings.enableRhythm) {
classesToAdd.add("chisel-vertical-rhythm");
}
// Single DOM update for all classes
const bodyClassList = document.body.classList;
classesToAdd.forEach((cls) => {
if (!this.appliedClasses.has(cls)) {
bodyClassList.add(cls);
}
});
this.appliedClasses = classesToAdd;
// Apply saved snippets (non-blocking)
if (Array.isArray(snap.snippetNames) && snap.snippetNames.length > 0) {
// Use setTimeout to make this non-blocking
setTimeout(async () => {
try {
await this.applyChiselNote(snap.snippetNames);
} catch (error) {
console.warn("Chisel: Error applying startup snippets:", error);
}
}, 10);
}
this.hasAppliedStartupSnapshot = true;
}
clearModeViewClasses() {
const activeLeaf = document.querySelector(
".mod-root .workspace-leaf.mod-active .workspace-leaf-content",
);
if (!activeLeaf) return;
const viewEls = activeLeaf.querySelectorAll(
".markdown-source-view, .markdown-preview-view",
);
const modeClasses = [
"chisel-reading",
"chisel-editing",
"chisel-canvas",
"chisel-empty",
"chisel-base",
"chisel-webviewer",
"chisel-note",
];
modeClasses.forEach((className) => {
viewEls.forEach((el) => el.classList.remove(className));
if (this.appliedSnippetViewClasses) {
this.appliedSnippetViewClasses.delete(className);
}
});
}
applyFrontmatter(frontmatter) {
const chiselProps = {};
const fontProperties = new Set();
for (const [key, value] of Object.entries(frontmatter)) {
if (key.startsWith("chisel-") && key !== "chisel") {
const cssVarName = "--" + key.substring(7);
chiselProps[cssVarName] = value;
const fontKeys = [
"font-text",
"font-header",
"font-monospace",
"font-interface",
];
if (fontKeys.includes(cssVarName.substring(2))) {
const fontNames = value
.split(",")
.map((font) => font.trim().replace(/['"]/g, ""));
fontNames.forEach((font) => fontProperties.add(font));
}
}
}
if (Object.keys(chiselProps).length > 0) {
// Ensure the element exists
if (
!this.chiselFrontmatterElement ||
!document.getElementById("chisel-frontmatter")
) {
this.chiselFrontmatterElement = document.createElement("style");
this.chiselFrontmatterElement.id = "chisel-frontmatter";
// Insert after chiselNoteElement if it exists, otherwise append to head
if (
this.chiselNoteElement &&
document.contains(this.chiselNoteElement)
) {
this.chiselNoteElement.after(this.chiselFrontmatterElement);
} else {
document.head.appendChild(this.chiselFrontmatterElement);
}
}
let chiselFrontmatterElement = this.chiselFrontmatterElement;
const googleFontsImports = Array.from(fontProperties)
.map((font) => {
const fontUrl = font.replace(/\s+/g, "+");
return `@import url('https://fonts.googleapis.com/css2?family=${fontUrl}&display=swap');`;
})
.join("\n");
const cssVars = Object.entries(chiselProps)
.map(([prop, value]) => {
const formattedValue =
typeof value === "string" && value.includes(" ")
? "'" + value + "'"
: value;
return ` ${prop}: ${formattedValue} !important;`;
})
.join("\n");
const newCssContent = [googleFontsImports, `html body {\n${cssVars}\n}`]
.filter(Boolean)
.join("\n\n");
if (newCssContent === this.lastAppliedCustomCss) {
return; // No change, so no DOM update needed
}
chiselFrontmatterElement.textContent = newCssContent;
this.lastAppliedCustomCss = newCssContent;
}
}
clearFrontmatterProperties() {
if (this.chiselFrontmatterElement) {
this.chiselFrontmatterElement.textContent = "";
this.lastAppliedCustomCss = "";
}
}
async applyChiselNote(chiselNoteName) {
if (
!chiselNoteName ||
(Array.isArray(chiselNoteName) && chiselNoteName.length === 0)
) {
this.clearChiselNote();
this.lastAppliedChiselNoteCss = "";
return;
}
// Handle boolean values (common mistake in frontmatter)
if (typeof chiselNoteName === "boolean") {
this.clearChiselNote();
this.lastAppliedChiselNoteCss = "";
return;
}
// Convert to array of strings, filtering out non-strings
let noteNames;
if (Array.isArray(chiselNoteName)) {
noteNames = chiselNoteName
.filter((name) => typeof name === "string" && name.trim().length > 0)
.map((name) => name.trim());
} else if (typeof chiselNoteName === "string") {
noteNames = [chiselNoteName.trim()];
} else {
this.clearChiselNote();
this.lastAppliedChiselNoteCss = "";
return;
}
if (noteNames.length === 0) {
this.clearChiselNote();
this.lastAppliedChiselNoteCss = "";
return;
}
const files = this.app.vault.getMarkdownFiles();
let allCssContent = "";
for (const name of noteNames) {
const cssFile = files.find((file) => file.basename === name);
if (!cssFile) {
continue; // Continue to the next snippet if one is not found
}
const noteContent = await this.app.vault.cachedRead(cssFile);
const codeBlockRegex = /```css\b[^\n]*\n([\s\S]*?)```/gi;
const matches = [...noteContent.matchAll(codeBlockRegex)];
const cssContent = matches.map((match) => match[1]).join("\n");
if (cssContent && cssContent.trim().length > 0) {
allCssContent += cssContent + "\n";
}
}
if (allCssContent === this.lastAppliedChiselNoteCss) {
return; // No change, so no DOM update needed
}
if (allCssContent) {
// Ensure the element exists
if (!this.chiselNoteElement || !document.getElementById("chisel-note")) {
this.chiselNoteElement = document.createElement("style");
this.chiselNoteElement.id = "chisel-note";
// Insert after chiselGlobalElement if it exists, otherwise append to head
if (
this.chiselGlobalElement &&
document.contains(this.chiselGlobalElement)
) {
this.chiselGlobalElement.after(this.chiselNoteElement);
} else {
document.head.appendChild(this.chiselNoteElement);
}
}
this.chiselNoteElement.textContent = allCssContent;
this.lastAppliedChiselNoteCss = allCssContent;
} else {
this.clearChiselNote();
this.lastAppliedChiselNoteCss = "";
}
}
clearChiselNote() {
if (this.chiselNoteElement) {
this.chiselNoteElement.textContent = "";
this.lastAppliedChiselNoteCss = "";
}
}
hasAutoloadFlag(frontmatter) {
if (!frontmatter) return false;
// Only the "chisel" frontmatter flag enables autoload
return Boolean(frontmatter[this.settings.snippets_global]);
}
async updateAutoloadedSnippets() {
let chiselGlobalElement = this.chiselGlobalElement;
const now = Date.now();
// Use cached results if available and recent (less than 5 seconds old)
if (this.autoloadedSnippetsInitialized && now - this.lastVaultScan < 5000) {
return;
}
const files = this.app.vault.getMarkdownFiles();
const autoloadFiles = [];
// Use incremental scanning with cache
for (const file of files) {
const cacheKey = `${file.path}-${file.stat.mtime}`;
// Check cache first
if (this.autoloadFileCache.has(cacheKey)) {
const cached = this.autoloadFileCache.get(cacheKey);
if (cached.hasAutoload) {
autoloadFiles.push(file);
}
continue;
}
// Not in cache, check metadata
const meta = this.app.metadataCache.getFileCache(file);
const hasAutoload = this.hasAutoloadFlag(meta?.frontmatter);
// Cache the result
this.autoloadFileCache.set(cacheKey, { hasAutoload });
if (hasAutoload) {
autoloadFiles.push(file);
}
}
// Clean up old cache entries (keep cache size reasonable)
if (this.autoloadFileCache.size > files.length * 2) {
const validKeys = new Set(files.map((f) => `${f.path}-${f.stat.mtime}`));
for (const key of this.autoloadFileCache.keys()) {
if (!validKeys.has(key)) {
this.autoloadFileCache.delete(key);
}
}
}
autoloadFiles.sort((a, b) => a.path.localeCompare(b.path));
if (autoloadFiles.length === 0) {
if (chiselGlobalElement) {
chiselGlobalElement.textContent = "";
}
this.autoloadedSnippets.clear();
this.concatenatedAutoloadCss = "";
this.lastVaultScan = now;
this.autoloadedSnippetsInitialized = true;
return;
}
let allCssContent = "";
const processedFiles = new Set();
// Process files in batches to avoid blocking
for (let i = 0; i < autoloadFiles.length; i += 5) {
const batch = autoloadFiles.slice(i, i + 5);
// Process batch
await Promise.all(
batch.map(async (file) => {
if (processedFiles.has(file.path)) return;
processedFiles.add(file.path);
try {
const noteContent = await this.app.vault.cachedRead(file);
const codeBlockRegex = /```css\b[^\n]*\n([\s\S]*?)```/gi;
const matches = [...noteContent.matchAll(codeBlockRegex)];
const cssContent = matches.map((match) => match[1]).join("\n");
if (cssContent && cssContent.trim().length > 0) {
allCssContent += cssContent + "\n";
this.autoloadedSnippets.set(file.path, cssContent);
}
} catch (error) {
console.warn(`Chisel: Error reading file ${file.path}:`, error);
}
}),
);
// Small delay between batches to keep UI responsive
if (i + 5 < autoloadFiles.length) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
// Only update if content changed
if (allCssContent !== this.concatenatedAutoloadCss) {
this.concatenatedAutoloadCss = allCssContent;
chiselGlobalElement.textContent = allCssContent;
}
this.lastVaultScan = now;
this.autoloadedSnippetsInitialized = true;
}
updateModeClasses() {
const body = document.body;
const leafContentEl = document.querySelector(
".mod-root .workspace-leaf.mod-active .workspace-leaf-content",
);
if (!leafContentEl) return;
this.clearModeClasses();
this.clearModeViewClasses();
let newMode = null;
const dataType = leafContentEl.getAttribute("data-type");
switch (dataType) {
case "markdown":
body.classList.add("chisel-note");
this.addClassToViews("chisel-note");
const dataMode = leafContentEl.getAttribute("data-mode");
if (dataMode === "preview") {
newMode = "reading";
body.classList.add("chisel-reading");
this.addClassToViews("chisel-reading");
} else if (dataMode === "source") {
newMode = "editing";
body.classList.add("chisel-editing");
this.addClassToViews("chisel-editing");
}
break;
case "canvas":
newMode = "canvas";
body.classList.add("chisel-canvas");
this.addClassToViews("chisel-canvas");
break;
case "empty":
newMode = "empty";
body.classList.add("chisel-empty");
this.addClassToViews("chisel-empty");
break;
case "webviewer":
newMode = "webviewer";
body.classList.add("chisel-webviewer");
this.addClassToViews("chisel-webviewer");
break;
case "bases":
newMode = "base";