generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.ts
722 lines (622 loc) · 19.8 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
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
import {
App,
Debouncer,
Editor,
MarkdownFileInfo,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
SuggestModal,
TFile,
debounce,
} from 'obsidian';
import matter from 'gray-matter';
import {
CreateGistResultStatus,
Target,
createGist,
updateGist,
} from 'src/gists';
import {
getDotcomAccessToken,
getGhesAccessToken,
getGhesBaseUrl,
isDotcomEnabled,
isGhesEnabled,
setDotcomAccessToken,
setGhesAccessToken,
setGhesBaseUrl,
} from './src/storage';
import {
SharedGist,
getSharedGistsForFile,
getTargetForSharedGist,
upsertSharedGistForFile,
} from './src/shared-gists';
interface ShareAsGistSettings {
enableUpdatingGistsAfterCreation: boolean;
enableAutoSaving: boolean;
showAutoSaveNotice: boolean;
includeFrontMatter: boolean;
}
const DEFAULT_SETTINGS: ShareAsGistSettings = {
includeFrontMatter: false,
enableUpdatingGistsAfterCreation: true,
enableAutoSaving: false,
showAutoSaveNotice: false,
};
interface ShareGistEditorCallbackParams {
app: App;
isPublic: boolean;
plugin: ShareAsGistPlugin;
target: Target;
}
interface CopyGistUrlEditorCallbackParams {
app: App;
plugin: ShareAsGistPlugin;
}
interface OpenGistEditorCallbackParams {
app: App;
plugin: ShareAsGistPlugin;
}
interface DocumentChangedAutoSaveCallbackParams {
app: App;
plugin: ShareAsGistPlugin;
content: string;
file: TFile;
}
const getLatestSettings = async (
plugin: ShareAsGistPlugin,
): Promise<ShareAsGistSettings> => {
await plugin.loadSettings();
return plugin.settings;
};
const stripFrontMatter = (content: string): string => matter(content).content;
const copyGistUrlEditorCallback =
(opts: CopyGistUrlEditorCallbackParams) => async () => {
const { app, plugin } = opts;
const view = app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
return new Notice('No active file');
}
const editor = view.editor;
const originalContent = editor.getValue();
const existingSharedGists = getSharedGistsForFile(originalContent);
if (existingSharedGists.length === 0) {
const { enableUpdatingGistsAfterCreation } =
await getLatestSettings(plugin);
if (!enableUpdatingGistsAfterCreation) {
return new Notice(
"You need to enable 'Update gists after creation' in Settings to use this command.",
);
} else {
return new Notice(
'You must share this note as a gist before you can copy its URL to the clipboard.',
);
}
}
if (existingSharedGists.length > 1) {
new SelectExistingGistModal(
app,
existingSharedGists,
false,
async (sharedGist) => {
navigator.clipboard.writeText(sharedGist.url);
new Notice('Copied gist URL to clipboard.');
},
).open();
} else {
const sharedGist = existingSharedGists[0];
navigator.clipboard.writeText(sharedGist.url);
return new Notice('Copied gist URL to clipboard.');
}
};
const openGistEditorCallback =
(opts: OpenGistEditorCallbackParams) => async () => {
const { app, plugin } = opts;
const view = app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
return new Notice('No active file');
}
const editor = view.editor;
const originalContent = editor.getValue();
const existingSharedGists = getSharedGistsForFile(originalContent);
if (existingSharedGists.length === 0) {
const { enableUpdatingGistsAfterCreation } =
await getLatestSettings(plugin);
if (!enableUpdatingGistsAfterCreation) {
return new Notice(
"You need to enable 'Update gists after creation' in Settings to use this command.",
);
} else {
return new Notice(
'You must share this note as a gist before you can open its gist.',
);
}
}
if (existingSharedGists.length > 1) {
new SelectExistingGistModal(
app,
existingSharedGists,
false,
async (sharedGist) => {
window.open(sharedGist.url, '_blank');
},
).open();
} else {
const sharedGist = existingSharedGists[0];
window.open(sharedGist.url, '_blank');
}
};
const shareGistEditorCallback =
(opts: ShareGistEditorCallbackParams) => async () => {
const { isPublic, app, plugin, target } = opts;
const { enableUpdatingGistsAfterCreation, includeFrontMatter } =
await getLatestSettings(plugin);
const view = app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
return new Notice('No active file');
}
const editor = view.editor;
const originalContent = editor.getValue();
const filename = view.file.name;
const existingSharedGists = getSharedGistsForFile(
originalContent,
target,
).filter((sharedGist) => sharedGist.isPublic === isPublic);
const gistContent = includeFrontMatter
? originalContent
: stripFrontMatter(originalContent);
if (enableUpdatingGistsAfterCreation && existingSharedGists.length) {
new SelectExistingGistModal(
app,
existingSharedGists,
true,
async (sharedGist) => {
if (sharedGist) {
const result = await updateGist({
sharedGist,
content: gistContent,
});
if (result.status === CreateGistResultStatus.Succeeded) {
navigator.clipboard.writeText(result.sharedGist.url);
new Notice(
`Copied ${isPublic ? 'public' : 'private'} gist URL to clipboard`,
);
const updatedContent = upsertSharedGistForFile(
result.sharedGist,
originalContent,
);
editor.setValue(updatedContent);
} else {
new Notice(`Error: ${result.errorMessage}`);
}
} else {
new SetGistDescriptionModal(app, filename, async (description) => {
const result = await createGist({
target,
content: gistContent,
description,
filename,
isPublic,
});
if (result.status === CreateGistResultStatus.Succeeded) {
navigator.clipboard.writeText(result.sharedGist.url);
new Notice(
`Copied ${isPublic ? 'public' : 'private'} gist URL to clipboard`,
);
const updatedContent = upsertSharedGistForFile(
result.sharedGist,
originalContent,
);
editor.setValue(updatedContent);
} else {
new Notice(`Error: ${result.errorMessage}`);
}
}).open();
}
},
).open();
} else {
new SetGistDescriptionModal(app, filename, async (description) => {
const result = await createGist({
target,
content: gistContent,
description,
filename,
isPublic,
});
if (result.status === CreateGistResultStatus.Succeeded) {
navigator.clipboard.writeText(result.sharedGist.url);
new Notice(
`Copied ${isPublic ? 'public' : 'private'} gist URL to clipboard`,
);
if (enableUpdatingGistsAfterCreation) {
const updatedContent = upsertSharedGistForFile(
result.sharedGist,
originalContent,
);
app.vault.modify(view.file, updatedContent);
editor.refresh();
}
} else {
new Notice(`GitHub API error: ${result.errorMessage}`);
}
}).open();
}
};
const documentChangedAutoSaveCallback = async (
opts: DocumentChangedAutoSaveCallbackParams,
) => {
const { plugin, file, content: rawContent } = opts;
const { includeFrontMatter, showAutoSaveNotice } =
await getLatestSettings(plugin);
const existingSharedGists = getSharedGistsForFile(rawContent);
const content = includeFrontMatter
? rawContent
: stripFrontMatter(rawContent);
if (existingSharedGists.length) {
for (const sharedGist of existingSharedGists) {
const result = await updateGist({ sharedGist, content });
if (result.status === CreateGistResultStatus.Succeeded) {
const updatedContent = upsertSharedGistForFile(
result.sharedGist,
rawContent,
);
await file.vault.adapter.write(file.path, updatedContent);
if (showAutoSaveNotice) {
return new Notice('Gist updated');
}
} else {
return new Notice(`Error: ${result.errorMessage}`);
}
}
}
};
const hasAtLeastOneSharedGist = (editor: Editor): boolean => {
const originalContent = editor.getValue();
const existingSharedGists = getSharedGistsForFile(originalContent);
return existingSharedGists.length > 0;
};
export default class ShareAsGistPlugin extends Plugin {
settings: ShareAsGistSettings;
async onload() {
await this.loadSettings();
this.registerCommands();
this.addModifyCallback();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new ShareAsGistSettingTab(this.app, this));
}
addEditorCommandWithCheck(opts: {
id: string;
name: string;
callback: (editor: Editor, ctx: MarkdownView | MarkdownFileInfo) => void;
performCheck: (
editor: Editor,
ctx: MarkdownView | MarkdownFileInfo,
) => boolean;
}) {
const { id, name, performCheck, callback } = opts;
this.addCommand({
id,
name,
editorCheckCallback: (checking, editor, ctx) => {
if (performCheck(editor, ctx)) {
if (checking) {
return true;
}
callback(editor, ctx);
}
},
});
}
registerCommands() {
this.addEditorCommandWithCheck({
id: 'share-as-private-dotcom-gist',
name: 'Share as private gist on GitHub.com',
callback: shareGistEditorCallback({
plugin: this,
app: this.app,
isPublic: false,
target: Target.Dotcom,
}),
performCheck: isDotcomEnabled,
});
this.addEditorCommandWithCheck({
id: 'share-as-public-dotcom-gist',
name: 'Share as public gist on GitHub.com',
callback: shareGistEditorCallback({
plugin: this,
app: this.app,
isPublic: true,
target: Target.Dotcom,
}),
performCheck: isDotcomEnabled,
});
this.addEditorCommandWithCheck({
id: 'share-as-private-ghes-gist',
name: 'Share as private gist on GitHub Enterprise Server',
callback: shareGistEditorCallback({
plugin: this,
app: this.app,
isPublic: false,
target: Target.GitHubEnterpriseServer,
}),
performCheck: isGhesEnabled,
});
this.addEditorCommandWithCheck({
id: 'share-as-public-ghes-gist',
name: 'Share as public gist on GitHub Enterprise Server',
callback: shareGistEditorCallback({
plugin: this,
app: this.app,
isPublic: true,
target: Target.GitHubEnterpriseServer,
}),
performCheck: isGhesEnabled,
});
this.addEditorCommandWithCheck({
id: 'copy-gist-url',
name: 'Copy gist URL',
callback: copyGistUrlEditorCallback({
plugin: this,
app: this.app,
}),
performCheck: hasAtLeastOneSharedGist,
});
this.addEditorCommandWithCheck({
id: 'open-gist-url',
name: 'Open gist',
callback: openGistEditorCallback({
plugin: this,
app: this.app,
}),
performCheck: hasAtLeastOneSharedGist,
});
}
addModifyCallback() {
const previousContents: Record<string, string> = {};
const debouncedCallbacks: Record<
string,
Debouncer<[string, TFile], Promise<Notice>>
> = {};
this.app.vault.on('modify', async (file: TFile) => {
const content = await file.vault.adapter.read(file.path);
// Frontmatter is stripped here because it is updated when the gist is updated,
// so there would be an infinite loop of updating if it wasn't.
if (stripFrontMatter(content) === previousContents[file.path]) {
return;
}
previousContents[file.path] = stripFrontMatter(content);
if (!debouncedCallbacks[file.path]) {
debouncedCallbacks[file.path] = debounce(
async (content: string, file: TFile) =>
await documentChangedAutoSaveCallback({
plugin: this,
app: this.app,
content,
file,
}),
15 * 1000,
true,
);
}
const { enableAutoSaving } = await getLatestSettings(this);
if (enableAutoSaving) {
await debouncedCallbacks[file.path](content, file);
}
});
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SelectExistingGistModal extends SuggestModal<SharedGist> {
sharedGists: SharedGist[];
allowCreatingNewGist: boolean;
onSubmit: (sharedGist: SharedGist | null) => Promise<void>;
constructor(
app: App,
sharedGists: SharedGist[],
allowCreatingNewGist: boolean,
onSubmit: (sharedGist: SharedGist) => Promise<void>,
) {
super(app);
this.sharedGists = sharedGists;
this.allowCreatingNewGist = allowCreatingNewGist;
this.onSubmit = onSubmit;
}
getSuggestions(): Array<SharedGist | null> {
if (this.allowCreatingNewGist) {
return this.sharedGists.concat(null);
} else {
return this.sharedGists;
}
}
renderSuggestion(sharedGist: SharedGist | null, el: HTMLElement) {
if (sharedGist === null) {
el.createEl('div', { text: 'Create new gist' });
} else {
const targetLabel =
getTargetForSharedGist(sharedGist) === Target.Dotcom
? 'GitHub.com'
: new URL(sharedGist.baseUrl).host;
el.createEl('div', {
text:
(sharedGist.isPublic ? 'Public gist' : 'Private gist') +
` on ${targetLabel}`,
});
el.createEl('small', { text: `Created at ${sharedGist.createdAt}` });
}
}
onChooseSuggestion(sharedGist: SharedGist | null) {
this.onSubmit(sharedGist).then(() => this.close());
}
}
class SetGistDescriptionModal extends Modal {
description: string | null = null;
onSubmit: (description: string | null) => void;
constructor(
app: App,
filename: string,
onSubmit: (description: string | null) => void,
) {
super(app);
this.description = filename;
this.onSubmit = onSubmit;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h1', { text: 'Set a description for your gist' });
contentEl.createEl('p', {
text: 'Hit the Return key to continue',
attr: { style: 'font-style: italic' },
});
new Setting(contentEl).setName('Description').addTextArea((text) => {
text.inputEl.setCssStyles({ width: '100%' });
text.setValue(this.description).onChange((value) => {
this.description = value;
});
});
new Setting(contentEl).addButton((btn) =>
btn
.setButtonText('Create gist')
.setCta()
.onClick(() => {
this.close();
this.onSubmit(this.description);
}),
);
this.scope.register([], 'Enter', (evt: KeyboardEvent) => {
evt.preventDefault();
if (evt.isComposing) {
return;
}
this.close();
this.onSubmit(this.description);
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class ShareAsGistSettingTab extends PluginSettingTab {
plugin: ShareAsGistPlugin;
constructor(app: App, plugin: ShareAsGistPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
const dotcomAccessToken = getDotcomAccessToken();
const ghesBaseUrl = getGhesBaseUrl();
const ghesAccessToken = getGhesAccessToken();
containerEl.empty();
containerEl.createEl('h2', { text: 'Share as Gist' });
containerEl.createEl('h3', { text: 'GitHub.com' });
new Setting(containerEl)
.setName('Personal access token')
.setDesc(
'An access token for GitHub.com with permission to write gists. You can create one from "Settings" in your GitHub account.',
)
.addText((text) =>
text
.setPlaceholder('Your personal access token')
.setValue(dotcomAccessToken)
.onChange(async (value) => {
setDotcomAccessToken(value);
await this.plugin.saveSettings();
}),
);
containerEl.createEl('h3', { text: 'GitHub Enterprise Server' });
new Setting(containerEl)
.setName('Base URL')
.setDesc(
'The base URL for the GitHub REST API on your GitHub Enterprise Server instance. This usually ends with `/api/v3`.',
)
.addText((text) =>
text
.setPlaceholder('https://github.example.com/api/v3')
.setValue(ghesBaseUrl)
.onChange(async (value) => {
setGhesBaseUrl(value);
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Personal access token')
.setDesc(
'An access token for your GitHub Enterprise Server instance with permission to write gists. You can create one from "Settings" in your GitHub account.',
)
.addText((text) =>
text
.setPlaceholder('Your personal access token')
.setValue(ghesAccessToken)
.onChange(async (value) => {
setGhesAccessToken(value);
await this.plugin.saveSettings();
}),
);
containerEl.createEl('h3', { text: 'Advanced options' });
new Setting(containerEl)
.setName('Enable updating gists after creation')
.setDesc(
'Whether gists should be updateable through this plugin after creation. ' +
'If this is turned on, when you create a gist, you will be able to choose ' +
'to update an existing gist (if one exists) or create a brand new one. ' +
'To make this possible, front matter will be added to your notes to track ' +
'gists that you have created. If this is turned off, a brand new gist will ' +
'always be created.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.enableUpdatingGistsAfterCreation)
.onChange(async (value) => {
this.plugin.settings.enableUpdatingGistsAfterCreation = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Include front matter in gists')
.setDesc(
'Whether the front matter should be included or stripped away when a note is shared as a gist',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.includeFrontMatter)
.onChange(async (value) => {
this.plugin.settings.includeFrontMatter = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Enable auto-saving Gists after edit')
.setDesc('Whether to update linked gists when the document is updated')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.enableAutoSaving)
.onChange(async (value) => {
this.plugin.settings.enableAutoSaving = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Enable auto-save notice')
.setDesc('Whether to show a notice when a linked gist is auto-saved')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showAutoSaveNotice)
.onChange(async (value) => {
this.plugin.settings.showAutoSaveNotice = value;
await this.plugin.saveSettings();
}),
);
}
}