dsh-practical-frontend 0.0.0-stage → 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/client.js ADDED
@@ -0,0 +1,2361 @@
1
+ /**
2
+ * Browser half of the practical-frontend bundle.
3
+ *
4
+ * Two features for the Web GUI:
5
+ * 1. A background tint for each Workspace row in the sidebar, chosen from the
6
+ * row's own "…" menu.
7
+ * 2. Bookmarks: select any part of a conversation, name it, and find it again
8
+ * in the sidebar's 书签 panel, grouped by project.
9
+ *
10
+ * The colour feature uses three cooperating pieces:
11
+ * - a stylesheet keyed on the row's `data-row-key` attribute (no DOM surgery),
12
+ * - a row appended to the shipped rename/delete menu of a project row,
13
+ * - a popover registered into `shell.overlay` that holds the palette.
14
+ *
15
+ * The bookmark feature uses the published composition seats rather than the
16
+ * shipped markup: a `sidebar.panellist` row opens a root-scoped `main` panel,
17
+ * and one `shell.overlay` entry owns the selection pill, the editor dialog and
18
+ * transient feedback. The only shipped DOM it reads is the conversation
19
+ * container's `data-conversation-content` / `data-conversation-session`
20
+ * attributes, which are the same stable contract the composer uses.
21
+ */
22
+
23
+ window.__ModuleLoader__.load({
24
+ id: 'dsh-practical-frontend',
25
+ factory(require) {
26
+ const React = require('react');
27
+ const primitives = require('@deepseek-ai/dsh-client-ui-primitives');
28
+ const {
29
+ Button,
30
+ Input,
31
+ Modal,
32
+ IconCloseOutlineRegular,
33
+ IconEditOutlineRegular,
34
+ IconFolderOpenOutlineRegular,
35
+ IconInspectOutlineRegular,
36
+ IconRefreshOutlineRegular,
37
+ IconSearchOutlineRegular,
38
+ IconTrashOutlineRegular,
39
+ IconWarningTriangleOutlineRegular,
40
+ } = primitives;
41
+ const { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React;
42
+
43
+ /** Client locale namespace and the Host endpoints this package owns. */
44
+ const NS = 'dsh-practical-frontend';
45
+ const COLOR_ENDPOINT = '/dsh-practical-frontend/project-colors';
46
+ const BOOKMARK_ENDPOINT = '/dsh-practical-frontend/bookmarks';
47
+ /** Attribute on a sidebar group row; its value is the Workspace id. */
48
+ const ROW_PREFIX = 'workspace:';
49
+ /** Marks the row this plugin appended to a shipped menu. */
50
+ const ITEM_ATTRIBUTE = 'data-dsh-practical-frontend-item';
51
+ const POPOVER_ID = 'practical-frontend-project-colors';
52
+ const BOOKMARK_PANEL_ID = 'practical-frontend-bookmarks';
53
+ const BOOKMARK_PILL_ATTRIBUTE = 'data-dsh-practical-frontend-bookmark-pill';
54
+ const STYLE_ATTRIBUTE = 'data-dsh-practical-frontend';
55
+ const POPOVER_STYLE_ATTRIBUTE = 'data-dsh-practical-frontend-popover';
56
+ const BOOKMARK_STYLE_ATTRIBUTE = 'data-dsh-practical-frontend-bookmarks';
57
+ /** Rough card width, used only to keep it inside the viewport. */
58
+ const POPOVER_WIDTH = 176;
59
+ /** Selection caps mirrored by the Host half. */
60
+ const MAX_TEXT = 20000;
61
+ const MAX_TITLE = 300;
62
+ const LOOKUP_TIMEOUT_MS = 600;
63
+ const LOOKUP_INTERVAL_MS = 24;
64
+
65
+ const TEXTS = {
66
+ zh: {
67
+ menuLabel: '项目颜色',
68
+ title: '项目颜色',
69
+ red: '红色',
70
+ orange: '橙色',
71
+ amber: '黄色',
72
+ green: '绿色',
73
+ teal: '青色',
74
+ blue: '蓝色',
75
+ indigo: '靛色',
76
+ pink: '粉色',
77
+ none: '无颜色',
78
+ panelLabel: '书签',
79
+ panelTitle: '书签',
80
+ searchPlaceholder: '搜索标题、内容或会话',
81
+ searchLabel: '搜索书签',
82
+ clearSearch: '清除搜索',
83
+ refresh: '刷新书签',
84
+ loading: '正在加载书签…',
85
+ loadFailed: '无法读取书签',
86
+ retry: '重试',
87
+ emptyTitle: '还没有书签',
88
+ emptyBody: '在对话中选中文字,点击出现的「书签」,给这段内容起个标题即可收藏。',
89
+ noMatchesTitle: '没有匹配的书签',
90
+ noMatchesBody: '换个关键词试试。',
91
+ ungrouped: '未归类',
92
+ untitled: '未命名书签',
93
+ unknownSession: '未知会话',
94
+ bookmarkCountOne: '1 条书签',
95
+ bookmarkCount: '{count} 条书签',
96
+ projectCountOne: '1 个项目',
97
+ projectCount: '{count} 个项目',
98
+ addTitle: '添加书签',
99
+ addAction: '书签',
100
+ titleLabel: '标题',
101
+ titlePlaceholder: '给这段内容起个标题',
102
+ quoteLabel: '选中的内容',
103
+ sourceLabel: '来源',
104
+ selectionTruncated: '内容较长,仅保存前 20000 个字符。',
105
+ save: '保存',
106
+ saving: '保存中…',
107
+ cancel: '取消',
108
+ delete: '删除',
109
+ deleteTitle: '删除书签',
110
+ deleteBody: '删除「{title}」?此操作无法撤销。',
111
+ editTitle: '编辑标题',
112
+ viewText: '查看全文',
113
+ openSession: '打开并高亮',
114
+ sessionArchived: '该会话已归档,先恢复后才能打开。',
115
+ sessionUnavailable: '找不到该会话,可能已被删除。',
116
+ saved: '已添加书签',
117
+ deleted: '已删除书签',
118
+ saveFailed: '保存失败,请重试。',
119
+ deleteFailed: '删除失败,请重试。',
120
+ },
121
+ en: {
122
+ menuLabel: 'Project color',
123
+ title: 'Project color',
124
+ red: 'Red',
125
+ orange: 'Orange',
126
+ amber: 'Yellow',
127
+ green: 'Green',
128
+ teal: 'Teal',
129
+ blue: 'Blue',
130
+ indigo: 'Indigo',
131
+ pink: 'Pink',
132
+ none: 'No color',
133
+ panelLabel: 'Bookmarks',
134
+ panelTitle: 'Bookmarks',
135
+ searchPlaceholder: 'Search title, text or session',
136
+ searchLabel: 'Search bookmarks',
137
+ clearSearch: 'Clear search',
138
+ refresh: 'Refresh bookmarks',
139
+ loading: 'Loading bookmarks…',
140
+ loadFailed: 'Could not load bookmarks',
141
+ retry: 'Retry',
142
+ emptyTitle: 'No bookmarks yet',
143
+ emptyBody: 'Select text in a conversation, then choose “Bookmark” to name and save it.',
144
+ noMatchesTitle: 'No matching bookmarks',
145
+ noMatchesBody: 'Try a different search.',
146
+ ungrouped: 'Ungrouped',
147
+ untitled: 'Untitled bookmark',
148
+ unknownSession: 'Unknown session',
149
+ bookmarkCountOne: '1 bookmark',
150
+ bookmarkCount: '{count} bookmarks',
151
+ projectCountOne: '1 project',
152
+ projectCount: '{count} projects',
153
+ addTitle: 'Add bookmark',
154
+ addAction: 'Bookmark',
155
+ titleLabel: 'Title',
156
+ titlePlaceholder: 'Name this excerpt',
157
+ quoteLabel: 'Selected text',
158
+ sourceLabel: 'Source',
159
+ selectionTruncated: 'The selection is long; only the first 20000 characters are saved.',
160
+ save: 'Save',
161
+ saving: 'Saving…',
162
+ cancel: 'Cancel',
163
+ delete: 'Delete',
164
+ deleteTitle: 'Delete bookmark',
165
+ deleteBody: 'Delete “{title}”? This cannot be undone.',
166
+ editTitle: 'Edit title',
167
+ viewText: 'View text',
168
+ openSession: 'Open and highlight',
169
+ sessionArchived: 'That conversation is archived. Restore it before opening.',
170
+ sessionUnavailable: 'That conversation is no longer available.',
171
+ saved: 'Bookmark added',
172
+ deleted: 'Bookmark deleted',
173
+ saveFailed: 'Could not save the bookmark. Try again.',
174
+ deleteFailed: 'Could not delete the bookmark. Try again.',
175
+ },
176
+ };
177
+
178
+ /**
179
+ * Palette entries are hue triples only: the row background is that hue at a
180
+ * low alpha over whatever the theme paints, so label contrast survives both
181
+ * light and dark themes instead of being decided by a literal colour.
182
+ */
183
+ const PALETTE = [
184
+ { id: 'red', rgb: '229, 72, 77' },
185
+ { id: 'orange', rgb: '247, 107, 21' },
186
+ { id: 'amber', rgb: '255, 178, 36' },
187
+ { id: 'green', rgb: '48, 164, 108' },
188
+ { id: 'teal', rgb: '18, 165, 148' },
189
+ { id: 'blue', rgb: '0, 145, 255' },
190
+ { id: 'indigo', rgb: '94, 106, 210' },
191
+ { id: 'pink', rgb: '214, 64, 159' },
192
+ ];
193
+
194
+ /** Row tint and hover tint, as a fraction of the chosen hue. */
195
+ const TINT_REST = 0.18;
196
+ const TINT_HOVER = 0.3;
197
+
198
+ const POPOVER_CSS = `
199
+ .dsh-pf-pop{pointer-events:auto;position:fixed;z-index:30;box-sizing:border-box;padding:12px;border-radius:var(--dsw-radius-lg,12px);border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;box-shadow:0 12px 32px rgb(0 0 0 / 12%),0 2px 8px rgb(0 0 0 / 6%)}
200
+ .dsh-pf-pop__title{margin-bottom:10px;color:var(--dsw-alias-label-secondary)}
201
+ .dsh-pf-pop__grid{display:grid;grid-template-columns:repeat(5,20px);gap:10px}
202
+ .dsh-pf-pop__swatch{box-sizing:border-box;display:grid;place-items:center;width:20px;height:20px;padding:0;border:2px solid transparent;border-radius:999px;background:transparent;cursor:pointer;transition:border-color .15s ease,opacity .15s ease}
203
+ .dsh-pf-pop__swatch:hover{opacity:.85}
204
+ .dsh-pf-pop__swatch[aria-pressed="true"]{border-color:var(--dsw-alias-border-l2)}
205
+ `;
206
+
207
+ /** Bookmark panel, selection pill, editor, and feedback. */
208
+ const BOOKMARK_CSS = `
209
+ .dsh-pf-bm-page{width:100%;min-width:0;height:100%;min-height:0;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font-size:14px;line-height:1.6;display:flex;overflow:hidden}
210
+ .dsh-pf-bm-scroll{flex:1;min-height:0;overflow:auto;scrollbar-gutter:stable;--dsh-scrollbar-width:9px;--dsh-scrollbar-thumb-border:2px}
211
+ .dsh-pf-bm-content{max-width:960px;margin:0 auto;padding:0 clamp(24px,4vw,48px) 48px}
212
+ .dsh-pf-bm-heading{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:16px;margin-bottom:20px;padding-top:28px;display:flex}
213
+ [data-platform="darwin"] .dsh-pf-bm-heading{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
214
+ .dsh-pf-bm-heading-text{min-width:0}
215
+ .dsh-pf-bm-heading h1{max-width:100%;min-width:0;flex:0 auto;margin:0;font-size:20px;font-weight:500;line-height:28px}
216
+ .dsh-pf-bm-count{color:var(--dsw-alias-label-tertiary);margin:2px 0 0;font-size:13px;line-height:20px}
217
+ .dsh-pf-bm-refresh{flex:none}
218
+ .dsh-pf-bm-notice{background:var(--dsw-specific-sidebar-fill);color:var(--dsw-alias-label-secondary);border-radius:10px;margin:0 0 16px;padding:10px 12px;font-size:13px;line-height:20px}
219
+ .dsh-pf-bm-search{border:.5px solid var(--dsw-alias-border-l3);height:36px;color:var(--dsw-alias-label-tertiary);border-radius:12px;align-items:center;margin:0 0 18px;padding:0 10px;transition:border-color .15s;display:flex}
220
+ .dsh-pf-bm-search:hover{border-color:var(--dsw-alias-border-l2)}
221
+ .dsh-pf-bm-search:focus-within{border-color:var(--dsw-alias-state-business-primary)}
222
+ .dsh-pf-bm-search>.dsh-pf-bm-search-input{background:0 0;border:0;border-radius:0;flex:1;min-width:0;height:100%;padding:0}
223
+ .dsh-pf-bm-search>.dsh-pf-bm-search-input:focus-within{border-color:#0000}
224
+ .dsh-pf-bm-search .dsh-pf-bm-search-input svg{width:14px;height:14px}
225
+ .dsh-pf-bm-search input::placeholder{color:var(--dsw-alias-label-caption)}
226
+ .dsh-pf-bm-search input:focus-visible{outline:none}
227
+ .dsh-pf-bm-search input::-webkit-search-cancel-button{display:none}
228
+ .dsh-pf-bm-search-clear{width:28px;height:28px;color:var(--dsw-alias-label-tertiary);flex:none;margin-right:-6px;padding:0}
229
+ .dsh-pf-bm-search-clear svg{width:14px;height:14px}
230
+ .dsh-pf-bm-group{margin:0 0 26px}
231
+ .dsh-pf-bm-group-head{color:var(--dsw-alias-label-secondary);align-items:center;gap:8px;margin:0 0 6px;padding:0 8px;font-size:13px;line-height:20px;font-weight:500;display:flex}
232
+ .dsh-pf-bm-group-icon{color:var(--dsw-alias-label-tertiary);flex:none}
233
+ .dsh-pf-bm-group-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
234
+ .dsh-pf-bm-group-count{margin-left:auto;color:var(--dsw-alias-label-caption);font-weight:400;font-variant-numeric:tabular-nums}
235
+ .dsh-pf-bm-rows{flex-direction:column;gap:2px;margin:0;padding:0;list-style:none;display:flex}
236
+ .dsh-pf-bm-row{border-radius:12px;align-items:flex-start;gap:8px;padding:8px;display:flex;position:relative}
237
+ .dsh-pf-bm-row:hover,.dsh-pf-bm-row:focus-within{background:var(--dsw-alias-interactive-bg-hover)}
238
+ .dsh-pf-bm-open{text-align:left;color:inherit;font:inherit;cursor:pointer;background:0 0;border:0;flex:1;min-width:0;padding:0;flex-direction:column;gap:2px;display:flex}
239
+ .dsh-pf-bm-open:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px;border-radius:8px}
240
+ .dsh-pf-bm-title{text-overflow:ellipsis;white-space:nowrap;min-width:0;font-weight:500;line-height:23px;display:block;overflow:hidden}
241
+ .dsh-pf-bm-quote{color:var(--dsw-alias-label-tertiary);white-space:pre-wrap;overflow-wrap:anywhere;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-width:0;font-size:13px;line-height:21px;display:-webkit-box;overflow:hidden}
242
+ .dsh-pf-bm-meta{color:var(--dsw-alias-label-caption);gap:6px;min-width:0;font-size:12px;line-height:18px;display:flex}
243
+ .dsh-pf-bm-meta-source{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}
244
+ .dsh-pf-bm-meta-date{flex:none}
245
+ .dsh-pf-bm-meta-date:before{content:"·";padding-right:2px}
246
+ .dsh-pf-bm-actions{flex:none;align-items:center;gap:2px;display:flex;opacity:0;transition:opacity .1s}
247
+ .dsh-pf-bm-row:hover .dsh-pf-bm-actions,.dsh-pf-bm-row:focus-within .dsh-pf-bm-actions{opacity:1}
248
+ @media (hover:none){.dsh-pf-bm-actions{opacity:1}}
249
+ .dsh-pf-bm-iconbtn{width:28px;height:28px;border-radius:8px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:0;place-items:center;padding:0;display:grid}
250
+ .dsh-pf-bm-iconbtn:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}
251
+ .dsh-pf-bm-iconbtn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}
252
+ .dsh-pf-bm-iconbtn-danger:hover{color:var(--dsw-alias-state-error-primary)}
253
+ .dsh-pf-bm-empty{text-align:center;color:var(--dsw-alias-label-tertiary);flex-direction:column;align-items:center;padding:56px 20px;font-size:14px;display:flex}
254
+ .dsh-pf-bm-empty-glyph{color:var(--dsw-alias-label-caption);margin-bottom:12px;display:flex}
255
+ .dsh-pf-bm-empty h2{color:var(--dsw-alias-label-tertiary);margin:0 0 8px;font-size:14px;font-weight:400;line-height:1.6}
256
+ .dsh-pf-bm-empty p{max-width:360px;margin:0 0 14px;color:var(--dsw-alias-label-caption);line-height:1.6}
257
+ .dsh-pf-bm-loading{text-align:center;color:var(--dsw-alias-label-tertiary);padding:56px 20px;font-size:14px}
258
+ .dsh-pf-bm-field{flex-direction:column;gap:6px;margin:0 0 16px;display:flex}
259
+ .dsh-pf-bm-field>label,.dsh-pf-bm-label{color:var(--dsw-alias-label-secondary);font-size:13px;line-height:20px}
260
+ .dsh-pf-bm-input{width:100%}
261
+ .dsh-pf-bm-quote-block{max-height:180px;color:var(--dsw-alias-label-secondary);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--dsw-specific-sidebar-fill);border-radius:10px;padding:10px 12px;font-size:13px;line-height:21px;overflow:auto}
262
+ .dsh-pf-bm-quote-full{max-height:min(50vh,360px)}
263
+ .dsh-pf-bm-hint{color:var(--dsw-alias-label-caption);font-size:12px;line-height:18px}
264
+ .dsh-pf-bm-source{color:var(--dsw-alias-label-tertiary);gap:8px;min-width:0;margin:0 0 4px;font-size:12px;line-height:18px;display:flex}
265
+ .dsh-pf-bm-source-label{color:var(--dsw-alias-label-caption);flex:none}
266
+ .dsh-pf-bm-source-value{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}
267
+ .dsh-pf-bm-error{color:var(--dsw-alias-state-error-primary);margin:0;font-size:12px;line-height:18px}
268
+ .dsh-pf-bm-modal-actions{justify-content:flex-end;align-items:center;gap:8px;display:flex}
269
+ .dsh-pf-bm-modal-actions .dsh-pf-bm-danger-button{background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}
270
+ .dsh-pf-bm-modal-actions .dsh-pf-bm-danger-button:hover{opacity:.9}
271
+ .dsh-pf-bm-pill{box-sizing:border-box;pointer-events:auto;position:fixed;z-index:40;height:32px;display:inline-flex;align-items:center;gap:6px;padding:0 11px;border-radius:9px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;font-family:inherit;cursor:pointer;box-shadow:0 8px 24px rgb(0 0 0 / 12%),0 2px 6px rgb(0 0 0 / 6%);transition:background .12s ease}
272
+ .dsh-pf-bm-pill:hover{background:var(--dsw-alias-interactive-bg-hover)}
273
+ .dsh-pf-bm-pill:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}
274
+ .dsh-pf-bm-toast{position:fixed;left:50%;bottom:72px;transform:translateX(-50%);z-index:50;display:flex;align-items:center;gap:8px;padding:8px 12px;border-radius:10px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px;box-shadow:0 10px 28px rgb(0 0 0 / 12%),0 2px 8px rgb(0 0 0 / 6%);pointer-events:none}
275
+ ::highlight(dsh-pf-bookmark){background-color:rgba(0,145,255,.3);color:inherit}
276
+ `;
277
+
278
+ /**
279
+ * Insert or update one stylesheet element in the document head.
280
+ *
281
+ * @param css - stylesheet text.
282
+ * @param attribute - data attribute identifying the element.
283
+ * @returns the element, for later updates and removal.
284
+ */
285
+ function insertStyle(css, attribute) {
286
+ const existing = document.head.querySelector(`style[${attribute}]`);
287
+ if (existing !== null) {
288
+ existing.textContent = css;
289
+ return existing;
290
+ }
291
+ const element = document.createElement('style');
292
+ element.setAttribute(attribute, '');
293
+ element.textContent = css;
294
+ document.head.appendChild(element);
295
+ return element;
296
+ }
297
+
298
+ /**
299
+ * Escape a value for use inside a double-quoted attribute selector.
300
+ *
301
+ * @param value - raw attribute value.
302
+ * @returns the escaped value.
303
+ */
304
+ function escapeAttribute(value) {
305
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
306
+ }
307
+
308
+ /**
309
+ * Create one small external store for local UI state.
310
+ *
311
+ * @param initial - first snapshot.
312
+ * @returns the store, with a synchronous setter.
313
+ */
314
+ function createSnapshotStore(initial) {
315
+ let value = initial;
316
+ const listeners = new Set();
317
+ return {
318
+ getSnapshot: () => value,
319
+ subscribe: (listener) => {
320
+ listeners.add(listener);
321
+ return () => {
322
+ listeners.delete(listener);
323
+ };
324
+ },
325
+ set: (next) => {
326
+ value = next;
327
+ for (const listener of listeners) listener();
328
+ },
329
+ };
330
+ }
331
+
332
+ /**
333
+ * Subscribe one component to a snapshot store.
334
+ *
335
+ * @param store - the snapshot store.
336
+ * @returns the current snapshot.
337
+ */
338
+ function useStoreSnapshot(store) {
339
+ const subscribe = useCallback((listener) => store.subscribe(listener), [store]);
340
+ const snapshot = useCallback(() => store.getSnapshot(), [store]);
341
+ return useSyncExternalStore(subscribe, snapshot, snapshot);
342
+ }
343
+
344
+ /**
345
+ * The sidebar panel glyph: an outlined bookmark.
346
+ *
347
+ * @param props - the sidebar's icon share: size and selected state.
348
+ * @returns an SVG element sized like the shipped panel icons.
349
+ */
350
+ function BookmarkGlyph({ size = 16, active = false }) {
351
+ return React.createElement(
352
+ 'svg',
353
+ {
354
+ viewBox: '0 0 16 16',
355
+ width: size,
356
+ height: size,
357
+ fill: 'none',
358
+ 'aria-hidden': 'true',
359
+ focusable: 'false',
360
+ },
361
+ React.createElement('path', {
362
+ d: 'M4.5 2.25h7a.75.75 0 0 1 .75.75v10.25L8 10.7l-4.25 2.55V3a.75.75 0 0 1 .75-.75Z',
363
+ fill: active === true ? 'currentColor' : 'none',
364
+ stroke: 'currentColor',
365
+ strokeWidth: '1.35',
366
+ strokeLinejoin: 'round',
367
+ }),
368
+ );
369
+ }
370
+
371
+ /**
372
+ * Convert a DOM node from a selection into its element.
373
+ *
374
+ * @param node - boundary node of a range.
375
+ * @returns the element, or null for an empty node.
376
+ */
377
+ function elementOf(node) {
378
+ if (node === null || node === undefined) return null;
379
+ return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
380
+ }
381
+
382
+ /**
383
+ * Read the last line box of a range, which is where the pill should sit.
384
+ *
385
+ * @param range - the selected range.
386
+ * @returns a plain rectangle, or null when the range has no geometry.
387
+ */
388
+ function lastRectOf(range) {
389
+ const rects = range.getClientRects();
390
+ const rect = rects.length === 0 ? range.getBoundingClientRect() : rects[rects.length - 1];
391
+ if (rect === undefined || (rect.width === 0 && rect.height === 0)) return null;
392
+ return { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom };
393
+ }
394
+
395
+ /**
396
+ * Escape a string for use inside a regular expression.
397
+ *
398
+ * @param value - literal text.
399
+ * @returns the escaped text.
400
+ */
401
+ function escapeRegExp(value) {
402
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
403
+ }
404
+
405
+ /**
406
+ * Drop every whitespace run, for anchor validation across block boundaries.
407
+ *
408
+ * @param value - source text.
409
+ * @returns the text without whitespace.
410
+ */
411
+ function compactTextOf(value) {
412
+ return value.replace(/\s+/g, '');
413
+ }
414
+
415
+ /**
416
+ * Character length of one element's text content.
417
+ *
418
+ * @param root - element whose text nodes are counted.
419
+ * @returns the character count.
420
+ */
421
+ function textLengthOf(root) {
422
+ return root.textContent?.length ?? 0;
423
+ }
424
+
425
+ /**
426
+ * Count the characters between an element's start and one range boundary.
427
+ *
428
+ * @param root - element that owns the text.
429
+ * @param node - range boundary node.
430
+ * @param offset - boundary offset.
431
+ * @returns the character offset, or -1 when the boundary is outside root.
432
+ */
433
+ function offsetWithin(root, node, offset) {
434
+ try {
435
+ const range = document.createRange();
436
+ range.selectNodeContents(root);
437
+ const maximum = node.nodeType === Node.TEXT_NODE
438
+ ? (node.nodeValue?.length ?? 0)
439
+ : node.childNodes.length;
440
+ range.setEnd(node, Math.max(0, Math.min(offset, maximum)));
441
+ return range.toString().length;
442
+ } catch {
443
+ return -1;
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Build a range between two character offsets inside one element.
449
+ *
450
+ * @param root - element that owns the text.
451
+ * @param start - first character offset.
452
+ * @param end - exclusive end offset.
453
+ * @returns the range, or null when the span is empty or out of bounds.
454
+ */
455
+ function rangeWithin(root, start, end) {
456
+ const length = textLengthOf(root);
457
+ const from = Math.max(0, Math.min(start, length));
458
+ const to = Math.max(from, Math.min(end, length));
459
+ if (to <= from) return null;
460
+ const range = document.createRange();
461
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
462
+ let offset = 0;
463
+ let started = false;
464
+ let current;
465
+ while ((current = walker.nextNode()) !== null) {
466
+ const value = current.nodeValue ?? '';
467
+ const next = offset + value.length;
468
+ if (started === false && from >= offset && from <= next) {
469
+ range.setStart(current, Math.min(from - offset, value.length));
470
+ started = true;
471
+ }
472
+ if (started && to >= offset && to <= next) {
473
+ range.setEnd(current, Math.min(to - offset, value.length));
474
+ return range.collapsed ? null : range;
475
+ }
476
+ offset = next;
477
+ }
478
+ return null;
479
+ }
480
+
481
+ /**
482
+ * Flatten one conversation container's visible text, skipping the composer.
483
+ *
484
+ * @param root - transcript container.
485
+ * @returns the concatenated text and its per-node offsets.
486
+ */
487
+ function collectTextSegments(root) {
488
+ const segments = [];
489
+ let full = '';
490
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
491
+ acceptNode(node) {
492
+ const parent = node.parentElement;
493
+ if (parent !== null && parent.closest('[data-conversation-region="composer"]') !== null) {
494
+ return NodeFilter.FILTER_REJECT;
495
+ }
496
+ return NodeFilter.FILTER_ACCEPT;
497
+ },
498
+ });
499
+ let current;
500
+ while ((current = walker.nextNode()) !== null) {
501
+ const value = current.nodeValue ?? '';
502
+ if (value === '') continue;
503
+ segments.push({ node: current, start: full.length, end: full.length + value.length });
504
+ full += value;
505
+ }
506
+ return { full, segments };
507
+ }
508
+
509
+ /**
510
+ * Map character offsets in a flattened text back onto a DOM range.
511
+ *
512
+ * @param segments - text nodes with their global offsets.
513
+ * @param from - first character offset.
514
+ * @param to - exclusive end offset.
515
+ * @returns the range, or null when the span cannot be represented.
516
+ */
517
+ function rangeFromSegments(segments, from, to) {
518
+ if (from < 0 || to <= from) return null;
519
+ const range = document.createRange();
520
+ let startSet = false;
521
+ let endSet = false;
522
+ for (const segment of segments) {
523
+ const valueLength = segment.node.nodeValue?.length ?? 0;
524
+ if (startSet === false && from >= segment.start && from <= segment.end) {
525
+ range.setStart(segment.node, Math.min(from - segment.start, valueLength));
526
+ startSet = true;
527
+ }
528
+ if (startSet && endSet === false && to >= segment.start && to <= segment.end) {
529
+ range.setEnd(segment.node, Math.min(to - segment.start, valueLength));
530
+ endSet = true;
531
+ break;
532
+ }
533
+ }
534
+ return startSet && endSet && range.collapsed === false ? range : null;
535
+ }
536
+
537
+ /**
538
+ * Find one saved excerpt in a rendered transcript.
539
+ *
540
+ * Exact text wins; a whitespace-tolerant pass then covers excerpts whose
541
+ * block boundaries disappeared from the DOM's text-node stream.
542
+ *
543
+ * @param root - transcript container.
544
+ * @param text - saved excerpt.
545
+ * @returns the range, or null when the text is absent.
546
+ */
547
+ function findTextRange(root, text) {
548
+ const needle = text.trim();
549
+ if (needle === '') return null;
550
+ const { full, segments } = collectTextSegments(root);
551
+ if (full === '') return null;
552
+ let index = full.indexOf(needle);
553
+ let length = needle.length;
554
+ if (index === -1) {
555
+ const pattern = needle.split(/\s+/).map((part) => escapeRegExp(part)).join('\\s+');
556
+ if (pattern !== '') {
557
+ const match = new RegExp(pattern).exec(full);
558
+ if (match !== null) {
559
+ index = match.index;
560
+ length = match[0].length;
561
+ }
562
+ }
563
+ }
564
+ if (index === -1) return null;
565
+ return rangeFromSegments(segments, index, index + length);
566
+ }
567
+
568
+ /** CSS Custom Highlight registry name used for the located bookmark. */
569
+ const BOOKMARK_HIGHLIGHT_NAME = 'dsh-pf-bookmark';
570
+ /** How long a fresh navigation waits for the target message to render. */
571
+ const BOOKMARK_HIGHLIGHT_TIMEOUT_MS = 12000;
572
+ const BOOKMARK_HIGHLIGHT_RETRY_MS = 200;
573
+
574
+ /**
575
+ * Locate a bookmark in the rendered transcript, paint it with the CSS
576
+ * Custom Highlight API, and bring it into view. The controller waits for a
577
+ * session's history to render, but never mutates React-owned markup.
578
+ *
579
+ * @returns show/clear/dispose controls.
580
+ */
581
+ function createBookmarkHighlighter() {
582
+ let observer = null;
583
+ let attemptTimer = 0;
584
+ let deadlineTimer = 0;
585
+ let watchTimer = 0;
586
+ let request = null;
587
+ let retryScheduled = false;
588
+
589
+ const supportsHighlights = () => typeof CSS !== 'undefined'
590
+ && CSS !== null
591
+ && CSS.highlights !== undefined
592
+ && typeof Highlight === 'function';
593
+
594
+ const clearRegistry = () => {
595
+ if (supportsHighlights() === false) return;
596
+ try {
597
+ CSS.highlights.delete(BOOKMARK_HIGHLIGHT_NAME);
598
+ } catch {
599
+ // A document that lost its registry needs no cleanup.
600
+ }
601
+ };
602
+
603
+ const stopWatching = () => {
604
+ if (observer !== null) {
605
+ observer.disconnect();
606
+ observer = null;
607
+ }
608
+ if (attemptTimer !== 0) {
609
+ window.clearTimeout(attemptTimer);
610
+ attemptTimer = 0;
611
+ }
612
+ if (deadlineTimer !== 0) {
613
+ window.clearTimeout(deadlineTimer);
614
+ deadlineTimer = 0;
615
+ }
616
+ retryScheduled = false;
617
+ request = null;
618
+ };
619
+
620
+ const stopWatch = () => {
621
+ if (watchTimer !== 0) {
622
+ window.clearInterval(watchTimer);
623
+ watchTimer = 0;
624
+ }
625
+ };
626
+
627
+ const startWatch = (sessionId) => {
628
+ stopWatch();
629
+ if (sessionId === '') return;
630
+ // A live highlight follows the active conversation. A different
631
+ // session id means the text nodes it points at are gone; drop both the
632
+ // registry entry and the interval rather than leave a stale range.
633
+ watchTimer = window.setInterval(() => {
634
+ // Keep the highlight while its session is on screen, even if it is
635
+ // the embedded copy. Only a visible *different* session means the
636
+ // highlighted text nodes are gone for good.
637
+ if (findConversation(sessionId) !== null) return;
638
+ const other = findConversation('');
639
+ const current = other === null ? '' : (other.getAttribute('data-conversation-session') ?? '');
640
+ if (current !== '' && current !== sessionId) clear();
641
+ }, 500);
642
+ };
643
+
644
+ const clear = () => {
645
+ stopWatching();
646
+ stopWatch();
647
+ clearRegistry();
648
+ };
649
+
650
+ const isVisible = (element) => element.getClientRects().length > 0;
651
+
652
+ const findConversation = (sessionId) => {
653
+ const containers = [...document.querySelectorAll('[data-conversation-content]')];
654
+ const candidates = sessionId === ''
655
+ ? containers
656
+ : containers.filter((container) => (
657
+ container.getAttribute('data-conversation-session') ?? ''
658
+ ) === sessionId);
659
+ const visible = candidates.filter(isVisible);
660
+ if (visible.length === 0) return null;
661
+ // The main conversation is the widest matching surface; this keeps a
662
+ // narrow embedded copy from winning the race while a panel closes.
663
+ return visible.reduce((best, current) => (
664
+ current.getBoundingClientRect().width > best.getBoundingClientRect().width ? current : best
665
+ ));
666
+ };
667
+
668
+ const nodeByKey = (container, key) => {
669
+ if (typeof key !== 'string' || key === '') return null;
670
+ for (const element of container.querySelectorAll('[data-chat-node-key]')) {
671
+ if (element.getAttribute('data-chat-node-key') === key) return element;
672
+ }
673
+ return null;
674
+ };
675
+
676
+ const rangesFor = (bookmark) => {
677
+ const text = typeof bookmark.text === 'string' ? bookmark.text : '';
678
+ if (text.trim() === '') return null;
679
+ const container = findConversation(typeof bookmark.sessionId === 'string' ? bookmark.sessionId : '');
680
+ if (container === null) return null;
681
+ const startKey = typeof bookmark.anchorStartKey === 'string' ? bookmark.anchorStartKey : '';
682
+ const endKey = typeof bookmark.anchorEndKey === 'string' ? bookmark.anchorEndKey : '';
683
+ const startOffset = Number.isSafeInteger(bookmark.anchorStartOffset)
684
+ ? Math.max(0, bookmark.anchorStartOffset)
685
+ : null;
686
+ const endOffset = Number.isSafeInteger(bookmark.anchorEndOffset)
687
+ ? Math.max(0, bookmark.anchorEndOffset)
688
+ : null;
689
+ const startNode = nodeByKey(container, startKey);
690
+ if (startNode !== null && startOffset !== null) {
691
+ const ranges = [];
692
+ if (endKey === '' || endKey === startKey) {
693
+ if (endOffset !== null && endOffset > startOffset) {
694
+ const range = rangeWithin(startNode, startOffset, endOffset);
695
+ if (range !== null) ranges.push(range);
696
+ }
697
+ } else {
698
+ const endNode = nodeByKey(container, endKey);
699
+ if (endNode !== null && endOffset !== null) {
700
+ const wrappers = [...container.querySelectorAll('[data-chat-node-key]')];
701
+ const startIndex = wrappers.indexOf(startNode);
702
+ const endIndex = wrappers.indexOf(endNode);
703
+ if (startIndex !== -1 && endIndex > startIndex) {
704
+ const first = rangeWithin(startNode, startOffset, textLengthOf(startNode));
705
+ if (first !== null) ranges.push(first);
706
+ for (let index = startIndex + 1; index < endIndex; index += 1) {
707
+ const middle = rangeWithin(wrappers[index], 0, textLengthOf(wrappers[index]));
708
+ if (middle !== null) ranges.push(middle);
709
+ }
710
+ const last = rangeWithin(endNode, 0, endOffset);
711
+ if (last !== null) ranges.push(last);
712
+ }
713
+ }
714
+ }
715
+ if (ranges.length > 0) {
716
+ const joined = ranges.map((range) => range.toString()).join('');
717
+ if (compactTextOf(joined) === compactTextOf(text)) return ranges;
718
+ }
719
+ }
720
+
721
+ // Old records (or records whose message markup changed) have no usable
722
+ // anchors: search the transcript, preferring the saved turn and role.
723
+ const wrappers = [...container.querySelectorAll('[data-chat-node-key]')];
724
+ const preferred = wrappers.filter((node) => {
725
+ if (Number.isSafeInteger(bookmark.turn) && node.getAttribute('data-chat-turn') !== String(bookmark.turn)) {
726
+ return false;
727
+ }
728
+ if (typeof bookmark.role === 'string' && bookmark.role !== ''
729
+ && node.getAttribute('data-chat-flow-kind') !== bookmark.role) {
730
+ return false;
731
+ }
732
+ return true;
733
+ });
734
+ // Probe only the best few turn/role candidates; the one whole-container
735
+ // search below covers everything else without rescanning every node on
736
+ // each retry.
737
+ for (const node of preferred.slice(0, 8)) {
738
+ const range = findTextRange(node, text);
739
+ if (range !== null) return [range];
740
+ }
741
+ const range = findTextRange(container, text);
742
+ return range === null ? null : [range];
743
+ };
744
+
745
+ const applyRanges = (ranges, sessionId) => {
746
+ const usable = ranges.filter((range) => range !== null && range.collapsed === false);
747
+ if (usable.length === 0) return false;
748
+ if (supportsHighlights()) {
749
+ try {
750
+ CSS.highlights.set(BOOKMARK_HIGHLIGHT_NAME, new Highlight(...usable));
751
+ } catch (error) {
752
+ console.warn('practical-frontend: applying the bookmark highlight failed', error);
753
+ }
754
+ } else {
755
+ console.warn('practical-frontend: this browser cannot paint the bookmark highlight');
756
+ }
757
+ const start = usable[0].startContainer;
758
+ const element = start.nodeType === Node.TEXT_NODE ? start.parentElement : start;
759
+ if (element !== null && typeof element.scrollIntoView === 'function') {
760
+ const reduced = typeof window.matchMedia === 'function'
761
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
762
+ element.scrollIntoView({ block: 'center', behavior: reduced ? 'auto' : 'smooth' });
763
+ }
764
+ startWatch(sessionId);
765
+ return true;
766
+ };
767
+
768
+ const locate = (bookmark) => {
769
+ try {
770
+ const ranges = rangesFor(bookmark);
771
+ if (ranges === null) return false;
772
+ return applyRanges(ranges, typeof bookmark.sessionId === 'string' ? bookmark.sessionId : '');
773
+ } catch (error) {
774
+ console.warn('practical-frontend: locating the bookmark failed', error);
775
+ return false;
776
+ }
777
+ };
778
+
779
+ const scheduleAttempt = () => {
780
+ if (request === null || retryScheduled) return;
781
+ retryScheduled = true;
782
+ attemptTimer = window.setTimeout(() => {
783
+ attemptTimer = 0;
784
+ retryScheduled = false;
785
+ if (request === null) return;
786
+ if (locate(request.bookmark)) stopWatching();
787
+ }, BOOKMARK_HIGHLIGHT_RETRY_MS);
788
+ };
789
+
790
+ const show = (bookmark) => {
791
+ clear();
792
+ if (typeof document === 'undefined' || bookmark === null || typeof bookmark !== 'object') return;
793
+ if (typeof bookmark.text !== 'string' || bookmark.text.trim() === '') return;
794
+ request = { bookmark };
795
+ if (typeof MutationObserver !== 'function') {
796
+ if (locate(bookmark)) stopWatching();
797
+ return;
798
+ }
799
+ observer = new MutationObserver(scheduleAttempt);
800
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
801
+ deadlineTimer = window.setTimeout(() => {
802
+ stopWatching();
803
+ }, BOOKMARK_HIGHLIGHT_TIMEOUT_MS);
804
+ // Give the main panel a beat to replace the bookmark panel before the
805
+ // first lookup; the observer covers everything after that.
806
+ scheduleAttempt();
807
+ };
808
+
809
+ return { show, clear, dispose: clear };
810
+ }
811
+
812
+ /**
813
+ * Read the directory name from a workspace path.
814
+ *
815
+ * @param path - absolute path.
816
+ * @returns the last segment, or an empty string.
817
+ */
818
+ function baseNameOf(path) {
819
+ if (typeof path !== 'string') return '';
820
+ const parts = path.split(/[\\/]+/).filter((part) => part !== '');
821
+ return parts.length === 0 ? '' : parts[parts.length - 1];
822
+ }
823
+
824
+ /**
825
+ * Cap a string by user-perceived characters.
826
+ *
827
+ * @param value - source text.
828
+ * @param maximum - maximum characters.
829
+ * @returns the longest allowed prefix.
830
+ */
831
+ function clipCharacters(value, maximum) {
832
+ return Array.from(value).slice(0, maximum).join('');
833
+ }
834
+
835
+ /**
836
+ * Derive a default bookmark title from its text.
837
+ *
838
+ * @param text - selected text.
839
+ * @param fallback - used when the selection has no visible characters.
840
+ * @returns a one-line title.
841
+ */
842
+ function defaultTitleOf(text, fallback) {
843
+ const line = text
844
+ .split(/\r?\n/)
845
+ .map((part) => part.trim())
846
+ .find((part) => part !== '') ?? '';
847
+ if (line === '') return fallback;
848
+ const clipped = clipCharacters(line, 48);
849
+ return Array.from(line).length > 48 ? `${clipped}…` : clipped;
850
+ }
851
+
852
+ /**
853
+ * A bookmark's display title, falling back to its excerpt.
854
+ *
855
+ * @param bookmark - the stored record.
856
+ * @param fallback - label when both title and text are empty.
857
+ * @returns the display title.
858
+ */
859
+ function titleOf(bookmark, fallback) {
860
+ if (typeof bookmark.title === 'string' && bookmark.title.trim() !== '') return bookmark.title;
861
+ return defaultTitleOf(typeof bookmark.text === 'string' ? bookmark.text : '', fallback);
862
+ }
863
+
864
+ /**
865
+ * Collapse an excerpt for the list's two-line preview.
866
+ *
867
+ * @param text - selected text.
868
+ * @returns a compact excerpt.
869
+ */
870
+ function excerptOf(text) {
871
+ return text.replace(/\r/g, '').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
872
+ }
873
+
874
+ /**
875
+ * Find the workspace that owns one session.
876
+ *
877
+ * @param workspaceSnapshot - Workspace projection.
878
+ * @param sessionId - session identity, possibly empty.
879
+ * @param sessionRow - Session list row, when listed.
880
+ * @returns the Workspace view, or undefined.
881
+ */
882
+ function workspaceOfSession(workspaceSnapshot, sessionId, sessionRow) {
883
+ const items = Array.isArray(workspaceSnapshot?.items) ? workspaceSnapshot.items : [];
884
+ if (sessionId !== '') {
885
+ const direct = items.find((item) => Array.isArray(item.sessionIds) && item.sessionIds.includes(sessionId));
886
+ if (direct !== undefined) return direct;
887
+ }
888
+ const cwd = sessionRow?.cwd;
889
+ if (typeof cwd === 'string' && cwd !== '') {
890
+ const byPath = items.find((item) => item.path === cwd);
891
+ if (byPath !== undefined) return byPath;
892
+ }
893
+ return undefined;
894
+ }
895
+
896
+ /**
897
+ * Capture the current conversation selection into a bookmark draft.
898
+ *
899
+ * @param sessions - Session list snapshot store.
900
+ * @param workspaces - Workspace list snapshot store.
901
+ * @returns the draft, or null when the selection is not a conversation excerpt.
902
+ */
903
+ function captureSelection(sessions, workspaces) {
904
+ if (typeof window === 'undefined' || typeof document === 'undefined') return null;
905
+ const selection = window.getSelection();
906
+ if (selection === null || selection.isCollapsed || selection.rangeCount === 0) return null;
907
+ const range = selection.getRangeAt(0);
908
+ const startElement = elementOf(range.startContainer);
909
+ const endElement = elementOf(range.endContainer);
910
+ if (startElement === null || endElement === null) return null;
911
+ const container = startElement.closest('[data-conversation-content]');
912
+ if (container === null || container.contains(endElement) === false) return null;
913
+ if (startElement.closest('input, textarea, [contenteditable="true"], [contenteditable=""]') !== null) return null;
914
+ if (endElement.closest('input, textarea, [contenteditable="true"], [contenteditable=""]') !== null) return null;
915
+ const raw = selection.toString().replaceAll('\u0000', '').trim();
916
+ if (raw === '') return null;
917
+ const rect = lastRectOf(range);
918
+ if (rect === null) return null;
919
+ const text = clipCharacters(raw, MAX_TEXT);
920
+ const sessionId = container.getAttribute('data-conversation-session') ?? '';
921
+ const sessionSnapshot = typeof sessions?.getSnapshot === 'function' ? sessions.getSnapshot() : undefined;
922
+ const sessionRow = sessionId !== '' ? sessionSnapshot?.byId?.[sessionId] : undefined;
923
+ const workspaceSnapshot = typeof workspaces?.getSnapshot === 'function' ? workspaces.getSnapshot() : undefined;
924
+ const workspace = workspaceOfSession(workspaceSnapshot, sessionId, sessionRow);
925
+ const flow = startElement.closest('[data-chat-flow-kind]');
926
+ const turn = startElement.closest('[data-chat-turn]');
927
+ const parsedTurn = turn === null ? Number.NaN : Number.parseInt(turn.getAttribute('data-chat-turn') ?? '', 10);
928
+ const startAnchor = startElement.closest('[data-chat-node-key]');
929
+ const endAnchor = endElement.closest('[data-chat-node-key]');
930
+ const startOffset = startAnchor === null
931
+ ? -1
932
+ : offsetWithin(startAnchor, range.startContainer, range.startOffset);
933
+ const endOffset = endAnchor === null
934
+ ? -1
935
+ : offsetWithin(endAnchor, range.endContainer, range.endOffset);
936
+ return {
937
+ text,
938
+ truncated: Array.from(raw).length > MAX_TEXT,
939
+ sessionId,
940
+ sessionTitle: sessionRow?.displayTitle ?? sessionRow?.title ?? '',
941
+ workspaceId: workspace?.workspaceId ?? '',
942
+ workspaceTitle: workspace?.title ?? baseNameOf(workspace?.path),
943
+ workspacePath: workspace?.path ?? '',
944
+ role: flow === null ? '' : (flow.getAttribute('data-chat-flow-kind') ?? '').slice(0, 32),
945
+ turn: Number.isSafeInteger(parsedTurn) && parsedTurn >= 0 ? parsedTurn : null,
946
+ anchorStartKey: startAnchor?.getAttribute('data-chat-node-key') ?? '',
947
+ anchorStartOffset: startOffset >= 0 ? startOffset : null,
948
+ anchorEndKey: endAnchor?.getAttribute('data-chat-node-key') ?? '',
949
+ anchorEndOffset: endOffset >= 0 ? endOffset : null,
950
+ rect,
951
+ };
952
+ }
953
+
954
+ /**
955
+ * Build the payload the Host stores from a captured draft.
956
+ *
957
+ * @param draft - captured selection.
958
+ * @param title - user-supplied title.
959
+ * @returns the bookmark fields, without the transient rectangle.
960
+ */
961
+ function bookmarkPayloadOf(draft, title) {
962
+ return {
963
+ title,
964
+ text: draft.text,
965
+ sessionId: draft.sessionId,
966
+ sessionTitle: draft.sessionTitle,
967
+ workspaceId: draft.workspaceId,
968
+ workspaceTitle: draft.workspaceTitle,
969
+ workspacePath: draft.workspacePath,
970
+ role: draft.role,
971
+ turn: draft.turn,
972
+ anchorStartKey: draft.anchorStartKey,
973
+ anchorStartOffset: draft.anchorStartOffset,
974
+ anchorEndKey: draft.anchorEndKey,
975
+ anchorEndOffset: draft.anchorEndOffset,
976
+ };
977
+ }
978
+
979
+ /** Formatter cache keyed by locale and options. */
980
+ const DATE_FORMATTERS = new Map();
981
+
982
+ /**
983
+ * Resolve one reusable date formatter.
984
+ *
985
+ * @param locale - BCP-47 locale.
986
+ * @param options - Intl.DateTimeFormat options.
987
+ * @returns the cached formatter.
988
+ */
989
+ function dateFormatterFor(locale, options) {
990
+ const key = `${locale}|${JSON.stringify(options)}`;
991
+ let formatter = DATE_FORMATTERS.get(key);
992
+ if (formatter === undefined) {
993
+ formatter = new Intl.DateTimeFormat(locale, options);
994
+ DATE_FORMATTERS.set(key, formatter);
995
+ }
996
+ return formatter;
997
+ }
998
+
999
+ /**
1000
+ * Format a bookmark timestamp for the active language.
1001
+ *
1002
+ * @param timestamp - milliseconds since the epoch.
1003
+ * @param locale - BCP-47 locale.
1004
+ * @returns a short date or time.
1005
+ */
1006
+ function formatBookmarkDate(timestamp, locale) {
1007
+ if (Number.isFinite(timestamp) === false || timestamp <= 0) return '';
1008
+ const date = new Date(timestamp);
1009
+ if (Number.isNaN(date.getTime())) return '';
1010
+ const now = new Date();
1011
+ const sameDay = date.getFullYear() === now.getFullYear()
1012
+ && date.getMonth() === now.getMonth()
1013
+ && date.getDate() === now.getDate();
1014
+ try {
1015
+ if (sameDay) return dateFormatterFor(locale, { hour: '2-digit', minute: '2-digit' }).format(date);
1016
+ if (date.getFullYear() === now.getFullYear()) {
1017
+ return dateFormatterFor(locale, { month: 'short', day: 'numeric' }).format(date);
1018
+ }
1019
+ return dateFormatterFor(locale, { year: 'numeric', month: 'short', day: 'numeric' }).format(date);
1020
+ } catch {
1021
+ return date.toLocaleDateString();
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * One dictionary-free locale hint for date formatting.
1027
+ *
1028
+ * @returns a BCP-47 locale.
1029
+ */
1030
+ function dateLocale() {
1031
+ const language = typeof navigator !== 'undefined' && typeof navigator.language === 'string'
1032
+ ? navigator.language
1033
+ : 'zh-CN';
1034
+ return language.toLowerCase().startsWith('zh') ? 'zh-CN' : language;
1035
+ }
1036
+
1037
+ /**
1038
+ * Whether one bookmark matches a lower-case search needle.
1039
+ *
1040
+ * @param bookmark - stored record.
1041
+ * @param needle - lower-case query.
1042
+ * @param sessionSnapshot - Session projection.
1043
+ * @param workspaceSnapshot - Workspace projection.
1044
+ * @returns true when any visible field contains the query.
1045
+ */
1046
+ function bookmarkMatches(bookmark, needle, sessionSnapshot, workspaceSnapshot) {
1047
+ if (needle === '') return true;
1048
+ if (typeof bookmark.searchText === 'string' && bookmark.searchText.includes(needle)) return true;
1049
+ const sessionRow = sessionSnapshot?.byId?.[bookmark.sessionId];
1050
+ const workspace = workspaceOfSession(workspaceSnapshot, bookmark.sessionId, sessionRow);
1051
+ const fields = [sessionRow?.displayTitle, workspace?.title, workspace?.path];
1052
+ return fields.some((field) => typeof field === 'string' && field.toLowerCase().includes(needle));
1053
+ }
1054
+
1055
+ /**
1056
+ * Group bookmarks by the Workspace that owns their session, newest first.
1057
+ *
1058
+ * @param bookmarks - already filtered bookmarks, newest first.
1059
+ * @param sessionSnapshot - Session projection.
1060
+ * @param workspaceSnapshot - Workspace projection.
1061
+ * @param ungroupedLabel - label for records without a Workspace.
1062
+ * @returns groups in first-appearance order.
1063
+ */
1064
+ function groupBookmarks(bookmarks, sessionSnapshot, workspaceSnapshot, ungroupedLabel) {
1065
+ const groups = new Map();
1066
+ for (const bookmark of bookmarks) {
1067
+ const sessionRow = sessionSnapshot?.byId?.[bookmark.sessionId];
1068
+ const live = workspaceOfSession(workspaceSnapshot, bookmark.sessionId, sessionRow);
1069
+ const workspaceId = live?.workspaceId ?? bookmark.workspaceId ?? '';
1070
+ const title = live !== undefined
1071
+ ? (live.title || baseNameOf(live.path))
1072
+ : (bookmark.workspaceTitle || baseNameOf(bookmark.workspacePath));
1073
+ const key = workspaceId === '' ? '\u0000ungrouped' : `workspace:${workspaceId}`;
1074
+ let group = groups.get(key);
1075
+ if (group === undefined) {
1076
+ group = { key, title: title || ungroupedLabel, bookmarks: [] };
1077
+ groups.set(key, group);
1078
+ } else if ((group.title === ungroupedLabel || group.title === '') && title !== '') {
1079
+ group.title = title;
1080
+ }
1081
+ group.bookmarks.push(bookmark);
1082
+ }
1083
+ return Array.from(groups.values());
1084
+ }
1085
+
1086
+ /**
1087
+ * Normalize one bookmark received from the Host and precompute its search
1088
+ * haystack, so typing in the panel never re-lowercases every excerpt.
1089
+ *
1090
+ * @param entry - one Host bookmark.
1091
+ * @returns the client-side record.
1092
+ */
1093
+ function normalizeClientBookmark(entry) {
1094
+ const text = typeof entry.text === 'string' ? entry.text : '';
1095
+ const title = typeof entry.title === 'string' ? entry.title : '';
1096
+ const sessionTitle = typeof entry.sessionTitle === 'string' ? entry.sessionTitle : '';
1097
+ const workspaceTitle = typeof entry.workspaceTitle === 'string' ? entry.workspaceTitle : '';
1098
+ const workspacePath = typeof entry.workspacePath === 'string' ? entry.workspacePath : '';
1099
+ return {
1100
+ ...entry,
1101
+ text,
1102
+ title,
1103
+ sessionId: typeof entry.sessionId === 'string' ? entry.sessionId : '',
1104
+ sessionTitle,
1105
+ workspaceId: typeof entry.workspaceId === 'string' ? entry.workspaceId : '',
1106
+ workspaceTitle,
1107
+ workspacePath,
1108
+ role: typeof entry.role === 'string' ? entry.role : '',
1109
+ turn: Number.isSafeInteger(entry.turn) ? entry.turn : null,
1110
+ anchorStartKey: typeof entry.anchorStartKey === 'string' ? entry.anchorStartKey : '',
1111
+ anchorStartOffset: Number.isSafeInteger(entry.anchorStartOffset) ? entry.anchorStartOffset : null,
1112
+ anchorEndKey: typeof entry.anchorEndKey === 'string' ? entry.anchorEndKey : '',
1113
+ anchorEndOffset: Number.isSafeInteger(entry.anchorEndOffset) ? entry.anchorEndOffset : null,
1114
+ createdAt: typeof entry.createdAt === 'number' && Number.isFinite(entry.createdAt) ? entry.createdAt : 0,
1115
+ searchText: [title, text, sessionTitle, workspaceTitle, workspacePath].join('\n').toLowerCase(),
1116
+ };
1117
+ }
1118
+
1119
+ /**
1120
+ * Read one bookmark list from a Host response.
1121
+ *
1122
+ * @param response - fetch response.
1123
+ * @returns the normalized list.
1124
+ */
1125
+ async function readBookmarkList(response) {
1126
+ const type = response.headers.get('content-type') ?? '';
1127
+ if (type.includes('application/json') === false) throw new Error('unexpected bookmark response');
1128
+ const body = await response.json();
1129
+ if (body === null || typeof body !== 'object' || Array.isArray(body.bookmarks) === false) {
1130
+ throw new Error('malformed bookmark response');
1131
+ }
1132
+ return body.bookmarks
1133
+ .filter((entry) => entry !== null && typeof entry === 'object' && typeof entry.id === 'string')
1134
+ .map((entry) => normalizeClientBookmark(entry));
1135
+ }
1136
+
1137
+ /**
1138
+ * Render one title field, shared by the editor and the rename dialog.
1139
+ *
1140
+ * @param props - field props.
1141
+ * @returns the labelled input.
1142
+ */
1143
+ function TitleField({ t, id, value, onChange }) {
1144
+ return React.createElement(
1145
+ 'div',
1146
+ { className: 'dsh-pf-bm-field' },
1147
+ React.createElement('label', { htmlFor: id }, t('titleLabel')),
1148
+ React.createElement(Input, {
1149
+ id,
1150
+ className: 'dsh-pf-bm-input',
1151
+ value,
1152
+ maxLength: MAX_TITLE,
1153
+ placeholder: t('titlePlaceholder'),
1154
+ autoFocus: true,
1155
+ onChange: (event) => onChange(event.target.value),
1156
+ }),
1157
+ );
1158
+ }
1159
+
1160
+ /**
1161
+ * The editor that turns one selected excerpt into a bookmark.
1162
+ *
1163
+ * @param props - draft, title, save state, and callbacks.
1164
+ * @returns the modal.
1165
+ */
1166
+ function BookmarkEditorDialog({ t, draft, title, saving, error, onTitleChange, onSave, onClose }) {
1167
+ const close = () => {
1168
+ if (saving === false) onClose();
1169
+ };
1170
+ const source = [];
1171
+ if (draft.sessionTitle !== '') source.push(draft.sessionTitle);
1172
+ else if (draft.sessionId !== '') source.push(draft.sessionId.slice(0, 8));
1173
+ if (draft.workspaceTitle !== '') source.push(draft.workspaceTitle);
1174
+ return React.createElement(
1175
+ Modal,
1176
+ {
1177
+ open: true,
1178
+ onClose: close,
1179
+ title: t('addTitle'),
1180
+ closeLabel: t('cancel'),
1181
+ footer: React.createElement(
1182
+ 'div',
1183
+ { className: 'dsh-pf-bm-modal-actions' },
1184
+ React.createElement(Button, { variant: 'ghost', onClick: close, disabled: saving }, t('cancel')),
1185
+ React.createElement(
1186
+ Button,
1187
+ {
1188
+ variant: 'primary',
1189
+ onClick: onSave,
1190
+ disabled: saving || title.trim() === '',
1191
+ },
1192
+ saving ? t('saving') : t('save'),
1193
+ ),
1194
+ ),
1195
+ },
1196
+ React.createElement(
1197
+ 'div',
1198
+ { className: 'dsh-pf-bm-editor' },
1199
+ React.createElement(TitleField, { t, id: 'dsh-pf-bm-title', value: title, onChange: onTitleChange }),
1200
+ React.createElement(
1201
+ 'div',
1202
+ { className: 'dsh-pf-bm-field' },
1203
+ React.createElement('span', { className: 'dsh-pf-bm-label' }, t('quoteLabel')),
1204
+ React.createElement('div', { className: 'dsh-pf-bm-quote-block', tabIndex: 0 }, draft.text),
1205
+ draft.truncated === true
1206
+ ? React.createElement('span', { className: 'dsh-pf-bm-hint' }, t('selectionTruncated'))
1207
+ : null,
1208
+ ),
1209
+ React.createElement(
1210
+ 'div',
1211
+ { className: 'dsh-pf-bm-source' },
1212
+ React.createElement('span', { className: 'dsh-pf-bm-source-label' }, t('sourceLabel')),
1213
+ React.createElement(
1214
+ 'span',
1215
+ { className: 'dsh-pf-bm-source-value' },
1216
+ source.length === 0 ? t('unknownSession') : source.join(' · '),
1217
+ ),
1218
+ ),
1219
+ error === ''
1220
+ ? null
1221
+ : React.createElement('p', { className: 'dsh-pf-bm-error', role: 'alert' }, error),
1222
+ ),
1223
+ );
1224
+ }
1225
+
1226
+ /**
1227
+ * The rename dialog reused by the panel.
1228
+ *
1229
+ * @param props - bookmark, title, save state, and callbacks.
1230
+ * @returns the modal.
1231
+ */
1232
+ function BookmarkRenameDialog({ t, bookmark, title, saving, error, onTitleChange, onSave, onClose }) {
1233
+ const close = () => {
1234
+ if (saving === false) onClose();
1235
+ };
1236
+ return React.createElement(
1237
+ Modal,
1238
+ {
1239
+ open: true,
1240
+ onClose: close,
1241
+ title: t('editTitle'),
1242
+ closeLabel: t('cancel'),
1243
+ footer: React.createElement(
1244
+ 'div',
1245
+ { className: 'dsh-pf-bm-modal-actions' },
1246
+ React.createElement(Button, { variant: 'ghost', onClick: close, disabled: saving }, t('cancel')),
1247
+ React.createElement(
1248
+ Button,
1249
+ {
1250
+ variant: 'primary',
1251
+ onClick: onSave,
1252
+ disabled: saving || title.trim() === '',
1253
+ },
1254
+ saving ? t('saving') : t('save'),
1255
+ ),
1256
+ ),
1257
+ },
1258
+ React.createElement(
1259
+ 'div',
1260
+ { className: 'dsh-pf-bm-editor' },
1261
+ React.createElement(TitleField, { t, id: 'dsh-pf-bm-rename', value: title, onChange: onTitleChange }),
1262
+ React.createElement('div', { className: 'dsh-pf-bm-quote-block' }, excerptOf(bookmark.text).slice(0, 400)),
1263
+ error === ''
1264
+ ? null
1265
+ : React.createElement('p', { className: 'dsh-pf-bm-error', role: 'alert' }, error),
1266
+ ),
1267
+ );
1268
+ }
1269
+
1270
+ /**
1271
+ * The destructive confirmation shown before a bookmark is removed.
1272
+ *
1273
+ * @param props - bookmark, progress, and callbacks.
1274
+ * @returns the modal.
1275
+ */
1276
+ function BookmarkDeleteDialog({ t, bookmark, deleting, error, onConfirm, onClose }) {
1277
+ return React.createElement(
1278
+ Modal,
1279
+ {
1280
+ open: true,
1281
+ onClose: deleting === true ? () => {} : onClose,
1282
+ title: t('deleteTitle'),
1283
+ description: t('deleteBody', { title: titleOf(bookmark, t('untitled')) }),
1284
+ closeLabel: t('cancel'),
1285
+ footer: React.createElement(
1286
+ 'div',
1287
+ { className: 'dsh-pf-bm-modal-actions' },
1288
+ React.createElement(Button, { variant: 'ghost', onClick: onClose, disabled: deleting }, t('cancel')),
1289
+ React.createElement(
1290
+ Button,
1291
+ {
1292
+ variant: 'primary',
1293
+ className: 'dsh-pf-bm-danger-button',
1294
+ onClick: onConfirm,
1295
+ disabled: deleting,
1296
+ },
1297
+ deleting ? t('saving') : t('delete'),
1298
+ ),
1299
+ ),
1300
+ },
1301
+ error === '' ? null : React.createElement('p', { className: 'dsh-pf-bm-error', role: 'alert' }, error),
1302
+ );
1303
+ }
1304
+
1305
+ /**
1306
+ * The read-only view of one saved excerpt.
1307
+ *
1308
+ * @param props - bookmark and callbacks.
1309
+ * @returns the modal.
1310
+ */
1311
+ function BookmarkDetailDialog({ t, bookmark, onOpen, onClose }) {
1312
+ const source = [];
1313
+ if (bookmark.sessionTitle !== '') source.push(bookmark.sessionTitle);
1314
+ else if (bookmark.sessionId !== '') source.push(bookmark.sessionId.slice(0, 8));
1315
+ if (bookmark.workspaceTitle !== '') source.push(bookmark.workspaceTitle);
1316
+ return React.createElement(
1317
+ Modal,
1318
+ {
1319
+ open: true,
1320
+ onClose,
1321
+ title: titleOf(bookmark, t('untitled')),
1322
+ closeLabel: t('cancel'),
1323
+ footer: React.createElement(
1324
+ 'div',
1325
+ { className: 'dsh-pf-bm-modal-actions' },
1326
+ React.createElement(Button, { variant: 'ghost', onClick: onClose }, t('cancel')),
1327
+ React.createElement(Button, { variant: 'primary', onClick: onOpen }, t('openSession')),
1328
+ ),
1329
+ },
1330
+ React.createElement(
1331
+ 'div',
1332
+ { className: 'dsh-pf-bm-editor' },
1333
+ React.createElement(
1334
+ 'div',
1335
+ { className: 'dsh-pf-bm-source' },
1336
+ React.createElement('span', { className: 'dsh-pf-bm-source-label' }, t('sourceLabel')),
1337
+ React.createElement(
1338
+ 'span',
1339
+ { className: 'dsh-pf-bm-source-value' },
1340
+ source.length === 0 ? t('unknownSession') : source.join(' · '),
1341
+ ),
1342
+ ),
1343
+ React.createElement(
1344
+ 'div',
1345
+ { className: 'dsh-pf-bm-quote-block dsh-pf-bm-quote-full', tabIndex: 0 },
1346
+ bookmark.text,
1347
+ ),
1348
+ ),
1349
+ );
1350
+ }
1351
+
1352
+ /**
1353
+ * The 书签 panel: searchable bookmarks grouped by project.
1354
+ *
1355
+ * @param props - stores, localized copy, and Host callbacks.
1356
+ * @returns the main panel.
1357
+ */
1358
+ function BookmarksPanel(props) {
1359
+ const { t, bookmarks, sessions, workspaces, openBookmark, onRefresh, onSave, onDelete } = props;
1360
+ const bookmarkState = useStoreSnapshot(bookmarks);
1361
+ const sessionState = useStoreSnapshot(sessions);
1362
+ const workspaceState = useStoreSnapshot(workspaces);
1363
+ const [query, setQuery] = useState('');
1364
+ const [notice, setNotice] = useState('');
1365
+ const [editing, setEditing] = useState(null);
1366
+ const [deleting, setDeleting] = useState(null);
1367
+ const [viewing, setViewing] = useState(null);
1368
+ const noticeTimer = useRef(0);
1369
+
1370
+ useEffect(() => () => {
1371
+ window.clearTimeout(noticeTimer.current);
1372
+ }, []);
1373
+
1374
+ // The Host list can move while the panel is away (another window or a
1375
+ // bookmark saved from the conversation). Read once whenever the panel
1376
+ // mounts; the heading's refresh control covers the rest.
1377
+ useEffect(() => {
1378
+ onRefresh();
1379
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-only read
1380
+ }, []);
1381
+
1382
+ const showNotice = (message) => {
1383
+ setNotice(message);
1384
+ window.clearTimeout(noticeTimer.current);
1385
+ noticeTimer.current = window.setTimeout(() => setNotice(''), 4000);
1386
+ };
1387
+
1388
+ const items = bookmarkState.items;
1389
+ const needle = query.trim().toLowerCase();
1390
+ const filtered = useMemo(
1391
+ () => (needle === ''
1392
+ ? items
1393
+ : items.filter((bookmark) => bookmarkMatches(bookmark, needle, sessionState, workspaceState))),
1394
+ [items, needle, sessionState, workspaceState],
1395
+ );
1396
+ const groups = useMemo(
1397
+ () => groupBookmarks(filtered, sessionState, workspaceState, t('ungrouped')),
1398
+ [filtered, sessionState, workspaceState, t],
1399
+ );
1400
+ const allGroups = useMemo(
1401
+ () => groupBookmarks(items, sessionState, workspaceState, t('ungrouped')),
1402
+ [items, sessionState, workspaceState, t],
1403
+ );
1404
+
1405
+ const open = (bookmark) => {
1406
+ if (bookmark.sessionId === '') {
1407
+ showNotice(t('sessionUnavailable'));
1408
+ return;
1409
+ }
1410
+ const archived = Array.isArray(workspaceState.archivedSessionIds)
1411
+ && workspaceState.archivedSessionIds.includes(bookmark.sessionId);
1412
+ if (archived) {
1413
+ showNotice(t('sessionArchived'));
1414
+ return;
1415
+ }
1416
+ try {
1417
+ openBookmark(bookmark);
1418
+ } catch (error) {
1419
+ console.error('practical-frontend: opening the bookmarked session failed', error);
1420
+ showNotice(t('sessionUnavailable'));
1421
+ }
1422
+ };
1423
+
1424
+ const beginRename = (bookmark) => {
1425
+ setEditing({ bookmark, title: titleOf(bookmark, t('untitled')), saving: false, error: '' });
1426
+ };
1427
+
1428
+ const saveRename = async () => {
1429
+ if (editing === null || editing.title.trim() === '') return;
1430
+ setEditing({ ...editing, saving: true, error: '' });
1431
+ try {
1432
+ await onSave({ ...editing.bookmark, title: editing.title.trim() });
1433
+ setEditing(null);
1434
+ } catch (error) {
1435
+ console.error('practical-frontend: renaming the bookmark failed', error);
1436
+ setEditing((current) => (current === null ? null : { ...current, saving: false, error: t('saveFailed') }));
1437
+ }
1438
+ };
1439
+
1440
+ const confirmDelete = async () => {
1441
+ if (deleting === null) return;
1442
+ setDeleting({ ...deleting, deleting: true, error: '' });
1443
+ try {
1444
+ await onDelete(deleting.bookmark.id);
1445
+ setDeleting(null);
1446
+ showNotice(t('deleted'));
1447
+ } catch (error) {
1448
+ console.error('practical-frontend: deleting the bookmark failed', error);
1449
+ setDeleting((current) => (current === null ? null : { ...current, deleting: false, error: t('deleteFailed') }));
1450
+ }
1451
+ };
1452
+
1453
+ const renderRow = (bookmark) => {
1454
+ const title = titleOf(bookmark, t('untitled'));
1455
+ const sessionRow = sessionState.byId?.[bookmark.sessionId];
1456
+ const sessionTitle = sessionRow?.displayTitle ?? bookmark.sessionTitle;
1457
+ const date = formatBookmarkDate(bookmark.createdAt, dateLocale());
1458
+ return React.createElement(
1459
+ 'li',
1460
+ { key: bookmark.id, className: 'dsh-pf-bm-row' },
1461
+ React.createElement(
1462
+ 'button',
1463
+ {
1464
+ type: 'button',
1465
+ className: 'dsh-pf-bm-open',
1466
+ title: t('openSession'),
1467
+ onClick: () => open(bookmark),
1468
+ },
1469
+ React.createElement('span', { className: 'dsh-pf-bm-title' }, title),
1470
+ bookmark.text.trim() === ''
1471
+ ? null
1472
+ : React.createElement('span', { className: 'dsh-pf-bm-quote' }, excerptOf(bookmark.text)),
1473
+ React.createElement(
1474
+ 'span',
1475
+ { className: 'dsh-pf-bm-meta' },
1476
+ React.createElement(
1477
+ 'span',
1478
+ { className: 'dsh-pf-bm-meta-source' },
1479
+ sessionTitle === '' ? t('unknownSession') : sessionTitle,
1480
+ ),
1481
+ date === '' ? null : React.createElement('span', { className: 'dsh-pf-bm-meta-date' }, date),
1482
+ ),
1483
+ ),
1484
+ React.createElement(
1485
+ 'span',
1486
+ { className: 'dsh-pf-bm-actions' },
1487
+ React.createElement(
1488
+ 'button',
1489
+ {
1490
+ type: 'button',
1491
+ className: 'dsh-pf-bm-iconbtn',
1492
+ title: t('viewText'),
1493
+ 'aria-label': `${t('viewText')}: ${title}`,
1494
+ onClick: () => setViewing(bookmark),
1495
+ },
1496
+ React.createElement(IconInspectOutlineRegular, { size: 14 }),
1497
+ ),
1498
+ React.createElement(
1499
+ 'button',
1500
+ {
1501
+ type: 'button',
1502
+ className: 'dsh-pf-bm-iconbtn',
1503
+ title: t('editTitle'),
1504
+ 'aria-label': `${t('editTitle')}: ${title}`,
1505
+ onClick: () => beginRename(bookmark),
1506
+ },
1507
+ React.createElement(IconEditOutlineRegular, { size: 14 }),
1508
+ ),
1509
+ React.createElement(
1510
+ 'button',
1511
+ {
1512
+ type: 'button',
1513
+ className: 'dsh-pf-bm-iconbtn dsh-pf-bm-iconbtn-danger',
1514
+ title: t('delete'),
1515
+ 'aria-label': `${t('delete')}: ${title}`,
1516
+ onClick: () => setDeleting({ bookmark, deleting: false, error: '' }),
1517
+ },
1518
+ React.createElement(IconTrashOutlineRegular, { size: 14 }),
1519
+ ),
1520
+ ),
1521
+ );
1522
+ };
1523
+
1524
+ const renderBody = () => {
1525
+ if (items.length === 0 && bookmarkState.status === 'loading') {
1526
+ return React.createElement('div', { className: 'dsh-pf-bm-loading', role: 'status' }, t('loading'));
1527
+ }
1528
+ if (items.length === 0 && bookmarkState.status === 'error') {
1529
+ return React.createElement(
1530
+ 'div',
1531
+ { className: 'dsh-pf-bm-empty', role: 'status' },
1532
+ React.createElement(IconWarningTriangleOutlineRegular, { size: 24, className: 'dsh-pf-bm-empty-glyph' }),
1533
+ React.createElement('h2', null, t('loadFailed')),
1534
+ React.createElement(Button, { variant: 'outline', onClick: onRefresh }, t('retry')),
1535
+ );
1536
+ }
1537
+ if (items.length === 0) {
1538
+ return React.createElement(
1539
+ 'div',
1540
+ { className: 'dsh-pf-bm-empty', role: 'status' },
1541
+ React.createElement(BookmarkGlyph, { size: 28 }),
1542
+ React.createElement('h2', null, t('emptyTitle')),
1543
+ React.createElement('p', null, t('emptyBody')),
1544
+ );
1545
+ }
1546
+ if (filtered.length === 0) {
1547
+ return React.createElement(
1548
+ 'div',
1549
+ { className: 'dsh-pf-bm-empty', role: 'status' },
1550
+ React.createElement(IconSearchOutlineRegular, { size: 24, className: 'dsh-pf-bm-empty-glyph' }),
1551
+ React.createElement('h2', null, t('noMatchesTitle')),
1552
+ React.createElement('p', null, t('noMatchesBody')),
1553
+ );
1554
+ }
1555
+ return groups.map((group) => React.createElement(
1556
+ 'section',
1557
+ { key: group.key, className: 'dsh-pf-bm-group', 'aria-label': group.title },
1558
+ React.createElement(
1559
+ 'div',
1560
+ { className: 'dsh-pf-bm-group-head' },
1561
+ React.createElement(IconFolderOpenOutlineRegular, { size: 14, className: 'dsh-pf-bm-group-icon' }),
1562
+ React.createElement('span', { className: 'dsh-pf-bm-group-title' }, group.title),
1563
+ React.createElement('span', { className: 'dsh-pf-bm-group-count' }, String(group.bookmarks.length)),
1564
+ ),
1565
+ React.createElement('ul', { className: 'dsh-pf-bm-rows' }, group.bookmarks.map(renderRow)),
1566
+ ));
1567
+ };
1568
+
1569
+ const bookmarkCount = items.length === 1
1570
+ ? t('bookmarkCountOne')
1571
+ : t('bookmarkCount', { count: items.length });
1572
+ const projectCount = allGroups.length === 1
1573
+ ? t('projectCountOne')
1574
+ : t('projectCount', { count: allGroups.length });
1575
+
1576
+ return React.createElement(
1577
+ 'section',
1578
+ { className: 'dsh-pf-bm-page', 'aria-label': t('panelTitle') },
1579
+ React.createElement(
1580
+ 'div',
1581
+ { className: 'dsh-pf-bm-scroll' },
1582
+ React.createElement(
1583
+ 'div',
1584
+ { className: 'dsh-pf-bm-content' },
1585
+ React.createElement(
1586
+ 'div',
1587
+ { className: 'dsh-pf-bm-heading' },
1588
+ React.createElement(
1589
+ 'div',
1590
+ { className: 'dsh-pf-bm-heading-text' },
1591
+ React.createElement('h1', null, t('panelTitle')),
1592
+ React.createElement('p', { className: 'dsh-pf-bm-count' }, `${bookmarkCount} · ${projectCount}`),
1593
+ ),
1594
+ React.createElement(Button, {
1595
+ variant: 'ghost',
1596
+ size: 'sm',
1597
+ className: 'dsh-pf-bm-refresh',
1598
+ icon: React.createElement(IconRefreshOutlineRegular, { size: 14 }),
1599
+ title: t('refresh'),
1600
+ 'aria-label': t('refresh'),
1601
+ disabled: bookmarkState.status === 'loading',
1602
+ onClick: onRefresh,
1603
+ }),
1604
+ ),
1605
+ notice === ''
1606
+ ? null
1607
+ : React.createElement('div', { className: 'dsh-pf-bm-notice', role: 'status' }, notice),
1608
+ React.createElement(
1609
+ 'div',
1610
+ { className: 'dsh-pf-bm-search' },
1611
+ React.createElement(Input, {
1612
+ type: 'search',
1613
+ className: 'dsh-pf-bm-search-input',
1614
+ value: query,
1615
+ icon: React.createElement(IconSearchOutlineRegular, {}),
1616
+ placeholder: t('searchPlaceholder'),
1617
+ 'aria-label': t('searchLabel'),
1618
+ onChange: (event) => setQuery(event.target.value),
1619
+ }),
1620
+ query === ''
1621
+ ? null
1622
+ : React.createElement(Button, {
1623
+ variant: 'ghost',
1624
+ size: 'sm',
1625
+ className: 'dsh-pf-bm-search-clear',
1626
+ icon: React.createElement(IconCloseOutlineRegular, {}),
1627
+ title: t('clearSearch'),
1628
+ 'aria-label': t('clearSearch'),
1629
+ onClick: () => setQuery(''),
1630
+ }),
1631
+ ),
1632
+ renderBody(),
1633
+ ),
1634
+ ),
1635
+ editing === null
1636
+ ? null
1637
+ : React.createElement(BookmarkRenameDialog, {
1638
+ t,
1639
+ bookmark: editing.bookmark,
1640
+ title: editing.title,
1641
+ saving: editing.saving,
1642
+ error: editing.error,
1643
+ onTitleChange: (value) => setEditing((current) => (current === null ? null : { ...current, title: value })),
1644
+ onSave: saveRename,
1645
+ onClose: () => setEditing(null),
1646
+ }),
1647
+ deleting === null
1648
+ ? null
1649
+ : React.createElement(BookmarkDeleteDialog, {
1650
+ t,
1651
+ bookmark: deleting.bookmark,
1652
+ deleting: deleting.deleting,
1653
+ error: deleting.error,
1654
+ onConfirm: confirmDelete,
1655
+ onClose: () => setDeleting(null),
1656
+ }),
1657
+ viewing === null
1658
+ ? null
1659
+ : React.createElement(BookmarkDetailDialog, {
1660
+ t,
1661
+ bookmark: viewing,
1662
+ onOpen: () => {
1663
+ open(viewing);
1664
+ setViewing(null);
1665
+ },
1666
+ onClose: () => setViewing(null),
1667
+ }),
1668
+ );
1669
+ }
1670
+
1671
+ /**
1672
+ * The selection pill, editor, and confirmation toast.
1673
+ *
1674
+ * @param props - snapshot stores, localized copy, and the Host save call.
1675
+ * @returns the overlay subtree.
1676
+ */
1677
+ function BookmarkOverlay(props) {
1678
+ const { t, sessions, workspaces, onSave } = props;
1679
+ const [selection, setSelection] = useState(null);
1680
+ const [editor, setEditor] = useState(null);
1681
+ const [toast, setToast] = useState('');
1682
+ const selectionRef = useRef(null);
1683
+ const editorRef = useRef(null);
1684
+ const toastTimer = useRef(0);
1685
+
1686
+ editorRef.current = editor;
1687
+
1688
+ useEffect(() => () => {
1689
+ window.clearTimeout(toastTimer.current);
1690
+ }, []);
1691
+
1692
+ const capture = useCallback(() => captureSelection(sessions, workspaces), [sessions, workspaces]);
1693
+
1694
+ const showToast = (message) => {
1695
+ setToast(message);
1696
+ window.clearTimeout(toastTimer.current);
1697
+ toastTimer.current = window.setTimeout(() => setToast(''), 2400);
1698
+ };
1699
+
1700
+ useEffect(() => {
1701
+ let frame = 0;
1702
+ const hide = () => {
1703
+ selectionRef.current = null;
1704
+ setSelection(null);
1705
+ };
1706
+ const sync = () => {
1707
+ if (editorRef.current !== null) return;
1708
+ const next = capture();
1709
+ selectionRef.current = next;
1710
+ setSelection(next);
1711
+ };
1712
+ const schedule = () => {
1713
+ if (frame !== 0) cancelAnimationFrame(frame);
1714
+ frame = requestAnimationFrame(() => {
1715
+ frame = 0;
1716
+ sync();
1717
+ });
1718
+ };
1719
+ const onPointerDown = (event) => {
1720
+ if (event.target instanceof Element && event.target.closest(`[${BOOKMARK_PILL_ATTRIBUTE}]`) !== null) return;
1721
+ hide();
1722
+ };
1723
+ const onPointerUp = (event) => {
1724
+ if (event.target instanceof Element && event.target.closest(`[${BOOKMARK_PILL_ATTRIBUTE}]`) !== null) return;
1725
+ schedule();
1726
+ };
1727
+ const onSelectionChange = () => {
1728
+ const current = window.getSelection();
1729
+ if (current === null || current.isCollapsed) hide();
1730
+ };
1731
+ const onKeyUp = (event) => {
1732
+ if (event.key === 'Escape') {
1733
+ hide();
1734
+ return;
1735
+ }
1736
+ if (event.shiftKey === true || event.key === 'Shift') schedule();
1737
+ };
1738
+ const onScroll = () => hide();
1739
+ document.addEventListener('pointerdown', onPointerDown, true);
1740
+ document.addEventListener('pointerup', onPointerUp, true);
1741
+ document.addEventListener('selectionchange', onSelectionChange);
1742
+ document.addEventListener('keyup', onKeyUp, true);
1743
+ window.addEventListener('scroll', onScroll, true);
1744
+ window.addEventListener('resize', onScroll);
1745
+ return () => {
1746
+ if (frame !== 0) cancelAnimationFrame(frame);
1747
+ document.removeEventListener('pointerdown', onPointerDown, true);
1748
+ document.removeEventListener('pointerup', onPointerUp, true);
1749
+ document.removeEventListener('selectionchange', onSelectionChange);
1750
+ document.removeEventListener('keyup', onKeyUp, true);
1751
+ window.removeEventListener('scroll', onScroll, true);
1752
+ window.removeEventListener('resize', onScroll);
1753
+ };
1754
+ }, [capture]);
1755
+
1756
+ const openEditor = () => {
1757
+ const fresh = capture();
1758
+ const draft = fresh ?? selectionRef.current;
1759
+ if (draft === null) return;
1760
+ selectionRef.current = null;
1761
+ setSelection(null);
1762
+ setEditor({
1763
+ draft,
1764
+ title: defaultTitleOf(draft.text, t('untitled')),
1765
+ saving: false,
1766
+ error: '',
1767
+ });
1768
+ try {
1769
+ window.getSelection()?.removeAllRanges();
1770
+ } catch {
1771
+ // A selection owned by another surface is already gone.
1772
+ }
1773
+ };
1774
+
1775
+ const saveEditor = async () => {
1776
+ if (editor === null || editor.saving || editor.title.trim() === '') return;
1777
+ setEditor({ ...editor, saving: true, error: '' });
1778
+ try {
1779
+ await onSave(bookmarkPayloadOf(editor.draft, editor.title.trim()));
1780
+ setEditor(null);
1781
+ showToast(t('saved'));
1782
+ } catch (error) {
1783
+ console.error('practical-frontend: saving the bookmark failed', error);
1784
+ setEditor((current) => (current === null ? null : { ...current, saving: false, error: t('saveFailed') }));
1785
+ }
1786
+ };
1787
+
1788
+ let pill = null;
1789
+ if (selection !== null) {
1790
+ const width = 92;
1791
+ const height = 32;
1792
+ const rect = selection.rect;
1793
+ const maxLeft = Math.max(8, window.innerWidth - width - 8);
1794
+ const left = Math.min(Math.max(8, rect.right - width), maxLeft);
1795
+ let top = rect.bottom + 8;
1796
+ if (top + height > window.innerHeight - 8) top = Math.max(8, rect.top - height - 8);
1797
+ pill = React.createElement(
1798
+ 'button',
1799
+ {
1800
+ type: 'button',
1801
+ className: 'dsh-pf-bm-pill',
1802
+ style: { left: `${Math.round(left)}px`, top: `${Math.round(top)}px` },
1803
+ [BOOKMARK_PILL_ATTRIBUTE]: '',
1804
+ onPointerDown: (event) => {
1805
+ // A pointerdown default would collapse the selection on mouse
1806
+ // before the click opens the editor. Touch keeps its default so
1807
+ // the tap still becomes a click; the captured draft is retained.
1808
+ if (event.pointerType !== 'touch') event.preventDefault();
1809
+ },
1810
+ onClick: openEditor,
1811
+ },
1812
+ React.createElement(BookmarkGlyph, { size: 13 }),
1813
+ React.createElement('span', null, t('addAction')),
1814
+ );
1815
+ }
1816
+
1817
+ return React.createElement(
1818
+ React.Fragment,
1819
+ null,
1820
+ pill,
1821
+ editor === null
1822
+ ? null
1823
+ : React.createElement(BookmarkEditorDialog, {
1824
+ t,
1825
+ draft: editor.draft,
1826
+ title: editor.title,
1827
+ saving: editor.saving,
1828
+ error: editor.error,
1829
+ onTitleChange: (value) => setEditor((current) => (current === null ? null : { ...current, title: value })),
1830
+ onSave: saveEditor,
1831
+ onClose: () => setEditor(null),
1832
+ }),
1833
+ toast === ''
1834
+ ? null
1835
+ : React.createElement(
1836
+ 'div',
1837
+ { className: 'dsh-pf-bm-toast', role: 'status' },
1838
+ React.createElement(BookmarkGlyph, { size: 14 }),
1839
+ React.createElement('span', null, toast),
1840
+ ),
1841
+ );
1842
+ }
1843
+
1844
+ /**
1845
+ * Build the menu-row icon: a half-filled circle, the "tint" mark.
1846
+ *
1847
+ * @returns an SVG element sized like the shipped menu icons.
1848
+ */
1849
+ function tintIcon() {
1850
+ const namespace = 'http://www.w3.org/2000/svg';
1851
+ const svg = document.createElementNS(namespace, 'svg');
1852
+ svg.setAttribute('viewBox', '0 0 16 16');
1853
+ svg.setAttribute('width', '16');
1854
+ svg.setAttribute('height', '16');
1855
+ svg.setAttribute('fill', 'none');
1856
+ svg.setAttribute('aria-hidden', 'true');
1857
+ const ring = document.createElementNS(namespace, 'circle');
1858
+ ring.setAttribute('cx', '8');
1859
+ ring.setAttribute('cy', '8');
1860
+ ring.setAttribute('r', '5.25');
1861
+ ring.setAttribute('stroke', 'currentColor');
1862
+ ring.setAttribute('stroke-width', '1.5');
1863
+ const half = document.createElementNS(namespace, 'path');
1864
+ half.setAttribute('d', 'M8 2.75a5.25 5.25 0 0 1 0 10.5Z');
1865
+ half.setAttribute('fill', 'currentColor');
1866
+ svg.append(ring, half);
1867
+ return svg;
1868
+ }
1869
+
1870
+ return {
1871
+ inject: ['slots', 'sessions', 'workspaces', 'uiWorkspace'],
1872
+ apply(ctx) {
1873
+ const fallback = typeof navigator !== 'undefined' && navigator.language.toLowerCase().startsWith('zh')
1874
+ ? TEXTS.zh
1875
+ : TEXTS.en;
1876
+ let locale;
1877
+ try {
1878
+ locale = ctx.get('locale');
1879
+ } catch {
1880
+ locale = undefined;
1881
+ }
1882
+ if (locale !== undefined && locale !== null) {
1883
+ ctx.effect(() => {
1884
+ const disposers = Object.entries(TEXTS).map(([id, dictionary]) => {
1885
+ try {
1886
+ return locale.register(NS, id, dictionary);
1887
+ } catch (error) {
1888
+ console.error('practical-frontend: locale dictionary registration failed', error);
1889
+ return undefined;
1890
+ }
1891
+ });
1892
+ return () => {
1893
+ for (const dispose of disposers) {
1894
+ try {
1895
+ dispose?.();
1896
+ } catch {
1897
+ // A disposed namespace is already gone; nothing to unwind.
1898
+ }
1899
+ }
1900
+ };
1901
+ }, 'practical-frontend: locale dictionaries');
1902
+ }
1903
+ /**
1904
+ * Read one label in the active locale. Rebinding per call keeps a label
1905
+ * that opens rarely (a menu row, a popover) in step with a locale switch.
1906
+ *
1907
+ * @param key - key in this package's namespace.
1908
+ * @param params - optional `{name}` interpolation values.
1909
+ * @returns the localized text, or the fallback dictionary's text.
1910
+ */
1911
+ const translate = (key, params) => {
1912
+ if (locale !== undefined && locale !== null) {
1913
+ try {
1914
+ const text = locale.bind(NS)(key, params);
1915
+ if (typeof text === 'string' && text !== '') return text;
1916
+ } catch {
1917
+ // Fall through to the packaged dictionary.
1918
+ }
1919
+ }
1920
+ const template = fallback[key] ?? key;
1921
+ if (params === undefined) return template;
1922
+ return template.replace(/\{(\w+)\}/g, (match, name) => (name in params ? String(params[name]) : match));
1923
+ };
1924
+
1925
+ const colors = {};
1926
+ const listeners = new Set();
1927
+ const overlay = { open: false, workspaceId: '', name: '', rect: null };
1928
+ let pendingTrigger = null;
1929
+ const rowStyle = insertStyle('', STYLE_ATTRIBUTE);
1930
+ insertStyle(POPOVER_CSS, POPOVER_STYLE_ATTRIBUTE);
1931
+ insertStyle(BOOKMARK_CSS, BOOKMARK_STYLE_ATTRIBUTE);
1932
+
1933
+ ctx.effect(() => () => {
1934
+ rowStyle.remove();
1935
+ document.head.querySelector(`style[${POPOVER_STYLE_ATTRIBUTE}]`)?.remove();
1936
+ document.head.querySelector(`style[${BOOKMARK_STYLE_ATTRIBUTE}]`)?.remove();
1937
+ }, 'practical-frontend: stylesheets');
1938
+
1939
+ const sessions = ctx.get('sessions');
1940
+ const workspaces = ctx.get('workspaces');
1941
+ const uiWorkspace = ctx.get('uiWorkspace');
1942
+ const bookmarks = createSnapshotStore({ status: 'loading', items: [], error: '' });
1943
+ const highlighter = createBookmarkHighlighter();
1944
+ ctx.effect(() => () => highlighter.dispose(), 'practical-frontend: bookmark highlight');
1945
+
1946
+ /**
1947
+ * Read the stored colour map from this package's Host half.
1948
+ */
1949
+ const refresh = async () => {
1950
+ try {
1951
+ const response = await fetch(COLOR_ENDPOINT, { cache: 'no-store' });
1952
+ if (response.ok === false) return;
1953
+ const type = response.headers.get('content-type') ?? '';
1954
+ if (!type.includes('application/json')) return;
1955
+ const body = await response.json();
1956
+ const stored = body !== null && typeof body === 'object' ? body.colors : undefined;
1957
+ if (stored === null || typeof stored !== 'object') return;
1958
+ for (const key of Object.keys(colors)) delete colors[key];
1959
+ for (const [key, value] of Object.entries(stored)) {
1960
+ if (typeof value === 'string') colors[key] = value;
1961
+ }
1962
+ paint();
1963
+ } catch (error) {
1964
+ console.error('practical-frontend: reading workspace colours failed', error);
1965
+ }
1966
+ };
1967
+
1968
+ /**
1969
+ * Paint one colour change immediately, then hand it to the Host half.
1970
+ *
1971
+ * @param workspaceId - Workspace whose row changes.
1972
+ * @param colorId - palette id, or null to clear the tint.
1973
+ */
1974
+ const persist = async (workspaceId, colorId) => {
1975
+ if (colorId === null) delete colors[workspaceId];
1976
+ else colors[workspaceId] = colorId;
1977
+ paint();
1978
+ emit();
1979
+ try {
1980
+ await fetch(COLOR_ENDPOINT, {
1981
+ method: 'POST',
1982
+ headers: { 'content-type': 'application/json' },
1983
+ body: JSON.stringify({ workspaceId, color: colorId }),
1984
+ });
1985
+ } catch (error) {
1986
+ console.error('practical-frontend: saving the workspace colour failed', error);
1987
+ }
1988
+ };
1989
+
1990
+ const emit = () => {
1991
+ for (const listener of listeners) listener();
1992
+ };
1993
+
1994
+ /** Repaint the row tint rules from the current colour map. */
1995
+ const paint = () => {
1996
+ const rules = [];
1997
+ for (const [workspaceId, colorId] of Object.entries(colors)) {
1998
+ const chip = PALETTE.find((entry) => entry.id === colorId);
1999
+ if (chip === undefined) continue;
2000
+ const selector = `[data-row-key="${ROW_PREFIX}${escapeAttribute(workspaceId)}"]`;
2001
+ rules.push(`${selector}{background:rgba(${chip.rgb},${TINT_REST}) !important}`);
2002
+ rules.push(`${selector}:hover{background:rgba(${chip.rgb},${TINT_HOVER}) !important}`);
2003
+ }
2004
+ rowStyle.textContent = rules.join('');
2005
+ };
2006
+
2007
+ const openOverlay = (workspaceId, name, rect) => {
2008
+ overlay.open = true;
2009
+ overlay.workspaceId = workspaceId;
2010
+ overlay.name = name;
2011
+ overlay.rect = rect;
2012
+ emit();
2013
+ };
2014
+
2015
+ const closeOverlay = () => {
2016
+ if (overlay.open === false) return;
2017
+ overlay.open = false;
2018
+ emit();
2019
+ };
2020
+
2021
+ /**
2022
+ * Serialize bookmark reads and writes so a slow refresh can never
2023
+ * overwrite a newer saved list in the panel.
2024
+ *
2025
+ * @param operation - one read or mutation.
2026
+ * @returns the operation's result.
2027
+ */
2028
+ let bookmarkQueue = Promise.resolve();
2029
+ const runBookmarkOperation = (operation) => {
2030
+ const result = bookmarkQueue.then(operation);
2031
+ bookmarkQueue = result.catch(() => {});
2032
+ return result;
2033
+ };
2034
+
2035
+ /**
2036
+ * Read the stored bookmark list from this package's Host half.
2037
+ */
2038
+ const refreshBookmarks = () => runBookmarkOperation(async () => {
2039
+ const current = bookmarks.getSnapshot();
2040
+ if (current.items.length === 0) bookmarks.set({ status: 'loading', items: [], error: '' });
2041
+ try {
2042
+ const response = await fetch(BOOKMARK_ENDPOINT, { cache: 'no-store' });
2043
+ if (response.ok === false) throw new Error(`bookmark read failed: ${response.status}`);
2044
+ const items = await readBookmarkList(response);
2045
+ bookmarks.set({ status: 'ready', items, error: '' });
2046
+ } catch (error) {
2047
+ console.error('practical-frontend: reading bookmarks failed', error);
2048
+ bookmarks.set({ status: 'error', items: current.items, error: translate('loadFailed') });
2049
+ }
2050
+ });
2051
+
2052
+ /**
2053
+ * Create or update one bookmark on the Host half.
2054
+ *
2055
+ * @param bookmark - bookmark fields, including the title.
2056
+ * @returns the complete list after the write.
2057
+ */
2058
+ const saveBookmark = (bookmark) => runBookmarkOperation(async () => {
2059
+ const response = await fetch(BOOKMARK_ENDPOINT, {
2060
+ method: 'POST',
2061
+ headers: { 'content-type': 'application/json' },
2062
+ body: JSON.stringify({ action: 'save', bookmark }),
2063
+ });
2064
+ if (response.ok === false) throw new Error(`bookmark save failed: ${response.status}`);
2065
+ const items = await readBookmarkList(response);
2066
+ bookmarks.set({ status: 'ready', items, error: '' });
2067
+ return items;
2068
+ });
2069
+
2070
+ /**
2071
+ * Remove one bookmark on the Host half.
2072
+ *
2073
+ * @param id - bookmark identity.
2074
+ * @returns the complete list after the write.
2075
+ */
2076
+ const deleteBookmark = (id) => runBookmarkOperation(async () => {
2077
+ const response = await fetch(BOOKMARK_ENDPOINT, {
2078
+ method: 'POST',
2079
+ headers: { 'content-type': 'application/json' },
2080
+ body: JSON.stringify({ action: 'delete', id }),
2081
+ });
2082
+ if (response.ok === false) throw new Error(`bookmark delete failed: ${response.status}`);
2083
+ const items = await readBookmarkList(response);
2084
+ bookmarks.set({ status: 'ready', items, error: '' });
2085
+ return items;
2086
+ });
2087
+
2088
+ /**
2089
+ * The palette popover. It stays open after a pick so colours can be
2090
+ * compared and adjusted, and closes on Escape, outside press, or scroll.
2091
+ *
2092
+ * @returns the popover, or null while closed.
2093
+ */
2094
+ function ProjectColorPopover() {
2095
+ const [, setVersion] = React.useState(0);
2096
+ const card = React.useRef(null);
2097
+ const open = overlay.open;
2098
+ const workspaceId = overlay.workspaceId;
2099
+ const selected = colors[workspaceId];
2100
+
2101
+ React.useEffect(() => {
2102
+ const listener = () => setVersion((value) => value + 1);
2103
+ listeners.add(listener);
2104
+ return () => {
2105
+ listeners.delete(listener);
2106
+ };
2107
+ }, []);
2108
+
2109
+ React.useEffect(() => {
2110
+ if (open === false) return undefined;
2111
+ const onPointerDown = (event) => {
2112
+ if (card.current !== null && event.target instanceof Node && card.current.contains(event.target)) return;
2113
+ closeOverlay();
2114
+ };
2115
+ const onKeyDown = (event) => {
2116
+ if (event.key !== 'Escape') return;
2117
+ event.preventDefault();
2118
+ event.stopPropagation();
2119
+ closeOverlay();
2120
+ };
2121
+ const onScroll = () => closeOverlay();
2122
+ document.addEventListener('pointerdown', onPointerDown, true);
2123
+ document.addEventListener('keydown', onKeyDown, true);
2124
+ window.addEventListener('scroll', onScroll, true);
2125
+ return () => {
2126
+ document.removeEventListener('pointerdown', onPointerDown, true);
2127
+ document.removeEventListener('keydown', onKeyDown, true);
2128
+ window.removeEventListener('scroll', onScroll, true);
2129
+ };
2130
+ }, [open]);
2131
+
2132
+ if (overlay.open === false || overlay.rect === null) return null;
2133
+ const rect = overlay.rect;
2134
+ const left = Math.max(8, Math.min(Math.round(rect.left), window.innerWidth - POPOVER_WIDTH - 8));
2135
+ const top = Math.min(Math.round(rect.bottom + 6), Math.max(8, window.innerHeight - 120));
2136
+ const swatches = PALETTE.map((chip) => React.createElement('button', {
2137
+ key: chip.id,
2138
+ type: 'button',
2139
+ className: 'dsh-pf-pop__swatch',
2140
+ 'aria-pressed': selected === chip.id,
2141
+ 'aria-label': translate(chip.id),
2142
+ style: { background: `rgb(${chip.rgb})` },
2143
+ onClick: () => {
2144
+ void persist(workspaceId, selected === chip.id ? null : chip.id);
2145
+ },
2146
+ }));
2147
+ swatches.push(React.createElement(
2148
+ 'button',
2149
+ {
2150
+ key: 'none',
2151
+ type: 'button',
2152
+ className: 'dsh-pf-pop__swatch',
2153
+ 'aria-pressed': selected === undefined,
2154
+ 'aria-label': translate('none'),
2155
+ onClick: () => {
2156
+ void persist(workspaceId, null);
2157
+ },
2158
+ },
2159
+ React.createElement(
2160
+ 'svg',
2161
+ {
2162
+ viewBox: '0 0 20 20',
2163
+ width: '100%',
2164
+ height: '100%',
2165
+ 'aria-hidden': 'true',
2166
+ focusable: 'false',
2167
+ },
2168
+ React.createElement('circle', {
2169
+ key: 'ring',
2170
+ cx: '10',
2171
+ cy: '10',
2172
+ r: '7.5',
2173
+ fill: 'none',
2174
+ stroke: 'var(--dsw-alias-label-tertiary)',
2175
+ strokeWidth: '1.5',
2176
+ }),
2177
+ React.createElement('path', {
2178
+ key: 'slash',
2179
+ d: 'M5.2 14.8 14.8 5.2',
2180
+ stroke: 'var(--dsw-alias-label-tertiary)',
2181
+ strokeWidth: '1.5',
2182
+ strokeLinecap: 'round',
2183
+ }),
2184
+ ),
2185
+ ));
2186
+ return React.createElement(
2187
+ 'div',
2188
+ {
2189
+ className: 'dsh-pf-pop',
2190
+ ref: card,
2191
+ role: 'dialog',
2192
+ 'aria-label': overlay.name === '' ? translate('title') : `${translate('title')} · ${overlay.name}`,
2193
+ style: { left: `${left}px`, top: `${top}px` },
2194
+ },
2195
+ React.createElement('div', { className: 'dsh-pf-pop__title' }, translate('title')),
2196
+ React.createElement('div', { className: 'dsh-pf-pop__grid' }, swatches),
2197
+ );
2198
+ }
2199
+
2200
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2201
+ name: 'shell.overlay',
2202
+ id: POPOVER_ID,
2203
+ order: 40,
2204
+ }, ProjectColorPopover));
2205
+
2206
+ ctx.slots.inject('main', () => ctx.slots.register({
2207
+ name: 'main',
2208
+ key: BOOKMARK_PANEL_ID,
2209
+ inject: () => ({
2210
+ t: translate,
2211
+ bookmarks,
2212
+ sessions: sessions.list,
2213
+ workspaces: workspaces.list,
2214
+ openBookmark: (bookmark) => {
2215
+ uiWorkspace.openSession(bookmark.sessionId);
2216
+ highlighter.show(bookmark);
2217
+ },
2218
+ onRefresh: () => {
2219
+ void refreshBookmarks();
2220
+ },
2221
+ onSave: saveBookmark,
2222
+ onDelete: deleteBookmark,
2223
+ }),
2224
+ }, BookmarksPanel));
2225
+
2226
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
2227
+ name: 'sidebar.panellist',
2228
+ id: BOOKMARK_PANEL_ID,
2229
+ order: 20,
2230
+ label: () => translate('panelLabel'),
2231
+ }, BookmarkGlyph));
2232
+
2233
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
2234
+ name: 'shell.overlay',
2235
+ id: 'practical-frontend-bookmark-selection',
2236
+ order: 41,
2237
+ inject: () => ({
2238
+ t: translate,
2239
+ sessions: sessions.list,
2240
+ workspaces: workspaces.list,
2241
+ onSave: saveBookmark,
2242
+ }),
2243
+ }, BookmarkOverlay));
2244
+
2245
+ /**
2246
+ * Find the project menu that is open right now. Only the rename/delete
2247
+ * pair qualifies, which keeps every other menu untouched.
2248
+ *
2249
+ * @returns the open project menu, or null.
2250
+ */
2251
+ const findProjectMenu = () => {
2252
+ for (const menu of document.querySelectorAll('[data-menu-material][role="menu"]')) {
2253
+ if (menu.querySelectorAll('button[role="menuitem"]').length === 2) return menu;
2254
+ }
2255
+ return null;
2256
+ };
2257
+
2258
+ /**
2259
+ * Close the shipped menu the way Escape does: the menu owns its open
2260
+ * state and listens for that key, and its rows unmount with it.
2261
+ */
2262
+ const dismissMenu = () => {
2263
+ document.dispatchEvent(new KeyboardEvent('keydown', {
2264
+ key: 'Escape',
2265
+ bubbles: true,
2266
+ cancelable: true,
2267
+ }));
2268
+ };
2269
+
2270
+ /**
2271
+ * Append this feature's row to the open project menu, copying the shipped
2272
+ * rename row so markup, spacing, and hover styling stay the host's.
2273
+ *
2274
+ * @param menu - the open menu surface.
2275
+ * @param trigger - the Workspace row that opened it.
2276
+ */
2277
+ const enhanceMenu = (menu, trigger) => {
2278
+ const rows = menu.querySelectorAll('button[role="menuitem"]');
2279
+ const template = rows[0]?.parentElement;
2280
+ if (template === undefined || template === null) return;
2281
+ const viewport = template.parentElement;
2282
+ if (viewport === null) return;
2283
+ if (viewport.querySelector(`[${ITEM_ATTRIBUTE}]`) !== null) return;
2284
+ const wrap = template.cloneNode(true);
2285
+ for (const separator of wrap.querySelectorAll('[role="separator"]')) separator.remove();
2286
+ const button = wrap.querySelector('button[role="menuitem"]');
2287
+ if (button === null) return;
2288
+ button.removeAttribute('aria-keyshortcuts');
2289
+ button.removeAttribute('aria-current');
2290
+ button.disabled = false;
2291
+ const label = button.lastElementChild;
2292
+ if (label !== null) label.textContent = translate('menuLabel');
2293
+ const icon = button.firstElementChild;
2294
+ if (icon !== null && icon !== label) icon.replaceChildren(tintIcon());
2295
+ wrap.setAttribute(ITEM_ATTRIBUTE, '');
2296
+ button.addEventListener('click', (event) => {
2297
+ event.preventDefault();
2298
+ event.stopPropagation();
2299
+ dismissMenu();
2300
+ openOverlay(trigger.workspaceId, trigger.name, trigger.rect);
2301
+ });
2302
+ template.after(wrap);
2303
+ };
2304
+
2305
+ /**
2306
+ * Poll briefly for the menu the clicked trigger opens.
2307
+ *
2308
+ * @param attempt - poll index.
2309
+ */
2310
+ const lookupMenu = (attempt) => {
2311
+ if (pendingTrigger === null) return;
2312
+ const menu = findProjectMenu();
2313
+ if (menu !== null) {
2314
+ const trigger = pendingTrigger;
2315
+ pendingTrigger = null;
2316
+ enhanceMenu(menu, trigger);
2317
+ return;
2318
+ }
2319
+ if (attempt * LOOKUP_INTERVAL_MS >= LOOKUP_TIMEOUT_MS) {
2320
+ pendingTrigger = null;
2321
+ return;
2322
+ }
2323
+ window.setTimeout(() => lookupMenu(attempt + 1), LOOKUP_INTERVAL_MS);
2324
+ };
2325
+
2326
+ /**
2327
+ * Record the project row whose "…" button was just pressed, so the menu
2328
+ * that opens after it is attributed to that Workspace.
2329
+ *
2330
+ * @param event - document click, capture phase.
2331
+ */
2332
+ const onDocumentClick = (event) => {
2333
+ if (!(event.target instanceof Element)) return;
2334
+ const row = event.target.closest(`[data-row-key^="${ROW_PREFIX}"]`);
2335
+ if (row === null) return;
2336
+ const actions = row.lastElementChild;
2337
+ if (actions === null) return;
2338
+ const buttons = actions.querySelectorAll('button');
2339
+ if (buttons.length !== 2) return;
2340
+ if (event.target.closest('button') !== buttons[0]) return;
2341
+ const workspaceId = (row.getAttribute('data-row-key') ?? '').slice(ROW_PREFIX.length);
2342
+ if (workspaceId === '') return;
2343
+ pendingTrigger = {
2344
+ workspaceId,
2345
+ rect: row.getBoundingClientRect(),
2346
+ name: (row.textContent ?? '').trim().slice(0, 60),
2347
+ };
2348
+ lookupMenu(0);
2349
+ };
2350
+
2351
+ ctx.effect(() => {
2352
+ document.addEventListener('click', onDocumentClick, true);
2353
+ return () => document.removeEventListener('click', onDocumentClick, true);
2354
+ }, 'practical-frontend: project menu rows');
2355
+
2356
+ void refresh();
2357
+ void refreshBookmarks();
2358
+ },
2359
+ };
2360
+ },
2361
+ });