driftnet 0.4.1 → 0.6.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
@@ -11,6 +11,7 @@
11
11
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
12
12
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
13
13
  <link rel="manifest" href="/manifest.webmanifest">
14
+ <link rel="alternate" type="application/atom+xml" title="driftnet" href="/feed.xml">
14
15
  <style>
15
16
  :root {
16
17
  --bg: #f7f7f5; --panel: #ffffff; --text: #1d1d1b; --muted: #6b6b66; --line: #e4e4df;
@@ -151,10 +152,10 @@
151
152
  .bar .spacer { flex: 1; }
152
153
  dialog.wide { width: min(720px, calc(100vw - 32px)); }
153
154
  #nd-body { min-height: 40vh; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 14px; }
154
- body.compact .card ul, body.compact .said, body.compact .card .found { display: none; }
155
+ body.compact .card .demo, body.compact .card .thumb { display: none; }
155
156
  body.compact .card { padding-top: 10px; padding-bottom: 10px; }
156
157
  body.compact .card p { margin: 2px 0; }
157
- body.hide-tags .meta .tags, body.hide-said .said { display: none; }
158
+ body.hide-tags .tags, body.hide-said .said { display: none; }
158
159
  .set-group { border: 0; padding: 0; margin: 0 0 16px; }
159
160
  .set-group legend { font-weight: 650; font-size: 14px; margin-bottom: 8px; padding: 0; }
160
161
  .set-row { display: grid; gap: 4px; margin-bottom: 10px; font-size: 13px; color: var(--muted); }
@@ -166,7 +167,13 @@
166
167
  /* The mind map: folders branch out to the right; drag cards onto folders. */
167
168
  .map-bar { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
168
169
  .map-bar .btn { min-height: 40px; padding: 6px 12px; display: inline-flex; align-items: center; gap: 6px; }
169
- .map-tip { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
170
+ .map-crumb { display: flex; flex-wrap: wrap; align-items: center; gap: 2px 6px; margin: 8px 0 0; font-size: 14px; }
171
+ .map-crumb button { background: none; border: 0; padding: 6px 4px; min-height: 32px; color: var(--accent, inherit); font: inherit; cursor: pointer; text-decoration: underline; }
172
+ .map-crumb [aria-current] { font-weight: 600; padding: 6px 4px; }
173
+ .map-crumb .sep { color: var(--muted); }
174
+ .mnode:focus-visible { outline: 2px solid var(--accent, currentColor); outline-offset: 2px; }
175
+ .map-tip { display: flex; gap: 16px; align-items: flex-start; justify-content: space-between; }
176
+ .map-tip > button { flex: none; }
170
177
  .map-wrap { position: relative; overflow: auto; height: 70vh; min-height: 320px; border: 1px solid var(--line);
171
178
  border-radius: 16px; background: var(--panel); box-shadow: var(--shadow); touch-action: pan-x pan-y pinch-zoom; overscroll-behavior: contain;
172
179
  background-image: radial-gradient(color-mix(in srgb, var(--muted) 18%, transparent) 1px, transparent 1px); background-size: 22px 22px; }
@@ -256,12 +263,27 @@
256
263
  .mnode .opt { position: relative; }
257
264
  .mnode .opt::before { content: ""; position: absolute; inset: -9px; }
258
265
  body.map-view main { padding-bottom: 0; }
266
+ /* Split view (wide screens): cards on the left, the mind map on the right. */
267
+ nav .split-btn { display: none; }
268
+ @media (min-width: 1200px) { nav .split-btn { display: flex; } }
269
+ body.split-view .layout { max-width: none; }
270
+ .split { display: grid; grid-template-columns: minmax(340px, 5fr) minmax(0, 7fr); gap: 16px; align-items: start; }
271
+ .split-list { overflow: auto; padding-right: 6px; min-width: 0; }
272
+ .split-map { min-width: 0; }
273
+ /* Command palette (⌘K / Ctrl+K). */
274
+ dialog.cmd { width: min(560px, calc(100vw - 24px)); padding: 0; margin: 12vh auto auto; }
275
+ 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; }
276
+ #cmd-list { max-height: min(52vh, 420px); overflow: auto; padding: 6px; }
277
+ .cmd-h { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); padding: 8px 10px 4px; }
278
+ .cmd-o { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
279
+ .cmd-o[aria-selected="true"] { background: var(--accent-soft); }
280
+ .cmd-o .sub { color: var(--muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
281
+ .cmd-o .lab { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
282
+ .cmd-o .lab::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--c, transparent); margin-right: 8px; }
283
+ .cmd-empty { padding: 14px 12px; color: var(--muted); }
284
+ @media (max-width: 720px) { #palette-btn { display: none; } }
259
285
  .map-wrap { user-select: none; -webkit-user-select: none; }
260
286
  .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); }
261
- .peek h3 { margin: 0 0 8px; font-size: 18px; }
262
- .peek ul { color: var(--muted); padding-left: 20px; }
263
- .peek-actions { flex-wrap: wrap; }
264
- .peek-actions .btn { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
265
287
  .tabs { display: flex; gap: 4px; padding: 3px; background: var(--bg); border-radius: 12px; margin-bottom: 14px; position: sticky; top: 0; z-index: 1; }
266
288
  .tabs button { flex: 1; border: 0; background: none; border-radius: 9px; padding: 8px 6px; min-height: 40px; cursor: pointer; color: var(--muted); font-weight: 600; }
267
289
  .tabs button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
@@ -275,7 +297,6 @@
275
297
  .meta .link-btn { min-height: 32px; }
276
298
  .tags { white-space: normal; } .tags .tag { white-space: nowrap; }
277
299
  .btn:disabled, .btn[disabled] { opacity: .45; cursor: not-allowed; filter: grayscale(.4); }
278
- @media (max-width: 720px) { .peek-actions { display: grid; grid-template-columns: 1fr 1fr; } .peek-actions .spacer { display: none; } }
279
300
  .set-row .envname { font-family: ui-monospace, Menlo, monospace; font-size: 11px; opacity: .6; }
280
301
  dialog::backdrop { backdrop-filter: blur(3px); }
281
302
  .act span { display: inline-flex; align-items: center; gap: 6px; }
@@ -285,6 +306,8 @@
285
306
  .empty.first { display: grid; gap: 14px; justify-items: center; }
286
307
  .empty.first .add { display: flex; gap: 8px; width: min(520px, 100%); }
287
308
  .empty.first .add input { flex: 1; min-width: 0; font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); color: var(--text); }
309
+ .empty.first .tpl { display: grid; gap: 6px; justify-items: center; margin-top: 8px; }
310
+ .empty.first .tpl-row { display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; }
288
311
  .empty.first .btn { display: inline-flex; align-items: center; gap: 6px; }
289
312
  @media (pointer: coarse) {
290
313
  .mnode .opt { padding: 10px; margin: -6px -12px -6px 0; }
@@ -302,11 +325,14 @@
302
325
  .meter[data-s="strong"] i { width: 100%; background: var(--ok); }
303
326
  .tok { justify-content: space-between; padding: 4px 0; border-bottom: 1px solid var(--line); }
304
327
  .tok.revoked { opacity: .55; }
328
+ .pair-out { display: grid; gap: 8px; justify-items: start; }
329
+ .pair-qr svg { display: block; max-width: 100%; height: auto; border-radius: 8px; }
330
+ .pair-time { margin: 0; font-variant-numeric: tabular-nums; }
305
331
  .tok-name { display: grid; gap: 2px; min-width: 0; justify-items: start; }
306
332
  .tok .btn { flex: none; }
307
333
  /* The create-token row: the name takes the room, the scope and button only what they need (the set-row rules below would stretch them). */
308
- .set-row .keyrow input, #at-name { flex: 1 1 120px; width: auto; min-width: 0; }
309
- .set-row .keyrow select, #at-scope { min-height: 38px; flex: 0 0 auto; width: auto; }
334
+ .set-row .keyrow input, #at-name, #pr-name, #pair-link { flex: 1 1 120px; width: auto; min-width: 0; }
335
+ .set-row .keyrow select, #at-scope, #pr-scope { min-height: 38px; flex: 0 0 auto; width: auto; }
310
336
  .warn { background: var(--star-soft); color: var(--text); border-radius: 8px; padding: 8px 10px; font-size: 13px; margin: 4px 0 10px; }
311
337
  .warn.danger { background: var(--danger-soft); }
312
338
  .conn { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; margin-bottom: 12px; }
@@ -357,6 +383,21 @@
357
383
  a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; }
358
384
  a.name:hover { color: var(--accent); }
359
385
  .badge { font-size: 12px; padding: 1px 9px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
386
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 2px; }
387
+ .chip { font: inherit; font-size: 13px; display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; border-radius: 999px; cursor: pointer;
388
+ border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--line)); background: var(--accent-soft); color: var(--text); }
389
+ .chip:hover, .chip:focus-visible { border-color: var(--accent); }
390
+ .chip.more { background: transparent; border-style: dashed; color: var(--muted); border-color: var(--line); }
391
+ .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); }
392
+ body.readonly .chips { display: none; }
393
+ .plan-op { display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; padding: 10px 0; border-top: 1px solid var(--line); }
394
+ .plan-op:first-child { border-top: 0; }
395
+ .plan-op input { margin-top: 3px; }
396
+ .plan-op .why { grid-column: 2; color: var(--muted); font-size: 13px; }
397
+ .plan-op details { grid-column: 2; font-size: 13px; color: var(--muted); }
398
+ .plan-op details ul { margin: 4px 0 0; padding-left: 18px; }
399
+ .plan-op.off { opacity: .5; }
400
+ #plan-body { max-height: 55vh; overflow: auto; }
360
401
  .badge.folder { background: color-mix(in srgb, var(--c) 14%, var(--panel)); color: var(--c); font-weight: 600; }
361
402
  .rating { font-size: 12px; color: var(--muted); white-space: nowrap; }
362
403
  .rating.must { color: var(--star); font-weight: 600; }
@@ -379,6 +420,8 @@
379
420
  display: grid; place-items: center; color: var(--muted); }
380
421
  .tool:hover, .tool:focus-visible { background: var(--bg); color: var(--text); }
381
422
  .tool.on { color: var(--star); }
423
+ .tool.spin .ico, .btn.spin .ico { animation: spin .9s linear infinite; }
424
+ @keyframes spin { to { transform: rotate(360deg); } }
382
425
  .empty { color: var(--muted); padding: 48px 0; text-align: center; }
383
426
 
384
427
  .toast { position: fixed; left: 50%; bottom: max(20px, calc(env(safe-area-inset-bottom) + 12px)); transform: translate(-50%, 140%);
@@ -431,6 +474,69 @@
431
474
  .tools { position: static; justify-content: flex-end; margin: 4px -6px -8px 0; }
432
475
  .card ul { padding-left: 18px; }
433
476
  }
477
+ /* Card list: a thumbnail, the name, the one-liner and what you would see. Everything else lives in the modal. */
478
+ .card { cursor: pointer; }
479
+ .crow { display: flex; gap: 14px; align-items: flex-start; }
480
+ .cbody { flex: 1; min-width: 0; }
481
+ .thumb { position: relative; flex: 0 0 132px; height: 88px; border-radius: 10px; overflow: hidden; background: var(--bg); border: 1px solid var(--line); }
482
+ .thumb .more-pics { position: absolute; right: 6px; bottom: 6px; padding: 1px 7px; border-radius: 999px; background: rgb(0 0 0 / .62); color: #fff; font-size: 12px; font-weight: 600; }
483
+ .thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
484
+ .thumb .play, .g-slide .play { position: absolute; inset: 0; margin: auto; width: 34px; height: 34px; border-radius: 50%; display: grid; place-items: center;
485
+ background: rgba(0,0,0,.6); color: #fff; font-size: 14px; pointer-events: none; }
486
+ .card p.demo { color: var(--muted); font-size: 14px; margin: 2px 0 4px; }
487
+ .meta .has-note { display: inline-flex; color: var(--accent); }
488
+ .meta .has-note .ico { width: 14px; height: 14px; }
489
+ /* The detail modal: gallery, the story, the actions. A full-screen sheet on a phone. */
490
+ dialog.mdl { padding: 0; width: min(760px, calc(100vw - 32px)); max-height: min(92vh, 900px); overflow: hidden; }
491
+ dialog.mdl[open] { display: flex; flex-direction: column; }
492
+ .md-top { display: flex; align-items: center; gap: 4px; padding: 8px 10px 4px 16px; touch-action: none; flex: none; }
493
+ .md-handle { display: none; }
494
+ .md-top .md-pos { color: var(--muted); font-size: 13px; margin-right: auto; }
495
+ .md-top .tool { width: 40px; height: 40px; font-size: 22px; }
496
+ .md-top .tool .ico { width: 20px; height: 20px; }
497
+ .md-top .prev .ico { transform: rotate(180deg); }
498
+ .md-scroll { overflow: auto; padding: 0 18px 12px; flex: 1; min-height: 0; overscroll-behavior: contain; }
499
+ .md-scroll h3 { margin: 12px 0 6px; font-size: 21px; letter-spacing: -.01em; }
500
+ .md-scroll h3 a { color: var(--text); text-decoration: none; }
501
+ .md-scroll h3 a:hover { color: var(--accent); }
502
+ .md-sub { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; margin: 0 0 10px; color: var(--muted); font-size: 13px; }
503
+ .md-one { margin: 0 0 6px; font-size: 16px; }
504
+ .md-sec { margin: 14px 0; }
505
+ .md-sec h4 { margin: 0 0 4px; font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); }
506
+ .md-sec p { margin: 4px 0; font-size: 15px; }
507
+ .md-sec ul { margin: 4px 0; padding-left: 20px; color: var(--muted); font-size: 14px; line-height: 1.65; }
508
+ .md-sec.demo p { font-size: 16px; }
509
+ .md-try { position: relative; }
510
+ .md-try pre { margin: 0; padding: 10px 70px 10px 12px; background: var(--bg); border: 1px solid var(--line); border-radius: 10px; overflow: auto; font-size: 13px; user-select: text; -webkit-user-select: text; }
511
+ .md-try button { position: absolute; top: 6px; right: 6px; }
512
+ .md-tags { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 13px; color: var(--muted); }
513
+ .md-fine { color: var(--muted); font-size: 12px; display: flex; flex-wrap: wrap; gap: 4px 12px; margin-top: 12px; }
514
+ .md-actions { flex: none; margin: 0; padding: 10px 18px calc(10px + env(safe-area-inset-bottom)); border-top: 1px solid var(--line); background: var(--panel); flex-wrap: wrap; }
515
+ .md-actions .spacer { flex: 1; }
516
+ .md-actions .btn { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
517
+ .md-actions .btn.on { border-color: var(--star); color: var(--star); }
518
+ .gallery { margin: 4px 0 0; }
519
+ .g-track { display: flex; overflow-x: auto; scroll-snap-type: x mandatory; scrollbar-width: none; border-radius: 12px; background: var(--bg); border: 1px solid var(--line); overscroll-behavior-x: contain; }
520
+ .g-track::-webkit-scrollbar { display: none; }
521
+ .g-slide { position: relative; flex: 0 0 100%; scroll-snap-align: center; aspect-ratio: 16 / 9; max-height: min(34vh, 340px); display: grid; place-items: center; }
522
+ .g-slide a { display: block; width: 100%; height: 100%; }
523
+ .g-slide img { width: 100%; height: 100%; object-fit: contain; display: block; }
524
+ .g-slide .play { width: 56px; height: 56px; font-size: 22px; }
525
+ .g-thumbs { display: flex; gap: 6px; margin-top: 8px; overflow-x: auto; padding-bottom: 2px; }
526
+ .g-th { flex: 0 0 72px; height: 48px; padding: 0; border-radius: 8px; overflow: hidden; border: 2px solid transparent; background: var(--bg); cursor: pointer; opacity: .7; }
527
+ .g-th.on { border-color: var(--accent); opacity: 1; }
528
+ .g-th img { width: 100%; height: 100%; object-fit: cover; display: block; }
529
+ @media (max-width: 720px) {
530
+ .thumb { flex-basis: 96px; height: 72px; }
531
+ .crow { gap: 10px; }
532
+ dialog.mdl { width: 100vw; max-width: 100vw; height: 100dvh; max-height: 100dvh; margin: 0; border: 0; border-radius: 0; transition: transform .2s ease; }
533
+ .md-handle { display: block; position: absolute; left: 50%; top: 6px; width: 40px; height: 4px; margin-left: -20px; border-radius: 4px; background: var(--line); }
534
+ .md-top { padding-top: 14px; }
535
+ .md-actions { display: grid; grid-template-columns: 1fr 1fr; }
536
+ .md-actions .spacer { display: none; }
537
+ .g-slide { max-height: 36vh; }
538
+ }
539
+ @media (prefers-reduced-motion: reduce) { dialog.mdl { transition: none; } }
434
540
  @media (prefers-reduced-motion: reduce) { .card, .swipe, .toast, nav, .scrim, nav .twist, .mnode, .mnode .tw, .tool { transition: none !important; } }
435
541
  </style>
436
542
  </head>
@@ -450,6 +556,7 @@
450
556
  <symbol id="i-download" viewBox="0 0 24 24"><path d="M12 3.5v11.5M7 10.5l5 5 5-5M4.5 20.5h15"/></symbol>
451
557
  <symbol id="i-lock" viewBox="0 0 24 24"><rect x="4.5" y="10.5" width="15" height="10" rx="2"/><path d="M8 10.5V7.5a4 4 0 0 1 8 0v3"/></symbol>
452
558
  <symbol id="i-logout" viewBox="0 0 24 24"><path d="M9.5 20.5H6a2 2 0 0 1-2-2v-13a2 2 0 0 1 2-2h3.5M15.5 16.5 20 12l-4.5-4.5M20 12H9.5"/></symbol>
559
+ <symbol id="i-refresh" viewBox="0 0 24 24"><path d="M20 11a8 8 0 0 0-14.5-4M4 4v4h4M4 13a8 8 0 0 0 14.5 4M20 20v-4h-4"/></symbol>
453
560
  <symbol id="i-undo" viewBox="0 0 24 24"><path d="M9 14 4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/></symbol>
454
561
  <symbol id="i-chat" viewBox="0 0 24 24"><path d="M20.5 11.5a8 8 0 0 1-11.7 7.1L4 20l1.4-4.6A8 8 0 1 1 20.5 11.5z"/></symbol>
455
562
  <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
@@ -462,6 +569,9 @@
462
569
  <symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></symbol>
463
570
  <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>
464
571
  <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>
572
+ <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>
573
+ <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>
574
+ <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>
465
575
  <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>
466
576
  </defs>
467
577
  </svg>
@@ -474,6 +584,7 @@
474
584
  <span class="stats" id="stats"></span>
475
585
  <input id="q" class="search" type="search" enterkeyhint="search">
476
586
  <button id="lock" class="lock" type="button" hidden></button>
587
+ <button id="palette-btn" class="lang" type="button" aria-haspopup="dialog"></button>
477
588
  <button id="lang" class="lang" type="button"></button>
478
589
  </header>
479
590
  <button id="crumb" class="crumb" type="button" aria-controls="nav"></button>
@@ -491,6 +602,7 @@
491
602
  <label><span id="fd-parent-l"></span><select id="fd-parent"></select></label>
492
603
  <div class="dlg-actions">
493
604
  <button class="btn danger" id="fd-delete" type="button"></button><span class="spacer"></span>
605
+ <button class="btn" id="fd-focus" type="button" hidden></button>
494
606
  <button class="btn" id="fd-cancel" type="button"></button><button class="btn primary" id="fd-save" type="submit"></button>
495
607
  </div>
496
608
  </form>
@@ -510,14 +622,14 @@
510
622
  <button class="btn" id="st-cancel" type="button"></button><button class="btn primary" id="st-save" type="submit"></button></div>
511
623
  </form>
512
624
  </dialog>
513
- <dialog id="peek-dlg" class="peek">
514
- <div id="pk-body"></div>
515
- <div class="dlg-actions peek-actions">
516
- <a class="btn primary" id="pk-open" target="_blank" rel="noopener noreferrer"></a>
517
- <button class="btn" type="button" id="pk-move"></button>
518
- <button class="btn" type="button" id="pk-list"></button>
519
- <span class="spacer"></span><button class="btn" type="button" id="pk-close"></button>
520
- </div>
625
+ <dialog id="item-dlg" class="mdl" aria-labelledby="md-title">
626
+ <div class="md-top" id="md-grab"><span class="md-handle" aria-hidden="true"></span>
627
+ <span class="md-pos" id="md-pos" aria-live="polite"></span>
628
+ <button class="tool prev" type="button" data-md="prev" id="md-prev"></button>
629
+ <button class="tool next" type="button" data-md="next" id="md-next"></button>
630
+ <button class="tool" type="button" data-md="close" id="md-close">×</button></div>
631
+ <div class="md-scroll" id="md-scroll"></div>
632
+ <div class="dlg-actions md-actions" id="md-actions"></div>
521
633
  </dialog>
522
634
  <dialog id="login-dlg" aria-labelledby="lg-title">
523
635
  <form id="login-form" method="dialog">
@@ -556,11 +668,21 @@
556
668
  </dialog>
557
669
  <div class="pickbar" id="pickbar" role="status" hidden><span id="pick-text"></span><button type="button" id="pick-cancel"></button></div>
558
670
  <div class="selbar" id="selbar" role="toolbar" hidden></div>
671
+ <dialog id="cmd-dlg" class="cmd">
672
+ <input id="cmd-input" type="text" role="combobox" aria-expanded="true" aria-controls="cmd-list" aria-autocomplete="list" autocomplete="off" spellcheck="false">
673
+ <div id="cmd-list" role="listbox"></div>
674
+ </dialog>
559
675
  <dialog id="keys-dlg" aria-labelledby="ky-title">
560
676
  <h3 id="ky-title"></h3>
561
677
  <dl class="keys" id="ky-body"></dl>
562
678
  <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="ky-close" type="button"></button></div>
563
679
  </dialog>
680
+ <dialog id="plan-dlg" class="wide" aria-labelledby="pl-title">
681
+ <h3 id="pl-title"></h3>
682
+ <p class="hint" id="pl-intro"></p>
683
+ <div id="plan-body"></div>
684
+ <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>
685
+ </dialog>
564
686
  <div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
565
687
  <script>
566
688
  const STRINGS = {
@@ -584,14 +706,19 @@
584
706
  folders: "Folders", newFolder: "New folder", newSub: "New folder inside", editFolder: "Edit folder", folderName: "Name",
585
707
  folderDesc: "What goes here? (driftnet's AI reads this to sort new links)", folderParent: "Inside", topLevel: "— Top level —",
586
708
  save: "Save", cancel: "Cancel", del: "Delete folder", delSure: "Delete? Links move up",
709
+ refresh: "Refresh (fetch and summarise again)", refreshed: (n) => `Refreshed “${n}”`, refreshBusy: "Already refreshing this one.", refreshWait: "Refreshed a moment ago — try again in a minute.", refreshFailed: (why) => `Couldn’t refresh${why ? `: ${why}` : ""}`,
587
710
  moveTo: "Move to…", moveTitle: (n) => `Move “${n}” to`, moved: (n, f) => `Moved “${n}” to ${f}`, expand: "Show sub-folders",
588
711
  dragHint: "Drag onto a folder in the sidebar", foundIn: "Found in this post:", folderMoved: (n, f) => `“${n}” is now inside ${f}`,
589
712
  topLevelShort: "the top level",
713
+ mapAll: "All", focusCrumb: "Mind map location", focusUp: "Up one level", focusFolder: "Focus on this folder", mapTree: "Mind map",
714
+ mapHintFocus: "Double-click a folder (or press z on it) to focus on it.",
715
+ 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",
716
+ kFocus: "Focus on the folder (mind map)", kFocusUp: "Back up one level (mind map)", keysMap: "Mind map",
590
717
  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.",
591
718
  a11yFolder: (n, c) => `Folder ${n}, ${c} cards`, a11yCard: (n) => `Card ${n}`,
592
719
  expandAll: "Expand all", collapseAll: "Collapse all", zoomIn: "Zoom in", zoomOut: "Zoom out", fit: "Fit", openCard: "Open card",
593
720
  layoutBoth: "Both sides", layoutRight: "Right side", layoutHelp: "Switch between branches on both sides (XMind) and all to the right",
594
- zoom: "Zoom", gotIt: "Got it", more: (n) => `+${n} more`, mapSearch: (q) => `Highlighting “${q}”`, openLink: "Open link", showInList: "Show in the list", close: "Close",
721
+ zoom: "Zoom", gotIt: "Got it", more: (n) => `+${n} more`, mapSearch: (q) => `Highlighting “${q}”`, openLink: "Open link", mdDemo: "What you'll see", mdWhy: "Why it's here", mdHighlights: "Highlights", mdUse: "Good for", mdTry: "Try it", mdCopy: "Copy", mdCopied: "Copied", mdPrev: "Previous card", mdNext: "Next card", mdPos: (n, m) => `${n} of ${m}`, mdSlide: (n, m) => `Picture ${n} of ${m}`, mdPlay: "Play the video", mdPictures: "Pictures", mdTags: "Tags", mdHasNote: "Has your note", showInList: "Show in the list", close: "Close",
595
722
  needPassword: "Changing things needs the admin password.",
596
723
  notes: "Notes", note: "Note", addNote: "Add a note", editNote: "Edit note", noteFor: (n) => `Note on “${n}”`,
597
724
  noteHelp: "Only for you: what you thought, whether you tried it…", newNote: "New note", noteTitle: "Title",
@@ -599,12 +726,23 @@
599
726
  emptyNotes: "No notes yet. Notes can link cards: write #12.", exportMd: "Download a backup (Markdown)", exportVault: "Download for Obsidian / Notion",
600
727
  saved: "Saved", settings: "Settings", pickedUp: (n) => `Picked up “${n}” — tap the folder it goes into`, alreadyThere: "It's already in that folder",
601
728
  readOnlyNudge: "You can only look here — tap Unlock at the top to change things", filterFolders: "Type to find a folder…", undoHint: "z undoes",
729
+ tplTitle: "Start with folders for:", tplAi: "AI & coding", tplResearch: "Research", tplEveryday: "Everyday", tplSkip: "Keep the default", tplFailed: "Can't change the folders now: you already have cards or changed them.",
602
730
  addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
603
731
  shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
604
732
  keysTitle: "Keyboard shortcuts", keysMove: "Move, favorite, trash", keysSelect: "Select several cards", keysGo: "Go to", keysQuick: "File into your most-used folders",
605
733
  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",
734
+ 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",
735
+ split: "Split", splitHelp: "Cards and mind map side by side", splitCards: "Cards",
606
736
  kSelect: "Select or unselect the card", kRange: "Select a range", kHold: "Hold", kLong: "Start selecting on a phone", keysClose: "Close", kClear: "Clear the selection", kUndo: "Undo the last action", kHelp: "This list",
607
737
  kQuickNone: "Move a card into a folder first; the nine you use most get a number here.", kQuickN: (f) => `Move into ${f}`,
738
+ 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.",
739
+ chipOther: "Other folder…", chipTitle: (p) => `Confidence ${p}%`,
740
+ 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.",
741
+ planBtn: "Suggest folders", planNoModel: "Needs an AI model (Settings → AI)", planTitle: "Suggested folder changes",
742
+ 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.",
743
+ planThinking: "Asking the model…", planNone: "The model found nothing worth changing.", planApply: (n) => `Apply ${n} selected`,
744
+ planCreate: (p) => `Create “${p}”`, planRename: (a, b) => `Rename “${a}” to “${b}”`, planMove: (n, d) => `Move ${n} ${n === 1 ? "card" : "cards"} to “${d}”`,
745
+ planMerge: (a, b) => `Merge “${a}” into “${b}”`, planApplied: (n) => `Applied ${n} ${n === 1 ? "change" : "changes"} to your folders`, planNeeds: "Needs the folder it creates",
608
746
  nSelected: (n) => `${n} selected`, selectAll: "Select all", clearSel: "Clear", trashShort: "Trash",
609
747
  moveTitleMany: (n) => `Move ${n} cards to`, pickedMany: (n) => `Picked up ${n} cards — tap the folder they go into`,
610
748
  bulkMoved: (n, f) => `Moved ${n} cards to ${f}`, bulkRemoved: (n) => `${n} cards moved to the trash`, bulkRestored: (n) => `${n} cards restored`,
@@ -618,7 +756,7 @@
618
756
  plugins: "Plugins", pluginsNone: (dir) => `No plugins. Put .js files in ${dir} — see examples/plugins in the repo.`,
619
757
  status: (e) => `Now: sorting by ${({ jev: "Jev", llm: "the model", heuristic: "built-in rules" })[e.judge] ?? e.judge}, summaries: ${e.summarizer === "off" ? "off" : e.summarizer}`, keep: "set — leave empty to keep", unset: "not set",
620
758
  locked: "set by the environment driftnet runs in", forbidden: "Server settings can only be changed on the computer running driftnet (or set DRIFTNET_TOKEN). Display settings still work.",
621
- savedServer: "Saved — already in effect", chat: "Chat replies", genCopied: "New password generated and copied — press Save to keep it",
759
+ savedServer: "Saved — already in effect", chat: "Chat replies", webhook: "Outgoing webhook", feed: "Feed (RSS)", genCopied: "New password generated and copied — press Save to keep it",
622
760
  tabGeneral: "General", tabAccess: "Access", tabAi: "AI",
623
761
  accessStatus: (pw, key, url) => `Password: ${pw === "✓" ? "set" : "not set"} · Share key: ${key === "✓" ? "made" : "none"} · Public URL: ${url === "—" ? "off" : url}`,
624
762
  access: "Access & connections",
@@ -637,6 +775,11 @@
637
775
  tokCardName: "Token name", tokCardCreate: "Create a token for this agent",
638
776
  tokCardDone: "Token “{name}” created and filled in above. Copy it now: it will not be shown again. Revoke it in Settings → Access when you no longer need it.",
639
777
  tokNameNeeded: "Give the token a name.", tokPasswordOnly: "Set an admin password first: tokens are what you give agents instead of it.",
778
+ 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.",
779
+ pairName: "Device name", pairCreate: "Show QR code", pairExpires: "Expires in {t}", pairExpired: "This code has expired. Make a new one.",
780
+ pairLink: "Or open this link on the phone", pairDone: "“{name}” is paired.", pairNameNeeded: "Name the device first.",
781
+ pairLocal: "This address only works on this computer. A phone needs a public URL (below) or this computer's network address.",
782
+ 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.",
640
783
  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.",
641
784
  tunnelOn: "Open a public URL", tunnelOff: "Close it", tunnelNeedsPassword: "Save an admin password first.",
642
785
  tunnelInstall: "Needs cloudflared (driftnet never downloads it for you):", tunnelPrivate: "Opening it switches reading to “only with the password or the share key”.",
@@ -660,15 +803,21 @@
660
803
  DRIFTNET_LOCALE: ["Bot language", ""],
661
804
  DRIFTNET_REPLY: ["How the bot replies", ""],
662
805
  DRIFTNET_PUBLIC_URL: ["This page's public URL", "Replies link here, e.g. https://driftnet.example.com"],
806
+ DRIFTNET_SUMMARY_DEPTH: ["Summary detail", "How much each card says. Detailed costs more model tokens and reads twice as much of each page."],
663
807
  DRIFTNET_SUMMARY_RULES: ["Extra rules for summaries", "e.g. Say whether it's free. Mention if it needs a GPU."],
664
808
  DRIFTNET_BLOCK_DOMAINS: ["Never catalogue these domains", "Comma or space separated, e.g. example.com, spam.io"],
809
+ DRIFTNET_WEBHOOK_URL: ["Webhook URL", "driftnet POSTs each new or updated card here (n8n, Zapier, Slack workflows…). Treated as a secret."],
810
+ DRIFTNET_WEBHOOK_SECRET: ["Webhook signing secret", "Optional. Adds X-Driftnet-Signature: sha256=<HMAC of the body>."],
811
+ DRIFTNET_WEBHOOK_ALLOW_LOCAL: ["Allow a local webhook", "Needed when the receiver is on your own network (n8n on a LAN). Only that exact address is allowed."],
665
812
  },
666
813
  choices: {
667
814
  DRIFTNET_LLM_PROVIDER: { "": "None", anthropic: "Anthropic (API key)", openai: "OpenAI-compatible (OpenAI, Gemini, Grok, Ollama…)", "claude-cli": "Claude subscription (Claude Code CLI)", "gemini-cli": "Google account (Gemini CLI)" },
668
815
  DRIFTNET_LLM_EFFORT: { "": "Default", low: "Low", medium: "Medium", high: "High" },
669
816
  DRIFTNET_JUDGE: { "": "On when a key is set", off: "Off" },
817
+ DRIFTNET_SUMMARY_DEPTH: { "": "Standard (default)", brief: "Brief: one line, 2 highlights, what you see", standard: "Standard", detailed: "Detailed: more highlights, use cases, how to try it" },
670
818
  DRIFTNET_LOCALE: { "": "Same as the summaries", en: "English", "zh-TW": "繁體中文" },
671
819
  DRIFTNET_REPLY: { "": "One line + link (default)", link: "One line + link", full: "Full summary", off: "Don't reply" },
820
+ DRIFTNET_WEBHOOK_ALLOW_LOCAL: { "": "No (public addresses only)", 1: "Yes" },
672
821
  },
673
822
  },
674
823
  },
@@ -691,14 +840,19 @@
691
840
  folders: "資料夾", newFolder: "新資料夾", newSub: "在裡面新增資料夾", editFolder: "編輯資料夾", folderName: "名稱",
692
841
  folderDesc: "放什麼?(driftnet 的 AI 會照這段說明把新連結分進來)", folderParent: "放在", topLevel: "— 最上層 —",
693
842
  save: "儲存", cancel: "取消", del: "刪除資料夾", delSure: "確定刪除?內容移到上一層",
843
+ refresh: "重新整理(再抓一次並重新摘要)", refreshed: (n) => `已重新整理「${n}」`, refreshBusy: "這張卡片正在重新整理。", refreshWait: "剛剛才整理過,請一分鐘後再試。", refreshFailed: (why) => `重新整理失敗${why ? `:${why}` : ""}`,
694
844
  moveTo: "移動到…", moveTitle: (n) => `把「${n}」移動到`, moved: (n, f) => `已將「${n}」移到 ${f}`, expand: "展開子資料夾",
695
845
  dragHint: "拖到側邊欄的資料夾", foundIn: "從這篇找到:", folderMoved: (n, f) => `「${n}」已移到 ${f} 底下`,
696
846
  topLevelShort: "最上層",
847
+ mapAll: "全部", focusCrumb: "樹狀圖位置", focusUp: "回上一層", focusFolder: "聚焦這個資料夾", mapTree: "樹狀圖",
848
+ mapHintFocus: "連點兩下資料夾(或在資料夾上按 z)可以只看這個資料夾。",
849
+ kTreeNav: "樹狀圖:下一個/上一個節點", kTreeOpen: "展開資料夾,或進入第一個子項", kTreeClose: "收合資料夾,或回到上一層", kTreeEnds: "第一個/最後一個節點", kTreeType: "直接輸入名稱", kTreeTypeText: "跳到名稱開頭相符的節點",
850
+ kFocus: "聚焦這個資料夾(樹狀圖)", kFocusUp: "回上一層(樹狀圖)", keysMap: "樹狀圖",
697
851
  map: "樹狀圖", mapHint: "點資料夾展開,點卡片預覽。整理卡片:把它拖到資料夾上;手機上按住卡片一下、放開,再點要放進去的資料夾。按 ⋯ 可以改資料夾名稱。",
698
852
  a11yFolder: (n, c) => `資料夾 ${n},${c} 張卡片`, a11yCard: (n) => `卡片 ${n}`,
699
853
  expandAll: "全部展開", collapseAll: "全部收合", zoomIn: "放大", zoomOut: "縮小", fit: "符合畫面", openCard: "開啟卡片",
700
854
  layoutBoth: "兩側展開", layoutRight: "往右展開", layoutHelp: "切換:分支分佈在兩側(XMind 預設)或全部往右",
701
- zoom: "縮放", gotIt: "知道了", more: (n) => `還有 ${n} 張`, mapSearch: (q) => `標亮「${q}」`, openLink: "開啟連結", showInList: "在清單中查看", close: "關閉",
855
+ zoom: "縮放", gotIt: "知道了", more: (n) => `還有 ${n} 張`, mapSearch: (q) => `標亮「${q}」`, openLink: "開啟連結", mdDemo: "你會看到什麼", mdWhy: "為什麼收進來", mdHighlights: "重點", mdUse: "適合用在", mdTry: "試試看", mdCopy: "複製", mdCopied: "已複製", mdPrev: "上一張卡片", mdNext: "下一張卡片", mdPos: (n, m) => `第 ${n} / ${m} 張`, mdSlide: (n, m) => `第 ${n} 張圖,共 ${m} 張`, mdPlay: "播放影片", mdPictures: "圖片", mdTags: "標籤", mdHasNote: "有你的筆記", showInList: "在清單中查看", close: "關閉",
702
856
  needPassword: "要修改需要管理密碼。",
703
857
  notes: "筆記", note: "筆記", addNote: "加筆記", editNote: "改筆記", noteFor: (n) => `「${n}」的筆記`,
704
858
  noteHelp: "只有你看得到:心得、試用結果、要注意的地方…", newNote: "新筆記", noteTitle: "標題",
@@ -706,12 +860,23 @@
706
860
  emptyNotes: "還沒有筆記。筆記可以連到卡片:寫 #12。", exportMd: "下載備份(Markdown)", exportVault: "下載給 Obsidian/Notion",
707
861
  saved: "已儲存", settings: "設定", pickedUp: (n) => `已拿起「${n}」,點要放進去的資料夾`, alreadyThere: "它已經在這個資料夾裡了",
708
862
  readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
863
+ tplTitle: "從這些資料夾開始:", tplAi: "AI 與程式", tplResearch: "研究", tplEveryday: "日常生活", tplSkip: "維持預設", tplFailed: "現在不能換資料夾了:已經有卡片,或資料夾被你改過。",
709
864
  addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
710
865
  shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
711
866
  keysTitle: "快捷鍵", keysMove: "移動、最愛、垃圾桶", keysSelect: "一次選多張卡片", keysGo: "切換畫面", keysQuick: "放進最常用的資料夾",
712
867
  kNext: "下一張/上一張", kFav: "最愛", kMove: "移動到…", kNote: "筆記", kTrash: "垃圾桶(在垃圾桶裡是還原)", kSearch: "搜尋", kMap: "樹狀圖", kAll: "全部卡片",
868
+ palette: "命令面板", palPlaceholder: "跳到資料夾、找卡片,或執行指令…", palGroups: { folders: "資料夾", cards: "卡片", commands: "指令" }, palNone: "沒有符合的項目", kPalette: "命令面板",
869
+ split: "並排", splitHelp: "卡片列表與樹狀圖並排顯示", splitCards: "卡片",
713
870
  kSelect: "選取/取消選取這張", kRange: "選取一段範圍", kHold: "長按", kLong: "在手機上開始選取卡片", keysClose: "關閉", kClear: "取消全部選取", kUndo: "復原上一個動作", kHelp: "顯示這份清單",
714
871
  kQuickNone: "先把卡片移進某個資料夾;最常用的九個資料夾會在這裡得到數字鍵。", kQuickN: (f) => `移到 ${f}`,
872
+ inbox: "收件匣", emptyInbox: "收件匣清空了——每張卡片都有你選的資料夾。", hintInbox: "點一下資料夾就能歸檔。下面是還沒歸檔的卡片。",
873
+ chipOther: "其他資料夾…", chipTitle: (p) => `信心 ${p}%`,
874
+ keysInbox: "在收件匣", kChip: "歸到這張卡片建議的第 1–3 個資料夾", kSkip: "略過:移到下一張卡片", kQuickInbox: "在收件匣裡,1–3 改成選擇目前卡片的建議資料夾;4–9 仍然是放進最常用的資料夾。",
875
+ planBtn: "建議整理資料夾", planNoModel: "需要先設定 AI 模型(設定 → AI)", planTitle: "建議的資料夾調整",
876
+ planIntro: "AI 只負責提議。勾選想要的項目再套用,套用前什麼都不會改;復原可以一次還原整份方案。你親手歸檔的卡片不會被移動。",
877
+ planThinking: "正在請模型想想…", planNone: "模型認為目前沒有值得調整的地方。", planApply: (n) => `套用選取的 ${n} 項`,
878
+ planCreate: (p) => `新增「${p}」`, planRename: (a, b) => `把「${a}」改名為「${b}」`, planMove: (n, d) => `把 ${n} 張卡片移到「${d}」`,
879
+ planMerge: (a, b) => `把「${a}」合併到「${b}」`, planApplied: (n) => `已套用 ${n} 項資料夾調整`, planNeeds: "需要它新增的資料夾",
715
880
  nSelected: (n) => `已選 ${n} 張`, selectAll: "全選", clearSel: "清除", trashShort: "垃圾桶",
716
881
  moveTitleMany: (n) => `把 ${n} 張卡片移動到`, pickedMany: (n) => `已拿起 ${n} 張卡片,點要放進去的資料夾`,
717
882
  bulkMoved: (n, f) => `已將 ${n} 張卡片移到 ${f}`, bulkRemoved: (n) => `已將 ${n} 張卡片移到垃圾桶`, bulkRestored: (n) => `已還原 ${n} 張卡片`,
@@ -725,7 +890,7 @@
725
890
  plugins: "外掛", pluginsNone: (dir) => `沒有外掛。把 .js 檔放進 ${dir},範例在 repo 的 examples/plugins。`,
726
891
  status: (e) => `目前:分類用 ${({ jev: "Jev", llm: "模型", heuristic: "內建規則" })[e.judge] ?? e.judge},摘要用 ${e.summarizer === "off" ? "(未開啟)" : e.summarizer}`, keep: "已設定,留空就不變", unset: "未設定",
727
892
  locked: "由執行環境設定", forbidden: "伺服器設定只能在執行 driftnet 的那台電腦上改(或設定 DRIFTNET_TOKEN)。顯示設定照常可用。",
728
- savedServer: "已儲存,馬上生效", chat: "聊天室回覆", genCopied: "已產生新密碼並複製,按「儲存」才會生效",
893
+ savedServer: "已儲存,馬上生效", chat: "聊天室回覆", webhook: "對外 Webhook", feed: "訂閱源(RSS)", genCopied: "已產生新密碼並複製,按「儲存」才會生效",
729
894
  tabGeneral: "一般", tabAccess: "存取", tabAi: "AI",
730
895
  accessStatus: (pw, key, url) => `密碼:${pw === "✓" ? "已設定" : "未設定"} · 分享碼:${key === "✓" ? "已產生" : "沒有"} · 公開網址:${url === "—" ? "關閉" : url}`,
731
896
  access: "存取與連線",
@@ -744,6 +909,11 @@
744
909
  tokCardName: "金鑰名稱", tokCardCreate: "幫這個 agent 建一把專用金鑰",
745
910
  tokCardDone: "已建立「{name}」專用金鑰,已填進上面的設定。請現在複製:之後不會再顯示。不用時到「設定 → 存取」撤銷。",
746
911
  tokNameNeeded: "請幫金鑰取個名字。", tokPasswordOnly: "請先設定管理密碼:金鑰就是用來取代它交給 agent 的。",
912
+ pairTitle: "用 QR code 解鎖手機", pairHelp: "用手機相機掃描這個圖形碼:會直接開啟已解鎖的 driftnet,並取得專屬、可隨時撤銷的金鑰。圖形碼只能用一次,5 分鐘內有效。",
913
+ pairName: "裝置名稱", pairCreate: "顯示 QR code", pairExpires: "剩餘 {t}", pairExpired: "這個圖形碼已過期,請重新產生。",
914
+ pairLink: "或在手機上開啟這個連結", pairDone: "「{name}」已配對完成。", pairNameNeeded: "請先為裝置命名。",
915
+ pairLocal: "這個位址只有這台電腦連得到。手機需要公開網址(見下方)或這台電腦的區域網路位址。",
916
+ pairOk: "這台裝置已解鎖。", pairFailed: "配對碼無法使用,可能已過期或已被使用,請在電腦上重新產生。",
747
917
  tunnel: "給雲端 AI 的公開網址", tunnelHelp: "Claude 網頁版、ChatGPT、Grok 和其他機器上的 agent 連不到 localhost。這會透過 Cloudflare(免帳號)開一個臨時的 https 網址;每次都不一樣,driftnet 關掉就跟著關。",
748
918
  tunnelOn: "開啟公開網址", tunnelOff: "關閉", tunnelNeedsPassword: "要先儲存管理密碼。",
749
919
  tunnelInstall: "需要 cloudflared(driftnet 不會自動幫你下載):", tunnelPrivate: "開啟後,「誰可以讀」會改成要有密碼或分享碼。",
@@ -767,25 +937,43 @@
767
937
  DRIFTNET_LOCALE: ["機器人語言", ""],
768
938
  DRIFTNET_REPLY: ["機器人怎麼回覆", ""],
769
939
  DRIFTNET_PUBLIC_URL: ["這個網頁的公開網址", "回覆裡的連結會指到這裡,例如 https://driftnet.example.com"],
940
+ DRIFTNET_SUMMARY_DEPTH: ["摘要詳細程度", "每張卡片寫多少。詳細會用較多模型 token,且每個頁面讀兩倍的內容。"],
770
941
  DRIFTNET_SUMMARY_RULES: ["摘要的額外規則", "例如:說明是否免費。需要 GPU 的話要提到。"],
771
942
  DRIFTNET_BLOCK_DOMAINS: ["不要收錄的網域", "用逗號或空白分隔,例如 example.com, spam.io"],
943
+ DRIFTNET_WEBHOOK_URL: ["Webhook 網址", "每張新增或更新的卡片都會 POST 到這裡(n8n、Zapier、Slack 工作流程…)。視為機密。"],
944
+ DRIFTNET_WEBHOOK_SECRET: ["Webhook 簽章密鑰", "選填。會加上 X-Driftnet-Signature: sha256=<內容的 HMAC>。"],
945
+ DRIFTNET_WEBHOOK_ALLOW_LOCAL: ["允許本機 Webhook", "接收端在你自己的區域網路時需要(例如內網的 n8n)。只放行你填的那個位址。"],
772
946
  },
773
947
  choices: {
774
948
  DRIFTNET_LLM_PROVIDER: { "": "不使用", anthropic: "Anthropic(API 金鑰)", openai: "OpenAI 相容(OpenAI、Gemini、Grok、Ollama…)", "claude-cli": "Claude 訂閱(Claude Code CLI)", "gemini-cli": "Google 帳號(Gemini CLI)" },
775
949
  DRIFTNET_LLM_EFFORT: { "": "預設", low: "低", medium: "中", high: "高" },
776
950
  DRIFTNET_JUDGE: { "": "有金鑰就開", off: "關閉" },
951
+ DRIFTNET_SUMMARY_DEPTH: { "": "標準(預設)", brief: "簡短:一句話、2 個重點、看得到什麼", standard: "標準", detailed: "詳細:更多重點、使用情境、怎麼試用" },
777
952
  DRIFTNET_LOCALE: { "": "跟摘要一樣", en: "English", "zh-TW": "繁體中文" },
778
953
  DRIFTNET_REPLY: { "": "一行+連結(預設)", link: "一行+連結", full: "完整摘要", off: "不回覆" },
954
+ DRIFTNET_WEBHOOK_ALLOW_LOCAL: { "": "否(只允許公開位址)", 1: "是" },
779
955
  },
780
956
  },
781
957
  },
782
958
  };
783
959
  const state = { view: "all", category: "", kind: "", q: "" };
784
- const $ = (id) => document.getElementById(id);
960
+ /** While a pane renders (split view), $("list") means that pane, so the list and map renderers can share the page unchanged. */
961
+ let paneFor = null, paneLock = Promise.resolve();
962
+ const $ = (id) => (paneFor && id === "list" ? paneFor : document.getElementById(id));
963
+ function inPane(pane, fn) {
964
+ const go = async () => { paneFor = pane; try { return await fn(); } finally { paneFor = null; } };
965
+ return (paneLock = paneLock.catch(() => {}).then(go));
966
+ }
785
967
  const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
786
968
  const safeUrl = (u) => (/^https?:\/\//.test(u) ? u : "#");
787
969
  const store = { get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
788
970
  set: (k, v) => { try { localStorage.setItem(k, v); } catch {} } };
971
+ const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
972
+ /** Split view: the saved choice; it only shows on wide screens, and only beside the card views. */
973
+ let split = store.get("driftnet-split") === "1";
974
+ const wideQuery = matchMedia("(min-width: 1200px)");
975
+ const splitOn = () => split && wideQuery.matches && (state.view === "all" || state.view === "favorites");
976
+ const mapShown = () => state.view === "map" || splitOn();
789
977
 
790
978
  let locale = "en";
791
979
  let catLabels = {};
@@ -875,6 +1063,8 @@
875
1063
  $("q").placeholder = T().search;
876
1064
  $("q").setAttribute("aria-label", T().search);
877
1065
  $("lang").textContent = T().switchTo;
1066
+ $("palette-btn").textContent = isMac ? "⌘K" : "Ctrl K";
1067
+ $("palette-btn").title = $("palette-btn").ariaLabel = T().palette;
878
1068
  $("nav").setAttribute("aria-label", T().nav);
879
1069
  $("menu").setAttribute("aria-label", T().menu);
880
1070
  }
@@ -902,7 +1092,7 @@
902
1092
  /** One line under the header saying what is shown, so a closed drawer hides nothing. */
903
1093
  function updateCrumb() {
904
1094
  const t = T();
905
- const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash
1095
+ const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash : state.view === "inbox" ? t.inbox
906
1096
  : state.view === "notes" ? t.notes : state.view === "map" ? t.map : t.all];
907
1097
  if (state.category) parts.push(catLabel(state.category));
908
1098
  if (state.kind) parts.push(t.kinds[state.kind] ?? state.kind);
@@ -940,11 +1130,14 @@
940
1130
  `<div class="drawer-head"><span class="brand"><img src="/favicon.svg" alt="" width="24" height="24">driftnet</span>` +
941
1131
  `<button type="button" class="menu" id="menu-close" aria-label="${esc(T().close)}">✕</button></div>` +
942
1132
  `<div class="row">` +
1133
+ (role === "admin" || stats.inbox ? btn("view", "inbox", T().inbox, stats.inbox || "", "inbox") : "") +
943
1134
  btn("view", "all", T().all, stats.items, "all") + btn("view", "favorites", T().favorites, stats.favorites, "star") +
944
1135
  btn("view", "map", T().map, "", "map") +
1136
+ `<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>` +
945
1137
  btn("view", "notes", T().notes, stats.notes || "", "note") +
946
1138
  btn("view", "trash", T().trash, stats.trash || "", "trash") +
947
1139
  `</div><div class="folders-head" data-drop-root><h2>${esc(T().folders)}</h2>` +
1140
+ (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>` : "") +
948
1141
  `<button type="button" class="icon" data-new="" title="${esc(T().newFolder)}" aria-label="${esc(T().newFolder)}">${ic("plus")}</button></div>` +
949
1142
  `<div class="tree" role="list">${folderRows(null, 0)}</div><h2>${esc(T().kind)}</h2><div class="row kinds">` + btn("kind", "", T().any, "") +
950
1143
  Object.entries(T().kinds).map(([k, v]) => btn("kind", k, v, "")).join("") + `</div>` +
@@ -972,7 +1165,15 @@
972
1165
  if (b.dataset.login !== undefined) { if (isDrawer()) setMenu(false); return openLogin(); }
973
1166
  if (b.dataset.logout !== undefined) { store.set("driftnet-token", ""); return load(); }
974
1167
  if (b.dataset.new !== undefined) return openFolderDialog(null, b.dataset.new || null);
1168
+ if (b.dataset.split !== undefined) {
1169
+ split = !split;
1170
+ store.set("driftnet-split", split ? "1" : "0");
1171
+ if (state.view !== "all" && state.view !== "favorites") state.view = "all";
1172
+ return load();
1173
+ }
1174
+ if (b.dataset.suggest !== undefined) { if (isDrawer()) setMenu(false); return openPlan(); }
975
1175
  const { field, value } = b.dataset;
1176
+ if (field === "view" && value === "map" && split) { split = false; store.set("driftnet-split", "0"); }
976
1177
  // Choosing a category stays inside the current view; choosing a view clears the category.
977
1178
  if (field === "view") state.category = "";
978
1179
  // The map has its own folders: picking one in the sidebar shows its cards.
@@ -1028,12 +1229,16 @@
1028
1229
  del.hidden = !id || id === "other";
1029
1230
  del.textContent = t.del;
1030
1231
  del.classList.remove("armed");
1232
+ const fb = $("fd-focus");
1233
+ fb.hidden = !id || state.view !== "map" || id === mapFocus;
1234
+ fb.textContent = t.focusFolder;
1031
1235
  $("fd-cancel").textContent = t.cancel;
1032
1236
  $("fd-save").textContent = t.save;
1033
1237
  $("fd-error").textContent = "";
1034
1238
  $("folder-dlg").showModal();
1035
1239
  $("fd-name").focus();
1036
1240
  }
1241
+ $("fd-focus").onclick = () => { $("folder-dlg").close(); setMapFocus(editing); };
1037
1242
  $("fd-cancel").onclick = () => $("folder-dlg").close();
1038
1243
  // Delete asks twice inside the dialog (no browser confirm box).
1039
1244
  $("fd-delete").onclick = async () => {
@@ -1100,6 +1305,39 @@
1100
1305
  $("mv-title").textContent = T().moveTitleMany(ids.length);
1101
1306
  showMovePicker(null);
1102
1307
  }
1308
+ // <fuzzy>
1309
+ /**
1310
+ * Rank entries against a query (empty query = all, in order). Tiers: exact, prefix, word start, substring, letters in order
1311
+ * (3+ characters, first field only); text in later fields counts a bit less. Only matches come back, best first.
1312
+ */
1313
+ function fuzzyRank(query, entries, fields) {
1314
+ const q = query.trim().toLowerCase();
1315
+ if (!q) return [...entries];
1316
+ const inOrder = (f) => { let at = 0; for (const ch of f) if (ch === q[at] && ++at === q.length) return true; return false; };
1317
+ const scored = [];
1318
+ entries.forEach((e, at) => {
1319
+ let best = null;
1320
+ fields(e).forEach((raw, i) => {
1321
+ const f = String(raw ?? "").toLowerCase();
1322
+ if (!f) return;
1323
+ let tier = null;
1324
+ if (f === q) tier = -1;
1325
+ else if (f.startsWith(q)) tier = 0;
1326
+ else if (f.split(/[\s\-_/›.,:]+/).some((w) => w.startsWith(q))) tier = 1;
1327
+ else if (f.includes(q)) tier = 2;
1328
+ else if (i === 0 && q.length >= 3 && inOrder(f)) tier = 4;
1329
+ if (tier === null) return;
1330
+ const score = tier + (i > 0 ? 3 : 0);
1331
+ if (best === null || score < best) best = score;
1332
+ });
1333
+ if (best !== null) scored.push({ e, best, at });
1334
+ });
1335
+ return scored.sort((a, b) => a.best - b.best || a.at - b.at).map((x) => x.e);
1336
+ }
1337
+ // </fuzzy>
1338
+ /** What the folder pickers search: its name, full path, description and id. */
1339
+ const folderFields = (id) => [catLabel(id), folderPath(id), folderById(id)?.description, id];
1340
+ let moveBest = null;
1103
1341
  function showMovePicker(current) {
1104
1342
  const t = T();
1105
1343
  const quick = quickFolders();
@@ -1108,6 +1346,7 @@
1108
1346
  $("mv-list").innerHTML = rows(null, 0);
1109
1347
  $("mv-cancel").textContent = t.cancel;
1110
1348
  $("mv-filter").value = "";
1349
+ moveBest = null;
1111
1350
  $("mv-filter").placeholder = t.filterFolders;
1112
1351
  $("mv-filter").setAttribute("aria-label", t.filterFolders);
1113
1352
  $("move-dlg").showModal();
@@ -1116,16 +1355,15 @@
1116
1355
  }
1117
1356
  $("mv-cancel").onclick = () => $("move-dlg").close();
1118
1357
  $("mv-filter").addEventListener("input", () => {
1119
- const q = $("mv-filter").value.trim().toLowerCase();
1120
1358
  const rows = [...$("mv-list").querySelectorAll("[data-to]")];
1121
- // Match what the reader sees; the hidden id (e.g. "coding-agent") only when no visible name matches.
1122
- const byName = rows.filter((b) => b.firstElementChild.textContent.toLowerCase().includes(q));
1123
- const shown = new Set(q ? (byName.length ? byName : rows.filter((b) => b.dataset.to.includes(q))) : rows);
1359
+ const hit = fuzzyRank($("mv-filter").value, rows, (b) => folderFields(b.dataset.to));
1360
+ const shown = new Set(hit);
1124
1361
  for (const b of rows) b.hidden = !shown.has(b);
1362
+ moveBest = $("mv-filter").value.trim() ? hit[0] ?? null : null; // Enter files into the best match
1125
1363
  });
1126
1364
  $("mv-filter").addEventListener("keydown", (e) => {
1127
1365
  const visible = [...$("mv-list").querySelectorAll("[data-to]:not([hidden])")];
1128
- if (e.key === "Enter") { e.preventDefault(); visible[0]?.click(); }
1366
+ if (e.key === "Enter") { e.preventDefault(); (moveBest ?? visible[0])?.click(); }
1129
1367
  else if (e.key === "ArrowDown") { e.preventDefault(); visible[0]?.focus(); }
1130
1368
  });
1131
1369
  $("mv-list").addEventListener("keydown", (e) => {
@@ -1143,6 +1381,7 @@
1143
1381
  if (!b) return;
1144
1382
  $("move-dlg").close();
1145
1383
  if (movingMany) bulkApply("move", movingMany, b.dataset.to);
1384
+ else if (state.view === "inbox") inboxFile(moving, b.dataset.to);
1146
1385
  else moveItem(moving, b.dataset.to);
1147
1386
  };
1148
1387
 
@@ -1160,7 +1399,7 @@
1160
1399
  const old = folderById(from); if (old) old.count--;
1161
1400
  const el = document.getElementById(`item-${id}`);
1162
1401
  // Still inside the folder being viewed? Update the badge; otherwise it leaves the list.
1163
- const visible = !state.category || subtreeOf(state.category).has(to);
1402
+ const visible = state.view !== "inbox" && (!state.category || subtreeOf(state.category).has(to));
1164
1403
  if (el && !visible) {
1165
1404
  if (el.contains(document.activeElement)) (el.nextElementSibling ?? el.previousElementSibling)?.querySelector?.(".card")?.focus();
1166
1405
  dismiss(el);
@@ -1170,7 +1409,7 @@
1170
1409
  // The list and the map hold their own copies of the item: keep both in step.
1171
1410
  const onMap = mapItems.find((x) => x.id === id);
1172
1411
  if (onMap && onMap !== item) onMap.category = to;
1173
- if (state.view === "map") drawMap();
1412
+ if (mapShown()) drawMap();
1174
1413
  bumpUse(to);
1175
1414
  if (!quiet) { toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); render(); }); }
1176
1415
  }
@@ -1279,8 +1518,8 @@
1279
1518
  const yes = (b) => (b ? "✓" : "—");
1280
1519
  const accessStatus = `<p class="set-status">${esc(st.accessStatus(yes(a.passwordSet), yes(a.readKey), a.tunnel.running ? a.tunnel.url : "—"))}</p>`;
1281
1520
  server = {
1282
- general: group("language") + group("chat"),
1283
- access: accessStatus + accessPanel(serverSettings, field) + (agentTokens ? tokensPanel(serverSettings.access, agentTokens, minted) : ""),
1521
+ general: group("language") + group("chat") + group("webhook"),
1522
+ access: accessStatus + accessPanel(serverSettings, field) + (agentTokens ? tokensPanel(serverSettings.access, agentTokens, minted) + pairPanel(serverSettings.access) : ""),
1284
1523
  ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + group("model") + group("rules") +
1285
1524
  `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
1286
1525
  };
@@ -1386,6 +1625,56 @@
1386
1625
  <small>${esc(st.agentTokensHelp)}</small>${box}
1387
1626
  <div class="set-row">${rows}</div><div class="set-row">${form}</div></fieldset>`;
1388
1627
  }
1628
+ function pairPanel(a) {
1629
+ const st = T().st;
1630
+ if (!a.passwordSet) return "";
1631
+ return `<fieldset class="set-group" id="pair-panel"><legend>${esc(st.pairTitle)}</legend>
1632
+ <small>${esc(st.pairHelp)}</small>
1633
+ <div class="keyrow"><input id="pr-name" maxlength="56" placeholder="${esc(st.pairName)}" autocomplete="off" aria-label="${esc(st.pairName)}">
1634
+ <select id="pr-scope" aria-label="${esc(st.tokScope)}">${["write", "read"].map((c) => `<option value="${c}">${esc(st.tokScopes[c])}</option>`).join("")}</select>
1635
+ <button class="btn primary" type="button" id="pr-create">${esc(st.pairCreate)}</button></div>
1636
+ <div id="pair-out" class="pair-out" aria-live="polite"></div></fieldset>`;
1637
+ }
1638
+ let pairTimer = null;
1639
+ /** Show the QR for a fresh code, count down, and notice when the phone has claimed it. */
1640
+ async function showPairing(made, name) {
1641
+ const st = T().st;
1642
+ clearInterval(pairTimer);
1643
+ const base = (serverSettings?.access?.publicUrl || location.origin).replace(/\/$/, "");
1644
+ const link = `${base}/#pair=${made.code}`;
1645
+ const { qrSvg } = await import("/qr.js");
1646
+ const out = $("pair-out");
1647
+ out.innerHTML = `<div class="pair-qr">${qrSvg(link, { scale: 6 })}</div>
1648
+ <p class="pair-time" id="pair-time"></p>
1649
+ ${/\/\/(localhost|127\.0\.0\.1|\[::1\])/.test(base) ? `<small class="dlg-error">${esc(st.pairLocal)}</small>` : ""}
1650
+ <small>${esc(st.pairLink)}</small>
1651
+ <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>`;
1652
+ const known = new Set(knownTokens.map((k) => k.id));
1653
+ const until = Date.parse(made.expiresAt);
1654
+ let polling = false;
1655
+ pairTimer = setInterval(async () => {
1656
+ if (!document.body.contains(out)) return clearInterval(pairTimer);
1657
+ const left = Math.max(0, Math.round((until - Date.now()) / 1000));
1658
+ if (!left) {
1659
+ clearInterval(pairTimer);
1660
+ out.innerHTML = `<small>${esc(st.pairExpired)}</small>`;
1661
+ return;
1662
+ }
1663
+ $("pair-time").textContent = st.pairExpires.replace("{t}", `${Math.floor(left / 60)}:${String(left % 60).padStart(2, "0")}`);
1664
+ if (polling || left % 3) return;
1665
+ polling = true;
1666
+ const token = store.get("driftnet-token");
1667
+ const res = await fetch("/api/agent-tokens", { headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
1668
+ const list = res?.ok ? await res.json() : [];
1669
+ polling = false;
1670
+ if (list.some((k) => !known.has(k.id) && !k.revokedAt && k.name === `📱 ${name}`)) {
1671
+ clearInterval(pairTimer);
1672
+ toast(st.pairDone.replace("{name}", name));
1673
+ openSettings();
1674
+ }
1675
+ }, 1000);
1676
+ $("pair-time").textContent = st.pairExpires.replace("{t}", "5:00");
1677
+ }
1389
1678
  async function adminFetch(path, method, body) {
1390
1679
  const token = store.get("driftnet-token");
1391
1680
  const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
@@ -1397,6 +1686,7 @@
1397
1686
  // Enter in the token name creates the token; it must not submit the whole settings form.
1398
1687
  $("st-body").addEventListener("keydown", (e) => {
1399
1688
  if (e.target.id === "at-name" && e.key === "Enter") { e.preventDefault(); $("at-create").click(); }
1689
+ if (e.target.id === "pr-name" && e.key === "Enter") { e.preventDefault(); $("pr-create").click(); }
1400
1690
  });
1401
1691
  $("st-body").addEventListener("input", (e) => {
1402
1692
  if (e.target.id !== "ac-pw") return;
@@ -1434,6 +1724,12 @@
1434
1724
  const duplicate = nameTaken(knownTokens, name);
1435
1725
  const made = await adminFetch("/api/agent-tokens", "POST", { name, scope: $("at-scope").value });
1436
1726
  if (made) { justMinted = { ...made, duplicate }; openSettings(); }
1727
+ } else if (b.id === "pr-create") {
1728
+ const name = $("pr-name").value.trim();
1729
+ if (!name) { $("st-error").textContent = st.pairNameNeeded; return; }
1730
+ $("st-error").textContent = "";
1731
+ const made = await adminFetch("/api/pair", "POST", { name, scope: $("pr-scope").value });
1732
+ if (made) showPairing(made, name);
1437
1733
  } else if (b.dataset.remove) {
1438
1734
  if (await adminFetch(`/api/agent-tokens/${encodeURIComponent(b.dataset.remove)}?purge=1`, "DELETE")) openSettings();
1439
1735
  } else if (b.dataset.revoke) {
@@ -1506,6 +1802,41 @@
1506
1802
  /** both: branches on both sides of the root (XMind's default); right: all to the right. */
1507
1803
  let mapLayout = store.get("driftnet-map-layout") || "both";
1508
1804
  let mapItems = [];
1805
+ /** The folder the map is focused on (null = the whole map); lives in the URL hash so it survives a reload. */
1806
+ let mapFocus = null;
1807
+ /** Zoom and scroll per focus root, so stepping back up returns to where you were. */
1808
+ const mapViews = new Map();
1809
+ /** Roving tabindex: the one node Tab lands on. */
1810
+ let mapActive = "root";
1811
+ const focusFromHash = () => { const m = /^#focus=(.+)$/.exec(location.hash); try { return m ? decodeURIComponent(m[1]) : null; } catch { return null; } };
1812
+ function syncFocusHash() {
1813
+ const want = mapShown() && mapFocus ? `#focus=${encodeURIComponent(mapFocus)}` : "";
1814
+ if (want === location.hash || (!want && !location.hash.startsWith("#focus="))) return;
1815
+ history.replaceState(null, "", location.pathname + location.search + want);
1816
+ }
1817
+ /** Focus the map on a folder (null = back to everything), remembering where each view was. */
1818
+ async function setMapFocus(id) {
1819
+ id = id && folderById(id) ? id : null;
1820
+ if (id === mapFocus) return;
1821
+ const wrap = $("map-wrap"), prev = mapFocus;
1822
+ mapViews.set(prev ?? "", { zoom: mapZoom, left: wrap?.scrollLeft ?? 0, top: wrap?.scrollTop ?? 0 });
1823
+ mapFocus = id;
1824
+ // Stepping up: make sure the folder we came from is visible so focus can return to it.
1825
+ mapActive = "root";
1826
+ if (prev && (id === null || isUnder(prev, id))) {
1827
+ for (let p = folderById(prev)?.parent; p && p !== id; p = folderById(p)?.parent) mapOpen.add(p);
1828
+ saveMapOpen();
1829
+ mapActive = `f:${prev}`;
1830
+ }
1831
+ const saved = mapViews.get(id ?? "");
1832
+ if (saved) mapZoom = saved.zoom;
1833
+ syncFocusHash();
1834
+ await renderMap();
1835
+ if (saved) { const w = $("map-wrap"); w.scrollLeft = saved.left; w.scrollTop = saved.top; }
1836
+ ($("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(mapActive)}"]`) ?? $("map-canvas")?.querySelector('.mnode[data-key="root"]'))?.focus({ preventScroll: true });
1837
+ }
1838
+ const isUnder = (id, anc) => { for (let p = folderById(id)?.parent; p; p = folderById(p)?.parent) if (p === anc) return true; return false; };
1839
+ const mapUp = () => setMapFocus(folderById(mapFocus)?.parent ?? null);
1509
1840
  /** Cards shown per folder before the rest fold into a "+N" node. */
1510
1841
  const MAP_CAP = 15;
1511
1842
 
@@ -1517,14 +1848,24 @@
1517
1848
  if (err.unauthorized) return askToken();
1518
1849
  throw err;
1519
1850
  }
1851
+ if (mapFocus && !folderById(mapFocus)) mapFocus = null;
1852
+ syncFocusHash();
1853
+ const crumb = mapFocus ? (() => {
1854
+ const chain = [];
1855
+ for (let p = mapFocus; p; p = folderById(p)?.parent) chain.unshift(p);
1856
+ return `<nav class="map-crumb" aria-label="${esc(t.focusCrumb)}"><button type="button" data-map="focus" data-id="">${esc(t.mapAll)}</button>` +
1857
+ chain.map((id, n) => `<span class="sep" aria-hidden="true">›</span>` + (n === chain.length - 1
1858
+ ? `<span aria-current="location">${esc(catLabel(id))}</span>`
1859
+ : `<button type="button" data-map="focus" data-id="${esc(id)}">${esc(catLabel(id))}</button>`)).join("") + `</nav>`;
1860
+ })() : "";
1520
1861
  const allOpen = mapOpen.size > 0 || !!state.q;
1521
- 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>`;
1862
+ const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip"><span>${esc(t.mapHint)} ${esc(t.mapHintFocus)}</span><button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
1522
1863
  $("list").innerHTML = `<div class="map-bar">
1523
1864
  <button class="btn" type="button" data-map="${allOpen ? "collapse" : "expand"}">${ic(allOpen ? "collapse" : "expand")} ${esc(allOpen ? t.collapseAll : t.expandAll)}</button>
1524
1865
  <button class="btn" type="button" data-map="new">${ic("plus")} ${esc(t.newFolder)}</button>
1525
1866
  <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>
1526
1867
  ${state.q ? `<span class="hint">${esc(t.mapSearch(state.q))}</span>` : ""}</div>
1527
- ${tip}
1868
+ ${crumb}${tip}
1528
1869
  <div class="map-shell"><div class="map-wrap" id="map-wrap"><div class="map-canvas" id="map-canvas"></div></div>
1529
1870
  <div class="map-zoom" role="group" aria-label="${esc(t.zoom)}">
1530
1871
  <button type="button" data-map="out" aria-label="${esc(t.zoomOut)}">${ic("minus")}</button>
@@ -1571,7 +1912,7 @@
1571
1912
  const wrap = $("map-wrap");
1572
1913
  if (wrap) wrap.style.height = `${Math.max(320, innerHeight - wrap.getBoundingClientRect().top - 12)}px`;
1573
1914
  }
1574
- addEventListener("resize", () => { if (state.view === "map") sizeMap(); });
1915
+ addEventListener("resize", () => { if (mapShown()) sizeMap(); if (splitOn()) sizeSplit(); });
1575
1916
 
1576
1917
  /** Root → folders → sub-folders and cards, laid out left to right like XMind. */
1577
1918
  function drawMap() {
@@ -1583,38 +1924,55 @@
1583
1924
  for (const i of mapItems) byFolder.set(i.category, [...(byFolder.get(i.category) ?? []), i]);
1584
1925
  const total = (f) => (byFolder.get(f.id)?.length ?? 0) + kids(f.id).reduce((n, c) => n + total(c), 0);
1585
1926
  const hits = (f) => (byFolder.get(f.id) ?? []).some(hit) || kids(f.id).some(hits);
1927
+ /** What hangs under folder f: its sub-folders, then its cards (capped), then a "+N" node. */
1928
+ const content = (f, depth, color, colorOf) => {
1929
+ const cards = byFolder.get(f.id) ?? [];
1930
+ const out = kids(f.id).map((c, n) => build(c, depth, colorOf ? colorOf(n) : color));
1931
+ const shown = q ? [...cards.filter(hit), ...cards.filter((i) => !hit(i))] : cards;
1932
+ out.push(...shown.slice(0, MAP_CAP).map((i) => ({ key: `i:${i.id}`, type: "item", id: i.id, depth, color,
1933
+ label: (i.summary?.name ?? i.title).slice(0, 32), worth: i.worth, hit: hit(i), children: [] })));
1934
+ 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: [] });
1935
+ return out;
1936
+ };
1586
1937
  const build = (f, depth, color) => {
1587
1938
  // While searching, folders holding a match open by themselves (not saved).
1588
1939
  const open = mapOpen.has(f.id) || (q && hits(f));
1589
1940
  const cards = byFolder.get(f.id) ?? [];
1590
1941
  const node = { key: `f:${f.id}`, type: "folder", id: f.id, label: catLabel(f.id), count: total(f), depth, color, open, children: [],
1591
1942
  hasKids: kids(f.id).length > 0 || cards.length > 0, hit: q && f.id && catLabel(f.id).toLowerCase().includes(q) };
1592
- if (open) {
1593
- node.children.push(...kids(f.id).map((c) => build(c, depth + 1, color)));
1594
- const shown = q ? [...cards.filter(hit), ...cards.filter((i) => !hit(i))] : cards;
1595
- node.children.push(...shown.slice(0, MAP_CAP).map((i) => ({ key: `i:${i.id}`, type: "item", id: i.id, depth: depth + 1, color,
1596
- label: (i.summary?.name ?? i.title).slice(0, 32), worth: i.worth, hit: hit(i), children: [] })));
1597
- 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: [] });
1598
- }
1943
+ if (open) node.children = content(f, depth + 1, color);
1599
1944
  return node;
1600
1945
  };
1601
- const root = { key: "root", type: "root", label: "driftnet", count: mapItems.length, depth: 0, color: "var(--m1)",
1602
- children: kids(null).map((f, n) => build(f, 1, `var(--m${(n % 8) + 1})`)) };
1946
+ const colorN = (n) => `var(--m${(n % 8) + 1})`;
1947
+ const focusF = mapFocus ? folderById(mapFocus) : null;
1948
+ // Focused: the folder itself is the root, with its own cards beside its sub-folders.
1949
+ const root = focusF
1950
+ ? { key: "root", type: "root", label: catLabel(focusF.id), count: total(focusF), depth: 0, color: "var(--m1)", children: content(focusF, 1, "var(--m1)", colorN) }
1951
+ : { key: "root", type: "root", label: "driftnet", count: mapItems.length, depth: 0, color: "var(--m1)",
1952
+ children: kids(null).map((f, n) => build(f, 1, colorN(n))) };
1603
1953
 
1604
1954
  // Pass 1: create the nodes and measure them.
1605
1955
  const flat = [];
1606
1956
  const walk = (n) => { flat.push(n); n.children.forEach(walk); };
1607
1957
  walk(root);
1608
1958
  canvas.classList.toggle("searching", !!q);
1609
- canvas.innerHTML = `<svg id="map-svg"></svg>` + flat.map((n) => {
1959
+ canvas.setAttribute("role", "tree");
1960
+ canvas.setAttribute("aria-label", T().mapTree);
1961
+ const nodeKeys = new Set(flat.map((n) => n.key));
1962
+ if (!nodeKeys.has(mapActive)) mapActive = "root";
1963
+ // Sibling position for aria-setsize / aria-posinset (nodes are absolutely positioned, so no group wrappers).
1964
+ flat[0].setsize = 1; flat[0].pos = 1;
1965
+ for (const n of flat) n.children.forEach((c, k) => { c.setsize = n.children.length; c.pos = k + 1; });
1966
+ canvas.innerHTML = `<svg id="map-svg" aria-hidden="true"></svg>` + flat.map((n) => {
1610
1967
  const level = n.type === "folder" ? (n.depth === 1 ? "l1" : "l2") : "";
1611
1968
  const tw = n.type === "folder" && n.hasKids ? `<span class="tw ${n.open ? "open" : ""}">${ic("chev")}</span>` : "";
1612
1969
  const cnt = (n.type === "folder" || n.type === "root") && n.count ? `<span class="cnt">${n.count}</span>` : "";
1613
1970
  const star = n.type === "item" && n.worth === "must-see" ? `<span class="w">${ic("star", "filled")}</span>` : "";
1614
1971
  const more = n.type === "folder" ? `<span class="opt" data-edit="${esc(n.id)}" aria-hidden="true" title="${esc(T().editFolder)}">${ic("dots")}</span>` : "";
1615
1972
  const name = n.type === "folder" ? T().a11yFolder(n.label, n.count) : n.type === "item" ? T().a11yCard(n.label) : n.label;
1616
- const aria = ` aria-label="${esc(name)}" aria-level="${n.depth + 1}"` + (n.type === "folder" && n.hasKids ? ` aria-expanded="${!!n.open}"` : "");
1617
- return `<div class="mnode ${n.type} ${level} ${n.type === "folder" && !n.hasKids ? "vacant" : ""} ${n.hit ? "hit" : ""} ${n.type === "item" && selected.has(Number(n.key.slice(2))) ? "sel" : ""}" role="button" tabindex="0"${aria}
1973
+ const aria = ` aria-label="${esc(name)}" aria-level="${n.depth + 1}" aria-setsize="${n.setsize}" aria-posinset="${n.pos}"`
1974
+ + (n.type === "root" ? (n.children.length ? ` aria-expanded="true"` : "") : n.type === "folder" && n.hasKids ? ` aria-expanded="${!!n.open}"` : "");
1975
+ 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}
1618
1976
  data-key="${esc(n.key)}" style="--c:${n.color}">${tw}${star}<span class="t">${esc(n.label)}</span>${cnt}${more}</div>`;
1619
1977
  }).join("");
1620
1978
  const el = new Map([...canvas.querySelectorAll(".mnode")].map((d) => [d.dataset.key, d]));
@@ -1747,12 +2105,13 @@
1747
2105
  else if (a === "in") mapZoomTo(mapZoom + 0.1);
1748
2106
  else if (a === "out") mapZoomTo(mapZoom - 0.1);
1749
2107
  else if (a === "fit") fitMap();
2108
+ else if (a === "focus") setMapFocus(b.dataset.id || null);
1750
2109
  });
1751
2110
  $("list").addEventListener("dblclick", (e) => {
1752
2111
  const node = e.target.closest(".mnode.folder");
1753
2112
  if (!node) return;
1754
2113
  clearTimeout(folderTap);
1755
- openFolderDialog(node.dataset.key.slice(2));
2114
+ setMapFocus(node.dataset.key.slice(2));
1756
2115
  });
1757
2116
 
1758
2117
  /**
@@ -1839,7 +2198,7 @@
1839
2198
  if (!p.drag && e.shiftKey && role === "admin" && p.key.startsWith("i:")) return toggleSelect(Number(p.key.slice(2)));
1840
2199
  if (!p.drag) return tapNode(p.key, !p.touch);
1841
2200
  if (!target) return;
1842
- const to = target.dataset.key === "root" ? null : target.dataset.key.slice(2);
2201
+ const to = target.dataset.key === "root" ? mapFocus : target.dataset.key.slice(2);
1843
2202
  // Dragging one of several selected cards takes them all.
1844
2203
  if (p.key.startsWith("i:") && selected.has(Number(p.key.slice(2))) && selected.size > 1) { if (to) await bulkApply("move", [...selected], to); }
1845
2204
  else if (p.key.startsWith("i:")) await mapMoveItem(Number(p.key.slice(2)), to);
@@ -1853,9 +2212,56 @@
1853
2212
  if (e.key === "Enter" || e.key === " ") { e.preventDefault(); tapNode(node.dataset.key); }
1854
2213
  else if ((e.key === "F2" || e.key === "e") && node.dataset.key.startsWith("f:") && role === "admin") { e.preventDefault(); openFolderDialog(node.dataset.key.slice(2)); }
1855
2214
  else if (e.key === "m" && node.dataset.key.startsWith("i:") && role === "admin") { e.preventDefault(); openMovePicker(Number(node.dataset.key.slice(2))); }
2215
+ else if (e.key === "z" && node.dataset.key.startsWith("f:") && !canUndo()) { e.preventDefault(); setMapFocus(node.dataset.key.slice(2)); }
2216
+ else treeKey(e, node);
1856
2217
  });
1857
2218
  })();
1858
2219
  let folderTap = null;
2220
+ /** WAI-ARIA tree keys on the map: arrows, Home/End, type-ahead. Nodes are in tree (document) order. */
2221
+ let typed = "", typedAt = 0;
2222
+ function treeKey(e, node) {
2223
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
2224
+ const nodes = [...$("map-canvas").querySelectorAll(".mnode")], at = nodes.indexOf(node);
2225
+ const go = (el) => { if (!el) return; el.focus({ preventScroll: true }); el.scrollIntoView({ block: "nearest", inline: "nearest" }); };
2226
+ const level = (n) => Number(n.getAttribute("aria-level"));
2227
+ const key = node.dataset.key, k = e.key;
2228
+ const folderId = key.startsWith("f:") ? key.slice(2) : null;
2229
+ const expanded = node.getAttribute("aria-expanded");
2230
+ if (k === "ArrowDown") go(nodes[Math.min(nodes.length - 1, at + 1)]);
2231
+ else if (k === "ArrowUp") go(nodes[Math.max(0, at - 1)]);
2232
+ else if (k === "Home") go(nodes[0]);
2233
+ else if (k === "End") go(nodes[nodes.length - 1]);
2234
+ else if (k === "ArrowRight") {
2235
+ if (expanded === "false" && folderId) toggleFolder(folderId);
2236
+ else if (expanded === "true" && nodes[at + 1] && level(nodes[at + 1]) === level(node) + 1) go(nodes[at + 1]);
2237
+ } else if (k === "ArrowLeft") {
2238
+ if (expanded === "true" && folderId && mapOpen.has(folderId)) toggleFolder(folderId);
2239
+ else { let p = at - 1; while (p >= 0 && level(nodes[p]) >= level(node)) p--; if (p >= 0) go(nodes[p]); }
2240
+ } else if (k.length === 1 && k !== " " || (k === " " && typed)) {
2241
+ const now = Date.now();
2242
+ const fresh = now - typedAt > 700;
2243
+ // Letters that already do something here (and the global shortcuts) can't start a search.
2244
+ 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"));
2245
+ if (acts) return;
2246
+ typed = (fresh ? "" : typed) + k.toLowerCase(); typedAt = now;
2247
+ const label = (n) => (n.querySelector(".t")?.textContent ?? "").toLowerCase();
2248
+ const order = [...nodes.slice(at + (typed.length > 1 ? 0 : 1)), ...nodes.slice(0, at + (typed.length > 1 ? 0 : 1))];
2249
+ const hit = order.find((n) => label(n).startsWith(typed));
2250
+ e.stopPropagation(); // not the global shortcuts (f, n, x, j, k …)
2251
+ e.preventDefault();
2252
+ go(hit);
2253
+ return;
2254
+ } else return;
2255
+ e.preventDefault();
2256
+ }
2257
+ // Roving tabindex: whichever node has focus is the one Tab lands on next time.
2258
+ $("list").addEventListener("focusin", (e) => {
2259
+ const node = e.target.closest?.(".mnode");
2260
+ if (!node || node.dataset.key === mapActive) return;
2261
+ $("map-canvas").querySelector(`.mnode[tabindex="0"]`)?.setAttribute("tabindex", "-1");
2262
+ node.setAttribute("tabindex", "0");
2263
+ mapActive = node.dataset.key;
2264
+ });
1859
2265
  /**
1860
2266
  * Picking up (touch): hold a card or folder, let go, then tap the folder it goes into.
1861
2267
  * Nothing competes with scrolling, and no precise finger drag is needed.
@@ -1894,12 +2300,12 @@
1894
2300
  if (key.startsWith("f:") || (key === "root" && what.startsWith("f:"))) {
1895
2301
  const ids = what.startsWith("i:") && selected.size > 1 ? [...selected] : null;
1896
2302
  dropPicked();
1897
- const to = key === "root" ? null : key.slice(2);
2303
+ const to = key === "root" ? mapFocus : key.slice(2);
1898
2304
  if (ids) return to ? bulkApply("move", ids, to) : undefined;
1899
2305
  return what.startsWith("i:") ? mapMoveItem(Number(what.slice(2)), to) : mapMoveFolder(what.slice(2), to);
1900
2306
  }
1901
2307
  }
1902
- // A mouse double-click edits the folder, so a single click waits a moment to be sure.
2308
+ // A mouse double-click focuses the folder, so a single click waits a moment to be sure.
1903
2309
  if (key.startsWith("f:") && viaMouse) { clearTimeout(folderTap); folderTap = setTimeout(() => toggleFolder(key.slice(2)), 230); return; }
1904
2310
  if (key.startsWith("f:")) toggleFolder(key.slice(2));
1905
2311
  else if (key.startsWith("i:")) openPeek(Number(key.slice(2)));
@@ -1908,38 +2314,188 @@
1908
2314
  // A long press on a phone must not open the system menu over the map.
1909
2315
  $("list").addEventListener("contextmenu", (e) => { if (e.target.closest(".mnode")) e.preventDefault(); });
1910
2316
 
1911
- /** A card from the map, without leaving the map. */
1912
- let peeking = null;
1913
- function openPeek(id) {
1914
- const i = mapItems.find((x) => x.id === id) ?? find(id);
1915
- if (!i) return;
1916
- peeking = id;
1917
- const t = T(), s = i.summary;
1918
- $("pk-body").innerHTML = `<h3>${esc(s?.name ?? i.title)}</h3>
1919
- <p><span class="badge folder" style="--c:${folderColor(i.category)}">${esc(folderPath(i.category))}</span>
1920
- <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span></p>
1921
- ${s ? `<p>${esc(s.oneLiner)}</p>` : ""}
1922
- ${s?.highlights?.length ? `<ul>${s.highlights.map((h) => `<li>${esc(h)}</li>`).join("")}</ul>` : ""}
1923
- ${i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""}`;
1924
- $("pk-open").href = safeUrl(s?.primaryUrl || i.url);
1925
- $("pk-open").innerHTML = `${ic("link")} ${esc(t.openLink)}`;
1926
- $("pk-move").innerHTML = `${ic("move")} ${esc(t.moveTo)}`;
1927
- $("pk-move").hidden = role !== "admin";
1928
- $("pk-list").innerHTML = `${ic("list")} ${esc(t.showInList)}`;
1929
- $("pk-close").textContent = t.close;
1930
- $("pk-close").hidden = matchMedia("(max-width: 720px)").matches; // tap outside closes it on a phone
1931
- $("peek-dlg").showModal();
1932
- }
1933
- $("pk-close").onclick = () => $("peek-dlg").close();
2317
+ /** A card from the map, without leaving the map: the same modal the list uses. */
2318
+ const openPeek = (id) => openModal(id, "map");
1934
2319
  $("pick-cancel").onclick = () => dropPicked();
1935
- $("peek-dlg").addEventListener("click", (e) => { if (e.target === $("peek-dlg")) $("peek-dlg").close(); });
1936
- $("pk-move").onclick = () => { $("peek-dlg").close(); openMovePicker(peeking); };
1937
- $("pk-list").onclick = () => {
1938
- $("peek-dlg").close();
1939
- Object.assign(state, { view: "all", category: "", kind: "" });
1940
- history.replaceState(null, "", `#item-${peeking}`);
1941
- load();
1942
- };
2320
+
2321
+ // ── The detail modal (one implementation for the list and the map) ───────
2322
+ const mdlDlg = $("item-dlg");
2323
+ let modalId = null, modalFrom = "list", keepHash = false;
2324
+ /** Cards ←/→ step through: what the list shows now (nothing when opened from the map). */
2325
+ const mdIds = () => modalFrom === "list" ? [...$("list").querySelectorAll(".swipe")].map((e) => Number(e.dataset.id)) : [];
2326
+ const mediaOf = (i) => (Array.isArray(i.media) ? i.media : []).filter((m) => m && typeof m.src === "string" && m.src.startsWith("/"));
2327
+ function galleryHtml(i) {
2328
+ const m = mediaOf(i), t = T(), name = i.summary?.name ?? i.title;
2329
+ if (!m.length) return "";
2330
+ const url = safeUrl(i.summary?.primaryUrl || i.url);
2331
+ const img = (x, extra = "") => `<img src="${esc(x.src)}" alt="${esc(extra === "t" ? "" : x.alt || name)}" referrerpolicy="no-referrer" loading="lazy" decoding="async" draggable="false" data-media>`;
2332
+ const slide = (x, n) => `<div class="g-slide" role="group" aria-roledescription="slide" aria-label="${esc(t.mdSlide(n + 1, m.length))}">${
2333
+ x.kind === "video" ? `<a href="${esc(url)}" target="_blank" rel="noopener noreferrer" aria-label="${esc(t.mdPlay)}">${img(x)}<span class="play" aria-hidden="true">▶</span></a>` : img(x)}</div>`;
2334
+ return `<div class="gallery"><div class="g-track" id="g-track" tabindex="0" role="region" aria-label="${esc(t.mdPictures)}">${m.map(slide).join("")}</div>${
2335
+ m.length > 1 ? `<div class="g-thumbs">${m.map((x, n) => `<button type="button" class="g-th ${n ? "" : "on"}" data-g="${n}" aria-label="${esc(t.mdSlide(n + 1, m.length))}">${img(x, "t")}</button>`).join("")}</div>` : ""}</div>`;
2336
+ }
2337
+ function paintModal() {
2338
+ const i = find(modalId);
2339
+ if (!i) return void (mdlDlg.open && mdlDlg.close());
2340
+ const t = T(), s = i.summary, admin = role === "admin", inTrash = state.view === "trash";
2341
+ const url = safeUrl(s?.primaryUrl || i.url), name = s?.name ?? i.title;
2342
+ const ids = mdIds(), at = ids.indexOf(i.id);
2343
+ $("md-pos").textContent = at >= 0 ? t.mdPos(at + 1, ids.length) : "";
2344
+ for (const [id, label, off] of [["md-prev", t.mdPrev, at <= 0], ["md-next", t.mdNext, at < 0 || at >= ids.length - 1]]) {
2345
+ const b = $(id); b.innerHTML = ic("chev"); b.setAttribute("aria-label", label); b.title = label; b.hidden = at < 0; b.disabled = off;
2346
+ }
2347
+ $("md-close").setAttribute("aria-label", t.close); $("md-close").title = t.close;
2348
+ const list = (arr) => `<ul>${arr.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>`;
2349
+ const sec = (cls, title, body) => body ? `<section class="md-sec ${cls}"><h4>${esc(title)}</h4>${body}</section>` : "";
2350
+ const why = [s?.why ? `<p>${esc(s.why)}</p>` : "",
2351
+ ...(i.said ?? []).map((x) => `<div class="said">${ic("chat")}<span>${esc(x)}</span></div>`),
2352
+ i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""].join("");
2353
+ $("md-scroll").innerHTML = `${galleryHtml(i)}
2354
+ <h3 id="md-title"><a href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(name)}</a></h3>
2355
+ <p class="md-sub"><span class="badge folder" style="--c:${folderColor(i.category)}">${esc(folderPath(i.category))}</span>
2356
+ <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span>
2357
+ <span>#${i.id} · ${esc(t.kind1?.[i.kind] ?? t.kinds[i.kind] ?? i.kind)}</span></p>
2358
+ ${s?.oneLiner ? `<p class="md-one">${esc(s.oneLiner)}</p>` : ""}
2359
+ ${sec("demo", t.mdDemo, s?.demo ? `<p>${esc(s.demo)}</p>` : "")}
2360
+ ${sec("why", t.mdWhy, why)}
2361
+ ${sec("hl", t.mdHighlights, s?.highlights?.length ? list(s.highlights) : "")}
2362
+ ${sec("uc", t.mdUse, s?.useCases?.length ? list(s.useCases) : "")}
2363
+ ${sec("try", t.mdTry, s?.tryIt ? `<div class="md-try"><pre><code>${esc(s.tryIt)}</code></pre><button class="btn" type="button" data-md="copy">${esc(t.mdCopy)}</button></div>` : "")}
2364
+ ${sec("tags", t.mdTags, s?.tags?.length ? `<div class="md-tags tags">${s.tags.map((x) => `<span class="tag">#${esc(x)}</span>`).join(" ")}</div>` : "")}
2365
+ ${i.found?.length ? `<div class="found"><span>${esc(t.foundIn)}</span>${i.found.map((c) => `<a href="#item-${c.id}" data-open="${c.id}">${esc(c.name)}</a>`).join("")}</div>` : ""}
2366
+ ${i.flags?.length ? `<div class="flag">⚠ ${esc(i.flags.map((f) => t.flags[f] ?? f).join(", "))}</div>` : ""}
2367
+ <div class="md-fine">${i.shareCount ? `<span>${esc(t.shared(i.shareCount))}</span>` : ""}<span>${esc(i.createdAt.slice(0, 10))}</span>${i.enrichedBy ? `<span>${esc(t.enrichedBy(i.enrichedBy.replace(/^agent:/, "")))}</span>` : ""}</div>`;
2368
+ const busy = refreshing.has(i.id);
2369
+ const btn = (act, icon, label, extra = "") => `<button class="btn ${extra}" type="button" data-md="${act}">${ic(icon)} ${esc(label)}</button>`;
2370
+ $("md-actions").innerHTML = `<a class="btn primary" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${ic("link")} ${esc(t.openLink)}</a>` +
2371
+ (admin ? (inTrash ? btn("restore", "undo", t.restore)
2372
+ : btn("favorite", "star", i.favorite ? t.unfavorite : t.favorite, i.favorite ? "on" : "") + btn("move", "move", t.moveTo) +
2373
+ `<button class="btn ${busy ? "spin" : ""}" type="button" data-md="refresh" ${busy ? "disabled" : ""}>${ic("refresh")} ${esc(t.refresh)}</button>` +
2374
+ btn("note", "note", i.note ? t.editNote : t.addNote) + `<span class="spacer"></span>` + btn("trash", "trash", t.remove, "danger")) : "") +
2375
+ (modalFrom === "map" ? btn("list", "list", t.showInList) : "");
2376
+ }
2377
+ function openModal(id, from = "list") {
2378
+ if (!find(id)) return;
2379
+ const wasOpen = mdlDlg.open;
2380
+ modalId = id; modalFrom = from;
2381
+ paintModal();
2382
+ if (!wasOpen) mdlDlg.showModal();
2383
+ $("md-scroll").scrollTop = 0;
2384
+ mdlDlg.style.transform = "";
2385
+ history.replaceState(null, "", `${location.pathname}${location.search}#item-${id}`);
2386
+ }
2387
+ /** Step to the previous / next card in the list the modal came from. */
2388
+ function stepModal(d) {
2389
+ const ids = mdIds(), at = ids.indexOf(modalId), to = ids[at + d];
2390
+ if (at < 0 || to == null) return;
2391
+ openModal(to, modalFrom);
2392
+ }
2393
+ mdlDlg.addEventListener("close", () => {
2394
+ if (mdlDlg.open) return; // reopened (a link, a hash) before this queued event ran
2395
+ const id = modalId, from = modalFrom;
2396
+ // Only this card's own hash: a late close event must not wipe the link of a card opened since.
2397
+ if (!keepHash && location.hash === `#item-${id}`) history.replaceState(null, "", location.pathname + location.search);
2398
+ keepHash = false;
2399
+ mdlDlg.style.transform = "";
2400
+ // Focus goes back to the card you ended on (the one you opened, or the last one you stepped to).
2401
+ setTimeout(() => {
2402
+ const c = from === "list" && !document.querySelector("dialog[open]") ? document.querySelector(`#item-${id} .card`) : null;
2403
+ if (c) { c.focus({ preventScroll: true }); c.scrollIntoView({ block: "nearest" }); }
2404
+ }, 0);
2405
+ });
2406
+ mdlDlg.addEventListener("click", async (e) => {
2407
+ if (e.target === mdlDlg) return mdlDlg.close(); // the backdrop
2408
+ const open = e.target.closest("a[data-open]");
2409
+ if (open) { e.preventDefault(); const to = Number(open.dataset.open); if (find(to)) openModal(to, modalFrom); else { mdlDlg.close(); jumpTo(to); } return; }
2410
+ const g = e.target.closest("[data-g]");
2411
+ if (g) { const tr = $("g-track"); tr.scrollTo({ left: Number(g.dataset.g) * tr.clientWidth, behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); return; }
2412
+ const b = e.target.closest("[data-md]");
2413
+ if (!b || b.disabled) return;
2414
+ const id = modalId, item = find(id), el = document.getElementById(`item-${id}`), act1 = b.dataset.md;
2415
+ if (act1 === "close") return mdlDlg.close();
2416
+ if (act1 === "prev") return stepModal(-1);
2417
+ if (act1 === "next") return stepModal(1);
2418
+ if (act1 === "copy") {
2419
+ await navigator.clipboard?.writeText(item?.summary?.tryIt ?? "").catch(() => {});
2420
+ b.textContent = T().mdCopied; setTimeout(() => { if (b.isConnected) b.textContent = T().mdCopy; }, 1500);
2421
+ return;
2422
+ }
2423
+ if (!item) return;
2424
+ if (act1 === "list") {
2425
+ keepHash = true; mdlDlg.close();
2426
+ Object.assign(state, { view: "all", category: "", kind: "" });
2427
+ history.replaceState(null, "", `#item-${id}`);
2428
+ return load();
2429
+ }
2430
+ if (act1 === "move") { mdlDlg.close(); return openMovePicker(id); }
2431
+ if (act1 === "refresh") return refreshItem(id);
2432
+ if (act1 === "note") return openItemNote(id);
2433
+ if (act1 === "favorite") {
2434
+ if (el) await run(el, "favorite");
2435
+ else { const on = !item.favorite; if (await act(id, on ? "favorite" : "unfavorite")) { item.favorite = on; refreshCounts(); if (mapShown()) drawMap(); } }
2436
+ return paintModal();
2437
+ }
2438
+ if (act1 === "trash" || act1 === "restore") {
2439
+ mdlDlg.close();
2440
+ if (el) return run(el, act1);
2441
+ if (!(await act(id, act1))) return;
2442
+ toast(act1 === "trash" ? T().removed(nameOf(item)) : T().restored(nameOf(item)), async () => { await act(id, act1 === "trash" ? "restore" : "trash"); load(); });
2443
+ return load();
2444
+ }
2445
+ });
2446
+ // ←/→ step through the list; the gallery follows its scroll position.
2447
+ addEventListener("keydown", (e) => {
2448
+ if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey || !mdlDlg.open || !["ArrowLeft", "ArrowRight", "Escape"].includes(e.key)) return;
2449
+ if (document.querySelectorAll("dialog[open]").length > 1) return; // a picker or note on top keeps its own keys
2450
+ e.preventDefault();
2451
+ if (e.key === "Escape") mdlDlg.close(); else stepModal(e.key === "ArrowLeft" ? -1 : 1);
2452
+ });
2453
+ mdlDlg.addEventListener("scroll", (e) => {
2454
+ const tr = e.target;
2455
+ if (tr?.id !== "g-track") return;
2456
+ const n = Math.round(tr.scrollLeft / Math.max(1, tr.clientWidth));
2457
+ for (const b of mdlDlg.querySelectorAll(".g-th")) b.classList.toggle("on", Number(b.dataset.g) === n);
2458
+ }, true);
2459
+ // A phone: pull the sheet down from its top bar to close it.
2460
+ {
2461
+ let y0 = null, dy = 0;
2462
+ const grab = $("md-grab");
2463
+ grab.addEventListener("touchstart", (e) => { if (e.target.closest("button")) return; y0 = e.touches[0].clientY; dy = 0; mdlDlg.style.transition = "none"; }, { passive: true });
2464
+ grab.addEventListener("touchmove", (e) => { if (y0 == null) return; dy = Math.max(0, e.touches[0].clientY - y0); mdlDlg.style.transform = `translateY(${dy}px)`; }, { passive: true });
2465
+ const end = () => { if (y0 == null) return; y0 = null; mdlDlg.style.transition = ""; if (dy > 90) mdlDlg.close(); else mdlDlg.style.transform = ""; };
2466
+ grab.addEventListener("touchend", end); grab.addEventListener("touchcancel", end);
2467
+ }
2468
+ // A picture that fails to load (a dead link, a missing proxy file) is dropped rather than shown broken.
2469
+ document.addEventListener("error", (e) => {
2470
+ const img = e.target;
2471
+ if (img?.tagName !== "IMG" || !img.hasAttribute("data-media")) return;
2472
+ const th = img.closest(".thumb");
2473
+ if (th) return th.remove();
2474
+ const gal = img.closest(".gallery");
2475
+ if (!gal) return;
2476
+ const slides = [...gal.querySelectorAll(".g-slide")], btns = [...gal.querySelectorAll(".g-th")];
2477
+ const n = img.closest(".g-th") ? btns.indexOf(img.closest(".g-th")) : slides.indexOf(img.closest(".g-slide"));
2478
+ slides[n]?.remove(); btns[n]?.remove();
2479
+ if (!gal.querySelector(".g-slide")) return gal.remove();
2480
+ gal.querySelectorAll(".g-th").forEach((b, k) => { b.dataset.g = k; b.classList.toggle("on", k === 0); });
2481
+ if (gal.querySelectorAll(".g-th").length < 2) gal.querySelector(".g-thumbs")?.remove();
2482
+ }, true);
2483
+ // A GIF in the list shows one still frame until you point at the card (or open it): a list full of moving pictures is noise.
2484
+ document.addEventListener("load", (e) => {
2485
+ const img = e.target;
2486
+ if (img?.tagName !== "IMG" || !img.hasAttribute("data-gif") || img.dataset.anim) return;
2487
+ try {
2488
+ const c = document.createElement("canvas");
2489
+ c.width = img.naturalWidth; c.height = img.naturalHeight;
2490
+ c.getContext("2d").drawImage(img, 0, 0);
2491
+ const still = c.toDataURL("image/png");
2492
+ img.dataset.anim = img.src; img.src = still;
2493
+ } catch { /* leave it moving rather than blank */ }
2494
+ }, true);
2495
+ let hot = null;
2496
+ const playGif = (card, on) => { const im = card?.querySelector("img[data-gif]"); if (im?.dataset.anim) { if (on) { im.dataset.still ??= im.src; im.src = im.dataset.anim; } else if (im.dataset.still) im.src = im.dataset.still; } };
2497
+ $("list").addEventListener("mouseover", (e) => { const c = e.target.closest?.(".card"); if (c === hot) return; playGif(hot, false); hot = c; playGif(hot, true); });
2498
+ $("list").addEventListener("mouseleave", () => { playGif(hot, false); hot = null; });
1943
2499
 
1944
2500
  async function mapWrite(path, method, body) {
1945
2501
  const token = store.get("driftnet-token");
@@ -2051,6 +2607,8 @@
2051
2607
  zh ? "只要 AI 會開網址就行,把這段貼進對話。唯讀。" : "Any AI that can open a link: paste this into the chat. Read-only.",
2052
2608
  zh ? `讀一下 ${withKey(`${base}/llms.txt`)} ,這是我收藏的 AI 工具清單。幫我找適合「(你的需求)」的工具。`
2053
2609
  : `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
2610
+ card("feed", st.feed, zh ? "RSS/Atom 訂閱源:最新 50 張卡片。給 RSS 閱讀器或 n8n、Zapier 用;加上 ?folder=資料夾代號 可只看一個資料夾。" : "RSS / Atom feed of the newest 50 cards, for feed readers, n8n or Zapier. Add ?folder=<folder-id> for one folder.",
2611
+ withKey(`${base}/feed.xml`)),
2054
2612
  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.",
2055
2613
  JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2), "Hermes"),
2056
2614
  ].join("");
@@ -2131,6 +2689,7 @@
2131
2689
  item.note = saved.note;
2132
2690
  const el = document.getElementById(`item-${noting}`);
2133
2691
  if (el) { el.outerHTML = card(item); attachSwipe(document.getElementById(`item-${noting}`)); }
2692
+ if (modalId === noting && mdlDlg.open) paintModal();
2134
2693
  setTimeout(restoreFocus, 0);
2135
2694
  toast(T().saved);
2136
2695
  };
@@ -2253,24 +2812,113 @@
2253
2812
  updateCrumb();
2254
2813
  const viewKey = [state.view, state.category, state.kind, state.q].join("|");
2255
2814
  if (viewKey !== lastViewKey) { lastViewKey = viewKey; selected.clear(); selAnchor = null; }
2256
- document.body.classList.toggle("map-view", state.view === "map");
2257
- if (state.view !== "map" && picked) dropPicked();
2815
+ document.body.classList.toggle("map-view", mapShown());
2816
+ document.body.classList.toggle("split-view", splitOn());
2817
+ if (!mapShown() && picked) dropPicked();
2258
2818
  if (state.view === "notes") return renderNotes();
2259
2819
  if (state.view === "map") return renderMap();
2820
+ syncFocusHash();
2821
+ if (splitOn()) return renderSplit();
2822
+ return renderCards();
2823
+ }
2824
+ let splitQueue = Promise.resolve();
2825
+ /** Cards on the left, the mind map on the right: each renderer fills its own pane. */
2826
+ function renderSplit() {
2827
+ const run = async () => {
2828
+ if (!splitOn()) return renderCards();
2829
+ $("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>`;
2830
+ await renderMap(); // the map first: the selection check then knows both sides
2831
+ await inPane($("split-list"), renderCards);
2832
+ sizeSplit();
2833
+ syncSelection();
2834
+ };
2835
+ return (splitQueue = splitQueue.catch(() => {}).then(run));
2836
+ }
2837
+ function sizeSplit() {
2838
+ const p = document.getElementById("split-list");
2839
+ if (p) p.style.height = `${Math.max(320, innerHeight - p.getBoundingClientRect().top - 12)}px`;
2840
+ }
2841
+ // The map renderer and the map's own moves write into whatever "list" is: send them to the map pane while split.
2842
+ const renderMapBase = renderMap, drawMapBase = drawMap;
2843
+ renderMap = () => { const pane = document.getElementById("split-map"); return pane && splitOn() ? inPane(pane, renderMapBase) : renderMapBase(); };
2844
+ drawMap = () => { drawMapBase(); if (splitOn()) syncListWithMap(); };
2845
+ /** A card moved on the map: bring the list beside it in step (no refetch). */
2846
+ function syncListWithMap() {
2847
+ const by = new Map(mapItems.map((i) => [i.id, i]));
2848
+ const gone = new Set();
2849
+ for (const i of items) {
2850
+ const m = by.get(i.id);
2851
+ if (!m || m.category === i.category) continue;
2852
+ i.category = m.category;
2853
+ const el = document.getElementById(`item-${i.id}`);
2854
+ if (!el) continue;
2855
+ if (state.category && !subtreeOf(state.category).has(i.category)) { gone.add(i.id); el.remove(); }
2856
+ else { el.outerHTML = card(i); attachSwipe(document.getElementById(`item-${i.id}`)); }
2857
+ }
2858
+ if (gone.size) items = items.filter((i) => !gone.has(i.id));
2859
+ syncSelection();
2860
+ }
2861
+ wideQuery.addEventListener("change", () => { if (split && (state.view === "all" || state.view === "favorites")) render(); });
2862
+ // Dragging a card from the list onto a folder of the map files it there (the whole selection, if it is part of one).
2863
+ (() => {
2864
+ const node = (e) => e.target.closest?.(".mnode.folder, .mnode.root");
2865
+ const clear = () => document.querySelectorAll(".mnode.drop").forEach((d) => d.classList.remove("drop"));
2866
+ $("list").addEventListener("dragover", (e) => {
2867
+ const n = node(e);
2868
+ if (!n || !e.dataTransfer.types.includes("text/x-driftnet-item")) return;
2869
+ e.preventDefault();
2870
+ e.dataTransfer.dropEffect = "move";
2871
+ if (!n.classList.contains("drop")) { clear(); n.classList.add("drop"); }
2872
+ });
2873
+ $("list").addEventListener("dragleave", (e) => { if (!$("list").contains(e.relatedTarget)) clear(); });
2874
+ document.addEventListener("dragend", clear);
2875
+ $("list").addEventListener("drop", (e) => {
2876
+ const n = node(e), id = Number(e.dataTransfer.getData("text/x-driftnet-item"));
2877
+ clear();
2878
+ if (!n || !id || n.dataset.key === "root") return;
2879
+ e.preventDefault();
2880
+ const to = n.dataset.key.slice(2);
2881
+ if (selected.has(id) && selected.size > 1) bulkApply("move", [...selected], to);
2882
+ else if (mapItems.some((i) => i.id === id)) mapMoveItem(id, to);
2883
+ else moveItem(id, to);
2884
+ });
2885
+ })();
2886
+ /** One-time chooser on a brand-new catalogue whose folders are still the untouched starter set. */
2887
+ const untouchedSeed = () => folders.length > 0 && folders.every((f) => f.builtin && !f.name && !f.parent);
2888
+ function templateChooser(t) {
2889
+ if (!untouchedSeed() || store.get("driftnet-template-seen")) return "";
2890
+ return `<div class="tpl"><small>${esc(t.tplTitle)}</small><div class="tpl-row">${[["ai", t.tplAi], ["research", t.tplResearch], ["everyday", t.tplEveryday]]
2891
+ .map(([k, l]) => `<button class="btn" type="button" data-template="${k}">${esc(l)}</button>`).join("")}</div></div>`;
2892
+ }
2893
+ async function pickTemplate(template) {
2894
+ store.set("driftnet-template-seen", "1");
2895
+ // "ai" is what is already there: nothing to replace.
2896
+ if (template !== "ai") {
2897
+ const token = store.get("driftnet-token");
2898
+ const res = await fetch("/api/folders/template", { method: "POST", headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
2899
+ body: JSON.stringify({ template }) }).catch(() => null);
2900
+ if (res?.status === 401) return needAdmin();
2901
+ if (!res?.ok) toast(res?.status === 409 ? T().tplFailed : T().failed);
2902
+ }
2903
+ folders = await api("/api/folders").catch(() => folders);
2904
+ await load();
2905
+ }
2906
+ async function renderCards() {
2260
2907
  const p = new URLSearchParams({ limit: "300" });
2261
2908
  if (prefs.sort !== "best") p.set("sort", prefs.sort);
2262
2909
  if (state.view !== "all") p.set("view", state.view);
2263
2910
  for (const k of ["category", "kind", "q"]) if (state[k]) p.set(k, state[k]);
2264
2911
  items = await api(`/api/items?${p}`);
2265
2912
  const t = T();
2266
- const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : t.empty;
2913
+ const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : state.view === "inbox" ? t.emptyInbox : t.empty;
2267
2914
  $("list").innerHTML = items.length
2268
- ? `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : t.hint)}</p>` + items.map(card).join("")
2915
+ ? `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : state.view === "inbox" ? t.hintInbox : t.hint)}</p>` + items.map(card).join("")
2269
2916
  : `<div class="empty first"><span>${esc(empty)}</span>${state.view === "all" && !state.q && !state.category && role === "admin"
2270
2917
  ? `<form class="add" id="add-form"><input id="add-url" type="url" inputmode="url" placeholder="${esc(t.addPlaceholder)}" aria-label="${esc(t.addPlaceholder)}">
2271
2918
  <button class="btn primary" type="submit">${ic("plus")} ${esc(t.addLink)}</button></form>
2272
- <button class="btn" type="button" data-connect-empty>${ic("plug")} ${esc(t.st.connect)}</button>` : ""}</div>`;
2919
+ <button class="btn" type="button" data-connect-empty>${ic("plug")} ${esc(t.st.connect)}</button>${templateChooser(t)}` : ""}</div>`;
2273
2920
  $("add-form")?.addEventListener("submit", addLink);
2921
+ for (const b of $("list").querySelectorAll("[data-template]")) b.addEventListener("click", () => pickTemplate(b.dataset.template));
2274
2922
  $("list").querySelector("[data-connect-empty]")?.addEventListener("click", () => openConnect());
2275
2923
  for (const el of $("list").querySelectorAll(".swipe")) attachSwipe(el);
2276
2924
  syncSelection();
@@ -2281,10 +2929,12 @@
2281
2929
  if (target) {
2282
2930
  // Clear the sticky header (taller on a phone), then flash the card so it's obvious which one was meant.
2283
2931
  const top = target.getBoundingClientRect().top + scrollY - document.querySelector("header").offsetHeight - ($("crumb").offsetHeight || 0) - 12;
2284
- scrollTo({ top });
2932
+ if (splitOn()) target.scrollIntoView({ block: "center" }); else scrollTo({ top });
2285
2933
  target.classList.remove("flash"); void target.offsetWidth; target.classList.add("flash");
2934
+ if (hashOpen) { hashOpen = false; openModal(Number(location.hash.slice(6)), "list"); }
2286
2935
  }
2287
2936
  }
2937
+ if (mdlDlg.open) paintModal();
2288
2938
  }
2289
2939
 
2290
2940
  function card(i) {
@@ -2296,6 +2946,7 @@
2296
2946
  ? `<button class="tool" type="button" data-act="restore" title="${esc(t.restore)}" aria-label="${esc(t.restore)}">${ic("undo")}</button>`
2297
2947
  : `<button class="tool grip" type="button" draggable="true" data-grip="${i.id}" title="${esc(t.dragHint)}" aria-hidden="true" tabindex="-1">${ic("grip")}</button>
2298
2948
  <button class="tool" type="button" data-act="move" title="${esc(t.moveTo)}" aria-label="${esc(t.moveTo)}">${ic("move")}</button>
2949
+ <button class="tool ${refreshing.has(i.id) ? "spin" : ""}" type="button" data-act="refresh" title="${esc(t.refresh)}" aria-label="${esc(t.refresh)}" ${refreshing.has(i.id) ? "disabled" : ""}>${ic("refresh")}</button>
2299
2950
  <button class="tool ${i.favorite ? "on" : ""}" type="button" data-act="favorite" aria-pressed="${i.favorite}"
2300
2951
  title="${esc(i.favorite ? t.unfavorite : t.favorite)}" aria-label="${esc(i.favorite ? t.unfavorite : t.favorite)}">${ic("star")}</button>
2301
2952
  <button class="tool" type="button" data-act="trash" title="${esc(t.remove)}" aria-label="${esc(t.remove)}">${ic("trash")}</button>`;
@@ -2303,32 +2954,67 @@
2303
2954
  <div class="act right ${inTrash ? "restore" : ""}"><span>${ic(inTrash ? "undo" : "star", inTrash || i.favorite ? "" : "filled")} ${esc(inTrash ? t.swipeRestore : i.favorite ? t.swipeUnfav : t.swipeFav)}</span></div>
2304
2955
  <div class="act left"><span>${inTrash ? "" : `${esc(t.swipeTrash)} ${ic("trash")}`}</span></div>
2305
2956
  <article class="card" tabindex="0" aria-labelledby="name-${i.id}">
2306
- <div class="top">
2307
- <a class="name" id="name-${i.id}" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(s?.name ?? i.title)}</a>
2308
- <span class="badge folder" style="--c:${folderColor(i.category)}">${esc(catLabel(i.category))}</span>
2309
- <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span>
2310
- ${i.pending ? `<span class="rating">${esc(summaries ? t.pending : t.noModel)}</span>` : ""}
2311
- </div>
2312
- ${s ? `<p>${esc(s.oneLiner)}</p>` : ""}
2313
- ${s?.highlights?.length ? `<ul>${s.highlights.map((h) => `<li>${esc(h)}</li>`).join("")}</ul>` : ""}
2314
- ${(i.said ?? []).slice(0, 2).map((x) => `<div class="said">${ic("chat")}<span>${esc(x)}</span></div>`).join("")}
2315
- ${i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""}
2316
- ${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>` : ""}
2317
- ${i.flags.length ? `<div class="flag">⚠ ${esc(i.flags.map((f) => t.flags[f] ?? f).join(", "))}</div>` : ""}
2318
- <div class="meta">
2319
- <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>` : ""}
2320
- <span>${esc(i.createdAt.slice(0, 10))}</span>
2321
- ${i.enrichedBy ? `<span>${esc(t.enrichedBy(i.enrichedBy.replace(/^agent:/, "")))}</span>` : ""}
2322
- ${s?.tags?.length ? `<span class="tags">${s.tags.map((x) => `<span class="tag">#${esc(x)}</span>`).join(" ")}</span>` : ""}
2323
- ${inTrash ? "" : `<button class="link-btn" type="button" data-act="note">${ic("note")} ${esc(i.note ? t.editNote : t.addNote)}</button>`}
2957
+ <div class="crow">
2958
+ ${thumbHtml(i)}
2959
+ <div class="cbody">
2960
+ <div class="top">
2961
+ <a class="name" id="name-${i.id}" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(s?.name ?? i.title)}</a>
2962
+ <span class="badge folder" style="--c:${folderColor(i.category)}">${esc(catLabel(i.category))}</span>
2963
+ <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span>
2964
+ ${i.pending ? `<span class="rating">${esc(summaries ? t.pending : t.noModel)}</span>` : ""}
2965
+ </div>
2966
+ ${s ? `<p>${esc(s.oneLiner)}</p>` : ""}
2967
+ ${s?.demo ? `<p class="demo">${esc(s.demo)}</p>` : ""}
2968
+ ${i.flags.length ? `<div class="flag">⚠ ${esc(i.flags.map((f) => t.flags[f] ?? f).join(", "))}</div>` : ""}
2969
+ ${state.view === "inbox" ? inboxChips(i) : ""}
2970
+ <div class="meta">
2971
+ <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>` : ""}
2972
+ <span>${esc(i.createdAt.slice(0, 10))}</span>
2973
+ ${i.note ? `<span class="has-note" title="${esc(t.mdHasNote)}" role="img" aria-label="${esc(t.mdHasNote)}">${ic("note")}</span>` : ""}
2974
+ </div>
2975
+ </div>
2324
2976
  </div>
2325
2977
  <div class="tools">${tools}</div>
2326
2978
  </article>
2327
2979
  </div>`;
2328
2980
  }
2981
+ /** The list thumbnail: the first picture, cropped; a card with none (or a broken one) simply has no box. */
2982
+ function thumbHtml(i) {
2983
+ const all = mediaOf(i), m = all[0];
2984
+ if (!m) return "";
2985
+ const gif = m.kind === "gif";
2986
+ return `<div class="thumb">
2987
+ <img src="${esc(m.src)}" alt="${esc(m.alt || i.summary?.name || i.title)}" referrerpolicy="no-referrer" loading="lazy" decoding="async" draggable="false" data-media ${gif ? "data-gif" : ""}>
2988
+ ${m.kind === "video" ? `<span class="play" aria-hidden="true">▶</span>` : ""}${all.length > 1 ? `<span class="more-pics">+${all.length - 1}</span>` : ""}</div>`;
2989
+ }
2990
+
2991
+ /** Inbox: one-tap chips for the card's suggested folders (keys 1–3), and "other folder…" (m). */
2992
+ function inboxChips(i) {
2993
+ const t = T();
2994
+ const picks = (i.suggestions ?? []).filter((x) => folderById(x.folder)).slice(0, 3);
2995
+ return `<div class="chips" role="group" aria-label="${esc(t.moveTo)}">` +
2996
+ 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("") +
2997
+ `<button type="button" class="chip more" data-chip-more><kbd>m</kbd>${esc(t.chipOther)}</button></div>`;
2998
+ }
2999
+ /** 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. */
3000
+ function inboxFile(id, folder) {
3001
+ const sw = document.getElementById(`item-${id}`);
3002
+ const nextId = Number((sw?.nextElementSibling ?? sw?.previousElementSibling)?.dataset?.id) || null;
3003
+ return bulkApply("move", [id], folder).then(() => { if (nextId) document.querySelector(`#item-${nextId} .card`)?.focus({ preventScroll: true }); });
3004
+ }
3005
+ $("list").addEventListener("click", (e) => {
3006
+ const chip = e.target.closest("[data-chip], [data-chip-more]");
3007
+ const sw = chip?.closest(".swipe");
3008
+ if (!chip || !sw || role !== "admin" || selected.size) return;
3009
+ e.preventDefault();
3010
+ if (chip.dataset.chip) inboxFile(Number(sw.dataset.id), chip.dataset.chip);
3011
+ else openMovePicker(Number(sw.dataset.id));
3012
+ });
2329
3013
 
2330
3014
  // ── Actions ──────────────────────────────────────────────────────────────
2331
- const find = (id) => items.find((x) => x.id === id) ?? mapItems.find((x) => x.id === id);
3015
+ /** Cards found by the palette that neither the list nor the map holds (so the preview and Move to… can still reach them). */
3016
+ const extraItems = new Map();
3017
+ const find = (id) => items.find((x) => x.id === id) ?? mapItems.find((x) => x.id === id) ?? extraItems.get(id);
2332
3018
  const nameOf = (i) => (i.summary?.name ?? i.title).slice(0, 40);
2333
3019
 
2334
3020
  async function act(id, action) {
@@ -2376,12 +3062,42 @@
2376
3062
  refreshCounts();
2377
3063
  }
2378
3064
 
3065
+ /** Fetch a card's page again and redo its summary. The note, star, shares and a folder you chose stay. */
3066
+ const refreshing = new Set();
3067
+ function repaintItem(id) {
3068
+ const el = document.getElementById(`item-${id}`), item = find(id);
3069
+ if (el && item) { const focus = el.contains(document.activeElement); el.outerHTML = card(item); attachSwipe(document.getElementById(`item-${id}`)); if (focus) document.querySelector(`#item-${id} [data-act="refresh"]`)?.focus(); }
3070
+ if (mapShown()) drawMap();
3071
+ if (modalId === id && mdlDlg.open) paintModal();
3072
+ }
3073
+ async function refreshItem(id) {
3074
+ const item = find(id);
3075
+ if (!item || refreshing.has(id)) return;
3076
+ const t = T();
3077
+ refreshing.add(id);
3078
+ repaintItem(id);
3079
+ try {
3080
+ const token = store.get("driftnet-token");
3081
+ const res = await fetch(`/api/items/${id}/refresh`, { method: "POST", headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
3082
+ if (res?.status === 401) return needAdmin();
3083
+ const data = await res?.json().catch(() => ({}));
3084
+ if (!res?.ok) return toast(res?.status === 429 ? t.refreshWait : res?.status === 409 ? t.refreshBusy : res ? t.refreshFailed(data?.error) : t.failed);
3085
+ Object.assign(item, data);
3086
+ toast(t.refreshed(nameOf(item)));
3087
+ } finally {
3088
+ refreshing.delete(id);
3089
+ repaintItem(id);
3090
+ if (modalId === id && mdlDlg.open) paintModal();
3091
+ refreshCounts();
3092
+ }
3093
+ }
3094
+
2379
3095
  async function refreshCounts() {
2380
3096
  const stats = await api("/api/stats").catch(() => null);
2381
3097
  if (!stats) return;
2382
3098
  $("stats").textContent = T().stats(stats.items, stats.shares);
2383
3099
  const set = (v, n) => { const c = $("nav").querySelector(`[data-field="view"][data-value="${v}"] .count`); if (c) c.textContent = n || (v === "all" ? "0" : ""); };
2384
- set("all", stats.items); set("favorites", stats.favorites); set("trash", stats.trash);
3100
+ set("all", stats.items); set("favorites", stats.favorites); set("trash", stats.trash); set("inbox", stats.inbox);
2385
3101
  }
2386
3102
 
2387
3103
  // ── Select several cards: x, Shift-click or a long press; then act on all of them ──
@@ -2406,7 +3122,7 @@
2406
3122
  function clearSelection() { selected.clear(); selAnchor = null; syncSelection(); }
2407
3123
  /** Paint the selection on whatever is drawn (list or map) and refresh the bar. */
2408
3124
  function syncSelection() {
2409
- const here = new Set(state.view === "map" ? mapItems.map((i) => i.id) : visibleIds());
3125
+ const here = new Set([...(mapShown() ? mapItems.map((i) => i.id) : []), ...(state.view === "map" ? [] : visibleIds())]);
2410
3126
  for (const id of [...selected]) if (!here.has(id)) selected.delete(id);
2411
3127
  for (const el of $("list").querySelectorAll(".swipe")) el.classList.toggle("selected", selected.has(Number(el.dataset.id)));
2412
3128
  for (const n of $("list").querySelectorAll(".mnode.item")) n.classList.toggle("sel", selected.has(Number(n.dataset.key.slice(2))));
@@ -2471,16 +3187,21 @@
2471
3187
  $("list").addEventListener("click", (e) => {
2472
3188
  // With cards selected a click picks or drops the card; Shift-click selects a range. Links and buttons don't fire meanwhile.
2473
3189
  const sw = e.target.closest(".swipe");
2474
- if (sw && role === "admin" && (e.shiftKey || selected.size) && !e.target.closest(".tool, .link-btn")) {
3190
+ if (sw && role === "admin" && (e.shiftKey || selected.size) && !e.target.closest(".tool, .link-btn, .chip")) {
2475
3191
  e.preventDefault();
2476
3192
  if (e.shiftKey) selectRange(Number(sw.dataset.id)); else toggleSelect(Number(sw.dataset.id));
2477
3193
  return;
2478
3194
  }
2479
- const n = e.target.closest('.link-btn[data-act="note"]');
2480
- if (n) return openItemNote(Number(n.closest(".swipe").dataset.id));
2481
3195
  const b = e.target.closest(".tool");
2482
- if (!b || b.dataset.grip) return;
3196
+ if (!b) {
3197
+ // The card body (not its name link, chips or buttons) opens the detail modal.
3198
+ const body = e.target.closest(".swipe .card");
3199
+ if (body && !e.target.closest("a, button, .chip, input, summary")) openModal(Number(body.closest(".swipe").dataset.id), "list");
3200
+ return;
3201
+ }
3202
+ if (b.dataset.grip) return;
2483
3203
  if (b.dataset.act === "move") return openMovePicker(Number(b.closest(".swipe").dataset.id));
3204
+ if (b.dataset.act === "refresh") return refreshItem(Number(b.closest(".swipe").dataset.id));
2484
3205
  run(b.closest(".swipe"), b.dataset.act);
2485
3206
  });
2486
3207
  $("list").addEventListener("dragstart", (e) => {
@@ -2491,9 +3212,19 @@
2491
3212
  const cardEl = grip.closest(".card");
2492
3213
  e.dataTransfer.setDragImage(cardEl, 24, 24);
2493
3214
  });
3215
+ // A shared link (#item-<id>) opens that card's modal once the list is drawn.
3216
+ let hashOpen = /^#item-\d+$/.test(location.hash);
2494
3217
  // A "found in" link to a card outside the current filter: show everything, then jump.
2495
3218
  addEventListener("hashchange", () => {
2496
- if (/^#item-\d+$/.test(location.hash) && !document.getElementById(location.hash.slice(1))) {
3219
+ if (location.hash.startsWith("#focus=")) {
3220
+ const id = focusFromHash();
3221
+ if (state.view !== "map") { mapFocus = id; Object.assign(state, { view: "map", category: "" }); load(); }
3222
+ else setMapFocus(id);
3223
+ return;
3224
+ }
3225
+ if (/^#item-\d+$/.test(location.hash)) {
3226
+ if (document.getElementById(location.hash.slice(1))) return openModal(Number(location.hash.slice(6)), "list");
3227
+ hashOpen = true;
2497
3228
  Object.assign(state, { view: "all", category: "", kind: "", q: "" });
2498
3229
  $("q").value = "";
2499
3230
  load();
@@ -2524,7 +3255,8 @@
2524
3255
  const limit = () => Math.min(140, el.offsetWidth * 0.32);
2525
3256
  const inTrash = state.view === "trash";
2526
3257
  cardEl.addEventListener("pointerdown", (e) => {
2527
- if (e.button !== 0 || e.target.closest("a, button")) return;
3258
+ // The name is a link and a natural place for a thumb: a swipe may start on it (the click after a drag is swallowed below).
3259
+ if (e.button !== 0 || e.target.closest("button, a:not(.name)")) return;
2528
3260
  x0 = e.clientX; y0 = e.clientY; dx = 0; active = true; horizontal = null;
2529
3261
  });
2530
3262
  cardEl.addEventListener("pointermove", (e) => {
@@ -2597,6 +3329,116 @@
2597
3329
  if (el) el.focus({ preventScroll: true });
2598
3330
  }
2599
3331
  for (const d of document.querySelectorAll("dialog")) d.addEventListener("close", () => setTimeout(restoreFocus, 0));
3332
+ // ── Commands and the palette (⌘K / Ctrl+K) ────────────────────────────────
3333
+ /** Everything the palette can run. keys (two keys = "g" then …) and help (a STRINGS key) also feed the ? dialog. */
3334
+ function showLayout(kind) {
3335
+ split = kind === "split";
3336
+ store.set("driftnet-split", split ? "1" : "0");
3337
+ Object.assign(state, { view: kind === "map" ? "map" : "all", category: "" });
3338
+ load();
3339
+ }
3340
+ function toggleDark() {
3341
+ const dark = document.documentElement.dataset.theme === "dark" || (prefs.theme === "auto" && matchMedia("(prefers-color-scheme: dark)").matches);
3342
+ prefs.theme = dark ? "light" : "dark";
3343
+ store.set("driftnet-prefs", JSON.stringify(prefs));
3344
+ applyPrefs();
3345
+ }
3346
+ const commands = [
3347
+ { id: "view-list", label: { en: "Show the card list", "zh-TW": "顯示卡片列表" }, keys: ["g", "a"], help: "kAll", run: () => showLayout("list") },
3348
+ { id: "view-map", label: { en: "Show the mind map", "zh-TW": "顯示樹狀圖" }, keys: ["g", "m"], help: "kMap", run: () => showLayout("map") },
3349
+ { id: "view-split", label: { en: "Show cards and mind map side by side", "zh-TW": "並排顯示卡片與樹狀圖" }, when: () => wideQuery.matches, run: () => showLayout("split") },
3350
+ { id: "move", label: { en: "Move the focused card…", "zh-TW": "移動目前選取的卡片…" }, when: () => role === "admin" && !!pal.focused, run: () => openMovePicker(pal.focused) },
3351
+ { id: "new-folder", label: { en: "New folder", "zh-TW": "新增資料夾" }, when: () => role === "admin", run: () => openFolderDialog(null, null) },
3352
+ { id: "export-md", label: { en: "Download a backup (Markdown)", "zh-TW": "下載備份(Markdown)" }, run: () => download("markdown") },
3353
+ { id: "export-vault", label: { en: "Download for Obsidian / Notion", "zh-TW": "下載給 Obsidian/Notion" }, run: () => download("vault") },
3354
+ { id: "settings", label: { en: "Settings", "zh-TW": "設定" }, run: () => openSettings() },
3355
+ { id: "dark", label: { en: "Toggle dark mode", "zh-TW": "切換深色模式" }, run: toggleDark },
3356
+ { id: "language", label: { en: "Switch language", "zh-TW": "切換語言" }, run: () => $("lang").click() },
3357
+ { id: "keys", label: { en: "Keyboard shortcuts", "zh-TW": "快捷鍵" }, keys: ["?"], help: "kHelp", run: () => openKeys() },
3358
+ ];
3359
+ const cmdLabel = (c) => c.label[locale] ?? c.label.en;
3360
+ const goFolder = (id) => { Object.assign(state, { view: "all", category: id, kind: "" }); load(); };
3361
+ const pal = { rows: [], at: 0, gen: 0, timer: 0, cards: [], focused: null };
3362
+ function paletteRows(q) {
3363
+ const rows = [];
3364
+ const fl = q ? fuzzyRank(q, folders, (f) => folderFields(f.id)) : quickFolders().map(folderById).filter(Boolean);
3365
+ 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) });
3366
+ 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); } });
3367
+ const avail = commands.filter((c) => !c.when || c.when());
3368
+ for (const c of fuzzyRank(q, avail, (c) => [cmdLabel(c), c.id]).slice(0, q ? 8 : 20))
3369
+ rows.push({ group: "commands", label: cmdLabel(c), sub: c.keys?.join(" ") ?? "", run: c.run });
3370
+ return rows;
3371
+ }
3372
+ function renderPalette() {
3373
+ const t = T(), input = $("cmd-input");
3374
+ pal.rows = paletteRows(input.value);
3375
+ pal.at = Math.min(pal.at, Math.max(0, pal.rows.length - 1));
3376
+ let html = "", last = "";
3377
+ pal.rows.forEach((r, i) => {
3378
+ if (r.group !== last) { last = r.group; html += `<div class="cmd-h" role="presentation">${esc(t.palGroups[r.group])}</div>`; }
3379
+ 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>` +
3380
+ (r.sub ? `<span class="sub">${esc(r.sub)}</span>` : "") + `</div>`;
3381
+ });
3382
+ $("cmd-list").innerHTML = html || `<div class="cmd-empty" role="presentation">${esc(t.palNone)}</div>`;
3383
+ if (pal.rows.length) input.setAttribute("aria-activedescendant", `cmd-o-${pal.at}`); else input.removeAttribute("aria-activedescendant");
3384
+ $("cmd-o-" + pal.at)?.scrollIntoView({ block: "nearest" });
3385
+ }
3386
+ function openPalette() {
3387
+ if (document.querySelector("dialog[open]")) return;
3388
+ const t = T();
3389
+ pal.focused = focusedId();
3390
+ pal.at = 0; pal.cards = []; pal.gen++;
3391
+ $("cmd-input").value = "";
3392
+ $("cmd-input").placeholder = t.palPlaceholder;
3393
+ $("cmd-input").setAttribute("aria-label", t.palette);
3394
+ $("cmd-list").setAttribute("aria-label", t.palette);
3395
+ renderPalette();
3396
+ $("cmd-dlg").showModal();
3397
+ $("cmd-input").focus();
3398
+ }
3399
+ function runPalette(i) {
3400
+ const r = pal.rows[i];
3401
+ if (!r) return;
3402
+ $("cmd-dlg").close();
3403
+ setTimeout(r.run, 0); // after the dialog has let go of focus
3404
+ }
3405
+ $("cmd-input").addEventListener("input", () => {
3406
+ const q = $("cmd-input").value.trim(), gen = ++pal.gen;
3407
+ pal.at = 0;
3408
+ clearTimeout(pal.timer);
3409
+ if (q.length < 2) pal.cards = [];
3410
+ else pal.timer = setTimeout(async () => {
3411
+ const found = await api(`/api/items?${new URLSearchParams({ q, limit: "6" })}`).catch(() => []);
3412
+ if (gen !== pal.gen) return;
3413
+ pal.cards = found;
3414
+ renderPalette();
3415
+ }, 150);
3416
+ renderPalette();
3417
+ });
3418
+ $("cmd-input").addEventListener("keydown", (e) => {
3419
+ const n = pal.rows.length;
3420
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
3421
+ e.preventDefault();
3422
+ if (n) { pal.at = (pal.at + (e.key === "ArrowDown" ? 1 : n - 1)) % n; renderPalette(); }
3423
+ } else if (e.key === "Enter") { e.preventDefault(); runPalette(pal.at); }
3424
+ });
3425
+ $("cmd-list").addEventListener("click", (e) => { const o = e.target.closest("[data-i]"); if (o) runPalette(Number(o.dataset.i)); });
3426
+ $("cmd-list").addEventListener("pointermove", (e) => {
3427
+ const o = e.target.closest("[data-i]");
3428
+ if (!o || Number(o.dataset.i) === pal.at) return;
3429
+ $("cmd-o-" + pal.at)?.setAttribute("aria-selected", "false");
3430
+ pal.at = Number(o.dataset.i);
3431
+ o.setAttribute("aria-selected", "true");
3432
+ $("cmd-input").setAttribute("aria-activedescendant", o.id);
3433
+ });
3434
+ $("cmd-dlg").addEventListener("click", (e) => { if (e.target === $("cmd-dlg")) $("cmd-dlg").close(); });
3435
+ $("cmd-dlg").addEventListener("close", () => { clearTimeout(pal.timer); pal.gen++; });
3436
+ $("palette-btn").onclick = openPalette;
3437
+ addEventListener("keydown", (e) => {
3438
+ if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey || e.key.toLowerCase() !== "k") return;
3439
+ e.preventDefault();
3440
+ if ($("cmd-dlg").open) $("cmd-dlg").close(); else openPalette();
3441
+ });
2600
3442
  /** The ? dialog: every shortcut, and which folder each number key files into. */
2601
3443
  function openKeys() {
2602
3444
  const t = T(), quick = quickFolders();
@@ -2605,13 +3447,93 @@
2605
3447
  $("ky-close").textContent = t.keysClose;
2606
3448
  $("ky-body").innerHTML =
2607
3449
  `<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) +
3450
+ `<h4>${esc(t.keysInbox)}</h4>` + row(["1", "2", "3"], t.kChip) + row(["s"], t.kSkip) + row(["m"], t.kMove) +
2608
3451
  `<h4>${esc(t.keysSelect)}</h4>` + row(["x"], t.kSelect) + row(["Shift", "click"], t.kRange) + row([t.kHold], t.kLong) + row(["Esc"], t.kClear) +
2609
3452
  `<h4>${esc(t.keysQuick)}</h4>` + (quick.length ? quick.map((id, i) => row([String(i + 1)], t.kQuickN(catLabel(id)))).join("") : `<dd style="grid-column:1/-1">${esc(t.kQuickNone)}</dd>`) +
2610
- `<h4>${esc(t.keysGo)}</h4>` + row(["/"], t.kSearch) + row(["g", "m"], t.kMap) + row(["g", "a"], t.kAll) + row(["z"], t.kUndo) + row(["?"], t.kHelp);
3453
+ `<dd style="grid-column:1/-1">${esc(t.kQuickInbox)}</dd>` +
3454
+ `<h4>${esc(t.keysGo)}</h4>` + row([isMac ? "⌘" : "Ctrl", "K"], t.kPalette) + row(["/"], t.kSearch) +
3455
+ commands.filter((c) => c.keys).map((c) => row(c.keys, t[c.help])).join("") + row(["z"], t.kUndo) +
3456
+ `<h4>${esc(t.keysMap)}</h4>` + row(["↓", "↑"], t.kTreeNav) + row(["→"], t.kTreeOpen) + row(["←"], t.kTreeClose) + row(["Home", "End"], t.kTreeEnds) +
3457
+ row([t.kTreeType], t.kTreeTypeText) + row(["z"], t.kFocus) + row(["Esc", "Backspace"], t.kFocusUp);
2611
3458
  $("keys-dlg").showModal();
2612
3459
  }
2613
3460
  $("ky-close").onclick = () => $("keys-dlg").close();
2614
3461
  $("keys-dlg").addEventListener("click", (e) => { if (e.target === $("keys-dlg")) $("keys-dlg").close(); });
3462
+ // ── AI folder plan: proposed, reviewed line by line, applied in one go ────
3463
+ let plan = null;
3464
+ const planOps = () => plan?.operations ?? [];
3465
+ /** A folder named in a plan: a real one by path, or one the plan itself creates (new:<ref>). */
3466
+ function planFolder(id) {
3467
+ if (!id.startsWith("new:")) return folderPath(id);
3468
+ const c = planOps().find((o) => o.op === "create" && o.ref === id.slice(4));
3469
+ return c ? (c.parent ? `${planFolder(c.parent)} › ${c.name}` : c.name) : id;
3470
+ }
3471
+ const planNeeds = (o) => o.op === "move" ? o.folder : o.op === "create" && o.parent ? o.parent : "";
3472
+ function planLine(o) {
3473
+ const t = T();
3474
+ return o.op === "create" ? t.planCreate(planFolder("new:" + o.ref))
3475
+ : o.op === "rename" ? t.planRename(folderPath(o.folder), o.name)
3476
+ : o.op === "move" ? t.planMove(o.cards.length, planFolder(o.folder))
3477
+ : t.planMerge(folderPath(o.from), folderPath(o.into));
3478
+ }
3479
+ function drawPlan() {
3480
+ const t = T();
3481
+ $("plan-body").innerHTML = planOps().length ? planOps().map((o) => `<div class="plan-op" data-op="${esc(o.id)}">
3482
+ <input type="checkbox" id="po-${esc(o.id)}" checked aria-labelledby="pol-${esc(o.id)}">
3483
+ <label id="pol-${esc(o.id)}" for="po-${esc(o.id)}"><b>${esc(planLine(o))}</b></label>
3484
+ ${o.reason ? `<span class="why">${esc(o.reason)}</span>` : ""}
3485
+ ${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>` : ""}
3486
+ </div>`).join("") : `<p class="hint">${esc(t.planNone)}</p>`;
3487
+ syncPlan();
3488
+ }
3489
+ /** An operation that points at a folder the plan creates goes with it: untick the create and those untick (and stay locked). */
3490
+ function syncPlan() {
3491
+ const on = (id) => $(`po-${id}`)?.checked;
3492
+ 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; };
3493
+ for (const o of planOps()) {
3494
+ const need = planNeeds(o), ok = !need.startsWith("new:") || refOn(need.slice(4));
3495
+ const box = $(`po-${o.id}`);
3496
+ if (!ok) box.checked = false;
3497
+ box.disabled = !ok;
3498
+ box.closest(".plan-op").classList.toggle("off", !box.checked);
3499
+ box.title = ok ? "" : T().planNeeds;
3500
+ }
3501
+ const n = planOps().filter((o) => on(o.id)).length;
3502
+ $("pl-apply").textContent = T().planApply(n);
3503
+ $("pl-apply").disabled = !n;
3504
+ }
3505
+ $("plan-body").addEventListener("change", syncPlan);
3506
+ async function openPlan() {
3507
+ const t = T();
3508
+ if (!summaries) return toast(t.planNoModel);
3509
+ plan = null;
3510
+ $("pl-title").textContent = t.planTitle;
3511
+ $("pl-intro").textContent = t.planIntro;
3512
+ $("pl-cancel").textContent = t.cancel;
3513
+ $("pl-apply").textContent = t.planApply(0);
3514
+ $("pl-apply").disabled = true;
3515
+ $("plan-body").innerHTML = `<p class="hint" role="status">${esc(t.planThinking)}</p>`;
3516
+ $("plan-dlg").showModal();
3517
+ const r = await mapWrite("/api/folders/suggest", "POST");
3518
+ if (!r) return $("plan-dlg").close();
3519
+ plan = r;
3520
+ drawPlan();
3521
+ }
3522
+ $("pl-cancel").onclick = () => $("plan-dlg").close();
3523
+ $("plan-dlg").addEventListener("click", (e) => { if (e.target === $("plan-dlg")) $("plan-dlg").close(); });
3524
+ $("pl-apply").onclick = async () => {
3525
+ const accept = planOps().filter((o) => $(`po-${o.id}`)?.checked).map((o) => o.id);
3526
+ if (!accept.length) return;
3527
+ $("pl-apply").disabled = true;
3528
+ const r = await mapWrite("/api/folders/suggest/apply", "POST", { plan: plan.plan, accept });
3529
+ if (!r) { $("pl-apply").disabled = false; return; }
3530
+ $("plan-dlg").close();
3531
+ await load();
3532
+ toast(T().planApplied(r.count), async () => {
3533
+ if (await mapWrite("/api/items/bulk/undo", "POST", { undo: r.undo })) await load();
3534
+ });
3535
+ };
3536
+
2615
3537
  /** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
2616
3538
  let lastUndo = null;
2617
3539
  function toast(text, undo) {
@@ -2628,6 +3550,8 @@
2628
3550
  }
2629
3551
  // Once the toast is gone, z no longer undoes something you can't see any more.
2630
3552
  function hideToast() { $("toast").classList.remove("show"); lastUndo = null; }
3553
+ /** z undoes only what the toast still shows. */
3554
+ const canUndo = () => !!lastUndo && $("toast").classList.contains("show");
2631
3555
  let toastMs = 5000;
2632
3556
  // Reading or reaching for Undo keeps the toast up.
2633
3557
  for (const ev of ["pointerenter", "focusin"]) $("toast").addEventListener(ev, () => clearTimeout(toastTimer));
@@ -2639,29 +3563,37 @@
2639
3563
  // ── Keyboard: j/k to step through cards, then act on the focused one ─────
2640
3564
  let lastKey = "";
2641
3565
  addEventListener("keydown", (e) => {
2642
- if ((e.metaKey || e.ctrlKey) && e.key === "z" && lastUndo && !/^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? "")) { e.preventDefault(); $("toast-undo").click(); return; }
3566
+ if ((e.metaKey || e.ctrlKey) && e.key === "z" && canUndo() && !/^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? "")) { e.preventDefault(); $("toast-undo").click(); return; }
2643
3567
  if (e.metaKey || e.ctrlKey || e.altKey || document.querySelector("dialog[open]")) return;
2644
3568
  if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? "")) return;
2645
3569
  const k = e.key, prev = lastKey;
2646
3570
  lastKey = k;
2647
3571
  if (k === "Escape" && selected.size) { clearSelection(); return; }
3572
+ if ((k === "Escape" || k === "Backspace") && mapShown() && mapFocus && !picked && !document.body.classList.contains("menu-open")) { e.preventDefault(); mapUp(); return; }
2648
3573
  if (k === "/") { e.preventDefault(); $("q").focus(); return; }
2649
- if ((k === "z" || k === "u") && lastUndo) { e.preventDefault(); $("toast-undo").click(); return; }
3574
+ if ((k === "z" || k === "u") && canUndo()) { e.preventDefault(); $("toast-undo").click(); return; }
2650
3575
  if (k === "?") { openKeys(); return; }
3576
+ // Inbox: 1–3 pick the focused card's suggestion chips (before the global "file into top-9 folders").
3577
+ if (state.view === "inbox" && /^[1-3]$/.test(k) && role === "admin" && focusedId() && !selected.size) {
3578
+ const chip = document.querySelectorAll(`#item-${focusedId()} [data-chip]`)[Number(k) - 1];
3579
+ if (chip) { e.preventDefault(); inboxFile(focusedId(), chip.dataset.chip); return; }
3580
+ }
2651
3581
  if (/^[1-9]$/.test(k) && role === "admin" && !document.activeElement?.isContentEditable && quickMove(Number(k))) { e.preventDefault(); return; }
2652
3582
  if (k === "x" && role === "admin" && !document.activeElement?.isContentEditable && focusedId() && state.view !== "map") { e.preventDefault(); toggleSelect(focusedId()); return; }
2653
- if (prev === "g" && k === "m") { Object.assign(state, { view: "map", category: "" }); load(); return; }
2654
- if (prev === "g" && k === "a") { Object.assign(state, { view: "all", category: "" }); load(); return; }
3583
+ const chord = commands.find((c) => c.keys?.length === 2 && c.keys[0] === prev && c.keys[1] === k);
3584
+ if (chord) { chord.run(); return; }
2655
3585
  const cards = [...$("list").querySelectorAll(".swipe .card")];
2656
3586
  if (!cards.length) return;
2657
3587
  const cur = document.activeElement?.closest?.(".card");
2658
3588
  const at = cards.indexOf(cur);
2659
- if (k === "j" || k === "k") {
3589
+ if (k === "j" || k === "k" || (k === "s" && state.view === "inbox")) {
2660
3590
  e.preventDefault();
2661
- const next = cards[Math.min(cards.length - 1, Math.max(0, at + (k === "j" ? 1 : -1)))] ?? cards[0];
3591
+ const next = cards[Math.min(cards.length - 1, Math.max(0, at + (k === "k" ? -1 : 1)))] ?? cards[0];
2662
3592
  next.focus(); next.scrollIntoView({ block: "nearest" });
2663
3593
  return;
2664
3594
  }
3595
+ // Enter or o on a focused card opens its detail modal.
3596
+ if ((k === "Enter" || k === "o") && cur && document.activeElement === cur) { e.preventDefault(); openModal(Number(cur.closest(".swipe").dataset.id), "list"); return; }
2665
3597
  if (!cur || role !== "admin") return;
2666
3598
  const swipe = cur.closest(".swipe");
2667
3599
  if (!["f", "#", "Delete", "m", "n"].includes(k)) return;
@@ -2678,8 +3610,22 @@
2678
3610
  load();
2679
3611
  };
2680
3612
  let timer;
3613
+ if (location.hash.startsWith("#focus=")) { mapFocus = focusFromHash(); state.view = "map"; }
2681
3614
  $("q").oninput = (e) => { clearTimeout(timer); timer = setTimeout(() => { state.q = e.target.value.trim(); render(); }, 200); };
2682
- load();
3615
+ // A scanned pairing link (#pair=<code>): take the code out of the address bar at once, swap it for this device's token.
3616
+ async function claimPairing() {
3617
+ const m = /^#pair=([\w-]{16,128})$/.exec(location.hash);
3618
+ if (!m) return;
3619
+ history.replaceState(null, "", location.pathname + location.search);
3620
+ const res = await fetch("/api/pair/claim", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: m[1] }) }).catch(() => null);
3621
+ if (!res?.ok) { toast(T().st.pairFailed); return; }
3622
+ const dev = await res.json();
3623
+ // A write token works like the password everywhere the page uses it, a read token like the share key.
3624
+ store.set(dev.scope === "write" ? "driftnet-token" : "driftnet-key", dev.token);
3625
+ store.set(dev.scope === "write" ? "driftnet-key" : "driftnet-token", "");
3626
+ toast(T().st.pairOk);
3627
+ }
3628
+ claimPairing().finally(load);
2683
3629
  </script>
2684
3630
  </body>
2685
3631
  </html>