@soffits/dsh-card-board 0.5.0 → 0.7.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 CHANGED
@@ -1,937 +1,135 @@
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
- */
1
+ /* @soffits/dsh-card-board 0.7.0: built by scripts/build.mjs from src/client/. Do not edit. */
12
2
  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 OWNER = '@soffits/dsh-card-board'
21
- const PANEL = 'dsh-card-board'
22
- const STYLE_ID = 'dsh-card-board-style'
23
- const STORE_KEY = 'dsh-card-board:board'
24
- const api = path => new URL(`api/card-board/${path}`, document.baseURI).href
25
-
26
- // ---- the page's own words -------------------------------------------------------
27
- // One file per language in the package's locale folder (`ui` in locale/<tag>.json), served by the
28
- // Host for the active language. The buttons come from @soffits/dsh-ui-actions, which has its own words.
29
- // The code names no language. A test fails when a component renders a
30
- // literal string instead of one of these.
31
-
32
- const messageRequests = new Map()
33
- /** The words for a DSH language id, fetched once per page load (a failed fetch is tried again next time). */
34
- function fetchMessages(tag) {
35
- if (!messageRequests.has(tag)) {
36
- const request = fetch(api(`locale?tag=${encodeURIComponent(tag)}`), { credentials: 'same-origin' })
37
- .then(response => (response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))))
38
- .then(body => body.messages)
39
- request.catch(() => messageRequests.delete(tag))
40
- messageRequests.set(tag, request)
41
- }
42
- return messageRequests.get(tag)
43
- }
44
-
45
- /** What a card writes for a person to read: a string, or a map of language id → string (`en` always there). */
46
- function pickText(value, active) {
47
- if (typeof value !== 'object' || value === null) return value
48
- const byId = new Map(Object.entries(value).map(([id, text]) => [id.toLowerCase(), text]))
49
- const tag = String(active ?? 'en').toLowerCase()
50
- const primary = tag.split('-')[0]
51
- return byId.get(tag) ?? byId.get(primary) ?? [...byId].find(([id]) => id.split('-')[0] === primary)?.[1] ?? byId.get('en') ?? [...byId.values()][0] ?? ''
52
- }
53
-
54
- /** A card copy whose texts are resolved: walks the whole tree, so every component sees plain strings. */
55
- function pickCard(card, active) {
56
- const withPrompt = payload => (payload && 'prompt' in payload ? { ...payload, prompt: pickText(payload.prompt, active) } : payload)
57
- const walk = value => {
58
- if (Array.isArray(value)) return value.map(walk)
59
- if (typeof value !== 'object' || value === null) return value
60
- const keys = Object.keys(value)
61
- if (keys.length > 0 && 'en' in value && keys.every(key => /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/.test(key)) && keys.every(key => typeof value[key] === 'string')) return pickText(value, active)
62
- // An action's payload is data for handlers, except the words a chat starts with.
63
- return Object.fromEntries(keys.map(key => [key, key === 'payload' ? withPrompt(value[key]) : walk(value[key])]))
64
- }
65
- return walk(card)
66
- }
67
-
68
- const fill = (text, params) => String(text).replace(/\{(\w+)\}/g, (match, key) => (key in params ? String(params[key]) : match))
69
-
70
- /** The language id as an Intl locale, when this browser knows it. */
71
- function intlTag(active) {
72
- try {
73
- return Intl.DateTimeFormat.supportedLocalesOf(active).length > 0 ? active : 'en'
74
- } catch {
75
- return 'en'
76
- }
77
- }
78
-
79
- const translator = messages => (key, params) => {
80
- const text = messages[key] ?? key
81
- return params ? fill(text, params) : text
82
- }
83
-
84
- /** The client context, for the locale service (set in apply). */
85
- let clientCtx = null
86
-
87
- /**
88
- * DSH's active language, live (the same value `useLocale(s => s.active)` gives a TSX plugin), with the
89
- * page's words for it. `ready` turns true when they have arrived; a switch keeps the old words until the new ones do.
90
- */
91
- function useActiveLocale() {
92
- const subscribe = useCallback(listener => clientCtx.locale.subscribe(listener), [])
93
- const active = React.useSyncExternalStore(subscribe, () => clientCtx.locale.getSnapshot().active)
94
- const [loaded, setLoaded] = useState(null)
95
- const [attempt, setAttempt] = useState(0)
96
- useEffect(() => {
97
- let live = true
98
- let timer
99
- fetchMessages(active).then(
100
- messages => { if (live) setLoaded({ active, messages }) },
101
- () => { if (live) timer = setTimeout(() => setAttempt(count => count + 1), 3000) })
102
- return () => { live = false; clearTimeout(timer) }
103
- }, [active, attempt])
104
- return useMemo(() => ({ active: loaded?.active ?? active, ready: loaded !== null, intl: intlTag(loaded?.active ?? active), t: translator(loaded?.messages ?? {}) }), [loaded, active])
105
- }
106
-
107
- /**
108
- * The shared buttons (`ctx.uiActions` from @soffits/dsh-ui-actions), once that plugin is there; the page
109
- * shows cards without buttons until then, or when it isn't installed.
110
- */
111
- const buttonsStore = (() => {
112
- let value = null
113
- const listeners = new Set()
114
- return {
115
- get: () => value,
116
- set: next => { value = next; for (const listener of listeners) listener() },
117
- subscribe: listener => { listeners.add(listener); return () => { listeners.delete(listener) } },
118
- }
119
- })()
120
- const useButtons = () => React.useSyncExternalStore(buttonsStore.subscribe, buttonsStore.get)
121
-
122
- // ---- numbers, dates, tones -------------------------------------------------
123
-
124
- const TONES = { ok: 'var(--cb-ok)', warn: 'var(--cb-warn)', bad: 'var(--cb-bad)', muted: 'var(--cb-muted)', accent: 'var(--cb-accent)' }
125
- const PALETTE = ['var(--cb-accent)', 'var(--cb-ok)', 'var(--cb-warn)', 'var(--cb-violet)', 'var(--cb-bad)', 'var(--cb-muted)']
126
- const toneColor = (tone, index = 0) => TONES[tone] ?? PALETTE[index % PALETTE.length]
127
-
128
- function formatNumber(value, locale, digits) {
129
- if (typeof value !== 'number') return String(value)
130
- const abs = Math.abs(value)
131
- const max = digits ?? (abs >= 1000 ? 0 : abs >= 100 ? 1 : 2)
132
- return new Intl.NumberFormat(locale, { maximumFractionDigits: max }).format(value)
133
- }
134
-
135
- /** Short axis numbers in the language's own way: 18,240 → 18.2K, 1.8万. */
136
- function formatAxis(value, locale) {
137
- const abs = Math.abs(value)
138
- if (abs >= 1e4) return new Intl.NumberFormat(locale, { notation: 'compact', maximumFractionDigits: abs >= 1e5 ? 0 : 1 }).format(value)
139
- return formatNumber(value, locale, abs >= 100 ? 0 : 1)
140
- }
141
-
142
- const DAY_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/
143
- /** A date string as a time: a bare day is local midnight, so it labels as that day everywhere. */
144
- function toTime(value) {
145
- if (typeof value !== 'string') return NaN
146
- const day = DAY_ONLY.exec(value)
147
- if (day) return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).getTime()
148
- return /^\d{4}-\d{2}-\d{2}T/.test(value) ? Date.parse(value) : NaN
149
- }
150
-
151
- function formatDay(time, locale, spanDays) {
152
- const date = new Date(time)
153
- if (spanDays > 120) return new Intl.DateTimeFormat(locale, { month: 'short' }).format(date)
154
- return new Intl.DateTimeFormat(locale, { month: 'numeric', day: 'numeric' }).format(date)
155
- }
156
-
157
- /** How long ago, in the language's own units: 3 min, 5 h, 2 d. */
158
- function formatAge(seconds, locale) {
159
- const [unit, amount] = seconds < 3600 ? ['minute', Math.max(1, Math.round(seconds / 60))] : seconds < 86400 * 2 ? ['hour', Math.round(seconds / 3600)] : ['day', Math.round(seconds / 86400)]
160
- return new Intl.NumberFormat(locale, { style: 'unit', unit, unitDisplay: 'short' }).format(amount)
161
- }
162
-
163
- function formatUpdated(time, locale) {
164
- const date = new Date(time)
165
- const today = new Date()
166
- const sameDay = date.toDateString() === today.toDateString()
167
- return new Intl.DateTimeFormat(locale, sameDay ? { hour: '2-digit', minute: '2-digit' } : { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(date)
168
- }
169
-
170
- /** About this many pixels for 11px label text: CJK characters are about twice as wide. */
171
- const textWidth = text => [...String(text)].reduce((sum, char) => sum + (char.charCodeAt(0) > 0x2e7f ? 11.5 : 6.4), 0)
172
-
173
- /** `text` cut with an ellipsis to fit about `px` pixels of label text. */
174
- function fit(text, px) {
175
- if (textWidth(text) <= px) return String(text)
176
- let out = ''
177
- for (const char of String(text)) {
178
- if (textWidth(`${out}${char}…`) > px) break
179
- out += char
180
- }
181
- return `${out}…`
182
- }
183
-
184
- /** Round tick values covering [min, max], about `count` of them. */
185
- function niceTicks(min, max, count) {
186
- if (min === max) return [min]
187
- const raw = (max - min) / Math.max(1, count)
188
- const power = 10 ** Math.floor(Math.log10(raw))
189
- const step = [1, 2, 2.5, 5, 10].map(m => m * power).find(s => s >= raw) ?? raw
190
- const ticks = []
191
- for (let v = Math.ceil(min / step) * step; v <= max + step * 1e-9; v += step) ticks.push(Number(v.toFixed(10)))
192
- return ticks
193
- }
194
-
195
- /** Evenly spaced indexes, at most `count`, always including the last. */
196
- function spread(length, count) {
197
- if (length <= count) return Array.from({ length }, (_, i) => i)
198
- const step = (length - 1) / Math.max(1, count - 1)
199
- return Array.from({ length: count }, (_, i) => Math.round(i * step))
200
- }
201
-
202
- /** A callback ref and the width of the element it is on, kept up to date as the element resizes (or appears later). */
203
- function useWidth() {
204
- const [element, setElement] = useState(null)
205
- const [width, setWidth] = useState(0)
206
- useLayoutEffect(() => {
207
- if (!element) return undefined
208
- const observer = new ResizeObserver(([entry]) => setWidth(Math.floor(entry.contentRect.width)))
209
- observer.observe(element)
210
- return () => observer.disconnect()
211
- }, [element])
212
- return [setElement, width]
213
- }
214
-
215
- // ---- pieces shared by cards ------------------------------------------------
216
-
217
- /** Text that shortens to fit; hover shows all of it, and a tap opens it up (or closes it again). */
218
- function Trunc({ text, as = 'div', className = '', lines = 1 }) {
219
- const [open, setOpen] = useState(false)
220
- return h(as, {
221
- className: `cb-trunc${lines > 1 ? ' cb-trunc2' : ''}${open ? ' cb-truncOpen' : ''} ${className}`.trim(),
222
- title: text,
223
- onClick: () => setOpen(value => !value),
224
- }, text)
225
- }
226
-
227
- function Chip({ text, tone }) {
228
- return h('span', { className: 'cb-chip', 'data-tone': tone ?? 'muted', title: text }, text)
229
- }
230
-
231
- function Legend({ items, locale }) {
232
- return h('ul', { className: 'cb-legend' }, items.map((item, i) =>
233
- h('li', { key: i },
234
- h('i', { style: { background: item.color } }),
235
- h(Trunc, { as: 'span', text: item.label }),
236
- item.value !== undefined && h('b', null, formatNumber(item.value, locale)))))
237
- }
238
-
239
- function StatBlock({ data, locale, compact }) {
240
- return h('div', { className: `cb-stats${compact ? ' cb-statsCompact' : ''}` }, data.items.map((item, i) =>
241
- h('div', { key: i, className: 'cb-stat' },
242
- !compact && h(Trunc, { className: 'cb-statLabel', text: item.label }),
243
- h('div', { className: 'cb-statValue', style: item.tone ? { color: toneColor(item.tone) } : undefined },
244
- h('span', null, formatNumber(item.value, locale)),
245
- item.unit && h('small', null, item.unit),
246
- item.delta && h('em', { className: 'cb-delta', style: { color: toneColor(item.delta.tone ?? 'muted') } },
247
- `${item.delta.value > 0 ? '▲' : item.delta.value < 0 ? '▼' : '•'} ${formatNumber(Math.abs(item.delta.value), locale)}${item.delta.unit ? ` ${item.delta.unit}` : ''}`)),
248
- (compact ? [item.label, item.sub].filter(Boolean).join(' · ') : item.sub) &&
249
- h(Trunc, { className: 'cb-statSub', lines: 2, text: compact ? [item.label, item.sub].filter(Boolean).join(' · ') : item.sub }))))
250
- }
251
-
252
- // ---- line ----------------------------------------------------------------
253
-
254
- function LineChart({ data, locale, height }) {
255
- const [ref, width] = useWidth()
256
- const model = useMemo(() => {
257
- // The x range covers the series, a goal drawn as points and the markers, so none of them runs off the plot.
258
- const allX = [...data.series.flatMap(s => s.points.map(p => p.x)), ...(data.goal?.points ?? []).map(p => p.x), ...(data.markers ?? []).map(m => m.x)]
259
- const times = allX.map(toTime)
260
- const timeAxis = times.every(Number.isFinite)
261
- const numberAxis = !timeAxis && allX.every(x => typeof x === 'number')
262
- const categories = timeAxis || numberAxis ? [] : [...new Set(allX.map(String))]
263
- const xValue = x => (timeAxis ? toTime(x) : numberAxis ? x : categories.indexOf(String(x)))
264
- const xs = allX.map(xValue)
265
- let ys = data.series.flatMap(s => s.points.map(p => p.y)).filter(y => typeof y === 'number')
266
- if (data.goal?.y !== undefined) ys = ys.concat(data.goal.y)
267
- if (data.goal?.points) ys = ys.concat(data.goal.points.map(p => p.y).filter(y => typeof y === 'number'))
268
- let yMin = Math.min(...ys)
269
- let yMax = Math.max(...ys)
270
- const pad = (yMax - yMin || Math.abs(yMax) || 1) * 0.08
271
- yMin -= pad
272
- yMax += pad
273
- return { timeAxis, categories, xValue, xMin: Math.min(...xs), xMax: Math.max(...xs), yMin, yMax }
274
- }, [data])
275
-
276
- const ticks = niceTicks(model.yMin, model.yMax, height > 160 ? 4 : 3).filter(v => v >= model.yMin && v <= model.yMax)
277
- const left = Math.max(...ticks.map(v => textWidth(formatAxis(v, locale)))) + 10
278
- const right = 12
279
- const top = 10
280
- const bottom = 20
281
- const plotW = Math.max(10, width - left - right)
282
- const plotH = Math.max(10, height - top - bottom)
283
- const sx = x => left + (model.xMax === model.xMin ? plotW / 2 : ((model.xValue(x) - model.xMin) / (model.xMax - model.xMin)) * plotW)
284
- const sy = y => top + (1 - (y - model.yMin) / (model.yMax - model.yMin || 1)) * plotH
285
- const spanDays = model.timeAxis ? (model.xMax - model.xMin) / 86400000 : 0
286
- const xLabel = x => (model.timeAxis ? formatDay(toTime(x), locale, spanDays) : typeof x === 'number' ? formatNumber(x, locale) : String(x))
287
-
288
- const longest = data.series.reduce((best, s) => (s.points.length > best.points.length ? s : best), data.series[0])
289
- const labelWidth = Math.max(36, ...longest.points.slice(0, 40).map(p => textWidth(xLabel(p.x)) + 12))
290
- const labelCount = Math.max(2, Math.floor(plotW / labelWidth))
291
- // Evenly spaced labels, minus any that would print the same text or sit on top of the one before.
292
- const xTicks = []
293
- for (const x of spread(longest.points.length, labelCount).map(i => longest.points[i].x)) {
294
- const last = xTicks[xTicks.length - 1]
295
- if (last !== undefined && (xLabel(last) === xLabel(x) || sx(x) - sx(last) < labelWidth)) continue
296
- xTicks.push(x)
297
- }
298
-
299
- // Marker labels sit just above the x axis, right of their line (left of it near the right edge), in up to two rows;
300
- // one that finds no free spot shows only its line, and its text on hover.
301
- const labelRows = [[], []]
302
- const markerLabels = [...(data.markers ?? [])].sort((a, b) => model.xValue(a.x) - model.xValue(b.x)).map(marker => {
303
- const x = sx(marker.x)
304
- const room = left + plotW - x - 6
305
- const flip = room < Math.min(textWidth(marker.label), 90) && x - left > room
306
- const space = Math.max(20, Math.min(120, flip ? x - left - 6 : room))
307
- const width = Math.min(textWidth(marker.label), space)
308
- const span = flip ? [x - 4 - width, x - 4] : [x + 4, x + 4 + width]
309
- const row = labelRows.findIndex(taken => taken.every(([from, to]) => span[0] > to + 4 || span[1] < from - 4))
310
- if (row >= 0) labelRows[row].push(span)
311
- return { marker, x, flip, space, label: row >= 0 ? row : null }
312
- })
313
-
314
- const path = points => {
315
- let d = ''
316
- let pen = false
317
- for (const p of points) {
318
- if (typeof p.y !== 'number') { pen = false; continue }
319
- d += `${pen ? 'L' : 'M'}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`
320
- pen = true
321
- }
322
- return d
323
- }
324
- const gradientId = useMemo(() => `cb-g-${Math.random().toString(36).slice(2, 9)}`, [])
325
-
326
- return h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
327
- h('defs', null, data.series.map((s, i) => h('linearGradient', { key: i, id: `${gradientId}-${i}`, x1: 0, y1: 0, x2: 0, y2: 1 },
328
- h('stop', { offset: '0%', stopColor: toneColor(s.tone, i), stopOpacity: 0.22 }),
329
- h('stop', { offset: '100%', stopColor: toneColor(s.tone, i), stopOpacity: 0 })))),
330
- ticks.map(v => h('g', { key: v },
331
- h('line', { x1: left, x2: left + plotW, y1: sy(v), y2: sy(v), className: 'cb-rule' }),
332
- h('text', { x: left - 8, y: sy(v), className: 'cb-axis', textAnchor: 'end', dominantBaseline: 'middle' }, formatAxis(v, locale)))),
333
- 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))),
334
- markerLabels.map(({ marker, x, label, flip, space }, i) => h('g', { key: `m${i}` },
335
- h('line', { x1: x, x2: x, y1: top, y2: top + plotH, className: 'cb-marker' }),
336
- h('title', null, marker.label),
337
- label !== null && h('text', { x: flip ? x - 4 : x + 4, y: top + plotH - 5 - label * 13, className: 'cb-markerLabel', textAnchor: flip ? 'end' : 'start' }, fit(marker.label, space)))),
338
- data.goal && (data.goal.points
339
- ? h('path', { d: path(data.goal.points), className: 'cb-goal' })
340
- : h('line', { x1: left, x2: left + plotW, y1: sy(data.goal.y), y2: sy(data.goal.y), className: 'cb-goal' })),
341
- data.goal?.label && (() => {
342
- const end = data.goal.points ? data.goal.points[data.goal.points.length - 1] : { x: null, y: data.goal.y }
343
- const x = end.x === null ? left + plotW : sx(end.x)
344
- return h('text', { x: Math.min(x, left + plotW), y: sy(end.y) - 5, className: 'cb-goalLabel', textAnchor: 'end' }, h('title', null, data.goal.label), fit(data.goal.label, plotW))
345
- })(),
346
- data.series.map((s, i) => {
347
- const color = toneColor(s.tone, i)
348
- const line = path(s.points)
349
- const valid = s.points.filter(p => typeof p.y === 'number')
350
- const last = valid[valid.length - 1]
351
- const area = data.area && valid.length > 1
352
- ? `${line}L${sx(last.x).toFixed(1)},${(top + plotH).toFixed(1)}L${sx(valid[0].x).toFixed(1)},${(top + plotH).toFixed(1)}Z`
353
- : null
354
- return h('g', { key: `s${i}` },
355
- area && h('path', { d: area, fill: `url(#${gradientId}-${i})`, stroke: 'none' }),
356
- h('path', { d: line, fill: 'none', stroke: color, strokeWidth: 2, strokeLinejoin: 'round', strokeLinecap: 'round' }),
357
- 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 },
358
- h('title', null, `${s.name ? `${s.name} · ` : ''}${xLabel(p.x)}: ${formatNumber(p.y, locale)}${data.unit ? ` ${data.unit}` : ''}`))),
359
- valid.length > 16 && last && h('circle', { cx: sx(last.x), cy: sy(last.y), r: 3, fill: color }))
360
- })))
361
- }
362
-
363
- // ---- bar -----------------------------------------------------------------
364
-
365
- function BarChart({ data, locale, height }) {
366
- const [ref, width] = useWidth()
367
- const keys = useMemo(() => {
368
- const seen = []
369
- for (const bar of data.bars) for (const key of Object.keys(bar.values ?? {})) if (!seen.includes(key)) seen.push(key)
370
- return seen
371
- }, [data])
372
- const multi = keys.length > 0
373
- const stacked = multi && data.stacked === true
374
- 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)))
375
- const peaks = data.bars.map((bar, i) => (multi && !stacked ? Math.max(0, ...keys.map(key => bar.values?.[key] ?? 0)) : totals[i]))
376
- const max = Math.max(1e-9, ...peaks, data.goal?.y ?? 0)
377
- const showValues = data.bars.length <= 14
378
- const top = showValues ? 16 : 6
379
- const bottom = 20
380
- const plotH = Math.max(10, height - top - bottom)
381
- const slot = width / data.bars.length
382
- const barW = Math.max(2, Math.min(44, slot * 0.62))
383
- const sy = v => top + plotH - (v / max) * plotH
384
- const labelEvery = Math.max(1, Math.ceil(data.bars.length / Math.max(1, Math.floor(width / 40))))
385
- const label = x => {
386
- const time = toTime(x)
387
- return Number.isFinite(time) ? formatDay(time, locale, 0) : String(x)
388
- }
389
- return h('div', null,
390
- h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
391
- h('line', { x1: 0, x2: width, y1: top + plotH + 0.5, y2: top + plotH + 0.5, className: 'cb-rule' }),
392
- data.goal && h('line', { x1: 0, x2: width, y1: sy(data.goal.y), y2: sy(data.goal.y), className: 'cb-goal' }),
393
- data.goal?.label && h('text', { x: width, y: sy(data.goal.y) - 4, className: 'cb-goalLabel', textAnchor: 'end' }, h('title', null, data.goal.label), fit(data.goal.label, width)),
394
- data.bars.map((bar, i) => {
395
- const cx = slot * i + slot / 2
396
- const tip = multi
397
- ? `${label(bar.x)}: ${keys.filter(k => bar.values?.[k] !== undefined).map(k => `${k} ${formatNumber(bar.values[k], locale)}`).join(', ')}`
398
- : `${label(bar.x)}: ${formatNumber(bar.value, locale)}${data.unit ? ` ${data.unit}` : ''}`
399
- let parts
400
- if (!multi) parts = [{ y0: 0, y1: Math.max(0, bar.value), color: toneColor(undefined, 1), x: cx - barW / 2, w: barW }]
401
- else if (stacked) {
402
- let base = 0
403
- parts = keys.map((key, k) => {
404
- const v = Math.max(0, bar.values?.[key] ?? 0)
405
- const part = { y0: base, y1: base + v, color: toneColor(undefined, k), x: cx - barW / 2, w: barW }
406
- base += v
407
- return part
408
- })
409
- } else {
410
- const each = barW / keys.length
411
- 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) }))
412
- }
413
- return h('g', { key: i },
414
- h('title', null, tip),
415
- parts.filter(p => p.y1 > p.y0).map((p, k) => h('rect', {
416
- key: k, x: p.x, width: p.w, y: sy(p.y1), height: Math.max(0.5, sy(p.y0) - sy(p.y1)),
417
- rx: Math.min(4, p.w / 3), fill: p.color, fillOpacity: multi ? 0.85 : 0.55,
418
- })),
419
- showValues && h('text', { x: cx, y: sy(peaks[i]) - 4, className: 'cb-barValue', textAnchor: 'middle' }, formatNumber(multi && !stacked ? peaks[i] : totals[i], locale, 1)),
420
- i % labelEvery === 0 && h('text', { x: Math.min(Math.max(cx, textWidth(label(bar.x)) / 2), width - textWidth(label(bar.x)) / 2), y: height - 4, className: 'cb-axis', textAnchor: 'middle' }, label(bar.x)))
421
- }))),
422
- multi && h(Legend, { items: keys.map((key, k) => ({ label: key, color: toneColor(undefined, k) })), locale }))
423
- }
424
-
425
- // ---- donut ---------------------------------------------------------------
426
-
427
- function arc(cx, cy, r, start, end) {
428
- const large = end - start > Math.PI ? 1 : 0
429
- const x0 = cx + r * Math.sin(start)
430
- const y0 = cy - r * Math.cos(start)
431
- const x1 = cx + r * Math.sin(end)
432
- const y1 = cy - r * Math.cos(end)
433
- return `M${x0.toFixed(2)},${y0.toFixed(2)}A${r},${r} 0 ${large} 1 ${x1.toFixed(2)},${y1.toFixed(2)}`
434
- }
435
-
436
- function Donut({ data, locale, height }) {
437
- const [ref, width] = useWidth()
438
- const total = data.segments.reduce((sum, s) => sum + s.value, 0)
439
- const narrow = width < 340
440
- const size = Math.max(90, Math.min(narrow ? 150 : 170, height - 8, narrow ? width * 0.6 : width * 0.42))
441
- const ring = size * 0.13
442
- const r = size / 2 - ring / 2
443
- let angle = 0
444
- const gap = data.segments.filter(s => s.value > 0).length > 1 ? 0.025 : 0
445
- const segments = data.segments.map((s, i) => {
446
- const sweep = total > 0 ? (s.value / total) * Math.PI * 2 : 0
447
- const seg = { ...s, color: toneColor(s.tone, i), start: angle + gap / 2, end: angle + sweep - gap / 2 }
448
- angle += sweep
449
- return seg
450
- })
451
- return h('div', { ref, className: `cb-donut${narrow ? ' cb-donutNarrow' : ''}` },
452
- width > 0 && h('div', { className: 'cb-donutRing', style: { width: size, height: size } },
453
- h('svg', { width: size, height: size, role: 'img' },
454
- h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-track)', strokeWidth: ring }),
455
- 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 },
456
- h('title', null, `${s.label}: ${formatNumber(s.value, locale)}${data.unit ? ` ${data.unit}` : ''}`)))),
457
- data.centre && h('div', { className: 'cb-donutCentre' },
458
- h('strong', null, data.centre.text),
459
- data.centre.sub && h('span', null, data.centre.sub))),
460
- h('table', { className: 'cb-donutTable' }, h('tbody', null, segments.map((s, i) => h('tr', { key: i },
461
- h('td', null, h('i', { style: { background: s.color } })),
462
- h('td', { className: 'cb-donutLabel' }, h(Trunc, { text: s.label })),
463
- h('td', { className: 'cb-num' }, formatNumber(s.value, locale)),
464
- h('td', { className: 'cb-num cb-dim' }, total > 0 ? `${Math.round((s.value / total) * 100)}%` : '–'))))))
465
- }
466
-
467
- // ---- list ----------------------------------------------------------------
468
-
469
- function CheckGlyph({ checked }) {
470
- return h('svg', { className: 'cb-check', 'data-checked': checked ? 'true' : 'false', width: 18, height: 18, viewBox: '0 0 18 18', 'aria-hidden': true },
471
- h('rect', { x: 1, y: 1, width: 16, height: 16, rx: 4.5 }),
472
- checked && h('path', { d: 'M5 9.4l2.6 2.5L13 6.4' }))
473
- }
474
-
475
- function ProgressRing({ progress, size }) {
476
- const ring = Math.max(6, size * 0.12)
477
- const r = size / 2 - ring / 2
478
- const share = progress.total > 0 ? Math.min(1, progress.done / progress.total) : 0
479
- return h('div', { className: 'cb-donutRing', style: { width: size, height: size } },
480
- h('svg', { width: size, height: size, role: 'img', 'aria-label': `${progress.done}/${progress.total}` },
481
- h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-track)', strokeWidth: ring }),
482
- share >= 1
483
- ? h('circle', { cx: size / 2, cy: size / 2, r, fill: 'none', stroke: 'var(--cb-accent)', strokeWidth: ring })
484
- : 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' })),
485
- h('div', { className: 'cb-donutCentre' },
486
- h('strong', { style: { fontSize: Math.round(size * 0.19) } }, `${progress.done}/${progress.total}`),
487
- progress.label && size >= 90 && h('span', null, progress.label)))
488
- }
489
-
490
- function ListCard({ data, locale, t, rowActions }) {
491
- const [ref, width] = useWidth()
492
- const checkable = data.rows.some(row => 'checked' in row)
493
- const rows = data.rows.length === 0
494
- ? h('p', { className: 'cb-muted' }, data.empty ?? t('listEmpty'))
495
- : h('ul', { className: 'cb-list' }, data.rows.map((row, i) =>
496
- h('li', { key: i, className: row.checked ? 'cb-done' : undefined },
497
- checkable && h('span', { className: 'cb-checkBox', role: 'img', 'aria-label': t(row.checked ? 'checked' : 'unchecked') }, h(CheckGlyph, { checked: row.checked === true })),
498
- h('div', { className: 'cb-listText' },
499
- h(Trunc, { className: 'cb-listTitle', lines: 2, text: row.title }),
500
- row.sub && h(Trunc, { className: 'cb-listSub', lines: 2, text: row.sub })),
501
- (row.date || row.chip) && h('span', { className: 'cb-listMeta' },
502
- row.date && h('span', { className: 'cb-listDate' }, formatDay(toTime(row.date), locale, 0)),
503
- row.chip && h(Chip, row.chip)),
504
- row.actions && rowActions && h('span', { className: 'cb-rowActions' }, rowActions(i, row.actions, listRowLine(row))))))
505
- if (!data.progress) return rows
506
- // Beside the rows when there is room for both, else a small ring with its count above them.
507
- const wide = width >= 460
508
- return h('div', { ref, className: `cb-listWrap${wide ? '' : ' cb-listWrapNarrow'}` },
509
- width > 0 && (wide
510
- ? h(ProgressRing, { progress: data.progress, size: Math.min(140, Math.round(width * 0.28)) })
511
- : h('div', { className: 'cb-progressLine' },
512
- h(ProgressRing, { progress: { ...data.progress, label: undefined }, size: 40 }),
513
- data.progress.label && h('span', null, data.progress.label))),
514
- h('div', { className: 'cb-listMain' }, rows))
515
- }
516
-
517
- // ---- timeline ------------------------------------------------------------
518
-
519
- const KIND_TONE = { due: 'warn', health: 'ok', event: 'accent', home: 'muted', money: 'ok', travel: 'accent' }
520
-
521
- function PlaneGlyph({ x, y, color }) {
522
- return h('path', {
523
- transform: `translate(${x - 7},${y - 7}) scale(0.58)`,
524
- 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',
525
- fill: color,
526
- })
527
- }
528
-
529
- function Timeline({ data, locale, t }) {
530
- const [ref, width] = useWidth()
531
- const from = toTime(data.from)
532
- const to = toTime(data.to)
533
- const days = Math.max(1, Math.round((to - from) / 86400000))
534
- const pad = 14
535
- const plotW = Math.max(10, width - pad * 2)
536
- const sx = time => pad + ((time - from) / (to - from)) * plotW
537
- const now = Date.now()
538
- const dayEvery = Math.max(1, Math.ceil(days / Math.max(1, Math.floor(plotW / 44))))
539
- const ticks = []
540
- for (let i = 0; i <= days; i += dayEvery) ticks.push(from + i * 86400000)
541
-
542
- // Points get label rows so neighbours don't overlap.
543
- 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)
544
- const rowEnds = []
545
- const placed = points.map(p => {
546
- const half = Math.min(90, textWidth(p.label)) / 2 + 4
547
- const x = sx(p.time)
548
- let row = rowEnds.findIndex(end => x - half > end)
549
- if (row === -1) { row = rowEnds.length; rowEnds.push(0) }
550
- rowEnds[row] = x + half
551
- return { ...p, x, row }
552
- })
553
- const labelRows = Math.max(1, rowEnds.length)
554
- const tickH = 18
555
- const pointY = tickH + 16
556
- const labelTop = pointY + 18
557
- const spansTop = labelTop + labelRows * 15 + 8
558
- 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)
559
- const height = spansTop + spans.length * 36 + 4
560
-
561
- return h('div', { ref, className: 'cb-chart', style: { height } }, width > 0 && h('svg', { width, height, role: 'img' },
562
- ticks.map((time, i) => h('g', { key: i },
563
- h('line', { x1: sx(time), x2: sx(time), y1: tickH, y2: height, className: 'cb-dayLine' }),
564
- h('text', { x: sx(time), y: 11, className: 'cb-axis', textAnchor: 'middle' }, formatDay(time, locale, 0)))),
565
- now >= from && now <= to && h('line', { x1: sx(now), x2: sx(now), y1: tickH - 2, y2: height, className: 'cb-today' }),
566
- placed.map((p, i) => {
567
- const color = toneColor(p.tone ?? KIND_TONE[p.kind] ?? 'accent')
568
- const text = fit(p.label, 90)
569
- return h('g', { key: i },
570
- h('title', null, `${formatDay(p.time, locale, 0)} · ${p.label}`),
571
- p.kind === 'travel' ? h(PlaneGlyph, { x: p.x, y: pointY, color }) : h('circle', { cx: p.x, cy: pointY, r: 5, fill: color }),
572
- p.row > 0 && h('line', { x1: p.x, x2: p.x, y1: pointY + 8, y2: labelTop + p.row * 15 - 9, className: 'cb-leader' }),
573
- h('text', { x: p.x, y: labelTop + p.row * 15, className: 'cb-pointLabel', textAnchor: 'middle' }, text))
574
- }),
575
- spans.map((s, i) => {
576
- const x = sx(s.a)
577
- const w = Math.max(6, sx(s.b) - x)
578
- const y = spansTop + i * 36
579
- const full = `${s.label} · ${formatDay(toTime(s.from), locale, 0)} – ${formatDay(toTime(s.to), locale, 0)}`
580
- return h('g', { key: `s${i}` },
581
- h('title', null, full),
582
- h('rect', { x, y, width: w, height: 12, rx: 6, fill: toneColor(s.tone ?? 'accent'), fillOpacity: 0.22 }),
583
- h('text', { x: Math.min(Math.max(x + w / 2, pad + Math.min(plotW, textWidth(full) * 0.55) / 2), width - pad - Math.min(plotW, textWidth(full) * 0.55) / 2), y: y + 26, className: 'cb-spanLabel', textAnchor: 'middle' }, fit(full, plotW)))
584
- })))
585
- }
586
-
587
- // ---- status --------------------------------------------------------------
588
-
589
- function Spark({ values, color }) {
590
- const [ref, width] = useWidth()
591
- const height = 22
592
- const min = Math.min(...values)
593
- const max = Math.max(...values)
594
- 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('')
595
- return h('div', { ref, className: 'cb-spark' }, width > 0 && h('svg', { width, height, 'aria-hidden': true },
596
- h('path', { d, fill: 'none', stroke: color, strokeWidth: 1.5, strokeLinejoin: 'round', strokeLinecap: 'round' })))
597
- }
598
-
599
- function StatusCard({ data, locale, rowActions }) {
600
- const sparks = data.rows.some(row => row.spark)
601
- const hasActions = data.rows.some(row => row.actions?.length > 0)
602
- return h('ul', { className: `cb-status${sparks ? ' cb-statusSparks' : ''}${hasActions ? ' cb-statusActions' : ''}` }, data.rows.map((row, i) =>
603
- h('li', { key: i },
604
- h('i', { className: 'cb-dot', style: { background: toneColor(row.tone) } }),
605
- h(Trunc, { as: 'span', className: 'cb-statusLabel', text: row.label }),
606
- h('span', { className: 'cb-statusValue' },
607
- h('span', { className: 'cb-statusNum', style: row.tone === 'bad' || row.tone === 'warn' ? { color: toneColor(row.tone) } : undefined }, formatNumber(row.value, locale)),
608
- row.sub && h(Trunc, { as: 'small', className: 'cb-statusSub', lines: 2, text: row.sub })),
609
- sparks && (row.spark ? h(Spark, { values: row.spark, color: toneColor(row.tone === 'ok' ? 'accent' : row.tone) }) : h('span', { className: 'cb-spark' })),
610
- hasActions && h('span', { className: 'cb-rowActions' }, rowActions && row.actions ? rowActions(i, row.actions, statusRowLine(row, locale)) : null))))
611
- }
612
-
613
- // ---- what a chat quotes ----------------------------------------------------
614
-
615
- function withUnit(value, unit, locale) {
616
- return `${formatNumber(value, locale)}${unit ? ` ${unit}` : ''}`
617
- }
618
-
619
- function statLines(data, locale) {
620
- 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}` : ''}`)
621
- }
622
-
623
- function listRowLine(row) {
624
- const box = 'checked' in row ? (row.checked ? '☑ ' : '☐ ') : ''
625
- return `${box}${row.title}${row.sub ? ` · ${row.sub}` : ''}${row.date ? ` · ${row.date}` : ''}${row.chip ? ` [${row.chip.text}]` : ''}`
626
- }
627
-
628
- function statusRowLine(row, locale) {
629
- return `${row.label}: ${formatNumber(row.value, locale)}${row.sub ? ` · ${row.sub}` : ''}`
630
- }
631
-
632
- /** A few plain lines saying what a card shows, for the agent. */
633
- function summaryLines(card, locale, t) {
634
- const data = card.data
635
- const lines = card.stat ? statLines(card.stat, locale) : []
636
- switch (card.type) {
637
- case 'stat': return statLines(data, locale)
638
- case 'line':
639
- for (const series of data.series) {
640
- const last = [...series.points].reverse().find(p => typeof p.y === 'number')
641
- if (last) lines.push(t('summary.latest', { name: series.name || t('summary.latestName'), value: withUnit(last.y, data.unit, locale), x: last.x, n: series.points.length, from: series.points[0].x }))
642
- }
643
- if (data.goal?.y !== undefined) lines.push(t('summary.goal', { value: withUnit(data.goal.y, data.unit, locale) }))
644
- return lines
645
- case 'bar':
646
- 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)}`))
647
- case 'donut': {
648
- const total = data.segments.reduce((sum, s) => sum + s.value, 0)
649
- return lines.concat(data.segments.map(s => `${s.label}: ${withUnit(s.value, data.unit, locale)}${total > 0 ? ` (${Math.round((s.value / total) * 100)}%)` : ''}`))
650
- }
651
- case 'list':
652
- return lines.concat(data.progress ? [t('summary.progress', data.progress)] : [], data.rows.slice(0, 15).map(listRowLine))
653
- case 'timeline':
654
- return lines.concat((data.points ?? []).map(p => `${p.date}: ${p.label}`), (data.spans ?? []).map(s => `${s.from} – ${s.to}: ${s.label}`))
655
- case 'status':
656
- return lines.concat(data.rows.map(row => statusRowLine(row, locale)))
657
- default: return lines
658
- }
659
- }
660
-
661
- /** Press states by action id for the card (row undefined) or one row: the latest press wins. */
662
- function statesOf(presses, row) {
663
- const states = {}
664
- for (const press of presses ?? []) if (press.row === row) states[press.id] = press.state
665
- return states
666
- }
667
-
668
- // ---- card frame ----------------------------------------------------------
669
-
670
- const CHART_HEIGHT = { 1: 150, 2: 360, 3: 560 }
671
- /** One column (a phone): taller cards would only scroll further, so charts stay moderate. */
672
- const CHART_HEIGHT_NARROW = { 1: 150, 2: 220, 3: 260 }
673
-
674
- function CardBody({ card, size, narrow, locale, t, rowActions }) {
675
- const height = (narrow ? CHART_HEIGHT_NARROW : CHART_HEIGHT)[size.h] - (card.stat ? 40 : 0)
676
- const data = card.data
677
- switch (card.type) {
678
- case 'stat': return h(StatBlock, { data, locale })
679
- case 'line': return h(LineChart, { data, locale, height })
680
- case 'bar': return h(BarChart, { data, locale, height: Math.min(height, 130 + (size.h - 1) * 200) })
681
- case 'donut': return h(Donut, { data, locale, height: Math.max(height, 160) })
682
- case 'list': return h(ListCard, { data, locale, t, rowActions })
683
- case 'timeline': return h(Timeline, { data, locale, t })
684
- case 'status': return h(StatusCard, { data, locale, rowActions })
685
- default: return null
686
- }
687
- }
688
-
689
- function LinkIcon() {
690
- 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' },
691
- h('path', { d: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5' }))
692
- }
693
-
694
- function Card({ entry, boardId, assistant, columns, now, active, locale, t, actions, press }) {
695
- const size = { w: Math.min(entry.w ?? 1, columns), h: entry.h ?? 1 }
696
- const style = { gridColumn: `span ${size.w}`, gridRow: size.h > 1 && columns > 1 ? `span ${size.h}` : undefined }
697
- if (!entry.card) {
698
- return h('section', { className: 'cb-card cb-cardError', style },
699
- h('header', { className: 'cb-cardHead' }, h('h3', { title: entry.id }, entry.id)),
700
- h('p', { className: 'cb-errorText' }, t('cardError')),
701
- h('ul', { className: 'cb-problems' }, (entry.problems ?? []).map((p, i) => h('li', { key: i }, p))))
702
- }
703
- const card = pickCard(entry.card, active)
704
- const updated = Date.parse(card.updatedAt)
705
- const age = Math.max(0, (now - updated) / 1000)
706
- const stale = typeof card.staleAfter === 'number' && age > card.staleAfter
707
- const external = card.link && /^https?:/i.test(card.link)
708
- // What a chat is about: the card as a few lines, or one row of it.
709
- const about = (row, rowLine) => ({
710
- source: OWNER,
711
- title: card.title,
712
- lines: row === undefined ? summaryLines(card, locale, t).slice(0, 15) : [rowLine],
713
- context: { board: boardId, card: entry.id, ...(row === undefined ? {} : { row }), type: card.type, updatedAt: card.updatedAt },
714
- })
715
- // A chat button without its own label says "Ask <assistant>" when the board names one.
716
- const askName = assistant ? t('action.chatNamed', { name: assistant }) : undefined
717
- const named = list => (assistant ? list?.map(action => (action.kind === 'chat' && action.label === undefined ? { ...action, label: askName } : action)) : list)
718
- const rowActions = actions && ((row, list, line) => h(actions.ActionBar, {
719
- actions: named(list),
720
- states: statesOf(entry.presses, row),
721
- compact: true,
722
- about: about(row, line),
723
- onPress: (action, extra) => press(action, extra, { card: entry.id, row }),
724
- }))
725
- return h('section', { className: `cb-card${stale ? ' cb-cardStale' : ''}`, style, 'data-type': card.type },
726
- h('header', { className: 'cb-cardHead' },
727
- h(Trunc, { as: 'h3', text: card.title }),
728
- stale && h('span', { className: 'cb-staleChip', title: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(updated) }, t('stale', { age: formatAge(age, locale) })),
729
- 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)),
730
- actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: { kind: 'chat', id: '_chat', label: askName }, compact: true, about: about() }))),
731
- card.stat && h(StatBlock, { data: card.stat, locale, compact: true }),
732
- h('div', { className: 'cb-cardBody' }, h(CardBody, { card, size, narrow: columns === 1, locale, t, rowActions })),
733
- actions && card.actions && h('footer', { className: 'cb-cardActions' }, h(actions.ActionBar, {
734
- actions: named(card.actions),
735
- states: statesOf(entry.presses, undefined),
736
- about: about(),
737
- onPress: (action, extra) => press(action, extra, { card: entry.id }),
738
- })))
739
- }
740
-
741
- // ---- page ----------------------------------------------------------------
742
-
743
- /** A failed request: its status says what went wrong; the server's own words stay out of the page. */
744
- function requestError(status, body) {
745
- const error = new Error(body?.error ?? `HTTP ${status}`)
746
- error.status = status
747
- return error
748
- }
749
-
750
- async function getJson(path, etag) {
751
- const response = await fetch(api(path), { cache: 'no-store', credentials: 'same-origin', headers: etag ? { 'if-none-match': etag } : {} })
752
- if (response.status === 304) return { notModified: true }
753
- let body = null
754
- try { body = await response.json() } catch { /* not JSON */ }
755
- if (!response.ok) throw requestError(response.status, body)
756
- return { body, etag: response.headers.get('etag') }
757
- }
758
-
759
- const ERROR_KEYS = { 403: 'error.forbidden', 404: 'error.notFound', 409: 'error.gone', 503: 'error.noProvider' }
760
- const errorText = (error, t) => (error.status === undefined ? error.message : t(ERROR_KEYS[error.status] ?? 'error.http', { status: error.status }))
761
-
762
- function useColumns() {
763
- const [ref, width] = useWidth()
764
- return [ref, width >= 1400 ? 4 : width >= 980 ? 3 : width >= 620 ? 2 : 1]
765
- }
766
-
767
- function BoardsPage() {
768
- const { active, intl: locale, ready, t } = useActiveLocale()
769
- const [boards, setBoards] = useState(null)
770
- const [listError, setListError] = useState(null)
771
- const [selected, setSelected] = useState(() => { try { return localStorage.getItem(STORE_KEY) } catch { return null } })
772
- const [board, setBoard] = useState(null)
773
- const [boardError, setBoardError] = useState(null)
774
- const [refreshFailed, setRefreshFailed] = useState(false)
775
- const [pollSeconds, setPollSeconds] = useState(30)
776
- const [now, setNow] = useState(() => Date.now())
777
- const etag = useRef(null)
778
- const [gridRef, columns] = useColumns()
779
- const actions = useButtons()
780
- const currentRef = useRef(null)
781
- // The buttons ask for words at render time, so a language switch reaches them without rebuilding them.
782
- const translateRef = useRef(t)
783
- translateRef.current = t
784
-
785
- const loadList = useCallback(async () => {
786
- try {
787
- const { body } = await getJson('boards')
788
- setBoards(body.boards)
789
- setPollSeconds(body.pollSeconds ?? 30)
790
- setListError(null)
791
- } catch (error) {
792
- setListError(error)
793
- }
794
- }, [])
795
-
796
- const current = boards?.some(b => b.id === selected) ? selected : boards?.[0]?.id ?? null
797
-
798
- const loadBoard = useCallback(async (id, fresh) => {
799
- if (!id) return
800
- try {
801
- const result = await getJson(`board?id=${encodeURIComponent(id)}`, fresh ? null : etag.current)
802
- setRefreshFailed(false)
803
- setBoardError(null)
804
- if (result.notModified) return
805
- etag.current = result.etag
806
- setBoard(result.body)
807
- } catch (error) {
808
- if (error.status === 403 || error.status === 404) { setBoard(null); setBoardError(error); loadList(); return }
809
- setRefreshFailed(true)
810
- }
811
- }, [loadList])
812
-
813
- useEffect(() => { loadList() }, [loadList])
814
-
815
- // A press of done, snooze or event goes to this plugin's server, which checks it and records it.
816
- const press = useCallback(async (action, extra, target) => {
817
- const response = await fetch(api('action'), {
818
- method: 'POST',
819
- credentials: 'same-origin',
820
- headers: { 'content-type': 'application/json' },
821
- body: JSON.stringify({ board: currentRef.current, ...target, id: action.id, ...extra }),
822
- })
823
- const body = await response.json().catch(() => null)
824
- if (!response.ok) throw new Error(errorText(requestError(response.status, body), translateRef.current))
825
- loadBoard(currentRef.current, false)
826
- return body
827
- }, [loadBoard])
828
-
829
- useEffect(() => {
830
- currentRef.current = current
831
- if (!current) return undefined
832
- etag.current = null
833
- setBoard(prev => (prev?.id === current ? prev : null))
834
- loadBoard(current, true)
835
- let ticks = 0
836
- const tick = () => {
837
- if (document.visibilityState !== 'visible') return
838
- setNow(Date.now())
839
- loadBoard(current, false)
840
- if (++ticks % 10 === 0) loadList()
841
- }
842
- const timer = setInterval(tick, Math.max(5, pollSeconds) * 1000)
843
- const onVisible = () => { if (document.visibilityState === 'visible') { setNow(Date.now()); loadBoard(current, false); loadList() } }
844
- document.addEventListener('visibilitychange', onVisible)
845
- return () => { clearInterval(timer); document.removeEventListener('visibilitychange', onVisible) }
846
- }, [current, pollSeconds, loadBoard, loadList])
847
-
848
- const choose = id => {
849
- setSelected(id)
850
- try { localStorage.setItem(STORE_KEY, id) } catch { /* private mode */ }
851
- }
852
-
853
- const newest = board?.cards?.reduce((max, entry) => {
854
- const time = entry.card ? Date.parse(entry.card.updatedAt) : NaN
855
- return Number.isFinite(time) && time > max ? time : max
856
- }, 0)
857
-
858
- const titleOf = entry => pickText(entry.title, active)
859
- const tabs = boards && boards.length > 1 && h('div', { className: 'cb-tabs', role: 'tablist' }, boards.map(b =>
860
- h('button', { key: b.id, type: 'button', role: 'tab', 'aria-selected': b.id === current, className: 'cb-tab', title: titleOf(b), onClick: () => choose(b.id) }, h('span', null, titleOf(b)))))
861
-
862
- if (!ready) return h('div', { className: 'cb-page' })
863
-
864
- let content
865
- if (listError) content = h('p', { className: 'cb-notice' }, errorText(listError, t))
866
- else if (boards === null) content = h('p', { className: 'cb-muted' }, t('loading'))
867
- 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')))
868
- else if (boardError) content = h('p', { className: 'cb-notice' }, errorText(boardError, t))
869
- else if (!board) content = h('p', { className: 'cb-muted' }, t('loading'))
870
- else content = h(React.Fragment, null,
871
- 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)))),
872
- board.cards.length === 0 && h('p', { className: 'cb-muted' }, t('noCards')),
873
- h('div', { className: 'cb-grid', style: { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } },
874
- board.cards.map(entry => h(Card, { key: entry.id, entry, boardId: board.id, assistant: board.assistant, columns, now, active, locale, t, actions, press }))))
875
-
876
- return h('div', { className: 'cb-page' },
877
- h('div', { className: 'cb-content', ref: gridRef },
878
- h('div', { className: 'cb-heading' },
879
- h('h1', null, boards?.length === 1 ? titleOf(boards[0]) : t('title')),
880
- h('p', { className: 'cb-sub' },
881
- newest > 0 ? t('updated', { time: formatUpdated(newest, locale) }) : ' ',
882
- refreshFailed && h('span', { className: 'cb-warnText' }, ` · ${t('refreshFailed')}`))),
883
- tabs,
884
- content))
885
- }
886
-
887
- function SidebarIcon({ size }) {
888
- const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round', fill: 'none' }
889
- return h('svg', { width: size, height: size, viewBox: '0 0 16 16', 'aria-hidden': true, focusable: 'false' },
890
- h('rect', { x: 1.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
891
- h('rect', { x: 8.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
892
- h('rect', { x: 1.75, y: 8.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
893
- h('path', { d: 'M9 13.5l1.6-2 1.4 1 2-2.8', ...stroke }))
894
- }
895
-
896
- const CSS = `
897
- .cb-page{overflow-x:hidden;--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}
3
+ id: "@soffits/dsh-card-board",
4
+ factory: (require) => {
5
+ var module = { exports: {} }
6
+ var exports = module.exports
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+
25
+ // src/client/index.js
26
+ var index_exports = {};
27
+ __export(index_exports, {
28
+ apply: () => apply,
29
+ inject: () => inject
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+ var import_react9 = require("react");
33
+
34
+ // src/client/look.js
35
+ var STYLE_ID = "dsh-card-board-style";
36
+ var CSS = `
37
+ .cb-page{overflow-x:hidden;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}
898
38
  .cb-content{box-sizing:border-box;max-width:1680px;margin:0 auto;padding:0 clamp(16px,3.2vw,40px) 48px}
899
39
  .cb-heading{padding-top:28px;margin-bottom:14px}
900
40
  [data-platform=darwin] .cb-heading{padding-top:calc(28px + var(--dsh-frame-top-clearance,0px))}
901
- .cb-heading h1{margin:0;font-size:22px;font-weight:600;line-height:30px}
902
- .cb-sub{margin:2px 0 0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}
903
- .cb-warnText{color:var(--cb-warn)}
904
- .cb-tabs{display:flex;flex-wrap:wrap;gap:0 4px;margin:0 0 18px;border-bottom:.5px solid var(--dsw-alias-border-l2)}
905
- .cb-tab{position:relative;flex:0 1 auto;min-width:40px;justify-content:center;display:inline-flex;align-items:center;min-width:0;max-width:100%;min-height:40px;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}
906
- .cb-tab span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:min(60vw,260px)}
907
- .cb-tab[aria-selected=true]{color:var(--dsw-alias-label-primary);font-weight:500}
908
- .cb-tab[aria-selected=true]:after{content:"";position:absolute;left:10px;right:10px;bottom:-.5px;height:2px;border-radius:2px;background:var(--cb-accent)}
909
- @media (hover:hover){.cb-tab:hover{color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}}
41
+ .cb-heading h1{margin:0;font-size:20px;font-weight:500;line-height:28px}
42
+ .cb-sub{margin-top:4px;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}
43
+ .cb-tabs{display:flex;flex-wrap:wrap;gap:6px 8px;margin:0 0 18px}
910
44
  .cb-grid{display:grid;gap:14px;grid-auto-flow:row dense;align-items:stretch}
911
- .cb-card{container-type:inline-size;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)}
912
- .cb-cardHead{display:flex;align-items:center;gap:8px;min-height:22px}
45
+ .cb-card{container-type:inline-size;box-sizing:border-box;min-width:0;display:flex;flex-direction:column;gap:12px;padding:16px 18px 18px;border-radius:16px;background:var(--dsw-alias-bg-base);box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l2)}
46
+ .cb-cardHead{display:flex;align-items:center;gap:10px;min-height:28px}
913
47
  .cb-cardHead h3{flex:1;min-width:0;margin:0;font-size:15px;font-weight:600;line-height:22px}
914
48
  .cb-trunc{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
915
49
  .cb-trunc2{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}
916
50
  .cb-truncOpen{white-space:normal;display:block;overflow:visible;overflow-wrap:anywhere}
917
51
  h3.cb-truncOpen{overflow:visible}
918
52
  .cb-cardChat{display:inline-flex;margin:-5px -8px -5px 0}
919
- .cb-cardActions{padding-top:4px}
920
- .cb-rowActions{display:inline-flex;flex-wrap:wrap;justify-content:flex-end;min-width:0}
921
- .cb-statusActions{grid-template-columns:8px fit-content(45%) minmax(0,1fr) auto}
922
- .cb-statusSparks.cb-statusActions{grid-template-columns:8px fit-content(40%) minmax(0,1fr) minmax(56px,1.2fr) auto}
923
- .cb-cardLink{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;margin:-5px 0;border-radius:6px;color:var(--dsw-alias-label-tertiary)}
53
+ .cb-cardLink{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;margin:-5px 0;border-radius:8px;color:var(--dsw-alias-label-tertiary)}
924
54
  @media (hover:hover){.cb-cardLink:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
925
- .cb-staleChip{flex:0 1 auto;min-width:0;max-width:45%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;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)}
55
+ .cb-stale{flex:0 1 auto;min-width:0;display:inline-flex}
926
56
  .cb-cardStale .cb-cardBody,.cb-cardStale .cb-stats{opacity:.62}
927
57
  .cb-cardBody{flex:1;min-width:0;display:flex;flex-direction:column;justify-content:flex-start}
928
- .cb-cardError{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--cb-bad) 35%,transparent)}
929
- .cb-errorText{margin:0;color:var(--cb-bad);font-size:13px}
58
+ .cb-cardActions{padding-top:2px}
59
+ .cb-cardError{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--dsw-alias-state-error-primary) 35%,transparent)}
60
+ .cb-errorText{margin:0;color:var(--dsw-alias-state-error-primary);font-size:13px}
930
61
  .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}
931
- .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}
62
+ .cb-notice{margin:0 0 14px;padding:10px 14px;border-radius:12px;background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 10%,transparent);color:var(--dsw-alias-label-secondary);font-size:13px}
932
63
  .cb-muted{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px}
933
64
  .cb-empty{padding:48px 0;text-align:center}
934
65
  .cb-emptyTitle{margin:0 0 4px;color:var(--dsw-alias-label-secondary)}
66
+
67
+ /* the summary: a full-width card with the day's line, a sentence and chips */
68
+ .cb-card-summary{flex-direction:row;align-items:flex-start;gap:16px;padding:18px 20px;background:linear-gradient(135deg,color-mix(in srgb,var(--dsw-alias-state-business-primary) 8%,var(--dsw-alias-bg-base)),var(--dsw-alias-bg-base) 70%)}
69
+ .cb-summaryMain{flex:1;min-width:0;display:flex;flex-direction:column;gap:12px}
70
+ .cb-summaryAside{display:flex;align-items:center;gap:8px}
71
+ .cb-summaryLine{display:flex;align-items:center;gap:8px;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
72
+ .cb-summaryText{margin:0;font-size:17px;font-weight:500;line-height:26px;letter-spacing:-.005em;text-wrap:pretty}
73
+ .cb-chips{display:flex;flex-wrap:wrap;gap:6px}
74
+
75
+ /* the countdown: the big number, then the stops with the next one marked */
76
+ .cb-countdown{display:flex;flex-direction:column;gap:14px}
77
+ .cb-countdownHead{display:flex;flex-wrap:wrap;align-items:center;gap:4px 18px}
78
+ .cb-countdownText{color:var(--dsw-alias-label-secondary);font-size:13px;line-height:19px}
79
+ .cb-track{position:relative;display:grid;grid-auto-flow:column;grid-auto-columns:1fr;margin:0;padding:0;list-style:none}
80
+ .cb-track:before{content:"";position:absolute;left:9px;right:9px;top:8px;height:2px;border-radius:2px;background:var(--dsw-alias-border-l2)}
81
+ .cb-track li{position:relative;min-width:0;padding-right:8px}
82
+ .cb-track i{display:block;width:18px;height:18px;margin-bottom:6px;border-radius:50%;background:var(--dsw-alias-bg-base);box-shadow:inset 0 0 0 2px var(--dsw-alias-border-l4,var(--dsw-alias-border-l3))}
83
+ .cb-track li[data-state=next] i{box-shadow:inset 0 0 0 5px var(--dsw-alias-state-business-primary)}
84
+ .cb-track li[data-state=past] i{background:var(--dsw-alias-border-l3);box-shadow:none}
85
+ .cb-track b{display:block;font-size:13px;font-weight:600;line-height:19px;font-variant-numeric:tabular-nums}
86
+ .cb-track span{display:block;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:17px;overflow-wrap:anywhere}
87
+ .cb-track li[data-state=past] b,.cb-track li[data-state=past] span{color:var(--dsw-alias-label-tertiary)}
88
+
89
+ /* stats */
90
+ .cb-stats{display:flex;flex-wrap:wrap;gap:14px 30px}
91
+ .cb-stat{min-width:0;display:flex;flex-direction:column;gap:2px}
92
+ .cb-statWide{flex:1 1 100%}
93
+ .cb-statLabel{display:flex;align-items:center;gap:6px;min-width:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
94
+ .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}
95
+ .cb-statValue small{font-size:14px;font-weight:500;color:var(--dsw-alias-label-secondary)}
96
+ .cb-statsCompact .cb-statValue{font-size:26px;line-height:32px}
97
+ .cb-delta{display:flex;align-items:center;gap:3px;font-size:12px;font-weight:500;line-height:18px}
98
+ .cb-statSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
99
+ .cb-statProgress{display:flex;flex-direction:column;gap:4px;min-width:180px;margin-top:4px}
100
+ .cb-strip{display:flex;justify-content:space-between;gap:4px;margin:10px 0 0;padding:0;list-style:none}
101
+ .cb-strip li{display:flex;flex-direction:column;align-items:center;gap:3px;min-width:0;color:var(--dsw-alias-label-tertiary);font-size:11px;font-variant-numeric:tabular-nums}
102
+ .cb-strip b{color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500}
103
+ .cb-strip li[data-on=true],.cb-strip li[data-on=true] b{color:var(--dsw-alias-state-business-primary)}
104
+ /* a chart card with headline numbers: side by side when there is room */
105
+ .cb-split{display:flex;flex-direction:column;gap:12px}
106
+ @container (width>=640px){.cb-split{display:grid;grid-template-columns:minmax(0,max-content) minmax(0,1fr);align-items:center;gap:28px}.cb-split .cb-stats{display:grid;grid-template-columns:repeat(2,max-content);gap:14px 40px}}
107
+
108
+ /* rows of lists and status cards */
109
+ .cb-list{display:flex;flex-direction:column;gap:10px}
110
+ .cb-progress{display:flex;align-items:center;gap:14px}
111
+ .cb-progressLabel{font-weight:600}
112
+ .cb-rows{list-style:none;margin:0;padding:0}
113
+ .cb-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px 11px;padding:9px 6px;border-top:.5px solid var(--dsw-alias-border-l2);border-radius:10px}
114
+ .cb-rows .cb-row:first-child{border-top:0}
115
+ .cb-row+.cb-row{border-top-left-radius:0;border-top-right-radius:0}
116
+ .cb-rowNow{background:color-mix(in srgb,var(--dsw-alias-state-business-primary) 6%,transparent)}
117
+ .cb-rowText{flex:1;min-width:0}
118
+ .cb-rowTitle{display:flex;align-items:center;gap:6px;min-width:0;font-size:14px;line-height:20px}
119
+ .cb-rowSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
120
+ .cb-done .cb-rowTitle{color:var(--dsw-alias-label-tertiary)}
121
+ .cb-rowMeta{display:flex;align-items:center;gap:8px;min-width:0;max-width:45%}
122
+ .cb-rowMeta>*{min-width:0;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
123
+ .cb-when{flex:none;color:var(--dsw-alias-label-tertiary);font-size:12px;font-variant-numeric:tabular-nums}
124
+ .cb-rowActions{display:inline-flex;flex-wrap:wrap;justify-content:flex-end;min-width:0}
125
+ .cb-rowSteps{flex-basis:100%;min-width:0;padding-left:41px}
126
+ .cb-check{flex:none;display:inline-grid;place-items:center;width:18px;height:18px;border-radius:5px;color:#fff;box-shadow:inset 0 0 0 1.5px var(--dsw-alias-border-l4,var(--dsw-alias-border-l3))}
127
+ .cb-check[data-checked=true]{background:var(--dsw-alias-state-success-primary);box-shadow:none}
128
+ .cb-dotSlot{flex:none;display:inline-grid;place-items:center;width:28px}
129
+ .cb-statusSpark{flex:0 1 90px;min-width:48px}
130
+ .cb-statusValue{flex:none;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
131
+
132
+ /* charts */
935
133
  .cb-chart{position:relative;width:100%;min-width:0}
936
134
  .cb-chart svg,.cb-donutRing svg{display:block;overflow:visible}
937
135
  .cb-rule{stroke:var(--dsw-alias-border-l2);stroke-width:1;shape-rendering:crispEdges}
@@ -942,18 +140,10 @@ h3.cb-truncOpen{overflow:visible}
942
140
  .cb-markerLabel{fill:var(--dsw-alias-label-tertiary);font-size:11px}
943
141
  .cb-barValue{fill:var(--dsw-alias-label-secondary);font-size:11px}
944
142
  .cb-dayLine{stroke:var(--dsw-alias-border-l1,var(--dsw-alias-border-l2));stroke-dasharray:2 4}
945
- .cb-today{stroke:var(--cb-accent);stroke-width:1.2;stroke-opacity:.6}
143
+ .cb-today{stroke:var(--dsw-alias-state-business-primary);stroke-width:1.2;stroke-opacity:.6}
946
144
  .cb-leader{stroke:var(--dsw-alias-border-l3)}
947
145
  .cb-pointLabel{fill:var(--dsw-alias-label-secondary);font-size:12px}
948
146
  .cb-spanLabel{fill:var(--dsw-alias-label-tertiary);font-size:12px}
949
- .cb-stats{display:flex;flex-wrap:wrap;gap:12px 28px}
950
- .cb-stat{min-width:0}
951
- .cb-statLabel{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
952
- .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}
953
- .cb-statValue small{font-size:15px;font-weight:500;color:var(--dsw-alias-label-secondary)}
954
- .cb-statsCompact .cb-statValue{font-size:26px;line-height:32px}
955
- .cb-delta{font-style:normal;font-size:12px;font-weight:500}
956
- .cb-statSub{color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:20px}
957
147
  .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}
958
148
  .cb-legend li{display:inline-flex;align-items:center;gap:6px;min-width:0;max-width:100%}
959
149
  .cb-legend i,.cb-donutTable i{display:inline-block;width:8px;height:8px;border-radius:50%}
@@ -971,142 +161,1254 @@ h3.cb-truncOpen{overflow:visible}
971
161
  .cb-donutLabel{max-width:0;width:100%}
972
162
  .cb-num{text-align:right;padding-left:14px!important;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
973
163
  .cb-dim{color:var(--dsw-alias-label-tertiary)}
974
- .cb-list{list-style:none;margin:0;padding:0}
975
- .cb-listWrap{display:flex;align-items:center;gap:24px}
976
- .cb-listWrapNarrow{flex-direction:column;align-items:stretch;gap:6px}
977
- .cb-progressLine{display:flex;align-items:center;gap:10px;color:var(--dsw-alias-label-tertiary);font-size:13px}
978
- .cb-progressLine strong{font-size:10px!important}
979
164
 
980
- .cb-listMain{flex:1;min-width:0}
981
- .cb-list li{display:flex;align-items:center;gap:10px;padding:8px 2px;border-top:.5px solid var(--dsw-alias-border-l2)}
982
- .cb-list li:first-child{border-top:0}
983
- .cb-listText{flex:1;min-width:0}
984
- .cb-listSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
985
- .cb-listMeta{display:flex;align-items:center;gap:10px;min-width:0}
986
- .cb-listDate{flex:none;color:var(--dsw-alias-label-tertiary);font-size:12px;font-variant-numeric:tabular-nums}
987
- .cb-done .cb-listTitle{color:var(--dsw-alias-label-tertiary)}
988
- .cb-checkBox{flex:none;display:inline-flex}
989
- .cb-check rect{fill:none;stroke:var(--dsw-alias-border-l4,var(--dsw-alias-label-caption));stroke-width:1.3}
990
- .cb-check[data-checked=true] rect{fill:var(--cb-accent);stroke:var(--cb-accent)}
991
- .cb-check path{fill:none;stroke:#fff;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
992
- .cb-chip{flex:0 1 auto;max-width:11em;overflow:hidden;text-overflow:ellipsis;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}
993
- .cb-chip[data-tone=ok]{color:var(--cb-ok);background:color-mix(in srgb,var(--cb-ok) 12%,transparent)}
994
- .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)}
995
- .cb-chip[data-tone=bad]{color:var(--cb-bad);background:color-mix(in srgb,var(--cb-bad) 12%,transparent)}
996
- .cb-chip[data-tone=accent]{color:var(--cb-accent);background:color-mix(in srgb,var(--cb-accent) 12%,transparent)}
997
- .cb-status{list-style:none;margin:0;padding:0}
998
- .cb-status{display:grid;grid-template-columns:8px fit-content(45%) minmax(0,1fr);column-gap:12px}
999
- .cb-statusSparks{grid-template-columns:8px fit-content(40%) minmax(0,1fr) minmax(56px,1.2fr)}
1000
- .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)}
1001
- .cb-status li:first-child{border-top:0}
1002
- .cb-dot{width:8px;height:8px;border-radius:50%}
1003
- .cb-statusLabel{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1004
- .cb-statusValue{min-width:0;display:flex;flex-direction:column;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
1005
- .cb-statusValue small{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px}
1006
- .cb-spark{min-width:0}
1007
- @container (width<380px){
1008
- .cb-list li{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:0}
1009
- .cb-list li .cb-checkBox{grid-column:1;grid-row:1;margin-right:10px}
1010
- .cb-list li .cb-listText{grid-column:2;grid-row:1}
1011
- .cb-list li .cb-rowActions{grid-column:3;grid-row:1;margin-left:8px}
1012
- .cb-list li .cb-listMeta{grid-column:2/-1;grid-row:2;margin-top:2px}
1013
- }
1014
- @container (width<380px){
1015
- .cb-status,.cb-statusSparks{grid-template-columns:8px minmax(0,1fr) auto}
1016
- .cb-status .cb-statusValue{display:contents}
1017
- .cb-status .cb-statusLabel{grid-column:2;grid-row:1}
1018
- .cb-status .cb-statusNum{grid-column:3;grid-row:1;justify-self:end}
1019
- .cb-status .cb-statusSub{grid-column:2/-1;grid-row:2}
1020
- .cb-status li>.cb-dot{grid-column:1;grid-row:1}
1021
- .cb-status li>.cb-spark{grid-column:2/-1;grid-row:3}
1022
- .cb-spark:empty{display:none}
165
+ /* narrow cards: meta and buttons move under the words */
166
+ @container (width<360px){
167
+ .cb-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;column-gap:10px}
168
+ .cb-row>.cb-rowText{grid-column:2}
169
+ .cb-row>.cb-rowMeta,.cb-row>.cb-statusSpark{grid-column:2/-1;max-width:none;justify-content:flex-start}
170
+ .cb-row>.cb-rowActions{grid-column:3;grid-row:1}
171
+ .cb-row>.cb-statusValue{grid-column:3;grid-row:1}
172
+ .cb-statusRow>.cb-rowActions{grid-row:2}
173
+ .cb-row>.cb-rowSteps{grid-column:2/-1;padding-left:0}
174
+ .cb-row>.cb-check+.uk-tile{display:none}
1023
175
  }
1024
176
  @container (width<520px){
1025
- .cb-statusActions,.cb-statusSparks.cb-statusActions{grid-template-columns:8px minmax(0,1fr) auto}
1026
- .cb-statusActions .cb-statusValue{display:contents}
1027
- .cb-statusActions .cb-statusLabel{grid-column:2;grid-row:1}
1028
- .cb-statusActions .cb-statusNum{grid-column:3;grid-row:1;justify-self:end}
1029
- .cb-statusActions .cb-statusSub{grid-column:2/-1;grid-row:2}
1030
- .cb-statusActions li>.cb-dot{grid-column:1;grid-row:1}
1031
- .cb-statusActions li>.cb-spark{grid-column:2/-1;grid-row:3}
1032
- .cb-statusActions li .cb-rowActions{grid-column:2/-1;grid-row:4;justify-content:flex-start}
177
+ .cb-track{grid-auto-flow:row;grid-auto-columns:auto;gap:10px}
178
+ .cb-track:before{left:8px;right:auto;top:9px;bottom:9px;width:2px;height:auto}
179
+ .cb-track li{display:grid;grid-template-columns:18px auto 1fr;column-gap:10px;align-items:baseline}
180
+ .cb-track i{margin:0;align-self:center}
181
+ .cb-track span{grid-column:3}
1033
182
  }
183
+ @media (width<=640px){
184
+ .cb-heading{padding-top:18px}
185
+ .cb-card{padding:14px 14px 16px;border-radius:14px}
186
+ .cb-card-summary{flex-direction:column;padding:15px}
187
+ .cb-summaryAside{position:absolute;right:10px;top:8px}
188
+ .cb-card-summary{position:relative}
189
+ .cb-summaryText{font-size:16px;line-height:24px}
190
+ .cb-statValue{font-size:24px;line-height:30px}
1034
191
  }
1035
- @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}}
1036
192
  @media (width<=768px),(pointer:coarse){
1037
193
  .cb-cardLink{width:40px;height:40px;margin:-9px 0}
1038
194
  .cb-cardChat{margin:-9px -10px -9px 0}
1039
- .cb-tab{padding:8px 14px 10px}
1040
195
  }
1041
- `
196
+ `;
197
+
198
+ // src/client/page.js
199
+ var import_react8 = require("react");
200
+ var import_dsh_client_ui_primitives4 = require("@deepseek-ai/dsh-client-ui-primitives");
201
+
202
+ // src/client/card.js
203
+ var import_react7 = require("react");
204
+ var import_dsh_client_ui_primitives3 = require("@deepseek-ai/dsh-client-ui-primitives");
205
+
206
+ // src/client/charts.js
207
+ var import_react4 = require("react");
208
+
209
+ // src/client/pieces.js
210
+ var import_react = require("react");
211
+ var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
212
+ function Trunc({ text, as = "div", className = "", lines = 1 }) {
213
+ const [open, setOpen] = (0, import_react.useState)(false);
214
+ return (0, import_react.createElement)(as, {
215
+ className: `cb-trunc${lines > 1 ? " cb-trunc2" : ""}${open ? " cb-truncOpen" : ""} ${className}`.trim(),
216
+ title: text,
217
+ onClick: () => setOpen((value) => !value)
218
+ }, text);
219
+ }
220
+ function CheckBox({ checked, label }) {
221
+ return (0, import_react.createElement)(
222
+ "span",
223
+ { className: "cb-check", "data-checked": checked ? "true" : "false", role: "img", "aria-label": label },
224
+ checked && (0, import_react.createElement)(import_dsh_client_ui_primitives.IconCheckOutlineMedium, { size: 12 })
225
+ );
226
+ }
1042
227
 
1043
- return {
1044
- inject: ['slots', 'locale'],
1045
- apply(ctx) {
1046
- clientCtx = ctx
1047
- // The sidebar entry's name comes from the same locale files: fetched for the active language, then
1048
- // handed to DSH's own dictionary (which also makes the sidebar redraw).
1049
- let forget = () => {}
1050
- ctx.effect(() => {
1051
- let live = true
1052
- let loadedFor = null
1053
- const load = () => {
1054
- const active = ctx.locale.getSnapshot().active
1055
- // Registering the words is itself a locale change notification, so only a new language starts a load.
1056
- if (active === loadedFor) return
1057
- loadedFor = active
1058
- fetchMessages(active).then(messages => {
1059
- if (!live) return
1060
- forget()
1061
- try {
1062
- forget = ctx.locale.register(NS, active, { panel: messages.panel })
1063
- } catch (error) {
1064
- console.warn('card-board: sidebar name not registered:', error)
1065
- }
1066
- }, () => { if (live) { loadedFor = null; setTimeout(load, 3000) } })
1067
- }
1068
- load()
1069
- const stop = ctx.locale.subscribe(load)
1070
- return () => { live = false; stop(); forget() }
1071
- }, 'card-board: sidebar words')
1072
- const sidebarT = ctx.locale.bind(NS)
228
+ // src/client/format.js
229
+ var import_react2 = require("react");
230
+ function formatNumber(value, locale, digits) {
231
+ if (typeof value !== "number") return String(value);
232
+ const abs = Math.abs(value);
233
+ const max = digits ?? (abs >= 1e3 ? 0 : abs >= 100 ? 1 : 2);
234
+ return new Intl.NumberFormat(locale, { maximumFractionDigits: max }).format(value);
235
+ }
236
+ function formatAxis(value, locale) {
237
+ const abs = Math.abs(value);
238
+ if (abs >= 1e4) return new Intl.NumberFormat(locale, { notation: "compact", maximumFractionDigits: abs >= 1e5 ? 0 : 1 }).format(value);
239
+ return formatNumber(value, locale, abs >= 100 ? 0 : 1);
240
+ }
241
+ var DAY_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
242
+ function toTime(value) {
243
+ if (typeof value !== "string") return NaN;
244
+ const day = DAY_ONLY.exec(value);
245
+ if (day) return new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3])).getTime();
246
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) ? Date.parse(value) : NaN;
247
+ }
248
+ function formatDay(time, locale, spanDays) {
249
+ const date = new Date(time);
250
+ if (spanDays > 120) return new Intl.DateTimeFormat(locale, { month: "short" }).format(date);
251
+ return new Intl.DateTimeFormat(locale, { month: "numeric", day: "numeric" }).format(date);
252
+ }
253
+ function formatAge(seconds, locale) {
254
+ const [unit, amount] = seconds < 3600 ? ["minute", Math.max(1, Math.round(seconds / 60))] : seconds < 86400 * 2 ? ["hour", Math.round(seconds / 3600)] : ["day", Math.round(seconds / 86400)];
255
+ return new Intl.NumberFormat(locale, { style: "unit", unit, unitDisplay: "short" }).format(amount);
256
+ }
257
+ function formatClock(time, locale, zone) {
258
+ return new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", ...zone ? { timeZone: zone } : {} }).format(time);
259
+ }
260
+ var textWidth = (text) => [...String(text)].reduce((sum, char) => sum + (char.charCodeAt(0) > 11903 ? 11.5 : 6.4), 0);
261
+ function fit(text, px) {
262
+ if (textWidth(text) <= px) return String(text);
263
+ let out = "";
264
+ for (const char of String(text)) {
265
+ if (textWidth(`${out}${char}\u2026`) > px) break;
266
+ out += char;
267
+ }
268
+ return `${out}\u2026`;
269
+ }
270
+ function niceTicks(min, max, count) {
271
+ if (min === max) return [min];
272
+ const raw = (max - min) / Math.max(1, count);
273
+ const power = 10 ** Math.floor(Math.log10(raw));
274
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * power).find((s) => s >= raw) ?? raw;
275
+ const ticks = [];
276
+ for (let v = Math.ceil(min / step) * step; v <= max + step * 1e-9; v += step) ticks.push(Number(v.toFixed(10)));
277
+ return ticks;
278
+ }
279
+ function spread(length, count) {
280
+ if (length <= count) return Array.from({ length }, (_, i) => i);
281
+ const step = (length - 1) / Math.max(1, count - 1);
282
+ return Array.from({ length: count }, (_, i) => Math.round(i * step));
283
+ }
284
+ function useWidth() {
285
+ const [element, setElement] = (0, import_react2.useState)(null);
286
+ const [width, setWidth] = (0, import_react2.useState)(0);
287
+ (0, import_react2.useLayoutEffect)(() => {
288
+ if (!element) return void 0;
289
+ const observer = new ResizeObserver(([entry]) => setWidth(Math.floor(entry.contentRect.width)));
290
+ observer.observe(element);
291
+ return () => observer.disconnect();
292
+ }, [element]);
293
+ return [setElement, width];
294
+ }
295
+ var isActive = (active, now) => active !== void 0 && Date.parse(active.from) <= now && now < Date.parse(active.to);
296
+
297
+ // src/client/services.js
298
+ var import_react3 = require("react");
299
+ var OWNER = "@soffits/dsh-card-board";
300
+ var api = (path) => new URL(`api/card-board/${path}`, document.baseURI).href;
301
+ function createStore() {
302
+ let value = null;
303
+ const listeners = /* @__PURE__ */ new Set();
304
+ return {
305
+ get: () => value,
306
+ set: (next) => {
307
+ value = next;
308
+ for (const listener of listeners) listener();
309
+ },
310
+ subscribe: (listener) => {
311
+ listeners.add(listener);
312
+ return () => {
313
+ listeners.delete(listener);
314
+ };
315
+ }
316
+ };
317
+ }
318
+ var kitStore = createStore();
319
+ var buttonsStore = createStore();
320
+ var useKit = () => (0, import_react3.useSyncExternalStore)(kitStore.subscribe, kitStore.get);
321
+ var useButtons = () => (0, import_react3.useSyncExternalStore)(buttonsStore.subscribe, buttonsStore.get);
322
+
323
+ // src/client/charts.js
324
+ var PALETTE = ["accent", "ok", "warn", "violet", "bad", "muted"];
325
+ var toneColor = (tone, index = 0) => kitStore.get().toneColor(tone ?? PALETTE[index % PALETTE.length]);
326
+ function Legend({ items, locale }) {
327
+ return (0, import_react4.createElement)("ul", { className: "cb-legend" }, items.map((item, i) => (0, import_react4.createElement)(
328
+ "li",
329
+ { key: i },
330
+ (0, import_react4.createElement)("i", { style: { background: item.color } }),
331
+ (0, import_react4.createElement)(Trunc, { as: "span", text: item.label }),
332
+ item.value !== void 0 && (0, import_react4.createElement)("b", null, formatNumber(item.value, locale))
333
+ )));
334
+ }
335
+ function LineChart({ data, locale, height }) {
336
+ const [ref, width] = useWidth();
337
+ const model = (0, import_react4.useMemo)(() => {
338
+ const allX = [...data.series.flatMap((s) => s.points.map((p) => p.x)), ...(data.goal?.points ?? []).map((p) => p.x), ...(data.markers ?? []).map((m) => m.x)];
339
+ const times = allX.map(toTime);
340
+ const timeAxis = times.every(Number.isFinite);
341
+ const numberAxis = !timeAxis && allX.every((x) => typeof x === "number");
342
+ const categories = timeAxis || numberAxis ? [] : [...new Set(allX.map(String))];
343
+ const xValue = (x) => timeAxis ? toTime(x) : numberAxis ? x : categories.indexOf(String(x));
344
+ const xs = allX.map(xValue);
345
+ let ys = data.series.flatMap((s) => s.points.map((p) => p.y)).filter((y) => typeof y === "number");
346
+ if (data.goal?.y !== void 0) ys = ys.concat(data.goal.y);
347
+ if (data.goal?.points) ys = ys.concat(data.goal.points.map((p) => p.y).filter((y) => typeof y === "number"));
348
+ let yMin = Math.min(...ys);
349
+ let yMax = Math.max(...ys);
350
+ const pad = (yMax - yMin || Math.abs(yMax) || 1) * 0.08;
351
+ yMin -= pad;
352
+ yMax += pad;
353
+ return { timeAxis, categories, xValue, xMin: Math.min(...xs), xMax: Math.max(...xs), yMin, yMax };
354
+ }, [data]);
355
+ const ticks = niceTicks(model.yMin, model.yMax, height > 160 ? 4 : 3).filter((v) => v >= model.yMin && v <= model.yMax);
356
+ const left = Math.max(...ticks.map((v) => textWidth(formatAxis(v, locale)))) + 10;
357
+ const right = 12;
358
+ const top = 10;
359
+ const bottom = 20;
360
+ const plotW = Math.max(10, width - left - right);
361
+ const plotH = Math.max(10, height - top - bottom);
362
+ const sx = (x) => left + (model.xMax === model.xMin ? plotW / 2 : (model.xValue(x) - model.xMin) / (model.xMax - model.xMin) * plotW);
363
+ const sy = (y) => top + (1 - (y - model.yMin) / (model.yMax - model.yMin || 1)) * plotH;
364
+ const spanDays = model.timeAxis ? (model.xMax - model.xMin) / 864e5 : 0;
365
+ const xLabel = (x) => model.timeAxis ? formatDay(toTime(x), locale, spanDays) : typeof x === "number" ? formatNumber(x, locale) : String(x);
366
+ const longest = data.series.reduce((best, s) => s.points.length > best.points.length ? s : best, data.series[0]);
367
+ const labelWidth = Math.max(36, ...longest.points.slice(0, 40).map((p) => textWidth(xLabel(p.x)) + 12));
368
+ const labelCount = Math.max(2, Math.floor(plotW / labelWidth));
369
+ const xTicks = [];
370
+ for (const x of spread(longest.points.length, labelCount).map((i) => longest.points[i].x)) {
371
+ const last = xTicks[xTicks.length - 1];
372
+ if (last !== void 0 && (xLabel(last) === xLabel(x) || sx(x) - sx(last) < labelWidth)) continue;
373
+ xTicks.push(x);
374
+ }
375
+ const labelRows = [[], []];
376
+ const markerLabels = [...data.markers ?? []].sort((a, b) => model.xValue(a.x) - model.xValue(b.x)).map((marker) => {
377
+ const x = sx(marker.x);
378
+ const room = left + plotW - x - 6;
379
+ const flip = room < Math.min(textWidth(marker.label), 90) && x - left > room;
380
+ const space = Math.max(20, Math.min(120, flip ? x - left - 6 : room));
381
+ const width2 = Math.min(textWidth(marker.label), space);
382
+ const span = flip ? [x - 4 - width2, x - 4] : [x + 4, x + 4 + width2];
383
+ const row = labelRows.findIndex((taken) => taken.every(([from, to]) => span[0] > to + 4 || span[1] < from - 4));
384
+ if (row >= 0) labelRows[row].push(span);
385
+ return { marker, x, flip, space, label: row >= 0 ? row : null };
386
+ });
387
+ const path = (points) => {
388
+ let d = "";
389
+ let pen = false;
390
+ for (const p of points) {
391
+ if (typeof p.y !== "number") {
392
+ pen = false;
393
+ continue;
394
+ }
395
+ d += `${pen ? "L" : "M"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`;
396
+ pen = true;
397
+ }
398
+ return d;
399
+ };
400
+ const gradientId = (0, import_react4.useMemo)(() => `cb-g-${Math.random().toString(36).slice(2, 9)}`, []);
401
+ return (0, import_react4.createElement)("div", { ref, className: "cb-chart", style: { height } }, width > 0 && (0, import_react4.createElement)(
402
+ "svg",
403
+ { width, height, role: "img" },
404
+ (0, import_react4.createElement)("defs", null, data.series.map((s, i) => (0, import_react4.createElement)(
405
+ "linearGradient",
406
+ { key: i, id: `${gradientId}-${i}`, x1: 0, y1: 0, x2: 0, y2: 1 },
407
+ (0, import_react4.createElement)("stop", { offset: "0%", stopColor: toneColor(s.tone, i), stopOpacity: 0.22 }),
408
+ (0, import_react4.createElement)("stop", { offset: "100%", stopColor: toneColor(s.tone, i), stopOpacity: 0 })
409
+ ))),
410
+ ticks.map((v) => (0, import_react4.createElement)(
411
+ "g",
412
+ { key: v },
413
+ (0, import_react4.createElement)("line", { x1: left, x2: left + plotW, y1: sy(v), y2: sy(v), className: "cb-rule" }),
414
+ (0, import_react4.createElement)("text", { x: left - 8, y: sy(v), className: "cb-axis", textAnchor: "end", dominantBaseline: "middle" }, formatAxis(v, locale))
415
+ )),
416
+ xTicks.map((x, i) => (0, import_react4.createElement)("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))),
417
+ markerLabels.map(({ marker, x, label, flip, space }, i) => (0, import_react4.createElement)(
418
+ "g",
419
+ { key: `m${i}` },
420
+ (0, import_react4.createElement)("line", { x1: x, x2: x, y1: top, y2: top + plotH, className: "cb-marker" }),
421
+ (0, import_react4.createElement)("title", null, marker.label),
422
+ label !== null && (0, import_react4.createElement)("text", { x: flip ? x - 4 : x + 4, y: top + plotH - 5 - label * 13, className: "cb-markerLabel", textAnchor: flip ? "end" : "start" }, fit(marker.label, space))
423
+ )),
424
+ data.goal && (data.goal.points ? (0, import_react4.createElement)("path", { d: path(data.goal.points), className: "cb-goal" }) : (0, import_react4.createElement)("line", { x1: left, x2: left + plotW, y1: sy(data.goal.y), y2: sy(data.goal.y), className: "cb-goal" })),
425
+ data.goal?.label && (() => {
426
+ const end = data.goal.points ? data.goal.points[data.goal.points.length - 1] : { x: null, y: data.goal.y };
427
+ const x = end.x === null ? left + plotW : sx(end.x);
428
+ return (0, import_react4.createElement)("text", { x: Math.min(x, left + plotW), y: sy(end.y) - 5, className: "cb-goalLabel", textAnchor: "end" }, (0, import_react4.createElement)("title", null, data.goal.label), fit(data.goal.label, plotW));
429
+ })(),
430
+ data.series.map((s, i) => {
431
+ const color = toneColor(s.tone, i);
432
+ const line = path(s.points);
433
+ const valid = s.points.filter((p) => typeof p.y === "number");
434
+ const last = valid[valid.length - 1];
435
+ const area = data.area && valid.length > 1 ? `${line}L${sx(last.x).toFixed(1)},${(top + plotH).toFixed(1)}L${sx(valid[0].x).toFixed(1)},${(top + plotH).toFixed(1)}Z` : null;
436
+ return (0, import_react4.createElement)(
437
+ "g",
438
+ { key: `s${i}` },
439
+ area && (0, import_react4.createElement)("path", { d: area, fill: `url(#${gradientId}-${i})`, stroke: "none" }),
440
+ (0, import_react4.createElement)("path", { d: line, fill: "none", stroke: color, strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round" }),
441
+ valid.length <= 16 && valid.map((p, j) => (0, import_react4.createElement)(
442
+ "circle",
443
+ { key: j, cx: sx(p.x), cy: sy(p.y), r: 2.6, fill: "var(--dsw-alias-bg-base)", stroke: color, strokeWidth: 1.6 },
444
+ (0, import_react4.createElement)("title", null, `${s.name ? `${s.name} \xB7 ` : ""}${xLabel(p.x)}: ${formatNumber(p.y, locale)}${data.unit ? ` ${data.unit}` : ""}`)
445
+ )),
446
+ valid.length > 16 && last && (0, import_react4.createElement)("circle", { cx: sx(last.x), cy: sy(last.y), r: 3, fill: color })
447
+ );
448
+ })
449
+ ));
450
+ }
451
+ function BarChart({ data, locale, height }) {
452
+ const [ref, width] = useWidth();
453
+ const keys = (0, import_react4.useMemo)(() => {
454
+ const seen = [];
455
+ for (const bar of data.bars) for (const key of Object.keys(bar.values ?? {})) if (!seen.includes(key)) seen.push(key);
456
+ return seen;
457
+ }, [data]);
458
+ const multi = keys.length > 0;
459
+ const stacked = multi && data.stacked === true;
460
+ 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));
461
+ const peaks = data.bars.map((bar, i) => multi && !stacked ? Math.max(0, ...keys.map((key) => bar.values?.[key] ?? 0)) : totals[i]);
462
+ const max = Math.max(1e-9, ...peaks, data.goal?.y ?? 0);
463
+ const showValues = data.bars.length <= 14;
464
+ const top = showValues ? 16 : 6;
465
+ const bottom = 20;
466
+ const plotH = Math.max(10, height - top - bottom);
467
+ const slot = width / data.bars.length;
468
+ const barW = Math.max(2, Math.min(44, slot * 0.62));
469
+ const sy = (v) => top + plotH - v / max * plotH;
470
+ const labelEvery = Math.max(1, Math.ceil(data.bars.length / Math.max(1, Math.floor(width / 40))));
471
+ const label = (x) => {
472
+ const time = toTime(x);
473
+ return Number.isFinite(time) ? formatDay(time, locale, 0) : String(x);
474
+ };
475
+ return (0, import_react4.createElement)(
476
+ "div",
477
+ null,
478
+ (0, import_react4.createElement)("div", { ref, className: "cb-chart", style: { height } }, width > 0 && (0, import_react4.createElement)(
479
+ "svg",
480
+ { width, height, role: "img" },
481
+ (0, import_react4.createElement)("line", { x1: 0, x2: width, y1: top + plotH + 0.5, y2: top + plotH + 0.5, className: "cb-rule" }),
482
+ data.goal && (0, import_react4.createElement)("line", { x1: 0, x2: width, y1: sy(data.goal.y), y2: sy(data.goal.y), className: "cb-goal" }),
483
+ data.goal?.label && (0, import_react4.createElement)("text", { x: width, y: sy(data.goal.y) - 4, className: "cb-goalLabel", textAnchor: "end" }, (0, import_react4.createElement)("title", null, data.goal.label), fit(data.goal.label, width)),
484
+ data.bars.map((bar, i) => {
485
+ const cx = slot * i + slot / 2;
486
+ const tip = multi ? `${label(bar.x)}: ${keys.filter((k) => bar.values?.[k] !== void 0).map((k) => `${k} ${formatNumber(bar.values[k], locale)}`).join(", ")}` : `${label(bar.x)}: ${formatNumber(bar.value, locale)}${data.unit ? ` ${data.unit}` : ""}`;
487
+ let parts;
488
+ if (!multi) parts = [{ y0: 0, y1: Math.max(0, bar.value), color: toneColor(void 0, 1), x: cx - barW / 2, w: barW }];
489
+ else if (stacked) {
490
+ let base = 0;
491
+ parts = keys.map((key, k) => {
492
+ const v = Math.max(0, bar.values?.[key] ?? 0);
493
+ const part = { y0: base, y1: base + v, color: toneColor(void 0, k), x: cx - barW / 2, w: barW };
494
+ base += v;
495
+ return part;
496
+ });
497
+ } else {
498
+ const each = barW / keys.length;
499
+ parts = keys.map((key, k) => ({ y0: 0, y1: Math.max(0, bar.values?.[key] ?? 0), color: toneColor(void 0, k), x: cx - barW / 2 + k * each, w: Math.max(1, each - 1) }));
500
+ }
501
+ return (0, import_react4.createElement)(
502
+ "g",
503
+ { key: i },
504
+ (0, import_react4.createElement)("title", null, tip),
505
+ parts.filter((p) => p.y1 > p.y0).map((p, k) => (0, import_react4.createElement)("rect", {
506
+ key: k,
507
+ x: p.x,
508
+ width: p.w,
509
+ y: sy(p.y1),
510
+ height: Math.max(0.5, sy(p.y0) - sy(p.y1)),
511
+ rx: Math.min(4, p.w / 3),
512
+ fill: p.color,
513
+ fillOpacity: multi ? 0.85 : 0.55
514
+ })),
515
+ showValues && (0, import_react4.createElement)("text", { x: cx, y: sy(peaks[i]) - 4, className: "cb-barValue", textAnchor: "middle" }, formatNumber(multi && !stacked ? peaks[i] : totals[i], locale, 1)),
516
+ i % labelEvery === 0 && (0, import_react4.createElement)("text", { x: Math.min(Math.max(cx, textWidth(label(bar.x)) / 2), width - textWidth(label(bar.x)) / 2), y: height - 4, className: "cb-axis", textAnchor: "middle" }, label(bar.x))
517
+ );
518
+ })
519
+ )),
520
+ multi && (0, import_react4.createElement)(Legend, { items: keys.map((key, k) => ({ label: key, color: toneColor(void 0, k) })), locale })
521
+ );
522
+ }
523
+ function arc(cx, cy, r, start, end) {
524
+ const large = end - start > Math.PI ? 1 : 0;
525
+ const x0 = cx + r * Math.sin(start);
526
+ const y0 = cy - r * Math.cos(start);
527
+ const x1 = cx + r * Math.sin(end);
528
+ const y1 = cy - r * Math.cos(end);
529
+ return `M${x0.toFixed(2)},${y0.toFixed(2)}A${r},${r} 0 ${large} 1 ${x1.toFixed(2)},${y1.toFixed(2)}`;
530
+ }
531
+ function Donut({ data, locale, height }) {
532
+ const [ref, width] = useWidth();
533
+ const total = data.segments.reduce((sum, s) => sum + s.value, 0);
534
+ const narrow = width < 340;
535
+ const size = Math.max(90, Math.min(narrow ? 150 : 170, height - 8, narrow ? width * 0.6 : width * 0.42));
536
+ const ring = size * 0.13;
537
+ const r = size / 2 - ring / 2;
538
+ let angle = 0;
539
+ const gap = data.segments.filter((s) => s.value > 0).length > 1 ? 0.025 : 0;
540
+ const segments = data.segments.map((s, i) => {
541
+ const sweep = total > 0 ? s.value / total * Math.PI * 2 : 0;
542
+ const seg = { ...s, color: toneColor(s.tone, i), start: angle + gap / 2, end: angle + sweep - gap / 2 };
543
+ angle += sweep;
544
+ return seg;
545
+ });
546
+ return (0, import_react4.createElement)(
547
+ "div",
548
+ { ref, className: `cb-donut${narrow ? " cb-donutNarrow" : ""}` },
549
+ width > 0 && (0, import_react4.createElement)(
550
+ "div",
551
+ { className: "cb-donutRing", style: { width: size, height: size } },
552
+ (0, import_react4.createElement)(
553
+ "svg",
554
+ { width: size, height: size, role: "img" },
555
+ (0, import_react4.createElement)("circle", { cx: size / 2, cy: size / 2, r, fill: "none", stroke: "var(--dsw-alias-border-l2)", strokeWidth: ring }),
556
+ segments.filter((s) => s.end > s.start).map((s, i) => (0, import_react4.createElement)(
557
+ "path",
558
+ { key: i, d: arc(size / 2, size / 2, r, s.start, s.end), fill: "none", stroke: s.color, strokeWidth: ring },
559
+ (0, import_react4.createElement)("title", null, `${s.label}: ${formatNumber(s.value, locale)}${data.unit ? ` ${data.unit}` : ""}`)
560
+ ))
561
+ ),
562
+ data.centre && (0, import_react4.createElement)(
563
+ "div",
564
+ { className: "cb-donutCentre" },
565
+ (0, import_react4.createElement)("strong", null, data.centre.text),
566
+ data.centre.sub && (0, import_react4.createElement)("span", null, data.centre.sub)
567
+ )
568
+ ),
569
+ (0, import_react4.createElement)("table", { className: "cb-donutTable" }, (0, import_react4.createElement)("tbody", null, segments.map((s, i) => (0, import_react4.createElement)(
570
+ "tr",
571
+ { key: i },
572
+ (0, import_react4.createElement)("td", null, (0, import_react4.createElement)("i", { style: { background: s.color } })),
573
+ (0, import_react4.createElement)("td", { className: "cb-donutLabel" }, (0, import_react4.createElement)(Trunc, { text: s.label })),
574
+ (0, import_react4.createElement)("td", { className: "cb-num" }, formatNumber(s.value, locale)),
575
+ (0, import_react4.createElement)("td", { className: "cb-num cb-dim" }, total > 0 ? `${Math.round(s.value / total * 100)}%` : "\u2013")
576
+ ))))
577
+ );
578
+ }
579
+ var KIND_TONE = { due: "warn", health: "ok", event: "accent", home: "muted", money: "ok", travel: "accent" };
580
+ var KIND_ICON = { due: "receipt", health: "heart-pulse", event: "calendar", home: "house", money: "wallet", travel: "plane" };
581
+ function Timeline({ data, locale }) {
582
+ const kit = useKit();
583
+ const [ref, width] = useWidth();
584
+ const from = toTime(data.from);
585
+ const to = toTime(data.to);
586
+ const days = Math.max(1, Math.round((to - from) / 864e5));
587
+ const pad = 14;
588
+ const plotW = Math.max(10, width - pad * 2);
589
+ const sx = (time) => pad + (time - from) / (to - from) * plotW;
590
+ const now = Date.now();
591
+ const dayEvery = Math.max(1, Math.ceil(days / Math.max(1, Math.floor(plotW / 44))));
592
+ const ticks = [];
593
+ for (let i = 0; i <= days; i += dayEvery) ticks.push(from + i * 864e5);
594
+ 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);
595
+ const rowEnds = [];
596
+ const placed = points.map((p) => {
597
+ const half = Math.min(90, textWidth(p.label)) / 2 + 4;
598
+ const x = sx(p.time);
599
+ let row = rowEnds.findIndex((end) => x - half > end);
600
+ if (row === -1) {
601
+ row = rowEnds.length;
602
+ rowEnds.push(0);
603
+ }
604
+ rowEnds[row] = x + half;
605
+ return { ...p, x, row };
606
+ });
607
+ const labelRows = Math.max(1, rowEnds.length);
608
+ const tickH = 18;
609
+ const pointY = tickH + 16;
610
+ const labelTop = pointY + 18;
611
+ const spansTop = labelTop + labelRows * 15 + 8;
612
+ const spans = (data.spans ?? []).map((s) => ({ ...s, a: Math.max(from, toTime(s.from)), b: Math.min(to, toTime(s.to) + 864e5 - 1) })).filter((s) => s.b >= s.a);
613
+ const height = spansTop + spans.length * 36 + 4;
614
+ return (0, import_react4.createElement)("div", { ref, className: "cb-chart", style: { height } }, width > 0 && (0, import_react4.createElement)(
615
+ "svg",
616
+ { width, height, role: "img" },
617
+ ticks.map((time, i) => (0, import_react4.createElement)(
618
+ "g",
619
+ { key: i },
620
+ (0, import_react4.createElement)("line", { x1: sx(time), x2: sx(time), y1: tickH, y2: height, className: "cb-dayLine" }),
621
+ (0, import_react4.createElement)("text", { x: sx(time), y: 11, className: "cb-axis", textAnchor: "middle" }, formatDay(time, locale, 0))
622
+ )),
623
+ now >= from && now <= to && (0, import_react4.createElement)("line", { x1: sx(now), x2: sx(now), y1: tickH - 2, y2: height, className: "cb-today" }),
624
+ placed.map((p, i) => {
625
+ const color = toneColor(p.tone ?? KIND_TONE[p.kind] ?? "accent");
626
+ const text = fit(p.label, 90);
627
+ return (0, import_react4.createElement)(
628
+ "g",
629
+ { key: i },
630
+ (0, import_react4.createElement)("title", null, `${formatDay(p.time, locale, 0)} \xB7 ${p.label}`),
631
+ KIND_ICON[p.kind] ? (0, import_react4.createElement)("g", { transform: `translate(${(p.x - 8).toFixed(1)},${pointY - 8})`, style: { color } }, (0, import_react4.createElement)(kit.Icon, { name: KIND_ICON[p.kind], size: 16 })) : (0, import_react4.createElement)("circle", { cx: p.x, cy: pointY, r: 5, fill: color }),
632
+ p.row > 0 && (0, import_react4.createElement)("line", { x1: p.x, x2: p.x, y1: pointY + 8, y2: labelTop + p.row * 15 - 9, className: "cb-leader" }),
633
+ (0, import_react4.createElement)("text", { x: p.x, y: labelTop + p.row * 15, className: "cb-pointLabel", textAnchor: "middle" }, text)
634
+ );
635
+ }),
636
+ spans.map((s, i) => {
637
+ const x = sx(s.a);
638
+ const w = Math.max(6, sx(s.b) - x);
639
+ const y = spansTop + i * 36;
640
+ const full = `${s.label} \xB7 ${formatDay(toTime(s.from), locale, 0)} \u2013 ${formatDay(toTime(s.to), locale, 0)}`;
641
+ return (0, import_react4.createElement)(
642
+ "g",
643
+ { key: `s${i}` },
644
+ (0, import_react4.createElement)("title", null, full),
645
+ (0, import_react4.createElement)("rect", { x, y, width: w, height: 12, rx: 6, fill: toneColor(s.tone ?? "accent"), fillOpacity: 0.22 }),
646
+ (0, import_react4.createElement)("text", { x: Math.min(Math.max(x + w / 2, pad + Math.min(plotW, textWidth(full) * 0.55) / 2), width - pad - Math.min(plotW, textWidth(full) * 0.55) / 2), y: y + 26, className: "cb-spanLabel", textAnchor: "middle" }, fit(full, plotW))
647
+ );
648
+ })
649
+ ));
650
+ }
1073
651
 
1074
- // The shared buttons, once @soffits/dsh-ui-actions is there; the board also names itself there, so a chat
1075
- // started from a card shows the board's icon and name.
1076
- ctx.inject(['uiActions'], scope => {
1077
- scope.effect(() => {
1078
- buttonsStore.set(scope.uiActions)
1079
- const unregister = scope.uiActions.registerSource({ id: OWNER, name: () => sidebarT('panel'), icon: SidebarIcon })
1080
- return () => { unregister(); buttonsStore.set(null) }
1081
- }, 'card-board: shared buttons')
1082
- })
652
+ // src/client/cards.js
653
+ var import_react5 = require("react");
654
+ var import_dsh_client_ui_primitives2 = require("@deepseek-ai/dsh-client-ui-primitives");
655
+ var STATE_OF_TONE = { ok: "done", warn: "warning", bad: "error" };
656
+ var DIRECTION_ICON = { up: "trending-up", down: "trending-down" };
657
+ function StatBlock({ data, locale, compact, wash }) {
658
+ const kit = useKit();
659
+ return (0, import_react5.createElement)("div", { className: `cb-stats${compact ? " cb-statsCompact" : ""}` }, data.items.map((item, i) => (0, import_react5.createElement)(
660
+ "div",
661
+ { key: i, className: `cb-stat${item.strip ? " cb-statWide" : ""}` },
662
+ (0, import_react5.createElement)("div", { className: "cb-statLabel" }, (0, import_react5.createElement)(Trunc, { as: "span", text: item.label }), i === 0 && wash && (0, import_react5.createElement)(kit.JustNow)),
663
+ (0, import_react5.createElement)(
664
+ "div",
665
+ { className: "cb-statValue", style: item.tone ? { color: kit.toneColor(item.tone) } : void 0 },
666
+ (0, import_react5.createElement)("span", null, formatNumber(item.value, locale)),
667
+ item.unit && (0, import_react5.createElement)("small", null, item.unit)
668
+ ),
669
+ item.delta && (0, import_react5.createElement)(
670
+ "div",
671
+ { className: "cb-delta", style: { color: kit.toneColor(item.delta.tone ?? "muted") } },
672
+ DIRECTION_ICON[item.delta.dir] && (0, import_react5.createElement)(kit.Icon, { name: DIRECTION_ICON[item.delta.dir], size: 13 }),
673
+ (0, import_react5.createElement)("span", null, item.delta.text)
674
+ ),
675
+ item.progress && (0, import_react5.createElement)(
676
+ "div",
677
+ { className: "cb-statProgress" },
678
+ (0, import_react5.createElement)(kit.Progress, { value: item.progress.value, max: item.progress.max, tone: item.tone ?? (item.progress.value > item.progress.max ? "warn" : "ok") }),
679
+ item.progress.text && (0, import_react5.createElement)("div", { className: "cb-statSub" }, item.progress.text)
680
+ ),
681
+ item.spark && (0, import_react5.createElement)(kit.Spark, { values: item.spark, tone: item.tone ?? "accent", height: 28, area: true }),
682
+ item.sub && (0, import_react5.createElement)(Trunc, { className: "cb-statSub", lines: 2, text: item.sub }),
683
+ item.strip && (0, import_react5.createElement)("ol", { className: "cb-strip" }, item.strip.map((cell, j) => (0, import_react5.createElement)(
684
+ "li",
685
+ { key: j, "data-on": cell.on ? "true" : void 0 },
686
+ (0, import_react5.createElement)("b", null, formatNumber(cell.value, locale, 1)),
687
+ cell.icon && (0, import_react5.createElement)(kit.Icon, { name: cell.icon, size: 14 }),
688
+ (0, import_react5.createElement)("span", null, cell.label)
689
+ )))
690
+ )));
691
+ }
692
+ function RowWhen({ row, locale, t }) {
693
+ const kit = useKit();
694
+ const now = kit.useNow();
695
+ if (row.active) {
696
+ if (isActive(row.active, now)) return (0, import_react5.createElement)(import_dsh_client_ui_primitives2.Tag, { tone: "info" }, t("now"));
697
+ const from = Date.parse(row.active.from);
698
+ if (from > now && new Date(from).toDateString() === new Date(now).toDateString()) return (0, import_react5.createElement)("span", { className: "cb-when" }, t("fromTime", { time: formatClock(from, locale) }));
699
+ }
700
+ return row.date ? (0, import_react5.createElement)("span", { className: "cb-when" }, (0, import_react5.createElement)(kit.RelativeDay, { date: row.date })) : null;
701
+ }
702
+ function Row({ lead, title, sub, meta, value, spark, row, index, washCount, fresh, rowActions, className }) {
703
+ const kit = useKit();
704
+ const now = kit.useNow();
705
+ const wash = kit.useWash(washCount, row.key);
706
+ return (0, import_react5.createElement)(
707
+ "li",
708
+ { className: ["cb-row", className, row.checked && "cb-done", isActive(row.active, now) && "cb-rowNow", wash].filter(Boolean).join(" ") },
709
+ lead,
710
+ (0, import_react5.createElement)(
711
+ "div",
712
+ { className: "cb-rowText" },
713
+ (0, import_react5.createElement)("div", { className: "cb-rowTitle" }, fresh && (0, import_react5.createElement)(kit.NewDot), (0, import_react5.createElement)(Trunc, { as: "span", lines: 2, text: title })),
714
+ sub && (0, import_react5.createElement)(Trunc, { className: "cb-rowSub", lines: 2, text: sub })
715
+ ),
716
+ spark,
717
+ meta,
718
+ value,
719
+ row.actions && rowActions && (0, import_react5.createElement)("span", { className: "cb-rowActions" }, rowActions(index, row.actions, "buttons")),
720
+ row.actions?.some((action) => action.kind === "step") && rowActions && (0, import_react5.createElement)("div", { className: "cb-rowSteps" }, rowActions(index, row.actions, "steps"))
721
+ );
722
+ }
723
+ var rowLive = (live, row) => ({ washCount: live.rows?.[row.key] ?? 0, fresh: row.key !== void 0 && live.freshRows.has(row.key) });
724
+ function ListCard({ data, live, locale, t, rowActions }) {
725
+ const kit = useKit();
726
+ const checkable = data.rows.some((row) => "checked" in row);
727
+ const progress = data.progress;
728
+ return (0, import_react5.createElement)(
729
+ "div",
730
+ { className: "cb-list" },
731
+ progress && (0, import_react5.createElement)(
732
+ "div",
733
+ { className: "cb-progress" },
734
+ (0, import_react5.createElement)(
735
+ kit.Ring,
736
+ { value: progress.done, max: progress.total, size: 54, tone: progress.done >= progress.total ? "ok" : "accent", label: `${progress.done}/${progress.total}` },
737
+ (0, import_react5.createElement)("span", null, String(progress.done)),
738
+ (0, import_react5.createElement)("small", null, t("ofTotal", { total: progress.total }))
739
+ ),
740
+ (0, import_react5.createElement)(
741
+ "div",
742
+ { className: "cb-progressText" },
743
+ progress.label && (0, import_react5.createElement)("div", { className: "cb-progressLabel" }, progress.label),
744
+ progress.sub && (0, import_react5.createElement)("div", { className: "cb-rowSub" }, progress.sub)
745
+ )
746
+ ),
747
+ data.rows.length === 0 ? (0, import_react5.createElement)("p", { className: "cb-muted" }, data.empty ?? t("listEmpty")) : (0, import_react5.createElement)("ul", { className: "cb-rows" }, data.rows.map((row, i) => (0, import_react5.createElement)(Row, {
748
+ key: row.key ?? i,
749
+ index: i,
750
+ row,
751
+ rowActions,
752
+ ...rowLive(live, row),
753
+ lead: [
754
+ checkable && (0, import_react5.createElement)(CheckBox, { key: "check", checked: row.checked === true, label: t(row.checked ? "checked" : "unchecked") }),
755
+ row.icon && (0, import_react5.createElement)(kit.Tile, { key: "tile", icon: row.icon, tone: row.tone ?? "muted", size: 30 })
756
+ ],
757
+ title: row.title,
758
+ sub: row.sub,
759
+ meta: (0, import_react5.createElement)(
760
+ "span",
761
+ { className: "cb-rowMeta" },
762
+ row.chip && (0, import_react5.createElement)(import_dsh_client_ui_primitives2.Tag, { tone: kit.tagTone(row.chip.tone ?? "muted") }, row.chip.text),
763
+ (0, import_react5.createElement)(RowWhen, { row, locale, t })
764
+ )
765
+ })))
766
+ );
767
+ }
768
+ function StatusCard({ data, live, locale, rowActions }) {
769
+ const kit = useKit();
770
+ return (0, import_react5.createElement)("ul", { className: "cb-rows" }, data.rows.map((row, i) => (0, import_react5.createElement)(Row, {
771
+ key: row.key ?? i,
772
+ index: i,
773
+ row,
774
+ rowActions,
775
+ ...rowLive(live, row),
776
+ className: "cb-statusRow",
777
+ lead: row.icon ? (0, import_react5.createElement)(kit.Tile, { icon: row.icon, tone: row.tone, size: 28 }) : (0, import_react5.createElement)("span", { className: "cb-dotSlot" }, (0, import_react5.createElement)(import_dsh_client_ui_primitives2.StateDot, { state: STATE_OF_TONE[row.tone] ?? "idle" })),
778
+ title: row.label,
779
+ sub: row.sub,
780
+ spark: row.spark && (0, import_react5.createElement)("span", { className: "cb-statusSpark" }, (0, import_react5.createElement)(kit.Spark, { values: row.spark, tone: row.tone === "ok" ? "ok" : row.tone, height: 22 })),
781
+ value: (0, import_react5.createElement)("span", { className: "cb-statusValue", style: row.tone === "bad" || row.tone === "warn" ? { color: kit.toneColor(row.tone) } : void 0 }, formatNumber(row.value, locale))
782
+ })));
783
+ }
784
+ var PARTS = [[5, "dayPart.morning"], [12, "dayPart.afternoon"], [18, "dayPart.evening"], [22, "dayPart.night"]];
785
+ function dayLine(now, locale, t) {
786
+ const hour = new Date(now).getHours();
787
+ const part = [...PARTS].reverse().find(([from]) => hour >= from)?.[1] ?? "dayPart.night";
788
+ return { text: t("dayLine", { day: new Intl.DateTimeFormat(locale, { weekday: "long" }).format(now), part: t(part) }), dark: part === "dayPart.night" || part === "dayPart.evening" };
789
+ }
790
+ function SummaryBody({ card, locale, t, wash }) {
791
+ const kit = useKit();
792
+ const now = kit.useNow();
793
+ const day = dayLine(now, locale, t);
794
+ return (0, import_react5.createElement)(
795
+ "div",
796
+ { className: "cb-summary" },
797
+ (0, import_react5.createElement)("div", { className: "cb-summaryLine" }, (0, import_react5.createElement)(kit.Icon, { name: day.dark ? "moon" : "sun-medium", size: 14 }), (0, import_react5.createElement)("span", null, `${day.text} \xB7 ${card.title}`), wash && (0, import_react5.createElement)(kit.JustNow)),
798
+ (0, import_react5.createElement)("p", { className: "cb-summaryText" }, card.data.text),
799
+ card.data.chips?.length > 0 && (0, import_react5.createElement)("div", { className: "cb-chips" }, card.data.chips.map((chip, i) => (0, import_react5.createElement)(kit.Chip, { key: i, icon: chip.icon, tone: chip.tone ?? "muted", to: chip.to }, chip.text)))
800
+ );
801
+ }
802
+ function stepTimes(steps, locale) {
803
+ const here = Intl.DateTimeFormat().resolvedOptions().timeZone;
804
+ let lastDay = null;
805
+ return steps.map((step) => {
806
+ const time = toTime(step.at);
807
+ const zone = step.zone ?? here;
808
+ const day = new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(time);
809
+ const showDay = day !== lastDay;
810
+ lastDay = day;
811
+ const text = new Intl.DateTimeFormat(locale, { timeZone: zone, hour: "2-digit", minute: "2-digit", ...showDay ? { weekday: "short" } : {}, ...zone !== here ? { timeZoneName: "short" } : {} }).format(time);
812
+ return { time, text };
813
+ });
814
+ }
815
+ function CountdownBody({ card, locale }) {
816
+ const kit = useKit();
817
+ const now = kit.useNow();
818
+ const data = card.data;
819
+ const times = data.steps ? stepTimes(data.steps, locale) : [];
820
+ const next = times.findIndex((step) => step.time > now);
821
+ return (0, import_react5.createElement)(
822
+ "div",
823
+ { className: "cb-countdown" },
824
+ (0, import_react5.createElement)(
825
+ "div",
826
+ { className: "cb-countdownHead" },
827
+ (0, import_react5.createElement)(kit.Countdown, { to: data.to }),
828
+ (0, import_react5.createElement)(
829
+ "div",
830
+ { className: "cb-countdownText" },
831
+ (0, import_react5.createElement)("div", null, data.label),
832
+ data.sub && (0, import_react5.createElement)("div", { className: "cb-rowSub" }, data.sub)
833
+ )
834
+ ),
835
+ times.length > 0 && (0, import_react5.createElement)("ol", { className: "cb-track" }, data.steps.map((step, i) => (0, import_react5.createElement)(
836
+ "li",
837
+ { key: i, "data-state": i === next ? "next" : times[i].time <= now ? "past" : "later" },
838
+ (0, import_react5.createElement)("i", { "aria-hidden": true }),
839
+ (0, import_react5.createElement)("b", null, times[i].text),
840
+ (0, import_react5.createElement)("span", null, step.sub ? `${step.label} \xB7 ${step.sub}` : step.label)
841
+ )))
842
+ );
843
+ }
1083
844
 
1084
- ctx.effect(() => {
1085
- if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
1086
- const tag = document.createElement('style')
1087
- tag.id = STYLE_ID
1088
- tag.dataset.plugin = OWNER
1089
- tag.textContent = CSS
1090
- document.head.appendChild(tag)
1091
- return () => tag.remove()
1092
- }, 'card-board: styles')
845
+ // src/client/quote.js
846
+ function withUnit(value, unit, locale) {
847
+ return `${formatNumber(value, locale)}${unit ? ` ${unit}` : ""}`;
848
+ }
849
+ function statLines(data, locale) {
850
+ return data.items.map((item) => `${item.label}: ${withUnit(item.value, item.unit, locale)}${item.delta ? ` (${item.delta.text})` : ""}${item.sub ? ` \xB7 ${item.sub}` : ""}${item.progress?.text ? ` \xB7 ${item.progress.text}` : ""}`);
851
+ }
852
+ function listRowLine(row) {
853
+ const box = "checked" in row ? row.checked ? "\u2611 " : "\u2610 " : "";
854
+ return `${box}${row.title}${row.sub ? ` \xB7 ${row.sub}` : ""}${row.date ? ` \xB7 ${row.date}` : ""}${row.chip ? ` [${row.chip.text}]` : ""}`;
855
+ }
856
+ function statusRowLine(row, locale) {
857
+ return `${row.label}: ${formatNumber(row.value, locale)}${row.sub ? ` \xB7 ${row.sub}` : ""}`;
858
+ }
859
+ function summaryLines(card, locale, t) {
860
+ const data = card.data;
861
+ const lines = card.stat ? statLines(card.stat, locale) : [];
862
+ switch (card.type) {
863
+ case "summary":
864
+ return [data.text, ...(data.chips ?? []).map((chip) => chip.to ? `${chip.text} (${chip.to})` : chip.text)];
865
+ case "countdown":
866
+ return [`${data.label}: ${data.to}`, ...data.sub ? [data.sub] : [], ...(data.steps ?? []).map((step) => `${step.at} ${step.label}${step.sub ? ` \xB7 ${step.sub}` : ""}`)];
867
+ case "stat":
868
+ return statLines(data, locale);
869
+ case "line":
870
+ for (const series of data.series) {
871
+ const last = [...series.points].reverse().find((p) => typeof p.y === "number");
872
+ if (last) lines.push(t("summary.latest", { name: series.name || t("summary.latestName"), value: withUnit(last.y, data.unit, locale), x: last.x, n: series.points.length, from: series.points[0].x }));
873
+ }
874
+ if (data.goal?.y !== void 0) lines.push(t("summary.goal", { value: withUnit(data.goal.y, data.unit, locale) }));
875
+ return lines;
876
+ case "bar":
877
+ 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)}`));
878
+ case "donut": {
879
+ const total = data.segments.reduce((sum, s) => sum + s.value, 0);
880
+ return lines.concat(data.segments.map((s) => `${s.label}: ${withUnit(s.value, data.unit, locale)}${total > 0 ? ` (${Math.round(s.value / total * 100)}%)` : ""}`));
881
+ }
882
+ case "list":
883
+ return lines.concat(data.progress ? [t("summary.progress", data.progress)] : [], data.rows.slice(0, 15).map(listRowLine));
884
+ case "timeline":
885
+ return lines.concat((data.points ?? []).map((p) => `${p.date}: ${p.label}`), (data.spans ?? []).map((s) => `${s.from} \u2013 ${s.to}: ${s.label}`));
886
+ case "status":
887
+ return lines.concat(data.rows.map((row) => statusRowLine(row, locale)));
888
+ default:
889
+ return lines;
890
+ }
891
+ }
1093
892
 
1094
- ctx.slots.inject('main', () => ctx.slots.register({
1095
- name: 'main',
1096
- key: PANEL,
1097
- locale: NS,
1098
- }, BoardsPage))
1099
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1100
- name: 'sidebar.panellist',
1101
- id: PANEL,
1102
- order: 13,
1103
- locale: NS,
1104
- label: () => {
1105
- const text = sidebarT('panel')
1106
- return text === 'panel' ? '' : text
1107
- },
1108
- }, SidebarIcon))
893
+ // src/client/words.js
894
+ var import_react6 = require("react");
895
+ var messageRequests = /* @__PURE__ */ new Map();
896
+ function fetchMessages(tag) {
897
+ if (!messageRequests.has(tag)) {
898
+ const request = fetch(api(`locale?tag=${encodeURIComponent(tag)}`), { credentials: "same-origin" }).then((response) => response.ok ? response.json() : Promise.reject(new Error(`HTTP ${response.status}`))).then((body) => body.messages);
899
+ request.catch(() => messageRequests.delete(tag));
900
+ messageRequests.set(tag, request);
901
+ }
902
+ return messageRequests.get(tag);
903
+ }
904
+ var LANGUAGE_KEY = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/;
905
+ function pickText(value, active) {
906
+ if (typeof value !== "object" || value === null) return value;
907
+ const byId = new Map(Object.entries(value).map(([id, text]) => [id.toLowerCase(), text]));
908
+ const tag = String(active ?? "en").toLowerCase();
909
+ const primary = tag.split("-")[0];
910
+ return byId.get(tag) ?? byId.get(primary) ?? [...byId].find(([id]) => id.split("-")[0] === primary)?.[1] ?? byId.get("en") ?? [...byId.values()][0] ?? "";
911
+ }
912
+ function pickCard(card, active) {
913
+ const withPrompt = (payload) => payload && "prompt" in payload ? { ...payload, prompt: pickText(payload.prompt, active) } : payload;
914
+ const walk = (value) => {
915
+ if (Array.isArray(value)) return value.map(walk);
916
+ if (typeof value !== "object" || value === null) return value;
917
+ const keys = Object.keys(value);
918
+ if (keys.length > 0 && "en" in value && keys.every((key) => LANGUAGE_KEY.test(key)) && keys.every((key) => typeof value[key] === "string")) return pickText(value, active);
919
+ return Object.fromEntries(keys.map((key) => [key, key === "payload" ? withPrompt(value[key]) : walk(value[key])]));
920
+ };
921
+ return walk(card);
922
+ }
923
+ var fill = (text, params) => String(text).replace(/\{(\w+)\}/g, (match, key) => key in params ? String(params[key]) : match);
924
+ function intlTag(active) {
925
+ try {
926
+ return Intl.DateTimeFormat.supportedLocalesOf(active).length > 0 ? active : "en";
927
+ } catch {
928
+ return "en";
929
+ }
930
+ }
931
+ var translator = (messages) => (key, params) => {
932
+ const text = messages[key] ?? key;
933
+ return params ? fill(text, params) : text;
934
+ };
935
+ var clientCtx = null;
936
+ var setClientContext = (ctx) => {
937
+ clientCtx = ctx;
938
+ };
939
+ function useActiveLocale() {
940
+ const subscribe = (0, import_react6.useCallback)((listener) => clientCtx.locale.subscribe(listener), []);
941
+ const active = (0, import_react6.useSyncExternalStore)(subscribe, () => clientCtx.locale.getSnapshot().active);
942
+ const [loaded, setLoaded] = (0, import_react6.useState)(null);
943
+ const [attempt, setAttempt] = (0, import_react6.useState)(0);
944
+ (0, import_react6.useEffect)(() => {
945
+ let live = true;
946
+ let timer;
947
+ fetchMessages(active).then(
948
+ (messages) => {
949
+ if (live) setLoaded({ active, messages });
1109
950
  },
951
+ () => {
952
+ if (live) timer = setTimeout(() => setAttempt((count) => count + 1), 3e3);
953
+ }
954
+ );
955
+ return () => {
956
+ live = false;
957
+ clearTimeout(timer);
958
+ };
959
+ }, [active, attempt]);
960
+ return (0, import_react6.useMemo)(() => ({ active: loaded?.active ?? active, ready: loaded !== null, intl: intlTag(loaded?.active ?? active), t: translator(loaded?.messages ?? {}) }), [loaded, active]);
961
+ }
962
+
963
+ // src/client/card.js
964
+ var CHART_HEIGHT = { 1: 150, 2: 360, 3: 560 };
965
+ var CHART_HEIGHT_NARROW = { 1: 150, 2: 220, 3: 260 };
966
+ var CHARTS = { line: LineChart, bar: BarChart, donut: Donut, timeline: Timeline };
967
+ function statesOf(presses, row) {
968
+ const states = {};
969
+ for (const press of presses ?? []) if (press.row === row) states[press.id] = press.state;
970
+ return states;
971
+ }
972
+ function Body({ card, size, narrow, live, wash, locale, t, rowActions }) {
973
+ const data = card.data;
974
+ switch (card.type) {
975
+ case "stat":
976
+ return (0, import_react7.createElement)(StatBlock, { data, locale, wash });
977
+ case "list":
978
+ return (0, import_react7.createElement)(ListCard, { data, live, locale, t, rowActions });
979
+ case "status":
980
+ return (0, import_react7.createElement)(StatusCard, { data, live, locale, rowActions });
981
+ case "countdown":
982
+ return (0, import_react7.createElement)(CountdownBody, { card, locale });
983
+ default: {
984
+ const Chart = CHARTS[card.type];
985
+ if (Chart === void 0) return null;
986
+ const height = (narrow ? CHART_HEIGHT_NARROW : CHART_HEIGHT)[size.h];
987
+ return (0, import_react7.createElement)(Chart, { data, locale, height: card.type === "bar" ? Math.min(height, 130 + (size.h - 1) * 200) : card.type === "donut" ? Math.max(height, 160) : height });
1110
988
  }
989
+ }
990
+ }
991
+ function Card({ entry, live, boardId, assistant, columns, active, locale, t, press }) {
992
+ const kit = useKit();
993
+ const actions = useButtons();
994
+ const now = kit.useNow();
995
+ const wash = kit.useWash(live.wash, entry.id);
996
+ const full = entry.card?.type === "summary";
997
+ const size = { w: full ? columns : Math.min(entry.w ?? 1, columns), h: entry.h ?? 1 };
998
+ const style = { gridColumn: `span ${size.w}`, gridRow: size.h > 1 && columns > 1 && !full ? `span ${size.h}` : void 0 };
999
+ if (!entry.card) {
1000
+ return (0, import_react7.createElement)(
1001
+ "section",
1002
+ { className: "cb-card cb-cardError", style },
1003
+ (0, import_react7.createElement)("header", { className: "cb-cardHead" }, (0, import_react7.createElement)("h3", { title: entry.id }, entry.id)),
1004
+ (0, import_react7.createElement)("p", { className: "cb-errorText" }, t("cardError")),
1005
+ (0, import_react7.createElement)("ul", { className: "cb-problems" }, (entry.problems ?? []).map((p, i) => (0, import_react7.createElement)("li", { key: i }, p)))
1006
+ );
1007
+ }
1008
+ const card = pickCard(entry.card, active);
1009
+ if (card.type === "countdown" && card.data.expiresAt && Date.parse(card.data.expiresAt) <= now) return null;
1010
+ const updated = Date.parse(card.updatedAt);
1011
+ const age = Math.max(0, (now - updated) / 1e3);
1012
+ const stale = typeof card.staleAfter === "number" && age > card.staleAfter;
1013
+ const external = card.link && /^https?:/i.test(card.link);
1014
+ const about = (row, line) => ({
1015
+ source: OWNER,
1016
+ title: card.title,
1017
+ lines: row === void 0 ? summaryLines(card, locale, t).slice(0, 15) : [line],
1018
+ context: { board: boardId, card: entry.id, ...row === void 0 ? {} : { row }, type: card.type, updatedAt: card.updatedAt }
1019
+ });
1020
+ const rowLine = (row) => card.type === "status" ? statusRowLine(card.data.rows[row], locale) : listRowLine(card.data.rows[row]);
1021
+ const askName = assistant ? t("action.chatNamed", { name: assistant }) : void 0;
1022
+ const named = (list) => assistant ? list?.map((action) => action.kind === "chat" && action.label === void 0 ? { ...action, label: askName } : action) : list;
1023
+ const onPress = (target) => (action, extra) => press(action, extra, { card: entry.id, ...target });
1024
+ const rowActions = actions && ((row, list, part) => (0, import_react7.createElement)(actions.ActionBar, {
1025
+ actions: named(list),
1026
+ part,
1027
+ states: statesOf(entry.presses, row),
1028
+ compact: true,
1029
+ about: about(row, rowLine(row)),
1030
+ onPress: onPress({ row })
1031
+ }));
1032
+ const chat = actions && (0, import_react7.createElement)("span", { className: "cb-cardChat" }, (0, import_react7.createElement)(actions.ActionButton, { action: { kind: "chat", id: "_chat", label: askName }, compact: true, about: about() }));
1033
+ const others = card.actions?.filter((action) => action.kind !== "step") ?? [];
1034
+ const steps = card.actions?.some((action) => action.kind === "step") && (0, import_react7.createElement)(kit.Suggested, { actions: card.actions, about: about(), states: statesOf(entry.presses, void 0), onPress: onPress({}) });
1035
+ const footer = actions && others.length > 0 && (0, import_react7.createElement)("footer", { className: "cb-cardActions" }, (0, import_react7.createElement)(actions.ActionBar, {
1036
+ actions: named(others),
1037
+ part: "buttons",
1038
+ states: statesOf(entry.presses, void 0),
1039
+ about: about(),
1040
+ onPress: onPress({})
1041
+ }));
1042
+ const className = ["cb-card", `cb-card-${card.type}`, stale && "cb-cardStale", wash].filter(Boolean).join(" ");
1043
+ if (card.type === "summary") {
1044
+ return (0, import_react7.createElement)(
1045
+ "section",
1046
+ { className, style, "data-type": card.type },
1047
+ (0, import_react7.createElement)("div", { className: "cb-summaryMain" }, (0, import_react7.createElement)(SummaryBody, { card, locale, t, wash: wash !== "" }), steps, footer),
1048
+ (0, import_react7.createElement)("div", { className: "cb-summaryAside" }, live.fresh && (0, import_react7.createElement)(kit.NewDot), chat)
1049
+ );
1050
+ }
1051
+ const statBlock = card.stat && (0, import_react7.createElement)(StatBlock, { data: card.stat, locale, compact: true, wash: wash !== "" });
1052
+ const body = (0, import_react7.createElement)(Body, { card, size, narrow: columns === 1, live, wash: wash !== "", locale, t, rowActions });
1053
+ return (0, import_react7.createElement)(
1054
+ "section",
1055
+ { className, style, "data-type": card.type },
1056
+ (0, import_react7.createElement)(
1057
+ "header",
1058
+ { className: "cb-cardHead" },
1059
+ card.icon && (0, import_react7.createElement)(kit.Tile, { icon: card.icon, tone: card.tone ?? "muted", size: 30 }),
1060
+ (0, import_react7.createElement)(Trunc, { as: "h3", text: card.title }),
1061
+ live.fresh && (0, import_react7.createElement)(kit.NewDot),
1062
+ wash !== "" && card.type !== "stat" && !card.stat && (0, import_react7.createElement)(kit.JustNow),
1063
+ stale && (0, import_react7.createElement)(
1064
+ "span",
1065
+ { className: "cb-stale", title: new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(updated) },
1066
+ (0, import_react7.createElement)(import_dsh_client_ui_primitives3.Tag, { tone: "warning" }, t("stale", { age: formatAge(age, locale) }))
1067
+ ),
1068
+ card.link && (0, import_react7.createElement)("a", { className: "cb-cardLink", href: card.link, title: t("open"), "aria-label": t("open"), ...external ? { target: "_blank", rel: "noopener noreferrer" } : {} }, (0, import_react7.createElement)(import_dsh_client_ui_primitives3.IconRightUpOutlineRegular, { size: 14 })),
1069
+ chat
1070
+ ),
1071
+ statBlock && ["line", "bar", "donut"].includes(card.type) ? (0, import_react7.createElement)("div", { className: "cb-split" }, statBlock, (0, import_react7.createElement)("div", { className: "cb-cardBody" }, body)) : [statBlock && (0, import_react7.createElement)("div", { key: "stat" }, statBlock), (0, import_react7.createElement)("div", { key: "body", className: "cb-cardBody" }, body)],
1072
+ steps,
1073
+ footer
1074
+ );
1075
+ }
1076
+
1077
+ // src/client/live-state.js
1078
+ var EMPTY = Object.freeze({ wash: 0, rows: Object.freeze({}), fresh: false, freshRows: /* @__PURE__ */ new Set() });
1079
+ var liveOf = (live, id) => live[id] ?? EMPTY;
1080
+ function nextLive(before, after, live) {
1081
+ const old = new Map((before?.cards ?? []).map((entry) => [entry.id, entry]));
1082
+ const next = {};
1083
+ for (const entry of after.cards) {
1084
+ const was = old.get(entry.id);
1085
+ const state = liveOf(live, entry.id);
1086
+ let { wash, rows } = state;
1087
+ if (before !== null && entry.version !== void 0 && was?.version !== entry.version) {
1088
+ const changed = was === void 0 ? [] : Object.keys(entry.rows ?? {}).filter((key) => was.rows?.[key] !== entry.rows[key]);
1089
+ if (changed.length > 0) rows = { ...rows, ...Object.fromEntries(changed.map((key) => [key, (rows[key] ?? 0) + 1])) };
1090
+ else wash += 1;
1091
+ }
1092
+ const freshRows = entry.fresh?.rows?.length ? /* @__PURE__ */ new Set([...state.freshRows, ...entry.fresh.rows]) : state.freshRows;
1093
+ next[entry.id] = { wash, rows, fresh: state.fresh || entry.fresh?.card === true, freshRows };
1094
+ }
1095
+ return next;
1096
+ }
1097
+ function withCard(board, id, entry) {
1098
+ if (entry === null) return { ...board, cards: board.cards.filter((card) => card.id !== id) };
1099
+ const present = board.cards.some((card) => card.id === id);
1100
+ return { ...board, cards: present ? board.cards.map((card) => card.id === id ? entry : card) : [...board.cards, entry] };
1101
+ }
1102
+ function seenReport(board) {
1103
+ const cards = {};
1104
+ for (const entry of board.cards) if (entry.version !== void 0) cards[entry.id] = entry.rows ? { v: entry.version, rows: entry.rows } : { v: entry.version };
1105
+ return { board: board.id, cards };
1106
+ }
1107
+
1108
+ // src/client/page.js
1109
+ var STORE_KEY = "dsh-card-board:board";
1110
+ var SEEN_AFTER_MS = 2500;
1111
+ function requestError(status, body) {
1112
+ const error = new Error(body?.error ?? `HTTP ${status}`);
1113
+ error.status = status;
1114
+ return error;
1115
+ }
1116
+ async function getJson(path, etag) {
1117
+ const response = await fetch(api(path), { cache: "no-store", credentials: "same-origin", headers: etag ? { "if-none-match": etag } : {} });
1118
+ if (response.status === 304) return { notModified: true };
1119
+ let body = null;
1120
+ try {
1121
+ body = await response.json();
1122
+ } catch {
1123
+ }
1124
+ if (!response.ok) throw requestError(response.status, body);
1125
+ return { body, etag: response.headers.get("etag") };
1126
+ }
1127
+ var ERROR_KEYS = { 403: "error.forbidden", 404: "error.notFound", 409: "error.gone", 503: "error.noProvider" };
1128
+ var errorText = (error, t) => error.status === void 0 ? error.message : t(ERROR_KEYS[error.status] ?? "error.http", { status: error.status });
1129
+ function useColumns() {
1130
+ const [ref, width] = useWidth();
1131
+ return [ref, width >= 1400 ? 4 : width >= 980 ? 3 : width >= 620 ? 2 : 1];
1132
+ }
1133
+ var visible = () => document.visibilityState === "visible";
1134
+ function BoardsPage() {
1135
+ const kit = useKit();
1136
+ const { active, intl: locale, ready, t } = useActiveLocale();
1137
+ const [boards, setBoards] = (0, import_react8.useState)(null);
1138
+ const [listError, setListError] = (0, import_react8.useState)(null);
1139
+ const [selected, setSelected] = (0, import_react8.useState)(() => {
1140
+ try {
1141
+ return localStorage.getItem(STORE_KEY);
1142
+ } catch {
1143
+ return null;
1144
+ }
1145
+ });
1146
+ const [view, setView] = (0, import_react8.useState)({ board: null, live: {} });
1147
+ const [boardError, setBoardError] = (0, import_react8.useState)(null);
1148
+ const [pollSeconds, setPollSeconds] = (0, import_react8.useState)(30);
1149
+ const etag = (0, import_react8.useRef)(null);
1150
+ const [gridRef, columns] = useColumns();
1151
+ const currentRef = (0, import_react8.useRef)(null);
1152
+ const translateRef = (0, import_react8.useRef)(t);
1153
+ translateRef.current = t;
1154
+ const board = view.board;
1155
+ const boardRef = (0, import_react8.useRef)(null);
1156
+ boardRef.current = board;
1157
+ const show = (0, import_react8.useCallback)((next) => setView((prev) => ({
1158
+ board: next,
1159
+ live: next === null ? {} : nextLive(prev.board?.id === next.id ? prev.board : null, next, prev.board?.id === next.id ? prev.live : {})
1160
+ })), []);
1161
+ const loadList = (0, import_react8.useCallback)(async () => {
1162
+ try {
1163
+ const { body } = await getJson("boards");
1164
+ setBoards(body.boards);
1165
+ setPollSeconds(body.pollSeconds ?? 30);
1166
+ setListError(null);
1167
+ } catch (error) {
1168
+ setListError(error);
1169
+ }
1170
+ }, []);
1171
+ const current = boards?.some((b) => b.id === selected) ? selected : boards?.[0]?.id ?? null;
1172
+ const loadBoard = (0, import_react8.useCallback)(async (id, fresh) => {
1173
+ if (!id) return;
1174
+ try {
1175
+ const result = await getJson(`board?id=${encodeURIComponent(id)}`, fresh ? null : etag.current);
1176
+ setBoardError(null);
1177
+ if (result.notModified || currentRef.current !== id) return;
1178
+ etag.current = result.etag;
1179
+ show(result.body);
1180
+ } catch (error) {
1181
+ if (error.status === 403 || error.status === 404) {
1182
+ show(null);
1183
+ setBoardError(error);
1184
+ loadList();
1185
+ }
1186
+ }
1187
+ }, [loadList, show]);
1188
+ const loadCard = (0, import_react8.useCallback)(async (boardId, id) => {
1189
+ try {
1190
+ if (boardRef.current?.id !== boardId || !boardRef.current.cards.some((card) => card.id === id)) return loadBoard(boardId, false);
1191
+ const { body } = await getJson(`card?board=${encodeURIComponent(boardId)}&id=${encodeURIComponent(id)}`);
1192
+ setView((prev) => {
1193
+ if (prev.board?.id !== boardId) return prev;
1194
+ const next = withCard(prev.board, id, body);
1195
+ return { board: next, live: nextLive(prev.board, next, prev.live) };
1196
+ });
1197
+ } catch (error) {
1198
+ if (error.status === 404) setView((prev) => prev.board?.id === boardId ? { ...prev, board: withCard(prev.board, id, null) } : prev);
1199
+ else loadBoard(boardId, false);
1200
+ }
1201
+ }, [loadBoard]);
1202
+ const onEvent = (0, import_react8.useCallback)((message) => {
1203
+ const id = currentRef.current;
1204
+ if (!id) return;
1205
+ if (message.type === "card") loadCard(id, message.id);
1206
+ else if (message.type === "board" || message.type === "hello") loadBoard(id, false);
1207
+ else if (message.type === "gone") {
1208
+ show(null);
1209
+ setBoardError(requestError(403));
1210
+ loadList();
1211
+ }
1212
+ }, [loadBoard, loadCard, loadList, show]);
1213
+ const status = kit.useEventStream(current ? `api/card-board/events?board=${encodeURIComponent(current)}` : null, onEvent);
1214
+ const press = (0, import_react8.useCallback)(async (action, extra, target) => {
1215
+ const response = await fetch(api("action"), {
1216
+ method: "POST",
1217
+ credentials: "same-origin",
1218
+ headers: { "content-type": "application/json" },
1219
+ body: JSON.stringify({ board: currentRef.current, ...target, id: action.id, ...extra })
1220
+ });
1221
+ const body = await response.json().catch(() => null);
1222
+ if (!response.ok) throw new Error(errorText(requestError(response.status, body), translateRef.current));
1223
+ loadBoard(currentRef.current, false);
1224
+ return body;
1225
+ }, [loadBoard]);
1226
+ (0, import_react8.useEffect)(() => {
1227
+ loadList();
1228
+ }, [loadList]);
1229
+ (0, import_react8.useEffect)(() => {
1230
+ currentRef.current = current;
1231
+ if (!current) return;
1232
+ etag.current = null;
1233
+ setView((prev) => prev.board?.id === current ? prev : { board: null, live: {} });
1234
+ loadBoard(current, true);
1235
+ }, [current, loadBoard]);
1236
+ const waiting = board?.cards.some((entry) => entry.presses?.some((p) => p.state === "pending")) === true;
1237
+ (0, import_react8.useEffect)(() => {
1238
+ if (!current || status === "live" && !waiting) return void 0;
1239
+ let ticks = 0;
1240
+ const timer = setInterval(() => {
1241
+ if (!visible()) return;
1242
+ loadBoard(current, false);
1243
+ if (++ticks % 10 === 0) loadList();
1244
+ }, Math.max(5, pollSeconds) * 1e3);
1245
+ const onVisible = () => {
1246
+ if (visible()) {
1247
+ loadBoard(current, false);
1248
+ loadList();
1249
+ }
1250
+ };
1251
+ document.addEventListener("visibilitychange", onVisible);
1252
+ return () => {
1253
+ clearInterval(timer);
1254
+ document.removeEventListener("visibilitychange", onVisible);
1255
+ };
1256
+ }, [current, status, waiting, pollSeconds, loadBoard, loadList]);
1257
+ const reported = (0, import_react8.useRef)("");
1258
+ (0, import_react8.useEffect)(() => {
1259
+ if (!board) return void 0;
1260
+ const report = seenReport(board);
1261
+ const text = JSON.stringify(report);
1262
+ if (text === reported.current) return void 0;
1263
+ const timer = setTimeout(() => {
1264
+ if (!visible()) return;
1265
+ fetch(api("seen"), { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: text }).then((response) => {
1266
+ if (response.ok) reported.current = text;
1267
+ }, () => {
1268
+ });
1269
+ }, SEEN_AFTER_MS);
1270
+ return () => clearTimeout(timer);
1271
+ }, [board]);
1272
+ const choose = (id) => {
1273
+ setSelected(id);
1274
+ try {
1275
+ localStorage.setItem(STORE_KEY, id);
1276
+ } catch {
1277
+ }
1278
+ };
1279
+ const newest = board?.cards.reduce((max, entry) => {
1280
+ const time = entry.card ? Date.parse(entry.card.updatedAt) : NaN;
1281
+ return Number.isFinite(time) && time > max ? time : max;
1282
+ }, 0);
1283
+ const titleOf = (entry) => pickText(entry.title, active);
1284
+ if (!ready) return (0, import_react8.createElement)("div", { className: "cb-page" });
1285
+ let content;
1286
+ if (listError) content = (0, import_react8.createElement)("p", { className: "cb-notice" }, errorText(listError, t));
1287
+ else if (boards === null) content = (0, import_react8.createElement)("p", { className: "cb-muted" }, t("loading"));
1288
+ else if (boards.length === 0) content = (0, import_react8.createElement)("div", { className: "cb-empty" }, (0, import_react8.createElement)("p", { className: "cb-emptyTitle" }, t("emptyTitle")), (0, import_react8.createElement)("p", { className: "cb-muted" }, t("emptyHint")));
1289
+ else if (boardError) content = (0, import_react8.createElement)("p", { className: "cb-notice" }, errorText(boardError, t));
1290
+ else if (!board) content = (0, import_react8.createElement)("p", { className: "cb-muted" }, t("loading"));
1291
+ else content = (0, import_react8.createElement)(
1292
+ import_react8.Fragment,
1293
+ null,
1294
+ board.problems?.length > 0 && (0, import_react8.createElement)("div", { className: "cb-notice" }, t("boardProblems"), (0, import_react8.createElement)("ul", { className: "cb-problems" }, board.problems.map((p, i) => (0, import_react8.createElement)("li", { key: i }, p)))),
1295
+ board.cards.length === 0 && (0, import_react8.createElement)("p", { className: "cb-muted" }, t("noCards")),
1296
+ (0, import_react8.createElement)(
1297
+ "div",
1298
+ { className: "cb-grid", style: { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } },
1299
+ board.cards.map((entry) => (0, import_react8.createElement)(Card, { key: entry.id, entry, live: liveOf(view.live, entry.id), boardId: board.id, assistant: board.assistant, columns, active, locale, t, press }))
1300
+ )
1301
+ );
1302
+ return (0, import_react8.createElement)(
1303
+ "div",
1304
+ { className: "cb-page" },
1305
+ (0, import_react8.createElement)(
1306
+ "div",
1307
+ { className: "cb-content", ref: gridRef },
1308
+ (0, import_react8.createElement)(
1309
+ "div",
1310
+ { className: "cb-heading" },
1311
+ (0, import_react8.createElement)("h1", null, boards?.length === 1 ? titleOf(boards[0]) : t("title")),
1312
+ board && (0, import_react8.createElement)("div", { className: "cb-sub" }, (0, import_react8.createElement)(kit.LiveStatus, { status, updatedAt: newest || void 0 }))
1313
+ ),
1314
+ boards && boards.length > 1 && (0, import_react8.createElement)("div", { className: "cb-tabs", role: "tablist" }, boards.map((b) => (0, import_react8.createElement)(import_dsh_client_ui_primitives4.Pill, { key: b.id, active: b.id === current, role: "tab", "aria-selected": b.id === current, title: titleOf(b), onClick: () => choose(b.id) }, titleOf(b)))),
1315
+ content
1316
+ )
1317
+ );
1318
+ }
1319
+
1320
+ // src/client/index.js
1321
+ var NS = "dsh-card-board";
1322
+ var PANEL = "dsh-card-board";
1323
+ function SidebarIcon({ size }) {
1324
+ const stroke = { stroke: "currentColor", strokeWidth: 1.2, strokeLinecap: "round", strokeLinejoin: "round", fill: "none" };
1325
+ return (0, import_react9.createElement)(
1326
+ "svg",
1327
+ { width: size, height: size, viewBox: "0 0 16 16", "aria-hidden": true, focusable: "false" },
1328
+ (0, import_react9.createElement)("rect", { x: 1.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
1329
+ (0, import_react9.createElement)("rect", { x: 8.75, y: 1.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
1330
+ (0, import_react9.createElement)("rect", { x: 1.75, y: 8.75, width: 5.5, height: 5.5, rx: 1.4, ...stroke }),
1331
+ (0, import_react9.createElement)("path", { d: "M9 13.5l1.6-2 1.4 1 2-2.8", ...stroke })
1332
+ );
1333
+ }
1334
+ function Page() {
1335
+ return useKit() === null ? (0, import_react9.createElement)("div", { className: "cb-page" }) : (0, import_react9.createElement)(BoardsPage);
1336
+ }
1337
+ var inject = ["slots", "locale"];
1338
+ function apply(ctx) {
1339
+ setClientContext(ctx);
1340
+ let forget = () => {
1341
+ };
1342
+ ctx.effect(() => {
1343
+ let live = true;
1344
+ let loadedFor = null;
1345
+ const load = () => {
1346
+ const active = ctx.locale.getSnapshot().active;
1347
+ if (active === loadedFor) return;
1348
+ loadedFor = active;
1349
+ fetchMessages(active).then((messages) => {
1350
+ if (!live) return;
1351
+ forget();
1352
+ try {
1353
+ forget = ctx.locale.register(NS, active, { panel: messages.panel });
1354
+ } catch (error) {
1355
+ console.warn("card-board: sidebar name not registered:", error);
1356
+ }
1357
+ }, () => {
1358
+ if (live) {
1359
+ loadedFor = null;
1360
+ setTimeout(load, 3e3);
1361
+ }
1362
+ });
1363
+ };
1364
+ load();
1365
+ const stop = ctx.locale.subscribe(load);
1366
+ return () => {
1367
+ live = false;
1368
+ stop();
1369
+ forget();
1370
+ };
1371
+ }, "card-board: sidebar words");
1372
+ const sidebarT = ctx.locale.bind(NS);
1373
+ ctx.inject(["uiKit"], (scope) => {
1374
+ scope.effect(() => {
1375
+ kitStore.set(scope.uiKit);
1376
+ return () => kitStore.set(null);
1377
+ }, "card-board: shared pieces");
1378
+ });
1379
+ ctx.inject(["uiActions"], (scope) => {
1380
+ scope.effect(() => {
1381
+ buttonsStore.set(scope.uiActions);
1382
+ const unregister = scope.uiActions.registerSource({ id: OWNER, name: () => sidebarT("panel"), icon: SidebarIcon });
1383
+ return () => {
1384
+ unregister();
1385
+ buttonsStore.set(null);
1386
+ };
1387
+ }, "card-board: shared buttons");
1388
+ });
1389
+ ctx.effect(() => {
1390
+ if (typeof document === "undefined" || document.getElementById(STYLE_ID)) return () => {
1391
+ };
1392
+ const tag = document.createElement("style");
1393
+ tag.id = STYLE_ID;
1394
+ tag.dataset.plugin = OWNER;
1395
+ tag.textContent = CSS;
1396
+ document.head.appendChild(tag);
1397
+ return () => tag.remove();
1398
+ }, "card-board: styles");
1399
+ ctx.slots.inject("main", () => ctx.slots.register({ name: "main", key: PANEL, locale: NS }, Page));
1400
+ ctx.slots.inject("sidebar.panellist", () => ctx.slots.register({
1401
+ name: "sidebar.panellist",
1402
+ id: PANEL,
1403
+ order: 13,
1404
+ locale: NS,
1405
+ label: () => {
1406
+ const text = sidebarT("panel");
1407
+ return text === "panel" ? "" : text;
1408
+ }
1409
+ }, SidebarIcon));
1410
+ }
1411
+
1412
+ return module.exports
1111
1413
  },
1112
1414
  })