generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.ts
1405 lines (1186 loc) · 41.7 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
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 {
App,
arrayBufferToBase64,
Component,
FileSystemAdapter,
MarkdownRenderer,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
TAbstractFile,
TFile
} from 'obsidian';
/*
* Generic lib functions
*/
/**
* Like Promise.all(), but with a callback to indicate progress. Graciously lifted from
* https://stackoverflow.com/a/42342373/1341132
*/
function allWithProgress(promises: Promise<never>[], callback: (percentCompleted: number) => void) {
let count = 0;
callback(0);
for (const promise of promises) {
promise.then(() => {
count++;
callback((count * 100) / promises.length);
});
}
return Promise.all(promises);
}
/**
* Do nothing for a while
*/
async function delay(milliseconds: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
/**
* Static assets
*/
const DEFAULT_STYLESHEET =
`body,input {
font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif
}
code, kbd, pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace;
background-color: #f5f5f5;
}
pre {
padding: 1em 0.5em;
}
table {
background: white;
border: 1px solid #666;
border-collapse: collapse;
padding: 0.5em;
}
table thead th,
table tfoot th {
text-align: left;
background-color: #eaeaea;
color: black;
}
table th, table td {
border: 1px solid #ddd;
padding: 0.5em;
}
table td {
color: #222222;
}
.callout[data-callout="abstract"] .callout-title,
.callout[data-callout="summary"] .callout-title,
.callout[data-callout="tldr"] .callout-title,
.callout[data-callout="faq"] .callout-title,
.callout[data-callout="info"] .callout-title,
.callout[data-callout="help"] .callout-title {
background-color: #828ee7;
}
.callout[data-callout="tip"] .callout-title,
.callout[data-callout="hint"] .callout-title,
.callout[data-callout="important"] .callout-title {
background-color: #34bbe6;
}
.callout[data-callout="success"] .callout-title,
.callout[data-callout="check"] .callout-title,
.callout[data-callout="done"] .callout-title {
background-color: #a3e048;
}
.callout[data-callout="question"] .callout-title,
.callout[data-callout="todo"] .callout-title {
background-color: #49da9a;
}
.callout[data-callout="caution"] .callout-title,
.callout[data-callout="attention"] .callout-title {
background-color: #f7d038;
}
.callout[data-callout="warning"] .callout-title,
.callout[data-callout="missing"] .callout-title,
.callout[data-callout="bug"] .callout-title {
background-color: #eb7532;
}
.callout[data-callout="failure"] .callout-title,
.callout[data-callout="fail"] .callout-title,
.callout[data-callout="danger"] .callout-title,
.callout[data-callout="error"] .callout-title {
background-color: #e6261f;
}
.callout[data-callout="example"] .callout-title {
background-color: #d23be7;
}
.callout[data-callout="quote"] .callout-title,
.callout[data-callout="cite"] .callout-title {
background-color: #aaaaaa;
}
.callout-icon {
flex: 0 0 auto;
display: flex;
align-self: center;
}
svg.svg-icon {
height: 18px;
width: 18px;
stroke-width: 1.75px;
}
.callout {
overflow: hidden;
margin: 1em 0;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
.callout-title {
padding: .5em;
display: flex;
gap: 8px;
font-size: inherit;
color: black;
line-height: 1.3em;
}
.callout-title-inner {
font-weight: bold;
color: black;
}
.callout-content {
overflow-x: auto;
padding: 0.25em .5em;
color: #222222;
background-color: white !important;
}
ul.contains-task-list {
padding-left: 0;
list-style: none;
}
ul.contains-task-list ul.contains-task-list {
padding-left: 2em;
}
ul.contains-task-list li input[type="checkbox"] {
margin-right: .5em;
}
.callout-table,
.callout-table tr,
.callout-table p {
width: 100%;
padding: 0;
}
.callout-table td {
width: 100%;
padding: 0 1em;
}
.callout-table p {
padding-bottom: 0.5em;
}
.source-table {
width: 100%;
background-color: #f5f5f5;
}
`;
// Thank you again Olivier Balfour !
const MERMAID_STYLESHEET = `
:root {
--default-font: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Microsoft YaHei Light", sans-serif;
--font-monospace: 'Source Code Pro', monospace;
--background-primary: #ffffff;
--background-modifier-border: #ddd;
--text-accent: #705dcf;
--text-accent-hover: #7a6ae6;
--text-normal: #2e3338;
--background-secondary: #f2f3f5;
--background-secondary-alt: #fcfcfc;
--text-muted: #888888;
--font-mermaid: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Inter", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Microsoft YaHei Light", sans-serif;
--text-error: #E4374B;
--background-primary-alt: '#fafafa';
--background-accent: '';
--interactive-accent: hsl( 254, 80%, calc( 68% + 2.5%));
--background-modifier-error: #E4374B;
--background-primary-alt: #fafafa;
--background-modifier-border: #e0e0e0;
}
`;
const DEFAULT_HTML_TEMPLATE = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>\${title}</title>
<style>
\${MERMAID_STYLESHEET}
\${stylesheet}
</style>
</head>
<body>
\${body}
</body>
</html>
`;
/*
* Plugin code
*/
/** Don't allow multiple copy processes to run at the same time */
let copyIsRunning = false;
/** true while a block is being processed by MarkDownPostProcessor instances */
let ppIsProcessing = false;
/** moment at which the last block finished post-processing */
let ppLastBlockDate = Date.now();
enum FootnoteHandling {
/** Remove references and links */
REMOVE_ALL,
/** Reference links to footnote using a unique id */
LEAVE_LINK,
/** Links are removed from reference and back-link from footnote */
REMOVE_LINK,
/** Footnote is moved to title attribute */
TITLE_ATTRIBUTE
}
enum InternalLinkHandling {
/**
* remove link and only display link text
*/
CONVERT_TO_TEXT,
/**
* convert to an obsidian:// link to open the file or tag in Obsidian
*/
CONVERT_TO_OBSIDIAN_URI,
/**
* Keep link, but convert extension to .html
*/
LINK_TO_HTML,
/**
* Keep generated link
*/
LEAVE_AS_IS
}
/**
* Options for DocumentRenderer
*/
type DocumentRendererOptions = {
convertSvgToBitmap: boolean,
removeFrontMatter: boolean,
formatCodeWithTables: boolean,
formatCalloutsWithTables: boolean,
embedExternalLinks: boolean,
removeDataviewMetadataLines: boolean,
footnoteHandling: FootnoteHandling
internalLinkHandling: InternalLinkHandling,
disableImageEmbedding: boolean
};
const documentRendererDefaults: DocumentRendererOptions = {
convertSvgToBitmap: true,
removeFrontMatter: true,
formatCodeWithTables: false,
formatCalloutsWithTables: false,
embedExternalLinks: false,
removeDataviewMetadataLines: false,
footnoteHandling: FootnoteHandling.REMOVE_LINK,
internalLinkHandling: InternalLinkHandling.CONVERT_TO_TEXT,
disableImageEmbedding: false
};
/**
* Render markdown to DOM, with some clean-up and embed images as data uris.
*/
class DocumentRenderer {
private modal: CopyingToHtmlModal;
private view: Component;
// time required after last block was rendered before we decide that rendering a view is completed
private optionRenderSettlingDelay: number = 100;
// only those which are different from image/${extension}
private readonly mimeMap = new Map([
['svg', 'image/svg+xml'],
['jpg', 'image/jpeg'],
]);
private readonly externalSchemes = ['http', 'https'];
private readonly vaultPath: string;
private readonly vaultLocalUriPrefix: string;
private readonly vaultOpenUri: string;
private readonly vaultSearchUri: string;
constructor(private app: App,
private options: DocumentRendererOptions = documentRendererDefaults) {
this.vaultPath = (this.app.vault.getRoot().vault.adapter as FileSystemAdapter).getBasePath()
.replace(/\\/g, '/');
this.vaultLocalUriPrefix = `app://local/${this.vaultPath}`;
this.vaultOpenUri = `obsidian://open?vault=${encodeURIComponent(this.app.vault.getName())}`;
this.vaultSearchUri = `obsidian://search?vault=${encodeURIComponent(this.app.vault.getName())}`;
this.view = new Component();
}
/**
* Render document into detached HTMLElement
*/
public async renderDocument(markdown: string, path: string): Promise<HTMLElement> {
this.modal = new CopyingToHtmlModal(this.app);
this.modal.open();
try {
const topNode = await this.renderMarkdown(markdown, path);
return await this.transformHTML(topNode!);
} finally {
this.modal.close();
}
}
/**
* Render current view into HTMLElement, expanding embedded links
*/
private async renderMarkdown(markdown: string, path: string): Promise<HTMLElement> {
const processedMarkdown = this.preprocessMarkdown(markdown);
const wrapper = document.createElement('div');
wrapper.style.display = 'hidden';
document.body.appendChild(wrapper);
await MarkdownRenderer.render(this.app, processedMarkdown, wrapper, path, this.view);
await this.untilRendered();
await this.loadComponents(this.view);
const result = wrapper.cloneNode(true) as HTMLElement;
document.body.removeChild(wrapper);
this.view.unload();
return result;
}
/**
* Some plugins may expose components that rely on onload() to be called which isn't the case due to the
* way we render the markdown. We need to call onload() on all components to ensure they are properly loaded.
* Since this is a bit of a hack (we need to access Obsidian internals), we limit this to components of which
* we know that they don't get rendered correctly otherwise.
* We attempt to make sure that if the Obsidian internals change, this will fail gracefully.
*/
private async loadComponents(view: Component) {
type InternalComponent = Component & {
_children: Component[];
onload: () => void | Promise<void>;
}
const internalView = view as InternalComponent;
// recursively call onload() on all children, depth-first
const loadChildren = async (
component: Component,
visited: Set<Component> = new Set()
): Promise<void> => {
if (visited.has(component)) {
return; // Skip if already visited
}
visited.add(component);
const internalComponent = component as InternalComponent;
if (internalComponent._children?.length) {
for (const child of internalComponent._children) {
await loadChildren(child, visited);
}
}
try {
// relies on the Sheet plugin (advanced-table-xt) not to be minified
if (component?.constructor?.name === 'SheetElement') {
await component.onload();
}
} catch (error) {
console.error(`Error calling onload()`, error);
}
};
await loadChildren(internalView);
}
private preprocessMarkdown(markdown: string): string {
let processed = markdown;
if (this.options.removeDataviewMetadataLines) {
processed = processed.replace(/^[^ \t:#`<>][^:#`<>]+::.*$/gm, '');
}
return processed;
}
/**
* Wait until the view has finished rendering
*
* Beware, this is a dirty hack...
*
* We have no reliable way to know if the document finished rendering. For instance dataviews or task blocks
* may not have been post processed.
* MarkdownPostProcessors are called on all the "blocks" in the HTML view. So we register one post-processor
* with high-priority (low-number to mark the block as being processed), and another one with low-priority that
* runs after all other post-processors.
* Now if we see that no blocks are being post-processed, it can mean 2 things :
* - either we are between blocks
* - or we finished rendering the view
* On the premise that the time that elapses between the post-processing of consecutive blocks is always very
* short (just iteration, no work is done), we conclude that the render is finished if no block has been
* rendered for enough time.
*/
private async untilRendered() {
while (ppIsProcessing || Date.now() - ppLastBlockDate < this.optionRenderSettlingDelay) {
if (ppLastBlockDate === 0) {
break;
}
await delay(20);
}
}
/**
* Transform rendered markdown to clean it up and embed images
*/
private async transformHTML(element: HTMLElement): Promise<HTMLElement> {
// Remove styling which forces the preview to fill the window vertically
// @ts-ignore
const node: HTMLElement = element.cloneNode(true);
node.removeAttribute('style');
if (this.options.removeFrontMatter) {
this.removeFrontMatter(node);
}
this.replaceLinksOfClass(node, 'internal-link');
this.replaceLinksOfClass(node, 'tag');
this.makeCheckboxesReadOnly(node);
this.removeCollapseIndicators(node);
this.removeButtons(node);
this.removeStrangeNewWorldsLinks(node);
if (this.options.formatCodeWithTables) {
this.transformCodeToTables(node);
}
if (this.options.formatCalloutsWithTables) {
this.transformCalloutsToTables(node);
}
if (this.options.footnoteHandling == FootnoteHandling.REMOVE_ALL) {
this.removeAllFootnotes(node);
}
if (this.options.footnoteHandling == FootnoteHandling.REMOVE_LINK) {
this.removeFootnoteLinks(node);
} else if (this.options.footnoteHandling == FootnoteHandling.TITLE_ATTRIBUTE) {
// not supported yet
}
if (!this.options.disableImageEmbedding) {
await this.embedImages(node);
await this.renderSvg(node);
}
return node;
}
/** Remove front-matter */
private removeFrontMatter(node: HTMLElement) {
node.querySelectorAll('.frontmatter, .frontmatter-container')
.forEach(node => node.remove());
}
private replaceLinksOfClass(node: HTMLElement, className: string) {
if (this.options.internalLinkHandling === InternalLinkHandling.LEAVE_AS_IS) {
return;
}
node.querySelectorAll(`a.${className}`)
.forEach(node => {
switch (this.options.internalLinkHandling) {
case InternalLinkHandling.CONVERT_TO_OBSIDIAN_URI: {
const linkNode = node.parentNode!.createEl('a');
linkNode.innerText = node.getText();
if (className === 'tag') {
linkNode.href = this.vaultSearchUri + "&query=tag:" + encodeURIComponent(node.getAttribute('href')!);
} else {
if (node.getAttribute('href')!.startsWith('#')) {
linkNode.href = node.getAttribute('href')!;
} else {
linkNode.href = this.vaultOpenUri + "&file=" + encodeURIComponent(node.getAttribute('href')!);
}
}
linkNode.className = className;
node.parentNode!.replaceChild(linkNode, node);
}
break;
case InternalLinkHandling.LINK_TO_HTML: {
const linkNode = node.parentNode!.createEl('a');
linkNode.innerText = node.getAttribute('href')!; //node.getText();
linkNode.className = className;
if (node.getAttribute('href')!.startsWith('#')) {
linkNode.href = node.getAttribute('href')!;
} else {
linkNode.href = node.getAttribute('href')!.replace(/^(.*?)(?:\.md)?(#.*?)?$/, '$1.html$2');
}
node.parentNode!.replaceChild(linkNode, node);
}
break;
case InternalLinkHandling.CONVERT_TO_TEXT:
default: {
const textNode = node.parentNode!.createEl('span');
textNode.innerText = node.getText();
textNode.className = className;
node.parentNode!.replaceChild(textNode, node);
}
break;
}
});
}
private makeCheckboxesReadOnly(node: HTMLElement) {
node.querySelectorAll('input[type="checkbox"]')
.forEach(node => node.setAttribute('disabled', 'disabled'));
}
/** Remove the collapse indicators from HTML, not needed (and not working) in copy */
private removeCollapseIndicators(node: HTMLElement) {
node.querySelectorAll('.collapse-indicator')
.forEach(node => node.remove());
}
/** Remove button elements (which appear after code blocks) */
private removeButtons(node: HTMLElement) {
node.querySelectorAll('button')
.forEach(node => node.remove());
}
/** Remove counters added by Strange New Worlds plugin (https://github.com/TfTHacker/obsidian42-strange-new-worlds) */
private removeStrangeNewWorldsLinks(node: HTMLElement) {
node.querySelectorAll('.snw-reference')
.forEach(node => node.remove());
}
/** Transform code blocks to tables */
private transformCodeToTables(node: HTMLElement) {
node.querySelectorAll('pre')
.forEach(node => {
const codeEl = node.querySelector('code');
if (codeEl) {
const code = codeEl.innerHTML.replace(/\n*$/, '');
const table = node.parentElement!.createEl('table');
table.className = 'source-table';
table.innerHTML = `<tr><td><pre>${code}</pre></td></tr>`;
node.parentElement!.replaceChild(table, node);
}
});
}
/** Transform callouts to tables */
private transformCalloutsToTables(node: HTMLElement) {
node.querySelectorAll('.callout')
.forEach(node => {
const callout = node.parentElement!.createEl('table');
callout.addClass('callout-table', 'callout');
callout.setAttribute('data-callout', node.getAttribute('data-callout') ?? 'quote');
const headRow = callout.createEl('tr');
const headColumn = headRow.createEl('td');
headColumn.addClass('callout-title');
// const img = node.querySelector('svg');
const title = node.querySelector('.callout-title-inner');
// if (img) {
// headColumn.appendChild(img);
// }
if (title) {
const span = headColumn.createEl('span');
span.innerHTML = title.innerHTML;
}
const originalContent = node.querySelector('.callout-content');
if (originalContent) {
const row = callout.createEl('tr');
const column = row.createEl('td');
column.innerHTML = originalContent.innerHTML;
}
node.replaceWith(callout);
});
}
/** Remove references to footnotes and the footnotes section */
private removeAllFootnotes(node: HTMLElement) {
node.querySelectorAll('section.footnotes')
.forEach(section => section.parentNode!.removeChild(section));
node.querySelectorAll('.footnote-link')
.forEach(link => {
link.parentNode!.parentNode!.removeChild(link.parentNode!);
});
}
/** Keep footnotes and references, but remove links */
private removeFootnoteLinks(node: HTMLElement) {
node.querySelectorAll('.footnote-link')
.forEach(link => {
const text = link.getText();
if (text === '↩︎') {
// remove back-link
link.parentNode!.removeChild(link);
} else {
// remove from reference
const span = link.parentNode!.createEl('span', {text: link.getText(), cls: 'footnote-link'})
link.parentNode!.replaceChild(span, link);
}
});
}
/** Replace all images sources with a data-uri */
private async embedImages(node: HTMLElement): Promise<HTMLElement> {
const promises: Promise<void>[] = [];
// Replace all image sources
node.querySelectorAll('img')
.forEach(img => {
if (img.src) {
if (img.src.startsWith('data:image/svg+xml') && this.options.convertSvgToBitmap) {
// image is an SVG, encoded as a data uri. This is the case with Excalidraw for instance.
// Convert it to bitmap
promises.push(this.replaceImageSource(img));
return;
}
if (!this.options.embedExternalLinks) {
const [scheme] = img.src.split(':', 1);
if (this.externalSchemes.includes(scheme.toLowerCase())) {
// don't touch external images
return;
} else {
// not an external image, continue processing below
}
}
if (!img.src.startsWith('data:')) {
// render bitmaps, except if already as data-uri
promises.push(this.replaceImageSource(img));
return;
}
}
});
// @ts-ignore
this.modal.progress.max = 100;
// @ts-ignore
await allWithProgress(promises, percentCompleted => this.modal.progress.value = percentCompleted);
return node;
}
private async renderSvg(node: HTMLElement): Promise<Element> {
const xmlSerializer = new XMLSerializer();
if (!this.options.convertSvgToBitmap) {
return node;
}
const promises: Promise<void>[] = [];
const replaceSvg = async (svg: SVGSVGElement) => {
const style: HTMLStyleElement = svg.querySelector('style') || svg.appendChild(document.createElement('style'));
style.innerHTML += MERMAID_STYLESHEET;
const svgAsString = xmlSerializer.serializeToString(svg);
const svgData = `data:image/svg+xml;base64,` + Buffer.from(svgAsString).toString('base64');
const dataUri = await this.imageToDataUri(svgData);
const img = svg.createEl('img');
img.style.cssText = svg.style.cssText;
img.src = dataUri;
svg.parentElement!.replaceChild(img, svg);
};
node.querySelectorAll('svg')
.forEach(svg => {
promises.push(replaceSvg(svg));
});
// @ts-ignore
this.modal.progress.max = 0;
// @ts-ignore
await allWithProgress(promises, percentCompleted => this.modal.progress.value = percentCompleted);
return node;
}
/** replace image src attribute with data uri */
private async replaceImageSource(image: HTMLImageElement): Promise<void> {
const imageSourcePath = decodeURI(image.src);
if (imageSourcePath.startsWith(this.vaultLocalUriPrefix)) {
// Transform uri to Obsidian relative path
let path = imageSourcePath.substring(this.vaultLocalUriPrefix.length + 1)
.replace(/[?#].*/, '');
path = decodeURI(path);
const mimeType = this.guessMimeType(path);
const data = await this.readFromVault(path, mimeType);
if (this.isSvg(mimeType) && this.options.convertSvgToBitmap) {
// render svg to bitmap for compatibility w/ for instance gmail
image.src = await this.imageToDataUri(data);
} else {
// file content as base64 data uri (including svg)
image.src = data;
}
} else {
// Attempt to render uri to canvas. This is not an uri that points to the vault. Not needed for public
// urls, but we may have un uri that points to our local machine or network, that will not be accessible
// wherever we intend to paste the document.
image.src = await this.imageToDataUri(image.src);
}
}
/**
* Draw image url to canvas and return as data uri containing image pixel data
*/
private async imageToDataUri(url: string): Promise<string> {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
const dataUriPromise = new Promise<string>((resolve, reject) => {
image.onload = () => {
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
ctx!.drawImage(image, 0, 0);
try {
const uri = canvas.toDataURL('image/png');
resolve(uri);
} catch (err) {
// leave error at `log` level (not `error`), since we leave an url that may be workable
console.log(`failed ${url}`, err);
// if we fail, leave the original url.
// This way images that we may not load from external sources (tainted) may still be accessed
// (eg. plantuml)
// TODO: should we attempt to fallback with fetch ?
resolve(url);
}
canvas.remove();
}
image.onerror = (err) => {
console.log('could not load data uri');
// if we fail, leave the original url
resolve(url);
}
})
image.src = url;
return dataUriPromise;
}
/**
* Get binary data as b64 from a file in the vault
*/
private async readFromVault(path: string, mimeType: string): Promise<string> {
const tfile = this.app.vault.getAbstractFileByPath(path) as TFile;
const data = await this.app.vault.readBinary(tfile);
return `data:${mimeType};base64,` + arrayBufferToBase64(data);
}
/** Guess an image's mime-type based on its extension */
private guessMimeType(filePath: string): string {
const extension = this.getExtension(filePath) || 'png';
return this.mimeMap.get(extension) || `image/${extension}`;
}
/** Get lower-case extension for a path */
private getExtension(filePath: string): string {
// avoid using the "path" library
const fileName = filePath.slice(filePath.lastIndexOf('/') + 1);
return fileName.slice(fileName.lastIndexOf('.') + 1 || fileName.length)
.toLowerCase();
}
private isSvg(mimeType: string): boolean {
return mimeType === 'image/svg+xml';
}
}
/**
* Modal to show progress during conversion
*/
class CopyingToHtmlModal extends Modal {
constructor(app: App) {
super(app);
}
private _progress: HTMLElement;
get progress() {
return this._progress;
}
onOpen() {
const {titleEl, contentEl} = this;
titleEl.setText('Copying to clipboard');
this._progress = contentEl.createEl('progress');
this._progress.style.width = '100%';
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
/**
* Settings dialog
*/
class CopyDocumentAsHTMLSettingsTab extends PluginSettingTab {
constructor(app: App, private plugin: CopyDocumentAsHTMLPlugin) {
super(app, plugin);
this.plugin = plugin;
}
// Thank you, Obsidian Tasks !
private static createFragmentWithHTML = (html: string) =>
createFragment((documentFragment) => (documentFragment.createDiv().innerHTML = html));
display(): void {
const {containerEl} = this;
containerEl.empty();
containerEl.createEl('h2', {text: 'Copy document as HTML Settings'});
containerEl.createEl('h3', {text: 'Compatibility'});
new Setting(containerEl)
.setName('Convert SVG files to bitmap')
.setDesc('If checked, SVG files are converted to bitmap. This makes the copied documents heavier but improves compatibility (eg. with gmail).')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.convertSvgToBitmap)
.onChange(async (value) => {
this.plugin.settings.convertSvgToBitmap = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Embed external images')
.setDesc('If checked, external images are downloaded and embedded. If unchecked, the resulting document may contain links to external resources')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.embedExternalLinks)
.onChange(async (value) => {
this.plugin.settings.embedExternalLinks = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Render code with tables')
.setDesc("If checked code blocks are rendered as tables, which makes pasting into Google docs somewhat prettier.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.formatCodeWithTables)
.onChange(async (value) => {
this.plugin.settings.formatCodeWithTables = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Render callouts with tables')
.setDesc("If checked callouts are rendered as tables, which makes pasting into Google docs somewhat prettier.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.formatCalloutsWithTables)
.onChange(async (value) => {
this.plugin.settings.formatCalloutsWithTables = value;
await this.plugin.saveSettings();
}));
containerEl.createEl('h3', {text: 'Rendering'});
new Setting(containerEl)
.setName('Include filename as header')
.setDesc("If checked, the filename is inserted as a level 1 header. (only if an entire document is copied)")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.fileNameAsHeader)
.onChange(async (value) => {
this.plugin.settings.fileNameAsHeader = value;
await this.plugin.saveSettings();
}))
new Setting(containerEl)
.setName('Copy HTML fragment only')
.setDesc("If checked, only generate a HTML fragment and not a full HTML document. This excludes the header, and effectively disables all styling.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.bareHtmlOnly)
.onChange(async (value) => {
this.plugin.settings.bareHtmlOnly = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Remove properties / front-matter sections')
.setDesc("If checked, the YAML content between --- lines at the front of the document are removed. If you don't know what this means, leave it on.")
.addToggle(toggle => toggle
.setValue(this.plugin.settings.removeFrontMatter)
.onChange(async (value) => {
this.plugin.settings.removeFrontMatter = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Remove dataview metadata lines')
.setDesc(CopyDocumentAsHTMLSettingsTab.createFragmentWithHTML(`
<p>Remove lines that only contain dataview meta-data, eg. "rating:: 9". Metadata between square brackets is left intact.</p>
<p>Current limitations are that lines starting with a space are not removed, and lines that look like metadata in code blocks are removed if they don't start with a space</p>`))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.removeDataviewMetadataLines)
.onChange(async (value) => {
this.plugin.settings.removeDataviewMetadataLines = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Footnote handling')
.setDesc(CopyDocumentAsHTMLSettingsTab.createFragmentWithHTML(`
<ul>
<li>Remove everything: Remove references and links.</li>
<li>Display only: leave reference and foot-note, but don't display as a link.</li>
<li>Display and link: attempt to link the reference to the footnote, may not work depending on paste target.</li>
</ul>`)