forked from clairefro/obsidian-plugin-chronos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
1426 lines (1240 loc) · 38.8 KB
/
main.ts
File metadata and controls
1426 lines (1240 loc) · 38.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
import {
Plugin,
App,
Setting,
PluginSettingTab,
Notice,
Editor,
TFile,
TFolder,
SecretComponent,
} from "obsidian";
import { ChronosPluginSettings } from "./types";
import { TextModal } from "./components/TextModal";
import { FolderListModal } from "./components/FolderListModal";
import { ChangelogView, CHANGELOG_VIEW_TYPE } from "./components/ChangelogView";
import { knownLocales } from "./util/knownLocales";
import { CacheUtils } from "./util/CacheUtils";
import { FileUtils } from "./util/FileUtils";
import {
DEFAULT_LOCALE,
PROVIDER_DEFAULT_MODELS,
DETECTION_PATTERN_TEXT,
DETECTION_PATTERN_HTML,
DETECTION_PATTERN_CODEBLOCK,
} from "./constants";
// HACKY IMPORT TO ACCOMODATE SYMLINKS IN LOCAL DEV
import * as ChronosLib from "chronos-timeline-md";
const ChronosTimeline: any =
(ChronosLib as any).ChronosTimeline ??
(ChronosLib as any).default ??
(ChronosLib as any);
// Debug: uncomment to inspect what was loaded if needed
// console.debug('Chronos lib exports:', ChronosLib);
const DEFAULT_SETTINGS: ChronosPluginSettings = {
selectedLocale: DEFAULT_LOCALE,
align: "left",
clickToUse: false,
roundRanges: false,
useUtc: true,
useAI: true,
showChangelogOnUpdate: true,
enableCaching: false,
};
export default class ChronosPlugin extends Plugin {
settings: ChronosPluginSettings;
private observedEditors = new Set<HTMLElement>();
cacheUtils: CacheUtils;
private fileUtils: FileUtils;
async onload() {
console.log("Loading Chronos Timeline Plugin....");
this.settings = {
...DEFAULT_SETTINGS,
...(await this.loadData()),
};
// Register the changelog view
// Pass settings and callback to ChangelogView
this.registerView(
CHANGELOG_VIEW_TYPE,
(leaf) =>
new ChangelogView(leaf, [], {
showChangelogOnUpdate:
this.settings.showChangelogOnUpdate ?? true,
onToggleNotification: async (newValue: boolean) => {
this.settings.showChangelogOnUpdate = newValue;
await this.saveSettings();
},
}),
);
// Remove old insecure aiKeys property (LEGACY)
if ((this.settings as any).aiKeys) {
delete (this.settings as any).aiKeys;
await this.saveSettings();
}
// Remove legacy key property (LEGACY LEGACY)
if ((this.settings as any).key) {
delete (this.settings as any).key;
await this.saveSettings();
}
this.cacheUtils = new CacheUtils(this);
this.fileUtils = new FileUtils(this);
// Load persistent cache or initialize if it doesn't exist (only if caching is enabled)
if (this.settings.enableCaching) {
await this.cacheUtils.loadCache();
}
this.addSettingTab(new ChronosPluginSettingTab(this.app, this));
// Initialize folder cache in background to track which folders contain chronos blocks (only if caching is enabled)
if (this.settings.enableCaching) {
this.cacheUtils.initializeFolderCache();
}
this.registerEvent(
this.app.vault.on("rename", async (file, oldPath) => {
await this.fileUtils.updateWikiLinks(oldPath, file.path);
}),
);
// Invalidate cache when files are modified, created, or deleted (check if caching is enabled)
this.registerEvent(
this.app.vault.on("modify", (file) => {
if (
this.settings.enableCaching &&
file instanceof TFile &&
file.extension === "md"
) {
this.cacheUtils.invalidateFolderCache(file.parent);
}
}),
);
this.registerEvent(
this.app.vault.on("create", (file) => {
if (
this.settings.enableCaching &&
file instanceof TFile &&
file.extension === "md"
) {
this.cacheUtils.invalidateFolderCache(file.parent);
}
}),
);
this.registerEvent(
this.app.vault.on("delete", (file) => {
if (
this.settings.enableCaching &&
file instanceof TFile &&
file.extension === "md"
) {
this.cacheUtils.invalidateFolderCache(file.parent);
}
}),
);
this.registerMarkdownCodeBlockProcessor(
"chronos",
this._renderChronosBlock.bind(this),
);
this.registerMarkdownPostProcessor((element, context) => {
const inlineCodes = element.querySelectorAll("code");
inlineCodes.forEach((codeEl) => {
if (codeEl.closest("pre")) return; // Skip fenced code blocks
let match;
if (
(match = DETECTION_PATTERN_HTML.exec(
codeEl.textContent ?? "",
)) !== null
) {
const date_match = /\[.*?\]/.exec(match[1]);
codeEl.textContent =
date_match == null
? "Chronos Error format..."
: new Date(
date_match[0].slice(1, -1),
).toLocaleDateString(
this.settings.selectedLocale,
{
month: "short",
day: "2-digit",
year: "2-digit",
},
);
}
});
});
this.addCommand({
id: "insert-timeline-blank",
name: "Insert timeline (blank)",
editorCallback: (editor, _view) => {
this._insertSnippet(editor, ChronosTimeline.templates.blank);
},
});
this.addCommand({
id: "insert-timeline-basic",
name: "Insert timeline example (basic)",
editorCallback: (editor, _view) => {
this._insertSnippet(editor, ChronosTimeline.templates.basic);
},
});
this.addCommand({
id: "insert-timeline-advanced",
name: "Insert timeline example (advanced)",
editorCallback: (editor, _view) => {
this._insertSnippet(editor, ChronosTimeline.templates.advanced);
},
});
this.addCommand({
id: "generate-timeline-folder",
name: "Generate timeline from folder",
editorCallback: (editor, _view) => {
this._generateTimelineFromFolder(editor);
},
});
this.addCommand({
id: "generate-timeline-ai",
name: "Generate timeline with AI",
editorCheckCallback: (checking, editor, _view) => {
if (checking) {
return this.settings.useAI;
} else {
this._generateTimelineWithAi(editor);
}
},
});
// Check for new versions and show changelog
this.app.workspace.onLayoutReady(async () => {
await this._checkAndShowChangelog();
});
}
onunload() {
// Clean up resize observers
this.observedEditors.forEach((editorEl) => {
const observer = (editorEl as any)._chronosResizeObserver;
if (observer) {
observer.disconnect();
delete (editorEl as any)._chronosResizeObserver;
}
});
this.observedEditors.clear();
console.log("Chronos plugin unloaded, all observers cleaned up");
}
async loadSettings() {
this.settings = {
...DEFAULT_SETTINGS,
...(await this.loadData()),
};
}
async saveSettings() {
const currentData = (await this.loadData()) || {};
const dataToSave = { ...currentData, ...this.settings };
await this.saveData(dataToSave);
}
private _insertSnippet(editor: Editor, snippet: string) {
const cursor = editor.getCursor();
editor.replaceRange(snippet, cursor);
}
private _insertTextAfterSelection(editor: Editor, textToInsert: string) {
const cursor = editor.getCursor("to");
const padding = "\n\n";
editor.replaceRange(padding + textToInsert, cursor);
}
/* Utility method to get current editor width */
private _getCurrentEditorWidth(container: HTMLElement): number {
const editorEl = container.closest(
".markdown-source-view",
) as HTMLElement;
if (editorEl) {
return editorEl.offsetWidth;
}
return 0;
}
/* Utility method to update width */
private _updateChronosWidth(container: HTMLElement, newWidth: number) {
const editorEl = container.closest(
".markdown-source-view",
) as HTMLElement;
if (editorEl) {
editorEl.style.setProperty(
"--chronos-editor-width",
`${newWidth}px`,
);
}
}
/* Setup ResizeObserver to track editor size changes */
private _setupEditorResizeObserver(container: HTMLElement) {
// Function to attempt finding the editor element
const attemptSetup = (attempt = 1) => {
const editorEl = container.closest(
".markdown-source-view",
) as HTMLElement;
if (!editorEl && attempt <= 5) {
// Wait and try again - DOM might not be ready
setTimeout(() => attemptSetup(attempt + 1), attempt * 100);
return;
}
if (!editorEl) {
console.log(
"Could not find .markdown-source-view element after 5 attempts",
);
// Debug: log the container's ancestors
let parent = container.parentElement;
let level = 0;
while (parent && level < 10) {
parent = parent.parentElement;
level++;
}
return;
}
// skip adding obeserver if already exists
if (this.observedEditors.has(editorEl)) {
return;
}
let lastWidth = editorEl.offsetWidth;
// Create ResizeObserver to watch for actual size changes
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const currentWidth = entry.contentRect.width;
if (currentWidth !== lastWidth) {
lastWidth = currentWidth;
// Only update if there are expanded chronos blocks in this editor
const hasExpanded = editorEl.querySelector(
".chronos-width-expanded",
);
if (hasExpanded && currentWidth > 0) {
// Update the CSS custom property so expanded timelines resize
editorEl.style.setProperty(
"--chronos-editor-width",
`${currentWidth}px`,
);
}
}
}
});
try {
resizeObserver.observe(editorEl);
} catch (error) {
console.error("Failed to observe editor element:", error);
}
this.observedEditors.add(editorEl);
// Store the observer so we can remove it later
(editorEl as any)._chronosResizeObserver = resizeObserver;
};
// Start the attempt process
attemptSetup();
}
/* Create and setup the width toggle button */
private _createWidthToggleButton(container: HTMLElement): {
button: HTMLButtonElement;
icon: HTMLSpanElement;
} {
const button = container.createEl("button", {
cls: "chronos-width-toggle",
attr: { title: "Toggle timeline width" },
});
const icon = button.createEl("span", { text: "⟷" });
return { button, icon };
}
/* Expand timeline to full editor width */
private _expandTimeline(
container: HTMLElement,
icon: HTMLSpanElement,
): boolean {
const grandparent = this._getTimelineGrandparent(container);
if (!grandparent) return false;
const editorWidth = this._getCurrentEditorWidth(container);
if (editorWidth <= 0) return false;
this._updateChronosWidth(container, editorWidth);
grandparent.addClass("chronos-width-expanded");
icon.textContent = "↔";
return true;
}
/* Collapse timeline to normal width */
private _collapseTimeline(
container: HTMLElement,
icon: HTMLSpanElement,
): void {
const grandparent = this._getTimelineGrandparent(container);
if (!grandparent) return;
grandparent.removeClass("chronos-width-expanded");
icon.textContent = "⟷";
}
/* Get the timeline's grandparent element for width manipulation */
private _getTimelineGrandparent(
container: HTMLElement,
): HTMLElement | null {
const grandparent = container.closest(
".cm-lang-chronos.cm-preview-code-block",
) as HTMLElement;
return grandparent;
}
/* Trigger timeline refit after width changes */
private _refitTimeline(timeline: any): void {
setTimeout(() => {
if (timeline?.timeline) {
timeline.timeline.redraw();
timeline.timeline.fit();
}
}, 300);
}
private _renderChronosBlock(source: string, el: HTMLElement) {
// HACK for preventing triple propogation of mouseDown handler
let lastEventTime = 0;
const THROTTLE_MS = 500;
const container = el.createEl("div", {
cls: "chronos-timeline-container",
});
// Create width toggle button
const { button: widthToggleBtn, icon: toggleIcon } =
this._createWidthToggleButton(container);
let isExpanded = false;
// Clean toggle logic
const toggleWidth = () => {
if (!isExpanded) {
isExpanded = this._expandTimeline(container, toggleIcon);
} else {
this._collapseTimeline(container, toggleIcon);
isExpanded = false;
}
// Refit timeline after width change
this._refitTimeline(timeline);
};
widthToggleBtn.addEventListener(
"click",
(e) => {
e.stopPropagation();
e.stopImmediatePropagation();
e.preventDefault();
toggleWidth();
},
true,
);
// Setup ResizeObserver to track editor size changes
this._setupEditorResizeObserver(container);
// disable touch event propogation on containainer so sidebars don't interfer on mobile when swiping timeline
["touchstart", "touchmove", "touchend"].forEach((evt) => {
container.addEventListener(
evt,
(e) => {
e.stopPropagation();
},
{ passive: false },
);
});
const timeline = new ChronosTimeline({
container,
settings: this.settings,
});
try {
timeline.render(source);
// handle note linking
timeline.on("mouseDown", (event: any) => {
const now = performance.now();
if (now - lastEventTime < THROTTLE_MS) {
event.event.stopImmediatePropagation();
event.event.preventDefault();
return;
}
lastEventTime = now;
// Stop event immediately
if (event.event instanceof MouseEvent) {
event.event.stopImmediatePropagation();
event.event.preventDefault();
const itemId = event.item;
if (!itemId) return;
const item = timeline.items?.find(
(i: any) => i.id === itemId,
);
if (!item?.cLink) return;
// Check for middle click or CMD+click (Mac)
const isMiddleClick = event.event.button === 1;
const isCmdClick =
event.event.metaKey && event.event.button === 0;
const isShiftClick = event.event.shiftKey;
const shouldOpenInNewLeaf =
isMiddleClick || isCmdClick || isShiftClick;
this.fileUtils.openFileFromWikiLink(
item.cLink,
shouldOpenInNewLeaf,
);
}
});
// Add hover preview for linked notes
timeline.on("itemover", async (event: any) => {
const itemId = event.item;
if (itemId) {
const item = timeline.items?.find(
(i: any) => i.id === itemId,
);
if (item?.cLink) {
// Get the target element to show hover on
const targetEl = event.event.target as HTMLElement;
// Use Obsidian's built-in hover preview
this.app.workspace.trigger("hover-link", {
event: event.event,
source: "chronos-timeline",
hoverParent: container,
targetEl: targetEl,
linktext: item.cLink,
});
}
}
});
// Close item preview on item out
timeline.on("itemout", () => {
// Force close any open hovers
this.app.workspace.trigger("hover-link:close");
});
// Add click to use functionality and UI hints if,enabled
if (this.settings.clickToUse && container) {
timeline.timeline?.setOptions({
clickToUse: this.settings.clickToUse,
});
timeline.on("mouseOver", (e: any) => {
if (
this.settings.clickToUse &&
!container.querySelectorAll(".vis-active").length
) {
// Tooltip removed due to deprecation
} else {
// Tooltip removed due to deprecation
}
});
}
} catch (error) {
console.log(error);
}
}
private async _generateTimelineWithAi(editor: Editor) {
if (!editor) {
new Notice(
"Make sure you are highlighting text in your note to generate a timeline from",
);
}
const selection = this._getCurrentSelectedText(editor);
if (!selection) {
new Notice(
"Highlight some text you'd like to convert into a timeline, then run the generate command again",
);
return;
}
// open loading modal
const provider = (this.settings as any).aiProvider || "openai"; // backwards compatibility: OpenAI used to be sole provider
const apiKey = this._getApiKey(provider);
if (!apiKey) {
new Notice(
`No API Key found for ${provider}. Please add an API key in Chronos Timeline Plugin Settings`,
);
return;
}
const model =
(this.settings as any).aiModels?.[provider] ||
(PROVIDER_DEFAULT_MODELS as any)[provider];
const loadingModal = new TextModal(
this.app,
`Working on it.... (Provider: ${provider}, Model: ${model})`,
);
loadingModal.open();
try {
const chronos = await this._textToChronos(selection);
chronos && this._insertTextAfterSelection(editor, chronos);
} catch (e) {
console.error(e);
loadingModal.setText(e.message);
return;
}
loadingModal.close();
}
private async _textToChronos(selection: string): Promise<string | void> {
// Determine provider (if settings include selection) otherwise default to openai
const provider = (this.settings as any).aiProvider || "openai"; // backwards compatibility: OpenAI used to be sole provider
const apiKey = this._getApiKey(provider);
if (!apiKey) {
new Notice(
`No API Key found for ${provider}. Please add an API key in Chronos Timeline Plugin Settings`,
);
return;
}
const model =
(this.settings as any).aiModels?.[provider] ||
(PROVIDER_DEFAULT_MODELS as any)[provider];
const { GenAi } = await import("./lib/ai/GenAi.js");
const res = await new GenAi(provider, apiKey, model).toChronos(
selection,
);
return res;
}
private _getApiKey(provider: string = "openai"): string | null {
const secretName = (this.settings as any)[`${provider}SecretName`];
if (!secretName) return null;
return this.app.secretStorage.getSecret(secretName);
}
private _getCurrentSelectedText(editor: Editor): string {
return editor ? editor.getSelection() : "";
}
// Ensure latest data is fetched before inserting combined timeline
private async _generateTimelineFromFolder(editor: Editor) {
try {
const allFolders = this.app.vault.getAllFolders();
// If caching is enabled, filter to folders with chronos items
// If caching is disabled, show all folders
const foldersToShow = this.settings.enableCaching
? allFolders.filter((folder) => {
const cached = this.cacheUtils.folderChronosCache.get(
folder.path,
);
return (cached ?? 0) > 0;
})
: allFolders;
if (foldersToShow.length === 0) {
new Notice(
this.settings.enableCaching
? "No folders contain chronos items (yet!)"
: "No folders found in vault",
);
return;
}
new FolderListModal(
this.app,
foldersToShow,
async (f: TFolder) => {
const folderPath = f.path;
// Update cache for the selected folder and its children (only if caching is enabled)
if (this.settings.enableCaching) {
await this.cacheUtils.updateFolderCache(f);
}
// Recursively get all files in this folder and subfolders
const allFiles = this.fileUtils.getAllFilesInFolder(f);
let extracted: string[] = []; // Keep the name as `extracted`
const tasks: Promise<string[]>[] = allFiles
.filter((file: TFile) => file.extension === "md")
.map((file: TFile) => {
return this.app.vault
.cachedRead(file as TFile)
.then((text) => {
const rex_match: string[] = [];
let current_match;
// Extract inline chronos blocks (check for indicators)
const inlineMatches = [];
while (
(current_match =
DETECTION_PATTERN_TEXT.exec(
text,
)) !== null
) {
const content =
current_match[1] as string;
const trimmed = content.trim();
const hasIndicator = /^[-@*~]/.test(
trimmed,
);
inlineMatches.push(
hasIndicator
? trimmed
: `- ${trimmed}`,
);
}
// Extract full chronos code blocks (check for indicators)
while (
(current_match =
DETECTION_PATTERN_CODEBLOCK.exec(
text,
)) !== null
) {
// Extract all non-blank, non-comment lines from the code block
const blockContent = current_match[1];
const lines = blockContent.split("\n");
lines.forEach((line) => {
const trimmed = line.trim();
// Include any line that isn't blank, doesn't start with #, and doesn't start with > (flags)
if (
trimmed &&
!trimmed.startsWith("#") &&
!trimmed.startsWith(">")
) {
// Check if line already has an indicator (-, @, *, etc)
const hasIndicator =
/^[-@*~]/.test(trimmed);
rex_match.push(
hasIndicator
? trimmed
: `- ${trimmed}`,
);
}
});
}
// Combine all matches (already have prefixes applied)
return [...inlineMatches, ...rex_match];
})
.catch((_error) => {
new Notice(
`Error while processing ${file.name}`,
);
return [];
});
});
await Promise.allSettled(tasks).then((results) => {
results.forEach((result) => {
if (result.status === "fulfilled") {
extracted = extracted.concat(result.value);
}
});
if (extracted.length === 0) {
new Notice(
`No chronos items found in ${folderPath}`,
);
return;
}
const heightFlag =
extracted.length > 26 ? "> HEIGHT 300\n" : "";
this._insertSnippet(
editor,
ChronosTimeline.templates.blank.replace(
/^\s*$/m,
heightFlag + extracted.join("\n"),
),
);
new Notice(
`Combined ${extracted.length} Chronos item${extracted.length !== 1 ? "s" : ""} found in ${folderPath}`,
);
});
},
this.settings.enableCaching
? this.cacheUtils.folderChronosCache
: undefined,
() => this.settings.enableCaching ?? false,
).open();
} catch (error) {
new Notice("Error scanning for chronos items");
console.error("Error in _generateTimelineFromFolder:", error);
}
}
// Changelog methods
private async _checkAndShowChangelog(): Promise<void> {
// Skip if user disabled changelog notifications
if (this.settings.showChangelogOnUpdate === false) {
return;
}
const currentVersion = this.manifest.version;
const lastSeenVersion = this.settings.lastSeenVersion;
// If no lastSeenVersion, show the current version's changelog (first install)
if (!lastSeenVersion) {
const unseenChangelogs = await this._getUnseenChangelogs(
"0.0.0", // Get all changelogs up to current version
currentVersion,
);
if (unseenChangelogs.length > 0) {
await this._showChangelogNote(unseenChangelogs);
// Set lastSeenVersion to current after successfully showing
this.settings.lastSeenVersion = currentVersion;
await this.saveSettings();
}
return;
}
// If same version, skip
if (lastSeenVersion === currentVersion) {
return;
}
// Get unseen changelogs
const unseenChangelogs = await this._getUnseenChangelogs(
lastSeenVersion,
currentVersion,
);
if (unseenChangelogs.length > 0) {
// Show changelog modal
await this._showChangelogNote(unseenChangelogs);
// Update last seen version after successfully showing
this.settings.lastSeenVersion = currentVersion;
await this.saveSettings();
}
}
private async _showChangelogNote(
entries: { version: string; date: string; content: string }[],
): Promise<void> {
// Don't create view if no entries
if (!entries || entries.length === 0) {
return;
}
// Check if a changelog view is already open
const existingLeaves =
this.app.workspace.getLeavesOfType(CHANGELOG_VIEW_TYPE);
if (existingLeaves.length > 0) {
// Close existing views first
for (const leaf of existingLeaves) {
leaf.detach();
}
}
// Create a new leaf and open the changelog view
const leaf = this.app.workspace.getLeaf("tab");
await leaf.setViewState({
type: CHANGELOG_VIEW_TYPE,
active: true,
});
// Update the view with the new entries
const view = leaf.view as ChangelogView;
if (view) {
(view as any).entries = entries;
await view.onOpen();
}
}
private async _getUnseenChangelogs(
lastSeenVersion: string,
currentVersion: string,
): Promise<{ version: string; date: string; content: string }[]> {
try {
const releases = await this._fetchGitHubReleases();
const unseenEntries: {
version: string;
date: string;
content: string;
}[] = [];
for (const release of releases) {
// Extract version from tag (e.g., "v3.0.0" or "3.0.0")
const version = release.tag_name.replace(/^v/, "");
// Include if version is greater than lastSeenVersion and <= currentVersion
const comparisonToLast = this._compareVersions(
version,
lastSeenVersion,
);
const comparisonToCurrent = this._compareVersions(
version,
currentVersion,
);
if (comparisonToLast > 0 && comparisonToCurrent <= 0) {
// Check if this is a patch release (x.x.non-zero)
const isPatchRelease = this._isPatchRelease(version);
const hasIncludeComment = release.body
?.trim()
.toLowerCase()
.replace(/\s+/g, "")
.startsWith("<!--include-->");
// Skip patch releases unless they have the <!-- include --> comment
if (isPatchRelease && !hasIncludeComment) {
continue;
}
unseenEntries.push({
version,
date: release.published_at,
content: release.body || "No release notes available.",
});
}
}
// Sort by published date descending (newest first)
unseenEntries.sort((a, b) => {
return new Date(b.date).getTime() - new Date(a.date).getTime();
});
// Limit to 4 most recent releases
return unseenEntries.slice(0, 4);
} catch (error) {
console.error(
"[Chronos] Error fetching changelogs from GitHub:",
error,
);
// Silently fail - don't show notice to user
return [];
}
}
private async _fetchGitHubReleases(): Promise<any[]> {
const url =
"https://api.github.com/repos/clairefro/obsidian-plugin-chronos/releases";
try {
const response = await fetch(url, {
headers: {
Accept: "application/vnd.github.v3+json",
},
});
if (!response.ok) {
throw new Error(
`GitHub API returned ${response.status}: ${response.statusText}`,
);
}
const releases = await response.json();
return releases;
} catch (error) {
console.error("[Chronos] Failed to fetch GitHub releases:", error);
throw error;
}
}
private _compareVersions(v1: string, v2: string): number {
const parts1 = v1.split(".").map(Number);
const parts2 = v2.split(".").map(Number);
for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
const part1 = parts1[i] || 0;
const part2 = parts2[i] || 0;
if (part1 > part2) return 1;
if (part1 < part2) return -1;
}
return 0;
}