driftnet 0.2.2 → 0.3.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
@@ -17,31 +17,63 @@
17
17
  --accent: #2f6fdb; --accent-soft: #e8effc; --warn: #b4540a; --star: #c58a00; --star-soft: #fff4d6;
18
18
  --danger: #c62828; --danger-soft: #fde8e8; --ok: #2e7d32; --ok-soft: #e6f4ea;
19
19
  font-family: ui-sans-serif, system-ui, -apple-system, "PingFang TC", "Noto Sans TC", sans-serif;
20
+ /* Branch colours for folders (map, badges, sidebar dots). */
21
+ --m1: oklch(52% .16 262); --m2: oklch(55% .11 185); --m3: oklch(58% .15 45); --m4: oklch(52% .17 300);
22
+ --m5: oklch(55% .17 355); --m6: oklch(53% .13 148); --m7: oklch(60% .13 75); --m8: oklch(54% .12 225);
23
+ --shadow: 0 1px 2px rgba(0,0,0,.05), 0 2px 8px rgba(0,0,0,.04);
20
24
  }
21
25
  @media (prefers-color-scheme: dark) {
22
26
  :root:not([data-theme="light"]) { --bg: #121211; --panel: #1b1b1a; --text: #ececea; --muted: #9a9a94; --line: #2d2d2b;
23
27
  --accent: #7aa7ff; --accent-soft: #1e2a40; --warn: #f0a050; --star: #f2c14e; --star-soft: #3a3016;
24
- --danger: #ef9a9a; --danger-soft: #3b1d1d; --ok: #81c784; --ok-soft: #1d3322; }
28
+ --danger: #ef9a9a; --danger-soft: #3b1d1d; --ok: #81c784; --ok-soft: #1d3322; color-scheme: dark;
29
+ --m1: oklch(74% .12 262); --m2: oklch(76% .1 185); --m3: oklch(76% .12 45); --m4: oklch(74% .13 300);
30
+ --m5: oklch(75% .13 355); --m6: oklch(76% .11 148); --m7: oklch(80% .11 75); --m8: oklch(76% .1 225);
31
+ --shadow: 0 0 0 1px rgba(255,255,255,.06); }
25
32
  }
26
33
  :root[data-theme="dark"] { --bg: #121211; --panel: #1b1b1a; --text: #ececea; --muted: #9a9a94; --line: #2d2d2b;
27
34
  --accent: #7aa7ff; --accent-soft: #1e2a40; --warn: #f0a050; --star: #f2c14e; --star-soft: #3a3016;
28
- --danger: #ef9a9a; --danger-soft: #3b1d1d; --ok: #81c784; --ok-soft: #1d3322; color-scheme: dark; }
35
+ --danger: #ef9a9a; --danger-soft: #3b1d1d; --ok: #81c784; --ok-soft: #1d3322; color-scheme: dark;
36
+ --m1: oklch(74% .12 262); --m2: oklch(76% .1 185); --m3: oklch(76% .12 45); --m4: oklch(74% .13 300);
37
+ --m5: oklch(75% .13 355); --m6: oklch(76% .11 148); --m7: oklch(80% .11 75); --m8: oklch(76% .1 225);
38
+ --shadow: 0 0 0 1px rgba(255,255,255,.06); }
29
39
  :root[data-theme="light"] { color-scheme: light; }
30
40
  * { box-sizing: border-box; }
31
- body { margin: 0; background: var(--bg); color: var(--text); font-size: 15px; line-height: 1.5; -webkit-tap-highlight-color: transparent; }
41
+ .ico { width: 18px; height: 18px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; vertical-align: -3px; }
42
+ .tool.on .ico, .ico.filled { fill: currentColor; }
43
+ body { margin: 0; background: var(--bg); color: var(--text); font-size: 15px; line-height: 1.5; -webkit-tap-highlight-color: transparent;
44
+ line-break: strict; text-wrap: pretty; }
32
45
  button { font: inherit; color: inherit; }
33
46
 
34
47
  header { display: flex; gap: 12px 16px; align-items: center; padding: 12px 20px; padding-top: max(12px, env(safe-area-inset-top));
35
48
  border-bottom: 1px solid var(--line); background: var(--panel); position: sticky; top: 0; z-index: 3; flex-wrap: wrap; }
36
- .brand { display: flex; align-items: center; gap: 8px; font-size: 18px; margin: 0; letter-spacing: -0.01em; }
49
+ .brand { display: flex; align-items: center; gap: 8px; font-size: 19px; margin: 0; letter-spacing: -0.02em; font-weight: 750; }
50
+ @media (min-width: 721px) { header { padding-inline: max(20px, calc((100vw - 1200px) / 2 + 20px)); } }
37
51
  .stats { color: var(--muted); font-size: 13px; }
38
52
  .search { flex: 1; min-width: 180px; max-width: 420px; margin-left: auto; padding: 9px 12px; border: 1px solid var(--line);
39
53
  border-radius: 10px; background: var(--bg); color: var(--text); font: inherit; }
54
+ .skip { position: absolute; left: 8px; top: -60px; z-index: 50; background: var(--accent); color: #fff; padding: 10px 14px; border-radius: 10px; }
55
+ .skip:focus { top: 8px; }
56
+ .lock { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--star); color: var(--text); background: var(--star-soft);
57
+ border-radius: 99px; padding: 6px 12px; font-size: 13px; cursor: pointer; min-height: 40px; white-space: nowrap; }
58
+ .lock[hidden] { display: none; }
59
+ .lock.bump { animation: bump .7s ease 2; }
60
+ .card.shake { animation: shake .35s ease; }
61
+ @keyframes shake { 25% { transform: translateX(-10px); } 75% { transform: translateX(8px); } }
62
+ @media (max-width: 720px) { .lock .long { display: none; } .lock { padding: 6px 10px; } }
63
+ @media (min-width: 721px) { .lock .short { display: none; } }
64
+ /* Browsing with a read-only share key: nothing that edits is offered. */
65
+ body.readonly .tools, body.readonly .link-btn[data-act="note"], body.readonly nav .more, body.readonly nav [data-new],
66
+ body.readonly .map-bar [data-map="new"], body.readonly #new-note, body.readonly .hint.swipe-hint { display: none !important; }
40
67
  .lang { border: 1px solid var(--line); background: var(--bg); border-radius: 10px; padding: 8px 12px; font-size: 13px; cursor: pointer; min-height: 40px; }
41
68
 
42
69
  .layout { display: grid; grid-template-columns: 256px 1fr; max-width: 1200px; margin: 0 auto; }
43
70
  nav { padding: 16px 12px; border-right: 1px solid var(--line); position: sticky; top: 65px; align-self: start; max-height: calc(100vh - 65px); overflow: auto; }
44
71
  nav .row { display: contents; }
72
+ nav button .lbl { display: inline-flex; align-items: center; gap: 9px; min-width: 0; }
73
+ nav button .lbl .ico { color: var(--muted); }
74
+ nav button[aria-pressed="true"] .lbl .ico { color: var(--accent); }
75
+ nav .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--c); flex: none; }
76
+ nav .dot.sub { background: none; border: 1.5px solid var(--c); width: 7px; height: 7px; }
45
77
  nav button { display: flex; justify-content: space-between; align-items: center; gap: 8px; width: 100%; padding: 8px 10px; border: 0;
46
78
  border-radius: 8px; background: none; text-align: left; cursor: pointer; }
47
79
  nav button:hover { background: var(--accent-soft); }
@@ -58,6 +90,7 @@
58
90
  nav .folder > [data-field] { flex: 1; min-width: 0; padding-left: 4px; }
59
91
  nav .folder > [data-field] > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
60
92
  nav .twist { transition: transform .15s ease; font-size: 10px; width: 22px; min-width: 22px; }
93
+ nav .twist .ico, nav .more .ico { width: 15px; height: 15px; }
61
94
  nav .folder .more { width: 26px; min-width: 26px; }
62
95
  nav .twist[aria-expanded="true"] { transform: rotate(90deg); }
63
96
  nav .twist.leaf { visibility: hidden; }
@@ -94,9 +127,10 @@
94
127
  .found a { color: var(--accent); text-decoration: none; background: var(--accent-soft); border-radius: 99px; padding: 1px 9px; }
95
128
  .found a:hover { text-decoration: underline; }
96
129
  .said { margin: 8px 0 2px; padding: 6px 10px; border-left: 3px solid var(--line); color: var(--muted); font-size: 14px; white-space: pre-wrap; }
97
- .said::before { content: "💬 "; }
130
+ .said, .mynote { display: flex; gap: 8px; align-items: flex-start; }
131
+ .said .ico, .mynote .ico { margin-top: 2px; width: 16px; height: 16px; }
98
132
  .mynote { margin: 8px 0 2px; padding: 8px 10px; border-radius: 8px; background: var(--star-soft); font-size: 14px; white-space: pre-wrap; }
99
- .mynote::before { content: "📝 "; }
133
+
100
134
  .link-btn { border: 0; background: none; color: var(--accent); font: inherit; font-size: 13px; padding: 0; cursor: pointer; }
101
135
  .link-btn:hover { text-decoration: underline; }
102
136
  nav .foot { display: grid; gap: 2px; margin-top: 14px; padding-top: 10px; border-top: 1px solid var(--line); }
@@ -129,6 +163,111 @@
129
163
  .set-row small { color: var(--muted); }
130
164
  .set-status { font-size: 13px; color: var(--muted); background: var(--bg); border-radius: 8px; padding: 8px 10px; margin-bottom: 14px; }
131
165
  .set-scroll { max-height: min(70vh, 640px); overflow: auto; margin: 0 -18px; padding: 0 18px; }
166
+ /* The mind map: folders branch out to the right; drag cards onto folders. */
167
+ .map-bar { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
168
+ .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-wrap { position: relative; overflow: auto; height: 70vh; min-height: 320px; border: 1px solid var(--line);
171
+ border-radius: 16px; background: var(--panel); box-shadow: var(--shadow); touch-action: pan-x pan-y pinch-zoom; overscroll-behavior: contain;
172
+ background-image: radial-gradient(color-mix(in srgb, var(--muted) 18%, transparent) 1px, transparent 1px); background-size: 22px 22px; }
173
+ .map-canvas { position: relative; transform-origin: 0 0; }
174
+ .map-canvas > svg { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }
175
+ .map-canvas > svg path { fill: none; stroke-linecap: round; opacity: .8; }
176
+ .map-canvas.searching > svg path:not(.hit) { opacity: .25; }
177
+ /* The zoom pill sits on the frame's corner, not on the (scrolling) map. */
178
+ .map-shell { position: relative; min-width: 0; width: 100%; } /* never wider than the page, however wide the map */
179
+ main { min-width: 0; }
180
+ .map-zoom { position: absolute; bottom: 12px; right: 12px; display: flex; background: var(--panel);
181
+ border: 1px solid var(--line); border-radius: 12px; box-shadow: var(--shadow); overflow: hidden; z-index: 2; }
182
+ .map-zoom button { width: 44px; height: 44px; border: 0; background: none; color: var(--text); cursor: pointer; display: grid; place-items: center; }
183
+ .map-zoom button + button { border-left: 1px solid var(--line); }
184
+ .map-zoom button:hover { background: var(--bg); }
185
+ .mnode { position: absolute; display: flex; align-items: center; gap: 6px; height: 36px; padding: 0 14px; border-radius: 18px;
186
+ white-space: nowrap; font-size: 14px; cursor: pointer; touch-action: pan-x pan-y; user-select: none; -webkit-user-select: none;
187
+ background: var(--panel); border: 2px solid var(--c); color: var(--text); box-shadow: var(--shadow);
188
+ transition: transform .12s ease, box-shadow .12s ease, opacity .15s ease; }
189
+ @media (pointer: fine) { .mnode { touch-action: none; } }
190
+ .mnode:hover { box-shadow: 0 4px 14px rgba(0,0,0,.12); }
191
+ .mnode:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
192
+ .mnode .ico { width: 15px; height: 15px; }
193
+ .mnode.root { height: 46px; border-radius: 23px; padding: 0 20px; font-size: 17px; font-weight: 750; color: #fff; letter-spacing: -.01em;
194
+ background: linear-gradient(135deg, oklch(45% .17 262), oklch(44% .1 190)); border: 0; }
195
+ .mnode.root .cnt { background: rgba(255,255,255,.22); color: #fff; }
196
+ .mnode.folder.l1 { background: var(--c); color: #fff; border: 0; font-weight: 650; height: 38px; }
197
+ .mnode.folder.l1 .cnt { background: rgba(255,255,255,.25); color: #fff; }
198
+ .mnode.folder.l1 .tw, .mnode.folder.l1 .opt { color: #fff; }
199
+ .mnode.folder.l2 { font-weight: 600; background: color-mix(in srgb, var(--c) 14%, var(--panel)); }
200
+ .mnode.folder.vacant { opacity: .75; border: 2px dashed var(--c); background: var(--panel); color: var(--text); }
201
+ .mnode.folder.vacant .opt { color: var(--muted); }
202
+ .mnode.item { height: 30px; font-size: 13px; padding: 0 4px; border: 0; border-bottom: 2px solid var(--c); border-radius: 0; background: none; box-shadow: none; }
203
+ .mnode.item:hover { background: color-mix(in srgb, var(--c) 10%, transparent); border-radius: 6px 6px 0 0; }
204
+ .mnode.item .w { color: var(--star); display: inline-flex; }
205
+ .mnode.more { height: 28px; font-size: 12.5px; border: 1px dashed var(--c); color: var(--c); background: var(--panel); box-shadow: none; }
206
+ .mnode .cnt { font-size: 12px; color: var(--c); font-weight: 600; background: color-mix(in srgb, var(--c) 18%, var(--panel)); border-radius: 99px; padding: 0 7px; }
207
+ .mnode .tw { display: inline-flex; color: var(--c); transition: transform .15s ease; }
208
+ .mnode .tw.open { transform: rotate(90deg); }
209
+ .mnode.left .tw:not(.open) { transform: rotate(180deg); }
210
+ .mnode .opt { display: inline-flex; color: var(--muted); margin-right: -8px; padding: 6px; border-radius: 50%; }
211
+ .mnode .opt:hover { background: rgba(0,0,0,.1); }
212
+ .map-canvas.searching .mnode:not(.hit):not(.root):not(.l1) { opacity: .35; }
213
+ .mnode.hit { box-shadow: 0 0 0 3px color-mix(in srgb, var(--star) 55%, transparent); opacity: 1; }
214
+ .mnode.lift { transform: scale(1.08); box-shadow: 0 8px 22px rgba(0,0,0,.22); }
215
+ .mnode.drop { transform: scale(1.1); box-shadow: 0 0 0 4px color-mix(in srgb, var(--c) 40%, transparent); }
216
+ .mnode.dragging { opacity: .35; }
217
+ .mnode.picked { outline: 3px solid var(--c); outline-offset: 3px; transform: scale(1.06); }
218
+ .pickbar { position: fixed; left: 12px; right: 12px; bottom: max(16px, calc(env(safe-area-inset-bottom) + 8px)); z-index: 6; display: flex; gap: 10px;
219
+ align-items: center; justify-content: space-between; background: var(--accent); color: #fff; border-radius: 14px; padding: 10px 10px 10px 16px;
220
+ box-shadow: 0 8px 26px rgba(0,0,0,.28); }
221
+ .pickbar[hidden] { display: none; }
222
+ .pickbar button { border: 0; background: rgba(255,255,255,.2); color: #fff; border-radius: 10px; min-height: 40px; padding: 0 14px; font-weight: 600; }
223
+ .mnode.bump { animation: bump .6s ease; }
224
+ @keyframes bump { 30% { transform: scale(1.14); box-shadow: 0 0 0 6px color-mix(in srgb, var(--c) 35%, transparent); } }
225
+ .map-wrap.panning { cursor: grabbing; }
226
+ body.map-view { overflow: hidden; }
227
+ /* On the map, messages sit at the top so they never cover the zoom buttons. */
228
+ body.map-view .toast { bottom: auto; top: calc(env(safe-area-inset-top) + 76px); transform: translate(-50%, calc(-100% - 120px)); }
229
+ body.map-view .toast.show { transform: translate(-50%, 0); }
230
+ body.map-view .pickbar { bottom: auto; top: calc(env(safe-area-inset-top) + 72px); }
231
+ .pickbar button { white-space: nowrap; }
232
+ .mnode .opt { position: relative; }
233
+ .mnode .opt::before { content: ""; position: absolute; inset: -9px; }
234
+ body.map-view main { padding-bottom: 0; }
235
+ .map-wrap { user-select: none; -webkit-user-select: none; }
236
+ .mghost { position: fixed; z-index: 30; pointer-events: none; transform: translate(-50%, -130%) rotate(-2deg); opacity: .95; box-shadow: 0 10px 28px rgba(0,0,0,.25); }
237
+ .peek h3 { margin: 0 0 8px; font-size: 18px; }
238
+ .peek ul { color: var(--muted); padding-left: 20px; }
239
+ .peek-actions { flex-wrap: wrap; }
240
+ .peek-actions .btn { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
241
+ .tabs { display: flex; gap: 4px; padding: 3px; background: var(--bg); border-radius: 12px; margin-bottom: 14px; position: sticky; top: 0; z-index: 1; }
242
+ .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; }
243
+ .tabs button[aria-selected="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
244
+ #st-body section[data-tab] { display: none; }
245
+ #st-body[data-tab="general"] section[data-tab="general"], #st-body[data-tab="access"] section[data-tab="access"],
246
+ #st-body[data-tab="ai"] section[data-tab="ai"] { display: block; }
247
+ .set-row { overflow-wrap: anywhere; }
248
+ #st-body:not(.show-env) .envname { display: none; }
249
+ .tabs { background: var(--bg); box-shadow: 0 -8px 0 var(--panel); margin-bottom: 16px; }
250
+ main .link-btn { min-height: 44px; padding: 0 6px; }
251
+ .meta .link-btn { min-height: 32px; }
252
+ .tags { white-space: normal; } .tags .tag { white-space: nowrap; }
253
+ .btn:disabled, .btn[disabled] { opacity: .45; cursor: not-allowed; filter: grayscale(.4); }
254
+ @media (max-width: 720px) { .peek-actions { display: grid; grid-template-columns: 1fr 1fr; } .peek-actions .spacer { display: none; } }
255
+ .set-row .envname { font-family: ui-monospace, Menlo, monospace; font-size: 11px; opacity: .6; }
256
+ dialog::backdrop { backdrop-filter: blur(3px); }
257
+ .act span { display: inline-flex; align-items: center; gap: 6px; }
258
+ .tool .ico { width: 20px; height: 20px; }
259
+ .link-btn { display: inline-flex; align-items: center; gap: 4px; }
260
+ .link-btn .ico { width: 15px; height: 15px; }
261
+ .empty.first { display: grid; gap: 14px; justify-items: center; }
262
+ .empty.first .add { display: flex; gap: 8px; width: min(520px, 100%); }
263
+ .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); }
264
+ .empty.first .btn { display: inline-flex; align-items: center; gap: 6px; }
265
+ @media (pointer: coarse) {
266
+ .mnode .opt { padding: 10px; margin: -6px -12px -6px 0; }
267
+ .meta .link-btn { min-height: 44px; }
268
+ nav .icon, nav .twist, nav .folder .more { width: 44px; min-width: 44px; height: 44px; }
269
+ .mnode { height: 40px; } .mnode.item { height: 36px; } .mnode.root { height: 48px; }
270
+ }
132
271
  .keyrow { display: flex; gap: 6px; align-items: center; }
133
272
  .keyrow input { flex: 1; min-width: 0; font-family: ui-monospace, Menlo, monospace; font-size: 14px; }
134
273
  .keyrow .btn { min-height: 38px; padding: 6px 10px; white-space: nowrap; }
@@ -142,8 +281,9 @@
142
281
  .conn { border: 1px solid var(--line); border-radius: 12px; padding: 12px 14px; margin-bottom: 12px; }
143
282
  .conn h4 { margin: 0 0 4px; font-size: 15px; }
144
283
  .conn p { margin: 0 0 8px; font-size: 13px; color: var(--muted); }
145
- .conn pre { margin: 0; background: var(--bg); border-radius: 8px; padding: 8px 10px; font-size: 12.5px; white-space: pre-wrap; word-break: break-all; }
146
- .conn .copy { float: right; margin: -2px 0 6px 8px; min-height: 32px; padding: 4px 10px; font-size: 13px; }
284
+ .conn pre { margin: 0; background: var(--bg); border-radius: 8px; padding: 10px 12px; font-size: 12.5px; white-space: pre; overflow-x: auto; }
285
+ .conn-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
286
+ .conn .copy { min-height: 36px; padding: 4px 12px; font-size: 13px; flex: none; }
147
287
  .welcome { background: var(--accent-soft); color: var(--text); border-radius: 10px; padding: 10px 12px; font-size: 14px; margin-bottom: 14px; }
148
288
  .tool.grip { cursor: grab; display: none; }
149
289
  @media (hover: hover) and (pointer: fine) { .tool.grip { display: grid; } }
@@ -163,6 +303,9 @@
163
303
  /* A card sits on top of two action strips that show while it is dragged. */
164
304
  .swipe { position: relative; border-radius: 12px; overflow: hidden; scroll-margin-top: 90px; transition: height .25s ease, margin .25s ease, opacity .25s ease; }
165
305
  .swipe.gone { opacity: 0; }
306
+ /* Inside the card (the swipe wrapper clips anything outside it). */
307
+ .swipe.flash .card { animation: flash 2s ease; }
308
+ @keyframes flash { 0%, 55% { outline: 3px solid var(--accent); outline-offset: -3px; background: var(--accent-soft); } 100% { outline-color: transparent; } }
166
309
  .act { position: absolute; inset: 0; display: flex; align-items: center; padding: 0 22px; font-weight: 600; font-size: 14px; }
167
310
  .act.right { justify-content: flex-start; background: var(--star-soft); color: var(--star); }
168
311
  .act.left { justify-content: flex-end; background: var(--danger-soft); color: var(--danger); }
@@ -171,20 +314,33 @@
171
314
  .swipe.armed .act { filter: saturate(1.6); }
172
315
  .swipe.armed .act span { transform: scale(1.12); }
173
316
  .act span { transition: transform .15s ease; }
174
- .card { position: relative; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px;
317
+ .card { position: relative; background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 15px 18px; box-shadow: var(--shadow);
175
318
  touch-action: pan-y; user-select: none; -webkit-user-select: none; transition: transform .22s ease; }
176
319
  .card.dragging { transition: none; }
177
- .swipe:target .card { outline: 2px solid var(--accent); outline-offset: -2px; }
178
- .top { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; padding-right: 168px; }
179
- a.name { color: var(--text); font-weight: 650; font-size: 16px; text-decoration: none; }
320
+ .swipe:target .card, .card:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
321
+ .top { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; padding-right: 0; }
322
+ @media (hover: hover) and (pointer: fine) { .top { padding-right: 150px; } }
323
+ a.name { color: var(--text); font-weight: 700; font-size: 17px; text-decoration: none; letter-spacing: -.01em; }
180
324
  a.name:hover { color: var(--accent); }
181
- .badge { font-size: 12px; padding: 1px 8px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
325
+ .badge { font-size: 12px; padding: 1px 9px; border-radius: 99px; background: var(--accent-soft); color: var(--accent); white-space: nowrap; }
326
+ .badge.folder { background: color-mix(in srgb, var(--c) 14%, var(--panel)); color: var(--c); font-weight: 600; }
327
+ .rating { font-size: 12px; color: var(--muted); white-space: nowrap; }
328
+ .rating.must { color: var(--star); font-weight: 600; }
329
+ .rating .ico { width: 13px; height: 13px; fill: currentColor; vertical-align: -2px; margin-right: 2px; }
182
330
  .worth-must-see { color: var(--star); }
183
- .card p { margin: 6px 0; }
184
- .card ul { margin: 6px 0; padding-left: 20px; }
331
+ .card p { margin: 6px 0; font-size: 15px; color: var(--text); }
332
+ .card ul { margin: 6px 0; padding-left: 20px; color: var(--muted); font-size: 14px; line-height: 1.65; }
333
+ .card ul li::marker { color: color-mix(in srgb, var(--muted) 60%, transparent); }
334
+ .meta .tags { font-size: 12px; color: color-mix(in srgb, var(--muted) 80%, transparent); }
185
335
  .meta { color: var(--muted); font-size: 13px; display: flex; gap: 4px 12px; flex-wrap: wrap; }
186
336
  .flag { color: var(--warn); font-size: 13px; }
187
337
  .tools { position: absolute; top: 8px; right: 8px; display: flex; gap: 2px; }
338
+ /* Desktop: the tools appear on hover / focus; a starred card keeps its star. */
339
+ @media (hover: hover) and (pointer: fine) {
340
+ .card .tools .tool { opacity: 0; transition: opacity .15s ease; }
341
+ .card:hover .tools .tool, .card:focus-within .tools .tool, .card .tools .tool.on { opacity: 1; }
342
+ .hint.swipe-hint { display: none; }
343
+ }
188
344
  .tool { width: 40px; height: 40px; border: 0; border-radius: 10px; background: none; cursor: pointer; font-size: 18px; line-height: 1;
189
345
  display: grid; place-items: center; color: var(--muted); }
190
346
  .tool:hover, .tool:focus-visible { background: var(--bg); color: var(--text); }
@@ -196,11 +352,24 @@
196
352
  align-items: center; box-shadow: 0 6px 24px rgba(0,0,0,.25); transition: transform .25s ease; z-index: 5;
197
353
  width: max-content; max-width: min(520px, calc(100vw - 32px)); }
198
354
  .toast span { flex: 1; min-width: 0; }
199
- .toast.show { transform: translate(-50%, 0); }
355
+ .toast { visibility: hidden; transform: translate(-50%, calc(100% + 40px)); }
356
+ .toast.show { transform: translate(-50%, 0); visibility: visible; }
200
357
  .toast button { border: 0; background: none; color: var(--accent-soft); font-weight: 650; padding: 8px 10px; border-radius: 8px; cursor: pointer;
201
358
  min-height: 40px; white-space: nowrap; flex-shrink: 0; }
202
- @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .toast button { color: var(--accent); } }
359
+ /* Dark mode: a dark toast with a light Undo, not a white slab. */
360
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .toast { background: #2c2c2a; color: var(--text); border: 1px solid #3a3a37; }
361
+ :root:not([data-theme="light"]) .toast button { color: var(--accent); } }
362
+ :root[data-theme="dark"] .toast { background: #2c2c2a; color: var(--text); border: 1px solid #3a3a37; }
203
363
  :root[data-theme="dark"] .toast button { color: var(--accent); }
364
+ /* Dark mode: light branch fills need dark text on the map. */
365
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .mnode.folder.l1, :root:not([data-theme="light"]) .mnode.folder.l1 .tw,
366
+ :root:not([data-theme="light"]) .mnode.folder.l1 .opt { color: #121211; }
367
+ :root:not([data-theme="light"]) .mnode.folder.l1 .cnt { background: rgba(0,0,0,.18); color: #121211; }
368
+ :root:not([data-theme="light"]) .mnode.folder.l1.vacant, :root:not([data-theme="light"]) .mnode.folder.l1.vacant .tw,
369
+ :root:not([data-theme="light"]) .mnode.folder.l1.vacant .opt { color: var(--text); } }
370
+ :root[data-theme="dark"] .mnode.folder.l1, :root[data-theme="dark"] .mnode.folder.l1 .tw, :root[data-theme="dark"] .mnode.folder.l1 .opt { color: #121211; }
371
+ :root[data-theme="dark"] .mnode.folder.l1 .cnt { background: rgba(0,0,0,.18); color: #121211; }
372
+ :root[data-theme="dark"] .mnode.folder.l1.vacant, :root[data-theme="dark"] .mnode.folder.l1.vacant .tw, :root[data-theme="dark"] .mnode.folder.l1.vacant .opt { color: var(--text); }
204
373
 
205
374
  @media (max-width: 720px) {
206
375
  header { padding: 10px 16px; padding-top: max(10px, env(safe-area-inset-top)); gap: 8px 10px; }
@@ -211,6 +380,7 @@
211
380
  /* The sidebar becomes a drawer behind the ☰ button. */
212
381
  .menu { display: grid; }
213
382
  nav { position: fixed; top: 0; bottom: 0; left: 0; z-index: 10; width: min(300px, 84vw); max-height: none; border-right: 1px solid var(--line);
383
+ align-self: stretch; height: 100dvh; overscroll-behavior: contain;
214
384
  background: var(--panel); padding: max(12px, env(safe-area-inset-top)) 10px calc(20px + env(safe-area-inset-bottom));
215
385
  transform: translateX(-102%); visibility: hidden; box-shadow: 8px 0 30px rgba(0,0,0,.18);
216
386
  transition: transform .25s ease, visibility 0s linear .25s; /* hide only after sliding out */ }
@@ -227,10 +397,41 @@
227
397
  .tools { position: static; justify-content: flex-end; margin: 4px -6px -8px 0; }
228
398
  .card ul { padding-left: 18px; }
229
399
  }
230
- @media (prefers-reduced-motion: reduce) { .card, .swipe, .toast, nav, .scrim, nav .twist { transition: none; } }
400
+ @media (prefers-reduced-motion: reduce) { .card, .swipe, .toast, nav, .scrim, nav .twist, .mnode, .mnode .tw, .tool { transition: none !important; } }
231
401
  </style>
232
402
  </head>
233
403
  <body>
404
+ <svg width="0" height="0" style="position:absolute" aria-hidden="true">
405
+ <defs>
406
+ <symbol id="i-all" viewBox="0 0 24 24"><path d="M3 12h5l2 3h4l2-3h5M5.5 5h13L21 12v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6z"/></symbol>
407
+ <symbol id="i-star" viewBox="0 0 24 24"><path d="M12 3.2l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17.2l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></symbol>
408
+ <symbol id="i-trash" viewBox="0 0 24 24"><path d="M4 7h16M9 7V4.5h6V7M6.5 7l.9 12.5a1.5 1.5 0 0 0 1.5 1.5h6.2a1.5 1.5 0 0 0 1.5-1.5L17.5 7M10 11v6M14 11v6"/></symbol>
409
+ <symbol id="i-note" viewBox="0 0 24 24"><path d="M14 3H6.5A1.5 1.5 0 0 0 5 4.5v15A1.5 1.5 0 0 0 6.5 21h11a1.5 1.5 0 0 0 1.5-1.5V8zM14 3v5h5M8.5 13h7M8.5 17h5"/></symbol>
410
+ <symbol id="i-map" viewBox="0 0 24 24"><circle cx="5" cy="12" r="2.5"/><circle cx="19" cy="5" r="2.2"/><circle cx="19" cy="12" r="2.2"/><circle cx="19" cy="19" r="2.2"/><path d="M7.5 12h9M7.2 11c3-1 5.6-4.6 9.6-5.6M7.2 13c3 1 5.6 4.6 9.6 5.6"/></symbol>
411
+ <symbol id="i-folder" viewBox="0 0 24 24"><path d="M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2.5h7.5A2.5 2.5 0 0 1 21 10v7.5a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z"/></symbol>
412
+ <symbol id="i-move" viewBox="0 0 24 24"><path d="M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2.5h7.5A2.5 2.5 0 0 1 21 10v7.5a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5zM10 14h6M13.5 11.5 16 14l-2.5 2.5"/></symbol>
413
+ <symbol id="i-grip" viewBox="0 0 24 24"><g fill="currentColor" stroke="none"><circle cx="9" cy="6" r="1.4"/><circle cx="15" cy="6" r="1.4"/><circle cx="9" cy="12" r="1.4"/><circle cx="15" cy="12" r="1.4"/><circle cx="9" cy="18" r="1.4"/><circle cx="15" cy="18" r="1.4"/></g></symbol>
414
+ <symbol id="i-plug" viewBox="0 0 24 24"><path d="M9 2.5V7M15 2.5V7M6.5 7h11v4a5.5 5.5 0 0 1-11 0zM12 16.5V21.5"/></symbol>
415
+ <symbol id="i-gear" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M12 2.5v2.6M12 18.9v2.6M4.6 4.6l1.8 1.8M17.6 17.6l1.8 1.8M2.5 12h2.6M18.9 12h2.6M4.6 19.4l1.8-1.8M17.6 6.4l1.8-1.8"/></symbol>
416
+ <symbol id="i-download" viewBox="0 0 24 24"><path d="M12 3.5v11.5M7 10.5l5 5 5-5M4.5 20.5h15"/></symbol>
417
+ <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>
418
+ <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>
419
+ <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>
420
+ <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>
421
+ <symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></symbol>
422
+ <symbol id="i-minus" viewBox="0 0 24 24"><path d="M5 12h14"/></symbol>
423
+ <symbol id="i-fit" viewBox="0 0 24 24"><path d="M8.5 3.5h-5v5M15.5 3.5h5v5M8.5 20.5h-5v-5M15.5 20.5h5v-5"/></symbol>
424
+ <symbol id="i-expand" viewBox="0 0 24 24"><path d="M7 15l5 5 5-5M7 9l5-5 5 5"/></symbol>
425
+ <symbol id="i-collapse" viewBox="0 0 24 24"><path d="M7 20l5-5 5 5M7 4l5 5 5-5"/></symbol>
426
+ <symbol id="i-dots" viewBox="0 0 24 24"><g fill="currentColor" stroke="none"><circle cx="5.5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="18.5" cy="12" r="1.6"/></g></symbol>
427
+ <symbol id="i-both" viewBox="0 0 24 24"><rect x="9" y="9.5" width="6" height="5" rx="1.5"/><circle cx="3.5" cy="5.5" r="1.8"/><circle cx="3.5" cy="18.5" r="1.8"/><circle cx="20.5" cy="5.5" r="1.8"/><circle cx="20.5" cy="18.5" r="1.8"/><path d="M9 11.5C7 11.5 6.5 6 5.3 5.6M9 12.5C7 12.5 6.5 18 5.3 18.4M15 11.5c2 0 2.5-5.5 3.7-5.9M15 12.5c2 0 2.5 5.5 3.7 5.9"/></symbol>
428
+ <symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></symbol>
429
+ <symbol id="i-link" viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-9 9M18 14v4.5a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 4 18.5v-11A1.5 1.5 0 0 1 5.5 6H10"/></symbol>
430
+ <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>
431
+ <symbol id="i-eye" viewBox="0 0 24 24"><path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="3"/></symbol>
432
+ </defs>
433
+ </svg>
434
+ <a class="skip" href="#list">Skip to the cards</a>
234
435
  <header>
235
436
  <button id="menu" class="menu" type="button" aria-controls="nav" aria-expanded="false">
236
437
  <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden="true"><path d="M3 6h16M3 11h16M3 16h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
@@ -238,20 +439,21 @@
238
439
  <h1 class="brand"><img src="/favicon.svg" alt="" width="26" height="26">driftnet</h1>
239
440
  <span class="stats" id="stats"></span>
240
441
  <input id="q" class="search" type="search" enterkeyhint="search">
442
+ <button id="lock" class="lock" type="button" hidden></button>
241
443
  <button id="lang" class="lang" type="button"></button>
242
444
  </header>
243
445
  <button id="crumb" class="crumb" type="button" aria-controls="nav"></button>
244
446
  <div class="scrim" id="scrim"></div>
245
447
  <div class="layout">
246
448
  <nav id="nav"></nav>
247
- <main id="list" aria-live="polite"></main>
449
+ <main id="list" tabindex="-1"></main>
248
450
  </div>
249
- <dialog id="folder-dlg">
451
+ <dialog id="folder-dlg" aria-labelledby="fd-title">
250
452
  <form id="folder-form" method="dialog">
251
453
  <h3 id="fd-title"></h3>
252
454
  <p class="dlg-error" id="fd-error"></p>
253
455
  <label><span id="fd-name-l"></span><input id="fd-name" maxlength="60" autocomplete="off"></label>
254
- <label><span id="fd-desc-l"></span><textarea id="fd-desc" rows="2" maxlength="300"></textarea></label>
456
+ <label><span id="fd-desc-l"></span><textarea id="fd-desc" rows="3" maxlength="300"></textarea></label>
255
457
  <label><span id="fd-parent-l"></span><select id="fd-parent"></select></label>
256
458
  <div class="dlg-actions">
257
459
  <button class="btn danger" id="fd-delete" type="button"></button><span class="spacer"></span>
@@ -259,12 +461,13 @@
259
461
  </div>
260
462
  </form>
261
463
  </dialog>
262
- <dialog id="move-dlg">
464
+ <dialog id="move-dlg" aria-labelledby="mv-title">
263
465
  <h3 id="mv-title"></h3>
264
- <div class="pick" id="mv-list"></div>
466
+ <input id="mv-filter" class="search" style="max-width:none;width:100%;margin:0 0 8px" type="search" autocomplete="off">
467
+ <div class="pick" id="mv-list" role="listbox"></div>
265
468
  <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="mv-cancel" type="button"></button></div>
266
469
  </dialog>
267
- <dialog id="settings-dlg" class="wide">
470
+ <dialog id="settings-dlg" aria-labelledby="st-title" class="wide">
268
471
  <form id="settings-form" method="dialog">
269
472
  <h3 id="st-title"></h3>
270
473
  <p class="dlg-error" id="st-error"></p>
@@ -273,12 +476,32 @@
273
476
  <button class="btn" id="st-cancel" type="button"></button><button class="btn primary" id="st-save" type="submit"></button></div>
274
477
  </form>
275
478
  </dialog>
276
- <dialog id="connect-dlg" class="wide">
479
+ <dialog id="peek-dlg" class="peek">
480
+ <div id="pk-body"></div>
481
+ <div class="dlg-actions peek-actions">
482
+ <a class="btn primary" id="pk-open" target="_blank" rel="noopener noreferrer"></a>
483
+ <button class="btn" type="button" id="pk-move"></button>
484
+ <button class="btn" type="button" id="pk-list"></button>
485
+ <span class="spacer"></span><button class="btn" type="button" id="pk-close"></button>
486
+ </div>
487
+ </dialog>
488
+ <dialog id="login-dlg" aria-labelledby="lg-title">
489
+ <form id="login-form" method="dialog">
490
+ <h3 id="lg-title"></h3>
491
+ <p class="dlg-error" id="lg-error"></p>
492
+ <label><span id="lg-label"></span><input id="lg-pw" type="password" autocomplete="current-password"></label>
493
+ <p class="hint" id="lg-help"></p>
494
+ <details class="hint"><summary id="lg-adv-s"></summary><p id="lg-adv"></p></details>
495
+ <div class="dlg-actions"><span class="spacer"></span>
496
+ <button class="btn" id="lg-cancel" type="button"></button><button class="btn primary" id="lg-ok" type="submit"></button></div>
497
+ </form>
498
+ </dialog>
499
+ <dialog id="connect-dlg" aria-labelledby="cx-title" class="wide">
277
500
  <h3 id="cx-title"></h3>
278
501
  <div class="set-scroll" id="cx-body"></div>
279
502
  <div class="dlg-actions"><span class="spacer"></span><button class="btn" id="cx-close" type="button"></button></div>
280
503
  </dialog>
281
- <dialog id="note-dlg">
504
+ <dialog id="note-dlg" aria-labelledby="in-title">
282
505
  <form id="note-form" method="dialog">
283
506
  <h3 id="in-title"></h3>
284
507
  <label><span id="in-help"></span><textarea id="in-text" rows="5" maxlength="5000"></textarea></label>
@@ -297,59 +520,77 @@
297
520
  </div>
298
521
  </form>
299
522
  </dialog>
523
+ <div class="pickbar" id="pickbar" role="status" hidden><span id="pick-text"></span><button type="button" id="pick-cancel"></button></div>
300
524
  <div class="toast" id="toast" role="status"><span id="toast-text"></span><button id="toast-undo" type="button"></button></div>
301
525
  <script>
302
526
  const STRINGS = {
303
527
  en: {
304
528
  search: "Search tools, tags, links…", all: "All", favorites: "Favorites", trash: "Trash", any: "Any",
305
529
  kind: "Kind", switchTo: "中文", nav: "Views and categories",
306
- stats: (n, s) => `${n} items · shared ${s}×`, shared: (n) => `shared ${n}×`,
307
- empty: "Nothing here yet — drop a link in your chat.", emptyFav: "No favorites yet — swipe a card right, or tap ☆.",
530
+ stats: (n, s) => `${n} ${n === 1 ? "item" : "items"} · shared ${s}×`, shared: (n) => `shared ${n}×`,
531
+ empty: "Nothing here yet — drop a link in your chat.", emptyFav: "No favorites yet — swipe a card right, or tap the star.",
308
532
  emptyTrash: "The trash is empty.", hint: "Swipe right to favorite, left to remove.", hintTrash: "Swipe right to restore.",
309
533
  kinds: { repo: "Repos", product: "Products", video: "Videos", article: "Articles", post: "Posts", other: "Other" },
310
- worth: { skip: "skip", low: "low", normal: "worth a look", "must-see": "★ must-see" },
534
+ kind1: { repo: "Repo", product: "Product", video: "Video", article: "Article", post: "Post", other: "Other" },
535
+ worth: { skip: "skip", low: "low", normal: "worth a look", "must-see": "must-see" },
311
536
  flags: { injection: "prompt injection", "hidden-chars": "hidden characters", "low-reputation": "low-reputation source" },
312
- pending: "⏳ waiting for a summary", enrichedBy: (a) => `summary by ${a}`,
537
+ pending: "waiting for a summary", noModel: "no summary — no model set up", enrichedBy: (a) => `summary by ${a}`,
313
538
  favorite: "Add to favorites", unfavorite: "Remove from favorites", remove: "Move to trash", restore: "Restore",
314
- swipeFav: "☆ Favorite", swipeUnfav: "★ Unfavorite", swipeTrash: "Remove 🗑", swipeRestore: "↩ Restore",
315
- removed: (n) => `“${n}” moved to the trash`, restored: (n) => `“${n}” restored`, faved: (n) => `★ “${n}” added to favorites`,
539
+ swipeFav: "Favorite", swipeUnfav: "Unfavorite", swipeTrash: "Remove", swipeRestore: "Restore",
540
+ removed: (n) => `“${n}” moved to the trash`, restored: (n) => `“${n}” restored`, faved: (n) => `“${n}” added to favorites`,
316
541
  undo: "Undo", tokenPrompt: "This catalogue is private. Enter the admin password, or a read-only share key to just look.", tokenSave: "Open",
317
542
  tokenToEdit: "You're viewing with a read-only link. To change things, enter the admin password once.", back: "Back",
318
543
  failed: "Couldn't save — check your connection.", menu: "Menu", close: "Close menu", showing: "Showing:",
319
544
  folders: "Folders", newFolder: "New folder", newSub: "New folder inside", editFolder: "Edit folder", folderName: "Name",
320
545
  folderDesc: "What goes here? (driftnet's AI reads this to sort new links)", folderParent: "Inside", topLevel: "— Top level —",
321
- save: "Save", cancel: "Cancel", del: "Delete folder", delSure: "Delete — its links move up",
546
+ save: "Save", cancel: "Cancel", del: "Delete folder", delSure: "Delete? Links move up",
322
547
  moveTo: "Move to…", moveTitle: (n) => `Move “${n}” to`, moved: (n, f) => `Moved “${n}” to ${f}`, expand: "Show sub-folders",
323
548
  dragHint: "Drag onto a folder in the sidebar", foundIn: "Found in this post:", folderMoved: (n, f) => `“${n}” is now inside ${f}`,
324
549
  topLevelShort: "the top level",
325
- notes: "Notes", note: "Note", addNote: "📝 Add a note", editNote: "📝 Edit note", noteFor: (n) => `Note on “${n}”`,
326
- noteHelp: "Only for you: what you thought, whether you tried it…", newNote: "+ New note", noteTitle: "Title",
550
+ map: "Mind map", mapHint: "Tap a folder to open it, tap a card to preview it. To file a card: drag it onto a folder — on a phone, hold it a moment, let go, then tap the folder. ⋯ renames a folder.",
551
+ a11yFolder: (n, c) => `Folder ${n}, ${c} cards`, a11yCard: (n) => `Card ${n}`,
552
+ expandAll: "Expand all", collapseAll: "Collapse all", zoomIn: "Zoom in", zoomOut: "Zoom out", fit: "Fit", openCard: "Open card",
553
+ layoutBoth: "Both sides", layoutRight: "Right side", layoutHelp: "Switch between branches on both sides (XMind) and all to the right",
554
+ zoom: "Zoom", gotIt: "Got it", more: (n) => `+${n} more`, mapSearch: (q) => `Highlighting “${q}”`, openLink: "Open link", showInList: "Show in the list", close: "Close",
555
+ needPassword: "Changing things needs the admin password.",
556
+ notes: "Notes", note: "Note", addNote: "Add a note", editNote: "Edit note", noteFor: (n) => `Note on “${n}”`,
557
+ noteHelp: "Only for you: what you thought, whether you tried it…", newNote: "New note", noteTitle: "Title",
327
558
  noteBody: "Markdown. Write #12 to link card 12.", delNote: "Delete note", delNoteSure: "Really delete?", untitled: "Untitled",
328
- emptyNotes: "No notes yet. Notes can link cards: write #12.", exportMd: "⬇ Export Markdown", exportVault: "⬇ Export for Obsidian / Notion",
329
- saved: "Saved", settings: "⚙ Settings",
559
+ emptyNotes: "No notes yet. Notes can link cards: write #12.", exportMd: "Download a backup (Markdown)", exportVault: "Download for Obsidian / Notion",
560
+ saved: "Saved", settings: "Settings", pickedUp: (n) => `Picked up “${n}” — tap the folder it goes into`, alreadyThere: "It's already in that folder",
561
+ readOnlyNudge: "You can only look here — tap Unlock at the top to change things", filterFolders: "Type to find a folder…", undoHint: "z undoes",
562
+ addLink: "Add", addPlaceholder: "Paste a link to a tool, post or video…", added: "Saved — sorting it now",
563
+ shortcuts: "Keys: j / k next / previous · f favorite · m move · n note · # trash · / search · g m mind map",
330
564
  st: {
331
- title: "Settings", save: "Save", welcome: "Welcome! Pick a model below (or none: Jev and the built-in rules still sort links), then drop a link in.",
565
+ title: "Settings", save: "Save", welcome: "Welcome! Pick a model below to get summaries — or none: links are still sorted into folders, just without a summary. Then paste a link.",
332
566
  display: "This browser", sort: "Order", sorts: { best: "Best first", newest: "Newest first", shared: "Most shared first" },
333
567
  compact: "Compact cards (one line each)", tags: "Show tags", said: "Show what people said in chat",
334
568
  theme: "Theme", themes: { auto: "Follow the system", light: "Light", dark: "Dark" },
335
569
  model: "Model & classifier", language: "Language & chat replies", rules: "Your rules",
336
570
  plugins: "Plugins", pluginsNone: (dir) => `No plugins. Put .js files in ${dir} — see examples/plugins in the repo.`,
337
- status: (e) => `Now: sorting by ${({ jev: "Jev", llm: "the model", heuristic: "built-in rules" })[e.judge] ?? e.judge}, summaries by ${e.summarizer === "off" ? "nobody (off)" : e.summarizer}`, keep: "set — leave empty to keep", unset: "not set",
571
+ 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",
338
572
  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.",
339
- savedServer: "Saved — already in effect",
573
+ savedServer: "Saved — already in effect", chat: "Chat replies", genCopied: "New password generated and copied — press Save to keep it",
574
+ tabGeneral: "General", tabAccess: "Access", tabAi: "AI",
575
+ accessStatus: (pw, key, url) => `Password: ${pw === "✓" ? "set" : "not set"} · Share key: ${key === "✓" ? "made" : "none"} · Public URL: ${url === "—" ? "off" : url}`,
340
576
  access: "Access & connections",
341
- password: "Admin password", passwordHelp: "Needed to add links, change settings and let agents write. At least 8 characters, no spaces.",
577
+ password: "Admin password", passwordHelp: "Once set, adding links, changing settings and agents that write all need it. At least 8 characters, no spaces.",
342
578
  generate: "Generate", show: "Show", hide: "Hide", copy: "Copy", copied: "Copied",
343
579
  strength: { weak: "Weak — easy to guess. Fine on this computer only; don't open a public URL with it.", ok: "OK", strong: "Strong" },
344
580
  passwordWarn: "Anyone with this password can add, move and delete in your catalogue. Don't reuse a password from elsewhere, and don't paste it into public chats.",
345
581
  accessMode: "Who can read", accessChoices: { "": "Anyone who can reach this page", public: "Anyone who can reach this page", private: "Only with the password or the share key" },
346
- shareKey: "Read-only share key", shareKeyHelp: "For AIs that can only open links (ChatGPT, Grok, Claude.ai): they can read your catalogue, nothing more. If it leaks, make a new one.",
582
+ shareKey: "Read-only share key", shareKeyHelp: "For AIs that can only open links (ChatGPT, Grok, Claude.ai): they can read your catalogue (notes included), nothing more. If it leaks, make a new one.",
347
583
  newShareKey: "New key", noShareKey: "No share key yet.",
348
584
  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.",
349
585
  tunnelOn: "Open a public URL", tunnelOff: "Close it", tunnelNeedsPassword: "Save an admin password first.",
350
586
  tunnelInstall: "Needs cloudflared (driftnet never downloads it for you):", tunnelPrivate: "Opening it switches reading to “only with the password or the share key”.",
351
587
  tunnelStarting: "Starting the tunnel… (up to 30 s)", saveFirst: "Save first, then open the public URL.",
352
- connect: "🔌 Connect an AI",
588
+ connect: "Connect an AI",
589
+ login: "Enter admin password", logout: "Log out on this device", loginTitle: "Unlock editing", loginOk: "Unlock", unlocked: "Unlocked — you can edit now", unlockShort: "Unlock",
590
+ loginWrong: "That password didn't work — try again.", viewOnly: "View only · Unlock",
591
+ loginHelp: "Type this driftnet's password — usually from whoever set it up. Without it you can still look at everything.",
592
+ loginAdvanced: "Forgot it (you set it up)? Open driftnet on the computer it runs on — Settings there sets a new one. On a server: From your computer run ssh -L PORT:127.0.0.1:PORT <server> and open http://localhost:PORT.",
593
+ keyWrong: "That's neither the admin password nor a share key.",
353
594
  labels: {
354
595
  DRIFTNET_LLM_PROVIDER: ["Model provider", "Summaries. None: links are still sorted, only without a summary."],
355
596
  DRIFTNET_LLM_MODEL: ["Model", "e.g. claude-haiku-5-5, gpt-5-mini, gemini-3.8-flash, qwen3"],
@@ -361,7 +602,7 @@
361
602
  GITHUB_TOKEN: ["GitHub token", "Optional: GitHub lookups go from 60 to 5000 an hour"],
362
603
  DRIFTNET_LANGUAGE: ["Summary language", "English, Traditional Chinese (Taiwan), Japanese…"],
363
604
  DRIFTNET_LOCALE: ["Bot language", ""],
364
- DRIFTNET_REPLY: ["Chat replies", ""],
605
+ DRIFTNET_REPLY: ["How the bot replies", ""],
365
606
  DRIFTNET_PUBLIC_URL: ["This page's public URL", "Replies link here, e.g. https://driftnet.example.com"],
366
607
  DRIFTNET_SUMMARY_RULES: ["Extra rules for summaries", "e.g. Say whether it's free. Mention if it needs a GPU."],
367
608
  DRIFTNET_BLOCK_DOMAINS: ["Never catalogue these domains", "Comma or space separated, e.g. example.com, spam.io"],
@@ -379,31 +620,40 @@
379
620
  search: "搜尋工具、標籤、連結…", all: "全部", favorites: "最愛", trash: "垃圾桶", any: "不限",
380
621
  kind: "類型", switchTo: "EN", nav: "檢視與分類",
381
622
  stats: (n, s) => `${n} 則 · 分享 ${s} 次`, shared: (n) => `分享 ${n} 次`,
382
- empty: "還沒有內容,把連結丟進聊天室吧。", emptyFav: "還沒有最愛,把卡片往右滑或按 ☆。",
623
+ empty: "還沒有內容,把連結丟進聊天室吧。", emptyFav: "還沒有最愛,把卡片往右滑或按星號。",
383
624
  emptyTrash: "垃圾桶是空的。", hint: "往右滑加入最愛,往左滑移到垃圾桶。", hintTrash: "往右滑還原。",
384
625
  kinds: { repo: "程式庫", product: "產品", video: "影片", article: "文章", post: "貼文", other: "其他" },
385
- worth: { skip: "略過", low: "普通", normal: "值得看", "must-see": "★ 必看" },
626
+ worth: { skip: "略過", low: "普通", normal: "值得看", "must-see": "必看" },
386
627
  flags: { injection: "提示詞注入", "hidden-chars": "隱藏字元", "low-reputation": "低信譽來源" },
387
- pending: "⏳ 等待摘要", enrichedBy: (a) => `由 ${a} 整理`,
628
+ pending: "等待摘要", noModel: "沒有摘要(未設定模型)", enrichedBy: (a) => `由 ${a} 整理`,
388
629
  favorite: "加入最愛", unfavorite: "移出最愛", remove: "移到垃圾桶", restore: "還原",
389
- swipeFav: "☆ 加入最愛", swipeUnfav: "★ 移出最愛", swipeTrash: "移到垃圾桶 🗑", swipeRestore: "↩ 還原",
390
- removed: (n) => `已將「${n}」移到垃圾桶`, restored: (n) => `已還原「${n}」`, faved: (n) => `★ 已將「${n}」加入最愛`,
630
+ swipeFav: "加入最愛", swipeUnfav: "移出最愛", swipeTrash: "移到垃圾桶", swipeRestore: "還原",
631
+ removed: (n) => `已將「${n}」移到垃圾桶`, restored: (n) => `已還原「${n}」`, faved: (n) => `已將「${n}」加入最愛`,
391
632
  undo: "復原", tokenPrompt: "這份清單是私人的。請輸入管理密碼;只想瀏覽的話,輸入唯讀分享碼也可以。", tokenSave: "開啟",
392
633
  tokenToEdit: "你是用唯讀連結在瀏覽。要修改的話,請輸入一次管理密碼。", back: "返回",
393
634
  failed: "沒有存成功,請檢查網路。", menu: "選單", close: "關閉選單", showing: "目前顯示:",
394
635
  folders: "資料夾", newFolder: "新資料夾", newSub: "在裡面新增資料夾", editFolder: "編輯資料夾", folderName: "名稱",
395
636
  folderDesc: "放什麼?(driftnet 的 AI 會照這段說明把新連結分進來)", folderParent: "放在", topLevel: "— 最上層 —",
396
- save: "儲存", cancel: "取消", del: "刪除資料夾", delSure: "確定刪除(內容會移到上一層)",
637
+ save: "儲存", cancel: "取消", del: "刪除資料夾", delSure: "確定刪除?內容移到上一層",
397
638
  moveTo: "移動到…", moveTitle: (n) => `把「${n}」移動到`, moved: (n, f) => `已將「${n}」移到 ${f}`, expand: "展開子資料夾",
398
639
  dragHint: "拖到側邊欄的資料夾", foundIn: "從這篇找到:", folderMoved: (n, f) => `「${n}」已移到 ${f} 底下`,
399
640
  topLevelShort: "最上層",
400
- notes: "筆記", note: "筆記", addNote: "📝 加筆記", editNote: "📝 改筆記", noteFor: (n) => `「${n}」的筆記`,
401
- noteHelp: "只有你看得到:心得、試用結果、要注意的地方…", newNote: "+ 新筆記", noteTitle: "標題",
641
+ map: "樹狀圖", mapHint: "點資料夾展開,點卡片預覽。整理卡片:把它拖到資料夾上;手機上按住卡片一下、放開,再點要放進去的資料夾。按 ⋯ 可以改資料夾名稱。",
642
+ a11yFolder: (n, c) => `資料夾 ${n},${c} 張卡片`, a11yCard: (n) => `卡片 ${n}`,
643
+ expandAll: "全部展開", collapseAll: "全部收合", zoomIn: "放大", zoomOut: "縮小", fit: "符合畫面", openCard: "開啟卡片",
644
+ layoutBoth: "兩側展開", layoutRight: "往右展開", layoutHelp: "切換:分支分佈在兩側(XMind 預設)或全部往右",
645
+ zoom: "縮放", gotIt: "知道了", more: (n) => `還有 ${n} 張`, mapSearch: (q) => `標亮「${q}」`, openLink: "開啟連結", showInList: "在清單中查看", close: "關閉",
646
+ needPassword: "要修改需要管理密碼。",
647
+ notes: "筆記", note: "筆記", addNote: "加筆記", editNote: "改筆記", noteFor: (n) => `「${n}」的筆記`,
648
+ noteHelp: "只有你看得到:心得、試用結果、要注意的地方…", newNote: "新筆記", noteTitle: "標題",
402
649
  noteBody: "支援 Markdown。寫 #12 就會連到第 12 張卡片。", delNote: "刪除筆記", delNoteSure: "確定刪除?", untitled: "未命名",
403
- emptyNotes: "還沒有筆記。筆記可以連到卡片:寫 #12。", exportMd: "⬇ 匯出 Markdown", exportVault: "⬇ 匯出到 Obsidian/Notion",
404
- saved: "已儲存", settings: "⚙ 設定",
650
+ emptyNotes: "還沒有筆記。筆記可以連到卡片:寫 #12。", exportMd: "下載備份(Markdown)", exportVault: "下載給 Obsidian/Notion",
651
+ saved: "已儲存", settings: "設定", pickedUp: (n) => `已拿起「${n}」,點要放進去的資料夾`, alreadyThere: "它已經在這個資料夾裡了",
652
+ readOnlyNudge: "目前只能看。要修改,請點上方的「解鎖」", filterFolders: "輸入文字找資料夾…", undoHint: "按 z 復原",
653
+ addLink: "收錄", addPlaceholder: "貼上工具、貼文或影片的連結…", added: "收到,正在整理",
654
+ shortcuts: "快捷鍵:j/k 下一張/上一張 · f 最愛 · m 移動 · n 筆記 · # 垃圾桶 · / 搜尋 · g m 樹狀圖",
405
655
  st: {
406
- title: "設定", save: "儲存", welcome: "歡迎!先在下面選一個模型(不選也可以:Jev 和內建規則一樣會分類),然後丟一個連結進來試試。",
656
+ title: "設定", save: "儲存", welcome: "歡迎!在下面選一個模型就會有摘要;不選也可以,連結一樣會分進資料夾,只是沒有摘要。接著貼一個連結試試看。",
407
657
  display: "這個瀏覽器", sort: "排序", sorts: { best: "值得看的在前", newest: "最新的在前", shared: "最多人分享的在前" },
408
658
  compact: "精簡卡片(每張一行)", tags: "顯示標籤", said: "顯示大家在聊天室說的話",
409
659
  theme: "外觀", themes: { auto: "跟系統一樣", light: "淺色", dark: "深色" },
@@ -411,20 +661,27 @@
411
661
  plugins: "外掛", pluginsNone: (dir) => `沒有外掛。把 .js 檔放進 ${dir},範例在 repo 的 examples/plugins。`,
412
662
  status: (e) => `目前:分類用 ${({ jev: "Jev", llm: "模型", heuristic: "內建規則" })[e.judge] ?? e.judge},摘要用 ${e.summarizer === "off" ? "(未開啟)" : e.summarizer}`, keep: "已設定,留空就不變", unset: "未設定",
413
663
  locked: "由執行環境設定", forbidden: "伺服器設定只能在執行 driftnet 的那台電腦上改(或設定 DRIFTNET_TOKEN)。顯示設定照常可用。",
414
- savedServer: "已儲存,馬上生效",
664
+ savedServer: "已儲存,馬上生效", chat: "聊天室回覆", genCopied: "已產生新密碼並複製,按「儲存」才會生效",
665
+ tabGeneral: "一般", tabAccess: "存取", tabAi: "AI",
666
+ accessStatus: (pw, key, url) => `密碼:${pw === "✓" ? "已設定" : "未設定"} · 分享碼:${key === "✓" ? "已產生" : "沒有"} · 公開網址:${url === "—" ? "關閉" : url}`,
415
667
  access: "存取與連線",
416
- password: "管理密碼", passwordHelp: "新增連結、改設定、讓 agent 寫入都需要它。至少 8 個字元,不能有空白。",
668
+ password: "管理密碼", passwordHelp: "設定之後,新增連結、改設定、agent 寫入都需要它。至少 8 個字元,不能有空白。",
417
669
  generate: "產生", show: "顯示", hide: "隱藏", copy: "複製", copied: "已複製",
418
670
  strength: { weak: "弱:很容易被猜到。只在這台電腦用還可以,不要拿它開公開網址。", ok: "普通", strong: "強" },
419
671
  passwordWarn: "知道這組密碼的人,可以新增、移動、刪除你清單裡的東西。不要沿用其他網站的密碼,也不要貼到公開的聊天室。",
420
672
  accessMode: "誰可以讀", accessChoices: { "": "連得到這個網頁的人都可以", public: "連得到這個網頁的人都可以", private: "要有密碼或分享碼才能讀" },
421
- shareKey: "唯讀分享碼", shareKeyHelp: "給只會開連結的 AI(ChatGPT、Grok、Claude 網頁版):只能讀你的清單,不能改。外流的話重產一組就好。",
673
+ shareKey: "唯讀分享碼", shareKeyHelp: "給只會開連結的 AI(ChatGPT、Grok、Claude 網頁版):只能讀你的清單(包含筆記),不能改。外流的話重產一組就好。",
422
674
  newShareKey: "重新產生", noShareKey: "還沒有分享碼。",
423
675
  tunnel: "給雲端 AI 的公開網址", tunnelHelp: "Claude 網頁版、ChatGPT、Grok 和其他機器上的 agent 連不到 localhost。這會透過 Cloudflare(免帳號)開一個臨時的 https 網址;每次都不一樣,driftnet 關掉就跟著關。",
424
676
  tunnelOn: "開啟公開網址", tunnelOff: "關閉", tunnelNeedsPassword: "要先儲存管理密碼。",
425
677
  tunnelInstall: "需要 cloudflared(driftnet 不會自動幫你下載):", tunnelPrivate: "開啟後,「誰可以讀」會改成要有密碼或分享碼。",
426
678
  tunnelStarting: "正在開通道…(最多 30 秒)", saveFirst: "先按儲存,再開公開網址。",
427
- connect: "🔌 連接 AI",
679
+ connect: "連接 AI",
680
+ login: "輸入管理密碼", logout: "在這台裝置登出", loginTitle: "解鎖編輯", loginOk: "解鎖", unlocked: "已解鎖,現在可以編輯了", unlockShort: "解鎖",
681
+ loginWrong: "密碼不對,再試一次。", viewOnly: "只能看 · 解鎖編輯",
682
+ loginHelp: "輸入這個 driftnet 的密碼,通常是架設它的人給你的。沒有密碼也能看所有內容,只是不能修改。",
683
+ loginAdvanced: "密碼是你自己設的但忘了?到跑 driftnet 的那台電腦打開網頁,設定裡可以直接設新的。跑在伺服器上的話:在你的電腦執行 ssh -L PORT:127.0.0.1:PORT <伺服器> 再打開 http://localhost:PORT。",
684
+ keyWrong: "這不是管理密碼,也不是分享碼。",
428
685
  labels: {
429
686
  DRIFTNET_LLM_PROVIDER: ["模型來源", "用來寫摘要。選「不使用」也會分類,只是沒有摘要。"],
430
687
  DRIFTNET_LLM_MODEL: ["模型", "例如 claude-haiku-5-5、gpt-5-mini、gemini-3.8-flash、qwen3"],
@@ -436,7 +693,7 @@
436
693
  GITHUB_TOKEN: ["GitHub token", "選填:GitHub 查詢上限從每小時 60 次變 5000 次"],
437
694
  DRIFTNET_LANGUAGE: ["摘要語言", "English、Traditional Chinese (Taiwan)、Japanese…"],
438
695
  DRIFTNET_LOCALE: ["機器人語言", ""],
439
- DRIFTNET_REPLY: ["聊天室回覆", ""],
696
+ DRIFTNET_REPLY: ["機器人怎麼回覆", ""],
440
697
  DRIFTNET_PUBLIC_URL: ["這個網頁的公開網址", "回覆裡的連結會指到這裡,例如 https://driftnet.example.com"],
441
698
  DRIFTNET_SUMMARY_RULES: ["摘要的額外規則", "例如:說明是否免費。需要 GPU 的話要提到。"],
442
699
  DRIFTNET_BLOCK_DOMAINS: ["不要收錄的網域", "用逗號或空白分隔,例如 example.com, spam.io"],
@@ -462,6 +719,15 @@
462
719
  let catLabels = {};
463
720
  let folders = [];
464
721
  let notes = [];
722
+ /** admin: may change things; reader: browsing with a share key (see /api/ui). */
723
+ let role = "admin";
724
+ let serverPort = 8787;
725
+ let summaries = true;
726
+ /** Something needs the password: ask in a dialog that checks it, and keep whatever the user was doing. */
727
+ function needAdmin() {
728
+ toast(T().needPassword);
729
+ openLogin();
730
+ }
465
731
  let items = [];
466
732
  // Folders the reader closed in the tree; remembered in this browser.
467
733
  const collapsed = new Set((() => { try { return JSON.parse(store.get("driftnet-collapsed") ?? "[]"); } catch { return []; } })());
@@ -469,6 +735,15 @@
469
735
  const subtotal = (f) => f.count + kids(f.id).reduce((n, c) => n + subtotal(c), 0);
470
736
  const folderById = (id) => folders.find((f) => f.id === id);
471
737
  const T = () => STRINGS[locale] ?? STRINGS.en;
738
+ /** An icon from the sprite at the top of <body>. */
739
+ const ic = (name, cls = "") => `<svg class="ico ${cls}" aria-hidden="true"><use href="#i-${name}"/></svg>`;
740
+ /** A folder's branch colour: the top-level folder it sits under decides it. */
741
+ function folderColor(id) {
742
+ let f = folderById(id);
743
+ while (f?.parent && folderById(f.parent)) f = folderById(f.parent);
744
+ const n = Math.max(0, kids(null).findIndex((x) => x.id === f?.id));
745
+ return `var(--m${(n % 8) + 1})`;
746
+ }
472
747
  const catLabel = (id) => catLabels[id]?.[locale] ?? id;
473
748
 
474
749
  // Private instances need the token on every request; it stays in this browser only.
@@ -486,7 +761,12 @@
486
761
  async function api(path, init = {}) {
487
762
  // Reads work with the admin password or the share key; writes go through other helpers with the password.
488
763
  const token = store.get("driftnet-token") || store.get("driftnet-key");
489
- const res = await fetch(path, { ...init, headers: { ...(init.headers ?? {}), ...(token ? { authorization: `Bearer ${token}` } : {}) } });
764
+ let res = await fetch(path, { ...init, headers: { ...(init.headers ?? {}), ...(token ? { authorization: `Bearer ${token}` } : {}) } });
765
+ // A stored password that no longer works must not hide a share key that does.
766
+ if (res.status === 401 && store.get("driftnet-token") && store.get("driftnet-key") && (init.method ?? "GET") === "GET") {
767
+ store.set("driftnet-token", "");
768
+ res = await fetch(path, { ...init, headers: { ...(init.headers ?? {}), authorization: `Bearer ${store.get("driftnet-key")}` } });
769
+ }
490
770
  if (res.status === 401) throw Object.assign(new Error("unauthorized"), { unauthorized: true });
491
771
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
492
772
  return res.json();
@@ -497,20 +777,29 @@
497
777
  const viewing = !!store.get("driftnet-key") && !store.get("driftnet-token");
498
778
  $("nav").innerHTML = "";
499
779
  $("list").innerHTML = `<form class="card" id="token-form">
500
- <p>${esc(viewing ? T().tokenToEdit : T().tokenPrompt)}</p>
780
+ <p>${esc(viewing ? T().tokenToEdit : T().tokenPrompt)}</p><p class="dlg-error" id="token-err"></p>
501
781
  <input id="token" class="search" style="max-width:none;width:100%" type="password" autocomplete="current-password">
502
782
  <p><button class="lang" type="submit">${esc(T().tokenSave)}</button>
503
- ${viewing ? `<button class="lang" type="button" id="token-back">${esc(T().back)}</button>` : ""}</p></form>`;
783
+ ${viewing ? `<button class="lang" type="button" id="token-back">${esc(T().back)}</button>` : ""}</p>
784
+ <p class="hint">${esc(T().st.loginHelp)}</p><p class="hint">${esc(T().st.loginAdvanced.replaceAll("PORT", String(serverPort)))}</p></form>`;
504
785
  if (viewing) $("token-back").onclick = () => load();
505
- $("token-form").onsubmit = (e) => {
786
+ $("token-form").onsubmit = async (e) => {
506
787
  e.preventDefault();
507
- store.set("driftnet-token", $("token").value.trim());
788
+ const v = $("token").value.trim();
789
+ if (!v) return;
790
+ // Check it before keeping it: the admin password opens the settings, a share key only reads.
791
+ const auth = { authorization: `Bearer ${v}` };
792
+ const read = await fetch("/api/stats", { headers: auth }).catch(() => null);
793
+ if (!read?.ok) { $("token-err").textContent = T().st.keyWrong; return; }
794
+ const admin = await fetch("/api/settings", { headers: auth }).catch(() => null);
795
+ store.set(admin?.ok ? "driftnet-token" : "driftnet-key", v);
508
796
  (then ?? load)();
509
797
  };
510
798
  }
511
799
 
512
800
  function applyLocale() {
513
801
  document.documentElement.lang = locale;
802
+ document.querySelector(".skip").textContent = locale === "zh-TW" ? "跳到卡片" : "Skip to the cards";
514
803
  $("q").placeholder = T().search;
515
804
  $("q").setAttribute("aria-label", T().search);
516
805
  $("lang").textContent = T().switchTo;
@@ -523,6 +812,10 @@
523
812
  /** keyboard: move focus into the drawer and back (a tap doesn't need the focus ring). */
524
813
  function setMenu(open, keyboard = false) {
525
814
  document.body.classList.toggle("menu-open", open);
815
+ // Keyboard and screen-reader focus stay inside the drawer while it is open.
816
+ for (const id of ["list", "crumb"]) $(id).inert = open && isDrawer();
817
+ document.querySelector("header").inert = open && isDrawer();
818
+ document.querySelector(".skip").inert = open && isDrawer();
526
819
  $("menu").setAttribute("aria-expanded", String(open));
527
820
  if (!keyboard) return;
528
821
  if (open) $("nav").querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
@@ -537,8 +830,8 @@
537
830
  /** One line under the header saying what is shown, so a closed drawer hides nothing. */
538
831
  function updateCrumb() {
539
832
  const t = T();
540
- const parts = [state.view === "favorites" ? `★ ${t.favorites}` : state.view === "trash" ? `🗑 ${t.trash}`
541
- : state.view === "notes" ? `📝 ${t.notes}` : t.all];
833
+ const parts = [state.view === "favorites" ? t.favorites : state.view === "trash" ? t.trash
834
+ : state.view === "notes" ? t.notes : state.view === "map" ? t.map : t.all];
542
835
  if (state.category) parts.push(catLabel(state.category));
543
836
  if (state.kind) parts.push(t.kinds[state.kind] ?? state.kind);
544
837
  $("crumb").innerHTML = `${esc(t.showing)} <b>${esc(parts.join(" · "))}</b>`;
@@ -557,28 +850,39 @@
557
850
  throw err;
558
851
  }
559
852
  catLabels = ui.categories;
853
+ role = ui.role ?? "admin";
854
+ serverPort = ui.port ?? 8787;
855
+ summaries = ui.summaries ?? true;
856
+ document.body.classList.toggle("readonly", role !== "admin");
857
+ $("lock").hidden = role === "admin";
560
858
  if (ui.setup && !store.get("driftnet-setup-seen")) { store.set("driftnet-setup-seen", "1"); setTimeout(() => openSettings(true), 300); }
561
859
  if (!STRINGS[saved] && STRINGS[ui.locale]) locale = ui.locale;
562
860
  applyLocale();
563
861
  $("stats").textContent = T().stats(stats.items, stats.shares);
564
- const btn = (field, key, label, n) =>
862
+ $("lock").innerHTML = `${ic("lock")}<span class="long">${esc(T().st.viewOnly)}</span><span class="short">${esc(T().st.unlockShort)}</span>`;
863
+ const btn = (field, key, label, n, icon) =>
565
864
  `<button type="button" data-field="${field}" data-value="${esc(key)}" aria-pressed="${state[field] === key}">
566
- <span>${esc(label)}</span><span class="count">${n ?? ""}</span></button>`;
865
+ <span class="lbl">${icon ? ic(icon) : ""}<span>${esc(label)}</span></span><span class="count">${n ?? ""}</span></button>`;
866
+ const footBtn = (attr, icon, label) => `<button type="button" ${attr}><span class="lbl">${ic(icon)}<span>${esc(label)}</span></span></button>`;
567
867
  $("nav").innerHTML =
568
868
  `<div class="drawer-head"><span class="brand"><img src="/favicon.svg" alt="" width="24" height="24">driftnet</span>` +
569
869
  `<button type="button" class="menu" id="menu-close" aria-label="${esc(T().close)}">✕</button></div>` +
570
870
  `<div class="row">` +
571
- btn("view", "all", T().all, stats.items) + btn("view", "favorites", `★ ${T().favorites}`, stats.favorites) +
572
- btn("view", "trash", `🗑 ${T().trash}`, stats.trash || "") +
573
- btn("view", "notes", `📝 ${T().notes}`, stats.notes || "") +
871
+ btn("view", "all", T().all, stats.items, "all") + btn("view", "favorites", T().favorites, stats.favorites, "star") +
872
+ btn("view", "map", T().map, "", "map") +
873
+ btn("view", "notes", T().notes, stats.notes || "", "note") +
874
+ btn("view", "trash", T().trash, stats.trash || "", "trash") +
574
875
  `</div><div class="folders-head" data-drop-root><h2>${esc(T().folders)}</h2>` +
575
- `<button type="button" class="icon" data-new="" title="${esc(T().newFolder)}" aria-label="${esc(T().newFolder)}">+</button></div>` +
876
+ `<button type="button" class="icon" data-new="" title="${esc(T().newFolder)}" aria-label="${esc(T().newFolder)}">${ic("plus")}</button></div>` +
576
877
  `<div class="tree" role="list">${folderRows(null, 0)}</div><h2>${esc(T().kind)}</h2><div class="row kinds">` + btn("kind", "", T().any, "") +
577
878
  Object.entries(T().kinds).map(([k, v]) => btn("kind", k, v, "")).join("") + `</div>` +
578
- `<div class="foot"><button type="button" data-connect>${esc(T().st.connect)}</button>` +
579
- `<button type="button" data-settings>${esc(T().settings)}</button>` +
580
- `<button type="button" data-export="markdown">${esc(T().exportMd)}</button>` +
581
- `<button type="button" data-export="vault">${esc(T().exportVault)}</button></div>`;
879
+ `<div class="foot">` +
880
+ (ui.role !== "admin" ? footBtn("data-login", "lock", T().st.login) : "") +
881
+ footBtn("data-connect", "plug", T().st.connect) +
882
+ footBtn("data-settings", "gear", T().settings) +
883
+ footBtn('data-export="markdown"', "download", T().exportMd) +
884
+ footBtn('data-export="vault"', "download", T().exportVault) +
885
+ (ui.role === "admin" && !ui.local && store.get("driftnet-token") ? footBtn("data-logout", "logout", T().st.logout) : "") + `</div>`;
582
886
  $("nav").onclick = (e) => {
583
887
  const b = e.target.closest("button");
584
888
  if (!b) return;
@@ -593,10 +897,14 @@
593
897
  if (b.dataset.export) return download(b.dataset.export);
594
898
  if (b.dataset.settings !== undefined) { if (isDrawer()) setMenu(false); return openSettings(); }
595
899
  if (b.dataset.connect !== undefined) { if (isDrawer()) setMenu(false); return openConnect(); }
900
+ if (b.dataset.login !== undefined) { if (isDrawer()) setMenu(false); return openLogin(); }
901
+ if (b.dataset.logout !== undefined) { store.set("driftnet-token", ""); return load(); }
596
902
  if (b.dataset.new !== undefined) return openFolderDialog(null, b.dataset.new || null);
597
903
  const { field, value } = b.dataset;
598
904
  // Choosing a category stays inside the current view; choosing a view clears the category.
599
905
  if (field === "view") state.category = "";
906
+ // The map has its own folders: picking one in the sidebar shows its cards.
907
+ if (field === "category" && (state.view === "map" || state.view === "notes")) state.view = "all";
600
908
  state[field] = field !== "view" && state[field] === value ? "" : value;
601
909
  $("nav").querySelectorAll("button[data-field]").forEach((x) => x.setAttribute("aria-pressed", state[x.dataset.field] === x.dataset.value));
602
910
  if (isDrawer()) setMenu(false);
@@ -614,10 +922,10 @@
614
922
  const open = hasKids && !collapsed.has(f.id);
615
923
  return `<div class="folder" role="listitem" data-folder="${esc(f.id)}" draggable="true" style="--depth:${depth}">
616
924
  <button type="button" class="icon twist ${hasKids ? "" : "leaf"}" ${hasKids ? `data-twist="${esc(f.id)}" aria-expanded="${open}"` : 'tabindex="-1" aria-hidden="true"'}
617
- aria-label="${esc(t.expand)}">▶</button>
618
- <button type="button" data-field="category" data-value="${esc(f.id)}" aria-pressed="${state.category === f.id}" title="${esc(f.description)}">
619
- <span>${esc(catLabel(f.id))}</span><span class="count">${subtotal(f) || ""}</span></button>
620
- <button type="button" class="icon more" data-edit="${esc(f.id)}" title="${esc(t.editFolder)}" aria-label="${esc(t.editFolder)}: ${esc(catLabel(f.id))}">⋯</button>
925
+ aria-label="${esc(t.expand)}">${ic("chev")}</button>
926
+ <button type="button" data-field="category" data-value="${esc(f.id)}" aria-pressed="${state.category === f.id}" title="${esc(f.description)}" style="--c:${folderColor(f.id)}">
927
+ <span class="lbl"><span class="dot ${depth ? "sub" : ""}"></span><span>${esc(catLabel(f.id))}</span></span><span class="count">${subtotal(f) || ""}</span></button>
928
+ <button type="button" class="icon more" data-edit="${esc(f.id)}" title="${esc(t.editFolder)}" aria-label="${esc(t.editFolder)}: ${esc(catLabel(f.id))}">${ic("dots")}</button>
621
929
  </div>` + (open ? folderRows(f.id, depth + 1) : "");
622
930
  }).join("");
623
931
  }
@@ -683,9 +991,9 @@
683
991
  try {
684
992
  const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
685
993
  ...(body ? { body: JSON.stringify(body) } : {}) });
686
- if (res.status === 401) { $("folder-dlg").close(); askToken(); return null; }
994
+ if (res.status === 401) { needAdmin(); return null; }
687
995
  const data = await res.json().catch(() => ({}));
688
- if (!res.ok) { $("fd-error").textContent = data.error ?? T().failed; return null; }
996
+ if (!res.ok) { $("fd-error").textContent = friendlyError(data.error) ?? T().failed; return null; }
689
997
  return data;
690
998
  } catch {
691
999
  $("fd-error").textContent = T().failed;
@@ -705,10 +1013,35 @@
705
1013
  aria-current="${f.id === item.category}"><span>${esc(catLabel(f.id))}</span><span class="count">${subtotal(f) || ""}</span></button>` + rows(f.id, depth + 1)).join("");
706
1014
  $("mv-list").innerHTML = rows(null, 0);
707
1015
  $("mv-cancel").textContent = t.cancel;
1016
+ $("mv-filter").value = "";
1017
+ $("mv-filter").placeholder = t.filterFolders;
1018
+ $("mv-filter").setAttribute("aria-label", t.filterFolders);
708
1019
  $("move-dlg").showModal();
709
- $("mv-list").querySelector('[aria-current="true"]')?.focus();
1020
+ // Type to narrow the folders; Enter files into the first match; arrows walk the list.
1021
+ $("mv-filter").focus();
710
1022
  }
711
1023
  $("mv-cancel").onclick = () => $("move-dlg").close();
1024
+ $("mv-filter").addEventListener("input", () => {
1025
+ const q = $("mv-filter").value.trim().toLowerCase();
1026
+ const rows = [...$("mv-list").querySelectorAll("[data-to]")];
1027
+ // Match what the reader sees; the hidden id (e.g. "coding-agent") only when no visible name matches.
1028
+ const byName = rows.filter((b) => b.textContent.toLowerCase().includes(q));
1029
+ const shown = new Set(q ? (byName.length ? byName : rows.filter((b) => b.dataset.to.includes(q))) : rows);
1030
+ for (const b of rows) b.hidden = !shown.has(b);
1031
+ });
1032
+ $("mv-filter").addEventListener("keydown", (e) => {
1033
+ const visible = [...$("mv-list").querySelectorAll("[data-to]:not([hidden])")];
1034
+ if (e.key === "Enter") { e.preventDefault(); visible[0]?.click(); }
1035
+ else if (e.key === "ArrowDown") { e.preventDefault(); visible[0]?.focus(); }
1036
+ });
1037
+ $("mv-list").addEventListener("keydown", (e) => {
1038
+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
1039
+ e.preventDefault();
1040
+ const visible = [...$("mv-list").querySelectorAll("[data-to]:not([hidden])")];
1041
+ const at = visible.indexOf(document.activeElement);
1042
+ if (e.key === "ArrowUp" && at <= 0) return $("mv-filter").focus();
1043
+ visible[Math.min(visible.length - 1, at + (e.key === "ArrowDown" ? 1 : -1))]?.focus();
1044
+ });
712
1045
  $("move-dlg").addEventListener("click", (e) => { if (e.target === $("move-dlg")) $("move-dlg").close(); });
713
1046
  $("folder-dlg").addEventListener("click", (e) => { if (e.target === $("folder-dlg")) $("folder-dlg").close(); });
714
1047
  $("mv-list").onclick = (e) => {
@@ -725,7 +1058,7 @@
725
1058
  const token = store.get("driftnet-token");
726
1059
  const res = await fetch(`/api/items/${id}/move`, { method: "POST", body: JSON.stringify({ folder: to }),
727
1060
  headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) } }).catch(() => null);
728
- if (res?.status === 401) return askToken();
1061
+ if (res?.status === 401) return needAdmin();
729
1062
  if (!res?.ok) return toast(T().failed);
730
1063
  item.category = to;
731
1064
  const f = folderById(to); if (f) f.count++;
@@ -733,9 +1066,16 @@
733
1066
  const el = document.getElementById(`item-${id}`);
734
1067
  // Still inside the folder being viewed? Update the badge; otherwise it leaves the list.
735
1068
  const visible = !state.category || subtreeOf(state.category).has(to);
736
- if (el && !visible) dismiss(el);
1069
+ if (el && !visible) {
1070
+ if (el.contains(document.activeElement)) (el.nextElementSibling ?? el.previousElementSibling)?.querySelector?.(".card")?.focus();
1071
+ dismiss(el);
1072
+ }
737
1073
  else if (el) { el.outerHTML = card(item); attachSwipe(document.getElementById(`item-${id}`)); }
738
1074
  refreshTree();
1075
+ // The list and the map hold their own copies of the item: keep both in step.
1076
+ const onMap = mapItems.find((x) => x.id === id);
1077
+ if (onMap && onMap !== item) onMap.category = to;
1078
+ if (state.view === "map") drawMap();
739
1079
  if (!quiet) toast(T().moved(nameOf(item), folderPath(to)), async () => { await moveItem(id, from, true); render(); });
740
1080
  }
741
1081
  const subtreeOf = (id) => { const out = new Set([id]); for (const q = [id]; q.length;) for (const k of kids(q.pop())) { out.add(k.id); q.push(k.id); } return out; };
@@ -774,7 +1114,13 @@
774
1114
  if (item && to) return moveItem(Number(item), to);
775
1115
  if (folder && folder !== to && !(to && subtreeOf(folder).has(to))) {
776
1116
  const ok = await folderWrite(`/api/folders/${encodeURIComponent(folder)}`, "PATCH", { parent: to });
777
- if (ok) { toast(T().folderMoved(catLabel(folder), to ? folderPath(to) : T().topLevelShort)); load(); }
1117
+ if (ok) {
1118
+ const from = folderById(folder)?.parent ?? null;
1119
+ toast(T().folderMoved(catLabel(folder), to ? folderPath(to) : T().topLevelShort), async () => {
1120
+ if (await folderWrite(`/api/folders/${encodeURIComponent(folder)}`, "PATCH", { parent: from })) load();
1121
+ });
1122
+ load();
1123
+ }
778
1124
  else toast($("fd-error").textContent || T().failed);
779
1125
  }
780
1126
  };
@@ -807,7 +1153,7 @@
807
1153
  <label class="set-row check"><input type="checkbox" data-pref="compact" ${prefs.compact ? "checked" : ""}><span>${esc(st.compact)}</span></label>
808
1154
  <label class="set-row check"><input type="checkbox" data-pref="tags" ${prefs.tags ? "checked" : ""}><span>${esc(st.tags)}</span></label>
809
1155
  <label class="set-row check"><input type="checkbox" data-pref="said" ${prefs.said ? "checked" : ""}><span>${esc(st.said)}</span></label></fieldset>`;
810
- let server = `<p class="set-status">${esc(st.forbidden)}</p>`;
1156
+ let server = `<p class="set-status">${esc(st.forbidden)}</p><p><button class="btn primary" type="button" id="st-login">${esc(st.login)}</button></p>`;
811
1157
  if (serverSettings) {
812
1158
  const field = (s) => {
813
1159
  const [label, help] = st.labels[s.key] ?? [s.key, ""];
@@ -818,24 +1164,61 @@
818
1164
  else if (s.multiline) input = `<textarea data-key="${s.key}" rows="3" ${dis}>${esc(s.value)}</textarea>`;
819
1165
  else if (s.secret) input = `<input data-key="${s.key}" type="password" autocomplete="off" placeholder="${esc(s.set ? st.keep : st.unset)}" ${dis}>`;
820
1166
  else input = `<input data-key="${s.key}" value="${esc(s.value)}" autocomplete="off" ${dis}>`;
821
- return `<label class="set-row"><span>${esc(label)}${s.key.startsWith("DRIFTNET") || s.secret ? ` <small>${esc(s.key)}</small>` : ""}</span>${input}${hint ? `<small>${esc(hint)}</small>` : ""}</label>`;
1167
+ return `<label class="set-row"><span>${esc(label)}</span>${input}${hint ? `<small>${esc(hint)}</small>` : ""}<small class="envname">${esc(s.key)}</small></label>`;
822
1168
  };
823
1169
  const group = (g) => `<fieldset class="set-group"><legend>${esc(st[g])}</legend>${serverSettings.settings.filter((s) => s.group === g).map(field).join("")}</fieldset>`;
824
- const plugins = serverSettings.plugins?.length ? serverSettings.plugins.map((p) => `<div>🧩 ${esc(p)}</div>`).join("")
1170
+ const plugins = serverSettings.plugins?.length ? serverSettings.plugins.map((p) => `<div>${esc(p)}</div>`).join("")
825
1171
  : esc(st.pluginsNone(serverSettings.file.replace(/\.env$/, "plugins/")));
826
- server = `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` +
827
- accessPanel(serverSettings, field) +
828
- group("model") + group("language") + group("rules") +
829
- `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`;
1172
+ const a = serverSettings.access;
1173
+ const yes = (b) => (b ? "✓" : "—");
1174
+ const accessStatus = `<p class="set-status">${esc(st.accessStatus(yes(a.passwordSet), yes(a.readKey), a.tunnel.running ? a.tunnel.url : "—"))}</p>`;
1175
+ server = {
1176
+ general: group("language") + group("chat"),
1177
+ access: accessStatus + accessPanel(serverSettings, field),
1178
+ ai: `<p class="set-status" id="st-status">${esc(st.status(serverSettings.engines))}</p>` + group("model") + group("rules") +
1179
+ `<fieldset class="set-group"><legend>${esc(st.plugins)}</legend><div class="set-row">${plugins}</div></fieldset>`,
1180
+ };
830
1181
  }
1182
+ // Three tabs instead of one long scroll: what you see, who gets in, which AI.
1183
+ const tab = welcome ? "ai" : store.get("driftnet-settings-tab") || "general";
1184
+ const tabs = [["general", st.tabGeneral], ["access", st.tabAccess], ["ai", st.tabAi]];
1185
+ const section = (k, html) => `<section data-tab="${k}" role="tabpanel" id="panel-${k}" aria-labelledby="tab-${k}">${html}</section>`;
831
1186
  $("st-title").textContent = st.title;
832
1187
  $("st-error").textContent = "";
833
- $("st-body").innerHTML = (welcome ? `<p class="welcome">${esc(st.welcome)}</p>` : "") + (welcome ? server + local : local + server);
1188
+ $("st-body").innerHTML = (welcome ? `<p class="welcome">${esc(st.welcome)}</p>` : "") +
1189
+ `<div class="tabs" role="tablist">${tabs.map(([k, l]) => `<button type="button" role="tab" id="tab-${k}" aria-controls="panel-${k}" tabindex="${k === tab ? 0 : -1}" data-tab-btn="${k}" aria-selected="${k === tab}">${esc(l)}</button>`).join("")}</div>` +
1190
+ (typeof server === "string"
1191
+ ? section("general", local) + section("access", server) + section("ai", server)
1192
+ : section("general", local + server.general) + section("access", server.access) + section("ai", server.ai));
1193
+ $("st-body").dataset.tab = tab;
834
1194
  $("st-cancel").textContent = t.cancel;
835
1195
  $("st-save").textContent = st.save;
1196
+ settingsOpener = isDrawer() ? $("menu") : document.activeElement;
836
1197
  $("settings-dlg").showModal();
1198
+ $("st-body").querySelector('[data-tab-btn][aria-selected="true"]')?.focus();
837
1199
  }
1200
+ let settingsOpener = null;
1201
+ $("settings-dlg").addEventListener("close", () => { if (settingsOpener?.isConnected) settingsOpener.focus(); });
838
1202
  $("st-cancel").onclick = () => $("settings-dlg").close();
1203
+ $("st-body").addEventListener("click", (e) => {
1204
+ const b = e.target.closest("[data-tab-btn]");
1205
+ if (!b) return;
1206
+ selectTab(b);
1207
+ });
1208
+ function selectTab(b) {
1209
+ $("st-body").dataset.tab = b.dataset.tabBtn;
1210
+ store.set("driftnet-settings-tab", b.dataset.tabBtn);
1211
+ $("st-body").querySelectorAll("[data-tab-btn]").forEach((x) => { x.setAttribute("aria-selected", x === b); x.tabIndex = x === b ? 0 : -1; });
1212
+ }
1213
+ $("st-body").addEventListener("keydown", (e) => {
1214
+ const b = e.target.closest?.("[data-tab-btn]");
1215
+ if (!b || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(e.key)) return;
1216
+ e.preventDefault();
1217
+ const all = [...$("st-body").querySelectorAll("[data-tab-btn]")];
1218
+ const at = all.indexOf(b);
1219
+ const next = e.key === "Home" ? all[0] : e.key === "End" ? all.at(-1) : all[(at + (e.key === "ArrowRight" ? 1 : all.length - 1)) % all.length];
1220
+ selectTab(next); next.focus();
1221
+ });
839
1222
 
840
1223
  // ── Access panel: password, who can read, share key, public URL ───────────
841
1224
  const pwStrength = (pw) => {
@@ -868,11 +1251,11 @@
868
1251
  else tun = `<button class="btn primary" type="button" id="ac-tunnel" data-on="1" ${a.passwordSet ? "" : "disabled"}>${esc(st.tunnelOn)}</button>
869
1252
  <small>${esc(a.passwordSet ? st.tunnelPrivate : st.tunnelNeedsPassword)}</small>`;
870
1253
  return `<fieldset class="set-group" id="ac"><legend>${esc(st.access)}</legend>
871
- <div class="set-row"><span>${esc(st.password)} <small>DRIFTNET_TOKEN</small></span>${pwInput}
1254
+ <div class="set-row"><span title="DRIFTNET_TOKEN">${esc(st.password)}</span>${pwInput}
872
1255
  <small>${esc(pw.locked ? st.locked : st.passwordHelp)}</small></div>
873
1256
  <p class="warn">${esc(st.passwordWarn)}</p>
874
- <label class="set-row"><span>${esc(st.accessMode)} <small>DRIFTNET_ACCESS</small></span>${modeSel}</label>
875
- <div class="set-row"><span>${esc(st.shareKey)} <small>DRIFTNET_READ_KEY</small></span>${key}<small>${esc(st.shareKeyHelp)}</small></div>
1257
+ <label class="set-row"><span title="DRIFTNET_ACCESS">${esc(st.accessMode)}</span>${modeSel}</label>
1258
+ <div class="set-row"><span title="DRIFTNET_READ_KEY">${esc(st.shareKey)}</span>${key}<small>${esc(st.shareKeyHelp)}</small></div>
876
1259
  <div class="set-row"><span>${esc(st.tunnel)}</span>${tun}<small>${esc(st.tunnelHelp)}</small>${t.error ? `<small class="dlg-error">${esc(t.error)}</small>` : ""}</div>
877
1260
  </fieldset>`;
878
1261
  }
@@ -881,7 +1264,7 @@
881
1264
  const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
882
1265
  ...(body ? { body: JSON.stringify(body) } : {}) }).catch(() => null);
883
1266
  const data = await res?.json().catch(() => ({}));
884
- if (!res?.ok) { $("st-error").textContent = data?.error ?? T().failed; return null; }
1267
+ if (!res?.ok) { $("st-error").textContent = friendlyError(data?.error) ?? T().failed; return null; }
885
1268
  return data;
886
1269
  }
887
1270
  $("st-body").addEventListener("input", (e) => {
@@ -898,22 +1281,29 @@
898
1281
  const el = $("st-body").querySelector(b.dataset.copy) ?? $("cx-body").querySelector(b.dataset.copy);
899
1282
  await navigator.clipboard?.writeText(el.value ?? el.textContent).catch(() => {});
900
1283
  b.textContent = st.copied; setTimeout(() => (b.textContent = st.copy), 1200);
1284
+ } else if (b.id === "st-login") {
1285
+ $("settings-dlg").close();
1286
+ openLogin();
901
1287
  } else if (b.id === "ac-show") {
902
1288
  const i = $("ac-pw"); i.type = i.type === "password" ? "text" : "password"; b.textContent = i.type === "password" ? st.show : st.hide;
903
1289
  } else if (b.id === "ac-gen") {
904
1290
  const i = $("ac-pw"); i.value = randomPassword(); i.type = "text"; $("ac-show").textContent = st.hide;
905
1291
  i.dispatchEvent(new Event("input", { bubbles: true }));
1292
+ await navigator.clipboard?.writeText(i.value).catch(() => {});
1293
+ toast(st.genCopied);
906
1294
  } else if (b.id === "ac-newkey") {
1295
+ // Whatever was typed (a new password, private reading) is saved first, not thrown away.
1296
+ if (!(await saveSettings())) return;
907
1297
  if (await adminFetch("/api/read-key", "POST", {})) openSettings();
908
1298
  } else if (b.id === "ac-tunnel") {
909
- if (b.dataset.on === "1" && $("ac-pw")?.value) { $("st-error").textContent = st.saveFirst; return; }
1299
+ if (b.dataset.on === "1" && !(await saveSettings())) return;
910
1300
  b.disabled = true; b.textContent = b.dataset.on === "1" ? st.tunnelStarting : b.textContent;
911
1301
  if (await adminFetch("/api/tunnel", "POST", { on: b.dataset.on === "1" })) openSettings();
912
1302
  else b.disabled = false;
913
1303
  }
914
1304
  });
915
- $("settings-form").onsubmit = async (e) => {
916
- e.preventDefault();
1305
+ /** Save what is typed in Settings. Returns false (and shows why) when the server refused. */
1306
+ async function saveSettings() {
917
1307
  const body = $("st-body");
918
1308
  for (const el of body.querySelectorAll("[data-pref]")) prefs[el.dataset.pref] = el.type === "checkbox" ? el.checked : el.value;
919
1309
  store.set("driftnet-prefs", JSON.stringify(prefs));
@@ -930,16 +1320,545 @@
930
1320
  const res = await fetch("/api/settings", { method: "PUT", body: JSON.stringify({ values }),
931
1321
  headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) } }).catch(() => null);
932
1322
  const data = await res?.json().catch(() => ({}));
933
- if (!res?.ok) { $("st-error").textContent = data?.error ?? T().failed; return; }
1323
+ if (!res?.ok) { $("st-error").textContent = friendlyError(data?.error) ?? T().failed; return null; }
934
1324
  serverSaved = true;
935
1325
  // The page keeps working with the password it just set (or forgets a removed one).
936
1326
  if ("DRIFTNET_TOKEN" in values) values.DRIFTNET_TOKEN ? store.set("driftnet-token", values.DRIFTNET_TOKEN.trim()) : store.set("driftnet-token", "");
937
1327
  }
938
1328
  }
1329
+ return { serverSaved };
1330
+ }
1331
+ $("settings-form").onsubmit = async (e) => {
1332
+ e.preventDefault();
1333
+ const saved = await saveSettings();
1334
+ if (!saved) return;
939
1335
  $("settings-dlg").close();
940
- toast(serverSaved ? T().st.savedServer : T().saved);
1336
+ toast(saved.serverSaved ? T().st.savedServer : T().saved);
941
1337
  load();
942
1338
  };
1339
+ /** Server refusals in words a person reads, in the page's language. */
1340
+ function friendlyError(msg) {
1341
+ if (!msg) return null;
1342
+ const zh = locale === "zh-TW";
1343
+ const rules = [
1344
+ [/DRIFTNET_TOKEN needs at least (\d+)/, (m) => zh ? `管理密碼至少要 ${m[1]} 個字元。` : `The admin password needs at least ${m[1]} characters.`],
1345
+ [/password can't contain spaces/, () => zh ? "管理密碼不能有空白。" : "The admin password can't contain spaces."],
1346
+ [/must not be weak|stronger password/, () => zh ? "開著公開網址時,密碼不能太弱:請按「產生」或換一組更長的。" : "With a public URL open, the password can't be weak — press Generate or use a longer one."],
1347
+ [/private access needs an admin password/, () => zh ? "要設成私人,得先設管理密碼。" : "Private reading needs an admin password first."],
1348
+ [/turn the public URL off/, () => zh ? "要先關掉公開網址,才能移除密碼。" : "Close the public URL before removing the password."],
1349
+ [/set an admin password first|Save first/, () => zh ? "要先設定並儲存管理密碼。" : "Set and save an admin password first."],
1350
+ [/cloudflared is not installed/, () => zh ? "這台電腦還沒安裝 cloudflared。" : "cloudflared isn't installed on this computer."],
1351
+ [/set by the environment/, () => zh ? "這個設定由執行環境決定(例如 systemd),要在那裡改。" : "This one is set by the environment driftnet runs in; change it there."],
1352
+ [/already a folder called “(.+)” here/, (m) => zh ? `這裡已經有一個叫「${m[1]}」的資料夾了。` : `There's already a folder called “${m[1]}” here.`],
1353
+ [/too many wrong passwords/, () => zh ? "密碼錯太多次,請 15 分鐘後再試。" : "Too many wrong passwords — try again in 15 minutes."],
1354
+ ];
1355
+ for (const [re, f] of rules) { const m = re.exec(msg); if (m) return f(m); }
1356
+ return msg;
1357
+ }
1358
+
1359
+ // ── Mind map ─────────────────────────────────────────────────────────────
1360
+ const mapOpen = new Set((() => { try { return JSON.parse(store.get("driftnet-map-open") ?? "[]"); } catch { return []; } })());
1361
+ const saveMapOpen = () => store.set("driftnet-map-open", JSON.stringify([...mapOpen]));
1362
+ let mapZoom = Number(store.get("driftnet-map-zoom")) || 1;
1363
+ /** both: branches on both sides of the root (XMind's default); right: all to the right. */
1364
+ let mapLayout = store.get("driftnet-map-layout") || "both";
1365
+ let mapItems = [];
1366
+ /** Cards shown per folder before the rest fold into a "+N" node. */
1367
+ const MAP_CAP = 15;
1368
+
1369
+ async function renderMap() {
1370
+ const t = T();
1371
+ try {
1372
+ mapItems = await api("/api/items?limit=500&minWorth=skip");
1373
+ } catch (err) {
1374
+ if (err.unauthorized) return askToken();
1375
+ throw err;
1376
+ }
1377
+ const allOpen = mapOpen.size > 0 || !!state.q;
1378
+ const tip = store.get("driftnet-map-tip") ? "" : `<p class="hint map-tip">${esc(t.mapHint)} <button class="link-btn" type="button" data-map="tip">${esc(t.gotIt)}</button></p>`;
1379
+ $("list").innerHTML = `<div class="map-bar">
1380
+ <button class="btn" type="button" data-map="${allOpen ? "collapse" : "expand"}">${ic(allOpen ? "collapse" : "expand")} ${esc(allOpen ? t.collapseAll : t.expandAll)}</button>
1381
+ <button class="btn" type="button" data-map="new">${ic("plus")} ${esc(t.newFolder)}</button>
1382
+ <button class="btn" type="button" data-map="layout" aria-pressed="${mapLayout === "both"}" title="${esc(t.layoutHelp)}">${ic(mapLayout === "both" ? "both" : "map")} ${esc(mapLayout === "both" ? t.layoutBoth : t.layoutRight)}</button>
1383
+ ${state.q ? `<span class="hint">${esc(t.mapSearch(state.q))}</span>` : ""}</div>
1384
+ ${tip}
1385
+ <div class="map-shell"><div class="map-wrap" id="map-wrap"><div class="map-canvas" id="map-canvas"></div></div>
1386
+ <div class="map-zoom" role="group" aria-label="${esc(t.zoom)}">
1387
+ <button type="button" data-map="out" aria-label="${esc(t.zoomOut)}">${ic("minus")}</button>
1388
+ <button type="button" data-map="fit" aria-label="${esc(t.fit)}">${ic("fit")}</button>
1389
+ <button type="button" data-map="in" aria-label="${esc(t.zoomIn)}">${ic("plus")}</button></div></div>`;
1390
+ drawMap();
1391
+ sizeMap();
1392
+ // On a phone the whole tree rarely fits: start fitted to the width (still readable).
1393
+ if (isDrawer() && !store.get("driftnet-map-zoom")) fitWidth();
1394
+ centreOnRoot();
1395
+ }
1396
+ /** The toolbar's Expand all / Collapse all follows what is open. */
1397
+ function syncMapToggle() {
1398
+ const b = $("list").querySelector('[data-map="expand"], [data-map="collapse"]');
1399
+ if (!b) return;
1400
+ const open = mapOpen.size > 0, t = T();
1401
+ b.dataset.map = open ? "collapse" : "expand";
1402
+ b.innerHTML = `${ic(open ? "collapse" : "expand")} ${esc(open ? t.collapseAll : t.expandAll)}`;
1403
+ }
1404
+ /** Every time the map opens, start from the root, not wherever the scroll happened to be. */
1405
+ function centreOnRoot() {
1406
+ const wrap = $("map-wrap"), root = $("map-canvas")?.querySelector('.mnode[data-key="root"]');
1407
+ if (!wrap || !root) return;
1408
+ wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
1409
+ wrap.scrollLeft = (root.offsetLeft + root.offsetWidth / 2) * mapZoom - wrap.clientWidth / 2;
1410
+ }
1411
+ function fitWidth() {
1412
+ const wrap = $("map-wrap"), c = $("map-canvas");
1413
+ if (!wrap || !c) return;
1414
+ mapZoomTo(Math.max(0.6, Math.min(1, (wrap.clientWidth - 8) / c.offsetWidth)));
1415
+ const root = c.querySelector('.mnode[data-key="root"]');
1416
+ if (root) wrap.scrollTop = root.offsetTop * mapZoom - wrap.clientHeight / 2;
1417
+ }
1418
+ function fitMap() {
1419
+ const wrap = $("map-wrap"), c = $("map-canvas");
1420
+ if (!wrap || !c) return;
1421
+ // Fit, but never so small the text can't be read (phones stop at 0.6, desktops at 0.45); then start at the root.
1422
+ const floor = isDrawer() ? 0.6 : 0.45;
1423
+ mapZoomTo(Math.max(floor, Math.min(1.3, (wrap.clientWidth - 8) / c.offsetWidth, (wrap.clientHeight - 8) / c.offsetHeight)));
1424
+ centreOnRoot();
1425
+ }
1426
+ /** The map fills the rest of the screen, so the page and the map don't scroll inside each other. */
1427
+ function sizeMap() {
1428
+ const wrap = $("map-wrap");
1429
+ if (wrap) wrap.style.height = `${Math.max(320, innerHeight - wrap.getBoundingClientRect().top - 12)}px`;
1430
+ }
1431
+ addEventListener("resize", () => { if (state.view === "map") sizeMap(); });
1432
+
1433
+ /** Root → folders → sub-folders and cards, laid out left to right like XMind. */
1434
+ function drawMap() {
1435
+ const canvas = $("map-canvas");
1436
+ if (!canvas) return;
1437
+ const q = state.q.toLowerCase();
1438
+ const hit = (i) => !!q && `${i.summary?.name ?? i.title} ${i.summary?.oneLiner ?? ""} ${(i.summary?.tags ?? []).join(" ")} ${i.url}`.toLowerCase().includes(q);
1439
+ const byFolder = new Map();
1440
+ for (const i of mapItems) byFolder.set(i.category, [...(byFolder.get(i.category) ?? []), i]);
1441
+ const total = (f) => (byFolder.get(f.id)?.length ?? 0) + kids(f.id).reduce((n, c) => n + total(c), 0);
1442
+ const hits = (f) => (byFolder.get(f.id) ?? []).some(hit) || kids(f.id).some(hits);
1443
+ const build = (f, depth, color) => {
1444
+ // While searching, folders holding a match open by themselves (not saved).
1445
+ const open = mapOpen.has(f.id) || (q && hits(f));
1446
+ const cards = byFolder.get(f.id) ?? [];
1447
+ const node = { key: `f:${f.id}`, type: "folder", id: f.id, label: catLabel(f.id), count: total(f), depth, color, open, children: [],
1448
+ hasKids: kids(f.id).length > 0 || cards.length > 0, hit: q && f.id && catLabel(f.id).toLowerCase().includes(q) };
1449
+ if (open) {
1450
+ node.children.push(...kids(f.id).map((c) => build(c, depth + 1, color)));
1451
+ const shown = q ? [...cards.filter(hit), ...cards.filter((i) => !hit(i))] : cards;
1452
+ node.children.push(...shown.slice(0, MAP_CAP).map((i) => ({ key: `i:${i.id}`, type: "item", id: i.id, depth: depth + 1, color,
1453
+ label: (i.summary?.name ?? i.title).slice(0, 32), worth: i.worth, hit: hit(i), children: [] })));
1454
+ if (cards.length > MAP_CAP) node.children.push({ key: `m:${f.id}`, type: "more", id: f.id, depth: depth + 1, color, label: T().more(cards.length - MAP_CAP), children: [] });
1455
+ }
1456
+ return node;
1457
+ };
1458
+ const root = { key: "root", type: "root", label: "driftnet", count: mapItems.length, depth: 0, color: "var(--m1)",
1459
+ children: kids(null).map((f, n) => build(f, 1, `var(--m${(n % 8) + 1})`)) };
1460
+
1461
+ // Pass 1: create the nodes and measure them.
1462
+ const flat = [];
1463
+ const walk = (n) => { flat.push(n); n.children.forEach(walk); };
1464
+ walk(root);
1465
+ canvas.classList.toggle("searching", !!q);
1466
+ canvas.innerHTML = `<svg id="map-svg"></svg>` + flat.map((n) => {
1467
+ const level = n.type === "folder" ? (n.depth === 1 ? "l1" : "l2") : "";
1468
+ const tw = n.type === "folder" && n.hasKids ? `<span class="tw ${n.open ? "open" : ""}">${ic("chev")}</span>` : "";
1469
+ const cnt = (n.type === "folder" || n.type === "root") && n.count ? `<span class="cnt">${n.count}</span>` : "";
1470
+ const star = n.type === "item" && n.worth === "must-see" ? `<span class="w">${ic("star", "filled")}</span>` : "";
1471
+ const more = n.type === "folder" ? `<span class="opt" data-edit="${esc(n.id)}" aria-hidden="true" title="${esc(T().editFolder)}">${ic("dots")}</span>` : "";
1472
+ const name = n.type === "folder" ? T().a11yFolder(n.label, n.count) : n.type === "item" ? T().a11yCard(n.label) : n.label;
1473
+ const aria = ` aria-label="${esc(name)}" aria-level="${n.depth + 1}"` + (n.type === "folder" && n.hasKids ? ` aria-expanded="${!!n.open}"` : "");
1474
+ return `<div class="mnode ${n.type} ${level} ${n.type === "folder" && !n.hasKids ? "vacant" : ""} ${n.hit ? "hit" : ""}" role="button" tabindex="0"${aria}
1475
+ data-key="${esc(n.key)}" style="--c:${n.color}">${tw}${star}<span class="t">${esc(n.label)}</span>${cnt}${more}</div>`;
1476
+ }).join("");
1477
+ const el = new Map([...canvas.querySelectorAll(".mnode")].map((d) => [d.dataset.key, d]));
1478
+ for (const n of flat) { n.w = el.get(n.key).offsetWidth; n.h = el.get(n.key).offsetHeight; }
1479
+
1480
+ // Which side each top-level branch grows to. "both" (XMind's default): the first half by height goes right,
1481
+ // top to bottom; the rest goes left with the last branch at the top. "right": everything to the right.
1482
+ const leaves = (n) => (n.children.length ? n.children.reduce((a, c) => a + leaves(c), 0) : 1);
1483
+ let right = root.children, left = [];
1484
+ if (mapLayout === "both" && root.children.length > 1) {
1485
+ const total = leaves(root);
1486
+ right = []; let acc = 0;
1487
+ for (const c of root.children) { if (!right.length || acc + leaves(c) / 2 <= total / 2) { right.push(c); acc += leaves(c); } else left.push(c); }
1488
+ if (!left.length) left.push(right.pop());
1489
+ left.reverse();
1490
+ }
1491
+ const mark = (n, side) => { n.side = side; n.children.forEach((c) => mark(c, side)); };
1492
+ right.forEach((c) => mark(c, 1));
1493
+ left.forEach((c) => mark(c, -1));
1494
+ root.side = 0;
1495
+
1496
+ // Columns per side: the widest node at each depth, plus a gap (wider next to the root).
1497
+ const GAP = (d) => (d === 1 ? 84 : 60);
1498
+ const colW = { 1: [], "-1": [] };
1499
+ for (const n of flat) if (n.side) colW[n.side][n.depth] = Math.max(colW[n.side][n.depth] ?? 0, n.w);
1500
+ const span = (side) => colW[side].reduce((a, w, d) => a + (w ?? 0) + GAP(d), 0);
1501
+ const rootX = 32 + span(-1);
1502
+ root.x = rootX;
1503
+ const edge = (side, d) => { // right side: a column's left edge; left side: its right edge
1504
+ let off = GAP(1);
1505
+ for (let k = 1; k < d; k++) off += (colW[side][k] ?? 0) + GAP(k + 1);
1506
+ return side === 1 ? rootX + root.w + off : rootX - off;
1507
+ };
1508
+
1509
+ // Rows: leaves take a row each, a parent sits in the middle of its children, branches get air between them.
1510
+ const ROW = 42;
1511
+ const rowsOf = (list) => {
1512
+ let row = 0;
1513
+ const place = (n) => {
1514
+ if (!n.children.length) { n.row = row++; return; }
1515
+ n.children.forEach(place);
1516
+ n.row = (n.children[0].row + n.children[n.children.length - 1].row) / 2;
1517
+ };
1518
+ list.forEach((c, k) => { if (k > 0) row += 0.4; place(c); });
1519
+ return row;
1520
+ };
1521
+ const rowsR = rowsOf(right), rowsL = rowsOf(left), rows = Math.max(rowsR, rowsL, 1);
1522
+ root.cy = 32 + (rows * ROW) / 2;
1523
+ // Each side is centred on the root.
1524
+ const top = { 1: root.cy - (rowsR * ROW) / 2, "-1": root.cy - (rowsL * ROW) / 2 };
1525
+ for (const n of flat) {
1526
+ if (n.side) {
1527
+ n.cy = top[n.side] + n.row * ROW + ROW / 2;
1528
+ n.x = n.side === 1 ? edge(1, n.depth) : edge(-1, n.depth) - n.w;
1529
+ }
1530
+ const d = el.get(n.key);
1531
+ d.style.left = `${n.x}px`;
1532
+ d.style.top = `${n.cy - n.h / 2}px`;
1533
+ d.classList.toggle("left", n.side === -1);
1534
+ }
1535
+ const width = Math.max(...flat.map((n) => n.x + n.w)) + 48;
1536
+ const height = 32 + rows * ROW + 32;
1537
+ const paths = [];
1538
+ // A short trunk out of the parent (on the side its children grow), then curves fan out from its end.
1539
+ const link = (p) => {
1540
+ for (const side of [1, -1]) {
1541
+ const kids = p.children.filter((c) => c.side === side);
1542
+ if (!kids.length) continue;
1543
+ const x0 = side === 1 ? p.x + p.w : p.x, trunk = x0 + side * (p.type === "root" ? 22 : 12);
1544
+ paths.push(`<path d="M${x0} ${p.cy} H${trunk}" style="stroke:${p.type === "root" ? "var(--muted)" : p.color}" stroke-width="${p.type === "root" ? 2.6 : 2}"/>`);
1545
+ for (const c of kids) {
1546
+ const x2 = side === 1 ? c.x : c.x + c.w, k = Math.min(48, Math.abs(x2 - trunk) / 2) * side;
1547
+ const sw = c.depth === 1 ? 3 : c.type === "folder" ? 2.2 : 1.6;
1548
+ paths.push(`<path d="M${trunk} ${p.cy} C${trunk + k} ${p.cy}, ${x2 - k} ${c.cy}, ${x2} ${c.cy}" style="stroke:${c.color}" stroke-width="${sw}" class="${c.hit ? "hit" : ""}"/>`);
1549
+ link(c);
1550
+ }
1551
+ }
1552
+ };
1553
+ link(root);
1554
+ const svg = $("map-svg");
1555
+ svg.setAttribute("width", width);
1556
+ svg.setAttribute("height", height);
1557
+ svg.innerHTML = paths.join("");
1558
+ canvas.style.width = `${width}px`;
1559
+ canvas.style.height = `${height}px`;
1560
+ canvas.style.transform = `scale(${mapZoom})`;
1561
+ // The scroll area follows the zoomed size.
1562
+ canvas.style.marginRight = `${width * mapZoom - width}px`;
1563
+ canvas.style.marginBottom = `${height * mapZoom - height}px`;
1564
+ restoreFocus();
1565
+ const first = canvas.querySelector(".mnode.hit");
1566
+ const wrap = $("map-wrap");
1567
+ // Scroll only the map, never the page (the toolbar must stay reachable).
1568
+ if (first && q && wrap) wrap.scrollTo({ left: first.offsetLeft * mapZoom - wrap.clientWidth / 2, top: first.offsetTop * mapZoom - wrap.clientHeight / 2 });
1569
+ }
1570
+
1571
+ function mapZoomTo(z) {
1572
+ const wrap = $("map-wrap");
1573
+ // Zoom around the centre of what is on screen, not the top-left corner.
1574
+ const cx = wrap ? (wrap.scrollLeft + wrap.clientWidth / 2) / mapZoom : 0, cy = wrap ? (wrap.scrollTop + wrap.clientHeight / 2) / mapZoom : 0;
1575
+ mapZoom = Math.min(2, Math.max(0.3, Math.round(z * 20) / 20));
1576
+ store.set("driftnet-map-zoom", String(mapZoom));
1577
+ drawMap();
1578
+ if (wrap) { wrap.scrollLeft = cx * mapZoom - wrap.clientWidth / 2; wrap.scrollTop = cy * mapZoom - wrap.clientHeight / 2; }
1579
+ }
1580
+ const pulse = (key) => {
1581
+ const n = $("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(key)}"]`);
1582
+ if (!n) return;
1583
+ n.classList.remove("bump"); void n.offsetWidth; n.classList.add("bump");
1584
+ };
1585
+ const toggleFolder = (id) => {
1586
+ const refocus = document.activeElement?.dataset?.key === `f:${id}`;
1587
+ mapOpen.has(id) ? mapOpen.delete(id) : mapOpen.add(id); saveMapOpen(); drawMap(); syncMapToggle();
1588
+ if (refocus) $("map-canvas").querySelector(`.mnode[data-key="f:${CSS.escape(id)}"]`)?.focus();
1589
+ };
1590
+ /** The "+N" node: everything in that folder, as cards. */
1591
+ const showFolderList = (id) => { Object.assign(state, { view: "all", category: id, kind: "" }); load(); };
1592
+
1593
+ $("list").addEventListener("click", (e) => {
1594
+ const edit = e.target.closest(".mnode [data-edit]");
1595
+ if (edit && !picked && !justDropped) { e.stopPropagation(); return openFolderDialog(edit.dataset.edit); }
1596
+ const b = e.target.closest("[data-map]");
1597
+ if (!b) return;
1598
+ const a = b.dataset.map;
1599
+ if (a === "expand") { folders.forEach((f) => mapOpen.add(f.id)); saveMapOpen(); renderMap().then(() => { if (isDrawer()) fitMap(); }); }
1600
+ else if (a === "collapse") { mapOpen.clear(); saveMapOpen(); renderMap(); }
1601
+ else if (a === "new") openFolderDialog(null, null);
1602
+ else if (a === "layout") { mapLayout = mapLayout === "both" ? "right" : "both"; store.set("driftnet-map-layout", mapLayout); renderMap(); }
1603
+ else if (a === "tip") { store.set("driftnet-map-tip", "1"); b.closest(".map-tip").remove(); sizeMap(); }
1604
+ else if (a === "in") mapZoomTo(mapZoom + 0.1);
1605
+ else if (a === "out") mapZoomTo(mapZoom - 0.1);
1606
+ else if (a === "fit") fitMap();
1607
+ });
1608
+ $("list").addEventListener("dblclick", (e) => {
1609
+ const node = e.target.closest(".mnode.folder");
1610
+ if (!node) return;
1611
+ clearTimeout(folderTap);
1612
+ openFolderDialog(node.dataset.key.slice(2));
1613
+ });
1614
+
1615
+ /**
1616
+ * Tap: open/close a folder, preview a card, or open "+N". Drag: file a card onto a folder, or nest a folder.
1617
+ * Mouse drags right away; a finger holds ~0.3 s first, so a quick swipe still pans the map.
1618
+ */
1619
+ (() => {
1620
+ let press = null;
1621
+ const nodeAt = (x, y) => document.elementFromPoint(x, y)?.closest?.(".mnode");
1622
+ const clearDrop = () => document.querySelectorAll(".mnode.drop").forEach((d) => d.classList.remove("drop"));
1623
+ const endPress = () => {
1624
+ if (!press) return;
1625
+ clearTimeout(press.timer);
1626
+ press.ghost?.remove();
1627
+ press.el.classList.remove("dragging", "lift");
1628
+ clearDrop();
1629
+ press = null;
1630
+ };
1631
+ const startDrag = (e) => {
1632
+ press.drag = true;
1633
+ press.el.classList.add("dragging");
1634
+ press.ghost = press.el.cloneNode(true);
1635
+ press.ghost.classList.remove("dragging", "lift");
1636
+ press.ghost.classList.add("mghost");
1637
+ press.ghost.style.left = `${e.clientX}px`;
1638
+ press.ghost.style.top = `${e.clientY}px`;
1639
+ document.body.append(press.ghost);
1640
+ };
1641
+ // Mouse: drag the empty background to pan, like XMind.
1642
+ let pan = null;
1643
+ $("list").addEventListener("pointerdown", (e) => {
1644
+ const wrap = e.target.closest?.("#map-wrap");
1645
+ if (!wrap || e.pointerType !== "mouse" || e.button !== 0 || e.target.closest(".mnode, .map-zoom")) return;
1646
+ pan = { x: e.clientX, y: e.clientY, l: wrap.scrollLeft, t: wrap.scrollTop, wrap };
1647
+ wrap.classList.add("panning");
1648
+ });
1649
+ addEventListener("pointermove", (e) => { if (pan) { pan.wrap.scrollLeft = pan.l - (e.clientX - pan.x); pan.wrap.scrollTop = pan.t - (e.clientY - pan.y); } });
1650
+ addEventListener("pointerup", () => { if (pan) { pan.wrap.classList.remove("panning"); pan = null; } });
1651
+ $("list").addEventListener("pointerdown", (e) => {
1652
+ const node = e.target.closest(".mnode");
1653
+ // While something is picked up, the whole folder (its ⋯ too) is a drop target.
1654
+ if (!node || e.button > 0 || (e.target.closest("[data-edit]") && !picked)) return;
1655
+ const key = node.dataset.key;
1656
+ const movable = role === "admin" && (key.startsWith("i:") || key.startsWith("f:"));
1657
+ press = { key, el: node, x: e.clientX, y: e.clientY, drag: false, armed: false, touch: e.pointerType === "touch", movable, id: e.pointerId };
1658
+ if (!press.touch) node.setPointerCapture(e.pointerId);
1659
+ else if (movable) press.timer = setTimeout(() => { if (press) { press.armed = true; node.classList.add("lift"); navigator.vibrate?.(12); } }, 280);
1660
+ });
1661
+ $("list").addEventListener("pointermove", (e) => {
1662
+ if (!press || e.pointerId !== press.id) return;
1663
+ const moved = Math.hypot(e.clientX - press.x, e.clientY - press.y);
1664
+ if (!press.drag) {
1665
+ if (press.touch && !press.armed) { if (moved > 8) endPress(); return; } // a pan, not a drag
1666
+ if (moved > 6 && press.movable) startDrag(e);
1667
+ else return;
1668
+ }
1669
+ press.ghost.style.left = `${e.clientX}px`;
1670
+ press.ghost.style.top = `${e.clientY}px`;
1671
+ clearDrop();
1672
+ const over = nodeAt(e.clientX, e.clientY);
1673
+ if (over && over !== press.el && (over.classList.contains("folder") || (over.classList.contains("root") && press.key.startsWith("f:")))) over.classList.add("drop");
1674
+ const wrap = $("map-wrap"), r = wrap.getBoundingClientRect();
1675
+ press.edge = { x: e.clientX > r.right - 44 ? 1 : e.clientX < r.left + 44 ? -1 : 0, y: e.clientY > r.bottom - 44 ? 1 : e.clientY < r.top + 44 ? -1 : 0 };
1676
+ if (!press.scrolling && (press.edge.x || press.edge.y)) {
1677
+ // Keep scrolling while the finger rests near an edge.
1678
+ press.scrolling = true;
1679
+ const tick = () => {
1680
+ if (!press?.drag || !(press.edge.x || press.edge.y)) { if (press) press.scrolling = false; return; }
1681
+ wrap.scrollLeft += press.edge.x * 10; wrap.scrollTop += press.edge.y * 10;
1682
+ requestAnimationFrame(tick);
1683
+ };
1684
+ requestAnimationFrame(tick);
1685
+ }
1686
+ });
1687
+ // While a lifted node is dragged by a finger, the page must not scroll.
1688
+ document.addEventListener("touchmove", (e) => { if (press && press.drag && e.cancelable) e.preventDefault(); }, { passive: false });
1689
+ const finish = async (e) => {
1690
+ if (!press || e.pointerId !== press.id) return;
1691
+ const p = press;
1692
+ // Held, then let go without dragging: the card stays picked up; the next tapped folder receives it.
1693
+ if (p.touch && p.armed && !p.drag) { endPress(); if (p.movable) pickUp(p.key); return; }
1694
+ const target = p.drag ? document.querySelector(".mnode.drop") : null;
1695
+ endPress();
1696
+ if (!p.drag) return tapNode(p.key, !p.touch);
1697
+ if (!target) return;
1698
+ const to = target.dataset.key === "root" ? null : target.dataset.key.slice(2);
1699
+ if (p.key.startsWith("i:")) await mapMoveItem(Number(p.key.slice(2)), to);
1700
+ else await mapMoveFolder(p.key.slice(2), to);
1701
+ };
1702
+ $("list").addEventListener("pointerup", finish);
1703
+ $("list").addEventListener("pointercancel", (e) => { if (press && e.pointerId === press.id) endPress(); });
1704
+ $("list").addEventListener("keydown", (e) => {
1705
+ const node = e.target.closest?.(".mnode");
1706
+ if (!node) return;
1707
+ if (e.key === "Enter" || e.key === " ") { e.preventDefault(); tapNode(node.dataset.key); }
1708
+ else if ((e.key === "F2" || e.key === "e") && node.dataset.key.startsWith("f:") && role === "admin") { e.preventDefault(); openFolderDialog(node.dataset.key.slice(2)); }
1709
+ else if (e.key === "m" && node.dataset.key.startsWith("i:") && role === "admin") { e.preventDefault(); openMovePicker(Number(node.dataset.key.slice(2))); }
1710
+ });
1711
+ })();
1712
+ let folderTap = null;
1713
+ /**
1714
+ * Picking up (touch): hold a card or folder, let go, then tap the folder it goes into.
1715
+ * Nothing competes with scrolling, and no precise finger drag is needed.
1716
+ */
1717
+ let picked = null;
1718
+ function pickUp(key) {
1719
+ picked = key;
1720
+ const t = T();
1721
+ const label = key.startsWith("i:") ? nameOf(mapItems.find((i) => i.id === Number(key.slice(2))) ?? { title: "" }) : catLabel(key.slice(2));
1722
+ $("pick-text").textContent = t.pickedUp(label);
1723
+ $("pick-cancel").textContent = t.cancel;
1724
+ $("pickbar").hidden = false;
1725
+ $("map-canvas")?.querySelector(`.mnode[data-key="${CSS.escape(key)}"]`)?.classList.add("picked");
1726
+ }
1727
+ let justDropped = false;
1728
+ function dropPicked() {
1729
+ picked = null;
1730
+ justDropped = true;
1731
+ setTimeout(() => (justDropped = false), 400); // the click that follows the tap isn't an edit
1732
+ $("pickbar").hidden = true;
1733
+ document.querySelectorAll(".mnode.picked").forEach((n) => n.classList.remove("picked"));
1734
+ }
1735
+ function tapNode(key, viaMouse = false) {
1736
+ if (picked) {
1737
+ const what = picked;
1738
+ if (key === what) return dropPicked();
1739
+ if (key.startsWith("f:") || (key === "root" && what.startsWith("f:"))) {
1740
+ dropPicked();
1741
+ const to = key === "root" ? null : key.slice(2);
1742
+ return what.startsWith("i:") ? mapMoveItem(Number(what.slice(2)), to) : mapMoveFolder(what.slice(2), to);
1743
+ }
1744
+ }
1745
+ // A mouse double-click edits the folder, so a single click waits a moment to be sure.
1746
+ if (key.startsWith("f:") && viaMouse) { clearTimeout(folderTap); folderTap = setTimeout(() => toggleFolder(key.slice(2)), 230); return; }
1747
+ if (key.startsWith("f:")) toggleFolder(key.slice(2));
1748
+ else if (key.startsWith("i:")) openPeek(Number(key.slice(2)));
1749
+ else if (key.startsWith("m:")) showFolderList(key.slice(2));
1750
+ }
1751
+ // A long press on a phone must not open the system menu over the map.
1752
+ $("list").addEventListener("contextmenu", (e) => { if (e.target.closest(".mnode")) e.preventDefault(); });
1753
+
1754
+ /** A card from the map, without leaving the map. */
1755
+ let peeking = null;
1756
+ function openPeek(id) {
1757
+ const i = mapItems.find((x) => x.id === id) ?? find(id);
1758
+ if (!i) return;
1759
+ peeking = id;
1760
+ const t = T(), s = i.summary;
1761
+ $("pk-body").innerHTML = `<h3>${esc(s?.name ?? i.title)}</h3>
1762
+ <p><span class="badge folder" style="--c:${folderColor(i.category)}">${esc(folderPath(i.category))}</span>
1763
+ <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span></p>
1764
+ ${s ? `<p>${esc(s.oneLiner)}</p>` : ""}
1765
+ ${s?.highlights?.length ? `<ul>${s.highlights.map((h) => `<li>${esc(h)}</li>`).join("")}</ul>` : ""}
1766
+ ${i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""}`;
1767
+ $("pk-open").href = safeUrl(s?.primaryUrl || i.url);
1768
+ $("pk-open").innerHTML = `${ic("link")} ${esc(t.openLink)}`;
1769
+ $("pk-move").innerHTML = `${ic("move")} ${esc(t.moveTo)}`;
1770
+ $("pk-move").hidden = role !== "admin";
1771
+ $("pk-list").innerHTML = `${ic("list")} ${esc(t.showInList)}`;
1772
+ $("pk-close").textContent = t.close;
1773
+ $("pk-close").hidden = matchMedia("(max-width: 720px)").matches; // tap outside closes it on a phone
1774
+ $("peek-dlg").showModal();
1775
+ }
1776
+ $("pk-close").onclick = () => $("peek-dlg").close();
1777
+ $("pick-cancel").onclick = () => dropPicked();
1778
+ $("peek-dlg").addEventListener("click", (e) => { if (e.target === $("peek-dlg")) $("peek-dlg").close(); });
1779
+ $("pk-move").onclick = () => { $("peek-dlg").close(); openMovePicker(peeking); };
1780
+ $("pk-list").onclick = () => {
1781
+ $("peek-dlg").close();
1782
+ Object.assign(state, { view: "all", category: "", kind: "" });
1783
+ history.replaceState(null, "", `#item-${peeking}`);
1784
+ load();
1785
+ };
1786
+
1787
+ async function mapWrite(path, method, body) {
1788
+ const token = store.get("driftnet-token");
1789
+ const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
1790
+ ...(body ? { body: JSON.stringify(body) } : {}) }).catch(() => null);
1791
+ if (res?.status === 401) { needAdmin(); return null; }
1792
+ const data = await res?.json().catch(() => ({}));
1793
+ if (!res?.ok) { toast(data?.error ?? T().failed); return null; }
1794
+ return data;
1795
+ }
1796
+ async function mapMoveItem(id, to) {
1797
+ const item = mapItems.find((i) => i.id === id);
1798
+ if (!item || !to) return;
1799
+ if (item.category === to) return toast(T().alreadyThere);
1800
+ const from = item.category;
1801
+ if (!(await mapWrite(`/api/items/${id}/move`, "POST", { folder: to }))) return;
1802
+ item.category = to;
1803
+ // Filing many cards in a row: the target stays as it was (no sudden expansion); its count pulses instead.
1804
+ drawMap();
1805
+ pulse(`f:${to}`);
1806
+ toast(T().moved(nameOf(item), folderPath(to)), async () => {
1807
+ if (await mapWrite(`/api/items/${id}/move`, "POST", { folder: from })) { item.category = from; drawMap(); refreshFolders(); }
1808
+ });
1809
+ refreshFolders();
1810
+ }
1811
+ async function mapMoveFolder(id, to) {
1812
+ if (id === to || (to && subtreeOf(id).has(to))) return;
1813
+ const f = folderById(id);
1814
+ if (!f || f.parent === to) return;
1815
+ const from = f.parent;
1816
+ if (!(await mapWrite(`/api/folders/${encodeURIComponent(id)}`, "PATCH", { parent: to }))) return;
1817
+ f.parent = to;
1818
+ if (to) { mapOpen.add(to); saveMapOpen(); }
1819
+ drawMap();
1820
+ toast(T().folderMoved(catLabel(id), to ? folderPath(to) : T().topLevelShort), async () => {
1821
+ if (await mapWrite(`/api/folders/${encodeURIComponent(id)}`, "PATCH", { parent: from })) { f.parent = from; drawMap(); refreshFolders(); }
1822
+ });
1823
+ refreshFolders();
1824
+ }
1825
+ /** Keep the sidebar tree and counts in step after a change made on the map. */
1826
+ async function refreshFolders() {
1827
+ folders = await api("/api/folders").catch(() => folders);
1828
+ refreshTree();
1829
+ }
1830
+
1831
+ // ── Unlock editing with the admin password ────────────────────────────────
1832
+ function openLogin() {
1833
+ const st = T().st;
1834
+ $("lg-title").textContent = st.loginTitle;
1835
+ $("lg-label").textContent = locale === "zh-TW" ? "密碼" : "Password";
1836
+ $("lg-help").textContent = st.loginHelp;
1837
+ $("lg-adv-s").textContent = locale === "zh-TW" ? "忘記密碼?" : "Forgot it?";
1838
+ $("lg-adv").textContent = st.loginAdvanced.replaceAll("PORT", String(serverPort));
1839
+ $("lg-ok").textContent = st.loginOk;
1840
+ $("lg-cancel").textContent = T().cancel;
1841
+ $("lg-error").textContent = "";
1842
+ $("lg-pw").value = "";
1843
+ $("login-dlg").showModal();
1844
+ $("lg-pw").focus();
1845
+ }
1846
+ $("lg-cancel").onclick = () => $("login-dlg").close();
1847
+ $("lock").onclick = () => openLogin();
1848
+ $("login-form").onsubmit = async (e) => {
1849
+ e.preventDefault();
1850
+ const pw = $("lg-pw").value.trim();
1851
+ if (!pw) return;
1852
+ // Only the admin password opens the settings, so that is the check.
1853
+ const res = await fetch("/api/settings", { headers: { authorization: `Bearer ${pw}` } }).catch(() => null);
1854
+ if (!res?.ok) { $("lg-error").textContent = T().st.loginWrong; return; }
1855
+ store.set("driftnet-token", pw);
1856
+ $("login-dlg").close();
1857
+ toast(T().st.unlocked);
1858
+ // Another dialog (a note being written) stays open: only refresh the page behind it.
1859
+ if (!document.querySelector("dialog[open]")) load();
1860
+ else { role = "admin"; document.body.classList.remove("readonly"); $("lock").hidden = true; }
1861
+ };
943
1862
 
944
1863
  // ── Connect an AI: copy-paste cards with the URL and keys filled in ───────
945
1864
  async function openConnect() {
@@ -952,11 +1871,14 @@
952
1871
  const key = a?.readKey || (zh ? "<唯讀分享碼>" : "<share-key>");
953
1872
  const pw = zh ? "<你的管理密碼>" : "<your-admin-password>";
954
1873
  const withKey = (u) => (a?.private || a?.readKey ? `${u}?key=${key}` : u);
955
- const card = (id, title, desc, code) => `<div class="conn"><h4>${esc(title)}</h4><p>${esc(desc)}</p>
956
- <button class="btn copy" type="button" data-copy="#cx-${id}">${esc(st.copy)}</button><pre id="cx-${id}">${esc(code)}</pre></div>`;
1874
+ const card = (id, title, desc, code) => `<div class="conn"><div class="conn-head"><h4>${esc(title)}</h4>
1875
+ <button class="btn copy" type="button" data-copy="#cx-${id}">${esc(st.copy)}</button></div><p>${esc(desc)}</p><pre id="cx-${id}">${esc(code)}</pre></div>`;
957
1876
  const cards = [
958
- card("cc", "Claude Code", zh ? "這台電腦上:裝插件(含 skill 和本機 MCP)。在別台電腦:連這個網址,可以讀也可以寫。" : "On this computer: the plugin (skill + local MCP). Elsewhere: connect to this URL, read and write.",
959
- `/plugin install driftnet --marketplace KevinChu1110/driftnet\n\nclaude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer ${pw}"`),
1877
+ card("ccp", zh ? "Claude Code:裝插件" : "Claude Code: the plugin", zh ? "在 Claude Code 裡輸入。會裝好 skill 和本機 MCP。" : "Type it inside Claude Code. Brings the skill and a local MCP server.",
1878
+ `/plugin install driftnet --marketplace KevinChu1110/driftnet`),
1879
+ card("cc", zh ? "Claude Code:連到這個 driftnet" : "Claude Code: connect to this driftnet",
1880
+ zh ? "在終端機執行。先 export DRIFTNET_TOKEN=你的管理密碼,指令會自動帶入。" : "Run in a terminal. Export DRIFTNET_TOKEN=<your admin password> first; the command reads it.",
1881
+ `claude mcp add --transport http driftnet ${base}/mcp \\\n --header "Authorization: Bearer $DRIFTNET_TOKEN"`),
960
1882
  card("claude", zh ? "Claude 網頁版/桌面版(自訂 connector)" : "Claude.ai / Claude Desktop (custom connector)",
961
1883
  zh ? "設定 → Connectors → 新增自訂 connector,貼上這個網址。用分享碼連線,只能搜尋和查看,不能改。" : "Settings → Connectors → Add custom connector, paste this URL. The share key makes it read-only: search and look, no changes.",
962
1884
  withKey(`${base}/mcp`)),
@@ -967,16 +1889,16 @@
967
1889
  zh ? "只要 AI 會開網址就行,把這段貼進對話。唯讀。" : "Any AI that can open a link: paste this into the chat. Read-only.",
968
1890
  zh ? `讀一下 ${withKey(`${base}/llms.txt`)} ,這是我收藏的 AI 工具清單。幫我找適合「(你的需求)」的工具。`
969
1891
  : `Read ${withKey(`${base}/llms.txt`)} — it's my catalogue of AI tools. Find me one for: (your task).`),
970
- card("agents", "Hermes / OpenClaw / pi", zh ? "這些 agent 的 MCP 設定。用管理密碼可以收錄、投票、幫忙讀佇列裡的連結。" : "MCP settings for these agents. With the admin password they can save, vote and work the queue.",
1892
+ 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.",
971
1893
  JSON.stringify({ mcpServers: { driftnet: { type: "http", url: `${base}/mcp`, headers: { Authorization: `Bearer ${pw}` } } } }, null, 2)),
972
1894
  ].join("");
973
1895
  const warn = isLocalUrl
974
- ? `<p class="warn danger">${esc(zh ? "這個網址只有這台電腦連得到。雲端的 AI(Claude 網頁版、ChatGPT、Grok、別台機器上的 agent)請先到 ⚙ 設定 →「存取與連線」開公開網址。"
975
- : "This address only works on this computer. For cloud AIs (Claude.ai, ChatGPT, Grok, agents on other machines), open a public URL first: ⚙ Settings → Access & connections.")}</p>` : "";
976
- const noKey = a && !a.readKey ? `<p class="warn">${esc(zh ? "還沒有唯讀分享碼:到 ⚙ 設定 →「存取與連線」產生一組。" : "No share key yet: make one in ⚙ Settings → Access & connections.")}</p>` : "";
1896
+ ? `<p class="warn">${esc(zh ? "這個網址只有這台電腦連得到。雲端的 AI(Claude 網頁版、ChatGPT、Grok、別台機器上的 agent)請先到「設定 → 存取」開公開網址。"
1897
+ : "This address only works on this computer. For cloud AIs (Claude.ai, ChatGPT, Grok, agents on other machines), open a public URL first: Settings → Access.")}</p>` : "";
1898
+ const noKey = a && !a.readKey ? `<p class="warn">${esc(zh ? "還沒有唯讀分享碼:到「設定 → 存取」產生一組。" : "No share key yet: make one in Settings → Access.")}</p>` : "";
977
1899
  $("cx-title").textContent = st.connect;
978
1900
  $("cx-body").innerHTML = warn + noKey + cards;
979
- $("cx-close").textContent = t.cancel === "Cancel" ? "Close" : "關閉";
1901
+ $("cx-close").textContent = t.close;
980
1902
  $("connect-dlg").showModal();
981
1903
  }
982
1904
  $("cx-close").onclick = () => $("connect-dlg").close();
@@ -994,7 +1916,8 @@
994
1916
  const token = store.get("driftnet-token");
995
1917
  const res = await fetch(path, { method, headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
996
1918
  ...(body ? { body: JSON.stringify(body) } : {}) }).catch(() => null);
997
- if (res?.status === 401) { document.querySelectorAll("dialog[open]").forEach((d) => d.close()); askToken(); return null; }
1919
+ // Keep the open dialog (and what was typed in it); unlock on top, then save again.
1920
+ if (res?.status === 401) { needAdmin(); return null; }
998
1921
  if (!res?.ok) { toast(T().failed); return null; }
999
1922
  return res.json();
1000
1923
  }
@@ -1023,6 +1946,7 @@
1023
1946
  item.note = saved.note;
1024
1947
  const el = document.getElementById(`item-${noting}`);
1025
1948
  if (el) { el.outerHTML = card(item); attachSwipe(document.getElementById(`item-${noting}`)); }
1949
+ setTimeout(restoreFocus, 0);
1026
1950
  toast(T().saved);
1027
1951
  };
1028
1952
 
@@ -1059,8 +1983,8 @@
1059
1983
  async function renderNotes() {
1060
1984
  const t = T();
1061
1985
  notes = await api(`/api/notes${state.q ? `?q=${encodeURIComponent(state.q)}` : ""}`);
1062
- $("list").innerHTML = `<div class="bar"><span class="hint">${esc(t.noteBody)}</span><span class="spacer"></span>
1063
- <button class="btn primary" type="button" id="new-note">${esc(t.newNote)}</button></div>` +
1986
+ $("list").innerHTML = `<div class="bar"><span class="hint">${notes.length ? esc(t.noteBody) : ""}</span><span class="spacer"></span>
1987
+ <button class="btn primary" type="button" id="new-note">${ic("plus")} ${esc(t.newNote)}</button></div>` +
1064
1988
  (notes.length
1065
1989
  ? notes.map((n) => `<button type="button" class="note-card" data-note="${n.id}"><h3>${esc(n.title || t.untitled)}</h3>
1066
1990
  <div class="md">${md(n.body)}</div><div class="meta"><span>${esc(n.updatedAt.slice(0, 10))}</span></div></button>`).join("")
@@ -1124,9 +2048,28 @@
1124
2048
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
1125
2049
  }
1126
2050
 
2051
+ /** The first link, straight from the page (the empty list offers this). */
2052
+ async function addLink(e) {
2053
+ e.preventDefault();
2054
+ const url = $("add-url").value.trim();
2055
+ if (!/^https?:\/\//.test(url)) return toast(T().addPlaceholder);
2056
+ const b = e.submitter; if (b) b.disabled = true;
2057
+ const token = store.get("driftnet-token");
2058
+ const res = await fetch("/api/ingest", { method: "POST", body: JSON.stringify({ url }),
2059
+ headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) } }).catch(() => null);
2060
+ if (b) b.disabled = false;
2061
+ if (res?.status === 401) return needAdmin();
2062
+ if (!res?.ok) return toast(T().failed);
2063
+ toast(T().added);
2064
+ load();
2065
+ }
2066
+
1127
2067
  async function render() {
1128
2068
  updateCrumb();
2069
+ document.body.classList.toggle("map-view", state.view === "map");
2070
+ if (state.view !== "map" && picked) dropPicked();
1129
2071
  if (state.view === "notes") return renderNotes();
2072
+ if (state.view === "map") return renderMap();
1130
2073
  const p = new URLSearchParams({ limit: "300" });
1131
2074
  if (prefs.sort !== "best") p.set("sort", prefs.sort);
1132
2075
  if (state.view !== "all") p.set("view", state.view);
@@ -1135,11 +2078,25 @@
1135
2078
  const t = T();
1136
2079
  const empty = state.view === "trash" ? t.emptyTrash : state.view === "favorites" ? t.emptyFav : t.empty;
1137
2080
  $("list").innerHTML = items.length
1138
- ? `<p class="hint">${esc(state.view === "trash" ? t.hintTrash : t.hint)}</p>` + items.map(card).join("")
1139
- : `<div class="empty">${esc(empty)}</div>`;
2081
+ ? `<p class="hint swipe-hint">${esc(state.view === "trash" ? t.hintTrash : t.hint)}</p>` + items.map(card).join("")
2082
+ : `<div class="empty first"><span>${esc(empty)}</span>${state.view === "all" && !state.q && !state.category && role === "admin"
2083
+ ? `<form class="add" id="add-form"><input id="add-url" type="url" inputmode="url" placeholder="${esc(t.addPlaceholder)}" aria-label="${esc(t.addPlaceholder)}">
2084
+ <button class="btn primary" type="submit">${ic("plus")} ${esc(t.addLink)}</button></form>
2085
+ <button class="btn" type="button" data-connect-empty>${ic("plug")} ${esc(t.st.connect)}</button>` : ""}</div>`;
2086
+ $("add-form")?.addEventListener("submit", addLink);
2087
+ $("list").querySelector("[data-connect-empty]")?.addEventListener("click", () => openConnect());
1140
2088
  for (const el of $("list").querySelectorAll(".swipe")) attachSwipe(el);
2089
+ restoreFocus();
1141
2090
  // Only #item-<n> is ours; anything else in the hash must not break the page.
1142
- if (/^#item-\d+$/.test(location.hash)) document.getElementById(location.hash.slice(1))?.scrollIntoView();
2091
+ if (/^#item-\d+$/.test(location.hash)) {
2092
+ const target = document.getElementById(location.hash.slice(1));
2093
+ if (target) {
2094
+ // Clear the sticky header (taller on a phone), then flash the card so it's obvious which one was meant.
2095
+ const top = target.getBoundingClientRect().top + scrollY - document.querySelector("header").offsetHeight - ($("crumb").offsetHeight || 0) - 12;
2096
+ scrollTo({ top });
2097
+ target.classList.remove("flash"); void target.offsetWidth; target.classList.add("flash");
2098
+ }
2099
+ }
1143
2100
  }
1144
2101
 
1145
2102
  function card(i) {
@@ -1148,34 +2105,34 @@
1148
2105
  const url = safeUrl(s?.primaryUrl || i.url);
1149
2106
  const inTrash = state.view === "trash";
1150
2107
  const tools = inTrash
1151
- ? `<button class="tool" type="button" data-act="restore" title="${esc(t.restore)}" aria-label="${esc(t.restore)}">↩</button>`
1152
- : `<button class="tool grip" type="button" draggable="true" data-grip="${i.id}" title="${esc(t.dragHint)}" aria-hidden="true" tabindex="-1">⠿</button>
1153
- <button class="tool" type="button" data-act="move" title="${esc(t.moveTo)}" aria-label="${esc(t.moveTo)}">📁</button>
2108
+ ? `<button class="tool" type="button" data-act="restore" title="${esc(t.restore)}" aria-label="${esc(t.restore)}">${ic("undo")}</button>`
2109
+ : `<button class="tool grip" type="button" draggable="true" data-grip="${i.id}" title="${esc(t.dragHint)}" aria-hidden="true" tabindex="-1">${ic("grip")}</button>
2110
+ <button class="tool" type="button" data-act="move" title="${esc(t.moveTo)}" aria-label="${esc(t.moveTo)}">${ic("move")}</button>
1154
2111
  <button class="tool ${i.favorite ? "on" : ""}" type="button" data-act="favorite" aria-pressed="${i.favorite}"
1155
- title="${esc(i.favorite ? t.unfavorite : t.favorite)}" aria-label="${esc(i.favorite ? t.unfavorite : t.favorite)}">${i.favorite ? "★" : "☆"}</button>
1156
- <button class="tool" type="button" data-act="trash" title="${esc(t.remove)}" aria-label="${esc(t.remove)}">🗑</button>`;
2112
+ title="${esc(i.favorite ? t.unfavorite : t.favorite)}" aria-label="${esc(i.favorite ? t.unfavorite : t.favorite)}">${ic("star")}</button>
2113
+ <button class="tool" type="button" data-act="trash" title="${esc(t.remove)}" aria-label="${esc(t.remove)}">${ic("trash")}</button>`;
1157
2114
  return `<div class="swipe" id="item-${i.id}" data-id="${i.id}">
1158
- <div class="act right ${inTrash ? "restore" : ""}"><span>${esc(inTrash ? t.swipeRestore : i.favorite ? t.swipeUnfav : t.swipeFav)}</span></div>
1159
- <div class="act left"><span>${esc(inTrash ? "" : t.swipeTrash)}</span></div>
1160
- <article class="card">
2115
+ <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>
2116
+ <div class="act left"><span>${inTrash ? "" : `${esc(t.swipeTrash)} ${ic("trash")}`}</span></div>
2117
+ <article class="card" tabindex="0" aria-labelledby="name-${i.id}">
1161
2118
  <div class="top">
1162
- <a class="name" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(s?.name ?? i.title)}</a>
1163
- <span class="badge">${esc(catLabel(i.category))}</span>
1164
- <span class="badge worth-${esc(i.worth)}">${esc(t.worth[i.worth] ?? i.worth)}</span>
1165
- ${i.pending ? `<span class="badge">${esc(t.pending)}</span>` : ""}
2119
+ <a class="name" id="name-${i.id}" href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(s?.name ?? i.title)}</a>
2120
+ <span class="badge folder" style="--c:${folderColor(i.category)}">${esc(catLabel(i.category))}</span>
2121
+ <span class="rating ${i.worth === "must-see" ? "must" : ""}">${i.worth === "must-see" ? ic("star") : ""}${esc(t.worth[i.worth] ?? i.worth)}</span>
2122
+ ${i.pending ? `<span class="rating">${esc(summaries ? t.pending : t.noModel)}</span>` : ""}
1166
2123
  </div>
1167
2124
  ${s ? `<p>${esc(s.oneLiner)}</p>` : ""}
1168
2125
  ${s?.highlights?.length ? `<ul>${s.highlights.map((h) => `<li>${esc(h)}</li>`).join("")}</ul>` : ""}
1169
- ${(i.said ?? []).slice(0, 2).map((x) => `<div class="said">${esc(x)}</div>`).join("")}
1170
- ${i.note ? `<div class="mynote">${esc(i.note)}</div>` : ""}
2126
+ ${(i.said ?? []).slice(0, 2).map((x) => `<div class="said">${ic("chat")}<span>${esc(x)}</span></div>`).join("")}
2127
+ ${i.note ? `<div class="mynote">${ic("note")}<span>${esc(i.note)}</span></div>` : ""}
1171
2128
  ${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>` : ""}
1172
2129
  ${i.flags.length ? `<div class="flag">⚠ ${esc(i.flags.map((f) => t.flags[f] ?? f).join(", "))}</div>` : ""}
1173
2130
  <div class="meta">
1174
- <span>#${i.id}</span><span>${esc(t.kinds[i.kind] ?? i.kind)}</span>${i.shareCount ? `<span>${esc(t.shared(i.shareCount))}</span>` : ""}
2131
+ <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>` : ""}
1175
2132
  <span>${esc(i.createdAt.slice(0, 10))}</span>
1176
2133
  ${i.enrichedBy ? `<span>${esc(t.enrichedBy(i.enrichedBy.replace(/^agent:/, "")))}</span>` : ""}
1177
- ${s?.tags?.length ? `<span class="tags">${s.tags.map((x) => "#" + esc(x)).join(" ")}</span>` : ""}
1178
- ${inTrash ? "" : `<button class="link-btn" type="button" data-act="note">${esc(i.note ? t.editNote : t.addNote)}</button>`}
2134
+ ${s?.tags?.length ? `<span class="tags">${s.tags.map((x) => `<span class="tag">#${esc(x)}</span>`).join(" ")}</span>` : ""}
2135
+ ${inTrash ? "" : `<button class="link-btn" type="button" data-act="note">${ic("note")} ${esc(i.note ? t.editNote : t.addNote)}</button>`}
1179
2136
  </div>
1180
2137
  <div class="tools">${tools}</div>
1181
2138
  </article>
@@ -1183,17 +2140,15 @@
1183
2140
  }
1184
2141
 
1185
2142
  // ── Actions ──────────────────────────────────────────────────────────────
1186
- const find = (id) => items.find((x) => x.id === id);
2143
+ const find = (id) => items.find((x) => x.id === id) ?? mapItems.find((x) => x.id === id);
1187
2144
  const nameOf = (i) => (i.summary?.name ?? i.title).slice(0, 40);
1188
2145
 
1189
2146
  async function act(id, action) {
1190
- try {
1191
- return await api(`/api/items/${id}/${action}`, { method: "POST" });
1192
- } catch (err) {
1193
- if (err.unauthorized) return new Promise((resolve) => askToken(async () => { await load(); resolve(null); }));
1194
- toast(T().failed);
1195
- throw err;
1196
- }
2147
+ const token = store.get("driftnet-token");
2148
+ const res = await fetch(`/api/items/${id}/${action}`, { method: "POST", headers: token ? { authorization: `Bearer ${token}` } : {} }).catch(() => null);
2149
+ if (res?.status === 401) { needAdmin(); return null; }
2150
+ if (!res?.ok) { toast(T().failed); return null; }
2151
+ return res.json();
1197
2152
  }
1198
2153
 
1199
2154
  /** Collapse a card out of the list, then refresh the counts. */
@@ -1213,17 +2168,21 @@
1213
2168
  if (!item) return;
1214
2169
  const t = T();
1215
2170
  if (action === "trash" || action === "restore") {
2171
+ // Only once the server agreed: a refused change must not look done.
2172
+ if (!(await act(id, action))) { el.querySelector(".card").style.transform = ""; delete el.dataset.dir; return; }
2173
+ // Keyboard users stay in the list: focus moves to the next card.
2174
+ if (el.contains(document.activeElement)) (el.nextElementSibling ?? el.previousElementSibling)?.querySelector?.(".card")?.focus();
1216
2175
  el.querySelector(".card").style.transform = `translateX(${action === "trash" ? "-110%" : "110%"})`;
1217
2176
  dismiss(el);
1218
- await act(id, action);
1219
2177
  const back = action === "trash" ? "restore" : "trash";
1220
2178
  toast(action === "trash" ? t.removed(nameOf(item)) : t.restored(nameOf(item)), async () => { await act(id, back); load(); });
1221
2179
  } else {
1222
2180
  const on = !item.favorite;
1223
- await act(id, on ? "favorite" : "unfavorite");
2181
+ if (!(await act(id, on ? "favorite" : "unfavorite"))) return;
1224
2182
  item.favorite = on;
2183
+ const hadFocus = el.contains(document.activeElement);
1225
2184
  if (state.view === "favorites" && !on) dismiss(el);
1226
- else el.outerHTML = card(item), attachSwipe(document.getElementById(`item-${id}`));
2185
+ else { el.outerHTML = card(item); attachSwipe(document.getElementById(`item-${id}`)); if (hadFocus) document.querySelector(`#item-${id} .card`)?.focus(); }
1227
2186
  if (on) toast(t.faved(nameOf(item)));
1228
2187
  }
1229
2188
  refreshCounts();
@@ -1262,8 +2221,24 @@
1262
2221
  }
1263
2222
  });
1264
2223
 
2224
+ /** A reader who swipes gets a nudge (and a shake), not silence. */
2225
+ let nudged = 0;
2226
+ function readerSwipe(el) {
2227
+ const cardEl = el.querySelector(".card");
2228
+ let x0 = 0, y0 = 0, on = false;
2229
+ cardEl.addEventListener("pointerdown", (e) => { x0 = e.clientX; y0 = e.clientY; on = true; });
2230
+ cardEl.addEventListener("pointermove", (e) => {
2231
+ if (!on || Math.abs(e.clientX - x0) < 30 || Math.abs(e.clientX - x0) < Math.abs(e.clientY - y0)) return;
2232
+ on = false;
2233
+ cardEl.classList.remove("shake"); void cardEl.offsetWidth; cardEl.classList.add("shake");
2234
+ if (Date.now() - nudged > 4000) { nudged = Date.now(); toast(T().readOnlyNudge); $("lock").classList.remove("bump"); void $("lock").offsetWidth; $("lock").classList.add("bump"); }
2235
+ });
2236
+ cardEl.addEventListener("pointerup", () => (on = false));
2237
+ }
2238
+
1265
2239
  // ── Swipe: right = favorite (restore in the trash), left = trash ─────────
1266
2240
  function attachSwipe(el) {
2241
+ if (el && role !== "admin") return readerSwipe(el);
1267
2242
  if (!el) return;
1268
2243
  const cardEl = el.querySelector(".card");
1269
2244
  let x0 = 0, y0 = 0, dx = 0, active = false, horizontal = null;
@@ -1313,16 +2288,79 @@
1313
2288
 
1314
2289
  // ── Toast with undo ──────────────────────────────────────────────────────
1315
2290
  let toastTimer;
2291
+ /**
2292
+ * Keyboard focus survives re-renders: remember the card or map node last focused, and put focus back
2293
+ * when a re-render or a closing dialog would otherwise drop it on <body>.
2294
+ */
2295
+ let focusKey = null, focusAt = 0;
2296
+ document.addEventListener("focusin", (e) => {
2297
+ const card = e.target.closest?.(".swipe"), node = e.target.closest?.(".mnode");
2298
+ if (card) { focusKey = `#${card.id} .card`; focusAt = Date.now(); }
2299
+ else if (node) { focusKey = `.mnode[data-key="${CSS.escape(node.dataset.key)}"]`; focusAt = Date.now(); }
2300
+ });
2301
+ function restoreFocus() {
2302
+ if (!focusKey || Date.now() - focusAt > 60_000 || document.querySelector("dialog[open]")) return;
2303
+ if (document.activeElement && document.activeElement !== document.body) return;
2304
+ const el = document.querySelector(focusKey);
2305
+ if (el) el.focus({ preventScroll: true });
2306
+ }
2307
+ for (const d of document.querySelectorAll("dialog")) d.addEventListener("close", () => setTimeout(restoreFocus, 0));
2308
+ /** The newest undoable action, so z (or ⌘/Ctrl+Z) can undo it from the keyboard. */
2309
+ let lastUndo = null;
1316
2310
  function toast(text, undo) {
1317
2311
  $("toast-text").textContent = text;
1318
2312
  const u = $("toast-undo");
1319
2313
  u.hidden = !undo;
1320
2314
  u.textContent = T().undo;
1321
- u.onclick = async () => { $("toast").classList.remove("show"); await undo?.(); };
2315
+ lastUndo = undo ?? null;
2316
+ u.onclick = async () => { clearTimeout(toastTimer); $("toast").classList.remove("show"); lastUndo = null; await undo?.(); };
1322
2317
  $("toast").classList.add("show");
2318
+ toastMs = Math.min(9000, 4500 + text.length * 45);
1323
2319
  clearTimeout(toastTimer);
1324
- toastTimer = setTimeout(() => $("toast").classList.remove("show"), 5000);
2320
+ toastTimer = setTimeout(hideToast, toastMs);
1325
2321
  }
2322
+ // Once the toast is gone, z no longer undoes something you can't see any more.
2323
+ function hideToast() { $("toast").classList.remove("show"); lastUndo = null; }
2324
+ let toastMs = 5000;
2325
+ // Reading or reaching for Undo keeps the toast up.
2326
+ for (const ev of ["pointerenter", "focusin"]) $("toast").addEventListener(ev, () => clearTimeout(toastTimer));
2327
+ for (const ev of ["pointerleave", "focusout"]) $("toast").addEventListener(ev, () => {
2328
+ clearTimeout(toastTimer);
2329
+ if ($("toast").classList.contains("show")) toastTimer = setTimeout(hideToast, 2500);
2330
+ });
2331
+
2332
+ // ── Keyboard: j/k to step through cards, then act on the focused one ─────
2333
+ let lastKey = "";
2334
+ addEventListener("keydown", (e) => {
2335
+ if ((e.metaKey || e.ctrlKey) && e.key === "z" && lastUndo && !/^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? "")) { e.preventDefault(); $("toast-undo").click(); return; }
2336
+ if (e.metaKey || e.ctrlKey || e.altKey || document.querySelector("dialog[open]")) return;
2337
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName ?? "")) return;
2338
+ const k = e.key, prev = lastKey;
2339
+ lastKey = k;
2340
+ if (k === "/") { e.preventDefault(); $("q").focus(); return; }
2341
+ if ((k === "z" || k === "u") && lastUndo) { e.preventDefault(); $("toast-undo").click(); return; }
2342
+ if (k === "?") { toast(T().shortcuts); return; }
2343
+ if (prev === "g" && k === "m") { Object.assign(state, { view: "map", category: "" }); load(); return; }
2344
+ if (prev === "g" && k === "a") { Object.assign(state, { view: "all", category: "" }); load(); return; }
2345
+ const cards = [...$("list").querySelectorAll(".swipe .card")];
2346
+ if (!cards.length) return;
2347
+ const cur = document.activeElement?.closest?.(".card");
2348
+ const at = cards.indexOf(cur);
2349
+ if (k === "j" || k === "k") {
2350
+ e.preventDefault();
2351
+ const next = cards[Math.min(cards.length - 1, Math.max(0, at + (k === "j" ? 1 : -1)))] ?? cards[0];
2352
+ next.focus(); next.scrollIntoView({ block: "nearest" });
2353
+ return;
2354
+ }
2355
+ if (!cur || role !== "admin") return;
2356
+ const swipe = cur.closest(".swipe");
2357
+ if (!["f", "#", "Delete", "m", "n"].includes(k)) return;
2358
+ e.preventDefault(); // or the letter lands in the dialog that opens
2359
+ if (k === "f") run(swipe, "favorite");
2360
+ else if (k === "#" || k === "Delete") run(swipe, state.view === "trash" ? "restore" : "trash");
2361
+ else if (k === "m") openMovePicker(Number(swipe.dataset.id));
2362
+ else if (k === "n") openItemNote(Number(swipe.dataset.id));
2363
+ });
1326
2364
 
1327
2365
  $("lang").onclick = () => {
1328
2366
  locale = locale === "en" ? "zh-TW" : "en";