@tangjs/dsh-memory 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1607 @@
1
+ // Browser half of dsh-memory: the "Memory" page in the right Sidebar.
2
+ //
3
+ // Zero build step. The harness module loader hands this factory the browser
4
+ // module table's `require`; `react` is a platform builtin there. Everything is
5
+ // `react.createElement` through `h`, because nothing compiles JSX here and no
6
+ // Harness client package may be imported (they change without notice, and a
7
+ // throwing component blanks the slot).
8
+ //
9
+ // The page reads three read-only, same-origin JSON routes that the Host half
10
+ // registers (src/host/api.mjs):
11
+ // /plugin/dsh-memory/api/spaces → { spaces[], current }
12
+ // /plugin/dsh-memory/api/notes?space=<key> → { space, notes[] }
13
+ // /plugin/dsh-memory/api/note?space=&file= → { space, file, frontmatter, body, bytes }
14
+ //
15
+ // Layout: one surface, two columns. The left column lists memory spaces (one
16
+ // per workspace directory, plus a disabled `_global` placeholder); the right
17
+ // column is either the note timeline of the selected space or, after a pick,
18
+ // the note detail with a breadcrumb back. Colour comes only from the host's
19
+ // `--dsw-alias-*` tokens so light and dark themes both work; the page never
20
+ // touches `document.body` and registers everything through `ctx.effect`.
21
+ //
22
+ // Copy is localised in two layers: the dictionaries below are the runtime
23
+ // source (a zero-build module cannot fetch package resources), and
24
+ // locale/{zh,en}.json mirror them under `page` for the Host's plugin metadata.
25
+ // `test/client.test.mjs` fails when the two drift apart.
26
+
27
+ ;(function () {
28
+ 'use strict'
29
+ if (typeof window === 'undefined' || !window.__ModuleLoader__ || !window.__ModuleLoader__.load) return
30
+ window.__ModuleLoader__.load({
31
+ id: '@tangzhicheng/dsh-memory',
32
+ factory: function (require) {
33
+ const react = require('react')
34
+ /** createElement shorthand: no build step, so no JSX. */
35
+ const h = react.createElement
36
+
37
+ /** Copy namespace, tab type id, and the key the tab body registers under. */
38
+ const NS = 'dsh-memory'
39
+ /** Base path of the Host's read-only JSON routes. */
40
+ const API_BASE = '/plugin/dsh-memory/api'
41
+ /** Give up on one request after this long so a stalled route still ends in a retry button. */
42
+ const REQUEST_TIMEOUT_MS = 15000
43
+
44
+ // ---------------------------------------------------------------- copy --
45
+
46
+ /**
47
+ * Page copy. Both locales carry the same keys: `test/client.test.mjs`
48
+ * asserts that, and that locale/*.json mirrors them.
49
+ */
50
+ const DICTS = {
51
+ zh: {
52
+ 'tab.title': '记忆',
53
+ 'guide.title': '记忆',
54
+ 'guide.description': '浏览各目录空间的记忆笔记',
55
+ 'spaces.title': '空间',
56
+ 'spaces.current': '当前',
57
+ 'spaces.global': '全局',
58
+ 'spaces.locked': '后续开放',
59
+ 'spaces.empty': '暂无空间',
60
+ 'spaces.count': '{count} 条',
61
+ 'spaces.none': '—',
62
+ 'notes.title': '记忆笔记',
63
+ 'notes.empty': '这个目录还没有记忆',
64
+ 'notes.emptyHint': '在对话里让助手记住某件事,笔记就会出现在这里。',
65
+ 'notes.count': '{count} 条笔记',
66
+ 'notes.refresh': '刷新',
67
+ 'index.badge': '索引',
68
+ 'index.title': 'MEMORY.md 索引',
69
+ 'index.subtitle': '目录 · {count} 条笔记',
70
+ 'index.open': '查看索引',
71
+ 'note.updatedAt': '更新于 {time}',
72
+ 'note.session': '会话 {id}',
73
+ 'note.noSession': '无来源会话',
74
+ 'note.noDescription': '(无描述)',
75
+ 'state.loading': '加载中…',
76
+ 'state.error.title': '加载失败',
77
+ 'state.error.retry': '重试',
78
+ 'state.error.network': '无法连接记忆服务,请确认插件仍在运行。',
79
+ 'state.error.http': '接口返回 {status}。',
80
+ 'state.error.body': '接口返回了无法解析的内容。',
81
+ 'state.error.timeout': '请求超时,请重试。',
82
+ 'detail.back': '返回',
83
+ 'detail.file': '文件',
84
+ 'detail.notFound': '这条笔记不存在,可能已被合并或删除。',
85
+ 'detail.bytes': '{bytes} 字节',
86
+ 'badge.type.user': '用户',
87
+ 'badge.type.feedback': '反馈',
88
+ 'badge.type.project': '项目',
89
+ 'badge.type.reference': '参考',
90
+ 'badge.origin.agent': '工具写入',
91
+ 'badge.origin.extract': '自动提取',
92
+ 'badge.origin.dream': '整理',
93
+ },
94
+ en: {
95
+ 'tab.title': 'Memory',
96
+ 'guide.title': 'Memory',
97
+ 'guide.description': 'Browse the memory notes of every workspace directory.',
98
+ 'spaces.title': 'Spaces',
99
+ 'spaces.current': 'Current',
100
+ 'spaces.global': 'Global',
101
+ 'spaces.locked': 'Coming soon',
102
+ 'spaces.empty': 'No spaces yet',
103
+ 'spaces.count': '{count}',
104
+ 'spaces.none': '—',
105
+ 'notes.title': 'Memory notes',
106
+ 'notes.empty': 'This directory has no memory yet.',
107
+ 'notes.emptyHint': 'Ask the assistant to remember something in a conversation and the note appears here.',
108
+ 'notes.count': '{count} notes',
109
+ 'notes.refresh': 'Refresh',
110
+ 'index.badge': 'Index',
111
+ 'index.title': 'MEMORY.md index',
112
+ 'index.subtitle': 'Index · {count} entries',
113
+ 'index.open': 'View index',
114
+ 'note.updatedAt': 'Updated {time}',
115
+ 'note.session': 'Session {id}',
116
+ 'note.noSession': 'No source session',
117
+ 'note.noDescription': '(no description)',
118
+ 'state.loading': 'Loading…',
119
+ 'state.error.title': 'Could not load',
120
+ 'state.error.retry': 'Retry',
121
+ 'state.error.network': 'Cannot reach the memory service. Check that the plugin is still running.',
122
+ 'state.error.http': 'The service returned {status}.',
123
+ 'state.error.body': 'The service returned an unreadable response.',
124
+ 'state.error.timeout': 'The request timed out. Try again.',
125
+ 'detail.back': 'Back',
126
+ 'detail.file': 'File',
127
+ 'detail.notFound': 'This note no longer exists; it may have been merged or deleted.',
128
+ 'detail.bytes': '{bytes} bytes',
129
+ 'badge.type.user': 'User',
130
+ 'badge.type.feedback': 'Feedback',
131
+ 'badge.type.project': 'Project',
132
+ 'badge.type.reference': 'Reference',
133
+ 'badge.origin.agent': 'Written by a tool',
134
+ 'badge.origin.extract': 'Extracted automatically',
135
+ 'badge.origin.dream': 'Consolidated',
136
+ },
137
+ }
138
+
139
+ /**
140
+ * Normalise a locale id to its primary subtag: `zh-CN` → `zh`.
141
+ * @param {unknown} value - a locale id, or anything else.
142
+ * @returns {string} the lowercase primary subtag, or '' when unusable.
143
+ */
144
+ function localeTag(value) {
145
+ if (typeof value !== 'string') return ''
146
+ const tag = value.trim().toLowerCase()
147
+ if (tag === '') return ''
148
+ return tag.split(/[-_]/)[0]
149
+ }
150
+
151
+ /**
152
+ * Pick the dictionary for an active locale: exact tag, then `zh`/`en`,
153
+ * then English (the Host's own fallback target).
154
+ * @param {string} active - active locale id.
155
+ * @returns {Record<string, string>} the dictionary to read.
156
+ */
157
+ function dictFor(active) {
158
+ const tag = localeTag(active)
159
+ if (tag !== '' && DICTS[tag] !== undefined) return DICTS[tag]
160
+ return tag === 'zh' ? DICTS.zh : tag === '' ? DICTS.zh : DICTS.en
161
+ }
162
+
163
+ /**
164
+ * Translate one key, substituting `{name}` placeholders.
165
+ * @param {string} active - active locale id.
166
+ * @param {string} key - dictionary key.
167
+ * @param {Record<string, unknown>} [params] - placeholder values.
168
+ * @returns {string} the template, or the key itself when absent.
169
+ */
170
+ function translate(active, key, params) {
171
+ const dict = dictFor(active)
172
+ const template = dict[key] !== undefined ? dict[key] : DICTS.zh[key] !== undefined ? DICTS.zh[key] : key
173
+ if (params === undefined) return template
174
+ return template.replace(/\{(\w+)\}/g, (match, name) =>
175
+ Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match,
176
+ )
177
+ }
178
+
179
+ /**
180
+ * Build a translate function bound to one active locale.
181
+ * @param {string} active - active locale id.
182
+ * @returns {(key: string, params?: Record<string, unknown>) => string} the translator.
183
+ */
184
+ function translatorFor(active) {
185
+ return function t(key, params) {
186
+ return translate(active, key, params)
187
+ }
188
+ }
189
+
190
+ // ------------------------------------------------------- pure helpers --
191
+
192
+ /**
193
+ * Short form of a session id for the note meta line.
194
+ * @param {unknown} value - a session id.
195
+ * @returns {string} the first eight characters, or ''.
196
+ */
197
+ function shortSession(value) {
198
+ const id = typeof value === 'string' ? value.trim() : ''
199
+ if (id === '') return ''
200
+ return id.length > 8 ? id.slice(0, 8) : id
201
+ }
202
+
203
+ /**
204
+ * Format an ISO timestamp in the reader's local time.
205
+ * @param {unknown} value - an ISO 8601 string.
206
+ * @returns {string} `YYYY-MM-DD HH:mm`, or '' when the value is unusable.
207
+ */
208
+ function formatTime(value) {
209
+ if (typeof value !== 'string' || value.trim() === '') return ''
210
+ const date = new Date(value)
211
+ if (Number.isNaN(date.getTime())) return ''
212
+ const pad = n => String(n).padStart(2, '0')
213
+ return (
214
+ `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
215
+ ` ${pad(date.getHours())}:${pad(date.getMinutes())}`
216
+ )
217
+ }
218
+
219
+ /**
220
+ * Order spaces for the left column: enabled before disabled, the current
221
+ * space first, then newest `updatedAt` first.
222
+ * @param {unknown} spaces - the `spaces` array from the API.
223
+ * @returns {Array<object>} a new, sorted array.
224
+ */
225
+ function sortSpaces(spaces) {
226
+ const rows = Array.isArray(spaces) ? spaces.filter(row => row !== null && typeof row === 'object') : []
227
+ // Rank: current workspace, other workspaces, the global space, then
228
+ // disabled placeholders. The global row never floats up by recency.
229
+ const rankOf = row => {
230
+ if (row.key === '_global') return 2
231
+ if (row.enabled === false) return 3
232
+ return row.current === true ? 0 : 1
233
+ }
234
+ return rows.slice().sort((a, b) => {
235
+ const rankA = rankOf(a)
236
+ const rankB = rankOf(b)
237
+ if (rankA !== rankB) return rankA - rankB
238
+ if (rankA === 1) {
239
+ const updatedA = String(a.updatedAt ?? '')
240
+ const updatedB = String(b.updatedAt ?? '')
241
+ if (updatedA !== updatedB) return updatedB.localeCompare(updatedA)
242
+ }
243
+ return String(a.title ?? a.key).localeCompare(String(b.title ?? b.key))
244
+ })
245
+ }
246
+
247
+ /**
248
+ * Pick the space to open when none is selected yet: the API's `current`,
249
+ * else the first enabled row.
250
+ * @param {unknown} spaces - the `spaces` array from the API.
251
+ * @param {unknown} current - the API's `current` key.
252
+ * @returns {string} a space key, or '' when nothing is selectable.
253
+ */
254
+ function pickInitialSpace(spaces, current) {
255
+ const rows = (Array.isArray(spaces) ? spaces : []).filter(
256
+ row => row !== null && typeof row === 'object' && typeof row.key === 'string' && row.enabled !== false,
257
+ )
258
+ if (rows.length === 0) return ''
259
+ const wanted = typeof current === 'string' ? current : ''
260
+ const byKey = wanted === '' ? undefined : rows.find(row => row.key === wanted)
261
+ const byFlag = rows.find(row => row.current === true)
262
+ const chosen = byKey !== undefined ? byKey : byFlag !== undefined ? byFlag : rows[0]
263
+ return String(chosen.key)
264
+ }
265
+
266
+ // ------------------------------------------------------------ markdown --
267
+
268
+ /** Inline syntax: code spans first, then strong, then emphasis. */
269
+ const INLINE_PATTERN = /`([^`\n]+)`|\*\*([^*\n]+)\*\*|\*([^*\n]+)\*/g
270
+
271
+ /**
272
+ * Split one line into inline tokens. Deliberately ignores `_` emphasis so
273
+ * `source_session`-style identifiers survive intact.
274
+ * @param {unknown} text - one line of Markdown.
275
+ * @returns {Array<{kind: string, text: string}>} tokens in order.
276
+ */
277
+ function parseInline(text) {
278
+ const source = typeof text === 'string' ? text : ''
279
+ if (source === '') return []
280
+ const tokens = []
281
+ let last = 0
282
+ INLINE_PATTERN.lastIndex = 0
283
+ let match = INLINE_PATTERN.exec(source)
284
+ while (match !== null) {
285
+ if (match.index > last) tokens.push({ kind: 'text', text: source.slice(last, match.index) })
286
+ if (match[1] !== undefined) tokens.push({ kind: 'code', text: match[1] })
287
+ else if (match[2] !== undefined) tokens.push({ kind: 'strong', text: match[2] })
288
+ else if (match[3] !== undefined) tokens.push({ kind: 'em', text: match[3] })
289
+ last = match.index + match[0].length
290
+ match = INLINE_PATTERN.exec(source)
291
+ }
292
+ if (last < source.length) tokens.push({ kind: 'text', text: source.slice(last) })
293
+ return tokens
294
+ }
295
+
296
+ /**
297
+ * Whether a line opens a non-paragraph block.
298
+ * @param {string} line - one source line.
299
+ * @returns {boolean} true when a paragraph must stop before it.
300
+ */
301
+ function startsBlock(line) {
302
+ return (
303
+ /^\s*(```|~~~)/.test(line) ||
304
+ /^\s*#{1,6}\s/.test(line) ||
305
+ /^\s*>/.test(line) ||
306
+ /^\s*([-*+]|\d{1,9}[.)])\s+/.test(line) ||
307
+ /^\s*([-*_])\s*(\1\s*){2,}$/.test(line)
308
+ )
309
+ }
310
+
311
+ /**
312
+ * Parse the small Markdown subset memory notes use into blocks. The body
313
+ * arrives without frontmatter, so a leading `---` is a rule.
314
+ * @param {unknown} source - the note body.
315
+ * @returns {Array<object>} blocks: heading, paragraph, list, quote, code, rule.
316
+ */
317
+ function parseMarkdown(source) {
318
+ const text = typeof source === 'string' ? source.replace(/\r\n?/g, '\n') : ''
319
+ const lines = text.split('\n')
320
+ const blocks = []
321
+ let i = 0
322
+ while (i < lines.length) {
323
+ const line = lines[i]
324
+ if (line.trim() === '') {
325
+ i += 1
326
+ continue
327
+ }
328
+ const fence = /^\s*(```|~~~)\s*([\w+#.-]*)\s*$/.exec(line)
329
+ if (fence !== null) {
330
+ const marker = fence[1]
331
+ const lang = fence[2]
332
+ const code = []
333
+ i += 1
334
+ while (i < lines.length) {
335
+ const current = lines[i]
336
+ if (/^\s*(```|~~~)\s*$/.test(current)) {
337
+ i += 1
338
+ break
339
+ }
340
+ code.push(current)
341
+ i += 1
342
+ }
343
+ // A blank line before the closing marker is the split artefact, not content.
344
+ while (code.length > 0 && code[code.length - 1] === '') code.pop()
345
+ blocks.push({ kind: 'code', lang: lang, text: code.join('\n') })
346
+ continue
347
+ }
348
+ const heading = /^\s*(#{1,6})\s+(.*)$/.exec(line)
349
+ if (heading !== null) {
350
+ blocks.push({ kind: 'heading', level: heading[1].length, text: heading[2].trim() })
351
+ i += 1
352
+ continue
353
+ }
354
+ if (/^\s*([-*_])\s*(\1\s*){2,}$/.test(line)) {
355
+ blocks.push({ kind: 'rule' })
356
+ i += 1
357
+ continue
358
+ }
359
+ if (/^\s*>/.test(line)) {
360
+ const quoted = []
361
+ while (i < lines.length && /^\s*>/.test(lines[i])) {
362
+ quoted.push(lines[i].replace(/^\s*>\s?/, ''))
363
+ i += 1
364
+ }
365
+ blocks.push({ kind: 'quote', blocks: parseMarkdown(quoted.join('\n')) })
366
+ continue
367
+ }
368
+ const bullet = /^\s*([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(line)
369
+ if (bullet !== null) {
370
+ const ordered = /\d/.test(bullet[1])
371
+ const items = [bullet[2]]
372
+ i += 1
373
+ while (i < lines.length) {
374
+ const next = /^\s*([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(lines[i])
375
+ if (next !== null) {
376
+ if (/\d/.test(next[1]) !== ordered) break
377
+ items.push(next[2])
378
+ i += 1
379
+ continue
380
+ }
381
+ // A wrapped continuation line belongs to the previous item.
382
+ if (lines[i].trim() !== '' && /^\s{2,}\S/.test(lines[i]) && !startsBlock(lines[i])) {
383
+ items[items.length - 1] = `${items[items.length - 1]} ${lines[i].trim()}`
384
+ i += 1
385
+ continue
386
+ }
387
+ break
388
+ }
389
+ blocks.push({ kind: 'list', ordered: ordered, items: items })
390
+ continue
391
+ }
392
+ const paragraph = []
393
+ while (i < lines.length && lines[i].trim() !== '' && !startsBlock(lines[i])) {
394
+ paragraph.push(lines[i].trim())
395
+ i += 1
396
+ }
397
+ if (paragraph.length === 0) {
398
+ i += 1
399
+ continue
400
+ }
401
+ blocks.push({ kind: 'paragraph', text: paragraph.join(' ') })
402
+ }
403
+ return blocks
404
+ }
405
+
406
+ /**
407
+ * Render inline tokens.
408
+ * @param {Array<{kind: string, text: string}>} tokens - from parseInline.
409
+ * @returns {Array<React.ReactNode>} nodes.
410
+ */
411
+ function renderInline(tokens) {
412
+ return tokens.map((token, index) => {
413
+ if (token.kind === 'code') return h('code', { key: `i${index}` }, token.text)
414
+ if (token.kind === 'strong') return h('strong', { key: `i${index}` }, token.text)
415
+ if (token.kind === 'em') return h('em', { key: `i${index}` }, token.text)
416
+ return token.text
417
+ })
418
+ }
419
+
420
+ /**
421
+ * Render one Markdown block.
422
+ * @param {object} block - from parseMarkdown.
423
+ * @param {string} key - React key.
424
+ * @returns {React.ReactNode} the element.
425
+ */
426
+ function renderBlock(block, key) {
427
+ if (block.kind === 'heading') {
428
+ const level = Math.min(6, Math.max(1, Number(block.level) || 1))
429
+ return h(`h${level}`, { key: key, className: `dm-md-h dm-md-h${level}` }, renderInline(parseInline(block.text)))
430
+ }
431
+ if (block.kind === 'code') {
432
+ return h(
433
+ 'pre',
434
+ { key: key, 'data-lang': block.lang || undefined },
435
+ h('code', null, block.text),
436
+ )
437
+ }
438
+ if (block.kind === 'list') {
439
+ const items = block.items.map((item, index) => h('li', { key: `l${index}` }, renderInline(parseInline(item))))
440
+ return h(block.ordered ? 'ol' : 'ul', { key: key }, items)
441
+ }
442
+ if (block.kind === 'quote') {
443
+ return h('blockquote', { key: key }, block.blocks.map((inner, index) => renderBlock(inner, `q${index}`)))
444
+ }
445
+ if (block.kind === 'rule') return h('hr', { key: key })
446
+ return h('p', { key: key }, renderInline(parseInline(block.text)))
447
+ }
448
+
449
+ /**
450
+ * Render a note body.
451
+ * @param {unknown} body - Markdown source.
452
+ * @returns {Array<React.ReactNode>} blocks; an empty body renders nothing.
453
+ */
454
+ function renderMarkdown(body) {
455
+ return parseMarkdown(body).map((block, index) => renderBlock(block, `b${index}`))
456
+ }
457
+
458
+ // ---------------------------------------------------------------- http --
459
+
460
+ /**
461
+ * One request failure, as data instead of a thrown string.
462
+ * @typedef {{code: string, status: string, detail: string}} RequestError
463
+ */
464
+
465
+ /**
466
+ * Build a request error.
467
+ * @param {string} code - 'network' | 'http' | 'body' | 'timeout'.
468
+ * @param {string} [status] - HTTP status when there was one.
469
+ * @param {string} [detail] - server-provided message.
470
+ * @returns {RequestError} the error value.
471
+ */
472
+ function requestError(code, status, detail) {
473
+ return {
474
+ code: code,
475
+ status: typeof status === 'string' ? status : '',
476
+ detail: typeof detail === 'string' ? detail : '',
477
+ }
478
+ }
479
+
480
+ /**
481
+ * GET one JSON route.
482
+ * @param {string} url - same-origin URL.
483
+ * @param {AbortSignal} [signal] - caller cancellation.
484
+ * @returns {Promise<object>} the parsed payload.
485
+ */
486
+ async function requestJson(url, signal) {
487
+ let response
488
+ try {
489
+ response = await fetch(url, {
490
+ signal: signal,
491
+ credentials: 'same-origin',
492
+ headers: { accept: 'application/json' },
493
+ })
494
+ } catch (error) {
495
+ if (error !== null && typeof error === 'object' && error.name === 'AbortError') throw error
496
+ throw requestError('network', '', error !== null && typeof error === 'object' ? error.message : '')
497
+ }
498
+ let payload = null
499
+ try {
500
+ payload = await response.json()
501
+ } catch {
502
+ payload = null
503
+ }
504
+ if (response.ok !== true) {
505
+ const message = payload !== null && typeof payload === 'object' && typeof payload.error === 'string' ? payload.error : ''
506
+ throw requestError('http', String(response.status), message)
507
+ }
508
+ if (payload === null || typeof payload !== 'object') throw requestError('body')
509
+ return payload
510
+ }
511
+
512
+ /**
513
+ * The three read routes, bound to the page's base path.
514
+ * @returns {{spaces: Function, notes: Function, note: Function}} the API face.
515
+ */
516
+ function createApi() {
517
+ return {
518
+ spaces(signal) {
519
+ return requestJson(`${API_BASE}/spaces`, signal)
520
+ },
521
+ notes(space, signal) {
522
+ return requestJson(`${API_BASE}/notes?space=${encodeURIComponent(String(space))}`, signal)
523
+ },
524
+ index(space, signal) {
525
+ return requestJson(`${API_BASE}/index?space=${encodeURIComponent(String(space))}`, signal)
526
+ },
527
+ note(space, file, signal) {
528
+ return requestJson(
529
+ `${API_BASE}/note?space=${encodeURIComponent(String(space))}&file=${encodeURIComponent(String(file))}`,
530
+ signal,
531
+ )
532
+ },
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Turn a request failure into one readable line.
538
+ * @param {RequestError|null} error - the failure.
539
+ * @param {(key: string, params?: Record<string, unknown>) => string} t - translator.
540
+ * @returns {string} the message.
541
+ */
542
+ function describeError(error, t) {
543
+ if (error === null || error === undefined) return ''
544
+ if (error.code === 'network') return t('state.error.network')
545
+ if (error.code === 'body') return t('state.error.body')
546
+ if (error.code === 'timeout') return t('state.error.timeout')
547
+ const line = t('state.error.http', { status: error.status })
548
+ if (error.detail !== '') return `${line} ${error.detail}`
549
+ return line
550
+ }
551
+
552
+ // -------------------------------------------------------------- state --
553
+
554
+ /**
555
+ * One resource's load state.
556
+ * @typedef {{status: 'idle'|'loading'|'ready'|'error', data: unknown, error: RequestError|null}} ResourceState
557
+ */
558
+
559
+ /**
560
+ * Load an API resource, cancelling on unmount and on dependency change.
561
+ *
562
+ * `loader` is read through a ref, so an inline arrow does not restart the
563
+ * request; `deps` is what actually decides when to reload.
564
+ * @param {null|((signal: AbortSignal|undefined) => Promise<unknown>)} loader - request, or null to stay idle.
565
+ * @param {Array<unknown>} deps - reload triggers.
566
+ * @returns {[ResourceState, () => void]} state and a retry trigger.
567
+ */
568
+ function useResource(loader, deps) {
569
+ const [state, setState] = react.useState({ status: loader === null ? 'idle' : 'loading', data: null, error: null })
570
+ const [nonce, setNonce] = react.useState(0)
571
+ const loaderRef = react.useRef(loader)
572
+ loaderRef.current = loader
573
+ const reload = react.useCallback(() => setNonce(value => value + 1), [])
574
+ const skip = loader === null
575
+ react.useEffect(() => {
576
+ const load = loaderRef.current
577
+ if (skip || typeof load !== 'function') {
578
+ setState({ status: 'idle', data: null, error: null })
579
+ return undefined
580
+ }
581
+ let active = true
582
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
583
+ setState({ status: 'loading', data: null, error: null })
584
+ const timer = setTimeout(() => {
585
+ if (controller !== null) controller.abort()
586
+ }, REQUEST_TIMEOUT_MS)
587
+ Promise.resolve()
588
+ .then(() => load(controller === null ? undefined : controller.signal))
589
+ .then(
590
+ data => {
591
+ if (!active) return
592
+ clearTimeout(timer)
593
+ setState({ status: 'ready', data: data, error: null })
594
+ },
595
+ error => {
596
+ if (!active) return
597
+ clearTimeout(timer)
598
+ if (error !== null && typeof error === 'object' && error.name === 'AbortError') {
599
+ setState({ status: 'error', data: null, error: requestError('timeout') })
600
+ return
601
+ }
602
+ const shaped =
603
+ error !== null && typeof error === 'object' && typeof error.code === 'string'
604
+ ? error
605
+ : requestError('network')
606
+ setState({ status: 'error', data: null, error: shaped })
607
+ },
608
+ )
609
+ return () => {
610
+ active = false
611
+ clearTimeout(timer)
612
+ if (controller !== null) controller.abort()
613
+ }
614
+ }, [nonce, skip].concat(deps))
615
+ return [state, reload]
616
+ }
617
+
618
+ /**
619
+ * Read the active locale id from the host locale service.
620
+ * @param {{locale: object|null}} env - page environment.
621
+ * @returns {string} the active locale id, or '' without a locale service.
622
+ */
623
+ function readLocale(env) {
624
+ const locale = env.locale
625
+ if (locale === null || typeof locale.getSnapshot !== 'function') return ''
626
+ try {
627
+ const snapshot = locale.getSnapshot()
628
+ return snapshot !== null && typeof snapshot === 'object' && typeof snapshot.active === 'string' ? snapshot.active : ''
629
+ } catch {
630
+ return ''
631
+ }
632
+ }
633
+
634
+ /**
635
+ * Subscribe to locale changes so the page re-renders on a language switch.
636
+ * @param {{locale: object|null}} env - page environment.
637
+ * @returns {string} the active locale id.
638
+ */
639
+ function useLocale(env) {
640
+ const [active, setActive] = react.useState(() => readLocale(env))
641
+ react.useEffect(() => {
642
+ setActive(readLocale(env))
643
+ const locale = env.locale
644
+ if (locale === null || typeof locale.subscribe !== 'function') return undefined
645
+ let unsubscribe = null
646
+ try {
647
+ unsubscribe = locale.subscribe(() => setActive(readLocale(env)))
648
+ } catch {
649
+ return undefined
650
+ }
651
+ return () => {
652
+ if (typeof unsubscribe === 'function') unsubscribe()
653
+ }
654
+ }, [env])
655
+ return active
656
+ }
657
+
658
+ // --------------------------------------------------------- components --
659
+
660
+ const COLUMN_CSS = `
661
+ .dm-page, .dm-page * { box-sizing: border-box; }
662
+ .dm-page {
663
+ display: flex;
664
+ flex-direction: column;
665
+ height: 100%;
666
+ min-height: 0;
667
+ min-width: 0;
668
+ color: var(--dsw-alias-label-primary);
669
+ font-size: 13px;
670
+ line-height: 1.5;
671
+ container-type: inline-size;
672
+ }
673
+ .dm-split { display: flex; flex: 1 1 auto; min-height: 0; min-width: 0; }
674
+
675
+ /* Left column: memory spaces, one per workspace directory. */
676
+ .dm-spaces {
677
+ display: flex;
678
+ flex: 0 0 134px;
679
+ flex-direction: column;
680
+ gap: 2px;
681
+ min-height: 0;
682
+ overflow-y: auto;
683
+ padding: 8px 6px;
684
+ background: var(--dsw-alias-bg-layer-1);
685
+ border-right: 0.5px solid var(--dsw-alias-border-l3);
686
+ }
687
+ .dm-spaces-label {
688
+ padding: 2px 8px 6px;
689
+ color: var(--dsw-alias-label-tertiary);
690
+ font-size: 11px;
691
+ letter-spacing: 0.02em;
692
+ }
693
+ .dm-space {
694
+ display: flex;
695
+ flex: none;
696
+ align-items: center;
697
+ gap: 6px;
698
+ width: 100%;
699
+ min-width: 0;
700
+ padding: 5px 8px;
701
+ border: 0;
702
+ border-radius: 6px;
703
+ background: transparent;
704
+ color: var(--dsw-alias-label-secondary);
705
+ font: inherit;
706
+ font-size: 12.5px;
707
+ text-align: left;
708
+ cursor: pointer;
709
+ }
710
+ .dm-space[data-selected="true"] {
711
+ background: var(--dsw-alias-interactive-bg-hover);
712
+ box-shadow: inset 2px 0 0 var(--dsw-alias-state-business-primary);
713
+ color: var(--dsw-alias-label-primary);
714
+ font-weight: 500;
715
+ }
716
+ .dm-space:disabled { opacity: 0.55; cursor: default; }
717
+ .dm-space-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
718
+ .dm-space-count {
719
+ flex: none;
720
+ color: var(--dsw-alias-label-caption);
721
+ font-size: 11px;
722
+ font-variant-numeric: tabular-nums;
723
+ }
724
+ .dm-space-flag {
725
+ flex: none;
726
+ padding: 0 4px;
727
+ border: 0.5px solid var(--dsw-alias-border-l3);
728
+ border-radius: 4px;
729
+ color: var(--dsw-alias-label-tertiary);
730
+ font-size: 10px;
731
+ line-height: 15px;
732
+ }
733
+ .dm-spaces-empty { padding: 6px 8px; color: var(--dsw-alias-label-tertiary); font-size: 11.5px; }
734
+
735
+ /* Right column: one pane, either the timeline or one note. */
736
+ .dm-index { border-left: 2px solid var(--dsw-alias-accent, #8fb3ff); }
737
+ .dm-index .dm-note-name { letter-spacing: 0.02em; }
738
+ .dm-notes { display: flex; flex: 1 1 auto; flex-direction: column; min-width: 0; min-height: 0; }
739
+ .dm-notes-head {
740
+ display: flex;
741
+ flex: none;
742
+ align-items: center;
743
+ gap: 8px;
744
+ padding: 10px 14px 8px;
745
+ border-bottom: 0.5px solid var(--dsw-alias-border-l3);
746
+ }
747
+ .dm-notes-title {
748
+ flex: 1 1 auto;
749
+ min-width: 0;
750
+ overflow: hidden;
751
+ font-size: 12.5px;
752
+ font-weight: 600;
753
+ text-overflow: ellipsis;
754
+ white-space: nowrap;
755
+ }
756
+ .dm-notes-sub {
757
+ flex: none;
758
+ color: var(--dsw-alias-label-tertiary);
759
+ font-size: 11px;
760
+ font-variant-numeric: tabular-nums;
761
+ white-space: nowrap;
762
+ }
763
+ .dm-scroll { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
764
+
765
+ /* Notes as a timeline: one clickable row per note. */
766
+ .dm-note {
767
+ display: block;
768
+ width: 100%;
769
+ padding: 10px 14px;
770
+ border: 0;
771
+ border-bottom: 0.5px solid var(--dsw-alias-border-l3);
772
+ background: transparent;
773
+ color: inherit;
774
+ font: inherit;
775
+ text-align: left;
776
+ cursor: pointer;
777
+ }
778
+ .dm-note-name { display: block; font-weight: 500; overflow-wrap: anywhere; }
779
+ .dm-badges { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
780
+ .dm-badge {
781
+ display: inline-flex;
782
+ align-items: center;
783
+ padding: 0 6px;
784
+ border: 0.5px solid var(--dsw-alias-border-l3);
785
+ border-radius: 4px;
786
+ background: var(--dsw-alias-bg-layer-2);
787
+ color: var(--dsw-alias-label-secondary);
788
+ font-size: 10.5px;
789
+ line-height: 16px;
790
+ white-space: nowrap;
791
+ }
792
+ .dm-badge[data-tone="user"] { color: var(--dsw-alias-state-business-primary); }
793
+ .dm-badge[data-tone="feedback"] { color: var(--dsw-alias-state-warn-primary); }
794
+ .dm-badge[data-tone="project"] { color: var(--dsw-alias-state-success-primary); }
795
+ .dm-badge[data-tone="reference"] { color: var(--dsw-alias-label-tertiary); }
796
+ .dm-badge[data-tone="origin"] { color: var(--dsw-alias-label-caption); }
797
+ .dm-note-desc {
798
+ display: -webkit-box;
799
+ margin: 3px 0 0;
800
+ overflow: hidden;
801
+ color: var(--dsw-alias-label-secondary);
802
+ font-size: 12px;
803
+ -webkit-box-orient: vertical;
804
+ -webkit-line-clamp: 2;
805
+ }
806
+ .dm-note-meta {
807
+ display: flex;
808
+ flex-wrap: wrap;
809
+ gap: 8px;
810
+ margin-top: 5px;
811
+ color: var(--dsw-alias-label-tertiary);
812
+ font-size: 11px;
813
+ font-variant-numeric: tabular-nums;
814
+ }
815
+
816
+ /* Loading, empty and failure states. */
817
+ .dm-skel-row {
818
+ display: flex;
819
+ flex-direction: column;
820
+ gap: 6px;
821
+ padding: 11px 14px;
822
+ border-bottom: 0.5px solid var(--dsw-alias-border-l3);
823
+ }
824
+ .dm-skel-bar {
825
+ height: 9px;
826
+ border-radius: 4px;
827
+ background: var(--dsw-alias-bg-skeleton);
828
+ animation: dm-pulse 1.3s ease-in-out infinite;
829
+ }
830
+ .dm-skel-bar:nth-child(2) { width: 68%; }
831
+ .dm-skel-bar:nth-child(3) { width: 38%; }
832
+ @keyframes dm-pulse { 0%, 100% { opacity: 0.45; } 50% { opacity: 0.9; } }
833
+ .dm-state { display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 26px 16px; }
834
+ .dm-state-title { margin: 0; color: var(--dsw-alias-label-primary); font-weight: 500; overflow-wrap: anywhere; }
835
+ .dm-state-hint { margin: 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; overflow-wrap: anywhere; }
836
+ .dm-state-error .dm-state-title { color: var(--dsw-alias-state-error-primary); }
837
+ .dm-state-detail { margin: 0; color: var(--dsw-alias-label-tertiary); font-size: 11.5px; overflow-wrap: anywhere; }
838
+
839
+ /* Controls are written here: no Harness UI package may be imported. */
840
+ .dm-ghost {
841
+ flex: none;
842
+ padding: 2px 8px;
843
+ border: 0.5px solid var(--dsw-alias-border-l3);
844
+ border-radius: 6px;
845
+ background: transparent;
846
+ color: var(--dsw-alias-label-secondary);
847
+ font: inherit;
848
+ font-size: 11.5px;
849
+ line-height: 18px;
850
+ cursor: pointer;
851
+ }
852
+ .dm-retry {
853
+ margin-top: 4px;
854
+ padding: 4px 12px;
855
+ border: 0.5px solid var(--dsw-alias-border-l3);
856
+ border-radius: 6px;
857
+ background: var(--dsw-alias-bg-layer-2);
858
+ color: var(--dsw-alias-label-primary);
859
+ font: inherit;
860
+ font-size: 12px;
861
+ line-height: 18px;
862
+ cursor: pointer;
863
+ }
864
+ .dm-ghost:disabled { opacity: 0.5; cursor: default; }
865
+ .dm-space:focus-visible, .dm-note:focus-visible, .dm-ghost:focus-visible, .dm-retry:focus-visible, .dm-back:focus-visible {
866
+ outline: 2px solid var(--dsw-alias-border-selected);
867
+ outline-offset: 1px;
868
+ }
869
+
870
+ /* Detail: breadcrumb, then the note itself. */
871
+ .dm-crumbs {
872
+ display: flex;
873
+ flex: none;
874
+ align-items: center;
875
+ gap: 6px;
876
+ padding: 8px 12px;
877
+ border-bottom: 0.5px solid var(--dsw-alias-border-l3);
878
+ min-width: 0;
879
+ }
880
+ .dm-back {
881
+ flex: none;
882
+ padding: 1px 7px;
883
+ border: 0.5px solid var(--dsw-alias-border-l3);
884
+ border-radius: 6px;
885
+ background: transparent;
886
+ color: var(--dsw-alias-label-secondary);
887
+ font: inherit;
888
+ font-size: 11.5px;
889
+ line-height: 18px;
890
+ cursor: pointer;
891
+ }
892
+ .dm-crumb {
893
+ min-width: 0;
894
+ overflow: hidden;
895
+ color: var(--dsw-alias-label-tertiary);
896
+ font-size: 11.5px;
897
+ text-overflow: ellipsis;
898
+ white-space: nowrap;
899
+ }
900
+ .dm-crumb[data-last="true"] { flex: 1 1 auto; color: var(--dsw-alias-label-secondary); }
901
+ .dm-crumb-sep { flex: none; color: var(--dsw-alias-label-dimmed); font-size: 11px; }
902
+ .dm-detail { display: flex; flex-direction: column; gap: 10px; padding: 12px 14px 22px; min-width: 0; }
903
+ .dm-detail-head { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
904
+ .dm-detail-title { margin: 0; font-size: 14px; font-weight: 600; line-height: 1.35; overflow-wrap: anywhere; }
905
+ .dm-detail-desc { margin: 0; color: var(--dsw-alias-label-secondary); font-size: 12px; overflow-wrap: anywhere; }
906
+ .dm-file {
907
+ margin: 0;
908
+ padding: 6px 8px;
909
+ border: 0.5px solid var(--dsw-alias-border-l3);
910
+ border-radius: 6px;
911
+ background: var(--dsw-alias-bg-layer-1);
912
+ color: var(--dsw-alias-label-tertiary);
913
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
914
+ font-size: 11px;
915
+ overflow-wrap: anywhere;
916
+ }
917
+ .dm-file-label { display: block; margin-bottom: 2px; color: var(--dsw-alias-label-caption); font-family: inherit; }
918
+
919
+ /* The note body: a deliberately small Markdown subset. */
920
+ .dm-md { display: flex; flex-direction: column; gap: 10px; min-width: 0; overflow-wrap: anywhere; }
921
+ .dm-md p { margin: 0; }
922
+ .dm-md-h { margin: 2px 0 0; font-weight: 600; line-height: 1.35; }
923
+ .dm-md-h1 { font-size: 15px; }
924
+ .dm-md-h2 { font-size: 14px; }
925
+ .dm-md-h3, .dm-md-h4, .dm-md-h5, .dm-md-h6 { font-size: 13px; }
926
+ .dm-md ul, .dm-md ol { margin: 0; padding-left: 18px; }
927
+ .dm-md li + li { margin-top: 2px; }
928
+ .dm-md blockquote {
929
+ margin: 0;
930
+ padding: 2px 0 2px 10px;
931
+ border-left: 2px solid var(--dsw-alias-border-l3);
932
+ color: var(--dsw-alias-label-secondary);
933
+ }
934
+ .dm-md pre {
935
+ margin: 0;
936
+ padding: 10px;
937
+ border: 0.5px solid var(--dsw-alias-border-l3);
938
+ border-radius: 6px;
939
+ background: var(--dsw-alias-markdown-code-block);
940
+ overflow-x: auto;
941
+ font-size: 11.5px;
942
+ line-height: 1.45;
943
+ }
944
+ .dm-md code {
945
+ padding: 1px 4px;
946
+ border-radius: 4px;
947
+ background: var(--dsw-alias-markdown-inline-code);
948
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
949
+ font-size: 0.92em;
950
+ }
951
+ .dm-md pre code { padding: 0; background: transparent; font-size: inherit; white-space: pre; }
952
+ .dm-md hr { margin: 2px 0; border: 0; border-top: 0.5px solid var(--dsw-alias-border-l3); }
953
+
954
+ /* Scrollbars inside this page only. */
955
+ .dm-scroll::-webkit-scrollbar { width: 8px; height: 8px; }
956
+ .dm-scroll::-webkit-scrollbar-track { background: transparent; }
957
+ .dm-scroll::-webkit-scrollbar-thumb { background: var(--dsw-alias-scrollbar-bg-l2); border-radius: 4px; }
958
+ .dm-scroll:hover::-webkit-scrollbar-thumb { background: var(--dsw-alias-scrollbar-hover-l2); }
959
+
960
+ /* Pointer-only affordances: a tap must not latch a hover state. */
961
+ @media (hover: hover) {
962
+ .dm-space:not(:disabled):hover { background: var(--dsw-alias-interactive-bg-hover); color: var(--dsw-alias-label-primary); }
963
+ .dm-note:hover { background: var(--dsw-alias-interactive-bg-hover); }
964
+ .dm-ghost:not(:disabled):hover, .dm-back:hover, .dm-retry:hover {
965
+ background: var(--dsw-alias-interactive-bg-hover);
966
+ color: var(--dsw-alias-label-primary);
967
+ }
968
+ }
969
+
970
+ /* A narrow pane turns the space list into a chip row above the timeline. */
971
+ @container (max-width: 340px) {
972
+ .dm-split { flex-direction: column; }
973
+ .dm-spaces {
974
+ flex: none;
975
+ flex-direction: row;
976
+ gap: 4px;
977
+ padding: 6px;
978
+ overflow-x: auto;
979
+ overflow-y: hidden;
980
+ border-right: 0;
981
+ border-bottom: 0.5px solid var(--dsw-alias-border-l3);
982
+ }
983
+ .dm-spaces-label { display: none; }
984
+ .dm-space { width: auto; max-width: 60cqw; }
985
+ .dm-space-count { display: none; }
986
+ }
987
+ .dm-sr {
988
+ position: absolute;
989
+ width: 1px;
990
+ height: 1px;
991
+ padding: 0;
992
+ margin: -1px;
993
+ overflow: hidden;
994
+ clip: rect(0 0 0 0);
995
+ white-space: nowrap;
996
+ border: 0;
997
+ }
998
+ `
999
+
1000
+ /** One `<style>` element: unmounting the page removes it with the rest of the tree. */
1001
+ function StyleSheet() {
1002
+ return h('style', { 'data-dsh-memory-style': '' }, COLUMN_CSS)
1003
+ }
1004
+
1005
+ /**
1006
+ * Loading placeholder rows.
1007
+ * @param {{rows: number, label: string}} props - how many rows, and the spoken label.
1008
+ * @returns {React.ReactNode} the skeleton.
1009
+ */
1010
+ function Skeleton(props) {
1011
+ const rows = []
1012
+ for (let index = 0; index < props.rows; index += 1) {
1013
+ rows.push(
1014
+ h(
1015
+ 'div',
1016
+ { key: `s${index}`, className: 'dm-skel-row', 'aria-hidden': 'true' },
1017
+ h('div', { className: 'dm-skel-bar' }),
1018
+ h('div', { className: 'dm-skel-bar' }),
1019
+ h('div', { className: 'dm-skel-bar' }),
1020
+ ),
1021
+ )
1022
+ }
1023
+ return h('div', { role: 'status', 'aria-live': 'polite', 'aria-busy': 'true' }, [
1024
+ h('span', { key: 'label', className: 'dm-sr' }, props.label),
1025
+ ...rows,
1026
+ ])
1027
+ }
1028
+
1029
+ /**
1030
+ * One badge.
1031
+ * @param {{label: string, tone?: string}} props - text and tone.
1032
+ * @returns {React.ReactNode} the badge.
1033
+ */
1034
+ function Badge(props) {
1035
+ return h('span', { className: 'dm-badge', 'data-tone': props.tone }, props.label)
1036
+ }
1037
+
1038
+ /**
1039
+ * A disabled `_global` or an unreachable space placeholder row.
1040
+ * @param {{label: string, note: string}} props - the row text and its suffix.
1041
+ * @returns {React.ReactNode} the row.
1042
+ */
1043
+ function PlaceholderRow(props) {
1044
+ return h('button', { type: 'button', className: 'dm-space', disabled: true, 'aria-disabled': 'true' }, [
1045
+ h('span', { key: 'name', className: 'dm-space-name' }, props.label),
1046
+ h('span', { key: 'note', className: 'dm-space-flag' }, props.note),
1047
+ ])
1048
+ }
1049
+
1050
+ /**
1051
+ * Left column: the spaces of every known workspace directory.
1052
+ * @param {object} props - rows, selection, status and the select handler.
1053
+ * @returns {React.ReactNode} the column.
1054
+ */
1055
+ function SpacesColumn(props) {
1056
+ const t = props.t
1057
+ const children = [h('div', { key: 'label', className: 'dm-spaces-label' }, t('spaces.title'))]
1058
+ if (props.status === 'loading') {
1059
+ children.push(h(Skeleton, { key: 'skel', rows: 3, label: t('state.loading') }))
1060
+ } else if (props.status === 'error') {
1061
+ children.push(h('div', { key: 'err', className: 'dm-spaces-empty' }, t('spaces.none')))
1062
+ } else if (props.rows.length === 0) {
1063
+ children.push(h('div', { key: 'empty', className: 'dm-spaces-empty' }, t('spaces.empty')))
1064
+ } else {
1065
+ for (const row of props.rows) {
1066
+ const disabled = row.enabled === false
1067
+ const label = row.key === '_global' ? t('spaces.global') : String(row.title ?? row.key)
1068
+ if (disabled) {
1069
+ children.push(
1070
+ h(PlaceholderRow, { key: String(row.key), label: label, note: t('spaces.locked') }),
1071
+ )
1072
+ continue
1073
+ }
1074
+ const count = Number(row.count)
1075
+ children.push(
1076
+ h(
1077
+ 'button',
1078
+ {
1079
+ key: String(row.key),
1080
+ type: 'button',
1081
+ className: 'dm-space',
1082
+ 'data-selected': props.spaceKey === row.key ? 'true' : 'false',
1083
+ 'aria-current': props.spaceKey === row.key ? 'true' : undefined,
1084
+ title: typeof row.path === 'string' && row.path !== '' ? row.path : String(row.key),
1085
+ onClick: () => props.onSelect(String(row.key)),
1086
+ },
1087
+ [
1088
+ h('span', { key: 'name', className: 'dm-space-name' }, label),
1089
+ row.current === true ? h('span', { key: 'flag', className: 'dm-space-flag' }, t('spaces.current')) : null,
1090
+ Number.isFinite(count) && count > 0
1091
+ ? h('span', { key: 'count', className: 'dm-space-count' }, t('spaces.count', { count: count }))
1092
+ : null,
1093
+ ],
1094
+ ),
1095
+ )
1096
+ }
1097
+ }
1098
+ return h('nav', { className: 'dm-spaces dm-scroll', 'aria-label': t('spaces.title') }, children)
1099
+ }
1100
+
1101
+ /**
1102
+ * The failure state with its retry control.
1103
+ * @param {{t: Function, message: string, onRetry: Function}} props - copy and handler.
1104
+ * @returns {React.ReactNode} the state block.
1105
+ */
1106
+ function ErrorState(props) {
1107
+ return h('div', { className: 'dm-state dm-state-error', role: 'alert' }, [
1108
+ h('p', { key: 'title', className: 'dm-state-title' }, props.t('state.error.title')),
1109
+ h('p', { key: 'detail', className: 'dm-state-detail' }, props.message),
1110
+ h(
1111
+ 'button',
1112
+ { key: 'retry', type: 'button', className: 'dm-retry', onClick: () => props.onRetry() },
1113
+ props.t('state.error.retry'),
1114
+ ),
1115
+ ])
1116
+ }
1117
+
1118
+ /**
1119
+ * The note timeline row.
1120
+ * @param {{t: Function, note: object, onOpen: Function}} props - copy, note and handler.
1121
+ * @returns {React.ReactNode} the row.
1122
+ */
1123
+ function NoteRow(props) {
1124
+ const note = props.note
1125
+ const t = props.t
1126
+ const updated = formatTime(note.updated)
1127
+ const created = formatTime(note.created)
1128
+ const time = updated !== '' ? updated : created
1129
+ const session = shortSession(note.sourceSession)
1130
+ const typeKey = `badge.type.${String(note.type)}`
1131
+ const originKey = `badge.origin.${String(note.origin)}`
1132
+ const typeLabel = translate(props.locale, typeKey) === typeKey ? String(note.type) : t(typeKey)
1133
+ const originLabel = translate(props.locale, originKey) === originKey ? String(note.origin) : t(originKey)
1134
+ const description = typeof note.description === 'string' && note.description.trim() !== '' ? note.description : t('note.noDescription')
1135
+ return h(
1136
+ 'button',
1137
+ {
1138
+ type: 'button',
1139
+ className: 'dm-note',
1140
+ 'data-note-file': String(note.file ?? ''),
1141
+ onClick: () => props.onOpen(String(note.file ?? '')),
1142
+ },
1143
+ [
1144
+ h('span', { key: 'name', className: 'dm-note-name' }, String(note.name ?? note.file ?? '')),
1145
+ h('span', { key: 'badges', className: 'dm-badges' }, [
1146
+ h(Badge, { key: 'type', label: typeLabel, tone: String(note.type) }),
1147
+ h(Badge, { key: 'origin', label: originLabel, tone: 'origin' }),
1148
+ ]),
1149
+ h('span', { key: 'desc', className: 'dm-note-desc' }, description),
1150
+ h('span', { key: 'meta', className: 'dm-note-meta' }, [
1151
+ time !== '' ? h('span', { key: 'time' }, t('note.updatedAt', { time: time })) : null,
1152
+ h('span', { key: 'session' }, session !== '' ? t('note.session', { id: session }) : t('note.noSession')),
1153
+ ]),
1154
+ ],
1155
+ )
1156
+ }
1157
+
1158
+ /**
1159
+ * Right column, timeline mode: header, then one of the four states.
1160
+ * @param {object} props - space title, count, notes state and handlers.
1161
+ * @returns {React.ReactNode} the column.
1162
+ */
1163
+ function NotesColumn(props) {
1164
+ const t = props.t
1165
+ const state = props.state
1166
+ const payload = state.status === 'ready' && state.data !== null && typeof state.data === 'object' ? state.data : null
1167
+ const notes = payload !== null && Array.isArray(payload.notes) ? payload.notes : []
1168
+ const indexInfo =
1169
+ payload !== null && payload.index !== null && typeof payload.index === 'object' ? payload.index : null
1170
+ const header = h('div', { key: 'head', className: 'dm-notes-head' }, [
1171
+ h('span', { key: 'title', className: 'dm-notes-title' }, props.title),
1172
+ state.status === 'ready' ? h('span', { key: 'count', className: 'dm-notes-sub' }, t('notes.count', { count: notes.length })) : null,
1173
+ h(
1174
+ 'button',
1175
+ {
1176
+ key: 'refresh',
1177
+ type: 'button',
1178
+ className: 'dm-ghost',
1179
+ disabled: state.status === 'loading',
1180
+ onClick: () => props.onReload(),
1181
+ },
1182
+ t('notes.refresh'),
1183
+ ),
1184
+ ])
1185
+ let body
1186
+ if (state.status === 'loading') {
1187
+ body = h(Skeleton, { key: 'skel', rows: 4, label: t('state.loading') })
1188
+ } else if (state.status === 'error') {
1189
+ body = h(ErrorState, { key: 'err', t: t, message: describeError(state.error, t), onRetry: props.onReload })
1190
+ } else if (notes.length === 0 && indexInfo === null) {
1191
+ body = h('div', { key: 'empty', className: 'dm-state' }, [
1192
+ h('p', { key: 'title', className: 'dm-state-title' }, t('notes.empty')),
1193
+ h('p', { key: 'hint', className: 'dm-state-hint' }, t('notes.emptyHint')),
1194
+ ])
1195
+ } else {
1196
+ const indexRow =
1197
+ indexInfo === null
1198
+ ? null
1199
+ : h(
1200
+ 'button',
1201
+ {
1202
+ type: 'button',
1203
+ className: 'dm-note dm-index',
1204
+ 'data-note-file': 'MEMORY.md',
1205
+ onClick: () => props.onOpenIndex(),
1206
+ },
1207
+ [
1208
+ h('span', { key: 'name', className: 'dm-note-name' }, 'MEMORY.md'),
1209
+ h('span', { key: 'badges', className: 'dm-badges' }, [
1210
+ h(Badge, { key: 'index', label: t('index.badge'), tone: 'index' }),
1211
+ ]),
1212
+ h('span', { key: 'desc', className: 'dm-note-desc' }, t('index.subtitle', { count: Number(indexInfo.entries) || 0 })),
1213
+ h('span', { key: 'open', className: 'dm-note-meta' }, t('index.open')),
1214
+ ],
1215
+ )
1216
+ body = h(
1217
+ 'div',
1218
+ { key: 'list', className: 'dm-scroll', role: 'list' },
1219
+ [
1220
+ indexRow !== null ? h('div', { key: 'index-row', role: 'listitem' }, [indexRow]) : null,
1221
+ ...notes.map((note, index) =>
1222
+ h('div', { key: `${String(note.file ?? index)}`, role: 'listitem' }, [
1223
+ h(NoteRow, {
1224
+ note: note,
1225
+ t: t,
1226
+ locale: props.locale,
1227
+ onOpen: props.onOpen,
1228
+ }),
1229
+ ]),
1230
+ ),
1231
+ ],
1232
+ )
1233
+ }
1234
+ return h('section', { className: 'dm-notes' }, [header, body])
1235
+ }
1236
+
1237
+ /**
1238
+ * Right column, detail mode: breadcrumb over one note.
1239
+ * @param {object} props - the note resource, space and file names, handlers.
1240
+ * @returns {React.ReactNode} the column.
1241
+ */
1242
+ function DetailColumn(props) {
1243
+ const t = props.t
1244
+ const state = props.state
1245
+ const crumbs = h('div', { key: 'crumbs', className: 'dm-crumbs' }, [
1246
+ h(
1247
+ 'button',
1248
+ { key: 'back', type: 'button', className: 'dm-back', onClick: () => props.onBack() },
1249
+ `← ${t('detail.back')}`,
1250
+ ),
1251
+ h('span', { key: 's1', className: 'dm-crumb-sep', 'aria-hidden': 'true' }, '/'),
1252
+ h('span', { key: 'space', className: 'dm-crumb' }, props.spaceTitle),
1253
+ h('span', { key: 's2', className: 'dm-crumb-sep', 'aria-hidden': 'true' }, '/'),
1254
+ h('span', { key: 'file', className: 'dm-crumb', 'data-last': 'true' }, props.fileLabel),
1255
+ ])
1256
+ let body
1257
+ if (state.status === 'loading') {
1258
+ body = h(Skeleton, { key: 'skel', rows: 5, label: t('state.loading') })
1259
+ } else if (state.status === 'error') {
1260
+ const notFound = state.error !== null && state.error !== undefined && state.error.code === 'http' && state.error.status === '404'
1261
+ body = h(ErrorState, {
1262
+ key: 'err',
1263
+ t: t,
1264
+ message: notFound ? t('detail.notFound') : describeError(state.error, t),
1265
+ onRetry: props.onReload,
1266
+ })
1267
+ } else if (state.data !== null && typeof state.data === 'object' && state.data.kind === 'index') {
1268
+ const data = state.data
1269
+ body = h('div', { key: 'index', className: 'dm-scroll' }, [
1270
+ h('div', { className: 'dm-detail' }, [
1271
+ h('div', { key: 'head', className: 'dm-detail-head' }, [
1272
+ h('h1', { key: 'title', className: 'dm-detail-title' }, 'MEMORY.md'),
1273
+ h('p', { key: 'desc', className: 'dm-detail-desc' }, t('index.subtitle', { count: Number(data.entries) || 0 })),
1274
+ h('div', { key: 'badges', className: 'dm-badges' }, [
1275
+ h(Badge, { key: 'index', label: t('index.badge'), tone: 'index' }),
1276
+ ]),
1277
+ ]),
1278
+ h('div', { key: 'md', className: 'dm-md' }, renderMarkdown(String(data.markdown ?? '').replace(/<!--[\s\S]*?-->/g, ''))),
1279
+ h(
1280
+ 'p',
1281
+ { key: 'file', className: 'dm-file' },
1282
+ [
1283
+ h('span', { key: 'label', className: 'dm-file-label' }, t('detail.file')),
1284
+ `spaces/${data.space !== undefined ? String(data.space) : props.spaceKey}/MEMORY.md`,
1285
+ ],
1286
+ ),
1287
+ ]),
1288
+ ])
1289
+ } else if (state.status !== 'ready' || state.data === null || typeof state.data !== 'object') {
1290
+ body = h('div', { key: 'idle', className: 'dm-state' }, [
1291
+ h('p', { key: 'title', className: 'dm-state-title' }, t('notes.empty')),
1292
+ ])
1293
+ } else {
1294
+ const data = state.data
1295
+ const frontmatter = data.frontmatter !== null && typeof data.frontmatter === 'object' ? data.frontmatter : {}
1296
+ const name = typeof frontmatter.name === 'string' && frontmatter.name !== '' ? frontmatter.name : props.fileLabel
1297
+ const description = typeof frontmatter.description === 'string' ? frontmatter.description : ''
1298
+ const type = typeof frontmatter.type === 'string' ? frontmatter.type : ''
1299
+ const origin = typeof frontmatter.origin === 'string' ? frontmatter.origin : ''
1300
+ const updated = formatTime(frontmatter.updated)
1301
+ const created = formatTime(frontmatter.created)
1302
+ const time = updated !== '' ? updated : created
1303
+ const session = shortSession(frontmatter.source_session)
1304
+ const typeKey = `badge.type.${type}`
1305
+ const originKey = `badge.origin.${origin}`
1306
+ const typeLabel = translate(props.locale, typeKey) === typeKey ? type : t(typeKey)
1307
+ const originLabel = translate(props.locale, originKey) === originKey ? origin : t(originKey)
1308
+ const badges = []
1309
+ if (type !== '') badges.push(h(Badge, { key: 'type', label: typeLabel, tone: type }))
1310
+ if (origin !== '') badges.push(h(Badge, { key: 'origin', label: originLabel, tone: 'origin' }))
1311
+ if (time !== '') badges.push(h(Badge, { key: 'time', label: t('note.updatedAt', { time: time }) }))
1312
+ if (session !== '') badges.push(h(Badge, { key: 'session', label: t('note.session', { id: session }) }))
1313
+ if (Number.isFinite(Number(data.bytes)) && Number(data.bytes) > 0) {
1314
+ badges.push(h(Badge, { key: 'bytes', label: t('detail.bytes', { bytes: Number(data.bytes) }) }))
1315
+ }
1316
+ body = h('div', { key: 'body', className: 'dm-scroll' }, [
1317
+ h('div', { className: 'dm-detail' }, [
1318
+ h('div', { key: 'head', className: 'dm-detail-head' }, [
1319
+ h('h1', { key: 'title', className: 'dm-detail-title' }, name),
1320
+ description !== '' ? h('p', { key: 'desc', className: 'dm-detail-desc' }, description) : null,
1321
+ h('div', { key: 'badges', className: 'dm-badges' }, badges),
1322
+ ]),
1323
+ h('div', { key: 'md', className: 'dm-md' }, renderMarkdown(data.body)),
1324
+ h(
1325
+ 'p',
1326
+ { key: 'file', className: 'dm-file' },
1327
+ [
1328
+ h('span', { key: 'label', className: 'dm-file-label' }, t('detail.file')),
1329
+ `spaces/${data.space !== undefined ? String(data.space) : props.spaceKey}/${
1330
+ data.file !== undefined ? String(data.file) : props.fileLabel
1331
+ }`,
1332
+ ],
1333
+ ),
1334
+ ]),
1335
+ ])
1336
+ }
1337
+ return h('section', { className: 'dm-notes' }, [crumbs, body])
1338
+ }
1339
+
1340
+ /**
1341
+ * The whole page for one explicit state bundle. Pure, so tests can render
1342
+ * every state without a React runtime.
1343
+ * @param {object} props - env, copy, resource states, selection and handlers.
1344
+ * @returns {React.ReactNode} the page element.
1345
+ */
1346
+ function renderMemoryPage(props) {
1347
+ const t = props.t
1348
+ const spacesPayload =
1349
+ props.spacesState.status === 'ready' && props.spacesState.data !== null && typeof props.spacesState.data === 'object'
1350
+ ? props.spacesState.data
1351
+ : null
1352
+ const rows = sortSpaces(spacesPayload !== null ? spacesPayload.spaces : [])
1353
+ const selected = rows.find(row => row.key === props.spaceKey)
1354
+ const spaceTitle =
1355
+ selected !== undefined && typeof selected.title === 'string' && selected.title !== ''
1356
+ ? selected.title
1357
+ : props.spaceKey !== ''
1358
+ ? props.spaceKey
1359
+ : t('notes.title')
1360
+ const indexOpen = props.indexOpen === true
1361
+ const detailOpen = props.detailFile !== '' || indexOpen
1362
+ const fileLabel = indexOpen ? 'MEMORY.md' : props.detailFile
1363
+ // Before the space list settles there is no "no memory here" answer to
1364
+ // give: the right column mirrors the spaces request, then the notes request.
1365
+ const spacesLoading = props.spacesState.status === 'loading'
1366
+ const spacesFailed = props.spacesState.status === 'error'
1367
+ const notesState = spacesLoading
1368
+ ? { status: 'loading', data: null, error: null }
1369
+ : spacesFailed
1370
+ ? { status: 'error', data: null, error: props.spacesState.error }
1371
+ : props.notesState
1372
+ const content = detailOpen
1373
+ ? h(DetailColumn, {
1374
+ key: 'detail',
1375
+ t: t,
1376
+ locale: props.locale,
1377
+ state: indexOpen ? props.indexState : props.detailState,
1378
+ spaceKey: props.spaceKey,
1379
+ spaceTitle: spaceTitle,
1380
+ fileLabel: fileLabel,
1381
+ onBack: props.actions.back,
1382
+ onReload: indexOpen ? props.actions.reloadIndex : props.actions.reloadDetail,
1383
+ })
1384
+ : h(NotesColumn, {
1385
+ key: 'notes',
1386
+ t: t,
1387
+ locale: props.locale,
1388
+ state: notesState,
1389
+ title: spaceTitle,
1390
+ onOpen: props.actions.openNote,
1391
+ onOpenIndex: props.actions.openIndex,
1392
+ onReload: spacesFailed ? props.actions.reloadSpaces : props.actions.reloadNotes,
1393
+ })
1394
+ return h('div', { className: 'dm-page', 'data-dsh-memory-page': '' }, [
1395
+ h(StyleSheet, { key: 'style' }),
1396
+ h('div', { key: 'split', className: 'dm-split' }, [
1397
+ h(SpacesColumn, {
1398
+ key: 'spaces',
1399
+ t: t,
1400
+ rows: rows,
1401
+ spaceKey: props.spaceKey,
1402
+ status: props.spacesState.status,
1403
+ onSelect: props.actions.selectSpace,
1404
+ }),
1405
+ content,
1406
+ ]),
1407
+ ])
1408
+ }
1409
+
1410
+ // ------------------------------------------------------------- plugin --
1411
+
1412
+ /**
1413
+ * Page environment: the host locale service (when present) and the API.
1414
+ * @param {object} ctx - client plugin context.
1415
+ * @returns {{locale: object|null, api: object, report: Function}} the environment.
1416
+ */
1417
+ function createEnv(ctx) {
1418
+ const locale = ctx !== null && typeof ctx === 'object' && ctx.locale !== null && typeof ctx.locale === 'object' ? ctx.locale : null
1419
+ return {
1420
+ locale: locale,
1421
+ api: createApi(),
1422
+ report(message, error) {
1423
+ if (typeof console === 'undefined' || typeof console.warn !== 'function') return
1424
+ console.warn(`dsh-memory: ${message}`, error)
1425
+ },
1426
+ }
1427
+ }
1428
+
1429
+ /**
1430
+ * The tab body: hooks only, then the pure view.
1431
+ * @param {{env: object}} props - the page environment.
1432
+ * @returns {React.ReactNode} the page.
1433
+ */
1434
+ function MemoryTabBody(props) {
1435
+ const env = props.env
1436
+ const active = useLocale(env)
1437
+ const t = react.useMemo(() => translatorFor(active), [active])
1438
+
1439
+ const [spacesState, reloadSpaces] = useResource(signal => env.api.spaces(signal), [])
1440
+ const [spaceKey, setSpaceKey] = react.useState('')
1441
+ react.useEffect(() => {
1442
+ if (spacesState.status !== 'ready' || spacesState.data === null) return
1443
+ const rows = Array.isArray(spacesState.data.spaces) ? spacesState.data.spaces : []
1444
+ setSpaceKey(previous => {
1445
+ const stillThere = rows.some(row => row !== null && typeof row === 'object' && row.key === previous && row.enabled !== false)
1446
+ return stillThere ? previous : pickInitialSpace(rows, spacesState.data.current)
1447
+ })
1448
+ }, [spacesState])
1449
+
1450
+ const notesLoader = react.useMemo(
1451
+ () => (spaceKey === '' ? null : signal => env.api.notes(spaceKey, signal)),
1452
+ [env, spaceKey],
1453
+ )
1454
+ const [notesState, reloadNotes] = useResource(notesLoader, [spaceKey])
1455
+
1456
+ const [detailFile, setDetailFile] = react.useState('')
1457
+ const [indexOpen, setIndexOpen] = react.useState(false)
1458
+ react.useEffect(() => {
1459
+ setDetailFile('')
1460
+ setIndexOpen(false)
1461
+ }, [spaceKey])
1462
+ const detailLoader = react.useMemo(
1463
+ () => (spaceKey === '' || detailFile === '' || indexOpen ? null : signal => env.api.note(spaceKey, detailFile, signal)),
1464
+ [env, spaceKey, detailFile, indexOpen],
1465
+ )
1466
+ const [detailState, reloadDetail] = useResource(detailLoader, [spaceKey, detailFile, indexOpen])
1467
+ const indexLoader = react.useMemo(
1468
+ () => (spaceKey === '' || indexOpen !== true ? null : signal => env.api.index(spaceKey, signal)),
1469
+ [env, spaceKey, indexOpen],
1470
+ )
1471
+ const [indexState, reloadIndex] = useResource(indexLoader, [spaceKey, indexOpen])
1472
+
1473
+ const actions = {
1474
+ selectSpace(key) {
1475
+ // Close an open note in the same batch: the old file does not belong
1476
+ // to the space being opened, and fetching it there would 404.
1477
+ setDetailFile('')
1478
+ setIndexOpen(false)
1479
+ setSpaceKey(key)
1480
+ },
1481
+ openNote(file) {
1482
+ setIndexOpen(false)
1483
+ setDetailFile(file)
1484
+ },
1485
+ openIndex() {
1486
+ setDetailFile('')
1487
+ setIndexOpen(true)
1488
+ },
1489
+ back() {
1490
+ setDetailFile('')
1491
+ setIndexOpen(false)
1492
+ },
1493
+ reloadSpaces,
1494
+ reloadNotes,
1495
+ reloadDetail,
1496
+ reloadIndex,
1497
+ }
1498
+
1499
+ return renderMemoryPage({
1500
+ t: t,
1501
+ locale: active,
1502
+ spacesState: spacesState,
1503
+ notesState: notesState,
1504
+ detailState: detailState,
1505
+ indexState: indexState,
1506
+ indexOpen: indexOpen,
1507
+ spaceKey: spaceKey,
1508
+ detailFile: detailFile,
1509
+ actions: actions,
1510
+ })
1511
+ }
1512
+
1513
+ /**
1514
+ * Wrap the body so it closes over one environment.
1515
+ * @param {object} env - page environment.
1516
+ * @returns {Function} the slot component.
1517
+ */
1518
+ function createBody(env) {
1519
+ return function DshMemoryTabBody() {
1520
+ return h(MemoryTabBody, { env: env })
1521
+ }
1522
+ }
1523
+
1524
+ /**
1525
+ * The tab type: a page type, opened from the guide by its kind.
1526
+ * @param {object} env - page environment.
1527
+ * @returns {object} the sidebarRightTabs definition.
1528
+ */
1529
+ function createDefinition(env) {
1530
+ const copy = key => () => translate(readLocale(env), key)
1531
+ return {
1532
+ id: NS,
1533
+ kind: 'memory',
1534
+ title: copy('tab.title'),
1535
+ guide: [
1536
+ {
1537
+ id: 'memory',
1538
+ order: 45,
1539
+ title: copy('guide.title'),
1540
+ description: copy('guide.description'),
1541
+ },
1542
+ ],
1543
+ }
1544
+ }
1545
+
1546
+ return {
1547
+ name: 'dsh-memory-client',
1548
+ // `sidebarRightTabs` must be declared: without it the service is absent at
1549
+ // apply time and the tab type silently never registers. The locale service
1550
+ // stays optional (Chinese fallback lives in the client).
1551
+ inject: ['slots', 'sidebarRightTabs', 'locale'],
1552
+ apply(ctx) {
1553
+ if (ctx === null || typeof ctx !== 'object' || typeof ctx.effect !== 'function') return
1554
+ const env = createEnv(ctx)
1555
+
1556
+ // Static declarations of the page: the tab type and the copy its thunks read.
1557
+ ctx.effect(() => {
1558
+ const disposers = []
1559
+ if (ctx.locale !== null && typeof ctx.locale === 'object' && typeof ctx.locale.register === 'function') {
1560
+ try {
1561
+ disposers.push(ctx.locale.register(NS, DICTS))
1562
+ } catch (error) {
1563
+ env.report('copy dictionary already registered, keeping the previous one', error)
1564
+ }
1565
+ }
1566
+ if (
1567
+ ctx.sidebarRightTabs !== null &&
1568
+ typeof ctx.sidebarRightTabs === 'object' &&
1569
+ typeof ctx.sidebarRightTabs.register === 'function'
1570
+ ) {
1571
+ disposers.push(ctx.sidebarRightTabs.register(createDefinition(env)))
1572
+ }
1573
+ return () => {
1574
+ for (const dispose of disposers.reverse()) {
1575
+ if (typeof dispose === 'function') dispose()
1576
+ }
1577
+ }
1578
+ }, 'dsh-memory: tab type')
1579
+
1580
+ // The page body itself, inside the right pane's tab seat.
1581
+ ctx.effect(() => {
1582
+ if (ctx.slots === null || typeof ctx.slots !== 'object' || typeof ctx.slots.inject !== 'function') {
1583
+ return () => {}
1584
+ }
1585
+ return ctx.slots.inject('sidebar.right.pane.tab', () =>
1586
+ ctx.slots.register({ name: 'sidebar.right.pane.tab', key: NS }, createBody(env)),
1587
+ )
1588
+ }, 'dsh-memory: tab body')
1589
+ },
1590
+ // Test surface only: the page's pure helpers, view and copy.
1591
+ __internals: {
1592
+ view: renderMemoryPage,
1593
+ parseMarkdown: parseMarkdown,
1594
+ parseInline: parseInline,
1595
+ translate: translate,
1596
+ formatTime: formatTime,
1597
+ shortSession: shortSession,
1598
+ sortSpaces: sortSpaces,
1599
+ pickInitialSpace: pickInitialSpace,
1600
+ createDefinition: createDefinition,
1601
+ DICTS: DICTS,
1602
+ NS: NS,
1603
+ },
1604
+ }
1605
+ },
1606
+ })
1607
+ })()