-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1816 lines (1802 loc) · 65.2 KB
/
Copy pathmain.js
File metadata and controls
1816 lines (1802 loc) · 65.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: () => BrowserBookmarkPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian8 = require("obsidian");
// src/types.ts
var DEFAULT_SETTINGS = {
openIn: "tab",
interceptLinks: false,
showFavicons: true,
showRibbonIcon: true,
readLaterFolderName: "Read Later"
};
var DEFAULT_DATA = {
items: [],
settings: DEFAULT_SETTINGS
};
var VIEW_TYPE_BROWSER_BOOKMARK = "browser-bookmark-view";
var PINNED_PARENT_ID = "__pinned__";
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substring(2, 9);
}
// src/store.ts
var BookmarkStore = class {
constructor(plugin) {
this.listeners = [];
this.plugin = plugin;
this.data = { items: [], settings: { ...DEFAULT_SETTINGS } };
}
async load() {
var _a, _b;
const saved = await this.plugin.loadData();
this.data = {
items: (_a = saved == null ? void 0 : saved.items) != null ? _a : DEFAULT_DATA.items,
settings: { ...DEFAULT_SETTINGS, ...(_b = saved == null ? void 0 : saved.settings) != null ? _b : {} }
};
}
async save() {
await this.plugin.saveData(this.data);
}
onChange(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter((l) => l !== listener);
};
}
notify() {
for (const listener of this.listeners)
listener();
}
get settings() {
return this.data.settings;
}
async updateSettings(patch) {
this.data.settings = { ...this.data.settings, ...patch };
await this.save();
this.notify();
}
get items() {
return this.data.items;
}
children(parentId) {
return this.data.items.filter((item) => item.parentId === parentId).sort((a, b) => a.order - b.order);
}
nextOrder(parentId) {
const siblings = this.children(parentId);
return siblings.length > 0 ? Math.max(...siblings.map((s) => s.order)) + 1 : 0;
}
async addBookmark(title, url, parentId = null, fields = {}) {
const node = {
id: generateId(),
type: "bookmark",
title,
url,
parentId,
order: this.nextOrder(parentId),
iconType: fields.iconType,
iconValue: fields.iconValue,
description: fields.description
};
this.data.items.push(node);
await this.save();
this.notify();
return node;
}
/**
* Finds a root-level folder by exact title, creating it if missing. Used to
* land bookmarks saved from the companion browser extension in a
* consistent place (e.g. "Read Later") without the extension needing any
* visibility into the vault's folder tree.
*/
async getOrCreateRootFolder(title) {
const existing = this.children(null).find((item) => item.type === "folder" && item.title === title);
if (existing)
return existing;
return this.addFolder(title, null);
}
async addFolder(title, parentId = null) {
const node = {
id: generateId(),
type: "folder",
title,
parentId,
order: this.nextOrder(parentId),
collapsed: false
};
this.data.items.push(node);
await this.save();
this.notify();
return node;
}
/** Normalizes a URL for comparison: trims whitespace and a single trailing slash. */
static normalizeUrl(url) {
const trimmed = url.trim();
return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
}
/** Finds an existing bookmark with the same URL, excluding `excludeId` (the one being edited). */
findByUrl(url, excludeId) {
const target = BookmarkStore.normalizeUrl(url);
if (!target)
return void 0;
return this.data.items.find(
(item) => item.type === "bookmark" && item.id !== excludeId && item.url !== void 0 && BookmarkStore.normalizeUrl(item.url) === target
);
}
/**
* Appends a batch of already-fully-formed nodes (e.g. from a bookmark
* import) in one save+notify, instead of one per node -- an import can be
* hundreds of nodes, and addBookmark/addFolder each write the whole
* data.json to disk, which would otherwise thrash on a big import.
*/
async importNodes(nodes) {
if (nodes.length === 0)
return;
this.data.items.push(...nodes);
await this.save();
this.notify();
}
async rename(id, title) {
const node = this.data.items.find((i) => i.id === id);
if (!node)
return;
node.title = title;
await this.save();
this.notify();
}
async updateBookmark(id, title, url, fields = {}) {
const node = this.data.items.find((i) => i.id === id);
if (!node)
return;
node.title = title;
node.url = url;
node.iconType = fields.iconType;
node.iconValue = fields.iconValue;
node.description = fields.description;
await this.save();
this.notify();
}
async toggleCollapsed(id) {
const node = this.data.items.find((i) => i.id === id);
if (!node || node.type !== "folder")
return;
node.collapsed = !node.collapsed;
await this.save();
this.notify();
}
async toggleOpenExternally(id) {
const node = this.data.items.find((i) => i.id === id);
if (!node || node.type !== "bookmark")
return;
node.openExternally = !node.openExternally;
await this.save();
this.notify();
}
/** Removes a node. If it's a folder, its descendants are removed too. */
async remove(id) {
const idsToRemove = /* @__PURE__ */ new Set([id]);
let grew = true;
while (grew) {
grew = false;
for (const item of this.data.items) {
if (item.parentId && idsToRemove.has(item.parentId) && !idsToRemove.has(item.id)) {
idsToRemove.add(item.id);
grew = true;
}
}
}
this.data.items = this.data.items.filter((i) => !idsToRemove.has(i.id));
await this.save();
this.notify();
}
/** Returns true if `ancestorId` is `id` itself or one of its ancestors. */
isDescendantOf(id, ancestorId) {
let current = this.data.items.find((i) => i.id === id);
while (current) {
if (current.id === ancestorId)
return true;
current = current.parentId ? this.data.items.find((i) => i.id === current.parentId) : void 0;
}
return false;
}
/**
* Moves `id` to be a child of `newParentId`, inserted at `index` among its
* new siblings. Reordering within the same parent is just a move to a new
* index there, so this single method covers both drag gestures. Pinning is
* also just a move -- `PINNED_PARENT_ID` is a reserved parentId, not a real
* folder, so no special-casing is needed for rename/delete/reorder on a
* pinned bookmark, only for the two convenience wrappers below.
*/
async moveInto(id, newParentId, index) {
const node = this.data.items.find((i) => i.id === id);
if (!node)
return;
if (newParentId && (newParentId === id || this.isDescendantOf(newParentId, id)))
return;
node.parentId = newParentId;
const siblings = this.children(newParentId).filter((s) => s.id !== id);
siblings.splice(Math.max(0, Math.min(index, siblings.length)), 0, node);
siblings.forEach((s, i) => {
s.order = i;
});
await this.save();
this.notify();
}
get pinned() {
return this.children(PINNED_PARENT_ID);
}
async pin(id) {
await this.moveInto(id, PINNED_PARENT_ID, this.children(PINNED_PARENT_ID).length);
}
/** Unpins to the root of the tree, not back to wherever it was before pinning -- simpler and more predictable than tracking a prior location that could itself have been deleted or reorganized since. */
async unpin(id) {
await this.moveInto(id, null, this.children(null).length);
}
};
// src/views/BookmarkListView.ts
var import_obsidian6 = require("obsidian");
// src/webviewer.ts
var import_obsidian = require("obsidian");
function isWebViewerAvailable(app) {
var _a, _b;
if (import_obsidian.Platform.isMobile)
return false;
const internalPlugins = app.internalPlugins;
return ((_b = (_a = internalPlugins == null ? void 0 : internalPlugins.plugins) == null ? void 0 : _a.webviewer) == null ? void 0 : _b.enabled) === true;
}
async function openExternally(url) {
if (import_obsidian.Platform.isDesktop) {
try {
const electron = require("electron");
await electron.shell.openExternal(url);
return;
} catch (err) {
console.error("Browser Bookmark: shell.openExternal threw, falling back to window.open", err);
}
}
window.open(url, "_blank");
}
async function openBookmark(app, url, paneType) {
if (isWebViewerAvailable(app)) {
try {
const leaf = app.workspace.getLeaf(paneType);
await leaf.setViewState({
type: "webviewer",
state: { url, navigate: true },
active: true
});
await app.workspace.revealLeaf(leaf);
return;
} catch (e) {
}
}
await openExternally(url);
}
async function openInSystemBrowser(url) {
await openExternally(url);
}
function getActiveWebViewerPage(app) {
var _a;
const leaf = app.workspace.getMostRecentLeaf();
if (!leaf)
return null;
const state = leaf.getViewState();
if (state.type !== "webviewer")
return null;
const url = (_a = state.state) == null ? void 0 : _a.url;
if (!url)
return null;
return { url, title: leaf.getDisplayText() || url };
}
// src/import.ts
var import_obsidian2 = require("obsidian");
function loadNodeFsModulesSync() {
const fs = require("fs");
const os = require("os");
const path = require("path");
return { fs, os, path };
}
function findArcSidebarFile() {
if (!import_obsidian2.Platform.isDesktop)
return null;
try {
const { fs, os, path } = loadNodeFsModulesSync();
if (import_obsidian2.Platform.isMacOS) {
const filePath = path.join(os.homedir(), "Library", "Application Support", "Arc", "StorableSidebar.json");
return fs.existsSync(filePath) ? filePath : null;
}
if (import_obsidian2.Platform.isWin) {
const packagesDir = path.join(os.homedir(), "AppData", "Local", "Packages");
if (!fs.existsSync(packagesDir))
return null;
const arcDir = fs.readdirSync(packagesDir).find((name) => name.startsWith("TheBrowserCompany.Arc"));
if (!arcDir)
return null;
const filePath = path.join(packagesDir, arcDir, "LocalCache", "Local", "Arc", "StorableSidebar.json");
return fs.existsSync(filePath) ? filePath : null;
}
} catch (e) {
}
return null;
}
function readArcSidebarFile(path) {
const { fs } = loadNodeFsModulesSync();
return fs.readFileSync(path, "utf8");
}
function emptyBatch() {
return { nodes: [], bookmarkCount: 0, folderCount: 0 };
}
function finalizeImport(batch, wrapperTitle) {
var _a;
const wrapperId = generateId();
const wrapper = {
id: wrapperId,
type: "folder",
title: wrapperTitle,
parentId: null,
order: 0,
collapsed: false
};
const nodes = batch.nodes.map(
(node) => node.parentId === null ? { ...node, parentId: wrapperId } : node
);
const orderCounters = /* @__PURE__ */ new Map();
for (const node of nodes) {
const count = (_a = orderCounters.get(node.parentId)) != null ? _a : 0;
node.order = count;
orderCounters.set(node.parentId, count + 1);
}
return [wrapper, ...nodes];
}
function parseNetscapeHtml(html) {
const doc = new DOMParser().parseFromString(html, "text/html");
const rootDl = doc.querySelector("dl");
const batch = emptyBatch();
if (!rootDl)
return batch;
walkNetscapeDl(rootDl, null, batch);
return batch;
}
function walkNetscapeDl(dl, parentId, batch) {
var _a, _b, _c;
const children = Array.from(dl.children);
for (let i = 0; i < children.length; i++) {
const el = children[i];
if (el.tagName === "DL") {
walkNetscapeDl(el, parentId, batch);
continue;
}
if (el.tagName !== "DT")
continue;
const h3 = el.querySelector(":scope > h3");
const a = el.querySelector(":scope > a");
if (h3) {
const folderId = generateId();
batch.nodes.push({
id: folderId,
type: "folder",
title: ((_a = h3.textContent) == null ? void 0 : _a.trim()) || "Imported folder",
parentId,
order: 0,
collapsed: false
});
batch.folderCount++;
let childDl = el.querySelector(":scope > dl");
if (!childDl && ((_b = children[i + 1]) == null ? void 0 : _b.tagName) === "DL") {
childDl = children[i + 1];
i++;
}
if (childDl)
walkNetscapeDl(childDl, folderId, batch);
} else if (a) {
const url = a.getAttribute("href");
if (!url)
continue;
batch.nodes.push({
id: generateId(),
type: "bookmark",
title: ((_c = a.textContent) == null ? void 0 : _c.trim()) || url,
url,
parentId,
order: 0
});
batch.bookmarkCount++;
}
}
}
function cleanArcUrl(url) {
return url.replace(/\\\//g, "/").trim();
}
function isRecord(value) {
return typeof value === "object" && value !== null;
}
function parseArcSidebarJson(json) {
var _a, _b;
const batch = emptyBatch();
const data = JSON.parse(json);
if (!isRecord(data))
return batch;
const containers = (_a = data.sidebar) == null ? void 0 : _a.containers;
if (!Array.isArray(containers))
return batch;
const container = containers.find(
(c) => isRecord(c) && Array.isArray(c.items) && Array.isArray(c.spaces)
);
if (!container)
return batch;
const itemsById = /* @__PURE__ */ new Map();
for (const raw of container.items) {
if (isRecord(raw) && typeof raw.id === "string")
itemsById.set(raw.id, raw);
}
const extractPinnedContainerIds = (space) => {
var _a2;
const source = (_a2 = space.newContainerIDs) != null ? _a2 : space.containerIDs;
if (!Array.isArray(source))
return [];
const ids = [];
for (let i = 0; i < source.length; i++) {
const marker = source[i];
const label = typeof marker === "string" ? marker : isRecord(marker) ? Object.keys(marker)[0] : void 0;
if (label !== "pinned")
continue;
const idEntry = source[i + 1];
if (typeof idEntry === "string")
ids.push(idEntry);
}
return ids;
};
const walkChildren = (childrenIds, parentId) => {
var _a2, _b2, _c, _d;
for (const rawId of childrenIds != null ? childrenIds : []) {
if (typeof rawId !== "string")
continue;
const item = itemsById.get(rawId);
if (!item)
continue;
if ((_a2 = item.data) == null ? void 0 : _a2.tab) {
const rawUrl = item.data.tab.savedURL;
if (!rawUrl)
continue;
const url = cleanArcUrl(rawUrl);
batch.nodes.push({
id: generateId(),
type: "bookmark",
title: ((_b2 = item.data.tab.savedTitle) == null ? void 0 : _b2.trim()) || url,
url,
parentId,
order: 0
});
batch.bookmarkCount++;
} else if ((_c = item.data) == null ? void 0 : _c.list) {
const folderId = generateId();
batch.nodes.push({
id: folderId,
type: "folder",
title: ((_d = item.title) == null ? void 0 : _d.trim()) || "Imported folder",
parentId,
order: 0,
collapsed: false
});
batch.folderCount++;
walkChildren(item.childrenIds, folderId);
} else {
walkChildren(item.childrenIds, parentId);
}
}
};
for (const rawSpace of container.spaces) {
if (!isRecord(rawSpace))
continue;
const space = rawSpace;
const spaceFolderId = generateId();
const beforeCount = batch.nodes.length;
const spaceNode = {
id: spaceFolderId,
type: "folder",
title: ((_b = space.title) == null ? void 0 : _b.trim()) || "Arc space",
parentId: null,
order: 0,
collapsed: false
};
for (const containerId of extractPinnedContainerIds(space)) {
const containerItem = itemsById.get(containerId);
if (containerItem)
walkChildren(containerItem.childrenIds, spaceFolderId);
}
if (batch.nodes.length > beforeCount) {
batch.nodes.splice(beforeCount, 0, spaceNode);
batch.folderCount++;
}
}
return batch;
}
// src/export.ts
function escapeHtml(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function childrenOf(items, parentId) {
return items.filter((item) => item.parentId === parentId).sort((a, b) => a.order - b.order);
}
function renderNode(items, node, depth) {
var _a;
const indent = " ".repeat(depth);
if (node.type === "folder") {
const kids = childrenOf(items, node.id);
return `${indent}<DT><H3>${escapeHtml(node.title)}</H3>
${indent}<DL><p>
` + kids.map((kid) => renderNode(items, kid, depth + 1)).join("") + `${indent}</DL><p>
`;
}
return `${indent}<DT><A HREF="${escapeHtml((_a = node.url) != null ? _a : "")}">${escapeHtml(node.title)}</A>
`;
}
function exportToNetscapeHtml(items) {
const rootItems = childrenOf(items, null);
const pinnedItems = childrenOf(items, PINNED_PARENT_ID);
let body = rootItems.map((node) => renderNode(items, node, 1)).join("");
if (pinnedItems.length > 0) {
body += " <DT><H3>Pinned</H3>\n <DL><p>\n" + pinnedItems.map((node) => renderNode(items, node, 2)).join("") + " </DL><p>\n";
}
return '<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">\n<TITLE>Bookmarks</TITLE>\n<H1>Bookmarks</H1>\n<DL><p>\n' + body + "</DL><p>\n";
}
// src/modals/BookmarkEditModal.ts
var import_obsidian3 = require("obsidian");
var BookmarkEditModal = class extends import_obsidian3.Modal {
constructor(app, heading, initial, onSubmit, findDuplicateTitle) {
var _a, _b, _c, _d, _e;
super(app);
this.heading = heading;
this.onSubmit = onSubmit;
this.findDuplicateTitle = findDuplicateTitle;
this.title_ = (_a = initial.title) != null ? _a : "";
this.url = (_b = initial.url) != null ? _b : "";
this.description = (_c = initial.description) != null ? _c : "";
this.iconType = (_d = initial.iconType) != null ? _d : "auto";
this.iconValue = (_e = initial.iconValue) != null ? _e : "";
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: this.heading });
new import_obsidian3.Setting(contentEl).setName("Title").addText(
(text) => text.setPlaceholder("My bookmark").setValue(this.title_).onChange((value) => this.title_ = value)
);
new import_obsidian3.Setting(contentEl).setName("Description").setDesc("Optional. Shown below the title in the sidebar, e.g. as a reminder of why you saved it.").addText(
(text) => text.setPlaceholder("What this is for").setValue(this.description).onChange((value) => this.description = value)
);
let updateWarning = () => {
};
new import_obsidian3.Setting(contentEl).setName("URL").addText(
(text) => text.setPlaceholder("https://example.com").setValue(this.url).onChange((value) => {
this.url = value;
updateWarning();
})
);
const warningEl = contentEl.createDiv({ cls: "browser-bookmark-modal-warning" });
updateWarning = () => {
var _a;
const existing = (_a = this.findDuplicateTitle) == null ? void 0 : _a.call(this, this.url.trim());
warningEl.setText(existing ? `Already bookmarked as "${existing}".` : "");
warningEl.toggleClass("is-visible", Boolean(existing));
};
updateWarning();
let updateIconUi = () => {
};
new import_obsidian3.Setting(contentEl).setName("Icon").setDesc("Auto uses the site's favicon.").addDropdown(
(dropdown) => dropdown.addOption("auto", "Auto (favicon)").addOption("lucide", "Icon name").addOption("image", "Image URL").setValue(this.iconType).onChange((value) => {
this.iconType = value;
updateIconUi();
})
);
let iconValueInputEl;
const iconValueSetting = new import_obsidian3.Setting(contentEl).addText((text) => {
text.setValue(this.iconValue).onChange((value) => {
this.iconValue = value;
updateIconUi();
});
iconValueInputEl = text.inputEl;
});
const previewEl = contentEl.createDiv({ cls: "browser-bookmark-icon-preview" });
updateIconUi = () => {
const isAuto = this.iconType === "auto";
iconValueSetting.settingEl.toggleClass("browser-bookmark-hidden", isAuto);
if (this.iconType === "lucide") {
iconValueSetting.setName("Icon name");
iconValueInputEl.placeholder = "e.g. star, bookmark, book-marked";
} else if (this.iconType === "image") {
iconValueSetting.setName("Image URL");
iconValueInputEl.placeholder = "https://example.com/icon.png";
}
previewEl.empty();
const value = this.iconValue.trim();
if (isAuto || !value)
return;
if (this.iconType === "lucide") {
(0, import_obsidian3.setIcon)(previewEl, value);
} else {
const img = previewEl.createEl("img", { attr: { src: value } });
img.addEventListener(
"error",
() => {
img.remove();
previewEl.setText("Could not load that image.");
},
{ once: true }
);
}
};
updateIconUi();
new import_obsidian3.Setting(contentEl).addButton(
(btn) => btn.setButtonText("Save").setCta().onClick(() => {
const trimmedUrl = this.url.trim();
if (!trimmedUrl) {
new import_obsidian3.Notice("A URL is required.");
return;
}
const trimmedTitle = this.title_.trim() || trimmedUrl;
const trimmedIconValue = this.iconValue.trim();
const useCustomIcon = this.iconType !== "auto" && Boolean(trimmedIconValue);
this.onSubmit({
title: trimmedTitle,
url: trimmedUrl,
description: this.description.trim() || void 0,
iconType: useCustomIcon ? this.iconType : void 0,
iconValue: useCustomIcon ? trimmedIconValue : void 0
});
this.close();
})
);
}
onClose() {
this.contentEl.empty();
}
};
// src/modals/FolderEditModal.ts
var import_obsidian4 = require("obsidian");
var FolderEditModal = class extends import_obsidian4.Modal {
constructor(app, heading, initialName, onSubmit) {
super(app);
this.heading = heading;
this.onSubmit = onSubmit;
this.name = initialName;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: this.heading });
new import_obsidian4.Setting(contentEl).setName("Folder name").addText((text) => {
text.setPlaceholder("New folder").setValue(this.name).onChange((value) => this.name = value);
text.inputEl.focus();
});
new import_obsidian4.Setting(contentEl).addButton(
(btn) => btn.setButtonText("Save").setCta().onClick(() => {
const trimmed = this.name.trim();
if (!trimmed) {
new import_obsidian4.Notice("A folder name is required.");
return;
}
this.onSubmit(trimmed);
this.close();
})
);
}
onClose() {
this.contentEl.empty();
}
};
// src/modals/ImportPreviewModal.ts
var import_obsidian5 = require("obsidian");
var PREVIEW_LIMIT = 12;
var ImportPreviewModal = class extends import_obsidian5.Modal {
constructor(app, batch, defaultFolderName, onConfirm) {
super(app);
this.batch = batch;
this.onConfirm = onConfirm;
this.folderName = defaultFolderName;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: "Import bookmarks" });
const bookmarkLabel = `${this.batch.bookmarkCount} bookmark${this.batch.bookmarkCount === 1 ? "" : "s"}`;
const folderLabel = `${this.batch.folderCount} folder${this.batch.folderCount === 1 ? "" : "s"}`;
contentEl.createEl("p", { text: `Found ${bookmarkLabel} in ${folderLabel}.` });
new import_obsidian5.Setting(contentEl).setName("Import into new folder").addText(
(text) => text.setValue(this.folderName).onChange((value) => this.folderName = value)
);
const topLevel = this.batch.nodes.filter((n) => n.parentId === null);
if (topLevel.length > 0) {
contentEl.createEl("p", {
text: "Top-level items:",
cls: "browser-bookmark-import-preview-label"
});
const list = contentEl.createEl("ul", { cls: "browser-bookmark-import-preview-list" });
for (const node of topLevel.slice(0, PREVIEW_LIMIT)) {
list.createEl("li", { text: node.title });
}
if (topLevel.length > PREVIEW_LIMIT) {
list.createEl("li", {
text: `\u2026and ${topLevel.length - PREVIEW_LIMIT} more`,
cls: "browser-bookmark-import-preview-more"
});
}
}
new import_obsidian5.Setting(contentEl).addButton((btn) => btn.setButtonText("Cancel").onClick(() => this.close())).addButton(
(btn) => btn.setButtonText("Import").setCta().onClick(() => {
const name = this.folderName.trim();
if (!name) {
new import_obsidian5.Notice("A folder name is required.");
return;
}
this.onConfirm(name);
this.close();
})
);
}
onClose() {
this.contentEl.empty();
}
};
// src/views/BookmarkListView.ts
function extractLinkFromDataTransfer(dt) {
var _a;
if (!dt)
return null;
const uriList = dt.getData("text/uri-list");
const line = uriList.split("\n").map((s) => s.trim()).find((s) => s && !s.startsWith("#"));
if (line)
return { title: line, url: line };
const html = dt.getData("text/html");
if (html) {
const anchor = new DOMParser().parseFromString(html, "text/html").querySelector("a[href]");
const href = anchor == null ? void 0 : anchor.getAttribute("href");
if (href)
return { title: ((_a = anchor == null ? void 0 : anchor.textContent) == null ? void 0 : _a.trim()) || href, url: href };
}
const text = dt.getData("text/plain").trim();
if (text) {
const markdownLink = text.match(/^\[([^\]]+)\]\((\S+)\)$/);
if (markdownLink)
return { title: markdownLink[1], url: markdownLink[2] };
try {
return { title: text, url: new URL(text).href };
} catch (e) {
}
}
return null;
}
function hasLinkData(dt) {
if (!dt)
return false;
return dt.types.includes("text/uri-list") || dt.types.includes("text/html") || dt.types.includes("text/plain");
}
var BookmarkListView = class extends import_obsidian6.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.plugin = plugin;
this.draggedId = null;
this.dropMarkedEl = null;
this.unsubscribe = null;
this.searchActive = false;
this.searchQuery = "";
this.visibleOrder = [];
this.focusedId = null;
this.store = plugin.store;
}
getViewType() {
return VIEW_TYPE_BROWSER_BOOKMARK;
}
getDisplayText() {
return "Browser bookmarks";
}
getIcon() {
return "bookmark";
}
async onOpen() {
const container = this.contentEl;
container.empty();
container.addClass("browser-bookmark-view");
const toolbar = container.createDiv({ cls: "browser-bookmark-toolbar" });
this.makeIconButton(toolbar, "file-plus", "New bookmark", () => this.createBookmark(null));
this.makeIconButton(toolbar, "folder-plus", "New folder", () => this.createFolder(null));
this.makeIconButton(toolbar, "download", "Import / export bookmarks", (evt) => this.openImportMenu(evt));
this.makeIconButton(toolbar, "search", "Search", () => this.toggleSearch()).addClass(
"browser-bookmark-search-toggle"
);
this.pinnedRowEl = container.createDiv({ cls: "browser-bookmark-pinned-row" });
this.registerPinnedRowDropZone();
this.searchInputEl = container.createEl("input", {
cls: "browser-bookmark-search-input",
attr: { type: "text", placeholder: "Search bookmarks\u2026" }
});
this.searchInputEl.addEventListener("input", () => {
this.searchQuery = this.searchInputEl.value;
this.render();
});
this.searchInputEl.addEventListener("keydown", (evt) => {
if (evt.key === "Escape") {
evt.preventDefault();
this.toggleSearch(false);
}
});
this.treeEl = container.createDiv({ cls: "browser-bookmark-tree", attr: { tabindex: "0" } });
this.registerRootDropZone(this.treeEl);
this.treeEl.addEventListener("keydown", (evt) => this.handleKeydown(evt));
this.unsubscribe = this.store.onChange(() => this.render());
this.render();
}
toggleSearch(forceOpen) {
this.searchActive = forceOpen != null ? forceOpen : !this.searchActive;
this.searchInputEl.toggleClass("is-visible", this.searchActive);
if (this.searchActive) {
this.searchInputEl.focus();
} else {
this.searchInputEl.value = "";
this.searchQuery = "";
this.render();
}
}
async onClose() {
var _a;
(_a = this.unsubscribe) == null ? void 0 : _a.call(this);
}
makeIconButton(parent, icon, label, onClick) {
const btn = parent.createDiv({ cls: "browser-bookmark-icon-btn", attr: { "aria-label": label } });
(0, import_obsidian6.setIcon)(btn, icon);
btn.addEventListener("click", onClick);
return btn;
}
matchesQuery(node, query) {
var _a, _b;
if (node.type === "bookmark") {
return node.title.toLowerCase().includes(query) || ((_a = node.url) != null ? _a : "").toLowerCase().includes(query) || ((_b = node.description) != null ? _b : "").toLowerCase().includes(query);
}
return this.store.children(node.id).some((child) => this.matchesQuery(child, query));
}
render() {
this.renderPinnedRow();
this.treeEl.empty();
this.visibleOrder = [];
const query = this.searchQuery.trim().toLowerCase();
const roots = this.store.children(null).filter((n) => !query || this.matchesQuery(n, query));
if (roots.length === 0) {
this.treeEl.createDiv({
cls: "browser-bookmark-empty",
text: query ? "No matches." : "No bookmarks yet."
});
return;
}
for (const node of roots)
this.renderNode(this.treeEl, node, 0, query);
}
renderNode(parentEl, node, depth, query) {
if (node.type === "folder")
this.renderFolder(parentEl, node, depth, query);
else
this.renderBookmark(parentEl, node, depth);
}
renderRowShell(parentEl, node, depth, extraCls = "") {
const row = parentEl.createDiv({
cls: `browser-bookmark-row ${extraCls}`.trim(),
attr: { "data-node-id": node.id, style: `padding-left: ${8 + depth * 16}px` }
});
const grip = row.createDiv({ cls: "browser-bookmark-grip", attr: { draggable: "true" } });
(0, import_obsidian6.setIcon)(grip, "grip-vertical");
this.wireDrag(row, grip, node);
this.visibleOrder.push(node.id);
if (node.id === this.focusedId)
row.addClass("is-focused");
row.addEventListener("mousedown", (evt) => {
if (evt.target.tagName === "INPUT")
return;
this.setFocus(node.id);
});
return row;
}
renderFolder(parentEl, node, depth, query) {
const wrapper = parentEl.createDiv({ cls: "browser-bookmark-folder" });
const row = this.renderRowShell(wrapper, node, depth, "browser-bookmark-group-header");
const expanded = query ? true : !node.collapsed;
const chevron = row.createDiv({ cls: "browser-bookmark-chevron" });
(0, import_obsidian6.setIcon)(chevron, expanded ? "chevron-down" : "chevron-right");
const title = row.createSpan({ cls: "browser-bookmark-title browser-bookmark-folder-title" });
title.setText(node.title);
this.wireRename(title, node);
this.wireRowClick(row, () => {
if (!query)
void this.store.toggleCollapsed(node.id);
});
row.addEventListener("contextmenu", (evt) => {
evt.preventDefault();
this.showFolderMenu(node, evt);
});
if (expanded) {
const childWrap = wrapper.createDiv({ cls: "browser-bookmark-group-children" });
const children = this.store.children(node.id).filter((child) => !query || this.matchesQuery(child, query));
for (const child of children)
this.renderNode(childWrap, child, depth + 1, query);
}
}
renderBookmark(parentEl, node, depth) {
const row = this.renderRowShell(parentEl, node, depth, "browser-bookmark-link-row");
this.renderFavicon(row, node);
const textCol = row.createDiv({ cls: "browser-bookmark-text-col" });
const title = textCol.createSpan({ cls: "browser-bookmark-title" });
title.setText(node.title);
this.wireRename(title, node);
if (node.description) {
textCol.createDiv({ cls: "browser-bookmark-description", text: node.description });
}
this.wireRowClick(row, () => this.openDefault(node));
row.addEventListener("contextmenu", (evt) => {
evt.preventDefault();
this.showBookmarkMenu(node, evt);
});
}
/**
* Shows, in order: a custom Lucide icon or custom image (set via the edit
* modal), then the site's real favicon, then a generic globe icon as the
* final fallback on any failure.
*/
renderFavicon(row, node) {
const box = row.createDiv({ cls: "browser-bookmark-favicon" });
if (node.iconType === "lucide" && node.iconValue) {
(0, import_obsidian6.setIcon)(box, node.iconValue);
return;
}
if (node.iconType === "image" && node.iconValue) {
const img2 = box.createEl("img", { cls: "browser-bookmark-favicon-img", attr: { src: node.iconValue } });
img2.addEventListener(
"error",
() => {
img2.remove();
(0, import_obsidian6.setIcon)(box, "globe");
},
{ once: true }
);
return;
}
const domain = this.store.settings.showFavicons ? this.extractDomain(node.url) : null;
if (!domain) {
(0, import_obsidian6.setIcon)(box, "globe");
return;
}
const img = box.createEl("img", {