-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.js
More file actions
1552 lines (1535 loc) · 52.2 KB
/
Copy pathmain.js
File metadata and controls
1552 lines (1535 loc) · 52.2 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => ImageInlinePlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian6 = require("obsidian");
// src/utils/base64/arrayBufferBase64.ts
var BYTE_CHUNK_SIZE = 32768;
function encodeArrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
let binary = "";
for (let offset = 0; offset < bytes.length; offset += BYTE_CHUNK_SIZE) {
const chunk = bytes.subarray(offset, offset + BYTE_CHUNK_SIZE);
for (const byte of chunk) {
binary += String.fromCharCode(byte);
}
}
return btoa(binary);
}
function decodeBase64ToArrayBuffer(base64) {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index++) {
bytes[index] = binary.charCodeAt(index);
}
return bytes.buffer;
}
// src/utils/base64/imageMime.ts
var DEFAULT_IMAGE_MIME_TYPE = "image/png";
var EXTENSION_TO_MIME_TYPE = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
svg: "image/svg+xml",
avif: "image/avif"
};
var MIME_TYPE_TO_EXTENSION = {
"image/png": "png",
"image/jpeg": "jpeg",
"image/gif": "gif",
"image/webp": "webp",
"image/bmp": "bmp",
"image/svg+xml": "svg",
"image/avif": "avif"
};
function inferMimeTypeFromFilename(filename) {
var _a, _b;
if (!filename) {
return DEFAULT_IMAGE_MIME_TYPE;
}
const extension = (_a = filename.split(".").pop()) == null ? void 0 : _a.toLowerCase();
if (!extension) {
return DEFAULT_IMAGE_MIME_TYPE;
}
return (_b = EXTENSION_TO_MIME_TYPE[extension]) != null ? _b : DEFAULT_IMAGE_MIME_TYPE;
}
function normalizeImageMimeType(mimeType, filename) {
if (!mimeType) {
return inferMimeTypeFromFilename(filename);
}
if (mimeType === "image/jpg") {
return "image/jpeg";
}
return mimeType;
}
function normalizeImageFilename(filename, mimeType) {
var _a;
const safeFilename = (filename == null ? void 0 : filename.trim()) || "image";
if (safeFilename.includes(".")) {
return safeFilename;
}
const extension = (_a = MIME_TYPE_TO_EXTENSION[mimeType]) != null ? _a : "png";
return `${safeFilename}.${extension}`;
}
function replaceFilenameExtension(filename, mimeType) {
const baseName = filename.includes(".") ? filename.slice(0, filename.lastIndexOf(".")) : filename;
return normalizeImageFilename(baseName, mimeType);
}
// src/utils/base64/base64File.ts
function parseMarkdownImageDataUrl(link) {
const match = link.match(/^!\[(.*?)\]\(data:(image\/[^;]+);base64,([^\)]+)\)$/);
if (!match) {
return null;
}
return {
filename: match[1],
mimeType: normalizeImageMimeType(match[2], match[1]),
base64: match[3]
};
}
var Base64File = class _Base64File {
constructor(bufferOrInit, filename, mimeType) {
const init = bufferOrInit instanceof ArrayBuffer ? { buffer: bufferOrInit, filename, mimeType } : bufferOrInit;
const resolvedMimeType = normalizeImageMimeType(init.mimeType, init.filename);
this.buffer = init.buffer;
this.mimeType = resolvedMimeType;
this.filename = normalizeImageFilename(init.filename, resolvedMimeType);
}
/**
* Reports the raw binary size of the wrapped image payload.
*/
get size() {
return this.buffer.byteLength;
}
/**
* Encodes the wrapped binary image into base64 text.
*/
toBase64String() {
return encodeArrayBufferToBase64(this.buffer);
}
/**
* Builds an inline Markdown image using the file's current MIME type and filename.
*/
toMarkdownImage() {
return `})`;
}
/**
* Preserves compatibility with the existing plugin API for base64 string generation.
*/
to64String() {
return this.toBase64String();
}
/**
* Preserves compatibility with the existing plugin API for inline Markdown generation.
*/
to64Link() {
return this.toMarkdownImage();
}
/**
* Rehydrates a Base64File from an inline Markdown image data URL.
*/
static from64Link(link) {
const parsed = parseMarkdownImageDataUrl(link);
if (!parsed) {
return null;
}
return new _Base64File({
buffer: decodeBase64ToArrayBuffer(parsed.base64),
filename: parsed.filename,
mimeType: parsed.mimeType
});
}
/**
* Rehydrates a Base64File from raw base64 data and optional image metadata.
*/
static from64String(base64, filename, mimeType) {
return new _Base64File({
buffer: decodeBase64ToArrayBuffer(base64),
filename,
mimeType
});
}
/**
* Builds a Base64File from a browser File while preserving browser-provided MIME metadata.
*/
static async fromFile(file) {
const arrayBuffer = await file.arrayBuffer();
return new _Base64File({
buffer: arrayBuffer,
filename: file.name,
mimeType: file.type || inferMimeTypeFromFilename(file.name)
});
}
/**
* Builds a Base64File from an Obsidian vault file while inferring MIME metadata from its name.
*/
static async fromTFile(tfile) {
const arrayBuffer = await tfile.vault.readBinary(tfile);
return new _Base64File({
buffer: arrayBuffer,
filename: tfile.name,
mimeType: inferMimeTypeFromFilename(tfile.name)
});
}
};
// src/utils/base64/base64Conversion.ts
var Base64Conversion = class {
/**
* Extracts the first image payload from a clipboard paste event.
*/
async fromClipboardEvent(event) {
var _a;
const items = (_a = event.clipboardData) == null ? void 0 : _a.items;
if (!items) {
return null;
}
for (const item of Array.from(items)) {
if (!item.type.startsWith("image/")) {
continue;
}
const file = item.getAsFile();
if (file) {
return this.fromFile(file);
}
}
return null;
}
/**
* Extracts the first image payload from the async clipboard API when available.
*/
async fromClipboard() {
var _a;
try {
const items = await navigator.clipboard.read();
for (const item of items) {
const imageType = item.types.find((type) => type.startsWith("image/"));
if (!imageType) {
continue;
}
const blob = await item.getType(imageType);
const arrayBuffer = await blob.arrayBuffer();
return new Base64File({
buffer: arrayBuffer,
filename: `clipboard.${(_a = imageType.split("/")[1]) != null ? _a : "png"}`,
mimeType: imageType
});
}
} catch (e) {
return null;
}
return null;
}
/**
* Converts a browser File into the plugin's image wrapper.
*/
async fromFile(file) {
return Base64File.fromFile(file);
}
/**
* Converts an Obsidian vault file into the plugin's image wrapper.
*/
async fromTFile(tfile) {
return Base64File.fromTFile(tfile);
}
/**
* Resizes an image and returns a PNG payload suitable for inline embedding.
*/
async resize(file, percentage) {
return new Promise((resolve, reject) => {
const blob = new Blob([file.buffer], { type: file.mimeType });
const imageUrl = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) {
URL.revokeObjectURL(imageUrl);
reject(new Error("Could not get canvas context"));
return;
}
const newWidth = Math.round(img.width * (percentage / 100));
const newHeight = Math.round(img.height * (percentage / 100));
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob(async (resizedBlob) => {
if (!resizedBlob) {
URL.revokeObjectURL(imageUrl);
reject(new Error("Could not create blob from canvas"));
return;
}
try {
const arrayBuffer = await resizedBlob.arrayBuffer();
URL.revokeObjectURL(imageUrl);
resolve(new Base64File({
buffer: arrayBuffer,
filename: replaceFilenameExtension(file.filename, "image/png"),
mimeType: "image/png"
}));
} catch (error) {
URL.revokeObjectURL(imageUrl);
reject(error);
}
}, "image/png");
};
img.onerror = () => {
URL.revokeObjectURL(imageUrl);
reject(new Error("Failed to load image"));
};
img.src = imageUrl;
});
}
};
// src/utils/base64/imagePersistence.ts
function splitFilenameParts(filename) {
const lastDot = filename.lastIndexOf(".");
if (lastDot <= 0) {
return {
stem: filename,
extension: ""
};
}
return {
stem: filename.slice(0, lastDot),
extension: filename.slice(lastDot + 1)
};
}
function buildOriginalBackupFilename(file, timestamp) {
const mimeType = normalizeImageMimeType(file.mimeType, file.filename);
const filename = normalizeImageFilename(file.filename, mimeType);
const { stem, extension } = splitFilenameParts(filename);
return extension ? `${stem}_original_${timestamp}.${extension}` : `${stem}_original_${timestamp}`;
}
function createImageFile(file, filename = file.filename) {
const mimeType = normalizeImageMimeType(file.mimeType, filename);
const resolvedFilename = normalizeImageFilename(filename, mimeType);
return new File([file.buffer], resolvedFilename, { type: mimeType });
}
// src/coms/antiLinkExpand.ts
var import_view = require("@codemirror/view");
var INLINE_IMAGE_DATA_URL_REGEX = /data:image\/[^;]+;base64,[^)]+/g;
function findInlineImageDataUrlRanges(text, offset = 0) {
const ranges = [];
const regex = new RegExp(INLINE_IMAGE_DATA_URL_REGEX);
let match;
while ((match = regex.exec(text)) !== null) {
ranges.push({
from: offset + match.index,
to: offset + match.index + match[0].length
});
}
return ranges;
}
function buildVisibleInlineImageDecorations(view) {
const decorations = [];
for (const visibleRange of view.visibleRanges) {
const text = view.state.doc.sliceString(visibleRange.from, visibleRange.to);
const matches = findInlineImageDataUrlRanges(text, visibleRange.from);
for (const match of matches) {
decorations.push(import_view.Decoration.replace({
widget: new InlineImageDataUrlWidget(),
inclusive: true
}).range(match.from, match.to));
}
}
return import_view.Decoration.set(decorations, true);
}
var InlineImageDataUrlWidget = class extends import_view.WidgetType {
/**
* Creates the compact inline replacement widget used in the editor.
*/
constructor() {
super();
}
/**
* Builds the DOM element that visually replaces the inline data URL text.
*/
toDOM() {
const span = document.createElement("span");
span.textContent = "...";
return span;
}
};
var InlineImageDecorationPlugin = class {
/**
* Creates the initial decoration set for the active editor viewport.
*/
constructor(view) {
this.decorations = buildVisibleInlineImageDecorations(view);
}
/**
* Refreshes decorations when edits or viewport changes affect visible inline data URLs.
*/
update(update) {
if (update.docChanged || update.viewportChanged) {
this.decorations = buildVisibleInlineImageDecorations(update.view);
}
}
};
var linkDecorations = import_view.ViewPlugin.fromClass(InlineImageDecorationPlugin, {
decorations: (plugin) => plugin.decorations
});
// src/comsContext/export.ts
var import_obsidian = require("obsidian");
function toArrayBuffer(buffer) {
return Uint8Array.from(buffer).buffer;
}
var ExportToVaultModal = class extends import_obsidian.Modal {
/**
* Stores the initial filename and binary image contents for the export dialog.
*/
constructor(app, filename, buffer) {
super(app);
this.filename = filename;
this.buffer = buffer;
}
/**
* Builds the export form and saves the image into the current note's attachment location.
*/
onOpen() {
const { contentEl } = this;
contentEl.createEl("h2", { text: "Export to Vault" });
const form = contentEl.createEl("form");
const filenameContainer = form.createEl("div", { cls: "setting-item" });
filenameContainer.createEl("label", { text: "Filename" });
const filenameInput = filenameContainer.createEl("input", {
type: "text",
value: this.filename
});
const buttonContainer = form.createEl("div", { cls: "setting-item" });
const exportButton = buttonContainer.createEl("button", {
text: "Save to Vault",
cls: "mod-cta"
});
exportButton.addEventListener("click", async (e) => {
e.preventDefault();
const filename = filenameInput.value || "image.png";
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
const targetPath = await this.app.fileManager.getAvailablePathForAttachment(
filename,
activeFile.path
);
await this.app.vault.createBinary(
targetPath,
this.buffer
);
new import_obsidian.Notice(`Image saved to ${targetPath}`);
}
this.close();
});
}
/**
* Clears the modal contents after the export dialog closes.
*/
onClose() {
const { contentEl } = this;
contentEl.empty();
}
};
async function registerExportToLocal(plugin) {
plugin.registerEvent(
plugin.app.workspace.on("editor-menu", (menu, editor) => {
const cursor = editor.getCursor();
const line = editor.getLine(cursor.line);
const base64Regex = /!\[.*?\]\(data:image\/[^;]+;base64,[^)]+\)/;
const isBase64Image = base64Regex.test(line);
if (isBase64Image) {
menu.addItem((item) => {
item.setTitle("Export to Vault").setIcon("vault").onClick(async () => {
const base64Match = line.match(/data:image\/[^;]+;base64,([^)]+)/);
if (!base64Match) return;
const base64Data = base64Match[1];
const buffer = Buffer.from(base64Data, "base64");
new ExportToVaultModal(plugin.app, "image.png", toArrayBuffer(buffer)).open();
});
});
}
})
);
}
// src/comsContext/convert.ts
var import_obsidian2 = require("obsidian");
var ConvertToBase64Modal = class extends import_obsidian2.Modal {
/**
* Captures the target image file and editor used for the one-line replacement.
*/
constructor(app, file, editor) {
super(app);
this.file = file;
this.editor = editor;
}
/**
* Replaces the current local image embed with an inline Markdown image in the active editor line.
*/
async onOpen() {
const { contentEl } = this;
contentEl.createEl("h2", { text: "Convert to Base64" });
try {
const inlineImage = await Base64File.fromTFile(this.file);
const markdown = `![[${this.file.name}]]`;
const newMarkdown = inlineImage.to64Link();
const cursor = this.editor.getCursor();
const line = this.editor.getLine(cursor.line);
const newLine = line.replace(markdown, newMarkdown);
const lineStart = this.editor.posToOffset({
line: cursor.line,
ch: 0
});
const lineEnd = this.editor.posToOffset({
line: cursor.line,
ch: line.length
});
this.editor.replaceRange(
newLine,
this.editor.offsetToPos(lineStart),
this.editor.offsetToPos(lineEnd)
);
new import_obsidian2.Notice("Image converted to base64");
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
new import_obsidian2.Notice("Failed to convert image: " + message);
}
this.close();
}
/**
* Clears modal contents when the temporary conversion dialog closes.
*/
onClose() {
const { contentEl } = this;
contentEl.empty();
}
};
async function fetchOnlineImage(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch image: HTTP ${response.status}`);
}
const contentType = response.headers.get("content-type");
if (!contentType) {
throw new Error("No content type received from server");
}
const mimeType = contentType.split(";")[0].trim();
if (!contentType.startsWith("image/")) {
throw new Error(
`URL does not point to an image (content-type: ${contentType})`
);
}
const blob = await response.blob();
if (!blob.type.startsWith("image/")) {
throw new Error(`Invalid image format (blob type: ${blob.type})`);
}
const arrayBuffer = await blob.arrayBuffer();
let filename = url.split("/").pop() || "image";
filename = filename.split("?")[0];
if (!filename.includes(".")) {
const ext = mimeType.split("/")[1] || "png";
filename = `${filename}.${ext}`;
}
return new Base64File({ buffer: arrayBuffer, filename, mimeType });
} catch (error) {
if (error instanceof Error) {
throw new Error(`Failed to fetch online image: ${error.message}`);
}
throw new Error("Failed to fetch online image: Unknown error");
}
}
async function handleImageResizing(base64File, plugin, activeFile) {
const sizeInKB = base64File.size / 1024;
let processedFile = base64File;
let shouldSaveAsAttachment = false;
if (plugin.settings.enableResizing) {
if (plugin.settings.resizeStrategy === "smaller") {
if (sizeInKB > plugin.settings.smallerThreshold) {
shouldSaveAsAttachment = true;
}
} else {
if (sizeInKB > plugin.settings.largerThreshold || plugin.settings.resizeSmallerFiles) {
processedFile = await plugin.conversion.resize(
base64File,
plugin.settings.resizePercentage
);
if (plugin.settings.backupOriginalImage && activeFile) {
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
const backupFilename = buildOriginalBackupFilename(base64File, timestamp);
const targetPath = await plugin.app.fileManager.getAvailablePathForAttachment(
backupFilename,
activeFile.path
);
const file = createImageFile(base64File, backupFilename);
await plugin.app.vault.createBinary(
targetPath,
await file.arrayBuffer()
);
}
}
}
}
return { processedFile, shouldSaveAsAttachment };
}
async function convertOnlineImageToBase64(imageUrl, plugin, editor, line, cursor, onlineMatch) {
try {
const base64File = await fetchOnlineImage(imageUrl);
const activeFile = plugin.app.workspace.getActiveFile();
const { processedFile, shouldSaveAsAttachment } = await handleImageResizing(
base64File,
plugin,
activeFile
);
if (shouldSaveAsAttachment && activeFile) {
const file = createImageFile(base64File);
const targetPath = await plugin.app.fileManager.getAvailablePathForAttachment(
base64File.filename,
activeFile.path
);
const newFile = await plugin.app.vault.createBinary(
targetPath,
await file.arrayBuffer()
);
const link = plugin.app.fileManager.generateMarkdownLink(
newFile,
activeFile.path
);
const newLine2 = line.replace(onlineMatch[0], link);
const lineStart2 = editor.posToOffset({
line: cursor.line,
ch: 0
});
const lineEnd2 = editor.posToOffset({
line: cursor.line,
ch: line.length
});
editor.replaceRange(
newLine2,
editor.offsetToPos(lineStart2),
editor.offsetToPos(lineEnd2)
);
new import_obsidian2.Notice("Image saved as attachment due to size");
return;
}
const newLine = line.replace(onlineMatch[0], processedFile.to64Link());
const lineStart = editor.posToOffset({
line: cursor.line,
ch: 0
});
const lineEnd = editor.posToOffset({
line: cursor.line,
ch: line.length
});
editor.replaceRange(
newLine,
editor.offsetToPos(lineStart),
editor.offsetToPos(lineEnd)
);
new import_obsidian2.Notice("Online image converted to base64");
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to convert online image: Unknown error";
new import_obsidian2.Notice(message);
}
}
async function registerConvertImage(plugin) {
plugin.registerEvent(
plugin.app.workspace.on("editor-menu", async (menu, editor) => {
const cursor = editor.getCursor();
const line = editor.getLine(cursor.line);
const localImageRegex = /!\[\[([^\]\n]+\.(png|jpg|jpeg))\]\]/;
const onlineImageRegex = /!\[([^\]]*)\]\((https?:\/\/[^\)]+)\)/;
const localMatch = line.match(localImageRegex);
const onlineMatch = line.match(onlineImageRegex);
if (localMatch) {
const imagePath = localMatch[1];
const activeFile = plugin.app.workspace.getActiveFile();
if (!activeFile) return;
const file = plugin.app.metadataCache.getFirstLinkpathDest(
imagePath,
activeFile.path
);
if (file instanceof import_obsidian2.TFile) {
menu.addItem((item) => {
item.setTitle("Convert to Base64").setIcon("code-glyph").onClick(async () => {
new ConvertToBase64Modal(
plugin.app,
file,
editor
).open();
});
});
}
} else if (onlineMatch) {
const imageUrl = onlineMatch[2];
menu.addItem((item) => {
item.setTitle("Convert online image to base64").setIcon("code-glyph").onClick(async () => {
await convertOnlineImageToBase64(
imageUrl,
plugin,
editor,
line,
cursor,
onlineMatch
);
});
});
}
})
);
}
// src/commands/selectAndConvert.ts
var import_obsidian3 = require("obsidian");
var CONVERT_DEBUG_PREFIX = "[image-inline:convert-images]";
function logConvertDebug(message, details) {
if (details === void 0) {
console.debug(CONVERT_DEBUG_PREFIX, message);
return;
}
console.debug(CONVERT_DEBUG_PREFIX, message, details);
}
function logConvertWarning(message, details) {
if (details === void 0) {
console.warn(CONVERT_DEBUG_PREFIX, message);
return;
}
console.warn(CONVERT_DEBUG_PREFIX, message, details);
}
function logConvertError(message, details) {
if (details === void 0) {
console.error(CONVERT_DEBUG_PREFIX, message);
return;
}
console.error(CONVERT_DEBUG_PREFIX, message, details);
}
var ConvertImagesModal = class extends import_obsidian3.Modal {
/**
* Stores the plugin reference and default conversion options for the modal session.
*/
constructor(app, plugin) {
super(app);
this.plugin = plugin;
this.conversionScope = "note";
this.conversionType = "toBase64";
}
/**
* Builds the modal UI for choosing conversion scope and direction.
*/
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Convert Images" });
const scopeContainer = contentEl.createEl("div", { cls: "setting-item" });
scopeContainer.createEl("label", { text: "Scope" });
const scopeSelect = scopeContainer.createEl("select");
const scopes = [
{ value: "note", text: "Current Note" },
{ value: "folder", text: "Current Folder" },
{ value: "vault", text: "Entire Vault" }
];
scopes.forEach((scope) => {
scopeSelect.createEl("option", {
value: scope.value,
text: scope.text
});
});
const typeContainer = contentEl.createEl("div", { cls: "setting-item" });
typeContainer.createEl("label", { text: "Conversion Type" });
const typeSelect = typeContainer.createEl("select");
const types = [
{ value: "toBase64", text: "Image Files \u2192 Base64" },
{ value: "toImage", text: "Base64 \u2192 Image Files" }
];
types.forEach((type) => {
typeSelect.createEl("option", {
value: type.value,
text: type.text
});
});
const buttonContainer = contentEl.createEl("div", { cls: "setting-item" });
const convertButton = buttonContainer.createEl("button", {
text: "Convert",
cls: "mod-cta"
});
convertButton.addEventListener("click", async () => {
this.conversionScope = scopeSelect.value;
this.conversionType = typeSelect.value;
await this.performConversion();
this.close();
});
}
/**
* Runs the requested batch conversion over the selected note scope.
*/
async performConversion() {
const files = await this.getFilesInScope();
let converted = 0;
logConvertDebug("Starting batch conversion", {
scope: this.conversionScope,
conversionType: this.conversionType,
fileCount: files.length
});
for (const file of files) {
if (this.conversionType === "toBase64") {
const modified = await this.convertToBase64(file);
if (modified) {
converted++;
}
} else {
const modified = await this.convertToImages(file);
if (modified) {
converted++;
}
}
}
logConvertDebug("Completed batch conversion", {
scope: this.conversionScope,
conversionType: this.conversionType,
converted,
totalFiles: files.length
});
new import_obsidian3.Notice(`Converted ${converted} files`);
}
/**
* Collects markdown files for the currently selected conversion scope.
*/
async getFilesInScope() {
switch (this.conversionScope) {
case "note":
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile) {
logConvertWarning("No active file was available for note-scoped conversion");
return [];
}
return [activeFile];
case "folder":
const currentFile = this.app.workspace.getActiveFile();
if (!(currentFile == null ? void 0 : currentFile.parent)) {
logConvertWarning("No active folder was available for folder-scoped conversion");
return [];
}
return this.app.vault.getMarkdownFiles().filter((f) => f.parent === currentFile.parent);
case "vault":
return this.app.vault.getMarkdownFiles();
default:
return [];
}
}
/**
* Returns the active editor when the target file is currently open, otherwise null.
*/
getActiveEditorForFile(file) {
var _a, _b;
const activeFile = this.app.workspace.getActiveFile();
const activeEditor = (_b = (_a = this.app.workspace.activeEditor) == null ? void 0 : _a.editor) != null ? _b : null;
if (!activeFile || activeFile.path !== file.path || !activeEditor) {
return null;
}
return activeEditor;
}
/**
* Updates a markdown file atomically in the vault or through the active editor when it is open.
*/
async updateMarkdownFile(file, updater) {
const activeEditor = this.getActiveEditorForFile(file);
if (activeEditor) {
const currentContent = activeEditor.getValue();
const updatedContent = updater(currentContent);
if (updatedContent === currentContent) {
logConvertDebug("Skipped editor update because content did not change", {
file: file.path
});
return false;
}
activeEditor.setValue(updatedContent);
logConvertDebug("Updated open note through active editor", {
file: file.path
});
return true;
}
let modified = false;
await this.app.vault.process(file, (content) => {
const updatedContent = updater(content);
modified = updatedContent !== content;
return updatedContent;
});
if (modified) {
logConvertDebug("Updated closed note through vault.process", {
file: file.path
});
} else {
logConvertDebug("Skipped vault.process update because content did not change", {
file: file.path
});
}
return modified;
}
/**
* Applies exact-string replacements to markdown content in a deterministic sequence.
*/
applyReplacements(content, replacements) {
let updatedContent = content;
for (const replacement of replacements) {
updatedContent = updatedContent.replace(replacement.from, replacement.to);
}
return updatedContent;
}
/**
* Rewrites local image embeds in a note into MIME-aware inline data URLs.
*/
async convertToBase64(file) {
const content = await this.app.vault.read(file);
const imageRegex = /!\[\[([^\]]+\.(png|jpg|jpeg))\]\]/g;
const replacements = [];
let match;
while ((match = imageRegex.exec(content)) !== null) {
const imagePath = match[1];
const imageFile = this.app.metadataCache.getFirstLinkpathDest(imagePath, file.path);
if (!(imageFile instanceof import_obsidian3.TFile)) {
logConvertWarning("Skipped image embed because the linked file could not be resolved", {
note: file.path,
imagePath
});
continue;
}
try {
replacements.push({
from: match[0],
to: (await Base64File.fromTFile(imageFile)).to64Link()
});
} catch (error) {
logConvertError("Failed to convert image embed to base64", {
note: file.path,
imagePath: imageFile.path,
error
});
continue;
}
}
logConvertDebug("Prepared base64 replacements", {
file: file.path,
replacements: replacements.length
});
return this.updateMarkdownFile(file, (currentContent) => {
return this.applyReplacements(currentContent, replacements);
});
}
/**
* Writes inline data URLs back to vault attachments while preserving their image metadata.
*/
async convertToImages(file) {
const content = await this.app.vault.read(file);
const base64Regex = /!\[.*?\]\(data:image\/[^;]+;base64,[^)]+\)/g;
const replacements = [];
let match;
while ((match = base64Regex.exec(content)) !== null) {
const base64File = Base64File.from64Link(match[0]);
if (!base64File) {
logConvertWarning("Skipped inline image because the data URL could not be parsed", {
note: file.path
});
continue;
}
try {
const targetPath = await this.app.fileManager.getAvailablePathForAttachment(
base64File.filename,
file.path
);
const imageFile = createImageFile(base64File);
await this.app.vault.createBinary(targetPath, await imageFile.arrayBuffer());
const newFile = this.app.vault.getAbstractFileByPath(targetPath);
if (newFile instanceof import_obsidian3.TFile) {
replacements.push({
from: match[0],
to: this.app.fileManager.generateMarkdownLink(newFile, file.path)
});
continue;
}
logConvertWarning("Created an attachment but could not resolve it back from the vault", {
note: file.path,
targetPath
});
} catch (error) {
logConvertError("Failed to materialize inline image as an attachment", {
note: file.path,
filename: base64File.filename,
error
});
}
}
logConvertDebug("Prepared attachment replacements", {
file: file.path,
replacements: replacements.length
});
return this.updateMarkdownFile(file, (currentContent) => {
return this.applyReplacements(currentContent, replacements);
});