-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
main.ts
483 lines (401 loc) · 11.1 KB
/
main.ts
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
import { Notice, Platform, Plugin, Workspace, addIcon } from "obsidian";
import Publisher from "./src/publisher/Publisher";
import DigitalGardenSettings from "./src/models/settings";
import { PublishStatusBar } from "./src/views/PublishStatusBar";
import { seedling } from "src/ui/suggest/constants";
import { PublicationCenter } from "src/views/PublicationCenter/PublicationCenter";
import PublishStatusManager from "src/publisher/PublishStatusManager";
import ObsidianFrontMatterEngine from "src/publishFile/ObsidianFrontMatterEngine";
import DigitalGardenSiteManager from "src/repositoryConnection/DigitalGardenSiteManager";
import { DigitalGardenSettingTab } from "./src/views/DigitalGardenSettingTab";
import Logger from "js-logger";
import { PublishFile } from "./src/publishFile/PublishFile";
import { FRONTMATTER_KEYS } from "./src/publishFile/FileMetaDataManager";
const DEFAULT_SETTINGS: DigitalGardenSettings = {
githubRepo: "",
githubToken: "",
githubUserName: "",
gardenBaseUrl: "",
prHistory: [],
baseTheme: "dark",
theme: '{"name": "default", "modes": ["dark"]}',
faviconPath: "",
useFullResolutionImages: false,
noteSettingsIsInitialized: false,
siteName: "Digital Garden",
mainLanguage: "en",
slugifyEnabled: true,
// Note Icon Related Settings
noteIconKey: "dg-note-icon",
defaultNoteIcon: "",
showNoteIconOnTitle: false,
showNoteIconInFileTree: false,
showNoteIconOnInternalLink: false,
showNoteIconOnBackLink: false,
// Timestamp related settings
showCreatedTimestamp: false,
createdTimestampKey: "",
showUpdatedTimestamp: false,
updatedTimestampKey: "",
timestampFormat: "MMM dd, yyyy h:mm a",
styleSettingsCss: "",
styleSettingsBodyClasses: "",
pathRewriteRules: "",
customFilters: [],
contentClassesKey: "dg-content-classes",
defaultNoteSettings: {
dgHomeLink: true,
dgPassFrontmatter: false,
dgShowBacklinks: false,
dgShowLocalGraph: false,
dgShowInlineTitle: false,
dgShowFileTree: false,
dgEnableSearch: false,
dgShowToc: false,
dgLinkPreview: false,
dgShowTags: false,
},
logLevel: undefined,
};
Logger.useDefaults({
defaultLevel: Logger.WARN,
formatter: function (messages, _context) {
messages.unshift(new Date().toUTCString());
messages.unshift("DG: ");
},
});
export default class DigitalGarden extends Plugin {
settings!: DigitalGardenSettings;
appVersion!: string;
publishModal!: PublicationCenter;
async onload() {
this.appVersion = this.manifest.version;
console.log("Initializing DigitalGarden plugin v" + this.appVersion);
await this.loadSettings();
this.settings.logLevel && Logger.setLevel(this.settings.logLevel);
Logger.info(
"Digital garden log level set to " + Logger.getLevel().name,
);
this.addSettingTab(new DigitalGardenSettingTab(this.app, this));
await this.addCommands();
addIcon("digital-garden-icon", seedling);
this.addRibbonIcon(
"digital-garden-icon",
"Digital Garden Publication Center",
async () => {
this.openPublishModal();
},
);
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
async saveSettings(): Promise<void> {
await this.saveData(this.settings);
}
async addCommands() {
this.addCommand({
id: "quick-publish-and-share-note",
name: "Quick Publish And Share Note",
callback: async () => {
new Notice("Adding publish flag to note and publishing it.");
await this.setPublishFlagValue(true);
const activeFile = this.app.workspace.getActiveFile();
const event = this.app.metadataCache.on(
"changed",
async (file, _data, _cache) => {
if (file.path === activeFile?.path) {
const successfullyPublished =
await this.publishSingleNote();
if (successfullyPublished) {
await this.copyGardenUrlToClipboard();
}
this.app.metadataCache.offref(event);
}
},
);
// Remove the event listener after 5 seconds in case the file is not changed.
setTimeout(() => {
this.app.metadataCache.offref(event);
}, 5000);
},
});
this.addCommand({
id: "publish-note",
name: "Publish Single Note",
callback: async () => {
await this.publishSingleNote();
},
});
if (this.settings["ENABLE_DEVELOPER_TOOLS"] && Platform.isDesktop) {
Logger.info("Developer tools enabled");
const publisher = new Publisher(
this.app.vault,
this.app.metadataCache,
this.settings,
);
import("./src/test/snapshot/generateGardenSnapshot")
.then((snapshotGen) => {
this.addCommand({
id: "generate-garden-snapshot",
name: "Generate Garden Snapshot",
callback: async () => {
await snapshotGen.generateGardenSnapshot(
this.settings,
publisher,
);
},
});
})
.catch((e) => {
Logger.error("Unable to load generateGardenSnapshot", e);
});
}
this.addCommand({
id: "publish-multiple-notes",
name: "Publish Multiple Notes",
// TODO: move to publisher?
callback: async () => {
const statusBarItem = this.addStatusBarItem();
try {
new Notice("Processing files to publish...");
const { vault, metadataCache } = this.app;
const publisher = new Publisher(
vault,
metadataCache,
this.settings,
);
publisher.validateSettings();
const siteManager = new DigitalGardenSiteManager(
metadataCache,
this.settings,
);
const publishStatusManager = new PublishStatusManager(
siteManager,
publisher,
);
const publishStatus =
await publishStatusManager.getPublishStatus();
const filesToPublish = publishStatus.changedNotes.concat(
publishStatus.unpublishedNotes,
);
const filesToDelete = publishStatus.deletedNotePaths;
const imagesToDelete = publishStatus.deletedImagePaths;
const totalItems =
filesToPublish.length +
filesToDelete.length +
imagesToDelete.length;
if (totalItems === 0) {
new Notice("Garden is already fully synced!");
statusBarItem.remove();
return;
}
const statusBar = new PublishStatusBar(
statusBarItem,
filesToPublish.length +
filesToDelete.length +
imagesToDelete.length,
);
new Notice(
`Publishing ${filesToPublish.length} notes, deleting ${filesToDelete.length} notes and ${imagesToDelete.length} images. See the status bar in lower right corner for progress.`,
8000,
);
await publisher.publishBatch(filesToPublish);
statusBar.incrementMultiple(filesToPublish.length);
for (const file of filesToDelete) {
await publisher.deleteNote(file.path);
statusBar.increment();
}
for (const image of imagesToDelete) {
await publisher.deleteImage(image.path);
statusBar.increment();
}
statusBar.finish(8000);
new Notice(
`Successfully published ${filesToPublish.length} notes to your garden.`,
);
if (filesToDelete.length > 0) {
new Notice(
`Successfully deleted ${filesToDelete.length} notes from your garden.`,
);
}
if (imagesToDelete.length > 0) {
new Notice(
`Successfully deleted ${imagesToDelete.length} images from your garden.`,
);
}
} catch (e) {
statusBarItem.remove();
console.error(e);
new Notice(
"Unable to publish multiple notes, something went wrong.",
);
}
},
});
this.addCommand({
id: "copy-garden-url",
name: "Copy Garden URL",
callback: async () => {
this.copyGardenUrlToClipboard();
},
});
this.addCommand({
id: "dg-open-publish-modal",
name: "Open Publication Center",
callback: async () => {
this.openPublishModal();
},
});
this.addCommand({
id: "dg-mark-note-for-publish",
name: "Add publish flag",
callback: async () => {
this.setPublishFlagValue(true);
},
});
this.addCommand({
id: "dg-unmark-note-for-publish",
name: "Remove publish flag",
callback: async () => {
this.setPublishFlagValue(false);
},
});
this.addCommand({
id: "dg-mark-toggle-publish-status",
name: "Toggle publication status",
callback: async () => {
this.togglePublishFlag();
},
});
}
private getActiveFile(workspace: Workspace) {
const activeFile = workspace.getActiveFile();
if (!activeFile) {
new Notice(
"No file is open/active. Please open a file and try again.",
);
return null;
}
return activeFile;
}
async copyGardenUrlToClipboard() {
try {
const { metadataCache, workspace } = this.app;
const activeFile = this.getActiveFile(workspace);
if (!activeFile) {
return;
}
const siteManager = new DigitalGardenSiteManager(
metadataCache,
this.settings,
);
const fullUrl = siteManager.getNoteUrl(activeFile);
await navigator.clipboard.writeText(fullUrl);
new Notice(`Note URL copied to clipboard`);
} catch (e) {
console.log(e);
new Notice(
"Unable to copy note URL to clipboard, something went wrong.",
);
}
}
// TODO: move to publisher?
async publishSingleNote() {
try {
const { vault, workspace, metadataCache } = this.app;
const activeFile = this.getActiveFile(workspace);
if (!activeFile) {
return;
}
if (activeFile.extension !== "md") {
new Notice(
"The current file is not a markdown file. Please open a markdown file and try again.",
);
return;
}
new Notice("Publishing note...");
const publisher = new Publisher(
vault,
metadataCache,
this.settings,
);
publisher.validateSettings();
const publishFile = await new PublishFile({
file: activeFile,
vault: vault,
compiler: publisher.compiler,
metadataCache: metadataCache,
settings: this.settings,
}).compile();
const publishSuccessful = await publisher.publish(publishFile);
if (publishSuccessful) {
new Notice(`Successfully published note to your garden.`);
}
return publishSuccessful;
} catch (e) {
console.error(e);
new Notice("Unable to publish note, something went wrong.");
return false;
}
}
async setPublishFlagValue(value: boolean) {
const activeFile = this.getActiveFile(this.app.workspace);
if (!activeFile) {
return;
}
const engine = new ObsidianFrontMatterEngine(
this.app.vault,
this.app.metadataCache,
activeFile,
);
engine.set(FRONTMATTER_KEYS.PUBLISH, value).apply();
}
async togglePublishFlag() {
const activeFile = this.getActiveFile(this.app.workspace);
if (!activeFile) {
return;
}
const engine = new ObsidianFrontMatterEngine(
this.app.vault,
this.app.metadataCache,
activeFile,
);
engine
.set(
FRONTMATTER_KEYS.PUBLISH,
!engine.get(FRONTMATTER_KEYS.PUBLISH),
)
.apply();
}
openPublishModal() {
if (!this.publishModal) {
const siteManager = new DigitalGardenSiteManager(
this.app.metadataCache,
this.settings,
);
const publisher = new Publisher(
this.app.vault,
this.app.metadataCache,
this.settings,
);
const publishStatusManager = new PublishStatusManager(
siteManager,
publisher,
);
this.publishModal = new PublicationCenter(
this.app,
publishStatusManager,
publisher,
siteManager,
this.settings,
);
}
this.publishModal.open();
}
}