-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
executable file
·1233 lines (1042 loc) · 39.7 KB
/
main.ts
File metadata and controls
executable file
·1233 lines (1042 loc) · 39.7 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 { DBSchema, IDBPDatabase, openDB } from 'idb';
import ThumbnailCacheWorker from 'inline-worker:./workers/thumbnail-cache.worker.ts';
import { App, CachedMetadata, Editor, getLinkpath, ItemView, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, prepareSimpleSearch, SectionCache, Setting, setTooltip, TAbstractFile, TFile, WorkspaceLeaf } from 'obsidian';
import gjako, { GjakoConfig, UploadResult } from 'services/gjako';
import { Accessor, createEffect, createMemo, createRoot, createSignal, Setter } from 'solid-js';
import { createStore, produce, SetStoreFunction } from 'solid-js/store';
import { createComponent, render } from 'solid-js/web';
import { Annotation, AnnotationsByURL, isImageLink, Picture, PicturesByPath, UploadResultDict } from 'types/picture';
import type { ThumbnailWorkerDone, ThumbnailWorkerRequest, ThumbnailWorkerResponse } from 'types/thumbnail-worker';
import { thumbnailCacheKey } from 'utils/cache-key';
import { debugLog } from 'utils/debug';
import { isRemoteHttpURL } from 'utils/url';
import { ActivePics, Gallery, ImageUpload, PicsExplorer, UploadResultSummary } from 'views/images';
export type { PskDBSchema };
const NAME = 'Picsake';
const LANG = 'psk';
const ICON = 'images';
const GALLERY_ID = 'psk-gallery-container';
const THUMBNAIL_WORKER_CONCURRENCY = 8;
const NIL = 'nil';
// function getSectionsOfType(type: 'code' | 'paragraph', fileCache: CachedMetadata): SectionCache[] {
// if (!fileCache.sections) return [];
// return fileCache.sections.filter(section => section.type === type);
// }
function getSectionsOfInterest(fileCache: CachedMetadata) {
const codeblocks: SectionCache[] = [];
const paragraphs: SectionCache[] = [];
if (fileCache.sections) {
for (const section of fileCache.sections) {
if (section.type === 'code') {
codeblocks.push(section);
} else if (section.type === 'paragraph') {
paragraphs.push(section);
}
}
}
return { codeblocks, paragraphs };
}
// function shouldHandleTargetImage(target: HTMLImageElement): boolean {
// // const isPicsExplorerView = target.closest(`[data-type="${VIEW_TYPE_PICS_EXPLORER}"]`) !== null;
// const isMarkdownView = target.closest('.workspace-leaf-content[data-type="markdown"]') !== null;
// return isMarkdownView;
// }
// function findPeerImages(target: HTMLImageElement): HTMLImageElement[] {
// const isReadingView = target.closest('.markdown-reading-view') !== null;
// const isLivePreview = target.closest('.markdown-source-view.is-live-preview') !== null;
// if (isLivePreview) {
// // Note: embedded local images are NOT among top-level siblings like remote ones!
// // const nodes = target.parentElement?.querySelectorAll('img:not(.psk-thumbnail)');
// const closestAncestor = target.closest('.cm-content');
// const imgNodes = closestAncestor?.querySelectorAll('img:not(.psk-thumbnail)') ?? [];
// return Array.from(imgNodes) as HTMLImageElement[];
// } else if (isReadingView) {
// const nodes = document.querySelectorAll('.markdown-reading-view img:not(.psk-thumbnail)');
// return Array.from(nodes) as HTMLImageElement[];
// } else {
// return [];
// }
// }
// function delay(ms: number): Promise<void> {
// return new Promise(resolve => setTimeout(resolve, ms));
// }
type Settings = {
explorerPageSize: number | null,
excludePaths: string[],
uploadImagesOnPaste: boolean,
cacheThumbnails: boolean,
gjako: GjakoConfig,
};
const DEFAULT_SETTINGS: Settings = {
explorerPageSize: 20,
excludePaths: [],
uploadImagesOnPaste: false,
cacheThumbnails: false,
gjako: gjako.DEFAULT_CONFIG,
}
const DB_VERSION = 2;
interface PskDBSchema extends DBSchema {
thumbnails: {
key: string,
value: Blob,
}
}
type Store = {
pictures: PicturesByPath,
uploads: UploadResultDict,
annotations: AnnotationsByURL,
};
export default class PskPlugin extends Plugin {
// 0. States
settings!: Settings;
db!: IDBPDatabase<PskDBSchema>;
// Solid stuff
store!: Store;
private setStore!: SetStoreFunction<Store>;
private disposeEffect!: () => void;
activeFile!: Accessor<TFile | null>;
setActiveFile!: Setter<TFile | null>;
gallery!: Accessor<Picture[]>;
setGallery!: Setter<Picture[]>;
galleryFocus!: Accessor<number | null>;
setGalleryFocus!: Setter<number | null>;
galleryFit!: Accessor<boolean>;
setGalleryFit!: Setter<boolean>;
galleryZoom!: Accessor<number>;
setGalleryZoom!: Setter<number>;
showPicDescription!: Accessor<boolean>;
setShowPicDescription!: Setter<boolean>;
translateX!: Accessor<number>;
setTranslateX!: Setter<number>;
translateY!: Accessor<number>;
setTranslateY!: Setter<number>;
// Make settings reactive!
explorerPageSize!: Accessor<number | null>;
setExplorerPageSize!: Setter<number | null>;
excludePaths!: Accessor<string[]>;
setExcludePaths!: Setter<string[]>;
cacheThumbnails!: Accessor<boolean>;
setCacheThumbnails!: Setter<boolean>;
// Thumbnail caching job control
private thumbnailCacheInFlight = false;
private pendingThumbnailURLs = new Set<string>();
// 1. Class fields as arrow functions
// Advantage over using class methods: `this` always refers to the class instance!
// No need for manual bind(this)
// Note: this is also called on file creation!
onFileCacheChanged = (file: TFile, newContent: string, cache: CachedMetadata) => {
const { codeblocks, paragraphs } = getSectionsOfInterest(cache);
const pictures = this.extractPicturesFromFile(file, newContent, paragraphs);
if (pictures.length > 0) {
this.setStore('pictures', file.path, pictures);
if (this.settings.cacheThumbnails) {
this.generateThumbnailCache(pictures);
}
} else {
this.setStore('pictures', produce(pictures => {
delete pictures[file.path];
}));
}
const { uploads } = this.extractPictureMetadataFromFile(file, newContent, codeblocks);
uploads.forEach(upload => {
this.setStore('uploads', upload.url, upload);
});
}
onFileRename = (newFile: TAbstractFile, oldPath: string) => {
if (this.activeFile()?.path === oldPath) {
// Note: newFile is NOT a TFile
// Note: alternatively, use `this.app.workspace.getActiveFile()`
this.setActiveFile(this.app.vault.getFileByPath(newFile.path));
}
const oldPictures = this.store.pictures[oldPath];
if (!oldPictures || oldPictures.length === 0) return;
this.setStore('pictures', produce(pictures => {
delete pictures[oldPath];
pictures[newFile.path] = oldPictures;
}));
new Notice(`${oldPictures.length} pictures moved from ${oldPath} to ${newFile.path}`);
}
onFileDelete = (file: TAbstractFile) => {
const oldPictures = this.store.pictures[file.path];
if (!oldPictures) return;
this.setStore('pictures', produce(pictures => {
delete pictures[file.path];
}));
new Notice(`${oldPictures.length} pictures deleted from ${file.path}`);
}
onActivateFile = (file: TFile | null) => {
// new Notice(`Activated ${file?.name}`);
this.setActiveFile(file);
// FIXME this doesn't dynamically update the tooltip text;
// somehow the Outline core plugin is able to update correctly, what's the API?
// const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_ACTIVE_PICS);
// for (const leaf of leaves) {
// // ???
// }
}
onPaste = (evt: ClipboardEvent, editor: Editor) => {
// https://docs.obsidian.md/Reference/TypeScript+API/Workspace/on('editor-paste')
// Check for evt.defaultPrevented before attempting to handle this event, and return if it has been already handled.
// Use evt.preventDefault() to indicate that you've handled the event.
if (evt.defaultPrevented) return;
const files = evt.clipboardData?.files;
if (!files) return;
const images = Array.from(files).filter((file) => file.type.startsWith('image/'));
if (images.length === 0) return;
// We have to use the blocking `window.confirm` dialogue to give users the option to use Obsidian's default pasting handler.
// const ok = window.confirm(`Upload ${images.length} images e.g. ${images[0]?.name}?`);
if (this.settings.uploadImagesOnPaste) {
evt.preventDefault();
new ImageUploadModal(this.app, this.settings, images,
{
onConfirm: async (selected, isPhoto, subDir) => {
new Notice(`Selected ${selected.size} images to upload`);
const res = await gjako.uploadImages(selected, isPhoto, subDir, this.settings.gjako);
const infoBlock = `\`\`\`${LANG}\n${JSON.stringify({ uploads: res }, null, '\t')}\n\`\`\``;
const imgMarkdown = res.map(info => ``).join('\n\n');
editor.replaceSelection(`${infoBlock}\n\n${imgMarkdown}`);
},
onCancel: () => { new Notice('No action is taken'); }
}
).open();
}
}
onClickDocument = (evt: PointerEvent) => {
if (evt.target) {
const targetEl = evt.target as HTMLElement;
if (targetEl instanceof HTMLImageElement) {
// Note: for our custom view like PicsExplorer, we don't have to trigger the Gallery modal from here, because we have full control of the UI;
// We do the following only in places where we don't have control, e.g. the Markdown view. (Well, technically we could, via editor extensions etc.)
// const picsExplorerView = this.app.workspace.getActiveViewOfType(PicsExplorerView);
//
// Note: if Gallery modal is already activated, then we shouldn't handle the click, o/w clicking the focused picture of the gallery will also trigger the handler here!
// Alternatively, we could use the old approach, which is a tad hacky, but safe from this false positive:
// const isMarkdownView = targetEl.closest('.workspace-leaf-content[data-type="markdown"]') !== null;
// if (isMarkdownView) {
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView && this.galleryFocus() === null) {
evt.preventDefault();
// Note: DOM cannot be used as a reliable source, because of lazy loading;
// We therefore have to use our global state obtained from parsing the Markdown source.
// see `extractPicturesFromFile`
const activeFile = this.activeFile();
if (activeFile) {
const gallery: Picture[] = this.store.pictures[activeFile.path] ?? [];
this.setGallery(gallery);
const targetIndex = gallery.map(pic => pic.url).indexOf(targetEl.src);
this.setGalleryFocus(targetIndex >= 0 ? targetIndex : null);
}
}
}
}
}
openActivePicsView = async (show: boolean) => {
const { workspace } = this.app;
let leaf: WorkspaceLeaf | null = null;
const leaves = workspace.getLeavesOfType(VIEW_TYPE_ACTIVE_PICS);
if (leaves[0]) {
// A leaf with our view already exists, use that
leaf = leaves[0];
} else {
// Our view could not be found in the workspace, create a new leaf
// in the right sidebar for it
leaf = workspace.getRightLeaf(false);
if (leaf) {
// console.log(`leaf: ${leaf.getViewState().type}`);
await leaf.setViewState({ type: VIEW_TYPE_ACTIVE_PICS, active: show });
// console.log(`leaf: ${leaf.getViewState().type}`);
} else {
// shouldn't happen!
new Notice('getRightLeaf failed');
}
}
// Reveal the leaf in case it is in a collapsed sidebar
if (leaf && show) await workspace.revealLeaf(leaf);
}
openPicsExplorerView = async () => {
const { workspace } = this.app;
let leaf: WorkspaceLeaf | null = null;
const leaves = workspace.getLeavesOfType(VIEW_TYPE_PICS_EXPLORER);
if (leaves[0]) {
// A leaf with our view already exists, use that
leaf = leaves[0];
} else {
// Our view could not be found in the workspace, create a new leaf
// in the right sidebar for it
leaf = workspace.getLeaf('tab');
await leaf?.setViewState({ type: VIEW_TYPE_PICS_EXPLORER, active: true });
}
// Reveal the leaf in case it is in a collapsed sidebar
if (leaf) await workspace.revealLeaf(leaf);
}
// Note: fts needs to be an arrow function instead of a class method because `this` binding is automatic;
// o/w we'd get TypeError: Cannot read properties of undefined (reading 'vault')
fts = async (query: string): Promise<string[]> => {
const searcher = prepareSimpleSearch(query);
const mdFiles = this.app.vault.getMarkdownFiles();
const matchedPaths = [];
for (const mdFile of mdFiles) {
const content = await this.app.vault.cachedRead(mdFile);
const searchResult = searcher(content);
if (searchResult !== null) matchedPaths.push(mdFile.path);
}
return matchedPaths;
}
// Used in `generateThumbnailCache`
cacheOneThumb = async (url: string): Promise<string> => {
if (!isRemoteHttpURL(url)) {
throw new Error(`Thumbnail caching only supports http/https URLs: ${url}`);
}
const thumb = await gjako.makeThumbnail(url, this.settings.gjako);
const key = thumbnailCacheKey(url);
return this.db.put('thumbnails', thumb, key);
}
private getThumbnailDBName(): string {
return `${NAME.toLowerCase()}-${this.app.appId}`;
}
private collectRemoteThumbnailURLs(pictures?: Picture[]): string[] {
const picsToCheck: Picture[] = pictures ?? Object.values(this.store.pictures).flat();
const urls = new Set<string>();
for (const pic of picsToCheck) {
if (!pic.localPath && isRemoteHttpURL(pic.url)) {
urls.add(pic.url);
}
}
return Array.from(urls);
}
private async runThumbnailCacheWorker(urls: string[]): Promise<ThumbnailWorkerDone['payload']> {
const msg: ThumbnailWorkerRequest = {
type: 'start',
payload: {
dbName: this.getThumbnailDBName(),
dbVersion: DB_VERSION,
urls,
gjako: {
urlPrefix: this.settings.gjako.urlPrefix,
apiKey: this.settings.gjako.apiKey,
},
concurrency: THUMBNAIL_WORKER_CONCURRENCY,
},
};
return new Promise((resolve, reject) => {
const worker = new ThumbnailCacheWorker({ name: `${NAME} Thumbnail Cache` });
const cleanup = () => {
worker.onmessage = null;
worker.onerror = null;
worker.terminate();
};
worker.onmessage = (event: MessageEvent<ThumbnailWorkerResponse>) => {
cleanup();
const data = event.data;
if (data.type === 'done') {
resolve(data.payload);
} else {
reject(new Error(data.payload.error));
}
};
worker.onerror = (event: ErrorEvent) => {
cleanup();
reject(new Error(event.message || 'Thumbnail worker crashed.'));
};
worker.postMessage(msg);
});
}
private async runThumbnailCacheOnMainThread(urls: string[]) {
const remoteKeyToURL = new Map<string, string>();
for (const url of urls) {
if (!isRemoteHttpURL(url)) continue;
const key = thumbnailCacheKey(url);
if (!remoteKeyToURL.has(key)) {
remoteKeyToURL.set(key, url);
}
}
const cached = await this.db.getAllKeys('thumbnails');
const cachedSet = new Set<string>(cached.map(key => String(key)));
const misses = cachedSet.size > 0
? [...remoteKeyToURL.keys()].filter(key => !cachedSet.has(key))
: Array.from(remoteKeyToURL.keys());
const results = await Promise.allSettled(
misses.map(key => this.cacheOneThumb(remoteKeyToURL.get(key)!))
);
const failed: string[] = [];
results.forEach((result, i) => {
if (result.status === 'rejected') {
const failedKey = misses[i];
const failedURL = failedKey ? remoteKeyToURL.get(failedKey) : undefined;
if (failedURL) failed.push(failedURL);
}
});
return {
cachedCount: cachedSet.size,
remoteCount: remoteKeyToURL.size,
attempted: misses.length,
failed,
};
}
private logThumbnailWarmupResult(source: 'worker' | 'main-thread', durationMs: number, result: {
cachedCount: number,
remoteCount: number,
attempted: number,
failed: string[],
}) {
console.log(
`[${NAME}] thumbnail warmup (${source}): remote=${result.remoteCount} cached=${result.cachedCount} attempted=${result.attempted} failed=${result.failed.length} in ${durationMs.toFixed(1)} ms`
);
if (result.failed.length > 0) {
debugLog({ failed: result.failed });
}
}
private queueThumbnailCache(urls: string[]) {
for (const url of urls) {
this.pendingThumbnailURLs.add(url);
}
if (this.thumbnailCacheInFlight) return;
void this.flushThumbnailCacheQueue();
}
private async flushThumbnailCacheQueue() {
if (this.thumbnailCacheInFlight) return;
this.thumbnailCacheInFlight = true;
try {
while (this.pendingThumbnailURLs.size > 0) {
const urls = Array.from(this.pendingThumbnailURLs);
this.pendingThumbnailURLs.clear();
console.log(`[${NAME}] thumbnail warmup queued: ${urls.length} urls`);
try {
const startedAt = performance.now();
const result = await this.runThumbnailCacheWorker(urls);
const durationMs = performance.now() - startedAt;
this.logThumbnailWarmupResult('worker', durationMs, result);
} catch (error) {
console.warn(`[${NAME}] Thumbnail worker failed; falling back to main thread.`, error);
const startedAt = performance.now();
const result = await this.runThumbnailCacheOnMainThread(urls);
const durationMs = performance.now() - startedAt;
this.logThumbnailWarmupResult('main-thread', durationMs, result);
}
}
} finally {
this.thumbnailCacheInFlight = false;
}
}
// 2. Overriding inherited class methods
async onload() {
const start = performance.now();
const [store, setStore] = createStore<Store>({
pictures: {},
uploads: {},
annotations: {},
});
// eslint-disable-next-line solid/reactivity
this.store = store;
this.setStore = setStore;
const [activeFile, setActiveFile] = createSignal<TFile | null>(null);
this.activeFile = activeFile;
this.setActiveFile = setActiveFile;
const [gallery, setGallery] = createSignal<Picture[]>([]);
this.gallery = gallery;
this.setGallery = setGallery;
const [galleryFocus, setGalleryFocus] = createSignal<number | null>(null);
this.galleryFocus = galleryFocus;
this.setGalleryFocus = setGalleryFocus;
const [galleryFit, setGalleryFit] = createSignal<boolean>(false);
this.galleryFit = galleryFit;
this.setGalleryFit = setGalleryFit;
const [galleryZoom, setGalleryZoom] = createSignal<number>(1);
this.galleryZoom = galleryZoom;
this.setGalleryZoom = setGalleryZoom;
const [showPicDescription, setShowPicDescription] = createSignal<boolean>(false);
this.showPicDescription = showPicDescription;
this.setShowPicDescription = setShowPicDescription;
const [translateX, setTranslateX] = createSignal<number>(0);
this.translateX = translateX;
this.setTranslateX = setTranslateX;
const [translateY, setTranslateY] = createSignal<number>(0);
this.translateY = translateY;
this.setTranslateY = setTranslateY;
// Note: This is not called when a file is renamed for performance reasons. You must hook the vault rename event for those.
this.registerEvent(this.app.metadataCache.on('changed', this.onFileCacheChanged, this));
this.registerEvent(this.app.vault.on('rename', this.onFileRename, this));
this.registerEvent(this.app.vault.on('delete', this.onFileDelete, this));
this.registerEvent(this.app.workspace.on('file-open', this.onActivateFile, this));
this.registerEvent(this.app.workspace.on('editor-paste', this.onPaste, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', this.onClickDocument);
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
// this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
// Critical importance: registerView must be done before `workspace.onLayoutReady`
// if we need to open a view leaf inside there,
// o/w `leaf.setViewState` can fail!
this.registerView(
VIEW_TYPE_ACTIVE_PICS,
(leaf) => new ActivePicsView(leaf, this)
);
this.registerView(
VIEW_TYPE_PICS_EXPLORER,
(leaf) => new PicsExplorerView(leaf, this)
);
this.registerMarkdownCodeBlockProcessor(LANG, (blockText, container, ctx) => {
const info = JSON.parse(blockText);
if (Object.hasOwn(info, 'uploads')) {
const uploads: UploadResult[] = info.uploads;
render(() => createComponent(UploadResultSummary, { uploads }), container);
}
});
await this.setupDB(); // this.db must be ready before calling `getAll` onLayoutReady
await this.loadSettings();
const [excludePaths, setExcludePaths] = createSignal<string[]>(this.settings.excludePaths);
this.excludePaths = excludePaths;
this.setExcludePaths = setExcludePaths;
const [explorerPageSize, setExplorerPageSize] = createSignal<number | null>(this.settings.explorerPageSize);
this.explorerPageSize = explorerPageSize;
this.setExplorerPageSize = setExplorerPageSize;
const [cacheThumbnails, setCacheThumbnails] = createSignal<boolean>(this.settings.cacheThumbnails);
this.cacheThumbnails = cacheThumbnails;
this.setCacheThumbnails = setCacheThumbnails;
// Important: this is where we do stuff on startup, w/o slowing down Obsidian startup
this.app.workspace.onLayoutReady(async () => {
const start = performance.now();
// new Notice('Workspace layout is ready!');
// 0. States
this.setActiveFile(this.app.workspace.getActiveFile());
const mdFiles = this.app.vault.getMarkdownFiles();
for (const mdFile of mdFiles) {
const fileCache = this.app.metadataCache.getFileCache(mdFile);
if (!fileCache) continue;
const { codeblocks, paragraphs } = getSectionsOfInterest(fileCache);
if (paragraphs.length === 0) continue; // avoid `cachedRead` of the file if we know it contains no paragraphs!
const fileContent = await this.app.vault.cachedRead(mdFile);
const pictures = this.extractPicturesFromFile(mdFile, fileContent, paragraphs);
if (pictures.length === 0) continue;
this.setStore('pictures', mdFile.path, pictures);
// Note: we assume that the metadata are bound to the pictures present in the file;
// if no pictures are found in the file, we skip, ignoring any metadata (regarding them as broken references)
const { uploads } = this.extractPictureMetadataFromFile(mdFile, fileContent, codeblocks);
uploads.forEach(upload => {
this.setStore('uploads', upload.url, upload);
});
}
// cache thumbnails in IDB
if (this.settings.cacheThumbnails) {
this.generateThumbnailCache(); // Don't await!
}
// 1. DOM
// insert modal UI
const appContainer = document.querySelector('.app-container');
if (appContainer) {
const galleryContainer = document.createElement('div');
galleryContainer.id = GALLERY_ID;
appContainer.appendChild(galleryContainer);
render(() => createComponent(Gallery, {
gallery: this.gallery,
galleryFocus: this.galleryFocus,
setGalleryFocus: this.setGalleryFocus,
galleryFit: this.galleryFit,
setGalleryFit: this.setGalleryFit,
galleryZoom: this.galleryZoom,
setGalleryZoom: this.setGalleryZoom,
showPicDescription: this.showPicDescription,
setShowPicDescription: this.setShowPicDescription,
translateX: this.translateX,
setTranslateX: this.setTranslateX,
translateY: this.translateY,
setTranslateY: this.setTranslateY,
useThumbnailCache: this.cacheThumbnails,
db: this.db,
}), galleryContainer);
}
const finish = performance.now();
console.log(`[${NAME}] onLayoutReady: ${(finish - start).toFixed(1)} ms`);
});
// This creates an icon in the left ribbon.
this.addRibbonIcon(ICON, NAME, (evt: MouseEvent) => {
if (evt.metaKey) {
new OverviewModal(this.app, this).open();
} else {
this.openPicsExplorerView();
}
});
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
createRoot((dispose) => {
// this.register(dispose); // do it in `onunload` is more explicit
this.disposeEffect = dispose;
const picsCount = createMemo(() => {
const urlSet = new Set<string>();
const localSet = new Set<string>();
for (const pictures of Object.values(this.store.pictures)) {
for (const pic of pictures) {
urlSet.add(pic.url);
if (pic.localPath) localSet.add(pic.localPath);
}
}
return { total: urlSet.size, local: localSet.size };
});
const uploadCount = createMemo(() => {
return Object.keys(this.store.uploads).length;
});
createEffect(() => {
const { total, local } = picsCount();
statusBarItemEl.setText(`${total} pics`);
const uploads = uploadCount();
const uploadsTooltip = uploads > 0 ? `\n${uploads} uploaded` : '';
setTooltip(statusBarItemEl, `${local} local, ${total - local} remote${uploadsTooltip}`, { placement: 'top', delay: 200 });
});
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-active-pics-view',
name: 'Open active pics view',
checkCallback: (checking: boolean) => {
// The currently active view could be in the sidebar, but what we care about is the most recently active file!
// const activeMarkdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
// actually, we already keep track of this in `this.store.activeFile`
// const activeFile = this.app.workspace.getActiveFile();
const canRunCommand = this.activeFile() !== null;
if (canRunCommand) {
// If checking is true, we're simply _checking_ if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
this.openActivePicsView(true);
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new PskPluginSettingTab(this.app, this));
const finish = performance.now();
console.log(`[${NAME}] onload: ${(finish - start).toFixed(1)} ms`);
}
// Important: this does NOT run on app / plugin startup! It's meant for _one-time_ initialization when plugin is _manually_ enabled;
// for code that needs to run on every plugin load, put it in workspace.onLayoutReady.
// This happens after workspace.onLayoutReady!
// Officially recommended place to auto open custom views! (This way, if a user wants a custom view closed, it'll stay so the next time the app / plugin starts.)
onUserEnable() {
// new Notice('onUserEnable');
// auto open custom views
this.openActivePicsView(false);
}
// onunload is inherited from generic Component rather than Plugin, and it can't be async!
onunload() {
const start = performance.now();
this.disposeEffect();
this.db.close();
// delete modal UI
document.getElementById(GALLERY_ID)?.remove();
// Have to manually reset the flag on plugin unload to shut up Solid,
// o/w when we reload the plugin, Solid sees this singleton flag already set, triggering a false positive:
// console.warn("You appear to have multiple instances of Solid. This can lead to unexpected behavior.")
if (globalThis.Solid$$) globalThis.Solid$$ = false;
const finish = performance.now();
console.log(`[${NAME}] onunload: ${(finish - start).toFixed(1)} ms`);
}
// 3. My own class methods (utilities)
async setupDB() {
this.db = await openDB<PskDBSchema>(this.getThumbnailDBName(), DB_VERSION, {
upgrade(database, oldVersion) {
if (oldVersion < 2) {
if (database.objectStoreNames.contains('thumbnails')) {
database.deleteObjectStore('thumbnails');
}
database.createObjectStore('thumbnails');
}
}
});
}
async loadSettings() {
// Assert: this.settings === undefined
const data = await this.loadData();
// As we add new fields to `GjakoConfig`, the `gjako` object from data.json, now with incomplete fields,
// will completely overwrite `DEFAULT_SETTINGS.gjako`, hence those new fields won't appear in the final settings;
// this is because `Object.assign` only does "shallow merge", so to speak.
if (data) {
data.gjako = data.gjako
? Object.assign({}, DEFAULT_SETTINGS.gjako, data.gjako)
: DEFAULT_SETTINGS.gjako;
}
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
// console.log(`settings: ${JSON.stringify(this.settings, null, '\t')}`);
}
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Currently, local images (attachments) are NOT cached!
* @param pictures If undefined, all pictures in the vault will be checked for caching.
*/
generateThumbnailCache(pictures?: Picture[]) {
if (!this.settings.cacheThumbnails) return;
const urls = this.collectRemoteThumbnailURLs(pictures);
if (urls.length === 0) return;
this.queueThumbnailCache(urls);
}
getAttachmentInfo(linkText: string): { url: string, path: string } | null {
const linkPath = getLinkpath(linkText);
const sourcePath = this.activeFile()?.path ?? '';
const file = this.app.metadataCache.getFirstLinkpathDest(linkPath, sourcePath);
return file ? { url: this.app.vault.getResourcePath(file), path: file.path } : null;
}
/**
* Currently naive parsing:
* - only allows a single image per line
* - only checks common image extensions
* - doesn't validate URL / path
* - doesn't support URL query string
* - doesn't support data: blobs
*/
extractPicturesFromFile(file: TFile, fileContent: string, paragraphs: SectionCache[]): Picture[] {
const fileLines = fileContent.split('\n');
const pictures = [];
for (const paragraph of paragraphs) {
const { start, end } = paragraph.position;
const sectionLines = fileLines.slice(start.line, end.line + 1);
for (const line of sectionLines) {
let picture: Picture | null = null;
const matches = line.trimStart().match(/^!\[([^\]]*)\]\(([^)]+)\)/); // Note: possible trailing block ID
if (matches) {
const [, description, url] = matches;
// Note: description is allowed to be an empty string here!
// Note: url is guaranteed to be non-empty by the regex.
if (description !== undefined && url && isImageLink(url)) {
picture = {
url,
localPath: null,
description,
};
}
} else {
// maybe it's an embedded local image?
const matchesEmbed = line.trimStart().match(/^!\[\[([^|\]]+)(?:\|([^\]]+))?\]\]/);
if (matchesEmbed) {
const [, linkText, displayText] = matchesEmbed;
if (linkText && isImageLink(linkText)) {
const info = this.getAttachmentInfo(linkText);
if (info) {
picture = {
url: info.url,
localPath: info.path,
description: displayText ?? linkText,
};
}
}
}
}
if (picture) {
// dedupe by url
if (!pictures.map(pic => pic.url).contains(picture.url)) {
pictures.push(picture);
}
}
}
}
return pictures;
}
extractPictureMetadataFromFile(file: TFile, fileContent: string, codeblocks: SectionCache[]) {
const uploads: UploadResult[] = [];
const annotations: Annotation[] = [];
const fileLines = fileContent.split('\n');
for (const codeblock of codeblocks) {
const { start, end } = codeblock.position;
const lines = fileLines.slice(start.line, end.line); // exclude the final ``` line
const firstLine = lines[0];
if (firstLine && firstLine === `\`\`\`${LANG}`) {
const content = lines.slice(1).join('\n');
const parsed = JSON.parse(content);
if (Object.hasOwn(parsed, 'uploads')) {
const uploadsInCodeblock: UploadResult[] = parsed.uploads;
uploads.push(...uploadsInCodeblock);
} else if (Object.hasOwn(parsed, 'annotations')) {
// MAYBE (NOT)
}
}
}
return { uploads, annotations };
}
}
const VIEW_TYPE_ACTIVE_PICS = 'psk-view-active-pics';
class ActivePicsView extends ItemView {
plugin: PskPlugin;
// Solid stuff
private dispose!: () => void;
constructor(leaf: WorkspaceLeaf, plugin: PskPlugin) {
super(leaf);
this.icon = ICON;
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_ACTIVE_PICS;
}
getDisplayText(): string {
// Note: the code below can update the "title" property persisted in "workspace.json" when active file changes,
// but it doesn't update the UI, including the view leaf's tab title and its tooltip.
// return `Pictures in ${this.plugin.store.activeFile?.name}`;
return 'Pictures in active file';
}
async onOpen() {
this.dispose = render(() => {
const activePictures = createMemo(() => {
const activeFile = this.plugin.activeFile();
return activeFile
? this.plugin.store.pictures[activeFile.path] ?? []
: []
});
return createComponent(ActivePics, {
activePictures,
activeFile: this.plugin.activeFile,
setGallery: this.plugin.setGallery,
setGalleryFocus: this.plugin.setGalleryFocus,
});
}, this.contentEl);
}
async onClose() {
this.dispose();
}
}
const VIEW_TYPE_PICS_EXPLORER = 'psk-view-pics-explorer';
class PicsExplorerView extends ItemView {
plugin: PskPlugin;
// Solid stuff
private dispose!: () => void;
constructor(leaf: WorkspaceLeaf, plugin: PskPlugin) {
super(leaf);
this.navigation = true; // if not, pressing Escape key will switch to the previous active file!
this.icon = ICON;
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_PICS_EXPLORER;
}
getDisplayText(): string {
return 'Pics explorer';
}
async onOpen() {
const { contentEl } = this;
this.dispose = render(() => {
const pictures = this.plugin.store.pictures;
return createComponent(PicsExplorer, {
pictures,
excludePaths: this.plugin.excludePaths,
pageSize: this.plugin.explorerPageSize,
useThumbnailCache: this.plugin.cacheThumbnails,
setGallery: this.plugin.setGallery,
setGalleryFocus: this.plugin.setGalleryFocus,
fts: this.plugin.fts,
// cacheOneThumb: this.plugin.cacheOneThumb,
db: this.plugin.db,
app: this.plugin.app,
});
}, contentEl);
}
async onClose() {
this.dispose();
}
}
class ImageUploadModal extends Modal {
settings: Settings;
images: File[];
onConfirm: (selected: Set<File>, isPhoto: boolean, subDir: string) => void;
onCancel: () => void;