driftnet 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -8
- package/README.zh-TW.md +24 -7
- package/dist/driftnet.mjs +426 -105
- package/package.json +1 -1
- package/public/index.html +329 -19
package/package.json
CHANGED
package/public/index.html
CHANGED
|
@@ -229,6 +229,30 @@
|
|
|
229
229
|
body.map-view .toast.show { transform: translate(-50%, 0); }
|
|
230
230
|
body.map-view .pickbar { bottom: auto; top: calc(env(safe-area-inset-top) + 72px); }
|
|
231
231
|
.pickbar button { white-space: nowrap; }
|
|
232
|
+
/* Several cards selected: a bar at the bottom (top on the map) with what can be done to all of them. */
|
|
233
|
+
.swipe.selected .card { outline: 2px solid var(--accent); outline-offset: -2px; background: var(--accent-soft); }
|
|
234
|
+
.swipe.selected .card::after { content: "✓"; position: absolute; left: -1px; top: -1px; width: 22px; height: 22px; border-radius: 12px 0 10px 0; background: var(--accent);
|
|
235
|
+
color: #fff; font-size: 13px; display: grid; place-items: center; }
|
|
236
|
+
.mnode.sel { outline: 3px solid var(--accent); outline-offset: 3px; }
|
|
237
|
+
.selbar { position: fixed; left: 50%; transform: translateX(-50%); bottom: max(16px, calc(env(safe-area-inset-bottom) + 8px)); z-index: 6; display: flex; flex-wrap: wrap;
|
|
238
|
+
gap: 6px; align-items: center; background: var(--accent); color: #fff; border-radius: 14px; padding: 8px 8px 8px 16px; box-shadow: 0 8px 26px rgba(0,0,0,.28);
|
|
239
|
+
width: max-content; max-width: calc(100vw - 24px); }
|
|
240
|
+
.selbar[hidden], body.readonly .selbar { display: none !important; }
|
|
241
|
+
.selbar .sel-n { font-weight: 650; margin-right: 6px; }
|
|
242
|
+
.selbar button { border: 0; background: rgba(255,255,255,.2); color: #fff; border-radius: 10px; min-height: 40px; padding: 0 12px; font-weight: 600; white-space: nowrap;
|
|
243
|
+
display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
|
244
|
+
.selbar button:hover, .selbar button:focus-visible { background: rgba(255,255,255,.34); }
|
|
245
|
+
.selbar .ico { width: 16px; height: 16px; }
|
|
246
|
+
body.selecting main { padding-bottom: 120px; }
|
|
247
|
+
body.selecting .toast { bottom: calc(max(16px, env(safe-area-inset-bottom) + 8px) + 72px); }
|
|
248
|
+
body.map-view .selbar { bottom: auto; top: calc(env(safe-area-inset-top) + 72px); }
|
|
249
|
+
body.map-view.selecting .toast { top: calc(env(safe-area-inset-top) + 136px); bottom: auto; }
|
|
250
|
+
.pick .qk, .keys kbd { font: 600 12px/1 ui-monospace, monospace; border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px; padding: 3px 6px; color: var(--muted); background: var(--bg); }
|
|
251
|
+
.pick .qk { margin-right: 6px; }
|
|
252
|
+
.keys { display: grid; grid-template-columns: auto 1fr; gap: 8px 14px; margin: 0 0 12px; font-size: 14px; align-items: center; }
|
|
253
|
+
.keys h4 { grid-column: 1 / -1; margin: 6px 0 0; font-size: 13px; color: var(--muted); font-weight: 600; }
|
|
254
|
+
.keys dt { justify-self: end; white-space: nowrap; }
|
|
255
|
+
.keys dd { margin: 0; }
|
|
232
256
|
.mnode .opt { position: relative; }
|
|
233
257
|
.mnode .opt::before { content: ""; position: absolute; inset: -9px; }
|
|
234
258
|
body.map-view main { padding-bottom: 0; }
|
|
@@ -276,12 +300,22 @@
|
|
|
276
300
|
.meter[data-s="weak"] i { width: 33%; background: var(--danger); }
|
|
277
301
|
.meter[data-s="ok"] i { width: 66%; background: var(--star); }
|
|
278
302
|
.meter[data-s="strong"] i { width: 100%; background: var(--ok); }
|
|
303
|
+
.tok { justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); }
|
|
304
|
+
.tok.revoked { opacity: .55; }
|
|
305
|
+
.tok-name { display: grid; gap: 2px; min-width: 0; justify-items: start; }
|
|
306
|
+
.tok .btn { flex: none; }
|
|
307
|
+
/* The create-token row: the name takes the room, the scope and button only what they need (the set-row rules below would stretch them). */
|
|
308
|
+
.set-row .keyrow input, #at-name { flex: 1 1 120px; width: auto; min-width: 0; }
|
|
309
|
+
.set-row .keyrow select, #at-scope { min-height: 38px; flex: 0 0 auto; width: auto; }
|
|
279
310
|
.warn { background: var(--star-soft); color: var(--text); border-radius: 8px; padding: 8px 10px; font-size: 13px; margin: 4px 0 10px; }
|
|
280
311
|
.warn.danger { background: var(--danger-soft); }
|
|
281
312
|
.conn { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; margin-bottom: 12px; }
|
|
282
313
|
.conn h4 { margin: 0 0 4px; font-size: 15px; }
|
|
283
314
|
.conn p { margin: 0 0 8px; font-size: 13px; color: var(--muted); }
|
|
284
315
|
.conn pre { margin: 0; background: var(--bg); border-radius: 8px; padding: 10px 12px; font-size: 12.5px; white-space: pre; overflow-x: auto; }
|
|
316
|
+
.conn-mint { margin-top: 8px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
|
317
|
+
.conn-mint .conn-name { flex: 1 1 140px; min-width: 0; max-width: 220px; }
|
|
318
|
+
.conn-mint .warn { margin: 0; }
|
|
285
319
|
.conn-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
|
286
320
|
.conn .copy { min-height: 36px; padding: 4px 12px; font-size: 13px; flex: none; }
|
|
287
321
|
.welcome { background: var(--accent-soft); color: var(--text); border-radius: 10px; padding: 10px 12px; font-size: 14px; margin-bottom: 14px; }
|
|
@@ -521,6 +555,12 @@
|
|
|
521
555
|
</form>
|
|
522
556
|
</dialog>
|
|
523
557
|
<div class="pickbar" id="pickbar" role="status" hidden><span id="pick-text"></span><button type="button" id="pick-cancel"></button></div>
|
|
558
|
+
<div class="selbar" id="selbar" role="toolbar" hidden></div>
|
|
559
|
+
<dialog id="keys-dlg" aria-labelledby="ky-title">
|
|
560
|
+
<h3 id="ky-title"></h3>
|
|
561
|
+
<dl class="keys" id="ky-body"></dl>
|
|
562
|
+
<div class="dlg-actions"><span class="spacer"></span><button class="btn" id="ky-close" type="button"></button></div>
|
|
563
|
+
</dialog>
|
|
524
564
|
<div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
|
|
525
565
|
<script>
|
|
526
566
|
const STRINGS = {
|
|
@@ -561,6 +601,14 @@
|
|
|
561
601
|
readOnlyNudge: "You can only look here — tap Unlock at the top to change things", filterFolders: "Type to find a folder…", undoHint: "z undoes",
|
|
562
602
|
addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
|
|
563
603
|
shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
|
|
604
|
+
keysTitle: "Keyboard shortcuts", keysMove: "Move, favorite, trash", keysSelect: "Select several cards", keysGo: "Go to", keysQuick: "File into your most-used folders",
|
|
605
|
+
kNext: "Next / previous card", kFav: "Favorite", kMove: "Move to…", kNote: "Note", kTrash: "Trash (restore in the trash)", kSearch: "Search", kMap: "Mind map", kAll: "All cards",
|
|
606
|
+
kSelect: "Select or unselect the card", kRange: "Select a range", kHold: "Hold", kLong: "Start selecting on a phone", keysClose: "Close", kClear: "Clear the selection", kUndo: "Undo the last action", kHelp: "This list",
|
|
607
|
+
kQuickNone: "Move a card into a folder first; the nine you use most get a number here.", kQuickN: (f) => `Move into ${f}`,
|
|
608
|
+
nSelected: (n) => `${n} selected`, selectAll: "Select all", clearSel: "Clear", trashShort: "Trash",
|
|
609
|
+
moveTitleMany: (n) => `Move ${n} cards to`, pickedMany: (n) => `Picked up ${n} cards — tap the folder they go into`,
|
|
610
|
+
bulkMoved: (n, f) => `Moved ${n} cards to ${f}`, bulkRemoved: (n) => `${n} cards moved to the trash`, bulkRestored: (n) => `${n} cards restored`,
|
|
611
|
+
bulkFaved: (n) => `${n} cards added to favorites`, bulkUnfaved: (n) => `${n} cards removed from favorites`,
|
|
564
612
|
st: {
|
|
565
613
|
title: "Settings", save: "Save", welcome: "Welcome! Pick a model below to get summaries — or none: links are still sorted into folders, just without a summary. Then paste a link.",
|
|
566
614
|
display: "This browser", sort: "Order", sorts: { best: "Best first", newest: "Newest first", shared: "Most shared first" },
|
|
@@ -581,6 +629,14 @@
|
|
|
581
629
|
accessMode: "Who can read", accessChoices: { "": "Anyone who can reach this page", public: "Anyone who can reach this page", private: "Only with the password or the share key" },
|
|
582
630
|
shareKey: "Read-only share key", shareKeyHelp: "For AIs that can only open links (ChatGPT, Grok, Claude.ai): they can read your catalogue (notes included), nothing more. If it leaks, make a new one.",
|
|
583
631
|
newShareKey: "New key", noShareKey: "No share key yet.",
|
|
632
|
+
agentTokens: "Agent tokens", agentTokensHelp: "One key per agent instead of the admin password. A write token can add, move and tidy; a read token can only look. Revoke one and only that agent is cut off; changing the admin password doesn't affect them.",
|
|
633
|
+
tokName: "Agent name", tokScope: "Access", tokScopes: { write: "Read and write", read: "Read only" }, tokCreate: "Create token",
|
|
634
|
+
tokNew: "New token for “{name}”", tokNewWarn: "Copy it now. It will not be shown again; only a fingerprint is kept.",
|
|
635
|
+
tokNone: "No tokens yet.", tokCreatedOn: "created", tokLastUsed: "last used", tokNever: "never", tokRevoke: "Revoke", tokRevoked: "revoked", tokRemove: "Remove",
|
|
636
|
+
tokDuplicate: "A token named “{name}” already exists. The old one keeps working; revoke it in Settings → Access if it's a replacement.",
|
|
637
|
+
tokCardName: "Token name", tokCardCreate: "Create a token for this agent",
|
|
638
|
+
tokCardDone: "Token “{name}” created and filled in above. Copy it now: it will not be shown again. Revoke it in Settings → Access when you no longer need it.",
|
|
639
|
+
tokNameNeeded: "Give the token a name.", tokPasswordOnly: "Set an admin password first: tokens are what you give agents instead of it.",
|
|
584
640
|
tunnel: "Public URL for cloud AIs", tunnelHelp: "Claude.ai, ChatGPT, Grok and agents on other machines can't reach localhost. This opens a temporary https address through Cloudflare (no account). It changes every time and closes when driftnet stops.",
|
|
585
641
|
tunnelOn: "Open a public URL", tunnelOff: "Close it", tunnelNeedsPassword: "Save an admin password first.",
|
|
586
642
|
tunnelInstall: "Needs cloudflared (driftnet never downloads it for you):", tunnelPrivate: "Opening it switches reading to “only with the password or the share key”.",
|
|
@@ -652,6 +708,14 @@
|
|
|
652
708
|
readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
|
|
653
709
|
addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
|
|
654
710
|
shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
|
|
711
|
+
keysTitle: "快捷鍵", keysMove: "移動、最愛、垃圾桶", keysSelect: "一次選多張卡片", keysGo: "切換畫面", keysQuick: "放進最常用的資料夾",
|
|
712
|
+
kNext: "下一張/上一張", kFav: "最愛", kMove: "移動到…", kNote: "筆記", kTrash: "垃圾桶(在垃圾桶裡是還原)", kSearch: "搜尋", kMap: "樹狀圖", kAll: "全部卡片",
|
|
713
|
+
kSelect: "選取/取消選取這張", kRange: "選取一段範圍", kHold: "長按", kLong: "在手機上開始選取卡片", keysClose: "關閉", kClear: "取消全部選取", kUndo: "復原上一個動作", kHelp: "顯示這份清單",
|
|
714
|
+
kQuickNone: "先把卡片移進某個資料夾;最常用的九個資料夾會在這裡得到數字鍵。", kQuickN: (f) => `移到 ${f}`,
|
|
715
|
+
nSelected: (n) => `已選 ${n} 張`, selectAll: "全選", clearSel: "清除", trashShort: "垃圾桶",
|
|
716
|
+
moveTitleMany: (n) => `把 ${n} 張卡片移動到`, pickedMany: (n) => `已拿起 ${n} 張卡片,點要放進去的資料夾`,
|
|
717
|
+
bulkMoved: (n, f) => `已將 ${n} 張卡片移到 ${f}`, bulkRemoved: (n) => `已將 ${n} 張卡片移到垃圾桶`, bulkRestored: (n) => `已還原 ${n} 張卡片`,
|
|
718
|
+
bulkFaved: (n) => `已將 ${n} 張卡片加入最愛`, bulkUnfaved: (n) => `已將 ${n} 張卡片移出最愛`,
|
|
655
719
|
st: {
|
|
656
720
|
title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型就會有摘要;不選也可以,連結一樣會分進資料夾,只是沒有摘要。接著貼一個連結試試看。",
|
|
657
721
|
display: "這個瀏覽器", sort: "排序", sorts: { best: "值得看的在前", newest: "最新的在前", shared: "最多人分享的在前" },
|
|
@@ -672,6 +736,14 @@
|
|
|
672
736
|
accessMode: "誰可以讀", accessChoices: { "": "連得到這個網頁的人都可以", public: "連得到這個網頁的人都可以", private: "要有密碼或分享碼才能讀" },
|
|
673
737
|
shareKey: "唯讀分享碼", shareKeyHelp: "給只會開連結的 AI(ChatGPT、Grok、Claude 網頁版):只能讀你的清單(包含筆記),不能改。外流的話重產一組就好。",
|
|
674
738
|
newShareKey: "重新產生", noShareKey: "還沒有分享碼。",
|
|
739
|
+
agentTokens: "Agent 專用金鑰", agentTokensHelp: "每個 agent 用自己的金鑰,不必拿管理密碼出去。可寫入的金鑰能收錄、搬移、整理;唯讀的只能看。撤銷其中一把只會斷掉那個 agent,換管理密碼也不影響它們。",
|
|
740
|
+
tokName: "Agent 名稱", tokScope: "權限", tokScopes: { write: "可讀寫", read: "唯讀" }, tokCreate: "建立金鑰",
|
|
741
|
+
tokNew: "「{name}」的新金鑰", tokNewWarn: "請現在複製。之後不會再顯示,系統只留下指紋。",
|
|
742
|
+
tokNone: "還沒有金鑰。", tokCreatedOn: "建立於", tokLastUsed: "最後使用", tokNever: "從未", tokRevoke: "撤銷", tokRevoked: "已撤銷", tokRemove: "移除",
|
|
743
|
+
tokDuplicate: "已經有一把叫「{name}」的金鑰。舊的仍然有效;如果是要換新,請到「設定 → 存取」撤銷舊的。",
|
|
744
|
+
tokCardName: "金鑰名稱", tokCardCreate: "幫這個 agent 建一把專用金鑰",
|
|
745
|
+
tokCardDone: "已建立「{name}」專用金鑰,已填進上面的設定。請現在複製:之後不會再顯示。不用時到「設定 → 存取」撤銷。",
|
|
746
|
+
tokNameNeeded: "請幫金鑰取個名字。", tokPasswordOnly: "請先設定管理密碼:金鑰就是用來取代它交給 agent 的。",
|
|
675
747
|
tunnel: "給雲端 AI 的公開網址", tunnelHelp: "Claude 網頁版、ChatGPT、Grok 和其他機器上的 agent 連不到 localhost。這會透過 Cloudflare(免帳號)開一個臨時的 https 網址;每次都不一樣,driftnet 關掉就跟著關。",
|
|
676
748
|
tunnelOn: "開啟公開網址", tunnelOff: "關閉", tunnelNeedsPassword: "要先儲存管理密碼。",
|
|
677
749
|
tunnelInstall: "需要 cloudflared(driftnet 不會自動幫你下載):", tunnelPrivate: "開啟後,「誰可以讀」會改成要有密碼或分享碼。",
|
|
@@ -1002,15 +1074,37 @@
|
|
|
1002
1074
|
}
|
|
1003
1075
|
|
|
1004
1076
|
// ── Move a card: picker (phones) or drag onto the sidebar (desktop) ───────
|
|
1005
|
-
let moving = null;
|
|
1077
|
+
let moving = null, movingMany = null;
|
|
1078
|
+
/** The nine folders cards were filed into most often (the server counts moves and undoes), in tree order on a tie: keys 1–9 file a card there. */
|
|
1079
|
+
function quickFolders() {
|
|
1080
|
+
const order = []; (function walk(p) { for (const f of kids(p)) { order.push(f.id); walk(f.id); } })(null);
|
|
1081
|
+
return order.map((id, at) => ({ id, at, n: folders.find((f) => f.id === id)?.uses ?? 0 })).filter((f) => f.n > 0)
|
|
1082
|
+
.sort((a, b) => b.n - a.n || a.at - b.at).slice(0, 9).map((f) => f.id);
|
|
1083
|
+
}
|
|
1084
|
+
/** Mirror the server's counter on the folders already loaded, so keys 1–9 stay current without a refetch. */
|
|
1085
|
+
function bumpUse(folder, by = 1) {
|
|
1086
|
+
const f = folders.find((x) => x.id === folder);
|
|
1087
|
+
if (f) f.uses = Math.max(0, (f.uses ?? 0) + by);
|
|
1088
|
+
}
|
|
1006
1089
|
function openMovePicker(id) {
|
|
1007
1090
|
const item = find(id);
|
|
1008
1091
|
if (!item) return;
|
|
1009
|
-
moving = id;
|
|
1092
|
+
moving = id; movingMany = null;
|
|
1093
|
+
$("mv-title").textContent = T().moveTitle(nameOf(item));
|
|
1094
|
+
showMovePicker(item.category);
|
|
1095
|
+
}
|
|
1096
|
+
/** Move to… for several cards at once (the selection). */
|
|
1097
|
+
function openMovePickerFor(ids) {
|
|
1098
|
+
if (ids.length === 1) return openMovePicker(ids[0]);
|
|
1099
|
+
moving = null; movingMany = ids;
|
|
1100
|
+
$("mv-title").textContent = T().moveTitleMany(ids.length);
|
|
1101
|
+
showMovePicker(null);
|
|
1102
|
+
}
|
|
1103
|
+
function showMovePicker(current) {
|
|
1010
1104
|
const t = T();
|
|
1011
|
-
|
|
1105
|
+
const quick = quickFolders();
|
|
1012
1106
|
const rows = (p, depth) => kids(p).map((f) => `<button type="button" data-to="${esc(f.id)}" style="--depth:${depth}"
|
|
1013
|
-
aria-current="${f.id ===
|
|
1107
|
+
aria-current="${f.id === current}"><span>${esc(catLabel(f.id))}</span><span>${quick.includes(f.id) ? `<kbd class="qk" title="${esc(t.kQuickN(catLabel(f.id)))}">${quick.indexOf(f.id) + 1}</kbd>` : ""}<span class="count">${subtotal(f) || ""}</span></span></button>` + rows(f.id, depth + 1)).join("");
|
|
1014
1108
|
$("mv-list").innerHTML = rows(null, 0);
|
|
1015
1109
|
$("mv-cancel").textContent = t.cancel;
|
|
1016
1110
|
$("mv-filter").value = "";
|
|
@@ -1025,7 +1119,7 @@
|
|
|
1025
1119
|
const q = $("mv-filter").value.trim().toLowerCase();
|
|
1026
1120
|
const rows = [...$("mv-list").querySelectorAll("[data-to]")];
|
|
1027
1121
|
// Match what the reader sees; the hidden id (e.g. "coding-agent") only when no visible name matches.
|
|
1028
|
-
const byName = rows.filter((b) => b.textContent.toLowerCase().includes(q));
|
|
1122
|
+
const byName = rows.filter((b) => b.firstElementChild.textContent.toLowerCase().includes(q));
|
|
1029
1123
|
const shown = new Set(q ? (byName.length ? byName : rows.filter((b) => b.dataset.to.includes(q))) : rows);
|
|
1030
1124
|
for (const b of rows) b.hidden = !shown.has(b);
|
|
1031
1125
|
});
|
|
@@ -1048,7 +1142,8 @@
|
|
|
1048
1142
|
const b = e.target.closest("[data-to]");
|
|
1049
1143
|
if (!b) return;
|
|
1050
1144
|
$("move-dlg").close();
|
|
1051
|
-
|
|
1145
|
+
if (movingMany) bulkApply("move", movingMany, b.dataset.to);
|
|
1146
|
+
else moveItem(moving, b.dataset.to);
|
|
1052
1147
|
};
|
|
1053
1148
|
|
|
1054
1149
|
async function moveItem(id, to, quiet = false) {
|
|
@@ -1076,7 +1171,8 @@
|
|
|
1076
1171
|
const onMap = mapItems.find((x) => x.id === id);
|
|
1077
1172
|
if (onMap && onMap !== item) onMap.category = to;
|
|
1078
1173
|
if (state.view === "map") drawMap();
|
|
1079
|
-
|
|
1174
|
+
bumpUse(to);
|
|
1175
|
+
if (!quiet) { toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); render(); }); }
|
|
1080
1176
|
}
|
|
1081
1177
|
const subtreeOf = (id) => { const out = new Set([id]); for (const q = [id]; q.length;) for (const k of kids(q.pop())) { out.add(k.id); q.push(k.id); } return out; };
|
|
1082
1178
|
/** Re-draw just the tree's counts after a move. */
|
|
@@ -1141,11 +1237,21 @@
|
|
|
1141
1237
|
|
|
1142
1238
|
// ── Settings ─────────────────────────────────────────────────────────────
|
|
1143
1239
|
let serverSettings = null;
|
|
1240
|
+
/** The token just created: shown once in the Access tab, then gone. */
|
|
1241
|
+
let justMinted = null;
|
|
1242
|
+
/** The token list Settings last fetched, to warn when a new token repeats an active name. */
|
|
1243
|
+
let knownTokens = [];
|
|
1244
|
+
const nameTaken = (list, name) => list.some((k) => !k.revokedAt && k.name.toLowerCase() === name.toLowerCase());
|
|
1144
1245
|
async function openSettings(welcome = false) {
|
|
1145
1246
|
const t = T(), st = t.st;
|
|
1146
1247
|
const token = store.get("driftnet-token");
|
|
1147
1248
|
const res = await fetch("/api/settings", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
|
|
1148
1249
|
serverSettings = res?.ok ? await res.json() : null;
|
|
1250
|
+
// Agent tokens: only the admin password may list them, so a failure just hides the section.
|
|
1251
|
+
const tokRes = serverSettings ? await fetch("/api/agent-tokens", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null) : null;
|
|
1252
|
+
const agentTokens = tokRes?.ok ? await tokRes.json() : null;
|
|
1253
|
+
knownTokens = agentTokens ?? [];
|
|
1254
|
+
const minted = justMinted; justMinted = null;
|
|
1149
1255
|
const opt = (v, label, cur) => `<option value="${esc(v)}" ${v === cur ? "selected" : ""}>${esc(label)}</option>`;
|
|
1150
1256
|
const local = `<fieldset class="set-group"><legend>${esc(st.display)}</legend>
|
|
1151
1257
|
<label class="set-row"><span>${esc(st.sort)}</span><select data-pref="sort">${Object.entries(st.sorts).map(([k, v]) => opt(k, v, prefs.sort)).join("")}</select></label>
|
|
@@ -1174,7 +1280,7 @@
|
|
|
1174
1280
|
const accessStatus = `<p class="set-status">${esc(st.accessStatus(yes(a.passwordSet), yes(a.readKey), a.tunnel.running ? a.tunnel.url : "—"))}</p>`;
|
|
1175
1281
|
server = {
|
|
1176
1282
|
general: group("language") + group("chat"),
|
|
1177
|
-
access: accessStatus + accessPanel(serverSettings, field),
|
|
1283
|
+
access: accessStatus + accessPanel(serverSettings, field) + (agentTokens ? tokensPanel(serverSettings.access, agentTokens, minted) : ""),
|
|
1178
1284
|
ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + group("model") + group("rules") +
|
|
1179
1285
|
`<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
|
|
1180
1286
|
};
|
|
@@ -1259,6 +1365,27 @@
|
|
|
1259
1365
|
<div class="set-row"><span>${esc(st.tunnel)}</span>${tun}<small>${esc(st.tunnelHelp)}</small>${t.error ? `<small class="dlg-error">${esc(t.error)}</small>` : ""}</div>
|
|
1260
1366
|
</fieldset>`;
|
|
1261
1367
|
}
|
|
1368
|
+
function tokensPanel(a, tokens, minted) {
|
|
1369
|
+
const st = T().st;
|
|
1370
|
+
// Local time, the way the reader's clock shows it; the server stores UTC.
|
|
1371
|
+
const when = (iso) => { const d = new Date(iso); return esc(isNaN(d) ? iso : d.toLocaleString(locale, { dateStyle: "short", timeStyle: "short" })); };
|
|
1372
|
+
const rows = tokens.length ? tokens.map((k) => `<div class="keyrow tok ${k.revokedAt ? "revoked" : ""}">
|
|
1373
|
+
<span class="tok-name"><b>${esc(k.name)}</b> <span class="badge">${esc(st.tokScopes[k.scope])}</span>
|
|
1374
|
+
<small>${esc(st.tokCreatedOn)} ${when(k.createdAt)} · ${esc(st.tokLastUsed)} ${k.lastUsedAt ? when(k.lastUsedAt) : esc(st.tokNever)}${k.revokedAt ? ` · ${esc(st.tokRevoked)}` : ""}</small></span>
|
|
1375
|
+
${k.revokedAt ? `<button class="btn" type="button" data-remove="${esc(k.id)}">${esc(st.tokRemove)}</button>` : `<button class="btn danger" type="button" data-revoke="${esc(k.id)}">${esc(st.tokRevoke)}</button>`}</div>`).join("")
|
|
1376
|
+
: `<small>${esc(st.tokNone)}</small>`;
|
|
1377
|
+
const box = minted ? `<div class="warn"><b>${esc(st.tokNew.replace("{name}", minted.name))}</b><br>${esc(st.tokNewWarn)}
|
|
1378
|
+
<div class="keyrow"><input id="ac-newtok" readonly value="${esc(minted.token)}"><button class="btn" type="button" data-copy="#ac-newtok">${esc(st.copy)}</button></div>
|
|
1379
|
+
${minted.duplicate ? `<small>${esc(st.tokDuplicate.replace("{name}", minted.name))}</small>` : ""}</div>` : "";
|
|
1380
|
+
const form = a.passwordSet
|
|
1381
|
+
? `<div class="keyrow"><input id="at-name" maxlength="60" placeholder="${esc(st.tokName)}" autocomplete="off" aria-label="${esc(st.tokName)}">
|
|
1382
|
+
<select id="at-scope" aria-label="${esc(st.tokScope)}">${["write", "read"].map((c) => `<option value="${c}">${esc(st.tokScopes[c])}</option>`).join("")}</select>
|
|
1383
|
+
<button class="btn primary" type="button" id="at-create">${esc(st.tokCreate)}</button></div>`
|
|
1384
|
+
: `<small>${esc(st.tokPasswordOnly)}</small>`;
|
|
1385
|
+
return `<fieldset class="set-group" id="agent-tokens"><legend>${esc(st.agentTokens)}</legend>
|
|
1386
|
+
<small>${esc(st.agentTokensHelp)}</small>${box}
|
|
1387
|
+
<div class="set-row">${rows}</div><div class="set-row">${form}</div></fieldset>`;
|
|
1388
|
+
}
|
|
1262
1389
|
async function adminFetch(path, method, body) {
|
|
1263
1390
|
const token = store.get("driftnet-token");
|
|
1264
1391
|
const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
|
|
@@ -1267,6 +1394,10 @@
|
|
|
1267
1394
|
if (!res?.ok) { $("st-error").textContent = friendlyError(data?.error) ?? T().failed; return null; }
|
|
1268
1395
|
return data;
|
|
1269
1396
|
}
|
|
1397
|
+
// Enter in the token name creates the token; it must not submit the whole settings form.
|
|
1398
|
+
$("st-body").addEventListener("keydown", (e) => {
|
|
1399
|
+
if (e.target.id === "at-name" && e.key === "Enter") { e.preventDefault(); $("at-create").click(); }
|
|
1400
|
+
});
|
|
1270
1401
|
$("st-body").addEventListener("input", (e) => {
|
|
1271
1402
|
if (e.target.id !== "ac-pw") return;
|
|
1272
1403
|
const pw = e.target.value, s = pw ? pwStrength(pw) : "";
|
|
@@ -1295,6 +1426,18 @@
|
|
|
1295
1426
|
// Whatever was typed (a new password, private reading) is saved first, not thrown away.
|
|
1296
1427
|
if (!(await saveSettings())) return;
|
|
1297
1428
|
if (await adminFetch("/api/read-key", "POST", {})) openSettings();
|
|
1429
|
+
} else if (b.id === "at-create") {
|
|
1430
|
+
const name = $("at-name").value.trim();
|
|
1431
|
+
if (!name) { $("st-error").textContent = st.tokNameNeeded; return; }
|
|
1432
|
+
// Whatever was typed elsewhere in Settings is saved first, not thrown away by the redraw.
|
|
1433
|
+
if (!(await saveSettings())) return;
|
|
1434
|
+
const duplicate = nameTaken(knownTokens, name);
|
|
1435
|
+
const made = await adminFetch("/api/agent-tokens", "POST", { name, scope: $("at-scope").value });
|
|
1436
|
+
if (made) { justMinted = { ...made, duplicate }; openSettings(); }
|
|
1437
|
+
} else if (b.dataset.remove) {
|
|
1438
|
+
if (await adminFetch(`/api/agent-tokens/${encodeURIComponent(b.dataset.remove)}?purge=1`, "DELETE")) openSettings();
|
|
1439
|
+
} else if (b.dataset.revoke) {
|
|
1440
|
+
if (await adminFetch(`/api/agent-tokens/${encodeURIComponent(b.dataset.revoke)}`, "DELETE")) openSettings();
|
|
1298
1441
|
} else if (b.id === "ac-tunnel") {
|
|
1299
1442
|
if (b.dataset.on === "1" && !(await saveSettings())) return;
|
|
1300
1443
|
b.disabled = true; b.textContent = b.dataset.on === "1" ? st.tunnelStarting : b.textContent;
|
|
@@ -1471,7 +1614,7 @@
|
|
|
1471
1614
|
const more = n.type === "folder" ? `<span class="opt" data-edit="${esc(n.id)}" aria-hidden="true" title="${esc(T().editFolder)}">${ic("dots")}</span>` : "";
|
|
1472
1615
|
const name = n.type === "folder" ? T().a11yFolder(n.label, n.count) : n.type === "item" ? T().a11yCard(n.label) : n.label;
|
|
1473
1616
|
const aria = ` aria-label="${esc(name)}" aria-level="${n.depth + 1}"` + (n.type === "folder" && n.hasKids ? ` aria-expanded="${!!n.open}"` : "");
|
|
1474
|
-
return `<div class="mnode ${n.type} ${level} ${n.type === "folder" && !n.hasKids ? "vacant" : ""} ${n.hit ? "hit" : ""}" role="button" tabindex="0"${aria}
|
|
1617
|
+
return `<div class="mnode ${n.type} ${level} ${n.type === "folder" && !n.hasKids ? "vacant" : ""} ${n.hit ? "hit" : ""} ${n.type === "item" && selected.has(Number(n.key.slice(2))) ? "sel" : ""}" role="button" tabindex="0"${aria}
|
|
1475
1618
|
data-key="${esc(n.key)}" style="--c:${n.color}">${tw}${star}<span class="t">${esc(n.label)}</span>${cnt}${more}</div>`;
|
|
1476
1619
|
}).join("");
|
|
1477
1620
|
const el = new Map([...canvas.querySelectorAll(".mnode")].map((d) => [d.dataset.key, d]));
|
|
@@ -1693,10 +1836,13 @@
|
|
|
1693
1836
|
if (p.touch && p.armed && !p.drag) { endPress(); if (p.movable) pickUp(p.key); return; }
|
|
1694
1837
|
const target = p.drag ? document.querySelector(".mnode.drop") : null;
|
|
1695
1838
|
endPress();
|
|
1839
|
+
if (!p.drag && e.shiftKey && role === "admin" && p.key.startsWith("i:")) return toggleSelect(Number(p.key.slice(2)));
|
|
1696
1840
|
if (!p.drag) return tapNode(p.key, !p.touch);
|
|
1697
1841
|
if (!target) return;
|
|
1698
1842
|
const to = target.dataset.key === "root" ? null : target.dataset.key.slice(2);
|
|
1699
|
-
|
|
1843
|
+
// Dragging one of several selected cards takes them all.
|
|
1844
|
+
if (p.key.startsWith("i:") && selected.has(Number(p.key.slice(2))) && selected.size > 1) { if (to) await bulkApply("move", [...selected], to); }
|
|
1845
|
+
else if (p.key.startsWith("i:")) await mapMoveItem(Number(p.key.slice(2)), to);
|
|
1700
1846
|
else await mapMoveFolder(p.key.slice(2), to);
|
|
1701
1847
|
};
|
|
1702
1848
|
$("list").addEventListener("pointerup", finish);
|
|
@@ -1717,15 +1863,23 @@
|
|
|
1717
1863
|
let picked = null;
|
|
1718
1864
|
function pickUp(key) {
|
|
1719
1865
|
picked = key;
|
|
1720
|
-
|
|
1866
|
+
if (key.startsWith("i:")) selected.add(Number(key.slice(2)));
|
|
1867
|
+
renderPickText();
|
|
1868
|
+
syncSelection();
|
|
1869
|
+
}
|
|
1870
|
+
/** While a card is picked up on a phone, tapping more cards adds them; the next folder tapped receives all. */
|
|
1871
|
+
function renderPickText() {
|
|
1872
|
+
const key = picked, t = T();
|
|
1873
|
+
const many = key.startsWith("i:") && selected.size > 1;
|
|
1721
1874
|
const label = key.startsWith("i:") ? nameOf(mapItems.find((i) => i.id === Number(key.slice(2))) ?? { title: "" }) : catLabel(key.slice(2));
|
|
1722
|
-
$("pick-text").textContent = t.pickedUp(label);
|
|
1875
|
+
$("pick-text").textContent = many ? t.pickedMany(selected.size) : t.pickedUp(label);
|
|
1723
1876
|
$("pick-cancel").textContent = t.cancel;
|
|
1724
1877
|
$("pickbar").hidden = false;
|
|
1725
1878
|
$("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(key)}"]`)?.classList.add("picked");
|
|
1726
1879
|
}
|
|
1727
1880
|
let justDropped = false;
|
|
1728
1881
|
function dropPicked() {
|
|
1882
|
+
if (picked?.startsWith("i:")) clearSelection();
|
|
1729
1883
|
picked = null;
|
|
1730
1884
|
justDropped = true;
|
|
1731
1885
|
setTimeout(() => (justDropped = false), 400); // the click that follows the tap isn't an edit
|
|
@@ -1736,9 +1890,12 @@
|
|
|
1736
1890
|
if (picked) {
|
|
1737
1891
|
const what = picked;
|
|
1738
1892
|
if (key === what) return dropPicked();
|
|
1893
|
+
if (what.startsWith("i:") && key.startsWith("i:")) { toggleSelect(Number(key.slice(2))); if (selected.size) renderPickText(); else dropPicked(); return; }
|
|
1739
1894
|
if (key.startsWith("f:") || (key === "root" && what.startsWith("f:"))) {
|
|
1895
|
+
const ids = what.startsWith("i:") && selected.size > 1 ? [...selected] : null;
|
|
1740
1896
|
dropPicked();
|
|
1741
1897
|
const to = key === "root" ? null : key.slice(2);
|
|
1898
|
+
if (ids) return to ? bulkApply("move", ids, to) : undefined;
|
|
1742
1899
|
return what.startsWith("i:") ? mapMoveItem(Number(what.slice(2)), to) : mapMoveFolder(what.slice(2), to);
|
|
1743
1900
|
}
|
|
1744
1901
|
}
|
|
@@ -1803,6 +1960,7 @@
|
|
|
1803
1960
|
// Filing many cards in a row: the target stays as it was (no sudden expansion); its count pulses instead.
|
|
1804
1961
|
drawMap();
|
|
1805
1962
|
pulse(`f:${to}`);
|
|
1963
|
+
bumpUse(to);
|
|
1806
1964
|
toast(T().moved(nameOf(item), folderPath(to)), async () => {
|
|
1807
1965
|
if (await mapWrite(`/api/items/${id}/move`, "POST", { folder: from })) { item.category = from; drawMap(); refreshFolders(); }
|
|
1808
1966
|
});
|
|
@@ -1871,14 +2029,18 @@
|
|
|
1871
2029
|
const key = a?.readKey || (zh ? "<唯讀分享碼>" : "<share-key>");
|
|
1872
2030
|
const pw = zh ? "<你的管理密碼>" : "<your-admin-password>";
|
|
1873
2031
|
const withKey = (u) => (a?.private || a?.readKey ? `${u}?key=${key}` : u);
|
|
1874
|
-
|
|
1875
|
-
|
|
2032
|
+
// With an admin password set, agent cards offer their own token instead of the password.
|
|
2033
|
+
const canMint = !!a?.passwordSet;
|
|
2034
|
+
const secrets = {};
|
|
2035
|
+
const card = (id, title, desc, code, agent) => `<div class="conn" id="cc-${id}"><div class="conn-head"><h4>${esc(title)}</h4>
|
|
2036
|
+
<button class="btn copy" type="button" data-copy="#cx-${id}">${esc(st.copy)}</button></div><p>${esc(desc)}</p><pre id="cx-${id}">${esc(code)}</pre>
|
|
2037
|
+
${agent && canMint ? `<div class="conn-mint"><input id="cn-${id}" class="conn-name" maxlength="60" value="${esc(agent)}" autocomplete="off" aria-label="${esc(st.tokCardName)}"><button class="btn" type="button" data-mint="${id}">${esc(st.tokCardCreate)}</button></div>` : ""}</div>`;
|
|
1876
2038
|
const cards = [
|
|
1877
2039
|
card("ccp", zh ? "Claude Code:裝插件" : "Claude Code: the plugin", zh ? "在 Claude Code 裡輸入。會裝好 skill 和本機 MCP。" : "Type it inside Claude Code. Brings the skill and a local MCP server.",
|
|
1878
2040
|
`/plugin install driftnet --marketplace KevinChu1110/driftnet`),
|
|
1879
2041
|
card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
|
|
1880
2042
|
zh ? "在終端機執行。先 export DRIFTNET_TOKEN=你的管理密碼,指令會自動帶入。" : "Run in a terminal. Export DRIFTNET_TOKEN=<your admin password> first; the command reads it.",
|
|
1881
|
-
`claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"
|
|
2043
|
+
`claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`, "Claude Code"),
|
|
1882
2044
|
card("claude", zh ? "Claude 網頁版/桌面版(自訂 connector)" : "Claude.ai / Claude Desktop (custom connector)",
|
|
1883
2045
|
zh ? "設定 → Connectors → 新增自訂 connector,貼上這個網址。用分享碼連線,只能搜尋和查看,不能改。" : "Settings → Connectors → Add custom connector, paste this URL. The share key makes it read-only: search and look, no changes.",
|
|
1884
2046
|
withKey(`${base}/mcp`)),
|
|
@@ -1890,8 +2052,13 @@
|
|
|
1890
2052
|
zh ? `讀一下 ${withKey(`${base}/llms.txt`)} ,這是我收藏的 AI 工具清單。幫我找適合「(你的需求)」的工具。`
|
|
1891
2053
|
: `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
|
|
1892
2054
|
card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。把裡面的 <你的管理密碼> 換成真的密碼;有了它,agent 可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. Replace <your-admin-password> with the real one; with it they can save, vote and work the queue.",
|
|
1893
|
-
JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2)),
|
|
2055
|
+
JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
|
|
1894
2056
|
].join("");
|
|
2057
|
+
// What each agent card shows once it has its own token.
|
|
2058
|
+
snippets = {
|
|
2059
|
+
cc: (tok) => `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer ${tok}"`,
|
|
2060
|
+
agents: (tok) => JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${tok}` } } } }, null, 2),
|
|
2061
|
+
};
|
|
1895
2062
|
const warn = isLocalUrl
|
|
1896
2063
|
? `<p class="warn">${esc(zh ? "這個網址只有這台電腦連得到。雲端的 AI(Claude 網頁版、ChatGPT、Grok、別台機器上的 agent)請先到「設定 → 存取」開公開網址。"
|
|
1897
2064
|
: "This address only works on this computer. For cloud AIs (Claude.ai, ChatGPT, Grok, agents on other machines), open a public URL first: Settings → Access.")}</p>` : "";
|
|
@@ -1901,9 +2068,27 @@
|
|
|
1901
2068
|
$("cx-close").textContent = t.close;
|
|
1902
2069
|
$("connect-dlg").showModal();
|
|
1903
2070
|
}
|
|
2071
|
+
let snippets = {};
|
|
1904
2072
|
$("cx-close").onclick = () => $("connect-dlg").close();
|
|
1905
2073
|
$("connect-dlg").addEventListener("click", async (e) => {
|
|
1906
2074
|
if (e.target === $("connect-dlg")) return $("connect-dlg").close();
|
|
2075
|
+
const mint = e.target.closest("button[data-mint]");
|
|
2076
|
+
if (mint) {
|
|
2077
|
+
const id = mint.dataset.mint, st = T().st;
|
|
2078
|
+
const name = $(`cn-${id}`).value.trim();
|
|
2079
|
+
if (!name) { $(`cn-${id}`).focus(); toast(st.tokNameNeeded); return; }
|
|
2080
|
+
const token = store.get("driftnet-token");
|
|
2081
|
+
const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
|
|
2082
|
+
mint.disabled = true;
|
|
2083
|
+
// Names needn't be unique, so never block: just say so when an active one already has this name.
|
|
2084
|
+
const before = await fetch("/api/agent-tokens", { headers }).then((r) => (r.ok ? r.json() : [])).catch(() => []);
|
|
2085
|
+
const res = await fetch("/api/agent-tokens", { method: "POST", headers, body: JSON.stringify({ name, scope: "write" }) }).catch(() => null);
|
|
2086
|
+
const made = res?.ok ? await res.json().catch(() => null) : null;
|
|
2087
|
+
if (!made) { mint.disabled = false; toast(T().failed); return; }
|
|
2088
|
+
$(`cx-${id}`).textContent = snippets[id](made.token);
|
|
2089
|
+
mint.closest(".conn-mint").innerHTML = `<p class="warn">${esc(st.tokCardDone.replace("{name}", made.name))}${nameTaken(before, made.name) ? `<br>${esc(st.tokDuplicate.replace("{name}", made.name))}` : ""}</p>`;
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
1907
2092
|
const b = e.target.closest("button[data-copy]");
|
|
1908
2093
|
if (!b) return;
|
|
1909
2094
|
await navigator.clipboard?.writeText($("cx-body").querySelector(b.dataset.copy).textContent).catch(() => {});
|
|
@@ -2066,6 +2251,8 @@
|
|
|
2066
2251
|
|
|
2067
2252
|
async function render() {
|
|
2068
2253
|
updateCrumb();
|
|
2254
|
+
const viewKey = [state.view, state.category, state.kind, state.q].join("|");
|
|
2255
|
+
if (viewKey !== lastViewKey) { lastViewKey = viewKey; selected.clear(); selAnchor = null; }
|
|
2069
2256
|
document.body.classList.toggle("map-view", state.view === "map");
|
|
2070
2257
|
if (state.view !== "map" && picked) dropPicked();
|
|
2071
2258
|
if (state.view === "notes") return renderNotes();
|
|
@@ -2086,6 +2273,7 @@
|
|
|
2086
2273
|
$("add-form")?.addEventListener("submit", addLink);
|
|
2087
2274
|
$("list").querySelector("[data-connect-empty]")?.addEventListener("click", () => openConnect());
|
|
2088
2275
|
for (const el of $("list").querySelectorAll(".swipe")) attachSwipe(el);
|
|
2276
|
+
syncSelection();
|
|
2089
2277
|
restoreFocus();
|
|
2090
2278
|
// Only #item-<n> is ours; anything else in the hash must not break the page.
|
|
2091
2279
|
if (/^#item-\d+$/.test(location.hash)) {
|
|
@@ -2196,7 +2384,98 @@
|
|
|
2196
2384
|
set("all", stats.items); set("favorites", stats.favorites); set("trash", stats.trash);
|
|
2197
2385
|
}
|
|
2198
2386
|
|
|
2387
|
+
// ── Select several cards: x, Shift-click or a long press; then act on all of them ──
|
|
2388
|
+
const selected = new Set();
|
|
2389
|
+
let selAnchor = null, lastViewKey = "";
|
|
2390
|
+
const visibleIds = () => [...$("list").querySelectorAll(".swipe")].map((el) => Number(el.dataset.id));
|
|
2391
|
+
const focusedId = () => Number(document.activeElement?.closest?.(".swipe")?.dataset.id) || null;
|
|
2392
|
+
function toggleSelect(id, on = !selected.has(id)) {
|
|
2393
|
+
if (role !== "admin") return;
|
|
2394
|
+
if (on) selected.add(id); else selected.delete(id);
|
|
2395
|
+
selAnchor = id;
|
|
2396
|
+
syncSelection();
|
|
2397
|
+
}
|
|
2398
|
+
function selectRange(id) {
|
|
2399
|
+
const ids = visibleIds();
|
|
2400
|
+
const a = ids.indexOf(selAnchor ?? focusedId() ?? id), b = ids.indexOf(id);
|
|
2401
|
+
if (a < 0 || b < 0) return toggleSelect(id, true);
|
|
2402
|
+
for (const x of ids.slice(Math.min(a, b), Math.max(a, b) + 1)) selected.add(x);
|
|
2403
|
+
selAnchor = id;
|
|
2404
|
+
syncSelection();
|
|
2405
|
+
}
|
|
2406
|
+
function clearSelection() { selected.clear(); selAnchor = null; syncSelection(); }
|
|
2407
|
+
/** Paint the selection on whatever is drawn (list or map) and refresh the bar. */
|
|
2408
|
+
function syncSelection() {
|
|
2409
|
+
const here = new Set(state.view === "map" ? mapItems.map((i) => i.id) : visibleIds());
|
|
2410
|
+
for (const id of [...selected]) if (!here.has(id)) selected.delete(id);
|
|
2411
|
+
for (const el of $("list").querySelectorAll(".swipe")) el.classList.toggle("selected", selected.has(Number(el.dataset.id)));
|
|
2412
|
+
for (const n of $("list").querySelectorAll(".mnode.item")) n.classList.toggle("sel", selected.has(Number(n.dataset.key.slice(2))));
|
|
2413
|
+
document.body.classList.toggle("selecting", selected.size > 0 && role === "admin");
|
|
2414
|
+
renderSelbar();
|
|
2415
|
+
}
|
|
2416
|
+
function renderSelbar() {
|
|
2417
|
+
const bar = $("selbar"), n = selected.size, t = T();
|
|
2418
|
+
bar.hidden = !n || role !== "admin" || (state.view === "map" && !!picked);
|
|
2419
|
+
if (bar.hidden) return;
|
|
2420
|
+
const keep = document.activeElement?.closest?.("#selbar")?.dataset?.sel ?? document.activeElement?.dataset?.sel;
|
|
2421
|
+
const trash = state.view === "trash", map = state.view === "map";
|
|
2422
|
+
const allFav = [...selected].every((id) => find(id)?.favorite);
|
|
2423
|
+
bar.setAttribute("aria-label", t.nSelected(n));
|
|
2424
|
+
bar.innerHTML = `<span class="sel-n" role="status">${esc(t.nSelected(n))}</span>` +
|
|
2425
|
+
(trash ? "" : `<button type="button" data-sel="move">${ic("move")} ${esc(t.moveTo)}</button>
|
|
2426
|
+
<button type="button" data-sel="fav" aria-pressed="${allFav}" title="${esc(allFav ? t.unfavorite : t.favorite)}" aria-label="${esc(allFav ? t.unfavorite : t.favorite)}">${ic("star", allFav ? "filled" : "")}</button>`) +
|
|
2427
|
+
`<button type="button" data-sel="trash">${ic(trash ? "undo" : "trash")} ${esc(trash ? t.restore : t.trashShort)}</button>` +
|
|
2428
|
+
(map ? "" : `<button type="button" data-sel="all">${esc(t.selectAll)}</button>`) +
|
|
2429
|
+
`<button type="button" data-sel="clear">${esc(t.clearSel)}</button>`;
|
|
2430
|
+
if (keep) bar.querySelector(`[data-sel="${keep}"]`)?.focus({ preventScroll: true });
|
|
2431
|
+
}
|
|
2432
|
+
$("selbar").addEventListener("click", (e) => {
|
|
2433
|
+
const b = e.target.closest("[data-sel]");
|
|
2434
|
+
if (!b) return;
|
|
2435
|
+
const ids = [...selected], a = b.dataset.sel;
|
|
2436
|
+
if (a === "move") openMovePickerFor(ids);
|
|
2437
|
+
else if (a === "fav") bulkApply(ids.every((id) => find(id)?.favorite) ? "unfavorite" : "favorite", ids);
|
|
2438
|
+
else if (a === "trash") bulkApply(state.view === "trash" ? "restore" : "trash", ids);
|
|
2439
|
+
else if (a === "all") { for (const id of visibleIds()) selected.add(id); syncSelection(); }
|
|
2440
|
+
else clearSelection();
|
|
2441
|
+
});
|
|
2442
|
+
/** One request for the whole batch; Undo hands back the id the server kept the snapshot under. */
|
|
2443
|
+
async function bulkApply(action, ids, folder) {
|
|
2444
|
+
if (!ids.length) return;
|
|
2445
|
+
const t = T(), n = ids.length;
|
|
2446
|
+
const r = await mapWrite("/api/items/bulk", "POST", { action, ids, ...(action === "move" ? { folder } : {}) });
|
|
2447
|
+
if (!r) return;
|
|
2448
|
+
clearSelection();
|
|
2449
|
+
await refreshFolders();
|
|
2450
|
+
await render();
|
|
2451
|
+
refreshCounts();
|
|
2452
|
+
if (action === "move" && state.view === "map") pulse(`f:${folder}`);
|
|
2453
|
+
const text = { move: () => t.bulkMoved(n, folderPath(folder)), trash: () => t.bulkRemoved(n), restore: () => t.bulkRestored(n),
|
|
2454
|
+
favorite: () => t.bulkFaved(n), unfavorite: () => t.bulkUnfaved(n) }[action]();
|
|
2455
|
+
toast(text, async () => {
|
|
2456
|
+
if (!(await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo }))) return;
|
|
2457
|
+
await refreshFolders();
|
|
2458
|
+
await render();
|
|
2459
|
+
refreshCounts();
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
/** Keys 1–9: file the selection, or else the focused card, into the nth most-used folder. */
|
|
2463
|
+
function quickMove(n) {
|
|
2464
|
+
const to = quickFolders()[n - 1];
|
|
2465
|
+
if (!to) return false;
|
|
2466
|
+
if (selected.size) bulkApply("move", [...selected], to);
|
|
2467
|
+
else if (focusedId() && state.view !== "map") moveItem(focusedId(), to);
|
|
2468
|
+
else return false;
|
|
2469
|
+
return true;
|
|
2470
|
+
}
|
|
2199
2471
|
$("list").addEventListener("click", (e) => {
|
|
2472
|
+
// With cards selected a click picks or drops the card; Shift-click selects a range. Links and buttons don't fire meanwhile.
|
|
2473
|
+
const sw = e.target.closest(".swipe");
|
|
2474
|
+
if (sw && role === "admin" && (e.shiftKey || selected.size) && !e.target.closest(".tool, .link-btn")) {
|
|
2475
|
+
e.preventDefault();
|
|
2476
|
+
if (e.shiftKey) selectRange(Number(sw.dataset.id)); else toggleSelect(Number(sw.dataset.id));
|
|
2477
|
+
return;
|
|
2478
|
+
}
|
|
2200
2479
|
const n = e.target.closest('.link-btn[data-act="note"]');
|
|
2201
2480
|
if (n) return openItemNote(Number(n.closest(".swipe").dataset.id));
|
|
2202
2481
|
const b = e.target.closest(".tool");
|
|
@@ -2282,8 +2561,21 @@
|
|
|
2282
2561
|
};
|
|
2283
2562
|
cardEl.addEventListener("pointerup", end);
|
|
2284
2563
|
cardEl.addEventListener("pointercancel", end);
|
|
2285
|
-
//
|
|
2286
|
-
|
|
2564
|
+
// Holding a card on a phone (~0.5 s, without moving) starts selecting.
|
|
2565
|
+
let hold = null, held = false, hx = 0, hy = 0;
|
|
2566
|
+
const cancelHold = () => { clearTimeout(hold); hold = null; };
|
|
2567
|
+
cardEl.addEventListener("pointerdown", (e) => {
|
|
2568
|
+
held = false;
|
|
2569
|
+
if (e.pointerType !== "touch" || e.button !== 0 || e.target.closest(".tool, .link-btn")) return;
|
|
2570
|
+
hx = e.clientX; hy = e.clientY;
|
|
2571
|
+
hold = setTimeout(() => { hold = null; held = true; navigator.vibrate?.(12); toggleSelect(Number(el.dataset.id), true); }, 500);
|
|
2572
|
+
});
|
|
2573
|
+
cardEl.addEventListener("pointermove", (e) => { if (hold && Math.hypot(e.clientX - hx, e.clientY - hy) > 8) cancelHold(); });
|
|
2574
|
+
cardEl.addEventListener("pointerup", cancelHold);
|
|
2575
|
+
cardEl.addEventListener("pointercancel", cancelHold);
|
|
2576
|
+
cardEl.addEventListener("contextmenu", (e) => { if (hold || held) e.preventDefault(); });
|
|
2577
|
+
// A drag that ends on a link must not open it, nor must the lift of a long press.
|
|
2578
|
+
cardEl.addEventListener("click", (e) => { if (Math.abs(dx) > 8 || held) { held = false; e.preventDefault(); e.stopPropagation(); } }, true);
|
|
2287
2579
|
}
|
|
2288
2580
|
|
|
2289
2581
|
// ── Toast with undo ──────────────────────────────────────────────────────
|
|
@@ -2305,6 +2597,21 @@
|
|
|
2305
2597
|
if (el) el.focus({ preventScroll: true });
|
|
2306
2598
|
}
|
|
2307
2599
|
for (const d of document.querySelectorAll("dialog")) d.addEventListener("close", () => setTimeout(restoreFocus, 0));
|
|
2600
|
+
/** The ? dialog: every shortcut, and which folder each number key files into. */
|
|
2601
|
+
function openKeys() {
|
|
2602
|
+
const t = T(), quick = quickFolders();
|
|
2603
|
+
const row = (keys, text) => `<dt>${keys.map((k) => `<kbd>${esc(k)}</kbd>`).join(" ")}</dt><dd>${esc(text)}</dd>`;
|
|
2604
|
+
$("ky-title").textContent = t.keysTitle;
|
|
2605
|
+
$("ky-close").textContent = t.keysClose;
|
|
2606
|
+
$("ky-body").innerHTML =
|
|
2607
|
+
`<h4>${esc(t.keysMove)}</h4>` + row(["j", "k"], t.kNext) + row(["f"], t.kFav) + row(["m"], t.kMove) + row(["n"], t.kNote) + row(["#"], t.kTrash) +
|
|
2608
|
+
`<h4>${esc(t.keysSelect)}</h4>` + row(["x"], t.kSelect) + row(["Shift", "click"], t.kRange) + row([t.kHold], t.kLong) + row(["Esc"], t.kClear) +
|
|
2609
|
+
`<h4>${esc(t.keysQuick)}</h4>` + (quick.length ? quick.map((id, i) => row([String(i + 1)], t.kQuickN(catLabel(id)))).join("") : `<dd style="grid-column:1/-1">${esc(t.kQuickNone)}</dd>`) +
|
|
2610
|
+
`<h4>${esc(t.keysGo)}</h4>` + row(["/"], t.kSearch) + row(["g", "m"], t.kMap) + row(["g", "a"], t.kAll) + row(["z"], t.kUndo) + row(["?"], t.kHelp);
|
|
2611
|
+
$("keys-dlg").showModal();
|
|
2612
|
+
}
|
|
2613
|
+
$("ky-close").onclick = () => $("keys-dlg").close();
|
|
2614
|
+
$("keys-dlg").addEventListener("click", (e) => { if (e.target === $("keys-dlg")) $("keys-dlg").close(); });
|
|
2308
2615
|
/** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
|
|
2309
2616
|
let lastUndo = null;
|
|
2310
2617
|
function toast(text, undo) {
|
|
@@ -2337,9 +2644,12 @@
|
|
|
2337
2644
|
if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? "")) return;
|
|
2338
2645
|
const k = e.key, prev = lastKey;
|
|
2339
2646
|
lastKey = k;
|
|
2647
|
+
if (k === "Escape" && selected.size) { clearSelection(); return; }
|
|
2340
2648
|
if (k === "/") { e.preventDefault(); $("q").focus(); return; }
|
|
2341
2649
|
if ((k === "z" || k === "u") && lastUndo) { e.preventDefault(); $("toast-undo").click(); return; }
|
|
2342
|
-
if (k === "?") {
|
|
2650
|
+
if (k === "?") { openKeys(); return; }
|
|
2651
|
+
if (/^[1-9]$/.test(k) && role === "admin" && !document.activeElement?.isContentEditable && quickMove(Number(k))) { e.preventDefault(); return; }
|
|
2652
|
+
if (k === "x" && role === "admin" && !document.activeElement?.isContentEditable && focusedId() && state.view !== "map") { e.preventDefault(); toggleSelect(focusedId()); return; }
|
|
2343
2653
|
if (prev === "g" && k === "m") { Object.assign(state, { view: "map", category: "" }); load(); return; }
|
|
2344
2654
|
if (prev === "g" && k === "a") { Object.assign(state, { view: "all", category: "" }); load(); return; }
|
|
2345
2655
|
const cards = [...$("list").querySelectorAll(".swipe .card")];
|