driftnet 0.4.0 → 0.5.0

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/public/index.html CHANGED
@@ -166,6 +166,11 @@
166
166
  /* The mind map: folders branch out to the right; drag cards onto folders. */
167
167
  .map-bar { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
168
168
  .map-bar .btn { min-height: 40px; padding: 6px 12px; display: inline-flex; align-items: center; gap: 6px; }
169
+ .map-crumb { display: flex; flex-wrap: wrap; align-items: center; gap: 2px 6px; margin: 8px 0 0; font-size: 14px; }
170
+ .map-crumb button { background: none; border: 0; padding: 6px 4px; min-height: 32px; color: var(--accent, inherit); font: inherit; cursor: pointer; text-decoration: underline; }
171
+ .map-crumb [aria-current] { font-weight: 600; padding: 6px 4px; }
172
+ .map-crumb .sep { color: var(--muted); }
173
+ .mnode:focus-visible { outline: 2px solid var(--accent, currentColor); outline-offset: 2px; }
169
174
  .map-tip { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
170
175
  .map-wrap { position: relative; overflow: auto; height: 70vh; min-height: 320px; border: 1px solid var(--line);
171
176
  border-radius: 16px; background: var(--panel); box-shadow: var(--shadow); touch-action: pan-x pan-y pinch-zoom; overscroll-behavior: contain;
@@ -229,9 +234,52 @@
229
234
  body.map-view .toast.show { transform: translate(-50%, 0); }
230
235
  body.map-view .pickbar { bottom: auto; top: calc(env(safe-area-inset-top) + 72px); }
231
236
  .pickbar button { white-space: nowrap; }
237
+ /* Several cards selected: a bar at the bottom (top on the map) with what can be done to all of them. */
238
+ .swipe.selected .card { outline: 2px solid var(--accent); outline-offset: -2px; background: var(--accent-soft); }
239
+ .swipe.selected .card::after { content: "✓"; position: absolute; left: -1px; top: -1px; width: 22px; height: 22px; border-radius: 12px 0 10px 0; background: var(--accent);
240
+ color: #fff; font-size: 13px; display: grid; place-items: center; }
241
+ .mnode.sel { outline: 3px solid var(--accent); outline-offset: 3px; }
242
+ .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;
243
+ 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);
244
+ width: max-content; max-width: calc(100vw - 24px); }
245
+ .selbar[hidden], body.readonly .selbar { display: none !important; }
246
+ .selbar .sel-n { font-weight: 650; margin-right: 6px; }
247
+ .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;
248
+ display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
249
+ .selbar button:hover, .selbar button:focus-visible { background: rgba(255,255,255,.34); }
250
+ .selbar .ico { width: 16px; height: 16px; }
251
+ body.selecting main { padding-bottom: 120px; }
252
+ body.selecting .toast { bottom: calc(max(16px, env(safe-area-inset-bottom) + 8px) + 72px); }
253
+ body.map-view .selbar { bottom: auto; top: calc(env(safe-area-inset-top) + 72px); }
254
+ body.map-view.selecting .toast { top: calc(env(safe-area-inset-top) + 136px); bottom: auto; }
255
+ .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); }
256
+ .pick .qk { margin-right: 6px; }
257
+ .keys { display: grid; grid-template-columns: auto 1fr; gap: 8px 14px; margin: 0 0 12px; font-size: 14px; align-items: center; }
258
+ .keys h4 { grid-column: 1 / -1; margin: 6px 0 0; font-size: 13px; color: var(--muted); font-weight: 600; }
259
+ .keys dt { justify-self: end; white-space: nowrap; }
260
+ .keys dd { margin: 0; }
232
261
  .mnode .opt { position: relative; }
233
262
  .mnode .opt::before { content: ""; position: absolute; inset: -9px; }
234
263
  body.map-view main { padding-bottom: 0; }
264
+ /* Split view (wide screens): cards on the left, the mind map on the right. */
265
+ nav .split-btn { display: none; }
266
+ @media (min-width: 1200px) { nav .split-btn { display: flex; } }
267
+ body.split-view .layout { max-width: none; }
268
+ .split { display: grid; grid-template-columns: minmax(340px, 5fr) minmax(0, 7fr); gap: 16px; align-items: start; }
269
+ .split-list { overflow: auto; padding-right: 6px; min-width: 0; }
270
+ .split-map { min-width: 0; }
271
+ /* Command palette (⌘K / Ctrl+K). */
272
+ dialog.cmd { width: min(560px, calc(100vw - 24px)); padding: 0; margin: 12vh auto auto; }
273
+ dialog.cmd input#cmd-input { border: 0; border-bottom: 1px solid var(--line); border-radius: 14px 14px 0 0; padding: 14px 16px; font-size: 16px; width: 100%; background: transparent; outline: none; }
274
+ #cmd-list { max-height: min(52vh, 420px); overflow: auto; padding: 6px; }
275
+ .cmd-h { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); padding: 8px 10px 4px; }
276
+ .cmd-o { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
277
+ .cmd-o[aria-selected="true"] { background: var(--accent-soft); }
278
+ .cmd-o .sub { color: var(--muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
279
+ .cmd-o .lab { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
280
+ .cmd-o .lab::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--c, transparent); margin-right: 8px; }
281
+ .cmd-empty { padding: 14px 12px; color: var(--muted); }
282
+ @media (max-width: 720px) { #palette-btn { display: none; } }
235
283
  .map-wrap { user-select: none; -webkit-user-select: none; }
236
284
  .mghost { position: fixed; z-index: 30; pointer-events: none; transform: translate(-50%, -130%) rotate(-2deg); opacity: .95; box-shadow: 0 10px 28px rgba(0,0,0,.25); }
237
285
  .peek h3 { margin: 0 0 8px; font-size: 18px; }
@@ -276,12 +324,25 @@
276
324
  .meter[data-s="weak"] i { width: 33%; background: var(--danger); }
277
325
  .meter[data-s="ok"] i { width: 66%; background: var(--star); }
278
326
  .meter[data-s="strong"] i { width: 100%; background: var(--ok); }
327
+ .tok { justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); }
328
+ .tok.revoked { opacity: .55; }
329
+ .pair-out { display: grid; gap: 8px; justify-items: start; }
330
+ .pair-qr svg { display: block; max-width: 100%; height: auto; border-radius: 8px; }
331
+ .pair-time { margin: 0; font-variant-numeric: tabular-nums; }
332
+ .tok-name { display: grid; gap: 2px; min-width: 0; justify-items: start; }
333
+ .tok .btn { flex: none; }
334
+ /* 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). */
335
+ .set-row .keyrow input, #at-name, #pr-name, #pair-link { flex: 1 1 120px; width: auto; min-width: 0; }
336
+ .set-row .keyrow select, #at-scope, #pr-scope { min-height: 38px; flex: 0 0 auto; width: auto; }
279
337
  .warn { background: var(--star-soft); color: var(--text); border-radius: 8px; padding: 8px 10px; font-size: 13px; margin: 4px 0 10px; }
280
338
  .warn.danger { background: var(--danger-soft); }
281
339
  .conn { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; margin-bottom: 12px; }
282
340
  .conn h4 { margin: 0 0 4px; font-size: 15px; }
283
341
  .conn p { margin: 0 0 8px; font-size: 13px; color: var(--muted); }
284
342
  .conn pre { margin: 0; background: var(--bg); border-radius: 8px; padding: 10px 12px; font-size: 12.5px; white-space: pre; overflow-x: auto; }
343
+ .conn-mint { margin-top: 8px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
344
+ .conn-mint .conn-name { flex: 1 1 140px; min-width: 0; max-width: 220px; }
345
+ .conn-mint .warn { margin: 0; }
285
346
  .conn-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
286
347
  .conn .copy { min-height: 36px; padding: 4px 12px; font-size: 13px; flex: none; }
287
348
  .welcome { background: var(--accent-soft); color: var(--text); border-radius: 10px; padding: 10px 12px; font-size: 14px; margin-bottom: 14px; }
@@ -323,6 +384,21 @@
323
384
  a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; }
324
385
  a.name:hover { color: var(--accent); }
325
386
  .badge { font-size: 12px; padding: 1px 9px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
387
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 2px; }
388
+ .chip { font: inherit; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border-radius: 999px; cursor: pointer;
389
+ border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--line)); background: var(--accent-soft); color: var(--text); }
390
+ .chip:hover, .chip:focus-visible { border-color: var(--accent); }
391
+ .chip.more { background: transparent; border-style: dashed; color: var(--muted); border-color: var(--line); }
392
+ .chip kbd { font: 600 11px/1 ui-monospace, monospace; border: 1px solid var(--line); border-radius: 4px; padding: 2px 5px; color: var(--muted); background: var(--panel); }
393
+ body.readonly .chips { display: none; }
394
+ .plan-op { display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; padding: 10px 0; border-top: 1px solid var(--line); }
395
+ .plan-op:first-child { border-top: 0; }
396
+ .plan-op input { margin-top: 3px; }
397
+ .plan-op .why { grid-column: 2; color: var(--muted); font-size: 13px; }
398
+ .plan-op details { grid-column: 2; font-size: 13px; color: var(--muted); }
399
+ .plan-op details ul { margin: 4px 0 0; padding-left: 18px; }
400
+ .plan-op.off { opacity: .5; }
401
+ #plan-body { max-height: 55vh; overflow: auto; }
326
402
  .badge.folder { background: color-mix(in srgb, var(--c) 14%, var(--panel)); color: var(--c); font-weight: 600; }
327
403
  .rating { font-size: 12px; color: var(--muted); white-space: nowrap; }
328
404
  .rating.must { color: var(--star); font-weight: 600; }
@@ -428,6 +504,9 @@
428
504
  <symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></symbol>
429
505
  <symbol id="i-link" viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-9 9M18 14v4.5a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 4 18.5v-11A1.5 1.5 0 0 1 5.5 6H10"/></symbol>
430
506
  <symbol id="i-list" viewBox="0 0 24 24"><path d="M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01"/></symbol>
507
+ <symbol id="i-split" viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="15" rx="2"/><path d="M12 4.5v15"/></symbol>
508
+ <symbol id="i-inbox" viewBox="0 0 24 24"><path d="M3.5 13.5 6 5.5h12l2.5 8M3.5 13.5V18a1.5 1.5 0 0 0 1.5 1.5h14a1.5 1.5 0 0 0 1.5-1.5v-4.5M3.5 13.5H8a4 4 0 0 0 8 0h4.5"/></symbol>
509
+ <symbol id="i-sparkle" viewBox="0 0 24 24"><path d="M10 4l1.8 5.2L17 11l-5.2 1.8L10 18l-1.8-5.2L3 11l5.2-1.8zM18 3v4M16 5h4M18 16v4M16 18h4"/></symbol>
431
510
  <symbol id="i-eye" viewBox="0 0 24 24"><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="3"/></symbol>
432
511
  </defs>
433
512
  </svg>
@@ -440,6 +519,7 @@
440
519
  <span class="stats" id="stats"></span>
441
520
  <input id="q" class="search" type="search" enterkeyhint="search">
442
521
  <button id="lock" class="lock" type="button" hidden></button>
522
+ <button id="palette-btn" class="lang" type="button" aria-haspopup="dialog"></button>
443
523
  <button id="lang" class="lang" type="button"></button>
444
524
  </header>
445
525
  <button id="crumb" class="crumb" type="button" aria-controls="nav"></button>
@@ -457,6 +537,7 @@
457
537
  <label><span id="fd-parent-l"></span><select id="fd-parent"></select></label>
458
538
  <div class="dlg-actions">
459
539
  <button class="btn danger" id="fd-delete" type="button"></button><span class="spacer"></span>
540
+ <button class="btn" id="fd-focus" type="button" hidden></button>
460
541
  <button class="btn" id="fd-cancel" type="button"></button><button class="btn primary" id="fd-save" type="submit"></button>
461
542
  </div>
462
543
  </form>
@@ -521,6 +602,22 @@
521
602
  </form>
522
603
  </dialog>
523
604
  <div class="pickbar" id="pickbar" role="status" hidden><span id="pick-text"></span><button type="button" id="pick-cancel"></button></div>
605
+ <div class="selbar" id="selbar" role="toolbar" hidden></div>
606
+ <dialog id="cmd-dlg" class="cmd">
607
+ <input id="cmd-input" type="text" role="combobox" aria-expanded="true" aria-controls="cmd-list" aria-autocomplete="list" autocomplete="off" spellcheck="false">
608
+ <div id="cmd-list" role="listbox"></div>
609
+ </dialog>
610
+ <dialog id="keys-dlg" aria-labelledby="ky-title">
611
+ <h3 id="ky-title"></h3>
612
+ <dl class="keys" id="ky-body"></dl>
613
+ <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="ky-close" type="button"></button></div>
614
+ </dialog>
615
+ <dialog id="plan-dlg" class="wide" aria-labelledby="pl-title">
616
+ <h3 id="pl-title"></h3>
617
+ <p class="hint" id="pl-intro"></p>
618
+ <div id="plan-body"></div>
619
+ <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="pl-cancel" type="button"></button><button class="btn primary" id="pl-apply" type="button" disabled></button></div>
620
+ </dialog>
524
621
  <div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
525
622
  <script>
526
623
  const STRINGS = {
@@ -547,6 +644,10 @@
547
644
  moveTo: "Move to…", moveTitle: (n) => `Move “${n}” to`, moved: (n, f) => `Moved “${n}” to ${f}`, expand: "Show sub-folders",
548
645
  dragHint: "Drag onto a folder in the sidebar", foundIn: "Found in this post:", folderMoved: (n, f) => `“${n}” is now inside ${f}`,
549
646
  topLevelShort: "the top level",
647
+ mapAll: "All", focusCrumb: "Mind map location", focusUp: "Up one level", focusFolder: "Focus on this folder", mapTree: "Mind map",
648
+ mapHintFocus: "Double-click a folder (or press z on it) to focus on it.",
649
+ kTreeNav: "Mind map: next / previous node", kTreeOpen: "Open a folder, or step into it", kTreeClose: "Close a folder, or step out to its parent", kTreeEnds: "First / last node", kTreeType: "Type a name", kTreeTypeText: "Jump to the node starting with it",
650
+ kFocus: "Focus on the folder (mind map)", kFocusUp: "Back up one level (mind map)", keysMap: "Mind map",
550
651
  map: "Mind map", mapHint: "Tap a folder to open it, tap a card to preview it. To file a card: drag it onto a folder — on a phone, hold it a moment, let go, then tap the folder. ⋯ renames a folder.",
551
652
  a11yFolder: (n, c) => `Folder ${n}, ${c} cards`, a11yCard: (n) => `Card ${n}`,
552
653
  expandAll: "Expand all", collapseAll: "Collapse all", zoomIn: "Zoom in", zoomOut: "Zoom out", fit: "Fit", openCard: "Open card",
@@ -561,6 +662,24 @@
561
662
  readOnlyNudge: "You can only look here — tap Unlock at the top to change things", filterFolders: "Type to find a folder…", undoHint: "z undoes",
562
663
  addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
563
664
  shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
665
+ keysTitle: "Keyboard shortcuts", keysMove: "Move, favorite, trash", keysSelect: "Select several cards", keysGo: "Go to", keysQuick: "File into your most-used folders",
666
+ 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",
667
+ palette: "Command palette", palPlaceholder: "Jump to a folder, find a card, or run a command…", palGroups: { folders: "Folders", cards: "Cards", commands: "Commands" }, palNone: "Nothing matches", kPalette: "Command palette",
668
+ split: "Split", splitHelp: "Cards and mind map side by side", splitCards: "Cards",
669
+ 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",
670
+ kQuickNone: "Move a card into a folder first; the nine you use most get a number here.", kQuickN: (f) => `Move into ${f}`,
671
+ inbox: "Inbox", emptyInbox: "Inbox zero — every card has a folder you chose.", hintInbox: "Tap a folder to file the card. Not filed yet: the cards below.",
672
+ chipOther: "Other folder…", chipTitle: (p) => `Confidence ${p}%`,
673
+ keysInbox: "In the Inbox", kChip: "File into the card's suggested folder 1–3", kSkip: "Skip: focus the next card", kQuickInbox: "In the Inbox, 1–3 pick the focused card's suggested folders instead; 4–9 still file into your most-used folders.",
674
+ planBtn: "Suggest folders", planNoModel: "Needs an AI model (Settings → AI)", planTitle: "Suggested folder changes",
675
+ planIntro: "The AI only proposes. Tick what you want, then apply; nothing changes until then, and Undo reverts the whole plan. Cards you filed by hand are never moved.",
676
+ planThinking: "Asking the model…", planNone: "The model found nothing worth changing.", planApply: (n) => `Apply ${n} selected`,
677
+ planCreate: (p) => `Create “${p}”`, planRename: (a, b) => `Rename “${a}” to “${b}”`, planMove: (n, d) => `Move ${n} ${n === 1 ? "card" : "cards"} to “${d}”`,
678
+ planMerge: (a, b) => `Merge “${a}” into “${b}”`, planApplied: (n) => `Applied ${n} ${n === 1 ? "change" : "changes"} to your folders`, planNeeds: "Needs the folder it creates",
679
+ nSelected: (n) => `${n} selected`, selectAll: "Select all", clearSel: "Clear", trashShort: "Trash",
680
+ moveTitleMany: (n) => `Move ${n} cards to`, pickedMany: (n) => `Picked up ${n} cards — tap the folder they go into`,
681
+ bulkMoved: (n, f) => `Moved ${n} cards to ${f}`, bulkRemoved: (n) => `${n} cards moved to the trash`, bulkRestored: (n) => `${n} cards restored`,
682
+ bulkFaved: (n) => `${n} cards added to favorites`, bulkUnfaved: (n) => `${n} cards removed from favorites`,
564
683
  st: {
565
684
  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
685
  display: "This browser", sort: "Order", sorts: { best: "Best first", newest: "Newest first", shared: "Most shared first" },
@@ -581,6 +700,19 @@
581
700
  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
701
  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
702
  newShareKey: "New key", noShareKey: "No share key yet.",
703
+ 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.",
704
+ tokName: "Agent name", tokScope: "Access", tokScopes: { write: "Read and write", read: "Read only" }, tokCreate: "Create token",
705
+ tokNew: "New token for “{name}”", tokNewWarn: "Copy it now. It will not be shown again; only a fingerprint is kept.",
706
+ tokNone: "No tokens yet.", tokCreatedOn: "created", tokLastUsed: "last used", tokNever: "never", tokRevoke: "Revoke", tokRevoked: "revoked", tokRemove: "Remove",
707
+ tokDuplicate: "A token named “{name}” already exists. The old one keeps working; revoke it in Settings → Access if it's a replacement.",
708
+ tokCardName: "Token name", tokCardCreate: "Create a token for this agent",
709
+ 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.",
710
+ tokNameNeeded: "Give the token a name.", tokPasswordOnly: "Set an admin password first: tokens are what you give agents instead of it.",
711
+ pairTitle: "Unlock a phone", pairHelp: "Scan this code with the phone's camera: it opens driftnet already unlocked, with its own revocable token. The code works once, for 5 minutes.",
712
+ pairName: "Device name", pairCreate: "Show QR code", pairExpires: "Expires in {t}", pairExpired: "This code has expired. Make a new one.",
713
+ pairLink: "Or open this link on the phone", pairDone: "“{name}” is paired.", pairNameNeeded: "Name the device first.",
714
+ pairLocal: "This address only works on this computer. A phone needs a public URL (below) or this computer's network address.",
715
+ pairOk: "This device is unlocked.", pairFailed: "That pairing code didn't work. It may have expired or been used: make a new one on your computer.",
584
716
  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
717
  tunnelOn: "Open a public URL", tunnelOff: "Close it", tunnelNeedsPassword: "Save an admin password first.",
586
718
  tunnelInstall: "Needs cloudflared (driftnet never downloads it for you):", tunnelPrivate: "Opening it switches reading to “only with the password or the share key”.",
@@ -638,6 +770,10 @@
638
770
  moveTo: "移動到…", moveTitle: (n) => `把「${n}」移動到`, moved: (n, f) => `已將「${n}」移到 ${f}`, expand: "展開子資料夾",
639
771
  dragHint: "拖到側邊欄的資料夾", foundIn: "從這篇找到:", folderMoved: (n, f) => `「${n}」已移到 ${f} 底下`,
640
772
  topLevelShort: "最上層",
773
+ mapAll: "全部", focusCrumb: "樹狀圖位置", focusUp: "回上一層", focusFolder: "聚焦這個資料夾", mapTree: "樹狀圖",
774
+ mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。",
775
+ kTreeNav: "樹狀圖:下一個/上一個節點", kTreeOpen: "展開資料夾,或進入第一個子項", kTreeClose: "收合資料夾,或回到上一層", kTreeEnds: "第一個/最後一個節點", kTreeType: "直接輸入名稱", kTreeTypeText: "跳到名稱開頭相符的節點",
776
+ kFocus: "聚焦這個資料夾(樹狀圖)", kFocusUp: "回上一層(樹狀圖)", keysMap: "樹狀圖",
641
777
  map: "樹狀圖", mapHint: "點資料夾展開,點卡片預覽。整理卡片:把它拖到資料夾上;手機上按住卡片一下、放開,再點要放進去的資料夾。按 ⋯ 可以改資料夾名稱。",
642
778
  a11yFolder: (n, c) => `資料夾 ${n},${c} 張卡片`, a11yCard: (n) => `卡片 ${n}`,
643
779
  expandAll: "全部展開", collapseAll: "全部收合", zoomIn: "放大", zoomOut: "縮小", fit: "符合畫面", openCard: "開啟卡片",
@@ -652,6 +788,24 @@
652
788
  readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
653
789
  addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
654
790
  shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
791
+ keysTitle: "快捷鍵", keysMove: "移動、最愛、垃圾桶", keysSelect: "一次選多張卡片", keysGo: "切換畫面", keysQuick: "放進最常用的資料夾",
792
+ kNext: "下一張/上一張", kFav: "最愛", kMove: "移動到…", kNote: "筆記", kTrash: "垃圾桶(在垃圾桶裡是還原)", kSearch: "搜尋", kMap: "樹狀圖", kAll: "全部卡片",
793
+ palette: "命令面板", palPlaceholder: "跳到資料夾、找卡片,或執行指令…", palGroups: { folders: "資料夾", cards: "卡片", commands: "指令" }, palNone: "沒有符合的項目", kPalette: "命令面板",
794
+ split: "並排", splitHelp: "卡片列表與樹狀圖並排顯示", splitCards: "卡片",
795
+ kSelect: "選取/取消選取這張", kRange: "選取一段範圍", kHold: "長按", kLong: "在手機上開始選取卡片", keysClose: "關閉", kClear: "取消全部選取", kUndo: "復原上一個動作", kHelp: "顯示這份清單",
796
+ kQuickNone: "先把卡片移進某個資料夾;最常用的九個資料夾會在這裡得到數字鍵。", kQuickN: (f) => `移到 ${f}`,
797
+ inbox: "收件匣", emptyInbox: "收件匣清空了——每張卡片都有你選的資料夾。", hintInbox: "點一下資料夾就能歸檔。下面是還沒歸檔的卡片。",
798
+ chipOther: "其他資料夾…", chipTitle: (p) => `信心 ${p}%`,
799
+ keysInbox: "在收件匣", kChip: "歸到這張卡片建議的第 1–3 個資料夾", kSkip: "略過:移到下一張卡片", kQuickInbox: "在收件匣裡,1–3 改成選擇目前卡片的建議資料夾;4–9 仍然是放進最常用的資料夾。",
800
+ planBtn: "建議整理資料夾", planNoModel: "需要先設定 AI 模型(設定 → AI)", planTitle: "建議的資料夾調整",
801
+ planIntro: "AI 只負責提議。勾選想要的項目再套用,套用前什麼都不會改;復原可以一次還原整份方案。你親手歸檔的卡片不會被移動。",
802
+ planThinking: "正在請模型想想…", planNone: "模型認為目前沒有值得調整的地方。", planApply: (n) => `套用選取的 ${n} 項`,
803
+ planCreate: (p) => `新增「${p}」`, planRename: (a, b) => `把「${a}」改名為「${b}」`, planMove: (n, d) => `把 ${n} 張卡片移到「${d}」`,
804
+ planMerge: (a, b) => `把「${a}」合併到「${b}」`, planApplied: (n) => `已套用 ${n} 項資料夾調整`, planNeeds: "需要它新增的資料夾",
805
+ nSelected: (n) => `已選 ${n} 張`, selectAll: "全選", clearSel: "清除", trashShort: "垃圾桶",
806
+ moveTitleMany: (n) => `把 ${n} 張卡片移動到`, pickedMany: (n) => `已拿起 ${n} 張卡片,點要放進去的資料夾`,
807
+ bulkMoved: (n, f) => `已將 ${n} 張卡片移到 ${f}`, bulkRemoved: (n) => `已將 ${n} 張卡片移到垃圾桶`, bulkRestored: (n) => `已還原 ${n} 張卡片`,
808
+ bulkFaved: (n) => `已將 ${n} 張卡片加入最愛`, bulkUnfaved: (n) => `已將 ${n} 張卡片移出最愛`,
655
809
  st: {
656
810
  title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型就會有摘要;不選也可以,連結一樣會分進資料夾,只是沒有摘要。接著貼一個連結試試看。",
657
811
  display: "這個瀏覽器", sort: "排序", sorts: { best: "值得看的在前", newest: "最新的在前", shared: "最多人分享的在前" },
@@ -672,6 +826,19 @@
672
826
  accessMode: "誰可以讀", accessChoices: { "": "連得到這個網頁的人都可以", public: "連得到這個網頁的人都可以", private: "要有密碼或分享碼才能讀" },
673
827
  shareKey: "唯讀分享碼", shareKeyHelp: "給只會開連結的 AI(ChatGPT、Grok、Claude 網頁版):只能讀你的清單(包含筆記),不能改。外流的話重產一組就好。",
674
828
  newShareKey: "重新產生", noShareKey: "還沒有分享碼。",
829
+ agentTokens: "Agent 專用金鑰", agentTokensHelp: "每個 agent 用自己的金鑰,不必拿管理密碼出去。可寫入的金鑰能收錄、搬移、整理;唯讀的只能看。撤銷其中一把只會斷掉那個 agent,換管理密碼也不影響它們。",
830
+ tokName: "Agent 名稱", tokScope: "權限", tokScopes: { write: "可讀寫", read: "唯讀" }, tokCreate: "建立金鑰",
831
+ tokNew: "「{name}」的新金鑰", tokNewWarn: "請現在複製。之後不會再顯示,系統只留下指紋。",
832
+ tokNone: "還沒有金鑰。", tokCreatedOn: "建立於", tokLastUsed: "最後使用", tokNever: "從未", tokRevoke: "撤銷", tokRevoked: "已撤銷", tokRemove: "移除",
833
+ tokDuplicate: "已經有一把叫「{name}」的金鑰。舊的仍然有效;如果是要換新,請到「設定 → 存取」撤銷舊的。",
834
+ tokCardName: "金鑰名稱", tokCardCreate: "幫這個 agent 建一把專用金鑰",
835
+ tokCardDone: "已建立「{name}」專用金鑰,已填進上面的設定。請現在複製:之後不會再顯示。不用時到「設定 → 存取」撤銷。",
836
+ tokNameNeeded: "請幫金鑰取個名字。", tokPasswordOnly: "請先設定管理密碼:金鑰就是用來取代它交給 agent 的。",
837
+ pairTitle: "用 QR code 解鎖手機", pairHelp: "用手機相機掃描這個圖形碼:會直接開啟已解鎖的 driftnet,並取得專屬、可隨時撤銷的金鑰。圖形碼只能用一次,5 分鐘內有效。",
838
+ pairName: "裝置名稱", pairCreate: "顯示 QR code", pairExpires: "剩餘 {t}", pairExpired: "這個圖形碼已過期,請重新產生。",
839
+ pairLink: "或在手機上開啟這個連結", pairDone: "「{name}」已配對完成。", pairNameNeeded: "請先為裝置命名。",
840
+ pairLocal: "這個位址只有這台電腦連得到。手機需要公開網址(見下方)或這台電腦的區域網路位址。",
841
+ pairOk: "這台裝置已解鎖。", pairFailed: "配對碼無法使用,可能已過期或已被使用,請在電腦上重新產生。",
675
842
  tunnel: "給雲端 AI 的公開網址", tunnelHelp: "Claude 網頁版、ChatGPT、Grok 和其他機器上的 agent 連不到 localhost。這會透過 Cloudflare(免帳號)開一個臨時的 https 網址;每次都不一樣,driftnet 關掉就跟著關。",
676
843
  tunnelOn: "開啟公開網址", tunnelOff: "關閉", tunnelNeedsPassword: "要先儲存管理密碼。",
677
844
  tunnelInstall: "需要 cloudflared(driftnet 不會自動幫你下載):", tunnelPrivate: "開啟後,「誰可以讀」會改成要有密碼或分享碼。",
@@ -709,11 +876,23 @@
709
876
  },
710
877
  };
711
878
  const state = { view: "all", category: "", kind: "", q: "" };
712
- const $ = (id) => document.getElementById(id);
879
+ /** While a pane renders (split view), $("list") means that pane, so the list and map renderers can share the page unchanged. */
880
+ let paneFor = null, paneLock = Promise.resolve();
881
+ const $ = (id) => (paneFor && id === "list" ? paneFor : document.getElementById(id));
882
+ function inPane(pane, fn) {
883
+ const go = async () => { paneFor = pane; try { return await fn(); } finally { paneFor = null; } };
884
+ return (paneLock = paneLock.catch(() => {}).then(go));
885
+ }
713
886
  const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
714
887
  const safeUrl = (u) => (/^https?:\/\//.test(u) ? u : "#");
715
888
  const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
716
889
  set: (k, v) => { try { localStorage.setItem(k, v); } catch {} } };
890
+ const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
891
+ /** Split view: the saved choice; it only shows on wide screens, and only beside the card views. */
892
+ let split = store.get("driftnet-split") === "1";
893
+ const wideQuery = matchMedia("(min-width: 1200px)");
894
+ const splitOn = () => split && wideQuery.matches && (state.view === "all" || state.view === "favorites");
895
+ const mapShown = () => state.view === "map" || splitOn();
717
896
 
718
897
  let locale = "en";
719
898
  let catLabels = {};
@@ -803,6 +982,8 @@
803
982
  $("q").placeholder = T().search;
804
983
  $("q").setAttribute("aria-label", T().search);
805
984
  $("lang").textContent = T().switchTo;
985
+ $("palette-btn").textContent = isMac ? "⌘K" : "Ctrl K";
986
+ $("palette-btn").title = $("palette-btn").ariaLabel = T().palette;
806
987
  $("nav").setAttribute("aria-label", T().nav);
807
988
  $("menu").setAttribute("aria-label", T().menu);
808
989
  }
@@ -830,7 +1011,7 @@
830
1011
  /** One line under the header saying what is shown, so a closed drawer hides nothing. */
831
1012
  function updateCrumb() {
832
1013
  const t = T();
833
- const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash
1014
+ const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash : state.view === "inbox" ? t.inbox
834
1015
  : state.view === "notes" ? t.notes : state.view === "map" ? t.map : t.all];
835
1016
  if (state.category) parts.push(catLabel(state.category));
836
1017
  if (state.kind) parts.push(t.kinds[state.kind] ?? state.kind);
@@ -868,11 +1049,14 @@
868
1049
  `<div class="drawer-head"><span class="brand"><img src="/favicon.svg" alt="" width="24" height="24">driftnet</span>` +
869
1050
  `<button type="button" class="menu" id="menu-close" aria-label="${esc(T().close)}">✕</button></div>` +
870
1051
  `<div class="row">` +
1052
+ (role === "admin" || stats.inbox ? btn("view", "inbox", T().inbox, stats.inbox || "", "inbox") : "") +
871
1053
  btn("view", "all", T().all, stats.items, "all") + btn("view", "favorites", T().favorites, stats.favorites, "star") +
872
1054
  btn("view", "map", T().map, "", "map") +
1055
+ `<button type="button" class="split-btn" data-split aria-pressed="${split}" title="${esc(T().splitHelp)}"><span class="lbl">${ic("split")}<span>${esc(T().split)}</span></span><span class="count"></span></button>` +
873
1056
  btn("view", "notes", T().notes, stats.notes || "", "note") +
874
1057
  btn("view", "trash", T().trash, stats.trash || "", "trash") +
875
1058
  `</div><div class="folders-head" data-drop-root><h2>${esc(T().folders)}</h2>` +
1059
+ (role === "admin" ? `<button type="button" class="icon" data-suggest title="${esc(summaries ? T().planBtn : T().planNoModel)}" aria-label="${esc(T().planBtn)}" ${summaries ? "" : "aria-disabled=\"true\""} ${summaries ? "" : 'style="opacity:.45"'}>${ic("sparkle")}</button>` : "") +
876
1060
  `<button type="button" class="icon" data-new="" title="${esc(T().newFolder)}" aria-label="${esc(T().newFolder)}">${ic("plus")}</button></div>` +
877
1061
  `<div class="tree" role="list">${folderRows(null, 0)}</div><h2>${esc(T().kind)}</h2><div class="row kinds">` + btn("kind", "", T().any, "") +
878
1062
  Object.entries(T().kinds).map(([k, v]) => btn("kind", k, v, "")).join("") + `</div>` +
@@ -900,7 +1084,15 @@
900
1084
  if (b.dataset.login !== undefined) { if (isDrawer()) setMenu(false); return openLogin(); }
901
1085
  if (b.dataset.logout !== undefined) { store.set("driftnet-token", ""); return load(); }
902
1086
  if (b.dataset.new !== undefined) return openFolderDialog(null, b.dataset.new || null);
1087
+ if (b.dataset.split !== undefined) {
1088
+ split = !split;
1089
+ store.set("driftnet-split", split ? "1" : "0");
1090
+ if (state.view !== "all" && state.view !== "favorites") state.view = "all";
1091
+ return load();
1092
+ }
1093
+ if (b.dataset.suggest !== undefined) { if (isDrawer()) setMenu(false); return openPlan(); }
903
1094
  const { field, value } = b.dataset;
1095
+ if (field === "view" && value === "map" && split) { split = false; store.set("driftnet-split", "0"); }
904
1096
  // Choosing a category stays inside the current view; choosing a view clears the category.
905
1097
  if (field === "view") state.category = "";
906
1098
  // The map has its own folders: picking one in the sidebar shows its cards.
@@ -956,12 +1148,16 @@
956
1148
  del.hidden = !id || id === "other";
957
1149
  del.textContent = t.del;
958
1150
  del.classList.remove("armed");
1151
+ const fb = $("fd-focus");
1152
+ fb.hidden = !id || state.view !== "map" || id === mapFocus;
1153
+ fb.textContent = t.focusFolder;
959
1154
  $("fd-cancel").textContent = t.cancel;
960
1155
  $("fd-save").textContent = t.save;
961
1156
  $("fd-error").textContent = "";
962
1157
  $("folder-dlg").showModal();
963
1158
  $("fd-name").focus();
964
1159
  }
1160
+ $("fd-focus").onclick = () => { $("folder-dlg").close(); setMapFocus(editing); };
965
1161
  $("fd-cancel").onclick = () => $("folder-dlg").close();
966
1162
  // Delete asks twice inside the dialog (no browser confirm box).
967
1163
  $("fd-delete").onclick = async () => {
@@ -1002,18 +1198,74 @@
1002
1198
  }
1003
1199
 
1004
1200
  // ── Move a card: picker (phones) or drag onto the sidebar (desktop) ───────
1005
- let moving = null;
1201
+ let moving = null, movingMany = null;
1202
+ /** 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. */
1203
+ function quickFolders() {
1204
+ const order = []; (function walk(p) { for (const f of kids(p)) { order.push(f.id); walk(f.id); } })(null);
1205
+ return order.map((id, at) => ({ id, at, n: folders.find((f) => f.id === id)?.uses ?? 0 })).filter((f) => f.n > 0)
1206
+ .sort((a, b) => b.n - a.n || a.at - b.at).slice(0, 9).map((f) => f.id);
1207
+ }
1208
+ /** Mirror the server's counter on the folders already loaded, so keys 1–9 stay current without a refetch. */
1209
+ function bumpUse(folder, by = 1) {
1210
+ const f = folders.find((x) => x.id === folder);
1211
+ if (f) f.uses = Math.max(0, (f.uses ?? 0) + by);
1212
+ }
1006
1213
  function openMovePicker(id) {
1007
1214
  const item = find(id);
1008
1215
  if (!item) return;
1009
- moving = id;
1216
+ moving = id; movingMany = null;
1217
+ $("mv-title").textContent = T().moveTitle(nameOf(item));
1218
+ showMovePicker(item.category);
1219
+ }
1220
+ /** Move to… for several cards at once (the selection). */
1221
+ function openMovePickerFor(ids) {
1222
+ if (ids.length === 1) return openMovePicker(ids[0]);
1223
+ moving = null; movingMany = ids;
1224
+ $("mv-title").textContent = T().moveTitleMany(ids.length);
1225
+ showMovePicker(null);
1226
+ }
1227
+ // <fuzzy>
1228
+ /**
1229
+ * Rank entries against a query (empty query = all, in order). Tiers: exact, prefix, word start, substring, letters in order
1230
+ * (3+ characters, first field only); text in later fields counts a bit less. Only matches come back, best first.
1231
+ */
1232
+ function fuzzyRank(query, entries, fields) {
1233
+ const q = query.trim().toLowerCase();
1234
+ if (!q) return [...entries];
1235
+ const inOrder = (f) => { let at = 0; for (const ch of f) if (ch === q[at] && ++at === q.length) return true; return false; };
1236
+ const scored = [];
1237
+ entries.forEach((e, at) => {
1238
+ let best = null;
1239
+ fields(e).forEach((raw, i) => {
1240
+ const f = String(raw ?? "").toLowerCase();
1241
+ if (!f) return;
1242
+ let tier = null;
1243
+ if (f === q) tier = -1;
1244
+ else if (f.startsWith(q)) tier = 0;
1245
+ else if (f.split(/[\s\-_/›.,:]+/).some((w) => w.startsWith(q))) tier = 1;
1246
+ else if (f.includes(q)) tier = 2;
1247
+ else if (i === 0 && q.length >= 3 && inOrder(f)) tier = 4;
1248
+ if (tier === null) return;
1249
+ const score = tier + (i > 0 ? 3 : 0);
1250
+ if (best === null || score < best) best = score;
1251
+ });
1252
+ if (best !== null) scored.push({ e, best, at });
1253
+ });
1254
+ return scored.sort((a, b) => a.best - b.best || a.at - b.at).map((x) => x.e);
1255
+ }
1256
+ // </fuzzy>
1257
+ /** What the folder pickers search: its name, full path, description and id. */
1258
+ const folderFields = (id) => [catLabel(id), folderPath(id), folderById(id)?.description, id];
1259
+ let moveBest = null;
1260
+ function showMovePicker(current) {
1010
1261
  const t = T();
1011
- $("mv-title").textContent = t.moveTitle(nameOf(item));
1262
+ const quick = quickFolders();
1012
1263
  const rows = (p, depth) => kids(p).map((f) => `<button type="button" data-to="${esc(f.id)}" style="--depth:${depth}"
1013
- aria-current="${f.id === item.category}"><span>${esc(catLabel(f.id))}</span><span class="count">${subtotal(f) || ""}</span></button>` + rows(f.id, depth + 1)).join("");
1264
+ 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
1265
  $("mv-list").innerHTML = rows(null, 0);
1015
1266
  $("mv-cancel").textContent = t.cancel;
1016
1267
  $("mv-filter").value = "";
1268
+ moveBest = null;
1017
1269
  $("mv-filter").placeholder = t.filterFolders;
1018
1270
  $("mv-filter").setAttribute("aria-label", t.filterFolders);
1019
1271
  $("move-dlg").showModal();
@@ -1022,16 +1274,15 @@
1022
1274
  }
1023
1275
  $("mv-cancel").onclick = () => $("move-dlg").close();
1024
1276
  $("mv-filter").addEventListener("input", () => {
1025
- const q = $("mv-filter").value.trim().toLowerCase();
1026
1277
  const rows = [...$("mv-list").querySelectorAll("[data-to]")];
1027
- // 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));
1029
- const shown = new Set(q ? (byName.length ? byName : rows.filter((b) => b.dataset.to.includes(q))) : rows);
1278
+ const hit = fuzzyRank($("mv-filter").value, rows, (b) => folderFields(b.dataset.to));
1279
+ const shown = new Set(hit);
1030
1280
  for (const b of rows) b.hidden = !shown.has(b);
1281
+ moveBest = $("mv-filter").value.trim() ? hit[0] ?? null : null; // Enter files into the best match
1031
1282
  });
1032
1283
  $("mv-filter").addEventListener("keydown", (e) => {
1033
1284
  const visible = [...$("mv-list").querySelectorAll("[data-to]:not([hidden])")];
1034
- if (e.key === "Enter") { e.preventDefault(); visible[0]?.click(); }
1285
+ if (e.key === "Enter") { e.preventDefault(); (moveBest ?? visible[0])?.click(); }
1035
1286
  else if (e.key === "ArrowDown") { e.preventDefault(); visible[0]?.focus(); }
1036
1287
  });
1037
1288
  $("mv-list").addEventListener("keydown", (e) => {
@@ -1048,7 +1299,9 @@
1048
1299
  const b = e.target.closest("[data-to]");
1049
1300
  if (!b) return;
1050
1301
  $("move-dlg").close();
1051
- moveItem(moving, b.dataset.to);
1302
+ if (movingMany) bulkApply("move", movingMany, b.dataset.to);
1303
+ else if (state.view === "inbox") inboxFile(moving, b.dataset.to);
1304
+ else moveItem(moving, b.dataset.to);
1052
1305
  };
1053
1306
 
1054
1307
  async function moveItem(id, to, quiet = false) {
@@ -1065,7 +1318,7 @@
1065
1318
  const old = folderById(from); if (old) old.count--;
1066
1319
  const el = document.getElementById(`item-${id}`);
1067
1320
  // Still inside the folder being viewed? Update the badge; otherwise it leaves the list.
1068
- const visible = !state.category || subtreeOf(state.category).has(to);
1321
+ const visible = state.view !== "inbox" && (!state.category || subtreeOf(state.category).has(to));
1069
1322
  if (el && !visible) {
1070
1323
  if (el.contains(document.activeElement)) (el.nextElementSibling ?? el.previousElementSibling)?.querySelector?.(".card")?.focus();
1071
1324
  dismiss(el);
@@ -1075,8 +1328,9 @@
1075
1328
  // The list and the map hold their own copies of the item: keep both in step.
1076
1329
  const onMap = mapItems.find((x) => x.id === id);
1077
1330
  if (onMap && onMap !== item) onMap.category = to;
1078
- if (state.view === "map") drawMap();
1079
- if (!quiet) toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); render(); });
1331
+ if (mapShown()) drawMap();
1332
+ bumpUse(to);
1333
+ if (!quiet) { toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); render(); }); }
1080
1334
  }
1081
1335
  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
1336
  /** Re-draw just the tree's counts after a move. */
@@ -1141,11 +1395,21 @@
1141
1395
 
1142
1396
  // ── Settings ─────────────────────────────────────────────────────────────
1143
1397
  let serverSettings = null;
1398
+ /** The token just created: shown once in the Access tab, then gone. */
1399
+ let justMinted = null;
1400
+ /** The token list Settings last fetched, to warn when a new token repeats an active name. */
1401
+ let knownTokens = [];
1402
+ const nameTaken = (list, name) => list.some((k) => !k.revokedAt && k.name.toLowerCase() === name.toLowerCase());
1144
1403
  async function openSettings(welcome = false) {
1145
1404
  const t = T(), st = t.st;
1146
1405
  const token = store.get("driftnet-token");
1147
1406
  const res = await fetch("/api/settings", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
1148
1407
  serverSettings = res?.ok ? await res.json() : null;
1408
+ // Agent tokens: only the admin password may list them, so a failure just hides the section.
1409
+ const tokRes = serverSettings ? await fetch("/api/agent-tokens", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null) : null;
1410
+ const agentTokens = tokRes?.ok ? await tokRes.json() : null;
1411
+ knownTokens = agentTokens ?? [];
1412
+ const minted = justMinted; justMinted = null;
1149
1413
  const opt = (v, label, cur) => `<option value="${esc(v)}" ${v === cur ? "selected" : ""}>${esc(label)}</option>`;
1150
1414
  const local = `<fieldset class="set-group"><legend>${esc(st.display)}</legend>
1151
1415
  <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 +1438,7 @@
1174
1438
  const accessStatus = `<p class="set-status">${esc(st.accessStatus(yes(a.passwordSet), yes(a.readKey), a.tunnel.running ? a.tunnel.url : "—"))}</p>`;
1175
1439
  server = {
1176
1440
  general: group("language") + group("chat"),
1177
- access: accessStatus + accessPanel(serverSettings, field),
1441
+ access: accessStatus + accessPanel(serverSettings, field) + (agentTokens ? tokensPanel(serverSettings.access, agentTokens, minted) + pairPanel(serverSettings.access) : ""),
1178
1442
  ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + group("model") + group("rules") +
1179
1443
  `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
1180
1444
  };
@@ -1259,6 +1523,77 @@
1259
1523
  <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
1524
  </fieldset>`;
1261
1525
  }
1526
+ function tokensPanel(a, tokens, minted) {
1527
+ const st = T().st;
1528
+ // Local time, the way the reader's clock shows it; the server stores UTC.
1529
+ const when = (iso) => { const d = new Date(iso); return esc(isNaN(d) ? iso : d.toLocaleString(locale, { dateStyle: "short", timeStyle: "short" })); };
1530
+ const rows = tokens.length ? tokens.map((k) => `<div class="keyrow tok ${k.revokedAt ? "revoked" : ""}">
1531
+ <span class="tok-name"><b>${esc(k.name)}</b> <span class="badge">${esc(st.tokScopes[k.scope])}</span>
1532
+ <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>
1533
+ ${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("")
1534
+ : `<small>${esc(st.tokNone)}</small>`;
1535
+ const box = minted ? `<div class="warn"><b>${esc(st.tokNew.replace("{name}", minted.name))}</b><br>${esc(st.tokNewWarn)}
1536
+ <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>
1537
+ ${minted.duplicate ? `<small>${esc(st.tokDuplicate.replace("{name}", minted.name))}</small>` : ""}</div>` : "";
1538
+ const form = a.passwordSet
1539
+ ? `<div class="keyrow"><input id="at-name" maxlength="60" placeholder="${esc(st.tokName)}" autocomplete="off" aria-label="${esc(st.tokName)}">
1540
+ <select id="at-scope" aria-label="${esc(st.tokScope)}">${["write", "read"].map((c) => `<option value="${c}">${esc(st.tokScopes[c])}</option>`).join("")}</select>
1541
+ <button class="btn primary" type="button" id="at-create">${esc(st.tokCreate)}</button></div>`
1542
+ : `<small>${esc(st.tokPasswordOnly)}</small>`;
1543
+ return `<fieldset class="set-group" id="agent-tokens"><legend>${esc(st.agentTokens)}</legend>
1544
+ <small>${esc(st.agentTokensHelp)}</small>${box}
1545
+ <div class="set-row">${rows}</div><div class="set-row">${form}</div></fieldset>`;
1546
+ }
1547
+ function pairPanel(a) {
1548
+ const st = T().st;
1549
+ if (!a.passwordSet) return "";
1550
+ return `<fieldset class="set-group" id="pair-panel"><legend>${esc(st.pairTitle)}</legend>
1551
+ <small>${esc(st.pairHelp)}</small>
1552
+ <div class="keyrow"><input id="pr-name" maxlength="56" placeholder="${esc(st.pairName)}" autocomplete="off" aria-label="${esc(st.pairName)}">
1553
+ <select id="pr-scope" aria-label="${esc(st.tokScope)}">${["write", "read"].map((c) => `<option value="${c}">${esc(st.tokScopes[c])}</option>`).join("")}</select>
1554
+ <button class="btn primary" type="button" id="pr-create">${esc(st.pairCreate)}</button></div>
1555
+ <div id="pair-out" class="pair-out" aria-live="polite"></div></fieldset>`;
1556
+ }
1557
+ let pairTimer = null;
1558
+ /** Show the QR for a fresh code, count down, and notice when the phone has claimed it. */
1559
+ async function showPairing(made, name) {
1560
+ const st = T().st;
1561
+ clearInterval(pairTimer);
1562
+ const base = (serverSettings?.access?.publicUrl || location.origin).replace(/\/$/, "");
1563
+ const link = `${base}/#pair=${made.code}`;
1564
+ const { qrSvg } = await import("/qr.js");
1565
+ const out = $("pair-out");
1566
+ out.innerHTML = `<div class="pair-qr">${qrSvg(link, { scale: 6 })}</div>
1567
+ <p class="pair-time" id="pair-time"></p>
1568
+ ${/\/\/(localhost|127\.0\.0\.1|\[::1\])/.test(base) ? `<small class="dlg-error">${esc(st.pairLocal)}</small>` : ""}
1569
+ <small>${esc(st.pairLink)}</small>
1570
+ <div class="keyrow"><input id="pair-link" readonly value="${esc(link)}"><button class="btn" type="button" data-copy="#pair-link">${esc(st.copy)}</button></div>`;
1571
+ const known = new Set(knownTokens.map((k) => k.id));
1572
+ const until = Date.parse(made.expiresAt);
1573
+ let polling = false;
1574
+ pairTimer = setInterval(async () => {
1575
+ if (!document.body.contains(out)) return clearInterval(pairTimer);
1576
+ const left = Math.max(0, Math.round((until - Date.now()) / 1000));
1577
+ if (!left) {
1578
+ clearInterval(pairTimer);
1579
+ out.innerHTML = `<small>${esc(st.pairExpired)}</small>`;
1580
+ return;
1581
+ }
1582
+ $("pair-time").textContent = st.pairExpires.replace("{t}", `${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")}`);
1583
+ if (polling || left % 3) return;
1584
+ polling = true;
1585
+ const token = store.get("driftnet-token");
1586
+ const res = await fetch("/api/agent-tokens", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
1587
+ const list = res?.ok ? await res.json() : [];
1588
+ polling = false;
1589
+ if (list.some((k) => !known.has(k.id) && !k.revokedAt && k.name === `📱 ${name}`)) {
1590
+ clearInterval(pairTimer);
1591
+ toast(st.pairDone.replace("{name}", name));
1592
+ openSettings();
1593
+ }
1594
+ }, 1000);
1595
+ $("pair-time").textContent = st.pairExpires.replace("{t}", "5:00");
1596
+ }
1262
1597
  async function adminFetch(path, method, body) {
1263
1598
  const token = store.get("driftnet-token");
1264
1599
  const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
@@ -1267,6 +1602,11 @@
1267
1602
  if (!res?.ok) { $("st-error").textContent = friendlyError(data?.error) ?? T().failed; return null; }
1268
1603
  return data;
1269
1604
  }
1605
+ // Enter in the token name creates the token; it must not submit the whole settings form.
1606
+ $("st-body").addEventListener("keydown", (e) => {
1607
+ if (e.target.id === "at-name" && e.key === "Enter") { e.preventDefault(); $("at-create").click(); }
1608
+ if (e.target.id === "pr-name" && e.key === "Enter") { e.preventDefault(); $("pr-create").click(); }
1609
+ });
1270
1610
  $("st-body").addEventListener("input", (e) => {
1271
1611
  if (e.target.id !== "ac-pw") return;
1272
1612
  const pw = e.target.value, s = pw ? pwStrength(pw) : "";
@@ -1295,6 +1635,24 @@
1295
1635
  // Whatever was typed (a new password, private reading) is saved first, not thrown away.
1296
1636
  if (!(await saveSettings())) return;
1297
1637
  if (await adminFetch("/api/read-key", "POST", {})) openSettings();
1638
+ } else if (b.id === "at-create") {
1639
+ const name = $("at-name").value.trim();
1640
+ if (!name) { $("st-error").textContent = st.tokNameNeeded; return; }
1641
+ // Whatever was typed elsewhere in Settings is saved first, not thrown away by the redraw.
1642
+ if (!(await saveSettings())) return;
1643
+ const duplicate = nameTaken(knownTokens, name);
1644
+ const made = await adminFetch("/api/agent-tokens", "POST", { name, scope: $("at-scope").value });
1645
+ if (made) { justMinted = { ...made, duplicate }; openSettings(); }
1646
+ } else if (b.id === "pr-create") {
1647
+ const name = $("pr-name").value.trim();
1648
+ if (!name) { $("st-error").textContent = st.pairNameNeeded; return; }
1649
+ $("st-error").textContent = "";
1650
+ const made = await adminFetch("/api/pair", "POST", { name, scope: $("pr-scope").value });
1651
+ if (made) showPairing(made, name);
1652
+ } else if (b.dataset.remove) {
1653
+ if (await adminFetch(`/api/agent-tokens/${encodeURIComponent(b.dataset.remove)}?purge=1`, "DELETE")) openSettings();
1654
+ } else if (b.dataset.revoke) {
1655
+ if (await adminFetch(`/api/agent-tokens/${encodeURIComponent(b.dataset.revoke)}`, "DELETE")) openSettings();
1298
1656
  } else if (b.id === "ac-tunnel") {
1299
1657
  if (b.dataset.on === "1" && !(await saveSettings())) return;
1300
1658
  b.disabled = true; b.textContent = b.dataset.on === "1" ? st.tunnelStarting : b.textContent;
@@ -1363,6 +1721,41 @@
1363
1721
  /** both: branches on both sides of the root (XMind's default); right: all to the right. */
1364
1722
  let mapLayout = store.get("driftnet-map-layout") || "both";
1365
1723
  let mapItems = [];
1724
+ /** The folder the map is focused on (null = the whole map); lives in the URL hash so it survives a reload. */
1725
+ let mapFocus = null;
1726
+ /** Zoom and scroll per focus root, so stepping back up returns to where you were. */
1727
+ const mapViews = new Map();
1728
+ /** Roving tabindex: the one node Tab lands on. */
1729
+ let mapActive = "root";
1730
+ const focusFromHash = () => { const m = /^#focus=(.+)$/.exec(location.hash); try { return m ? decodeURIComponent(m[1]) : null; } catch { return null; } };
1731
+ function syncFocusHash() {
1732
+ const want = mapShown() && mapFocus ? `#focus=${encodeURIComponent(mapFocus)}` : "";
1733
+ if (want === location.hash || (!want && !location.hash.startsWith("#focus="))) return;
1734
+ history.replaceState(null, "", location.pathname + location.search + want);
1735
+ }
1736
+ /** Focus the map on a folder (null = back to everything), remembering where each view was. */
1737
+ async function setMapFocus(id) {
1738
+ id = id && folderById(id) ? id : null;
1739
+ if (id === mapFocus) return;
1740
+ const wrap = $("map-wrap"), prev = mapFocus;
1741
+ mapViews.set(prev ?? "", { zoom: mapZoom, left: wrap?.scrollLeft ?? 0, top: wrap?.scrollTop ?? 0 });
1742
+ mapFocus = id;
1743
+ // Stepping up: make sure the folder we came from is visible so focus can return to it.
1744
+ mapActive = "root";
1745
+ if (prev && (id === null || isUnder(prev, id))) {
1746
+ for (let p = folderById(prev)?.parent; p && p !== id; p = folderById(p)?.parent) mapOpen.add(p);
1747
+ saveMapOpen();
1748
+ mapActive = `f:${prev}`;
1749
+ }
1750
+ const saved = mapViews.get(id ?? "");
1751
+ if (saved) mapZoom = saved.zoom;
1752
+ syncFocusHash();
1753
+ await renderMap();
1754
+ if (saved) { const w = $("map-wrap"); w.scrollLeft = saved.left; w.scrollTop = saved.top; }
1755
+ ($("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(mapActive)}"]`) ?? $("map-canvas")?.querySelector('.mnode[data-key="root"]'))?.focus({ preventScroll: true });
1756
+ }
1757
+ const isUnder = (id, anc) => { for (let p = folderById(id)?.parent; p; p = folderById(p)?.parent) if (p === anc) return true; return false; };
1758
+ const mapUp = () => setMapFocus(folderById(mapFocus)?.parent ?? null);
1366
1759
  /** Cards shown per folder before the rest fold into a "+N" node. */
1367
1760
  const MAP_CAP = 15;
1368
1761
 
@@ -1374,14 +1767,24 @@
1374
1767
  if (err.unauthorized) return askToken();
1375
1768
  throw err;
1376
1769
  }
1770
+ if (mapFocus && !folderById(mapFocus)) mapFocus = null;
1771
+ syncFocusHash();
1772
+ const crumb = mapFocus ? (() => {
1773
+ const chain = [];
1774
+ for (let p = mapFocus; p; p = folderById(p)?.parent) chain.unshift(p);
1775
+ return `<nav class="map-crumb" aria-label="${esc(t.focusCrumb)}"><button type="button" data-map="focus" data-id="">${esc(t.mapAll)}</button>` +
1776
+ chain.map((id, n) => `<span class="sep" aria-hidden="true">›</span>` + (n === chain.length - 1
1777
+ ? `<span aria-current="location">${esc(catLabel(id))}</span>`
1778
+ : `<button type="button" data-map="focus" data-id="${esc(id)}">${esc(catLabel(id))}</button>`)).join("") + `</nav>`;
1779
+ })() : "";
1377
1780
  const allOpen = mapOpen.size > 0 || !!state.q;
1378
- const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip">${esc(t.mapHint)} <button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
1781
+ const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip">${esc(t.mapHint)} ${esc(t.mapHintFocus)} <button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
1379
1782
  $("list").innerHTML = `<div class="map-bar">
1380
1783
  <button class="btn" type="button" data-map="${allOpen ? "collapse" : "expand"}">${ic(allOpen ? "collapse" : "expand")} ${esc(allOpen ? t.collapseAll : t.expandAll)}</button>
1381
1784
  <button class="btn" type="button" data-map="new">${ic("plus")} ${esc(t.newFolder)}</button>
1382
1785
  <button class="btn" type="button" data-map="layout" aria-pressed="${mapLayout === "both"}" title="${esc(t.layoutHelp)}">${ic(mapLayout === "both" ? "both" : "map")} ${esc(mapLayout === "both" ? t.layoutBoth : t.layoutRight)}</button>
1383
1786
  ${state.q ? `<span class="hint">${esc(t.mapSearch(state.q))}</span>` : ""}</div>
1384
- ${tip}
1787
+ ${crumb}${tip}
1385
1788
  <div class="map-shell"><div class="map-wrap" id="map-wrap"><div class="map-canvas" id="map-canvas"></div></div>
1386
1789
  <div class="map-zoom" role="group" aria-label="${esc(t.zoom)}">
1387
1790
  <button type="button" data-map="out" aria-label="${esc(t.zoomOut)}">${ic("minus")}</button>
@@ -1428,7 +1831,7 @@
1428
1831
  const wrap = $("map-wrap");
1429
1832
  if (wrap) wrap.style.height = `${Math.max(320, innerHeight - wrap.getBoundingClientRect().top - 12)}px`;
1430
1833
  }
1431
- addEventListener("resize", () => { if (state.view === "map") sizeMap(); });
1834
+ addEventListener("resize", () => { if (mapShown()) sizeMap(); if (splitOn()) sizeSplit(); });
1432
1835
 
1433
1836
  /** Root → folders → sub-folders and cards, laid out left to right like XMind. */
1434
1837
  function drawMap() {
@@ -1440,38 +1843,55 @@
1440
1843
  for (const i of mapItems) byFolder.set(i.category, [...(byFolder.get(i.category) ?? []), i]);
1441
1844
  const total = (f) => (byFolder.get(f.id)?.length ?? 0) + kids(f.id).reduce((n, c) => n + total(c), 0);
1442
1845
  const hits = (f) => (byFolder.get(f.id) ?? []).some(hit) || kids(f.id).some(hits);
1846
+ /** What hangs under folder f: its sub-folders, then its cards (capped), then a "+N" node. */
1847
+ const content = (f, depth, color, colorOf) => {
1848
+ const cards = byFolder.get(f.id) ?? [];
1849
+ const out = kids(f.id).map((c, n) => build(c, depth, colorOf ? colorOf(n) : color));
1850
+ const shown = q ? [...cards.filter(hit), ...cards.filter((i) => !hit(i))] : cards;
1851
+ out.push(...shown.slice(0, MAP_CAP).map((i) => ({ key: `i:${i.id}`, type: "item", id: i.id, depth, color,
1852
+ label: (i.summary?.name ?? i.title).slice(0, 32), worth: i.worth, hit: hit(i), children: [] })));
1853
+ if (cards.length > MAP_CAP) out.push({ key: `m:${f.id}`, type: "more", id: f.id, depth, color, label: T().more(cards.length - MAP_CAP), children: [] });
1854
+ return out;
1855
+ };
1443
1856
  const build = (f, depth, color) => {
1444
1857
  // While searching, folders holding a match open by themselves (not saved).
1445
1858
  const open = mapOpen.has(f.id) || (q && hits(f));
1446
1859
  const cards = byFolder.get(f.id) ?? [];
1447
1860
  const node = { key: `f:${f.id}`, type: "folder", id: f.id, label: catLabel(f.id), count: total(f), depth, color, open, children: [],
1448
1861
  hasKids: kids(f.id).length > 0 || cards.length > 0, hit: q && f.id && catLabel(f.id).toLowerCase().includes(q) };
1449
- if (open) {
1450
- node.children.push(...kids(f.id).map((c) => build(c, depth + 1, color)));
1451
- const shown = q ? [...cards.filter(hit), ...cards.filter((i) => !hit(i))] : cards;
1452
- node.children.push(...shown.slice(0, MAP_CAP).map((i) => ({ key: `i:${i.id}`, type: "item", id: i.id, depth: depth + 1, color,
1453
- label: (i.summary?.name ?? i.title).slice(0, 32), worth: i.worth, hit: hit(i), children: [] })));
1454
- if (cards.length > MAP_CAP) node.children.push({ key: `m:${f.id}`, type: "more", id: f.id, depth: depth + 1, color, label: T().more(cards.length - MAP_CAP), children: [] });
1455
- }
1862
+ if (open) node.children = content(f, depth + 1, color);
1456
1863
  return node;
1457
1864
  };
1458
- const root = { key: "root", type: "root", label: "driftnet", count: mapItems.length, depth: 0, color: "var(--m1)",
1459
- children: kids(null).map((f, n) => build(f, 1, `var(--m${(n % 8) + 1})`)) };
1865
+ const colorN = (n) => `var(--m${(n % 8) + 1})`;
1866
+ const focusF = mapFocus ? folderById(mapFocus) : null;
1867
+ // Focused: the folder itself is the root, with its own cards beside its sub-folders.
1868
+ const root = focusF
1869
+ ? { key: "root", type: "root", label: catLabel(focusF.id), count: total(focusF), depth: 0, color: "var(--m1)", children: content(focusF, 1, "var(--m1)", colorN) }
1870
+ : { key: "root", type: "root", label: "driftnet", count: mapItems.length, depth: 0, color: "var(--m1)",
1871
+ children: kids(null).map((f, n) => build(f, 1, colorN(n))) };
1460
1872
 
1461
1873
  // Pass 1: create the nodes and measure them.
1462
1874
  const flat = [];
1463
1875
  const walk = (n) => { flat.push(n); n.children.forEach(walk); };
1464
1876
  walk(root);
1465
1877
  canvas.classList.toggle("searching", !!q);
1466
- canvas.innerHTML = `<svg id="map-svg"></svg>` + flat.map((n) => {
1878
+ canvas.setAttribute("role", "tree");
1879
+ canvas.setAttribute("aria-label", T().mapTree);
1880
+ const nodeKeys = new Set(flat.map((n) => n.key));
1881
+ if (!nodeKeys.has(mapActive)) mapActive = "root";
1882
+ // Sibling position for aria-setsize / aria-posinset (nodes are absolutely positioned, so no group wrappers).
1883
+ flat[0].setsize = 1; flat[0].pos = 1;
1884
+ for (const n of flat) n.children.forEach((c, k) => { c.setsize = n.children.length; c.pos = k + 1; });
1885
+ canvas.innerHTML = `<svg id="map-svg" aria-hidden="true"></svg>` + flat.map((n) => {
1467
1886
  const level = n.type === "folder" ? (n.depth === 1 ? "l1" : "l2") : "";
1468
1887
  const tw = n.type === "folder" && n.hasKids ? `<span class="tw ${n.open ? "open" : ""}">${ic("chev")}</span>` : "";
1469
1888
  const cnt = (n.type === "folder" || n.type === "root") && n.count ? `<span class="cnt">${n.count}</span>` : "";
1470
1889
  const star = n.type === "item" && n.worth === "must-see" ? `<span class="w">${ic("star", "filled")}</span>` : "";
1471
1890
  const more = n.type === "folder" ? `<span class="opt" data-edit="${esc(n.id)}" aria-hidden="true" title="${esc(T().editFolder)}">${ic("dots")}</span>` : "";
1472
1891
  const name = n.type === "folder" ? T().a11yFolder(n.label, n.count) : n.type === "item" ? T().a11yCard(n.label) : n.label;
1473
- 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}
1892
+ const aria = ` aria-label="${esc(name)}" aria-level="${n.depth + 1}" aria-setsize="${n.setsize}" aria-posinset="${n.pos}"`
1893
+ + (n.type === "root" ? (n.children.length ? ` aria-expanded="true"` : "") : n.type === "folder" && n.hasKids ? ` aria-expanded="${!!n.open}"` : "");
1894
+ 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="treeitem" tabindex="${n.key === mapActive ? 0 : -1}"${aria}
1475
1895
  data-key="${esc(n.key)}" style="--c:${n.color}">${tw}${star}<span class="t">${esc(n.label)}</span>${cnt}${more}</div>`;
1476
1896
  }).join("");
1477
1897
  const el = new Map([...canvas.querySelectorAll(".mnode")].map((d) => [d.dataset.key, d]));
@@ -1604,12 +2024,13 @@
1604
2024
  else if (a === "in") mapZoomTo(mapZoom + 0.1);
1605
2025
  else if (a === "out") mapZoomTo(mapZoom - 0.1);
1606
2026
  else if (a === "fit") fitMap();
2027
+ else if (a === "focus") setMapFocus(b.dataset.id || null);
1607
2028
  });
1608
2029
  $("list").addEventListener("dblclick", (e) => {
1609
2030
  const node = e.target.closest(".mnode.folder");
1610
2031
  if (!node) return;
1611
2032
  clearTimeout(folderTap);
1612
- openFolderDialog(node.dataset.key.slice(2));
2033
+ setMapFocus(node.dataset.key.slice(2));
1613
2034
  });
1614
2035
 
1615
2036
  /**
@@ -1693,10 +2114,13 @@
1693
2114
  if (p.touch && p.armed && !p.drag) { endPress(); if (p.movable) pickUp(p.key); return; }
1694
2115
  const target = p.drag ? document.querySelector(".mnode.drop") : null;
1695
2116
  endPress();
2117
+ if (!p.drag && e.shiftKey && role === "admin" && p.key.startsWith("i:")) return toggleSelect(Number(p.key.slice(2)));
1696
2118
  if (!p.drag) return tapNode(p.key, !p.touch);
1697
2119
  if (!target) return;
1698
- const to = target.dataset.key === "root" ? null : target.dataset.key.slice(2);
1699
- if (p.key.startsWith("i:")) await mapMoveItem(Number(p.key.slice(2)), to);
2120
+ const to = target.dataset.key === "root" ? mapFocus : target.dataset.key.slice(2);
2121
+ // Dragging one of several selected cards takes them all.
2122
+ if (p.key.startsWith("i:") && selected.has(Number(p.key.slice(2))) && selected.size > 1) { if (to) await bulkApply("move", [...selected], to); }
2123
+ else if (p.key.startsWith("i:")) await mapMoveItem(Number(p.key.slice(2)), to);
1700
2124
  else await mapMoveFolder(p.key.slice(2), to);
1701
2125
  };
1702
2126
  $("list").addEventListener("pointerup", finish);
@@ -1707,9 +2131,56 @@
1707
2131
  if (e.key === "Enter" || e.key === " ") { e.preventDefault(); tapNode(node.dataset.key); }
1708
2132
  else if ((e.key === "F2" || e.key === "e") && node.dataset.key.startsWith("f:") && role === "admin") { e.preventDefault(); openFolderDialog(node.dataset.key.slice(2)); }
1709
2133
  else if (e.key === "m" && node.dataset.key.startsWith("i:") && role === "admin") { e.preventDefault(); openMovePicker(Number(node.dataset.key.slice(2))); }
2134
+ else if (e.key === "z" && node.dataset.key.startsWith("f:") && !lastUndo) { e.preventDefault(); setMapFocus(node.dataset.key.slice(2)); }
2135
+ else treeKey(e, node);
1710
2136
  });
1711
2137
  })();
1712
2138
  let folderTap = null;
2139
+ /** WAI-ARIA tree keys on the map: arrows, Home/End, type-ahead. Nodes are in tree (document) order. */
2140
+ let typed = "", typedAt = 0;
2141
+ function treeKey(e, node) {
2142
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
2143
+ const nodes = [...$("map-canvas").querySelectorAll(".mnode")], at = nodes.indexOf(node);
2144
+ const go = (el) => { if (!el) return; el.focus({ preventScroll: true }); el.scrollIntoView({ block: "nearest", inline: "nearest" }); };
2145
+ const level = (n) => Number(n.getAttribute("aria-level"));
2146
+ const key = node.dataset.key, k = e.key;
2147
+ const folderId = key.startsWith("f:") ? key.slice(2) : null;
2148
+ const expanded = node.getAttribute("aria-expanded");
2149
+ if (k === "ArrowDown") go(nodes[Math.min(nodes.length - 1, at + 1)]);
2150
+ else if (k === "ArrowUp") go(nodes[Math.max(0, at - 1)]);
2151
+ else if (k === "Home") go(nodes[0]);
2152
+ else if (k === "End") go(nodes[nodes.length - 1]);
2153
+ else if (k === "ArrowRight") {
2154
+ if (expanded === "false" && folderId) toggleFolder(folderId);
2155
+ else if (expanded === "true" && nodes[at + 1] && level(nodes[at + 1]) === level(node) + 1) go(nodes[at + 1]);
2156
+ } else if (k === "ArrowLeft") {
2157
+ if (expanded === "true" && folderId && mapOpen.has(folderId)) toggleFolder(folderId);
2158
+ else { let p = at - 1; while (p >= 0 && level(nodes[p]) >= level(node)) p--; if (p >= 0) go(nodes[p]); }
2159
+ } else if (k.length === 1 && k !== " " || (k === " " && typed)) {
2160
+ const now = Date.now();
2161
+ const fresh = now - typedAt > 700;
2162
+ // Letters that already do something here (and the global shortcuts) can't start a search.
2163
+ const acts = (fresh || !typed) && (/[0-9/?#gGzZ]/.test(k) || ((k === "e" || k === "E") && folderId && role === "admin") || ((k === "m" || k === "M") && key.startsWith("i:") && role === "admin"));
2164
+ if (acts) return;
2165
+ typed = (fresh ? "" : typed) + k.toLowerCase(); typedAt = now;
2166
+ const label = (n) => (n.querySelector(".t")?.textContent ?? "").toLowerCase();
2167
+ const order = [...nodes.slice(at + (typed.length > 1 ? 0 : 1)), ...nodes.slice(0, at + (typed.length > 1 ? 0 : 1))];
2168
+ const hit = order.find((n) => label(n).startsWith(typed));
2169
+ e.stopPropagation(); // not the global shortcuts (f, n, x, j, k …)
2170
+ e.preventDefault();
2171
+ go(hit);
2172
+ return;
2173
+ } else return;
2174
+ e.preventDefault();
2175
+ }
2176
+ // Roving tabindex: whichever node has focus is the one Tab lands on next time.
2177
+ $("list").addEventListener("focusin", (e) => {
2178
+ const node = e.target.closest?.(".mnode");
2179
+ if (!node || node.dataset.key === mapActive) return;
2180
+ $("map-canvas").querySelector(`.mnode[tabindex="0"]`)?.setAttribute("tabindex", "-1");
2181
+ node.setAttribute("tabindex", "0");
2182
+ mapActive = node.dataset.key;
2183
+ });
1713
2184
  /**
1714
2185
  * Picking up (touch): hold a card or folder, let go, then tap the folder it goes into.
1715
2186
  * Nothing competes with scrolling, and no precise finger drag is needed.
@@ -1717,15 +2188,23 @@
1717
2188
  let picked = null;
1718
2189
  function pickUp(key) {
1719
2190
  picked = key;
1720
- const t = T();
2191
+ if (key.startsWith("i:")) selected.add(Number(key.slice(2)));
2192
+ renderPickText();
2193
+ syncSelection();
2194
+ }
2195
+ /** While a card is picked up on a phone, tapping more cards adds them; the next folder tapped receives all. */
2196
+ function renderPickText() {
2197
+ const key = picked, t = T();
2198
+ const many = key.startsWith("i:") && selected.size > 1;
1721
2199
  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);
2200
+ $("pick-text").textContent = many ? t.pickedMany(selected.size) : t.pickedUp(label);
1723
2201
  $("pick-cancel").textContent = t.cancel;
1724
2202
  $("pickbar").hidden = false;
1725
2203
  $("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(key)}"]`)?.classList.add("picked");
1726
2204
  }
1727
2205
  let justDropped = false;
1728
2206
  function dropPicked() {
2207
+ if (picked?.startsWith("i:")) clearSelection();
1729
2208
  picked = null;
1730
2209
  justDropped = true;
1731
2210
  setTimeout(() => (justDropped = false), 400); // the click that follows the tap isn't an edit
@@ -1736,13 +2215,16 @@
1736
2215
  if (picked) {
1737
2216
  const what = picked;
1738
2217
  if (key === what) return dropPicked();
2218
+ if (what.startsWith("i:") && key.startsWith("i:")) { toggleSelect(Number(key.slice(2))); if (selected.size) renderPickText(); else dropPicked(); return; }
1739
2219
  if (key.startsWith("f:") || (key === "root" && what.startsWith("f:"))) {
2220
+ const ids = what.startsWith("i:") && selected.size > 1 ? [...selected] : null;
1740
2221
  dropPicked();
1741
- const to = key === "root" ? null : key.slice(2);
2222
+ const to = key === "root" ? mapFocus : key.slice(2);
2223
+ if (ids) return to ? bulkApply("move", ids, to) : undefined;
1742
2224
  return what.startsWith("i:") ? mapMoveItem(Number(what.slice(2)), to) : mapMoveFolder(what.slice(2), to);
1743
2225
  }
1744
2226
  }
1745
- // A mouse double-click edits the folder, so a single click waits a moment to be sure.
2227
+ // A mouse double-click focuses the folder, so a single click waits a moment to be sure.
1746
2228
  if (key.startsWith("f:") && viaMouse) { clearTimeout(folderTap); folderTap = setTimeout(() => toggleFolder(key.slice(2)), 230); return; }
1747
2229
  if (key.startsWith("f:")) toggleFolder(key.slice(2));
1748
2230
  else if (key.startsWith("i:")) openPeek(Number(key.slice(2)));
@@ -1803,6 +2285,7 @@
1803
2285
  // Filing many cards in a row: the target stays as it was (no sudden expansion); its count pulses instead.
1804
2286
  drawMap();
1805
2287
  pulse(`f:${to}`);
2288
+ bumpUse(to);
1806
2289
  toast(T().moved(nameOf(item), folderPath(to)), async () => {
1807
2290
  if (await mapWrite(`/api/items/${id}/move`, "POST", { folder: from })) { item.category = from; drawMap(); refreshFolders(); }
1808
2291
  });
@@ -1871,14 +2354,18 @@
1871
2354
  const key = a?.readKey || (zh ? "<唯讀分享碼>" : "<share-key>");
1872
2355
  const pw = zh ? "<你的管理密碼>" : "<your-admin-password>";
1873
2356
  const withKey = (u) => (a?.private || a?.readKey ? `${u}?key=${key}` : u);
1874
- const card = (id, title, desc, code) => `<div class="conn"><div class="conn-head"><h4>${esc(title)}</h4>
1875
- <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></div>`;
2357
+ // With an admin password set, agent cards offer their own token instead of the password.
2358
+ const canMint = !!a?.passwordSet;
2359
+ const secrets = {};
2360
+ const card = (id, title, desc, code, agent) => `<div class="conn" id="cc-${id}"><div class="conn-head"><h4>${esc(title)}</h4>
2361
+ <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>
2362
+ ${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
2363
  const cards = [
1877
2364
  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
2365
  `/plugin install driftnet --marketplace KevinChu1110/driftnet`),
1879
2366
  card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
1880
2367
  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"`),
2368
+ `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`, "Claude Code"),
1882
2369
  card("claude", zh ? "Claude 網頁版/桌面版(自訂 connector)" : "Claude.ai / Claude Desktop (custom connector)",
1883
2370
  zh ? "設定 → Connectors → 新增自訂 connector,貼上這個網址。用分享碼連線,只能搜尋和查看,不能改。" : "Settings → Connectors → Add custom connector, paste this URL. The share key makes it read-only: search and look, no changes.",
1884
2371
  withKey(`${base}/mcp`)),
@@ -1890,8 +2377,13 @@
1890
2377
  zh ? `讀一下 ${withKey(`${base}/llms.txt`)} ,這是我收藏的 AI 工具清單。幫我找適合「(你的需求)」的工具。`
1891
2378
  : `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
1892
2379
  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)),
2380
+ JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
1894
2381
  ].join("");
2382
+ // What each agent card shows once it has its own token.
2383
+ snippets = {
2384
+ cc: (tok) => `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer ${tok}"`,
2385
+ agents: (tok) => JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${tok}` } } } }, null, 2),
2386
+ };
1895
2387
  const warn = isLocalUrl
1896
2388
  ? `<p class="warn">${esc(zh ? "這個網址只有這台電腦連得到。雲端的 AI(Claude 網頁版、ChatGPT、Grok、別台機器上的 agent)請先到「設定 → 存取」開公開網址。"
1897
2389
  : "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 +2393,27 @@
1901
2393
  $("cx-close").textContent = t.close;
1902
2394
  $("connect-dlg").showModal();
1903
2395
  }
2396
+ let snippets = {};
1904
2397
  $("cx-close").onclick = () => $("connect-dlg").close();
1905
2398
  $("connect-dlg").addEventListener("click", async (e) => {
1906
2399
  if (e.target === $("connect-dlg")) return $("connect-dlg").close();
2400
+ const mint = e.target.closest("button[data-mint]");
2401
+ if (mint) {
2402
+ const id = mint.dataset.mint, st = T().st;
2403
+ const name = $(`cn-${id}`).value.trim();
2404
+ if (!name) { $(`cn-${id}`).focus(); toast(st.tokNameNeeded); return; }
2405
+ const token = store.get("driftnet-token");
2406
+ const headers = { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) };
2407
+ mint.disabled = true;
2408
+ // Names needn't be unique, so never block: just say so when an active one already has this name.
2409
+ const before = await fetch("/api/agent-tokens", { headers }).then((r) => (r.ok ? r.json() : [])).catch(() => []);
2410
+ const res = await fetch("/api/agent-tokens", { method: "POST", headers, body: JSON.stringify({ name, scope: "write" }) }).catch(() => null);
2411
+ const made = res?.ok ? await res.json().catch(() => null) : null;
2412
+ if (!made) { mint.disabled = false; toast(T().failed); return; }
2413
+ $(`cx-${id}`).textContent = snippets[id](made.token);
2414
+ 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>`;
2415
+ return;
2416
+ }
1907
2417
  const b = e.target.closest("button[data-copy]");
1908
2418
  if (!b) return;
1909
2419
  await navigator.clipboard?.writeText($("cx-body").querySelector(b.dataset.copy).textContent).catch(() => {});
@@ -2066,19 +2576,89 @@
2066
2576
 
2067
2577
  async function render() {
2068
2578
  updateCrumb();
2069
- document.body.classList.toggle("map-view", state.view === "map");
2070
- if (state.view !== "map" && picked) dropPicked();
2579
+ const viewKey = [state.view, state.category, state.kind, state.q].join("|");
2580
+ if (viewKey !== lastViewKey) { lastViewKey = viewKey; selected.clear(); selAnchor = null; }
2581
+ document.body.classList.toggle("map-view", mapShown());
2582
+ document.body.classList.toggle("split-view", splitOn());
2583
+ if (!mapShown() && picked) dropPicked();
2071
2584
  if (state.view === "notes") return renderNotes();
2072
2585
  if (state.view === "map") return renderMap();
2586
+ syncFocusHash();
2587
+ if (splitOn()) return renderSplit();
2588
+ return renderCards();
2589
+ }
2590
+ let splitQueue = Promise.resolve();
2591
+ /** Cards on the left, the mind map on the right: each renderer fills its own pane. */
2592
+ function renderSplit() {
2593
+ const run = async () => {
2594
+ if (!splitOn()) return renderCards();
2595
+ $("list").innerHTML = `<div class="split"><section class="split-list" id="split-list" aria-label="${esc(T().splitCards)}"></section><section class="split-map" id="split-map"></section></div>`;
2596
+ await renderMap(); // the map first: the selection check then knows both sides
2597
+ await inPane($("split-list"), renderCards);
2598
+ sizeSplit();
2599
+ syncSelection();
2600
+ };
2601
+ return (splitQueue = splitQueue.catch(() => {}).then(run));
2602
+ }
2603
+ function sizeSplit() {
2604
+ const p = document.getElementById("split-list");
2605
+ if (p) p.style.height = `${Math.max(320, innerHeight - p.getBoundingClientRect().top - 12)}px`;
2606
+ }
2607
+ // The map renderer and the map's own moves write into whatever "list" is: send them to the map pane while split.
2608
+ const renderMapBase = renderMap, drawMapBase = drawMap;
2609
+ renderMap = () => { const pane = document.getElementById("split-map"); return pane && splitOn() ? inPane(pane, renderMapBase) : renderMapBase(); };
2610
+ drawMap = () => { drawMapBase(); if (splitOn()) syncListWithMap(); };
2611
+ /** A card moved on the map: bring the list beside it in step (no refetch). */
2612
+ function syncListWithMap() {
2613
+ const by = new Map(mapItems.map((i) => [i.id, i]));
2614
+ const gone = new Set();
2615
+ for (const i of items) {
2616
+ const m = by.get(i.id);
2617
+ if (!m || m.category === i.category) continue;
2618
+ i.category = m.category;
2619
+ const el = document.getElementById(`item-${i.id}`);
2620
+ if (!el) continue;
2621
+ if (state.category && !subtreeOf(state.category).has(i.category)) { gone.add(i.id); el.remove(); }
2622
+ else { el.outerHTML = card(i); attachSwipe(document.getElementById(`item-${i.id}`)); }
2623
+ }
2624
+ if (gone.size) items = items.filter((i) => !gone.has(i.id));
2625
+ syncSelection();
2626
+ }
2627
+ wideQuery.addEventListener("change", () => { if (split && (state.view === "all" || state.view === "favorites")) render(); });
2628
+ // Dragging a card from the list onto a folder of the map files it there (the whole selection, if it is part of one).
2629
+ (() => {
2630
+ const node = (e) => e.target.closest?.(".mnode.folder, .mnode.root");
2631
+ const clear = () => document.querySelectorAll(".mnode.drop").forEach((d) => d.classList.remove("drop"));
2632
+ $("list").addEventListener("dragover", (e) => {
2633
+ const n = node(e);
2634
+ if (!n || !e.dataTransfer.types.includes("text/x-driftnet-item")) return;
2635
+ e.preventDefault();
2636
+ e.dataTransfer.dropEffect = "move";
2637
+ if (!n.classList.contains("drop")) { clear(); n.classList.add("drop"); }
2638
+ });
2639
+ $("list").addEventListener("dragleave", (e) => { if (!$("list").contains(e.relatedTarget)) clear(); });
2640
+ document.addEventListener("dragend", clear);
2641
+ $("list").addEventListener("drop", (e) => {
2642
+ const n = node(e), id = Number(e.dataTransfer.getData("text/x-driftnet-item"));
2643
+ clear();
2644
+ if (!n || !id || n.dataset.key === "root") return;
2645
+ e.preventDefault();
2646
+ const to = n.dataset.key.slice(2);
2647
+ if (selected.has(id) && selected.size > 1) bulkApply("move", [...selected], to);
2648
+ else if (mapItems.some((i) => i.id === id)) mapMoveItem(id, to);
2649
+ else moveItem(id, to);
2650
+ });
2651
+ })();
2652
+ async function renderCards() {
2073
2653
  const p = new URLSearchParams({ limit: "300" });
2074
2654
  if (prefs.sort !== "best") p.set("sort", prefs.sort);
2075
2655
  if (state.view !== "all") p.set("view", state.view);
2076
2656
  for (const k of ["category", "kind", "q"]) if (state[k]) p.set(k, state[k]);
2077
2657
  items = await api(`/api/items?${p}`);
2078
2658
  const t = T();
2079
- const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : t.empty;
2659
+ const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : state.view === "inbox" ? t.emptyInbox : t.empty;
2080
2660
  $("list").innerHTML = items.length
2081
- ? `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : t.hint)}</p>` + items.map(card).join("")
2661
+ ? `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : state.view === "inbox" ? t.hintInbox : t.hint)}</p>` + items.map(card).join("")
2082
2662
  : `<div class="empty first"><span>${esc(empty)}</span>${state.view === "all" && !state.q && !state.category && role === "admin"
2083
2663
  ? `<form class="add" id="add-form"><input id="add-url" type="url" inputmode="url" placeholder="${esc(t.addPlaceholder)}" aria-label="${esc(t.addPlaceholder)}">
2084
2664
  <button class="btn primary" type="submit">${ic("plus")} ${esc(t.addLink)}</button></form>
@@ -2086,6 +2666,7 @@
2086
2666
  $("add-form")?.addEventListener("submit", addLink);
2087
2667
  $("list").querySelector("[data-connect-empty]")?.addEventListener("click", () => openConnect());
2088
2668
  for (const el of $("list").querySelectorAll(".swipe")) attachSwipe(el);
2669
+ syncSelection();
2089
2670
  restoreFocus();
2090
2671
  // Only #item-<n> is ours; anything else in the hash must not break the page.
2091
2672
  if (/^#item-\d+$/.test(location.hash)) {
@@ -2093,7 +2674,7 @@
2093
2674
  if (target) {
2094
2675
  // Clear the sticky header (taller on a phone), then flash the card so it's obvious which one was meant.
2095
2676
  const top = target.getBoundingClientRect().top + scrollY - document.querySelector("header").offsetHeight - ($("crumb").offsetHeight || 0) - 12;
2096
- scrollTo({ top });
2677
+ if (splitOn()) target.scrollIntoView({ block: "center" }); else scrollTo({ top });
2097
2678
  target.classList.remove("flash"); void target.offsetWidth; target.classList.add("flash");
2098
2679
  }
2099
2680
  }
@@ -2127,6 +2708,7 @@
2127
2708
  ${i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""}
2128
2709
  ${i.found?.length ? `<div class="found"><span>${esc(t.foundIn)}</span>${i.found.map((c) => `<a href="#item-${c.id}">${esc(c.name)}</a>`).join("")}</div>` : ""}
2129
2710
  ${i.flags.length ? `<div class="flag">⚠ ${esc(i.flags.map((f) => t.flags[f] ?? f).join(", "))}</div>` : ""}
2711
+ ${state.view === "inbox" ? inboxChips(i) : ""}
2130
2712
  <div class="meta">
2131
2713
  <span>#${i.id}</span><span>${esc(t.kind1?.[i.kind] ?? t.kinds[i.kind] ?? i.kind)}</span>${i.shareCount ? `<span>${esc(t.shared(i.shareCount))}</span>` : ""}
2132
2714
  <span>${esc(i.createdAt.slice(0, 10))}</span>
@@ -2139,8 +2721,33 @@
2139
2721
  </div>`;
2140
2722
  }
2141
2723
 
2724
+ /** Inbox: one-tap chips for the card's suggested folders (keys 1–3), and "other folder…" (m). */
2725
+ function inboxChips(i) {
2726
+ const t = T();
2727
+ const picks = (i.suggestions ?? []).filter((x) => folderById(x.folder)).slice(0, 3);
2728
+ return `<div class="chips" role="group" aria-label="${esc(t.moveTo)}">` +
2729
+ picks.map((x, n) => `<button type="button" class="chip" data-chip="${esc(x.folder)}" title="${esc(t.chipTitle(Math.round(x.score * 100)))}"><kbd>${n + 1}</kbd>${esc(folderPath(x.folder))}</button>`).join("") +
2730
+ `<button type="button" class="chip more" data-chip-more><kbd>m</kbd>${esc(t.chipOther)}</button></div>`;
2731
+ }
2732
+ /** File an Inbox card; the next one takes focus so a run of keys or taps keeps going. Undo puts it back in the Inbox. */
2733
+ function inboxFile(id, folder) {
2734
+ const sw = document.getElementById(`item-${id}`);
2735
+ const nextId = Number((sw?.nextElementSibling ?? sw?.previousElementSibling)?.dataset?.id) || null;
2736
+ return bulkApply("move", [id], folder).then(() => { if (nextId) document.querySelector(`#item-${nextId} .card`)?.focus({ preventScroll: true }); });
2737
+ }
2738
+ $("list").addEventListener("click", (e) => {
2739
+ const chip = e.target.closest("[data-chip], [data-chip-more]");
2740
+ const sw = chip?.closest(".swipe");
2741
+ if (!chip || !sw || role !== "admin" || selected.size) return;
2742
+ e.preventDefault();
2743
+ if (chip.dataset.chip) inboxFile(Number(sw.dataset.id), chip.dataset.chip);
2744
+ else openMovePicker(Number(sw.dataset.id));
2745
+ });
2746
+
2142
2747
  // ── Actions ──────────────────────────────────────────────────────────────
2143
- const find = (id) => items.find((x) => x.id === id) ?? mapItems.find((x) => x.id === id);
2748
+ /** Cards found by the palette that neither the list nor the map holds (so the preview and Move to… can still reach them). */
2749
+ const extraItems = new Map();
2750
+ const find = (id) => items.find((x) => x.id === id) ?? mapItems.find((x) => x.id === id) ?? extraItems.get(id);
2144
2751
  const nameOf = (i) => (i.summary?.name ?? i.title).slice(0, 40);
2145
2752
 
2146
2753
  async function act(id, action) {
@@ -2193,10 +2800,101 @@
2193
2800
  if (!stats) return;
2194
2801
  $("stats").textContent = T().stats(stats.items, stats.shares);
2195
2802
  const set = (v, n) => { const c = $("nav").querySelector(`[data-field="view"][data-value="${v}"] .count`); if (c) c.textContent = n || (v === "all" ? "0" : ""); };
2196
- set("all", stats.items); set("favorites", stats.favorites); set("trash", stats.trash);
2803
+ set("all", stats.items); set("favorites", stats.favorites); set("trash", stats.trash); set("inbox", stats.inbox);
2197
2804
  }
2198
2805
 
2806
+ // ── Select several cards: x, Shift-click or a long press; then act on all of them ──
2807
+ const selected = new Set();
2808
+ let selAnchor = null, lastViewKey = "";
2809
+ const visibleIds = () => [...$("list").querySelectorAll(".swipe")].map((el) => Number(el.dataset.id));
2810
+ const focusedId = () => Number(document.activeElement?.closest?.(".swipe")?.dataset.id) || null;
2811
+ function toggleSelect(id, on = !selected.has(id)) {
2812
+ if (role !== "admin") return;
2813
+ if (on) selected.add(id); else selected.delete(id);
2814
+ selAnchor = id;
2815
+ syncSelection();
2816
+ }
2817
+ function selectRange(id) {
2818
+ const ids = visibleIds();
2819
+ const a = ids.indexOf(selAnchor ?? focusedId() ?? id), b = ids.indexOf(id);
2820
+ if (a < 0 || b < 0) return toggleSelect(id, true);
2821
+ for (const x of ids.slice(Math.min(a, b), Math.max(a, b) + 1)) selected.add(x);
2822
+ selAnchor = id;
2823
+ syncSelection();
2824
+ }
2825
+ function clearSelection() { selected.clear(); selAnchor = null; syncSelection(); }
2826
+ /** Paint the selection on whatever is drawn (list or map) and refresh the bar. */
2827
+ function syncSelection() {
2828
+ const here = new Set([...(mapShown() ? mapItems.map((i) => i.id) : []), ...(state.view === "map" ? [] : visibleIds())]);
2829
+ for (const id of [...selected]) if (!here.has(id)) selected.delete(id);
2830
+ for (const el of $("list").querySelectorAll(".swipe")) el.classList.toggle("selected", selected.has(Number(el.dataset.id)));
2831
+ for (const n of $("list").querySelectorAll(".mnode.item")) n.classList.toggle("sel", selected.has(Number(n.dataset.key.slice(2))));
2832
+ document.body.classList.toggle("selecting", selected.size > 0 && role === "admin");
2833
+ renderSelbar();
2834
+ }
2835
+ function renderSelbar() {
2836
+ const bar = $("selbar"), n = selected.size, t = T();
2837
+ bar.hidden = !n || role !== "admin" || (state.view === "map" && !!picked);
2838
+ if (bar.hidden) return;
2839
+ const keep = document.activeElement?.closest?.("#selbar")?.dataset?.sel ?? document.activeElement?.dataset?.sel;
2840
+ const trash = state.view === "trash", map = state.view === "map";
2841
+ const allFav = [...selected].every((id) => find(id)?.favorite);
2842
+ bar.setAttribute("aria-label", t.nSelected(n));
2843
+ bar.innerHTML = `<span class="sel-n" role="status">${esc(t.nSelected(n))}</span>` +
2844
+ (trash ? "" : `<button type="button" data-sel="move">${ic("move")} ${esc(t.moveTo)}</button>
2845
+ <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>`) +
2846
+ `<button type="button" data-sel="trash">${ic(trash ? "undo" : "trash")} ${esc(trash ? t.restore : t.trashShort)}</button>` +
2847
+ (map ? "" : `<button type="button" data-sel="all">${esc(t.selectAll)}</button>`) +
2848
+ `<button type="button" data-sel="clear">${esc(t.clearSel)}</button>`;
2849
+ if (keep) bar.querySelector(`[data-sel="${keep}"]`)?.focus({ preventScroll: true });
2850
+ }
2851
+ $("selbar").addEventListener("click", (e) => {
2852
+ const b = e.target.closest("[data-sel]");
2853
+ if (!b) return;
2854
+ const ids = [...selected], a = b.dataset.sel;
2855
+ if (a === "move") openMovePickerFor(ids);
2856
+ else if (a === "fav") bulkApply(ids.every((id) => find(id)?.favorite) ? "unfavorite" : "favorite", ids);
2857
+ else if (a === "trash") bulkApply(state.view === "trash" ? "restore" : "trash", ids);
2858
+ else if (a === "all") { for (const id of visibleIds()) selected.add(id); syncSelection(); }
2859
+ else clearSelection();
2860
+ });
2861
+ /** One request for the whole batch; Undo hands back the id the server kept the snapshot under. */
2862
+ async function bulkApply(action, ids, folder) {
2863
+ if (!ids.length) return;
2864
+ const t = T(), n = ids.length;
2865
+ const r = await mapWrite("/api/items/bulk", "POST", { action, ids, ...(action === "move" ? { folder } : {}) });
2866
+ if (!r) return;
2867
+ clearSelection();
2868
+ await refreshFolders();
2869
+ await render();
2870
+ refreshCounts();
2871
+ if (action === "move" && state.view === "map") pulse(`f:${folder}`);
2872
+ const text = { move: () => t.bulkMoved(n, folderPath(folder)), trash: () => t.bulkRemoved(n), restore: () => t.bulkRestored(n),
2873
+ favorite: () => t.bulkFaved(n), unfavorite: () => t.bulkUnfaved(n) }[action]();
2874
+ toast(text, async () => {
2875
+ if (!(await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo }))) return;
2876
+ await refreshFolders();
2877
+ await render();
2878
+ refreshCounts();
2879
+ });
2880
+ }
2881
+ /** Keys 1–9: file the selection, or else the focused card, into the nth most-used folder. */
2882
+ function quickMove(n) {
2883
+ const to = quickFolders()[n - 1];
2884
+ if (!to) return false;
2885
+ if (selected.size) bulkApply("move", [...selected], to);
2886
+ else if (focusedId() && state.view !== "map") moveItem(focusedId(), to);
2887
+ else return false;
2888
+ return true;
2889
+ }
2199
2890
  $("list").addEventListener("click", (e) => {
2891
+ // With cards selected a click picks or drops the card; Shift-click selects a range. Links and buttons don't fire meanwhile.
2892
+ const sw = e.target.closest(".swipe");
2893
+ if (sw && role === "admin" && (e.shiftKey || selected.size) && !e.target.closest(".tool, .link-btn, .chip")) {
2894
+ e.preventDefault();
2895
+ if (e.shiftKey) selectRange(Number(sw.dataset.id)); else toggleSelect(Number(sw.dataset.id));
2896
+ return;
2897
+ }
2200
2898
  const n = e.target.closest('.link-btn[data-act="note"]');
2201
2899
  if (n) return openItemNote(Number(n.closest(".swipe").dataset.id));
2202
2900
  const b = e.target.closest(".tool");
@@ -2214,6 +2912,12 @@
2214
2912
  });
2215
2913
  // A "found in" link to a card outside the current filter: show everything, then jump.
2216
2914
  addEventListener("hashchange", () => {
2915
+ if (location.hash.startsWith("#focus=")) {
2916
+ const id = focusFromHash();
2917
+ if (state.view !== "map") { mapFocus = id; Object.assign(state, { view: "map", category: "" }); load(); }
2918
+ else setMapFocus(id);
2919
+ return;
2920
+ }
2217
2921
  if (/^#item-\d+$/.test(location.hash) && !document.getElementById(location.hash.slice(1))) {
2218
2922
  Object.assign(state, { view: "all", category: "", kind: "", q: "" });
2219
2923
  $("q").value = "";
@@ -2282,8 +2986,21 @@
2282
2986
  };
2283
2987
  cardEl.addEventListener("pointerup", end);
2284
2988
  cardEl.addEventListener("pointercancel", end);
2285
- // A drag that ends on a link must not open it.
2286
- cardEl.addEventListener("click", (e) => { if (Math.abs(dx) > 8) { e.preventDefault(); e.stopPropagation(); } }, true);
2989
+ // Holding a card on a phone (~0.5 s, without moving) starts selecting.
2990
+ let hold = null, held = false, hx = 0, hy = 0;
2991
+ const cancelHold = () => { clearTimeout(hold); hold = null; };
2992
+ cardEl.addEventListener("pointerdown", (e) => {
2993
+ held = false;
2994
+ if (e.pointerType !== "touch" || e.button !== 0 || e.target.closest(".tool, .link-btn")) return;
2995
+ hx = e.clientX; hy = e.clientY;
2996
+ hold = setTimeout(() => { hold = null; held = true; navigator.vibrate?.(12); toggleSelect(Number(el.dataset.id), true); }, 500);
2997
+ });
2998
+ cardEl.addEventListener("pointermove", (e) => { if (hold && Math.hypot(e.clientX - hx, e.clientY - hy) > 8) cancelHold(); });
2999
+ cardEl.addEventListener("pointerup", cancelHold);
3000
+ cardEl.addEventListener("pointercancel", cancelHold);
3001
+ cardEl.addEventListener("contextmenu", (e) => { if (hold || held) e.preventDefault(); });
3002
+ // A drag that ends on a link must not open it, nor must the lift of a long press.
3003
+ cardEl.addEventListener("click", (e) => { if (Math.abs(dx) > 8 || held) { held = false; e.preventDefault(); e.stopPropagation(); } }, true);
2287
3004
  }
2288
3005
 
2289
3006
  // ── Toast with undo ──────────────────────────────────────────────────────
@@ -2305,6 +3022,211 @@
2305
3022
  if (el) el.focus({ preventScroll: true });
2306
3023
  }
2307
3024
  for (const d of document.querySelectorAll("dialog")) d.addEventListener("close", () => setTimeout(restoreFocus, 0));
3025
+ // ── Commands and the palette (⌘K / Ctrl+K) ────────────────────────────────
3026
+ /** Everything the palette can run. keys (two keys = "g" then …) and help (a STRINGS key) also feed the ? dialog. */
3027
+ function showLayout(kind) {
3028
+ split = kind === "split";
3029
+ store.set("driftnet-split", split ? "1" : "0");
3030
+ Object.assign(state, { view: kind === "map" ? "map" : "all", category: "" });
3031
+ load();
3032
+ }
3033
+ function toggleDark() {
3034
+ const dark = document.documentElement.dataset.theme === "dark" || (prefs.theme === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
3035
+ prefs.theme = dark ? "light" : "dark";
3036
+ store.set("driftnet-prefs", JSON.stringify(prefs));
3037
+ applyPrefs();
3038
+ }
3039
+ const commands = [
3040
+ { id: "view-list", label: { en: "Show the card list", "zh-TW": "顯示卡片列表" }, keys: ["g", "a"], help: "kAll", run: () => showLayout("list") },
3041
+ { id: "view-map", label: { en: "Show the mind map", "zh-TW": "顯示樹狀圖" }, keys: ["g", "m"], help: "kMap", run: () => showLayout("map") },
3042
+ { id: "view-split", label: { en: "Show cards and mind map side by side", "zh-TW": "並排顯示卡片與樹狀圖" }, when: () => wideQuery.matches, run: () => showLayout("split") },
3043
+ { id: "move", label: { en: "Move the focused card…", "zh-TW": "移動目前選取的卡片…" }, when: () => role === "admin" && !!pal.focused, run: () => openMovePicker(pal.focused) },
3044
+ { id: "new-folder", label: { en: "New folder", "zh-TW": "新增資料夾" }, when: () => role === "admin", run: () => openFolderDialog(null, null) },
3045
+ { id: "export-md", label: { en: "Download a backup (Markdown)", "zh-TW": "下載備份(Markdown)" }, run: () => download("markdown") },
3046
+ { id: "export-vault", label: { en: "Download for Obsidian / Notion", "zh-TW": "下載給 Obsidian/Notion" }, run: () => download("vault") },
3047
+ { id: "settings", label: { en: "Settings", "zh-TW": "設定" }, run: () => openSettings() },
3048
+ { id: "dark", label: { en: "Toggle dark mode", "zh-TW": "切換深色模式" }, run: toggleDark },
3049
+ { id: "language", label: { en: "Switch language", "zh-TW": "切換語言" }, run: () => $("lang").click() },
3050
+ { id: "keys", label: { en: "Keyboard shortcuts", "zh-TW": "快捷鍵" }, keys: ["?"], help: "kHelp", run: () => openKeys() },
3051
+ ];
3052
+ const cmdLabel = (c) => c.label[locale] ?? c.label.en;
3053
+ const goFolder = (id) => { Object.assign(state, { view: "all", category: id, kind: "" }); load(); };
3054
+ const pal = { rows: [], at: 0, gen: 0, timer: 0, cards: [], focused: null };
3055
+ function paletteRows(q) {
3056
+ const rows = [];
3057
+ const fl = q ? fuzzyRank(q, folders, (f) => folderFields(f.id)) : quickFolders().map(folderById).filter(Boolean);
3058
+ for (const f of fl.slice(0, q ? 6 : 5)) rows.push({ group: "folders", label: catLabel(f.id), sub: folderPath(f.id) === catLabel(f.id) ? "" : folderPath(f.id), color: folderColor(f.id), run: () => goFolder(f.id) });
3059
+ if (q) for (const i of pal.cards) rows.push({ group: "cards", label: nameOf(i), sub: folderPath(i.category), run: () => { extraItems.set(i.id, i); openPeek(i.id); } });
3060
+ const avail = commands.filter((c) => !c.when || c.when());
3061
+ for (const c of fuzzyRank(q, avail, (c) => [cmdLabel(c), c.id]).slice(0, q ? 8 : 20))
3062
+ rows.push({ group: "commands", label: cmdLabel(c), sub: c.keys?.join(" ") ?? "", run: c.run });
3063
+ return rows;
3064
+ }
3065
+ function renderPalette() {
3066
+ const t = T(), input = $("cmd-input");
3067
+ pal.rows = paletteRows(input.value);
3068
+ pal.at = Math.min(pal.at, Math.max(0, pal.rows.length - 1));
3069
+ let html = "", last = "";
3070
+ pal.rows.forEach((r, i) => {
3071
+ if (r.group !== last) { last = r.group; html += `<div class="cmd-h" role="presentation">${esc(t.palGroups[r.group])}</div>`; }
3072
+ html += `<div class="cmd-o" role="option" id="cmd-o-${i}" data-i="${i}" aria-selected="${i === pal.at}"><span class="lab" ${r.color ? `style="--c:${r.color}"` : ""}>${esc(r.label)}</span>` +
3073
+ (r.sub ? `<span class="sub">${esc(r.sub)}</span>` : "") + `</div>`;
3074
+ });
3075
+ $("cmd-list").innerHTML = html || `<div class="cmd-empty" role="presentation">${esc(t.palNone)}</div>`;
3076
+ if (pal.rows.length) input.setAttribute("aria-activedescendant", `cmd-o-${pal.at}`); else input.removeAttribute("aria-activedescendant");
3077
+ $("cmd-o-" + pal.at)?.scrollIntoView({ block: "nearest" });
3078
+ }
3079
+ function openPalette() {
3080
+ if (document.querySelector("dialog[open]")) return;
3081
+ const t = T();
3082
+ pal.focused = focusedId();
3083
+ pal.at = 0; pal.cards = []; pal.gen++;
3084
+ $("cmd-input").value = "";
3085
+ $("cmd-input").placeholder = t.palPlaceholder;
3086
+ $("cmd-input").setAttribute("aria-label", t.palette);
3087
+ $("cmd-list").setAttribute("aria-label", t.palette);
3088
+ renderPalette();
3089
+ $("cmd-dlg").showModal();
3090
+ $("cmd-input").focus();
3091
+ }
3092
+ function runPalette(i) {
3093
+ const r = pal.rows[i];
3094
+ if (!r) return;
3095
+ $("cmd-dlg").close();
3096
+ setTimeout(r.run, 0); // after the dialog has let go of focus
3097
+ }
3098
+ $("cmd-input").addEventListener("input", () => {
3099
+ const q = $("cmd-input").value.trim(), gen = ++pal.gen;
3100
+ pal.at = 0;
3101
+ clearTimeout(pal.timer);
3102
+ if (q.length < 2) pal.cards = [];
3103
+ else pal.timer = setTimeout(async () => {
3104
+ const found = await api(`/api/items?${new URLSearchParams({ q, limit: "6" })}`).catch(() => []);
3105
+ if (gen !== pal.gen) return;
3106
+ pal.cards = found;
3107
+ renderPalette();
3108
+ }, 150);
3109
+ renderPalette();
3110
+ });
3111
+ $("cmd-input").addEventListener("keydown", (e) => {
3112
+ const n = pal.rows.length;
3113
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
3114
+ e.preventDefault();
3115
+ if (n) { pal.at = (pal.at + (e.key === "ArrowDown" ? 1 : n - 1)) % n; renderPalette(); }
3116
+ } else if (e.key === "Enter") { e.preventDefault(); runPalette(pal.at); }
3117
+ });
3118
+ $("cmd-list").addEventListener("click", (e) => { const o = e.target.closest("[data-i]"); if (o) runPalette(Number(o.dataset.i)); });
3119
+ $("cmd-list").addEventListener("pointermove", (e) => {
3120
+ const o = e.target.closest("[data-i]");
3121
+ if (!o || Number(o.dataset.i) === pal.at) return;
3122
+ $("cmd-o-" + pal.at)?.setAttribute("aria-selected", "false");
3123
+ pal.at = Number(o.dataset.i);
3124
+ o.setAttribute("aria-selected", "true");
3125
+ $("cmd-input").setAttribute("aria-activedescendant", o.id);
3126
+ });
3127
+ $("cmd-dlg").addEventListener("click", (e) => { if (e.target === $("cmd-dlg")) $("cmd-dlg").close(); });
3128
+ $("cmd-dlg").addEventListener("close", () => { clearTimeout(pal.timer); pal.gen++; });
3129
+ $("palette-btn").onclick = openPalette;
3130
+ addEventListener("keydown", (e) => {
3131
+ if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey || e.key.toLowerCase() !== "k") return;
3132
+ e.preventDefault();
3133
+ if ($("cmd-dlg").open) $("cmd-dlg").close(); else openPalette();
3134
+ });
3135
+ /** The ? dialog: every shortcut, and which folder each number key files into. */
3136
+ function openKeys() {
3137
+ const t = T(), quick = quickFolders();
3138
+ const row = (keys, text) => `<dt>${keys.map((k) => `<kbd>${esc(k)}</kbd>`).join(" ")}</dt><dd>${esc(text)}</dd>`;
3139
+ $("ky-title").textContent = t.keysTitle;
3140
+ $("ky-close").textContent = t.keysClose;
3141
+ $("ky-body").innerHTML =
3142
+ `<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) +
3143
+ `<h4>${esc(t.keysInbox)}</h4>` + row(["1", "2", "3"], t.kChip) + row(["s"], t.kSkip) + row(["m"], t.kMove) +
3144
+ `<h4>${esc(t.keysSelect)}</h4>` + row(["x"], t.kSelect) + row(["Shift", "click"], t.kRange) + row([t.kHold], t.kLong) + row(["Esc"], t.kClear) +
3145
+ `<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>`) +
3146
+ `<dd style="grid-column:1/-1">${esc(t.kQuickInbox)}</dd>` +
3147
+ `<h4>${esc(t.keysGo)}</h4>` + row([isMac ? "⌘" : "Ctrl", "K"], t.kPalette) + row(["/"], t.kSearch) +
3148
+ commands.filter((c) => c.keys).map((c) => row(c.keys, t[c.help])).join("") + row(["z"], t.kUndo) +
3149
+ `<h4>${esc(t.keysMap)}</h4>` + row(["↓", "↑"], t.kTreeNav) + row(["→"], t.kTreeOpen) + row(["←"], t.kTreeClose) + row(["Home", "End"], t.kTreeEnds) +
3150
+ row([t.kTreeType], t.kTreeTypeText) + row(["z"], t.kFocus) + row(["Esc", "Backspace"], t.kFocusUp);
3151
+ $("keys-dlg").showModal();
3152
+ }
3153
+ $("ky-close").onclick = () => $("keys-dlg").close();
3154
+ $("keys-dlg").addEventListener("click", (e) => { if (e.target === $("keys-dlg")) $("keys-dlg").close(); });
3155
+ // ── AI folder plan: proposed, reviewed line by line, applied in one go ────
3156
+ let plan = null;
3157
+ const planOps = () => plan?.operations ?? [];
3158
+ /** A folder named in a plan: a real one by path, or one the plan itself creates (new:<ref>). */
3159
+ function planFolder(id) {
3160
+ if (!id.startsWith("new:")) return folderPath(id);
3161
+ const c = planOps().find((o) => o.op === "create" && o.ref === id.slice(4));
3162
+ return c ? (c.parent ? `${planFolder(c.parent)} › ${c.name}` : c.name) : id;
3163
+ }
3164
+ const planNeeds = (o) => o.op === "move" ? o.folder : o.op === "create" && o.parent ? o.parent : "";
3165
+ function planLine(o) {
3166
+ const t = T();
3167
+ return o.op === "create" ? t.planCreate(planFolder("new:" + o.ref))
3168
+ : o.op === "rename" ? t.planRename(folderPath(o.folder), o.name)
3169
+ : o.op === "move" ? t.planMove(o.cards.length, planFolder(o.folder))
3170
+ : t.planMerge(folderPath(o.from), folderPath(o.into));
3171
+ }
3172
+ function drawPlan() {
3173
+ const t = T();
3174
+ $("plan-body").innerHTML = planOps().length ? planOps().map((o) => `<div class="plan-op" data-op="${esc(o.id)}">
3175
+ <input type="checkbox" id="po-${esc(o.id)}" checked aria-labelledby="pol-${esc(o.id)}">
3176
+ <label id="pol-${esc(o.id)}" for="po-${esc(o.id)}"><b>${esc(planLine(o))}</b></label>
3177
+ ${o.reason ? `<span class="why">${esc(o.reason)}</span>` : ""}
3178
+ ${o.op === "move" ? `<details><summary>${esc(t.planMove(o.cards.length, planFolder(o.folder)))}</summary><ul>${o.cards.map((c) => `<li>${esc(c.name)}</li>`).join("")}</ul></details>` : ""}
3179
+ </div>`).join("") : `<p class="hint">${esc(t.planNone)}</p>`;
3180
+ syncPlan();
3181
+ }
3182
+ /** An operation that points at a folder the plan creates goes with it: untick the create and those untick (and stay locked). */
3183
+ function syncPlan() {
3184
+ const on = (id) => $(`po-${id}`)?.checked;
3185
+ const refOn = (ref) => { const c = planOps().find((o) => o.op === "create" && o.ref === ref); return c ? on(c.id) && refOn(planNeeds(c).replace(/^new:/, "")) : true; };
3186
+ for (const o of planOps()) {
3187
+ const need = planNeeds(o), ok = !need.startsWith("new:") || refOn(need.slice(4));
3188
+ const box = $(`po-${o.id}`);
3189
+ if (!ok) box.checked = false;
3190
+ box.disabled = !ok;
3191
+ box.closest(".plan-op").classList.toggle("off", !box.checked);
3192
+ box.title = ok ? "" : T().planNeeds;
3193
+ }
3194
+ const n = planOps().filter((o) => on(o.id)).length;
3195
+ $("pl-apply").textContent = T().planApply(n);
3196
+ $("pl-apply").disabled = !n;
3197
+ }
3198
+ $("plan-body").addEventListener("change", syncPlan);
3199
+ async function openPlan() {
3200
+ const t = T();
3201
+ if (!summaries) return toast(t.planNoModel);
3202
+ plan = null;
3203
+ $("pl-title").textContent = t.planTitle;
3204
+ $("pl-intro").textContent = t.planIntro;
3205
+ $("pl-cancel").textContent = t.cancel;
3206
+ $("pl-apply").textContent = t.planApply(0);
3207
+ $("pl-apply").disabled = true;
3208
+ $("plan-body").innerHTML = `<p class="hint" role="status">${esc(t.planThinking)}</p>`;
3209
+ $("plan-dlg").showModal();
3210
+ const r = await mapWrite("/api/folders/suggest", "POST");
3211
+ if (!r) return $("plan-dlg").close();
3212
+ plan = r;
3213
+ drawPlan();
3214
+ }
3215
+ $("pl-cancel").onclick = () => $("plan-dlg").close();
3216
+ $("plan-dlg").addEventListener("click", (e) => { if (e.target === $("plan-dlg")) $("plan-dlg").close(); });
3217
+ $("pl-apply").onclick = async () => {
3218
+ const accept = planOps().filter((o) => $(`po-${o.id}`)?.checked).map((o) => o.id);
3219
+ if (!accept.length) return;
3220
+ $("pl-apply").disabled = true;
3221
+ const r = await mapWrite("/api/folders/suggest/apply", "POST", { plan: plan.plan, accept });
3222
+ if (!r) { $("pl-apply").disabled = false; return; }
3223
+ $("plan-dlg").close();
3224
+ await load();
3225
+ toast(T().planApplied(r.count), async () => {
3226
+ if (await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo })) await load();
3227
+ });
3228
+ };
3229
+
2308
3230
  /** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
2309
3231
  let lastUndo = null;
2310
3232
  function toast(text, undo) {
@@ -2337,18 +3259,27 @@
2337
3259
  if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? "")) return;
2338
3260
  const k = e.key, prev = lastKey;
2339
3261
  lastKey = k;
3262
+ if (k === "Escape" && selected.size) { clearSelection(); return; }
3263
+ if ((k === "Escape" || k === "Backspace") && mapShown() && mapFocus && !picked && !document.body.classList.contains("menu-open")) { e.preventDefault(); mapUp(); return; }
2340
3264
  if (k === "/") { e.preventDefault(); $("q").focus(); return; }
2341
3265
  if ((k === "z" || k === "u") && lastUndo) { e.preventDefault(); $("toast-undo").click(); return; }
2342
- if (k === "?") { toast(T().shortcuts); return; }
2343
- if (prev === "g" && k === "m") { Object.assign(state, { view: "map", category: "" }); load(); return; }
2344
- if (prev === "g" && k === "a") { Object.assign(state, { view: "all", category: "" }); load(); return; }
3266
+ if (k === "?") { openKeys(); return; }
3267
+ // Inbox: 1–3 pick the focused card's suggestion chips (before the global "file into top-9 folders").
3268
+ if (state.view === "inbox" && /^[1-3]$/.test(k) && role === "admin" && focusedId() && !selected.size) {
3269
+ const chip = document.querySelectorAll(`#item-${focusedId()} [data-chip]`)[Number(k) - 1];
3270
+ if (chip) { e.preventDefault(); inboxFile(focusedId(), chip.dataset.chip); return; }
3271
+ }
3272
+ if (/^[1-9]$/.test(k) && role === "admin" && !document.activeElement?.isContentEditable && quickMove(Number(k))) { e.preventDefault(); return; }
3273
+ if (k === "x" && role === "admin" && !document.activeElement?.isContentEditable && focusedId() && state.view !== "map") { e.preventDefault(); toggleSelect(focusedId()); return; }
3274
+ const chord = commands.find((c) => c.keys?.length === 2 && c.keys[0] === prev && c.keys[1] === k);
3275
+ if (chord) { chord.run(); return; }
2345
3276
  const cards = [...$("list").querySelectorAll(".swipe .card")];
2346
3277
  if (!cards.length) return;
2347
3278
  const cur = document.activeElement?.closest?.(".card");
2348
3279
  const at = cards.indexOf(cur);
2349
- if (k === "j" || k === "k") {
3280
+ if (k === "j" || k === "k" || (k === "s" && state.view === "inbox")) {
2350
3281
  e.preventDefault();
2351
- const next = cards[Math.min(cards.length - 1, Math.max(0, at + (k === "j" ? 1 : -1)))] ?? cards[0];
3282
+ const next = cards[Math.min(cards.length - 1, Math.max(0, at + (k === "k" ? -1 : 1)))] ?? cards[0];
2352
3283
  next.focus(); next.scrollIntoView({ block: "nearest" });
2353
3284
  return;
2354
3285
  }
@@ -2368,8 +3299,22 @@
2368
3299
  load();
2369
3300
  };
2370
3301
  let timer;
3302
+ if (location.hash.startsWith("#focus=")) { mapFocus = focusFromHash(); state.view = "map"; }
2371
3303
  $("q").oninput = (e) => { clearTimeout(timer); timer = setTimeout(() => { state.q = e.target.value.trim(); render(); }, 200); };
2372
- load();
3304
+ // A scanned pairing link (#pair=<code>): take the code out of the address bar at once, swap it for this device's token.
3305
+ async function claimPairing() {
3306
+ const m = /^#pair=([\w-]{16,128})$/.exec(location.hash);
3307
+ if (!m) return;
3308
+ history.replaceState(null, "", location.pathname + location.search);
3309
+ const res = await fetch("/api/pair/claim", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: m[1] }) }).catch(() => null);
3310
+ if (!res?.ok) { toast(T().st.pairFailed); return; }
3311
+ const dev = await res.json();
3312
+ // A write token works like the password everywhere the page uses it, a read token like the share key.
3313
+ store.set(dev.scope === "write" ? "driftnet-token" : "driftnet-key", dev.token);
3314
+ store.set(dev.scope === "write" ? "driftnet-key" : "driftnet-token", "");
3315
+ toast(T().st.pairOk);
3316
+ }
3317
+ claimPairing().finally(load);
2373
3318
  </script>
2374
3319
  </body>
2375
3320
  </html>