@soffits/dsh-card-board 0.0.0-stage → 0.1.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,954 @@
1
+ /*
2
+ * Browser half of dsh-card-board: the Boards entry in the sidebar and its
3
+ * page in the main column.
4
+ *
5
+ * Plain JavaScript in DSH's Client module format (no build step); React
6
+ * comes from the page's module table. The page asks the Host for the boards
7
+ * this person may see, shows one at a time, and polls the open board with
8
+ * If-None-Match while the tab is visible. Charts are small hand-drawn SVGs
9
+ * sized to their card, coloured only through DSH's theme tokens, so light and
10
+ * dark both follow the app.
11
+ */
12
+ window.__ModuleLoader__.load({
13
+ id: '@soffits/dsh-card-board',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const h = React.createElement
17
+ const { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallback } = React
18
+
19
+ const NS = 'dsh-card-board'
20
+ const PANEL = 'dsh-card-board'
21
+ const STYLE_ID = 'dsh-card-board-style'
22
+ const STORE_KEY = 'dsh-card-board:board'
23
+ const api = path => new URL(`api/card-board/${path}`, document.baseURI).href
24
+
25
+ const en = {
26
+ panel: 'Boards',
27
+ title: 'Boards',
28
+ updated: 'Updated {time}',
29
+ refreshFailed: 'Couldn’t refresh; trying again',
30
+ loading: 'Loading…',
31
+ emptyTitle: 'No boards yet.',
32
+ emptyHint: 'A board shows up here once a script writes its board.json into the data folder.',
33
+ noProvider: 'Boards need a sign-in plugin that says who is asking, and none is running.',
34
+ noCards: 'This board has no cards yet.',
35
+ cardError: 'This card can’t be shown',
36
+ boardProblems: 'board.json has problems:',
37
+ stale: 'stale · {age}',
38
+ open: 'Open',
39
+ listEmpty: 'Nothing here.',
40
+ minutes: '{n} min',
41
+ hours: '{n} h',
42
+ days: '{n} d',
43
+ 'time.locale': 'en-US',
44
+ }
45
+ const zh = {
46
+ panel: '面板',
47
+ title: '面板',
48
+ updated: '{time} 更新',
49
+ refreshFailed: '刷新失败,稍后重试',
50
+ loading: '加载中…',
51
+ emptyTitle: '还没有面板。',
52
+ emptyHint: '脚本把 board.json 写进数据目录后,面板就会出现在这里。',
53
+ noProvider: '面板需要一个能确认访问者身份的登录插件,但现在没有运行。',
54
+ noCards: '这个面板还没有卡片。',
55
+ cardError: '这张卡片无法显示',
56
+ boardProblems: 'board.json 有问题:',
57
+ stale: '已过时 · {age}',
58
+ open: '打开',
59
+ listEmpty: '暂无',
60
+ minutes: '{n} 分钟',
61
+ hours: '{n} 小时',
62
+ days: '{n} 天',
63
+ 'time.locale': 'zh-CN',
64
+ }
65
+
66
+ /** The client context, for the Web UI services the actions reach (set in apply). */
67
+ let clientCtx = null
68
+ /** The shared action buttons (client.actions.js), loaded with the page. */
69
+ let actionsModule
70
+ const loadActions = () => {
71
+ actionsModule ??= require.async('./client.actions.js').catch(error => {
72
+ actionsModule = undefined
73
+ throw error
74
+ })
75
+ return actionsModule
76
+ }
77
+
78
+ const fill = (text, params) => String(text).replace(/\{(\w+)\}/g, (match, key) => (key in params ? String(params[key]) : match))
79
+
80
+ // ---- numbers, dates, tones -------------------------------------------------
81
+
82
+ const TONES = { ok: 'var(--cb-ok)', warn: 'var(--cb-warn)', bad: 'var(--cb-bad)', muted: 'var(--cb-muted)', accent: 'var(--cb-accent)' }
83
+ const PALETTE = ['var(--cb-accent)', 'var(--cb-ok)', 'var(--cb-warn)', 'var(--cb-violet)', 'var(--cb-bad)', 'var(--cb-muted)']
84
+ const toneColor = (tone, index = 0) => TONES[tone] ?? PALETTE[index % PALETTE.length]
85
+
86
+ function formatNumber(value, locale, digits) {
87
+ if (typeof value !== 'number') return String(value)
88
+ const abs = Math.abs(value)
89
+ const max = digits ?? (abs >= 1000 ? 0 : abs >= 100 ? 1 : 2)
90
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: max }).format(value)
91
+ }
92
+
93
+ /** Short axis numbers: 18,240 → 18.2k. */
94
+ function formatAxis(value, locale) {
95
+ const abs = Math.abs(value)
96
+ if (abs >= 1e6) return `${formatNumber(value / 1e6, locale, 1)}M`
97
+ if (abs >= 1e4) return `${formatNumber(value / 1e3, locale, abs >= 1e5 ? 0 : 1)}k`
98
+ return formatNumber(value, locale, abs >= 100 ? 0 : 1)
99
+ }
100
+
101
+ const DAY_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/
102
+ /** A date string as a time: a bare day is local midnight, so it labels as that day everywhere. */
103
+ function toTime(value) {
104
+ if (typeof value !== 'string') return NaN
105
+ const day = DAY_ONLY.exec(value)
106
+ if (day) return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).getTime()
107
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) ? Date.parse(value) : NaN
108
+ }
109
+
110
+ function formatDay(time, locale, spanDays) {
111
+ const date = new Date(time)
112
+ if (spanDays > 120) return date.toLocaleDateString(locale, { month: 'short' })
113
+ return date.toLocaleDateString(locale, { month: 'numeric', day: 'numeric' })
114
+ }
115
+
116
+ function formatAge(seconds, t) {
117
+ if (seconds < 3600) return fill(t('minutes'), { n: Math.max(1, Math.round(seconds / 60)) })
118
+ if (seconds < 86400 * 2) return fill(t('hours'), { n: Math.round(seconds / 3600) })
119
+ return fill(t('days'), { n: Math.round(seconds / 86400) })
120
+ }
121
+
122
+ function formatUpdated(time, locale) {
123
+ const date = new Date(time)
124
+ const today = new Date()
125
+ const sameDay = date.toDateString() === today.toDateString()
126
+ return sameDay
127
+ ? date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' })
128
+ : date.toLocaleString(locale, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
129
+ }
130
+
131
+ /** About this many pixels per character of 11px label text. */
132
+ const textWidth = text => String(text).length * 6.4
133
+
134
+ /** Round tick values covering [min, max], about `count` of them. */
135
+ function niceTicks(min, max, count) {
136
+ if (min === max) return [min]
137
+ const raw = (max - min) / Math.max(1, count)
138
+ const power = 10 ** Math.floor(Math.log10(raw))
139
+ const step = [1, 2, 2.5, 5, 10].map(m => m * power).find(s => s >= raw) ?? raw
140
+ const ticks = []
141
+ for (let v = Math.ceil(min / step) * step; v <= max + step * 1e-9; v += step) ticks.push(Number(v.toFixed(10)))
142
+ return ticks
143
+ }
144
+
145
+ /** Evenly spaced indexes, at most `count`, always including the last. */
146
+ function spread(length, count) {
147
+ if (length <= count) return Array.from({ length }, (_, i) => i)
148
+ const step = (length - 1) / Math.max(1, count - 1)
149
+ return Array.from({ length: count }, (_, i) => Math.round(i * step))
150
+ }
151
+
152
+ function useWidth() {
153
+ const ref = useRef(null)
154
+ const [width, setWidth] = useState(0)
155
+ useLayoutEffect(() => {
156
+ const element = ref.current
157
+ if (!element) return undefined
158
+ setWidth(Math.floor(element.clientWidth))
159
+ const observer = new ResizeObserver(([entry]) => setWidth(Math.floor(entry.contentRect.width)))
160
+ observer.observe(element)
161
+ return () => observer.disconnect()
162
+ }, [])
163
+ return [ref, width]
164
+ }
165
+
166
+ // ---- pieces shared by cards ------------------------------------------------
167
+
168
+ function Chip({ text, tone }) {
169
+ return h('span', { className: 'cb-chip', 'data-tone': tone ?? 'muted' }, text)
170
+ }
171
+
172
+ function Legend({ items, locale }) {
173
+ return h('ul', { className: 'cb-legend' }, items.map((item, i) =>
174
+ h('li', { key: i },
175
+ h('i', { style: { background: item.color } }),
176
+ h('span', null, item.label),
177
+ item.value !== undefined && h('b', null, formatNumber(item.value, locale)))))
178
+ }
179
+
180
+ function StatBlock({ data, locale, compact }) {
181
+ return h('div', { className: `cb-stats${compact ? ' cb-statsCompact' : ''}` }, data.items.map((item, i) =>
182
+ h('div', { key: i, className: 'cb-stat' },
183
+ !compact && h('div', { className: 'cb-statLabel' }, item.label),
184
+ h('div', { className: 'cb-statValue', style: item.tone ? { color: toneColor(item.tone) } : undefined },
185
+ h('span', null, formatNumber(item.value, locale)),
186
+ item.unit && h('small', null, item.unit),
187
+ item.delta && h('em', { className: 'cb-delta', style: { color: toneColor(item.delta.tone ?? 'muted') } },
188
+ `${item.delta.value > 0 ? '▲' : item.delta.value < 0 ? '▼' : '•'} ${formatNumber(Math.abs(item.delta.value), locale)}${item.delta.unit ? ` ${item.delta.unit}` : ''}`)),
189
+ (compact ? [item.label, item.sub].filter(Boolean).join(' · ') : item.sub) &&
190
+ h('div', { className: 'cb-statSub' }, compact ? [item.label, item.sub].filter(Boolean).join(' · ') : item.sub))))
191
+ }
192
+
193
+ // ---- line ----------------------------------------------------------------
194
+
195
+ function LineChart({ data, locale, height }) {
196
+ const [ref, width] = useWidth()
197
+ const model = useMemo(() => {
198
+ const allX = data.series.flatMap(s => s.points.map(p => p.x))
199
+ const times = allX.map(toTime)
200
+ const timeAxis = times.every(Number.isFinite)
201
+ const numberAxis = !timeAxis && allX.every(x => typeof x === 'number')
202
+ const categories = timeAxis || numberAxis ? [] : [...new Set(allX.map(String))]
203
+ const xValue = x => (timeAxis ? toTime(x) : numberAxis ? x : categories.indexOf(String(x)))
204
+ const xs = allX.map(xValue)
205
+ let ys = data.series.flatMap(s => s.points.map(p => p.y)).filter(y => typeof y === 'number')
206
+ if (data.goal?.y !== undefined) ys = ys.concat(data.goal.y)
207
+ if (data.goal?.points) ys = ys.concat(data.goal.points.map(p => p.y).filter(y => typeof y === 'number'))
208
+ let yMin = Math.min(...ys)
209
+ let yMax = Math.max(...ys)
210
+ const pad = (yMax - yMin || Math.abs(yMax) || 1) * 0.08
211
+ yMin -= pad
212
+ yMax += pad
213
+ return { timeAxis, categories, xValue, xMin: Math.min(...xs), xMax: Math.max(...xs), yMin, yMax }
214
+ }, [data])
215
+
216
+ const ticks = niceTicks(model.yMin, model.yMax, height > 160 ? 4 : 3).filter(v => v >= model.yMin && v <= model.yMax)
217
+ const left = Math.max(...ticks.map(v => textWidth(formatAxis(v, locale)))) + 10
218
+ const right = 12
219
+ const top = 10
220
+ const bottom = 20
221
+ const plotW = Math.max(10, width - left - right)
222
+ const plotH = Math.max(10, height - top - bottom)
223
+ const sx = x => left + (model.xMax === model.xMin ? plotW / 2 : ((model.xValue(x) - model.xMin) / (model.xMax - model.xMin)) * plotW)
224
+ const sy = y => top + (1 - (y - model.yMin) / (model.yMax - model.yMin || 1)) * plotH
225
+ const spanDays = model.timeAxis ? (model.xMax - model.xMin) / 86400000 : 0
226
+ const xLabel = x => (model.timeAxis ? formatDay(toTime(x), locale, spanDays) : typeof x === 'number' ? formatNumber(x, locale) : String(x))
227
+
228
+ const longest = data.series.reduce((best, s) => (s.points.length > best.points.length ? s : best), data.series[0])
229
+ const labelCount = Math.max(2, Math.floor(plotW / 44))
230
+ const xTicks = spread(longest.points.length, labelCount).map(i => longest.points[i].x)
231
+
232
+ const path = points => {
233
+ let d = ''
234
+ let pen = false
235
+ for (const p of points) {
236
+ if (typeof p.y !== 'number') { pen = false; continue }
237
+ d += `${pen ? 'L' : 'M'}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`
238
+ pen = true
239
+ }
240
+ return d
241
+ }
242
+ const gradientId = useMemo(() => `cb-g-${Math.random().toString(36).slice(2, 9)}`, [])
243
+
244
+ return h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
245
+ h('defs', null, data.series.map((s, i) => h('linearGradient', { key: i, id: `${gradientId}-${i}`, x1: 0, y1: 0, x2: 0, y2: 1 },
246
+ h('stop', { offset: '0%', stopColor: toneColor(s.tone, i), stopOpacity: 0.22 }),
247
+ h('stop', { offset: '100%', stopColor: toneColor(s.tone, i), stopOpacity: 0 })))),
248
+ ticks.map(v => h('g', { key: v },
249
+ h('line', { x1: left, x2: left + plotW, y1: sy(v), y2: sy(v), className: 'cb-rule' }),
250
+ h('text', { x: left - 8, y: sy(v), className: 'cb-axis', textAnchor: 'end', dominantBaseline: 'middle' }, formatAxis(v, locale)))),
251
+ xTicks.map((x, i) => h('text', { key: i, x: sx(x), y: height - 4, className: 'cb-axis', textAnchor: i === 0 && xTicks.length > 1 ? 'start' : i === xTicks.length - 1 && xTicks.length > 1 ? 'end' : 'middle' }, xLabel(x))),
252
+ (data.markers ?? []).map((m, i) => h('g', { key: `m${i}` },
253
+ h('line', { x1: sx(m.x), x2: sx(m.x), y1: top, y2: top + plotH, className: 'cb-marker' }),
254
+ h('text', { x: sx(m.x) + 4, y: top + 8, className: 'cb-markerLabel' }, m.label))),
255
+ data.goal && (data.goal.points
256
+ ? h('path', { d: path(data.goal.points), className: 'cb-goal' })
257
+ : h('line', { x1: left, x2: left + plotW, y1: sy(data.goal.y), y2: sy(data.goal.y), className: 'cb-goal' })),
258
+ data.goal?.label && (() => {
259
+ const end = data.goal.points ? data.goal.points[data.goal.points.length - 1] : { x: null, y: data.goal.y }
260
+ const x = end.x === null ? left + plotW : sx(end.x)
261
+ return h('text', { x: Math.min(x, left + plotW), y: sy(end.y) - 5, className: 'cb-goalLabel', textAnchor: 'end' }, data.goal.label)
262
+ })(),
263
+ data.series.map((s, i) => {
264
+ const color = toneColor(s.tone, i)
265
+ const line = path(s.points)
266
+ const valid = s.points.filter(p => typeof p.y === 'number')
267
+ const last = valid[valid.length - 1]
268
+ const area = data.area && valid.length > 1
269
+ ? `${line}L${sx(last.x).toFixed(1)},${(top + plotH).toFixed(1)}L${sx(valid[0].x).toFixed(1)},${(top + plotH).toFixed(1)}Z`
270
+ : null
271
+ return h('g', { key: `s${i}` },
272
+ area && h('path', { d: area, fill: `url(#${gradientId}-${i})`, stroke: 'none' }),
273
+ h('path', { d: line, fill: 'none', stroke: color, strokeWidth: 2, strokeLinejoin: 'round', strokeLinecap: 'round' }),
274
+ valid.length <= 16 && valid.map((p, j) => h('circle', { key: j, cx: sx(p.x), cy: sy(p.y), r: 2.6, fill: 'var(--cb-card)', stroke: color, strokeWidth: 1.6 },
275
+ h('title', null, `${s.name ? `${s.name} · ` : ''}${xLabel(p.x)}: ${formatNumber(p.y, locale)}${data.unit ? ` ${data.unit}` : ''}`))),
276
+ valid.length > 16 && last && h('circle', { cx: sx(last.x), cy: sy(last.y), r: 3, fill: color }))
277
+ })))
278
+ }
279
+
280
+ // ---- bar -----------------------------------------------------------------
281
+
282
+ function BarChart({ data, locale, height }) {
283
+ const [ref, width] = useWidth()
284
+ const keys = useMemo(() => {
285
+ const seen = []
286
+ for (const bar of data.bars) for (const key of Object.keys(bar.values ?? {})) if (!seen.includes(key)) seen.push(key)
287
+ return seen
288
+ }, [data])
289
+ const multi = keys.length > 0
290
+ const stacked = multi && data.stacked === true
291
+ const totals = data.bars.map(bar => (multi ? keys.reduce((sum, key) => sum + Math.max(0, bar.values?.[key] ?? 0), 0) : Math.max(0, bar.value ?? 0)))
292
+ const peaks = data.bars.map((bar, i) => (multi && !stacked ? Math.max(0, ...keys.map(key => bar.values?.[key] ?? 0)) : totals[i]))
293
+ const max = Math.max(1e-9, ...peaks, data.goal?.y ?? 0)
294
+ const showValues = data.bars.length <= 14
295
+ const top = showValues ? 16 : 6
296
+ const bottom = 20
297
+ const plotH = Math.max(10, height - top - bottom)
298
+ const slot = width / data.bars.length
299
+ const barW = Math.max(2, Math.min(44, slot * 0.62))
300
+ const sy = v => top + plotH - (v / max) * plotH
301
+ const labelEvery = Math.max(1, Math.ceil(data.bars.length / Math.max(1, Math.floor(width / 40))))
302
+ const label = x => {
303
+ const time = toTime(x)
304
+ return Number.isFinite(time) ? formatDay(time, locale, 0) : String(x)
305
+ }
306
+ return h('div', null,
307
+ h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
308
+ h('line', { x1: 0, x2: width, y1: top + plotH + 0.5, y2: top + plotH + 0.5, className: 'cb-rule' }),
309
+ data.goal && h('line', { x1: 0, x2: width, y1: sy(data.goal.y), y2: sy(data.goal.y), className: 'cb-goal' }),
310
+ data.goal?.label && h('text', { x: width, y: sy(data.goal.y) - 4, className: 'cb-goalLabel', textAnchor: 'end' }, data.goal.label),
311
+ data.bars.map((bar, i) => {
312
+ const cx = slot * i + slot / 2
313
+ const tip = multi
314
+ ? `${label(bar.x)}: ${keys.filter(k => bar.values?.[k] !== undefined).map(k => `${k} ${formatNumber(bar.values[k], locale)}`).join(', ')}`
315
+ : `${label(bar.x)}: ${formatNumber(bar.value, locale)}${data.unit ? ` ${data.unit}` : ''}`
316
+ let parts
317
+ if (!multi) parts = [{ y0: 0, y1: Math.max(0, bar.value), color: toneColor(undefined, 1), x: cx - barW / 2, w: barW }]
318
+ else if (stacked) {
319
+ let base = 0
320
+ parts = keys.map((key, k) => {
321
+ const v = Math.max(0, bar.values?.[key] ?? 0)
322
+ const part = { y0: base, y1: base + v, color: toneColor(undefined, k), x: cx - barW / 2, w: barW }
323
+ base += v
324
+ return part
325
+ })
326
+ } else {
327
+ const each = barW / keys.length
328
+ parts = keys.map((key, k) => ({ y0: 0, y1: Math.max(0, bar.values?.[key] ?? 0), color: toneColor(undefined, k), x: cx - barW / 2 + k * each, w: Math.max(1, each - 1) }))
329
+ }
330
+ return h('g', { key: i },
331
+ h('title', null, tip),
332
+ parts.filter(p => p.y1 > p.y0).map((p, k) => h('rect', {
333
+ key: k, x: p.x, width: p.w, y: sy(p.y1), height: Math.max(0.5, sy(p.y0) - sy(p.y1)),
334
+ rx: Math.min(4, p.w / 3), fill: p.color, fillOpacity: multi ? 0.85 : 0.55,
335
+ })),
336
+ showValues && h('text', { x: cx, y: sy(peaks[i]) - 4, className: 'cb-barValue', textAnchor: 'middle' }, formatNumber(multi && !stacked ? peaks[i] : totals[i], locale, 1)),
337
+ i % labelEvery === 0 && h('text', { x: cx, y: height - 4, className: 'cb-axis', textAnchor: 'middle' }, label(bar.x)))
338
+ }))),
339
+ multi && h(Legend, { items: keys.map((key, k) => ({ label: key, color: toneColor(undefined, k) })), locale }))
340
+ }
341
+
342
+ // ---- donut ---------------------------------------------------------------
343
+
344
+ function arc(cx, cy, r, start, end) {
345
+ const large = end - start > Math.PI ? 1 : 0
346
+ const x0 = cx + r * Math.sin(start)
347
+ const y0 = cy - r * Math.cos(start)
348
+ const x1 = cx + r * Math.sin(end)
349
+ const y1 = cy - r * Math.cos(end)
350
+ return `M${x0.toFixed(2)},${y0.toFixed(2)}A${r},${r} 0 ${large} 1 ${x1.toFixed(2)},${y1.toFixed(2)}`
351
+ }
352
+
353
+ function Donut({ data, locale, height }) {
354
+ const [ref, width] = useWidth()
355
+ const total = data.segments.reduce((sum, s) => sum + s.value, 0)
356
+ const narrow = width < 340
357
+ const size = Math.max(90, Math.min(narrow ? 150 : 170, height - 8, narrow ? width * 0.6 : width * 0.42))
358
+ const ring = size * 0.13
359
+ const r = size / 2 - ring / 2
360
+ let angle = 0
361
+ const gap = data.segments.filter(s => s.value > 0).length > 1 ? 0.025 : 0
362
+ const segments = data.segments.map((s, i) => {
363
+ const sweep = total > 0 ? (s.value / total) * Math.PI * 2 : 0
364
+ const seg = { ...s, color: toneColor(s.tone, i), start: angle + gap / 2, end: angle + sweep - gap / 2 }
365
+ angle += sweep
366
+ return seg
367
+ })
368
+ return h('div', { ref, className: `cb-donut${narrow ? ' cb-donutNarrow' : ''}` },
369
+ width > 0 && h('div', { className: 'cb-donutRing', style: { width: size, height: size } },
370
+ h('svg', { width: size, height: size, role: 'img' },
371
+ h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-track)', strokeWidth: ring }),
372
+ segments.filter(s => s.end > s.start).map((s, i) => h('path', { key: i, d: arc(size / 2, size / 2, r, s.start, s.end), fill: 'none', stroke: s.color, strokeWidth: ring },
373
+ h('title', null, `${s.label}: ${formatNumber(s.value, locale)}${data.unit ? ` ${data.unit}` : ''}`)))),
374
+ data.centre && h('div', { className: 'cb-donutCentre' },
375
+ h('strong', null, data.centre.text),
376
+ data.centre.sub && h('span', null, data.centre.sub))),
377
+ h('table', { className: 'cb-donutTable' }, h('tbody', null, segments.map((s, i) => h('tr', { key: i },
378
+ h('td', null, h('i', { style: { background: s.color } })),
379
+ h('td', { className: 'cb-donutLabel' }, s.label),
380
+ h('td', { className: 'cb-num' }, formatNumber(s.value, locale)),
381
+ h('td', { className: 'cb-num cb-dim' }, total > 0 ? `${Math.round((s.value / total) * 100)}%` : '–'))))))
382
+ }
383
+
384
+ // ---- list ----------------------------------------------------------------
385
+
386
+ function CheckGlyph({ checked }) {
387
+ return h('svg', { className: 'cb-check', 'data-checked': checked ? 'true' : 'false', width: 18, height: 18, viewBox: '0 0 18 18', 'aria-hidden': true },
388
+ h('rect', { x: 1, y: 1, width: 16, height: 16, rx: 4.5 }),
389
+ checked && h('path', { d: 'M5 9.4l2.6 2.5L13 6.4' }))
390
+ }
391
+
392
+ function ProgressRing({ progress, size }) {
393
+ const ring = Math.max(6, size * 0.12)
394
+ const r = size / 2 - ring / 2
395
+ const share = progress.total > 0 ? Math.min(1, progress.done / progress.total) : 0
396
+ return h('div', { className: 'cb-donutRing', style: { width: size, height: size } },
397
+ h('svg', { width: size, height: size, role: 'img', 'aria-label': `${progress.done}/${progress.total}` },
398
+ h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-track)', strokeWidth: ring }),
399
+ share >= 1
400
+ ? h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-accent)', strokeWidth: ring })
401
+ : share > 0 && h('path', { d: arc(size / 2, size / 2, r, 0, share * Math.PI * 2), fill: 'none', stroke: 'var(--cb-accent)', strokeWidth: ring, strokeLinecap: 'round' })),
402
+ h('div', { className: 'cb-donutCentre' },
403
+ h('strong', { style: { fontSize: Math.round(size * 0.19) } }, `${progress.done}/${progress.total}`),
404
+ progress.label && size >= 90 && h('span', null, progress.label)))
405
+ }
406
+
407
+ function ListCard({ data, locale, t, rowActions }) {
408
+ const [ref, width] = useWidth()
409
+ const checkable = data.rows.some(row => 'checked' in row)
410
+ const rows = data.rows.length === 0
411
+ ? h('p', { className: 'cb-muted' }, data.empty ?? t('listEmpty'))
412
+ : h('ul', { className: 'cb-list' }, data.rows.map((row, i) =>
413
+ h('li', { key: i, className: row.checked ? 'cb-done' : undefined },
414
+ checkable && h('span', { className: 'cb-checkBox', role: 'img', 'aria-label': row.checked ? '✓' : '○' }, h(CheckGlyph, { checked: row.checked === true })),
415
+ h('div', { className: 'cb-listText' },
416
+ h('div', { className: 'cb-listTitle' }, row.title),
417
+ row.sub && h('div', { className: 'cb-listSub' }, row.sub)),
418
+ row.date && h('span', { className: 'cb-listDate' }, formatDay(toTime(row.date), locale, 0)),
419
+ row.chip && h(Chip, row.chip),
420
+ rowActions && row.actions && rowActions(i, row.actions, listRowLine(row)))))
421
+ if (!data.progress) return rows
422
+ // Beside the rows when there is room for both, else a small ring with its count above them.
423
+ const wide = width >= 460
424
+ return h('div', { ref, className: `cb-listWrap${wide ? '' : ' cb-listWrapNarrow'}` },
425
+ width > 0 && (wide
426
+ ? h(ProgressRing, { progress: data.progress, size: Math.min(140, Math.round(width * 0.28)) })
427
+ : h('div', { className: 'cb-progressLine' },
428
+ h(ProgressRing, { progress: { ...data.progress, label: undefined }, size: 40 }),
429
+ data.progress.label && h('span', null, data.progress.label))),
430
+ h('div', { className: 'cb-listMain' }, rows))
431
+ }
432
+
433
+ // ---- timeline ------------------------------------------------------------
434
+
435
+ const KIND_TONE = { due: 'warn', health: 'ok', event: 'accent', home: 'muted', money: 'ok', travel: 'accent' }
436
+
437
+ function PlaneGlyph({ x, y, color }) {
438
+ return h('path', {
439
+ transform: `translate(${x - 7},${y - 7}) scale(0.58)`,
440
+ d: 'M21 16v-2l-8-5V3.5a1.5 1.5 0 0 0-3 0V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z',
441
+ fill: color,
442
+ })
443
+ }
444
+
445
+ function Timeline({ data, locale, t }) {
446
+ const [ref, width] = useWidth()
447
+ const from = toTime(data.from)
448
+ const to = toTime(data.to)
449
+ const days = Math.max(1, Math.round((to - from) / 86400000))
450
+ const pad = 14
451
+ const plotW = Math.max(10, width - pad * 2)
452
+ const sx = time => pad + ((time - from) / (to - from)) * plotW
453
+ const now = Date.now()
454
+ const dayEvery = Math.max(1, Math.ceil(days / Math.max(1, Math.floor(plotW / 44))))
455
+ const ticks = []
456
+ for (let i = 0; i <= days; i += dayEvery) ticks.push(from + i * 86400000)
457
+
458
+ // Points get label rows so neighbours don't overlap.
459
+ const points = (data.points ?? []).map(p => ({ ...p, time: toTime(p.date) })).filter(p => p.time >= from && p.time <= to).sort((a, b) => a.time - b.time)
460
+ const rowEnds = []
461
+ const placed = points.map(p => {
462
+ const half = Math.min(90, textWidth(p.label)) / 2 + 4
463
+ const x = sx(p.time)
464
+ let row = rowEnds.findIndex(end => x - half > end)
465
+ if (row === -1) { row = rowEnds.length; rowEnds.push(0) }
466
+ rowEnds[row] = x + half
467
+ return { ...p, x, row }
468
+ })
469
+ const labelRows = Math.max(1, rowEnds.length)
470
+ const tickH = 18
471
+ const pointY = tickH + 16
472
+ const labelTop = pointY + 18
473
+ const spansTop = labelTop + labelRows * 15 + 8
474
+ const spans = (data.spans ?? []).map(s => ({ ...s, a: Math.max(from, toTime(s.from)), b: Math.min(to, toTime(s.to) + 86400000 - 1) })).filter(s => s.b >= s.a)
475
+ const height = spansTop + spans.length * 36 + 4
476
+
477
+ return h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
478
+ ticks.map((time, i) => h('g', { key: i },
479
+ h('line', { x1: sx(time), x2: sx(time), y1: tickH, y2: height, className: 'cb-dayLine' }),
480
+ h('text', { x: sx(time), y: 11, className: 'cb-axis', textAnchor: 'middle' }, formatDay(time, locale, 0)))),
481
+ now >= from && now <= to && h('line', { x1: sx(now), x2: sx(now), y1: tickH - 2, y2: height, className: 'cb-today' }),
482
+ placed.map((p, i) => {
483
+ const color = toneColor(p.tone ?? KIND_TONE[p.kind] ?? 'accent')
484
+ const text = p.label.length > 16 ? `${p.label.slice(0, 15)}…` : p.label
485
+ return h('g', { key: i },
486
+ h('title', null, `${formatDay(p.time, locale, 0)} · ${p.label}`),
487
+ p.kind === 'travel' ? h(PlaneGlyph, { x: p.x, y: pointY, color }) : h('circle', { cx: p.x, cy: pointY, r: 5, fill: color }),
488
+ p.row > 0 && h('line', { x1: p.x, x2: p.x, y1: pointY + 8, y2: labelTop + p.row * 15 - 9, className: 'cb-leader' }),
489
+ h('text', { x: p.x, y: labelTop + p.row * 15, className: 'cb-pointLabel', textAnchor: 'middle' }, text))
490
+ }),
491
+ spans.map((s, i) => {
492
+ const x = sx(s.a)
493
+ const w = Math.max(6, sx(s.b) - x)
494
+ const y = spansTop + i * 36
495
+ return h('g', { key: `s${i}` },
496
+ h('title', null, `${s.label}: ${s.from} – ${s.to}`),
497
+ h('rect', { x, y, width: w, height: 12, rx: 6, fill: toneColor(s.tone ?? 'accent'), fillOpacity: 0.22 }),
498
+ h('text', { x: Math.min(Math.max(x + w / 2, pad + 30), width - pad - 30), y: y + 26, className: 'cb-spanLabel', textAnchor: 'middle' },
499
+ `${s.label} · ${formatDay(toTime(s.from), locale, 0)} – ${formatDay(toTime(s.to), locale, 0)}`))
500
+ })))
501
+ }
502
+
503
+ // ---- status --------------------------------------------------------------
504
+
505
+ function Spark({ values, color }) {
506
+ const [ref, width] = useWidth()
507
+ const height = 22
508
+ const min = Math.min(...values)
509
+ const max = Math.max(...values)
510
+ const d = values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (values.length - 1)) * (width - 4) + 2).toFixed(1)},${(height - 3 - ((v - min) / (max - min || 1)) * (height - 6)).toFixed(1)}`).join('')
511
+ return h('div', { ref, className: 'cb-spark' }, width > 0 && h('svg', { width, height, 'aria-hidden': true },
512
+ h('path', { d, fill: 'none', stroke: color, strokeWidth: 1.5, strokeLinejoin: 'round', strokeLinecap: 'round' })))
513
+ }
514
+
515
+ function StatusCard({ data, locale, rowActions }) {
516
+ const sparks = data.rows.some(row => row.spark)
517
+ const hasActions = data.rows.some(row => row.actions?.length > 0)
518
+ return h('ul', { className: `cb-status${sparks ? ' cb-statusSparks' : ''}${hasActions ? ' cb-statusActions' : ''}` }, data.rows.map((row, i) =>
519
+ h('li', { key: i },
520
+ h('i', { className: 'cb-dot', style: { background: toneColor(row.tone) } }),
521
+ h('span', { className: 'cb-statusLabel' }, row.label),
522
+ h('span', { className: 'cb-statusValue' },
523
+ h('span', { style: row.tone === 'bad' || row.tone === 'warn' ? { color: toneColor(row.tone) } : undefined }, formatNumber(row.value, locale)),
524
+ row.sub && h('small', null, row.sub)),
525
+ sparks && (row.spark ? h(Spark, { values: row.spark, color: toneColor(row.tone === 'ok' ? 'accent' : row.tone) }) : h('span', null)),
526
+ hasActions && h('span', { className: 'cb-rowActions' }, rowActions && row.actions ? rowActions(i, row.actions, statusRowLine(row, locale)) : null))))
527
+ }
528
+
529
+ // ---- what a chat quotes ----------------------------------------------------
530
+
531
+ function withUnit(value, unit, locale) {
532
+ return `${formatNumber(value, locale)}${unit ? ` ${unit}` : ''}`
533
+ }
534
+
535
+ function statLines(data, locale) {
536
+ return data.items.map(item => `${item.label}: ${withUnit(item.value, item.unit, locale)}${item.delta ? ` (${item.delta.value > 0 ? '+' : ''}${formatNumber(item.delta.value, locale)}${item.delta.unit ? ` ${item.delta.unit}` : ''})` : ''}${item.sub ? ` · ${item.sub}` : ''}`)
537
+ }
538
+
539
+ function listRowLine(row) {
540
+ const box = 'checked' in row ? (row.checked ? '☑ ' : '☐ ') : ''
541
+ return `${box}${row.title}${row.sub ? ` · ${row.sub}` : ''}${row.date ? ` · ${row.date}` : ''}${row.chip ? ` [${row.chip.text}]` : ''}`
542
+ }
543
+
544
+ function statusRowLine(row, locale) {
545
+ return `${row.label}: ${formatNumber(row.value, locale)}${row.sub ? ` · ${row.sub}` : ''}`
546
+ }
547
+
548
+ /** A few plain lines saying what a card shows, for the agent. */
549
+ function summaryLines(card, locale) {
550
+ const data = card.data
551
+ const lines = card.stat ? statLines(card.stat, locale) : []
552
+ switch (card.type) {
553
+ case 'stat': return statLines(data, locale)
554
+ case 'line':
555
+ for (const series of data.series) {
556
+ const last = [...series.points].reverse().find(p => typeof p.y === 'number')
557
+ if (last) lines.push(`${series.name || 'latest'}: ${withUnit(last.y, data.unit, locale)} at ${last.x} (${series.points.length} points from ${series.points[0].x})`)
558
+ }
559
+ if (data.goal?.y !== undefined) lines.push(`goal: ${withUnit(data.goal.y, data.unit, locale)}`)
560
+ return lines
561
+ case 'bar':
562
+ return lines.concat(data.bars.slice(-10).map(bar => `${bar.x}: ${bar.values ? Object.entries(bar.values).map(([k, v]) => `${k} ${formatNumber(v, locale)}`).join(', ') : withUnit(bar.value, data.unit, locale)}`))
563
+ case 'donut': {
564
+ const total = data.segments.reduce((sum, s) => sum + s.value, 0)
565
+ return lines.concat(data.segments.map(s => `${s.label}: ${withUnit(s.value, data.unit, locale)}${total > 0 ? ` (${Math.round((s.value / total) * 100)}%)` : ''}`))
566
+ }
567
+ case 'list':
568
+ return lines.concat(data.progress ? [`progress: ${data.progress.done}/${data.progress.total}`] : [], data.rows.slice(0, 15).map(listRowLine))
569
+ case 'timeline':
570
+ return lines.concat((data.points ?? []).map(p => `${p.date}: ${p.label}`), (data.spans ?? []).map(s => `${s.from} – ${s.to}: ${s.label}`))
571
+ case 'status':
572
+ return lines.concat(data.rows.map(row => statusRowLine(row, locale)))
573
+ default: return lines
574
+ }
575
+ }
576
+
577
+ /** Press states by action id for the card (row undefined) or one row: the latest press wins. */
578
+ function statesOf(presses, row) {
579
+ const states = {}
580
+ for (const press of presses ?? []) if (press.row === row) states[press.id] = press.state
581
+ return states
582
+ }
583
+
584
+ // ---- card frame ----------------------------------------------------------
585
+
586
+ const CHART_HEIGHT = { 1: 150, 2: 360, 3: 560 }
587
+
588
+ function CardBody({ card, size, locale, t, rowActions }) {
589
+ const height = CHART_HEIGHT[size.h] - (card.stat ? 40 : 0)
590
+ const data = card.data
591
+ switch (card.type) {
592
+ case 'stat': return h(StatBlock, { data, locale })
593
+ case 'line': return h(LineChart, { data, locale, height })
594
+ case 'bar': return h(BarChart, { data, locale, height: Math.min(height, 130 + (size.h - 1) * 200) })
595
+ case 'donut': return h(Donut, { data, locale, height: Math.max(height, 160) })
596
+ case 'list': return h(ListCard, { data, locale, t, rowActions })
597
+ case 'timeline': return h(Timeline, { data, locale, t })
598
+ case 'status': return h(StatusCard, { data, locale, rowActions })
599
+ default: return null
600
+ }
601
+ }
602
+
603
+ function LinkIcon() {
604
+ return h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', 'aria-hidden': true, fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round' },
605
+ h('path', { d: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5' }))
606
+ }
607
+
608
+ function Card({ entry, boardId, columns, now, locale, t, actions }) {
609
+ const size = { w: Math.min(entry.w ?? 1, columns), h: entry.h ?? 1 }
610
+ const style = { gridColumn: `span ${size.w}`, gridRow: size.h > 1 ? `span ${size.h}` : undefined }
611
+ if (!entry.card) {
612
+ return h('section', { className: 'cb-card cb-cardError', style },
613
+ h('header', { className: 'cb-cardHead' }, h('h3', null, entry.id)),
614
+ h('p', { className: 'cb-errorText' }, t('cardError')),
615
+ h('ul', { className: 'cb-problems' }, (entry.problems ?? []).map((p, i) => h('li', { key: i }, p))))
616
+ }
617
+ const card = entry.card
618
+ const updated = Date.parse(card.updatedAt)
619
+ const age = Math.max(0, (now - updated) / 1000)
620
+ const stale = typeof card.staleAfter === 'number' && age > card.staleAfter
621
+ const external = card.link && /^https?:/i.test(card.link)
622
+ const context = row => ({ board: boardId, card: entry.id, ...(row === undefined ? {} : { row }), type: card.type, updatedAt: card.updatedAt })
623
+ // A chat opens a new conversation whose draft quotes the card (or the row) and names it.
624
+ const chat = (action, row, rowLine) => actions.startChat({
625
+ text: actions.chatText({
626
+ prompt: action.payload?.prompt ?? '',
627
+ title: card.title,
628
+ lines: row === undefined ? summaryLines(card, locale) : [rowLine],
629
+ context: action.payload?.context ?? context(row),
630
+ }),
631
+ session: action.payload?.session,
632
+ })
633
+ const defaultChat = { kind: 'chat', id: '_chat', label: t('chatAbout') }
634
+ const rowActions = actions && ((row, list, line) => h(actions.ActionBar, {
635
+ actions: list,
636
+ states: statesOf(entry.presses, row),
637
+ compact: true,
638
+ chat: action => chat(action, row, line),
639
+ onPress: (action, extra) => actions.press(action, extra, { card: entry.id, row }),
640
+ }))
641
+ return h('section', { className: `cb-card${stale ? ' cb-cardStale' : ''}`, style, 'data-type': card.type },
642
+ h('header', { className: 'cb-cardHead' },
643
+ h('h3', null, card.title),
644
+ stale && h('span', { className: 'cb-staleChip', title: new Date(updated).toLocaleString(locale) }, fill(t('stale'), { age: formatAge(age, t) })),
645
+ card.link && h('a', { className: 'cb-cardLink', href: card.link, title: t('open'), 'aria-label': t('open'), ...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {}) }, h(LinkIcon)),
646
+ actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: defaultChat, compact: true, chat: action => chat(action) }))),
647
+ card.stat && h(StatBlock, { data: card.stat, locale, compact: true }),
648
+ h('div', { className: 'cb-cardBody' }, h(CardBody, { card, size, locale, t, rowActions })),
649
+ actions && card.actions && h('footer', { className: 'cb-cardActions' }, h(actions.ActionBar, {
650
+ actions: card.actions,
651
+ states: statesOf(entry.presses, undefined),
652
+ chat: action => chat(action),
653
+ onPress: (action, extra) => actions.press(action, extra, { card: entry.id }),
654
+ })))
655
+ }
656
+
657
+ // ---- page ----------------------------------------------------------------
658
+
659
+ async function getJson(path, etag) {
660
+ const response = await fetch(api(path), { cache: 'no-store', credentials: 'same-origin', headers: etag ? { 'if-none-match': etag } : {} })
661
+ if (response.status === 304) return { notModified: true }
662
+ let body = null
663
+ try { body = await response.json() } catch { /* not JSON */ }
664
+ if (!response.ok) {
665
+ const error = new Error(body?.error ?? `HTTP ${response.status}`)
666
+ error.status = response.status
667
+ throw error
668
+ }
669
+ return { body, etag: response.headers.get('etag') }
670
+ }
671
+
672
+ function useColumns() {
673
+ const [ref, width] = useWidth()
674
+ return [ref, width >= 980 ? 3 : width >= 620 ? 2 : 1]
675
+ }
676
+
677
+ function BoardsPage({ translate: t }) {
678
+ const locale = t('time.locale')
679
+ const [boards, setBoards] = useState(null)
680
+ const [listError, setListError] = useState(null)
681
+ const [selected, setSelected] = useState(() => { try { return localStorage.getItem(STORE_KEY) } catch { return null } })
682
+ const [board, setBoard] = useState(null)
683
+ const [boardError, setBoardError] = useState(null)
684
+ const [refreshFailed, setRefreshFailed] = useState(false)
685
+ const [pollSeconds, setPollSeconds] = useState(30)
686
+ const [now, setNow] = useState(() => Date.now())
687
+ const etag = useRef(null)
688
+ const [gridRef, columns] = useColumns()
689
+ const [actions, setActions] = useState(null)
690
+ const currentRef = useRef(null)
691
+
692
+ const loadList = useCallback(async () => {
693
+ try {
694
+ const { body } = await getJson('boards')
695
+ setBoards(body.boards)
696
+ setPollSeconds(body.pollSeconds ?? 30)
697
+ setListError(null)
698
+ } catch (error) {
699
+ setListError(error.status === 503 ? t('noProvider') : error.message)
700
+ }
701
+ }, [t])
702
+
703
+ const current = boards?.some(b => b.id === selected) ? selected : boards?.[0]?.id ?? null
704
+
705
+ const loadBoard = useCallback(async (id, fresh) => {
706
+ if (!id) return
707
+ try {
708
+ const result = await getJson(`board?id=${encodeURIComponent(id)}`, fresh ? null : etag.current)
709
+ setRefreshFailed(false)
710
+ setBoardError(null)
711
+ if (result.notModified) return
712
+ etag.current = result.etag
713
+ setBoard(result.body)
714
+ } catch (error) {
715
+ if (error.status === 403 || error.status === 404) { setBoard(null); setBoardError(error.message); loadList(); return }
716
+ setRefreshFailed(true)
717
+ }
718
+ }, [loadList])
719
+
720
+ useEffect(() => { loadList() }, [loadList])
721
+
722
+ // The action buttons load with the page; until then (or if they fail) cards show without them.
723
+ useEffect(() => {
724
+ let live = true
725
+ loadActions().then(({ createActions }) => {
726
+ if (!live) return
727
+ const press = async (action, extra, target) => {
728
+ const response = await fetch(api('action'), {
729
+ method: 'POST',
730
+ credentials: 'same-origin',
731
+ headers: { 'content-type': 'application/json' },
732
+ body: JSON.stringify({ board: currentRef.current, ...target, id: action.id, ...extra }),
733
+ })
734
+ const body = await response.json().catch(() => null)
735
+ if (!response.ok) throw new Error(body?.error ?? `HTTP ${response.status}`)
736
+ loadBoard(currentRef.current, false)
737
+ return body
738
+ }
739
+ const ui = createActions({ React, ctx: clientCtx, locale })
740
+ setActions({ ...ui, press })
741
+ }, error => console.warn('card-board: action buttons not loaded:', error))
742
+ return () => { live = false }
743
+ }, [loadBoard, locale])
744
+
745
+ useEffect(() => {
746
+ currentRef.current = current
747
+ if (!current) return undefined
748
+ etag.current = null
749
+ setBoard(prev => (prev?.id === current ? prev : null))
750
+ loadBoard(current, true)
751
+ let ticks = 0
752
+ const tick = () => {
753
+ if (document.visibilityState !== 'visible') return
754
+ setNow(Date.now())
755
+ loadBoard(current, false)
756
+ if (++ticks % 10 === 0) loadList()
757
+ }
758
+ const timer = setInterval(tick, Math.max(5, pollSeconds) * 1000)
759
+ const onVisible = () => { if (document.visibilityState === 'visible') { setNow(Date.now()); loadBoard(current, false); loadList() } }
760
+ document.addEventListener('visibilitychange', onVisible)
761
+ return () => { clearInterval(timer); document.removeEventListener('visibilitychange', onVisible) }
762
+ }, [current, pollSeconds, loadBoard, loadList])
763
+
764
+ const choose = id => {
765
+ setSelected(id)
766
+ try { localStorage.setItem(STORE_KEY, id) } catch { /* private mode */ }
767
+ }
768
+
769
+ const newest = board?.cards?.reduce((max, entry) => {
770
+ const time = entry.card ? Date.parse(entry.card.updatedAt) : NaN
771
+ return Number.isFinite(time) && time > max ? time : max
772
+ }, 0)
773
+
774
+ const tabs = boards && boards.length > 1 && h('div', { className: 'cb-tabs', role: 'tablist' }, boards.map(b =>
775
+ h('button', { key: b.id, type: 'button', role: 'tab', 'aria-selected': b.id === current, className: 'cb-tab', onClick: () => choose(b.id) }, b.title)))
776
+
777
+ let content
778
+ if (listError) content = h('p', { className: 'cb-notice' }, listError)
779
+ else if (boards === null) content = h('p', { className: 'cb-muted' }, t('loading'))
780
+ else if (boards.length === 0) content = h('div', { className: 'cb-empty' }, h('p', { className: 'cb-emptyTitle' }, t('emptyTitle')), h('p', { className: 'cb-muted' }, t('emptyHint')))
781
+ else if (boardError) content = h('p', { className: 'cb-notice' }, boardError)
782
+ else if (!board) content = h('p', { className: 'cb-muted' }, t('loading'))
783
+ else content = h(React.Fragment, null,
784
+ board.problems?.length > 0 && h('div', { className: 'cb-notice' }, t('boardProblems'), h('ul', { className: 'cb-problems' }, board.problems.map((p, i) => h('li', { key: i }, p)))),
785
+ board.cards.length === 0 && h('p', { className: 'cb-muted' }, t('noCards')),
786
+ h('div', { className: 'cb-grid', style: { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } },
787
+ board.cards.map(entry => h(Card, { key: entry.id, entry, boardId: board.id, columns, now, locale, t, actions }))))
788
+
789
+ return h('div', { className: 'cb-page' },
790
+ h('div', { className: 'cb-content', ref: gridRef },
791
+ h('div', { className: 'cb-heading' },
792
+ h('h1', null, boards?.length === 1 ? boards[0].title : t('title')),
793
+ h('p', { className: 'cb-sub' },
794
+ newest > 0 ? fill(t('updated'), { time: formatUpdated(newest, locale) }) : ' ',
795
+ refreshFailed && h('span', { className: 'cb-warnText' }, ` · ${t('refreshFailed')}`))),
796
+ tabs,
797
+ content))
798
+ }
799
+
800
+ function SidebarIcon({ size }) {
801
+ const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round', fill: 'none' }
802
+ return h('svg', { width: size, height: size, viewBox: '0 0 16 16', 'aria-hidden': true, focusable: 'false' },
803
+ h('rect', { x: 1.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
804
+ h('rect', { x: 8.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
805
+ h('rect', { x: 1.75, y: 8.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
806
+ h('path', { d: 'M9 13.5l1.6-2 1.4 1 2-2.8', ...stroke }))
807
+ }
808
+
809
+ const CSS = `
810
+ .cb-page{--cb-ok:var(--dsw-alias-state-success-primary,#22a06b);--cb-warn:var(--dsw-alias-state-warn-primary,#f5a524);--cb-bad:var(--dsw-alias-state-error-primary,#e5484d);--cb-muted:var(--dsw-alias-state-idle-primary,#b8bec9);--cb-accent:var(--dsw-alias-state-business-primary,#3b82f6);--cb-violet:var(--dsw-alias-state-done-primary,#8b5cf6);--cb-card:var(--dsw-alias-bg-base,#fff);--cb-track:var(--dsw-alias-border-l2,#0000001a);width:100%;height:100%;min-height:0;overflow:auto;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font-size:14px;line-height:1.5;scrollbar-gutter:stable}
811
+ .cb-content{max-width:1240px;margin:0 auto;padding:0 clamp(16px,3.2vw,40px) 48px}
812
+ .cb-heading{padding-top:28px;margin-bottom:14px}
813
+ [data-platform=darwin] .cb-heading{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
814
+ .cb-heading h1{margin:0;font-size:22px;font-weight:600;line-height:30px}
815
+ .cb-sub{margin:2px 0 0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}
816
+ .cb-warnText{color:var(--cb-warn)}
817
+ .cb-tabs{display:flex;gap:4px;margin:0 0 18px;border-bottom:.5px solid var(--dsw-alias-border-l2);overflow-x:auto;scrollbar-width:none}
818
+ .cb-tab{position:relative;flex:none;padding:8px 12px 10px;border:0;background:none;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:14px;cursor:pointer;border-radius:8px 8px 0 0}
819
+ .cb-tab[aria-selected=true]{color:var(--dsw-alias-label-primary);font-weight:500}
820
+ .cb-tab[aria-selected=true]:after{content:"";position:absolute;left:10px;right:10px;bottom:-.5px;height:2px;border-radius:2px;background:var(--cb-accent)}
821
+ @media (hover:hover){.cb-tab:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}}
822
+ .cb-grid{display:grid;gap:14px;grid-auto-flow:row dense;align-items:stretch}
823
+ .cb-card{box-sizing:border-box;min-width:0;display:flex;flex-direction:column;gap:10px;padding:16px 18px 18px;border-radius:16px;background:var(--cb-card);box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l2)}
824
+ .cb-cardHead{display:flex;align-items:center;gap:8px;min-height:22px}
825
+ .cb-cardHead h3{flex:1;min-width:0;margin:0;font-size:15px;font-weight:600;line-height:22px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
826
+ .cb-cardChat{display:inline-flex;margin-right:-6px}
827
+ .cb-cardActions{padding-top:4px}
828
+ .cb-rowActions{display:inline-flex;justify-content:flex-end}
829
+ .cb-statusActions{grid-template-columns:8px fit-content(45%) minmax(0,1fr) auto}
830
+ .cb-statusSparks.cb-statusActions{grid-template-columns:8px fit-content(40%) minmax(0,1fr) minmax(56px,1.2fr) auto}
831
+ .cb-cardLink{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:6px;color:var(--dsw-alias-label-tertiary)}
832
+ @media (hover:hover){.cb-cardLink:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
833
+ .cb-staleChip{flex:none;padding:1px 8px;border-radius:999px;font-size:11px;line-height:18px;color:var(--dsw-alias-state-warn-label,var(--cb-warn));background:color-mix(in srgb,var(--cb-warn) 14%,transparent)}
834
+ .cb-cardStale .cb-cardBody,.cb-cardStale .cb-stats{opacity:.62}
835
+ .cb-cardBody{flex:1;min-width:0;display:flex;flex-direction:column;justify-content:flex-start}
836
+ .cb-cardError{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--cb-bad) 35%,transparent)}
837
+ .cb-errorText{margin:0;color:var(--cb-bad);font-size:13px}
838
+ .cb-problems{margin:6px 0 0;padding:0 0 0 16px;color:var(--dsw-alias-label-tertiary);font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
839
+ .cb-notice{margin:0 0 14px;padding:10px 14px;border-radius:12px;background:color-mix(in srgb,var(--cb-warn) 10%,transparent);color:var(--dsw-alias-label-secondary);font-size:13px}
840
+ .cb-muted{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px}
841
+ .cb-empty{padding:48px 0;text-align:center}
842
+ .cb-emptyTitle{margin:0 0 4px;color:var(--dsw-alias-label-secondary)}
843
+ .cb-chart{position:relative;width:100%;min-width:0}
844
+ .cb-chart svg,.cb-donutRing svg{display:block;overflow:visible}
845
+ .cb-rule{stroke:var(--dsw-alias-border-l2);stroke-width:1;shape-rendering:crispEdges}
846
+ .cb-axis{fill:var(--dsw-alias-label-caption);font-size:11px}
847
+ .cb-goal{stroke:var(--dsw-alias-label-caption);stroke-width:1.2;stroke-dasharray:4 4;fill:none}
848
+ .cb-goalLabel{fill:var(--dsw-alias-label-tertiary);font-size:11px}
849
+ .cb-marker{stroke:var(--dsw-alias-border-l3);stroke-dasharray:2 3}
850
+ .cb-markerLabel{fill:var(--dsw-alias-label-tertiary);font-size:11px}
851
+ .cb-barValue{fill:var(--dsw-alias-label-secondary);font-size:11px}
852
+ .cb-dayLine{stroke:var(--dsw-alias-border-l1,var(--dsw-alias-border-l2));stroke-dasharray:2 4}
853
+ .cb-today{stroke:var(--cb-accent);stroke-width:1.2;stroke-opacity:.6}
854
+ .cb-leader{stroke:var(--dsw-alias-border-l3)}
855
+ .cb-pointLabel{fill:var(--dsw-alias-label-secondary);font-size:12px}
856
+ .cb-spanLabel{fill:var(--dsw-alias-label-tertiary);font-size:12px}
857
+ .cb-stats{display:flex;flex-wrap:wrap;gap:12px 28px}
858
+ .cb-stat{min-width:0}
859
+ .cb-statLabel{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
860
+ .cb-statValue{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 6px;font-size:28px;font-weight:600;line-height:36px;font-variant-numeric:tabular-nums;letter-spacing:-.01em}
861
+ .cb-statValue small{font-size:15px;font-weight:500;color:var(--dsw-alias-label-secondary)}
862
+ .cb-statsCompact .cb-statValue{font-size:26px;line-height:32px}
863
+ .cb-delta{font-style:normal;font-size:12px;font-weight:500}
864
+ .cb-statSub{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}
865
+ .cb-legend{display:flex;flex-wrap:wrap;gap:4px 14px;margin:8px 0 0;padding:0;list-style:none;color:var(--dsw-alias-label-secondary);font-size:12px}
866
+ .cb-legend li{display:inline-flex;align-items:center;gap:6px}
867
+ .cb-legend i,.cb-donutTable i{display:inline-block;width:8px;height:8px;border-radius:50%}
868
+ .cb-legend b{font-weight:500;color:var(--dsw-alias-label-tertiary)}
869
+ .cb-donut{display:flex;align-items:center;gap:24px}
870
+ .cb-donutNarrow{flex-direction:column;align-items:stretch;gap:12px}
871
+ .cb-donutNarrow .cb-donutRing{align-self:center}
872
+ .cb-donutRing{position:relative;flex:none}
873
+ .cb-donutCentre{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;pointer-events:none}
874
+ .cb-donutCentre strong{font-size:22px;font-weight:600;line-height:28px;font-variant-numeric:tabular-nums}
875
+ .cb-donutCentre span{color:var(--dsw-alias-label-tertiary);font-size:12px}
876
+ .cb-donutTable{flex:1;min-width:0;border-collapse:collapse;font-size:13px}
877
+ .cb-donutTable td{padding:4px 0;white-space:nowrap}
878
+ .cb-donutTable td:first-child{width:8px;padding-right:10px}
879
+ .cb-donutLabel{overflow:hidden;text-overflow:ellipsis;max-width:0;width:100%}
880
+ .cb-num{text-align:right;padding-left:14px!important;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
881
+ .cb-dim{color:var(--dsw-alias-label-tertiary)}
882
+ .cb-list{list-style:none;margin:0;padding:0}
883
+ .cb-listWrap{display:flex;align-items:center;gap:24px}
884
+ .cb-listWrapNarrow{flex-direction:column;align-items:stretch;gap:6px}
885
+ .cb-progressLine{display:flex;align-items:center;gap:10px;color:var(--dsw-alias-label-tertiary);font-size:13px}
886
+ .cb-progressLine strong{font-size:10px!important}
887
+
888
+ .cb-listMain{flex:1;min-width:0}
889
+ .cb-list li{display:flex;align-items:center;gap:10px;padding:8px 2px;border-top:.5px solid var(--dsw-alias-border-l2)}
890
+ .cb-list li:first-child{border-top:0}
891
+ .cb-listText{flex:1;min-width:0}
892
+ .cb-listTitle{overflow-wrap:anywhere}
893
+ .cb-listSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
894
+ .cb-listDate{flex:none;color:var(--dsw-alias-label-tertiary);font-size:12px;font-variant-numeric:tabular-nums}
895
+ .cb-done .cb-listTitle{color:var(--dsw-alias-label-tertiary)}
896
+ .cb-checkBox{flex:none;display:inline-flex}
897
+ .cb-check rect{fill:none;stroke:var(--dsw-alias-border-l4,var(--dsw-alias-label-caption));stroke-width:1.3}
898
+ .cb-check[data-checked=true] rect{fill:var(--cb-accent);stroke:var(--cb-accent)}
899
+ .cb-check path{fill:none;stroke:#fff;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
900
+ .cb-chip{flex:none;padding:1px 8px;border-radius:6px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-interactive-bg-hover,#0000000d);font-variant-numeric:tabular-nums;white-space:nowrap}
901
+ .cb-chip[data-tone=ok]{color:var(--cb-ok);background:color-mix(in srgb,var(--cb-ok) 12%,transparent)}
902
+ .cb-chip[data-tone=warn]{color:var(--dsw-alias-state-warn-label,var(--cb-warn));background:color-mix(in srgb,var(--cb-warn) 14%,transparent)}
903
+ .cb-chip[data-tone=bad]{color:var(--cb-bad);background:color-mix(in srgb,var(--cb-bad) 12%,transparent)}
904
+ .cb-chip[data-tone=accent]{color:var(--cb-accent);background:color-mix(in srgb,var(--cb-accent) 12%,transparent)}
905
+ .cb-status{list-style:none;margin:0;padding:0}
906
+ .cb-status{display:grid;grid-template-columns:8px fit-content(45%) minmax(0,1fr);column-gap:12px}
907
+ .cb-statusSparks{grid-template-columns:8px fit-content(40%) minmax(0,1fr) minmax(56px,1.2fr)}
908
+ .cb-status li{grid-column:1/-1;display:grid;grid-template-columns:subgrid;align-items:center;padding:8px 2px;border-top:.5px solid var(--dsw-alias-border-l2)}
909
+ .cb-status li:first-child{border-top:0}
910
+ .cb-dot{width:8px;height:8px;border-radius:50%}
911
+ .cb-statusLabel{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
912
+ .cb-statusValue{min-width:0;display:flex;flex-direction:column;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
913
+ .cb-statusValue small{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}
914
+ .cb-spark{min-width:0}
915
+ @media (width<=640px){.cb-heading{padding-top:18px}.cb-heading h1{font-size:20px}.cb-card{padding:14px 14px 16px;border-radius:14px}.cb-statValue{font-size:24px;line-height:30px}}
916
+ `
917
+
918
+ return {
919
+ inject: ['slots', 'locale'],
920
+ apply(ctx) {
921
+ clientCtx = ctx
922
+ ctx.effect(() => {
923
+ const disposers = [ctx.locale.register(NS, 'en', en), ctx.locale.register(NS, 'zh', zh)]
924
+ return () => { for (const dispose of disposers) dispose() }
925
+ }, 'card-board: dictionaries')
926
+ const t = ctx.locale.bind(NS)
927
+
928
+ ctx.effect(() => {
929
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
930
+ const tag = document.createElement('style')
931
+ tag.id = STYLE_ID
932
+ tag.dataset.plugin = '@soffits/dsh-card-board'
933
+ tag.textContent = CSS
934
+ document.head.appendChild(tag)
935
+ return () => tag.remove()
936
+ }, 'card-board: styles')
937
+
938
+ ctx.slots.inject('main', () => ctx.slots.register({
939
+ name: 'main',
940
+ key: PANEL,
941
+ locale: NS,
942
+ inject: () => ({ translate: t }),
943
+ }, BoardsPage))
944
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
945
+ name: 'sidebar.panellist',
946
+ id: PANEL,
947
+ order: 13,
948
+ locale: NS,
949
+ label: () => t('panel'),
950
+ }, SidebarIcon))
951
+ },
952
+ }
953
+ },
954
+ })