@soffits/dsh-card-board 0.4.2 → 0.6.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0
4
+
5
+ - Suggested next steps: cards and rows can carry `step` actions, concrete next steps whoever writes the card knows ("Renew the books online"). A tap records the press like done and snooze (the event `ui.action.step`, with who pressed it), then the step is sent with the card or row to the assistant as the person, and the button links to the conversation. At most 3 per card or row, a label of up to 80 characters is required. Needs @soffits/dsh-ui-actions 0.2.0.
6
+ - A row's steps sit on their own line under it; its other buttons stay beside the title.
7
+
8
+ ## 0.5.0
9
+
10
+ - The action buttons come from the shared [`@soffits/dsh-ui-actions`](https://github.com/soffits/dsh-ui-actions) plugin (`ctx.uiActions`) instead of a copy of `client.actions.js` in this package, which is gone. Install that plugin to get buttons; the page works without it, just without buttons. A chat button opens a conversation with the card or row attached to the message box as a small card, and the sent message shows it with the board's icon and name. The board names itself to it once, so cards from other pages read the same.
11
+ - Status rows with buttons stack (label and value above, sub-line and buttons beneath) on cards narrower than 520 px, so the value no longer gets squeezed in a two-column board.
12
+ - The buttons' own words (ask, done, snooze, pick a time, errors) now live in that plugin's language files; this package keeps only "Ask <name>".
13
+
3
14
  ## 0.4.2
4
15
 
5
16
  - List rows on narrow cards (a phone) keep their buttons beside the title, with the date and chip underneath, instead of putting the buttons on a line of their own: a long list takes about a third less height.
package/README.md CHANGED
@@ -219,17 +219,19 @@ A card, a list row or a status row can carry up to six buttons:
219
219
  "actions": [
220
220
  { "kind": "done", "id": "library-books:done" },
221
221
  { "kind": "snooze", "id": "library-books:snooze" },
222
+ { "kind": "step", "id": "library-books:renew", "label": { "en": "Renew the books online", "fr": "Renouveler les livres en ligne" } },
222
223
  { "kind": "chat", "id": "landlord:ask", "label": "Draft a message", "payload": { "prompt": "Help me write a short follow-up to the landlord." } },
223
224
  { "kind": "event", "id": "front-door:lock", "label": "Lock" },
224
225
  { "kind": "link", "id": "panel", "label": "Home panel", "payload": { "url": "https://example.com/home" } }
225
226
  ]
226
227
  ```
227
228
 
228
- - `chat` opens a new conversation (or the session named in `payload.session`) with a draft that quotes the card or row and carries its ids as JSON, after `payload.prompt` if you gave one. Nothing is sent until the person sends it, so the message comes from them like any other. Every card also has a chat button in its corner without declaring one; when the board names an `assistant` the button says who it asks. A `label` and `payload.prompt` can be text in several languages.
229
+ - `chat` opens a new conversation (or the session named in `payload.session`) with a draft that quotes the card or row and carries its ids as JSON, after `payload.prompt` if you gave one. Nothing is sent until the person sends it, so the message comes from them like any other. Every card also has a chat button in its corner without declaring one ("Chat about this"); when the board names an `assistant` the buttons say who they ask ("Ask Robin"). A `label` and `payload.prompt` can be text in several languages.
230
+ - `step` is a suggested next step the assistant starts on one tap: the label says the step plainly ("Renew the books online") and the tap is the person's go-ahead for exactly that. The press is recorded on the server like `done`, then the page sends the step (`payload.prompt` when it needs more words than the label, never more than it authorises; otherwise the label) with the card or row into a new session (or `payload.session`) as the person, with no draft to confirm, and the button links to that session. At most 3 steps per card or row; add one only where the data has a clear next step. The label (up to 80 characters) is required.
229
231
  - `done`, `snooze` and `event` are pressed on the server. A snooze without `payload.until` asks: in 3 hours, tomorrow at 9:00, or a time.
230
232
  - `link` opens `payload.url`.
231
233
 
232
- `id` is yours: letters, digits and `. _ : -`, unique within the card or row. `label` is optional except for `event`. `payload` is any small object (up to 4 KB of JSON).
234
+ `id` is yours: letters, digits and `. _ : -`, unique within the card or row. `label` is optional except for `event` and `step`. `payload` is any small object (up to 4 KB of JSON).
233
235
 
234
236
  The plugin doesn't act on a press itself. It checks that the person may see the board and that the action is in the card as written, then records an event:
235
237
 
@@ -250,7 +252,7 @@ It's appended to the action log, emitted in-process as the Cordis event `card-bo
250
252
 
251
253
  The button shows the press as pending until the card file is written again, then done. If nothing rewrites the card within `actionTimeoutSeconds`, it says nothing picked the press up. So a handler should rewrite the card when it has acted, even if only `updatedAt` changes.
252
254
 
253
- The buttons come from [`client.actions.js`](client.actions.js), loaded with the page. On a phone they are at least 40 px, and a snooze picker opens as a sheet at the bottom of the screen.
255
+ The buttons come from [`@soffits/dsh-ui-actions`](https://github.com/soffits/dsh-ui-actions), a separate plugin the board uses when it is installed (`dsh plugin --profile web add @soffits/dsh-ui-actions`; DSH 0.2.2-rc.1 or later). Without it cards show no buttons. A chat button opens a new conversation with the card or row attached to the message box as a small card, and the person writes beside it; a chat button's words ("Ask", "Chat about this") and the done and snooze buttons' words come from that plugin, in the person's language. On a phone the buttons are at least 40 px, and a snooze picker opens as a sheet at the bottom of the screen.
254
256
 
255
257
  ## Writing cards: the CLI
256
258
 
package/client.js CHANGED
@@ -17,6 +17,7 @@ window.__ModuleLoader__.load({
17
17
  const { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallback } = React
18
18
 
19
19
  const NS = 'dsh-card-board'
20
+ const OWNER = '@soffits/dsh-card-board'
20
21
  const PANEL = 'dsh-card-board'
21
22
  const STYLE_ID = 'dsh-card-board-style'
22
23
  const STORE_KEY = 'dsh-card-board:board'
@@ -24,8 +25,8 @@ window.__ModuleLoader__.load({
24
25
 
25
26
  // ---- the page's own words -------------------------------------------------------
26
27
  // One file per language in the package's locale folder (`ui` in locale/<tag>.json), served by the
27
- // Host for the active language; the action buttons (client.actions.js) take theirs from the same
28
- // files under `action.`. The code names no language. A test fails when a component renders a
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
29
30
  // literal string instead of one of these.
30
31
 
31
32
  const messageRequests = new Map()
@@ -80,7 +81,7 @@ window.__ModuleLoader__.load({
80
81
  return params ? fill(text, params) : text
81
82
  }
82
83
 
83
- /** The client context: the locale service and the Web UI services the actions reach (set in apply). */
84
+ /** The client context, for the locale service (set in apply). */
84
85
  let clientCtx = null
85
86
 
86
87
  /**
@@ -103,15 +104,20 @@ window.__ModuleLoader__.load({
103
104
  return useMemo(() => ({ active: loaded?.active ?? active, ready: loaded !== null, intl: intlTag(loaded?.active ?? active), t: translator(loaded?.messages ?? {}) }), [loaded, active])
104
105
  }
105
106
 
106
- /** The shared action buttons (client.actions.js), loaded with the page. */
107
- let actionsModule
108
- const loadActions = () => {
109
- actionsModule ??= require.async('./client.actions.js').catch(error => {
110
- actionsModule = undefined
111
- throw error
112
- })
113
- return actionsModule
114
- }
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)
115
121
 
116
122
  // ---- numbers, dates, tones -------------------------------------------------
117
123
 
@@ -481,6 +487,9 @@ window.__ModuleLoader__.load({
481
487
  progress.label && size >= 90 && h('span', null, progress.label)))
482
488
  }
483
489
 
490
+ /** A row's suggested steps go on their own line under it; its other buttons stay beside the title. */
491
+ const hasSteps = row => row.actions?.some(action => action.kind === 'step') === true
492
+
484
493
  function ListCard({ data, locale, t, rowActions }) {
485
494
  const [ref, width] = useWidth()
486
495
  const checkable = data.rows.some(row => 'checked' in row)
@@ -495,7 +504,8 @@ window.__ModuleLoader__.load({
495
504
  (row.date || row.chip) && h('span', { className: 'cb-listMeta' },
496
505
  row.date && h('span', { className: 'cb-listDate' }, formatDay(toTime(row.date), locale, 0)),
497
506
  row.chip && h(Chip, row.chip)),
498
- row.actions && rowActions && h('span', { className: 'cb-rowActions' }, rowActions(i, row.actions, listRowLine(row))))))
507
+ row.actions && rowActions && h('span', { className: 'cb-rowActions' }, rowActions(i, row.actions, listRowLine(row), 'buttons')),
508
+ hasSteps(row) && rowActions && h('div', { className: 'cb-rowSteps' }, rowActions(i, row.actions, listRowLine(row), 'steps')))))
499
509
  if (!data.progress) return rows
500
510
  // Beside the rows when there is room for both, else a small ring with its count above them.
501
511
  const wide = width >= 460
@@ -601,7 +611,8 @@ window.__ModuleLoader__.load({
601
611
  h('span', { className: 'cb-statusNum', style: row.tone === 'bad' || row.tone === 'warn' ? { color: toneColor(row.tone) } : undefined }, formatNumber(row.value, locale)),
602
612
  row.sub && h(Trunc, { as: 'small', className: 'cb-statusSub', lines: 2, text: row.sub })),
603
613
  sparks && (row.spark ? h(Spark, { values: row.spark, color: toneColor(row.tone === 'ok' ? 'accent' : row.tone) }) : h('span', { className: 'cb-spark' })),
604
- hasActions && h('span', { className: 'cb-rowActions' }, rowActions && row.actions ? rowActions(i, row.actions, statusRowLine(row, locale)) : null))))
614
+ hasActions && h('span', { className: 'cb-rowActions' }, rowActions && row.actions ? rowActions(i, row.actions, statusRowLine(row, locale), 'buttons') : null),
615
+ hasSteps(row) && rowActions && h('div', { className: 'cb-rowSteps' }, rowActions(i, row.actions, statusRowLine(row, locale), 'steps')))))
605
616
  }
606
617
 
607
618
  // ---- what a chat quotes ----------------------------------------------------
@@ -685,7 +696,7 @@ window.__ModuleLoader__.load({
685
696
  h('path', { d: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5' }))
686
697
  }
687
698
 
688
- function Card({ entry, boardId, assistant, columns, now, active, locale, t, actions }) {
699
+ function Card({ entry, boardId, assistant, columns, now, active, locale, t, actions, press }) {
689
700
  const size = { w: Math.min(entry.w ?? 1, columns), h: entry.h ?? 1 }
690
701
  const style = { gridColumn: `span ${size.w}`, gridRow: size.h > 1 && columns > 1 ? `span ${size.h}` : undefined }
691
702
  if (!entry.card) {
@@ -699,40 +710,37 @@ window.__ModuleLoader__.load({
699
710
  const age = Math.max(0, (now - updated) / 1000)
700
711
  const stale = typeof card.staleAfter === 'number' && age > card.staleAfter
701
712
  const external = card.link && /^https?:/i.test(card.link)
702
- const context = row => ({ board: boardId, card: entry.id, ...(row === undefined ? {} : { row }), type: card.type, updatedAt: card.updatedAt })
703
- // A chat opens a new conversation whose draft quotes the card (or the row) and names it.
704
- const chat = (action, row, rowLine) => actions.startChat({
705
- text: actions.chatText({
706
- prompt: action.payload?.prompt ?? '',
707
- title: card.title,
708
- lines: row === undefined ? summaryLines(card, locale, t) : [rowLine],
709
- context: action.payload?.context ?? context(row),
710
- }),
711
- session: action.payload?.session,
713
+ // What a chat is about: the card as a few lines, or one row of it.
714
+ const about = (row, rowLine) => ({
715
+ source: OWNER,
716
+ title: card.title,
717
+ lines: row === undefined ? summaryLines(card, locale, t).slice(0, 15) : [rowLine],
718
+ context: { board: boardId, card: entry.id, ...(row === undefined ? {} : { row }), type: card.type, updatedAt: card.updatedAt },
712
719
  })
713
720
  // A chat button without its own label says "Ask <assistant>" when the board names one.
714
- const named = list => (assistant ? list?.map(action => (action.kind === 'chat' && action.label === undefined ? { ...action, label: t('action.chatNamed', { name: assistant }) } : action)) : list)
715
- const defaultChat = { kind: 'chat', id: '_chat', label: assistant ? t('action.chatNamed', { name: assistant }) : t('action.chatAbout') }
716
- const rowActions = actions && ((row, list, line) => h(actions.ActionBar, {
721
+ const askName = assistant ? t('action.chatNamed', { name: assistant }) : undefined
722
+ const named = list => (assistant ? list?.map(action => (action.kind === 'chat' && action.label === undefined ? { ...action, label: askName } : action)) : list)
723
+ const rowActions = actions && ((row, list, line, part) => h(actions.ActionBar, {
717
724
  actions: named(list),
725
+ part,
718
726
  states: statesOf(entry.presses, row),
719
727
  compact: true,
720
- chat: action => chat(action, row, line),
721
- onPress: (action, extra) => actions.press(action, extra, { card: entry.id, row }),
728
+ about: about(row, line),
729
+ onPress: (action, extra) => press(action, extra, { card: entry.id, row }),
722
730
  }))
723
731
  return h('section', { className: `cb-card${stale ? ' cb-cardStale' : ''}`, style, 'data-type': card.type },
724
732
  h('header', { className: 'cb-cardHead' },
725
733
  h(Trunc, { as: 'h3', text: card.title }),
726
734
  stale && h('span', { className: 'cb-staleChip', title: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(updated) }, t('stale', { age: formatAge(age, locale) })),
727
735
  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)),
728
- actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: defaultChat, compact: true, chat: action => chat(action) }))),
736
+ actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: { kind: 'chat', id: '_chat', label: askName }, compact: true, about: about() }))),
729
737
  card.stat && h(StatBlock, { data: card.stat, locale, compact: true }),
730
738
  h('div', { className: 'cb-cardBody' }, h(CardBody, { card, size, narrow: columns === 1, locale, t, rowActions })),
731
739
  actions && card.actions && h('footer', { className: 'cb-cardActions' }, h(actions.ActionBar, {
732
740
  actions: named(card.actions),
733
741
  states: statesOf(entry.presses, undefined),
734
- chat: action => chat(action),
735
- onPress: (action, extra) => actions.press(action, extra, { card: entry.id }),
742
+ about: about(),
743
+ onPress: (action, extra) => press(action, extra, { card: entry.id }),
736
744
  })))
737
745
  }
738
746
 
@@ -774,7 +782,7 @@ window.__ModuleLoader__.load({
774
782
  const [now, setNow] = useState(() => Date.now())
775
783
  const etag = useRef(null)
776
784
  const [gridRef, columns] = useColumns()
777
- const [actions, setActions] = useState(null)
785
+ const actions = useButtons()
778
786
  const currentRef = useRef(null)
779
787
  // The buttons ask for words at render time, so a language switch reaches them without rebuilding them.
780
788
  const translateRef = useRef(t)
@@ -810,27 +818,18 @@ window.__ModuleLoader__.load({
810
818
 
811
819
  useEffect(() => { loadList() }, [loadList])
812
820
 
813
- // The action buttons load with the page; until then (or if they fail) cards show without them.
814
- useEffect(() => {
815
- let live = true
816
- loadActions().then(({ createActions }) => {
817
- if (!live) return
818
- const press = async (action, extra, target) => {
819
- const response = await fetch(api('action'), {
820
- method: 'POST',
821
- credentials: 'same-origin',
822
- headers: { 'content-type': 'application/json' },
823
- body: JSON.stringify({ board: currentRef.current, ...target, id: action.id, ...extra }),
824
- })
825
- const body = await response.json().catch(() => null)
826
- if (!response.ok) throw new Error(errorText(requestError(response.status, body), translateRef.current))
827
- loadBoard(currentRef.current, false)
828
- return body
829
- }
830
- const ui = createActions({ React, ctx: clientCtx, t: (key, params) => translateRef.current(`action.${key}`, params) })
831
- setActions({ ...ui, press })
832
- }, error => console.warn('card-board: action buttons not loaded:', error))
833
- return () => { live = false }
821
+ // A press of done, snooze or event goes to this plugin's server, which checks it and records it.
822
+ const press = useCallback(async (action, extra, target) => {
823
+ const response = await fetch(api('action'), {
824
+ method: 'POST',
825
+ credentials: 'same-origin',
826
+ headers: { 'content-type': 'application/json' },
827
+ body: JSON.stringify({ board: currentRef.current, ...target, id: action.id, ...extra }),
828
+ })
829
+ const body = await response.json().catch(() => null)
830
+ if (!response.ok) throw new Error(errorText(requestError(response.status, body), translateRef.current))
831
+ loadBoard(currentRef.current, false)
832
+ return body
834
833
  }, [loadBoard])
835
834
 
836
835
  useEffect(() => {
@@ -878,7 +877,7 @@ window.__ModuleLoader__.load({
878
877
  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)))),
879
878
  board.cards.length === 0 && h('p', { className: 'cb-muted' }, t('noCards')),
880
879
  h('div', { className: 'cb-grid', style: { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } },
881
- board.cards.map(entry => h(Card, { key: entry.id, entry, boardId: board.id, assistant: board.assistant, columns, now, active, locale, t, actions }))))
880
+ board.cards.map(entry => h(Card, { key: entry.id, entry, boardId: board.id, assistant: board.assistant, columns, now, active, locale, t, actions, press }))))
882
881
 
883
882
  return h('div', { className: 'cb-page' },
884
883
  h('div', { className: 'cb-content', ref: gridRef },
@@ -985,7 +984,10 @@ h3.cb-truncOpen{overflow:visible}
985
984
  .cb-progressLine strong{font-size:10px!important}
986
985
 
987
986
  .cb-listMain{flex:1;min-width:0}
988
- .cb-list li{display:flex;align-items:center;gap:10px;padding:8px 2px;border-top:.5px solid var(--dsw-alias-border-l2)}
987
+ .cb-list li{display:flex;flex-wrap:wrap;align-items:center;gap:10px;padding:8px 2px;border-top:.5px solid var(--dsw-alias-border-l2)}
988
+ .cb-rowSteps{flex-basis:100%;min-width:0}
989
+ .cb-list li .cb-checkBox~.cb-rowSteps{padding-left:28px}
990
+ .cb-status li>.cb-rowSteps{grid-column:2/-1}
989
991
  .cb-list li:first-child{border-top:0}
990
992
  .cb-listText{flex:1;min-width:0}
991
993
  .cb-listSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}
@@ -1017,18 +1019,29 @@ h3.cb-truncOpen{overflow:visible}
1017
1019
  .cb-list li .cb-listText{grid-column:2;grid-row:1}
1018
1020
  .cb-list li .cb-rowActions{grid-column:3;grid-row:1;margin-left:8px}
1019
1021
  .cb-list li .cb-listMeta{grid-column:2/-1;grid-row:2;margin-top:2px}
1022
+ .cb-list li .cb-rowSteps,.cb-list li .cb-checkBox~.cb-rowSteps{grid-column:2/-1;grid-row:3;margin-top:6px;padding-left:0}
1020
1023
  }
1021
1024
  @container (width<380px){
1022
- .cb-status,.cb-statusSparks,.cb-statusActions,.cb-statusSparks.cb-statusActions{grid-template-columns:8px minmax(0,1fr) auto}
1023
- .cb-statusValue{display:contents}
1025
+ .cb-status,.cb-statusSparks{grid-template-columns:8px minmax(0,1fr) auto}
1026
+ .cb-status .cb-statusValue{display:contents}
1027
+ .cb-status .cb-statusLabel{grid-column:2;grid-row:1}
1028
+ .cb-status .cb-statusNum{grid-column:3;grid-row:1;justify-self:end}
1029
+ .cb-status .cb-statusSub{grid-column:2/-1;grid-row:2}
1024
1030
  .cb-status li>.cb-dot{grid-column:1;grid-row:1}
1025
- .cb-statusLabel{grid-column:2;grid-row:1}
1026
- .cb-statusNum{grid-column:3;grid-row:1;justify-self:end}
1027
- .cb-statusSub{grid-column:2/-1;grid-row:2}
1028
1031
  .cb-status li>.cb-spark{grid-column:2/-1;grid-row:3}
1029
1032
  .cb-spark:empty{display:none}
1033
+ }
1034
+ @container (width<520px){
1035
+ .cb-statusActions,.cb-statusSparks.cb-statusActions{grid-template-columns:8px minmax(0,1fr) auto}
1036
+ .cb-statusActions .cb-statusValue{display:contents}
1037
+ .cb-statusActions .cb-statusLabel{grid-column:2;grid-row:1}
1038
+ .cb-statusActions .cb-statusNum{grid-column:3;grid-row:1;justify-self:end}
1039
+ .cb-statusActions .cb-statusSub{grid-column:2/-1;grid-row:2}
1040
+ .cb-statusActions li>.cb-dot{grid-column:1;grid-row:1}
1041
+ .cb-statusActions li>.cb-spark{grid-column:2/-1;grid-row:3}
1030
1042
  .cb-statusActions li .cb-rowActions{grid-column:2/-1;grid-row:4;justify-content:flex-start}
1031
1043
  }
1044
+ }
1032
1045
  @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}}
1033
1046
  @media (width<=768px),(pointer:coarse){
1034
1047
  .cb-cardLink{width:40px;height:40px;margin:-9px 0}
@@ -1068,11 +1081,21 @@ h3.cb-truncOpen{overflow:visible}
1068
1081
  }, 'card-board: sidebar words')
1069
1082
  const sidebarT = ctx.locale.bind(NS)
1070
1083
 
1084
+ // The shared buttons, once @soffits/dsh-ui-actions is there; the board also names itself there, so a chat
1085
+ // started from a card shows the board's icon and name.
1086
+ ctx.inject(['uiActions'], scope => {
1087
+ scope.effect(() => {
1088
+ buttonsStore.set(scope.uiActions)
1089
+ const unregister = scope.uiActions.registerSource({ id: OWNER, name: () => sidebarT('panel'), icon: SidebarIcon })
1090
+ return () => { unregister(); buttonsStore.set(null) }
1091
+ }, 'card-board: shared buttons')
1092
+ })
1093
+
1071
1094
  ctx.effect(() => {
1072
1095
  if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
1073
1096
  const tag = document.createElement('style')
1074
1097
  tag.id = STYLE_ID
1075
- tag.dataset.plugin = '@soffits/dsh-card-board'
1098
+ tag.dataset.plugin = OWNER
1076
1099
  tag.textContent = CSS
1077
1100
  document.head.appendChild(tag)
1078
1101
  return () => tag.remove()
@@ -37,6 +37,20 @@
37
37
  "tone": "warn"
38
38
  },
39
39
  "actions": [
40
+ {
41
+ "kind": "step",
42
+ "id": "library-books:renew",
43
+ "label": {
44
+ "en": "Renew the books online",
45
+ "fr": "Renouveler les livres en ligne",
46
+ "zh": "在网上续借这些书"
47
+ },
48
+ "payload": {
49
+ "prompt": {
50
+ "en": "Renew the library books that are due on the library's website, then tell me the new due date."
51
+ }
52
+ }
53
+ },
40
54
  {
41
55
  "kind": "done",
42
56
  "id": "library-books:done"
package/locale/en.json CHANGED
@@ -28,23 +28,6 @@
28
28
  "summary.latestName": "latest",
29
29
  "summary.goal": "goal: {value}",
30
30
  "summary.progress": "progress: {done}/{total}",
31
- "action.chat": "Ask",
32
- "action.chatAbout": "Chat about this",
33
- "action.done": "Done",
34
- "action.snooze": "Snooze",
35
- "action.event": "Go",
36
- "action.link": "Open",
37
- "action.in3h": "In 3 hours",
38
- "action.tomorrow": "Tomorrow 9:00",
39
- "action.pick": "Pick a time…",
40
- "action.set": "Snooze",
41
- "action.cancel": "Cancel",
42
- "action.sending": "Sending…",
43
- "action.pending": "Waiting for it to be picked up",
44
- "action.handled": "Done",
45
- "action.unhandled": "Nothing picked this up yet",
46
- "action.failed": "Didn’t go through: {message}",
47
- "action.noWorkspace": "Open a conversation once first, then try again.",
48
31
  "action.chatNamed": "Ask {name}"
49
32
  }
50
33
  }
package/locale/fr.json CHANGED
@@ -28,23 +28,6 @@
28
28
  "summary.latestName": "dernière valeur",
29
29
  "summary.goal": "objectif : {value}",
30
30
  "summary.progress": "progression : {done}/{total}",
31
- "action.chat": "Demander",
32
- "action.chatAbout": "En discuter",
33
- "action.done": "Fait",
34
- "action.snooze": "Reporter",
35
- "action.event": "Lancer",
36
- "action.link": "Ouvrir",
37
- "action.in3h": "Dans 3 heures",
38
- "action.tomorrow": "Demain à 9 h",
39
- "action.pick": "Choisir une heure…",
40
- "action.set": "Reporter",
41
- "action.cancel": "Annuler",
42
- "action.sending": "Envoi…",
43
- "action.pending": "En attente de prise en charge",
44
- "action.handled": "Fait",
45
- "action.unhandled": "Personne ne s’en est encore occupé",
46
- "action.failed": "Échec : {message}",
47
- "action.noWorkspace": "Ouvrez d’abord une conversation, puis réessayez.",
48
31
  "action.chatNamed": "Demander à {name}"
49
32
  }
50
33
  }
package/locale/zh.json CHANGED
@@ -28,23 +28,6 @@
28
28
  "summary.latestName": "最新",
29
29
  "summary.goal": "目标:{value}",
30
30
  "summary.progress": "进度:{done}/{total}",
31
- "action.chat": "问问",
32
- "action.chatAbout": "聊聊这个",
33
- "action.done": "完成",
34
- "action.snooze": "稍后提醒",
35
- "action.event": "执行",
36
- "action.link": "打开",
37
- "action.in3h": "3 小时后",
38
- "action.tomorrow": "明天 9:00",
39
- "action.pick": "选个时间…",
40
- "action.set": "稍后提醒",
41
- "action.cancel": "取消",
42
- "action.sending": "发送中…",
43
- "action.pending": "等待处理",
44
- "action.handled": "已处理",
45
- "action.unhandled": "还没有被处理",
46
- "action.failed": "没有成功:{message}",
47
- "action.noWorkspace": "请先打开一次对话,再试一次。",
48
31
  "action.chatNamed": "问问 {name}"
49
32
  }
50
33
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-card-board",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "A data-driven card board for DeepSeek Harness: scripts write small JSON cards, the Web UI shows each person the boards they may see.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,7 +37,6 @@
37
37
  "bin",
38
38
  "src",
39
39
  "client.js",
40
- "client.actions.js",
41
40
  "index.js",
42
41
  "cordis.patch.yml",
43
42
  "locale/*.json",
@@ -57,7 +56,8 @@
57
56
  "inject": [
58
57
  "@deepseek-ai/dsh-client-locale",
59
58
  "@deepseek-ai/dsh-client-ui-layout",
60
- "@deepseek-ai/dsh-client-ui-sidebar"
59
+ "@deepseek-ai/dsh-client-ui-sidebar",
60
+ "@soffits/dsh-ui-actions"
61
61
  ]
62
62
  }
63
63
  },
package/src/schema.js CHANGED
@@ -10,9 +10,11 @@
10
10
 
11
11
  export const CARD_TYPES = Object.freeze(['stat', 'line', 'bar', 'donut', 'list', 'timeline', 'status'])
12
12
  export const TONES = Object.freeze(['ok', 'warn', 'bad', 'muted', 'accent'])
13
- export const ACTION_KINDS = Object.freeze(['chat', 'done', 'snooze', 'event', 'link'])
13
+ export const ACTION_KINDS = Object.freeze(['chat', 'step', 'done', 'snooze', 'event', 'link'])
14
14
  /** Kinds the server records as events; chat and link happen in the browser only. */
15
- export const PRESS_KINDS = Object.freeze(['done', 'snooze', 'event'])
15
+ export const PRESS_KINDS = Object.freeze(['step', 'done', 'snooze', 'event'])
16
+ /** Suggested steps per card or row: a few clear next moves, not a menu. */
17
+ export const MAX_STEPS = 3
16
18
  export const ACTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/
17
19
  const MAX_ACTIONS = 6
18
20
  const MAX_PAYLOAD_BYTES = 4096
@@ -145,6 +147,7 @@ function tone(c, value, path) {
145
147
  /** Problems with an `actions` list (on a card, a list row or a status row). */
146
148
  function actions(c, list, path) {
147
149
  if (!c.array(list, path, { max: MAX_ACTIONS })) return
150
+ if (list.filter(action => action?.kind === 'step').length > MAX_STEPS) c.fail(path, `has more than ${MAX_STEPS} steps`)
148
151
  const seen = new Set()
149
152
  list.forEach((action, i) => {
150
153
  const p = join(path, i)
@@ -153,8 +156,8 @@ function actions(c, list, path) {
153
156
  if (typeof action.id !== 'string' || !ACTION_ID_PATTERN.test(action.id)) c.fail(join(p, 'id'), 'must be letters, digits and . _ : - (up to 100), starting with a letter or digit')
154
157
  else if (seen.has(action.id)) c.fail(join(p, 'id'), 'repeats another action id here')
155
158
  else seen.add(action.id)
156
- if ('label' in action) c.label(action.label, join(p, 'label'), { max: 40 })
157
- else if (action.kind === 'event') c.fail(join(p, 'label'), 'is required for an event action')
159
+ if ('label' in action) c.label(action.label, join(p, 'label'), { max: action.kind === 'step' ? 80 : 40 })
160
+ else if (action.kind === 'event' || action.kind === 'step') c.fail(join(p, 'label'), `is required for ${action.kind === 'step' ? 'a step: it says the step plainly' : 'an event action'}`)
158
161
  const payload = action.payload
159
162
  if ('payload' in action) {
160
163
  const pp = join(p, 'payload')
@@ -166,7 +169,7 @@ function actions(c, list, path) {
166
169
  if (!isSafeLink(payload?.url)) c.fail(join(join(p, 'payload'), 'url'), 'is required: an http(s) URL or a path starting with /')
167
170
  }
168
171
  if (action.kind === 'snooze' && payload !== undefined && 'until' in payload) c.dateTime(payload.until, join(join(p, 'payload'), 'until'))
169
- if (action.kind === 'chat' && payload !== undefined) {
172
+ if ((action.kind === 'chat' || action.kind === 'step') && payload !== undefined) {
170
173
  const pp = join(p, 'payload')
171
174
  if ('prompt' in payload) c.label(payload.prompt, join(pp, 'prompt'), { max: 2000 })
172
175
  if ('session' in payload) c.text(payload.session, join(pp, 'session'), { max: 200 })
package/client.actions.js DELETED
@@ -1,234 +0,0 @@
1
- /*
2
- * Action buttons for DSH Web UI plugins: chat, done, snooze, event and link,
3
- * the same look and behaviour wherever an item offers them.
4
- *
5
- * A DSH client chunk: dsh-card-board's client loads it with
6
- * `require.async('./client.actions.js')`. Another plugin can ship a copy as
7
- * its own `client.actions.js`, changing OWNER below to its package name.
8
- *
9
- * DSH runs a chunk as a classic script, so everything sits inside one function
10
- * (a top-level `const` would clash with another plugin's copy and the second
11
- * chunk would never register).
12
- *
13
- * const { createActions } = await require.async('./client.actions.js')
14
- * const ui = createActions({ React, ctx, t, press })
15
- * h(ui.ActionBar, { actions, states, chat, onPress })
16
- *
17
- * `t(key, params)` gives the words in the person's language; the host plugin
18
- * keeps them in its one message table. The keys it must know are exported as
19
- * `KEYS`: chat, chatAbout, done, snooze, event, link, in3h, tomorrow, pick,
20
- * set, cancel, sending, pending, handled, unhandled, failed ({message}),
21
- * noWorkspace. `t` is called while rendering, so a language switch shows up
22
- * without building the buttons again.
23
- *
24
- * `press(action, extra)` is the plugin's own server call for done, snooze and
25
- * event (extra carries `until` for a snooze); it should resolve once the
26
- * server has accepted the press. `chat` and `link` never reach the server:
27
- * chat opens a conversation with a prefilled, editable draft through the Web
28
- * UI's own workspace service (so the person sends it themselves, signed in as
29
- * themselves), and link opens the URL.
30
- */
31
- (() => {
32
- const OWNER = '@soffits/dsh-card-board'
33
-
34
- const KEYS = ['chat', 'chatAbout', 'done', 'snooze', 'event', 'link', 'in3h', 'tomorrow', 'pick', 'set', 'cancel', 'sending', 'pending', 'handled', 'unhandled', 'failed', 'noWorkspace']
35
-
36
- const CSS = `
37
- .ua-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center;min-width:0}
38
- .ua-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:32px;max-width:100%;padding:0 12px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;text-decoration:none;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
39
- .ua-btn span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
40
- .ua-btn svg{flex:none;width:14px;height:14px}
41
- .ua-btn:disabled{cursor:default;opacity:.7}
42
- @media (hover:hover){.ua-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
43
- .ua-icon{width:32px;padding:0;box-shadow:none;color:var(--dsw-alias-label-tertiary)}
44
- .ua-btn[data-state=pending] svg,.ua-btn[data-state=sending] svg{animation:ua-pulse 1.2s ease-in-out infinite}
45
- .ua-btn[data-state=done]{color:var(--dsw-alias-state-success-primary)}
46
- .ua-btn[data-state=unhandled]{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}
47
- @keyframes ua-pulse{50%{opacity:.35}}
48
- .ua-wrap{position:relative;display:inline-flex;max-width:100%;flex-wrap:wrap;align-items:center;gap:4px 8px}
49
- .ua-menu{position:absolute;z-index:20;top:calc(100% + 4px);right:0;min-width:168px;padding:4px;border-radius:12px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base));box-shadow:0 6px 24px #0000001f,inset 0 0 0 .5px var(--dsw-alias-border-l2);display:flex;flex-direction:column}
50
- .ua-menu button{display:flex;align-items:center;gap:8px;min-height:36px;padding:7px 10px;border:0;border-radius:8px;background:none;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;cursor:pointer}
51
- @media (hover:hover){.ua-menu button:hover{background:var(--dsw-alias-interactive-bg-hover)}}
52
- .ua-menu input{margin:4px 6px;min-height:36px;padding:6px 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:8px;background:transparent;color:inherit;font:inherit;font-size:16px}
53
- .ua-menuRow{display:flex;justify-content:flex-end;gap:4px;padding:2px 4px}
54
- .ua-error{flex-basis:100%;color:var(--dsw-alias-state-error-primary);font-size:12px;overflow-wrap:anywhere}
55
- @media (width<=768px),(pointer:coarse){
56
- .ua-btn{min-height:40px}
57
- .ua-icon{width:40px}
58
- .ua-menu{position:fixed;z-index:1000;top:auto;left:12px;right:12px;bottom:12px;max-height:60vh;overflow:auto;padding:8px;box-shadow:0 8px 40px #00000040,inset 0 0 0 .5px var(--dsw-alias-border-l2)}
59
- .ua-menu button{min-height:44px;font-size:15px}
60
- .ua-menu input{min-height:44px}
61
- }
62
- `
63
-
64
- const ICONS = {
65
- chat: 'M3 4.5A1.5 1.5 0 0 1 4.5 3h7A1.5 1.5 0 0 1 13 4.5v5A1.5 1.5 0 0 1 11.5 11H7l-3 2.5V11h.5A1.5 1.5 0 0 1 3 9.5z',
66
- done: 'M3.5 8.5l3 3 6-7',
67
- snooze: 'M8 4.5V8l2.2 1.4M13.5 8a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z',
68
- event: 'M8.8 2.5 4 9h4l-.8 4.5L12 7H8z',
69
- link: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5',
70
- pending: 'M8 8m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0',
71
- unhandled: 'M8 3.5v5.5M8 12v.5',
72
- }
73
-
74
- /** The next 09:00 after now, as an ISO string. */
75
- function tomorrowMorning(now = new Date()) {
76
- const date = new Date(now)
77
- date.setDate(date.getDate() + 1)
78
- date.setHours(9, 0, 0, 0)
79
- return date.toISOString()
80
- }
81
-
82
- /**
83
- * The draft for a chat about an item: the person's question goes first (a
84
- * prompt from the data, or nothing yet), then the item quoted, then its
85
- * context as JSON for the agent.
86
- */
87
- function chatText({ prompt = '', title, lines = [], context }) {
88
- const quote = [title ? `**${title}**` : null, ...lines].filter(Boolean).map(line => `> ${line}`).join('\n')
89
- const parts = [prompt, quote]
90
- if (context !== undefined) parts.push(`\`\`\`json\n${JSON.stringify(context, null, 2)}\n\`\`\``)
91
- return `${parts.filter(Boolean).join('\n\n')}\n`
92
- }
93
-
94
- /**
95
- * @param {object} options
96
- * @param {object} options.React - the page's React
97
- * @param {object} options.ctx - the plugin's client context (ctx.get reaches the Web UI's services)
98
- * @param {(key: string, params?: object) => string} options.t - the words in the person's language, one of KEYS
99
- * @param {(action: object, extra: object) => Promise<unknown>} [options.press] - the server call for done, snooze and event
100
- */
101
- function createActions({ React, ctx, t, press }) {
102
- const h = React.createElement
103
- const { useState, useEffect, useRef } = React
104
-
105
- if (typeof document !== 'undefined' && !document.getElementById('dsh-actions-ui-style')) {
106
- const style = document.createElement('style')
107
- style.id = 'dsh-actions-ui-style'
108
- style.dataset.plugin = OWNER
109
- style.textContent = CSS
110
- document.head.appendChild(style)
111
- }
112
-
113
- function Icon({ name }) {
114
- return h('svg', { viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('path', { d: ICONS[name] ?? ICONS.event }))
115
- }
116
-
117
- /**
118
- * Open a conversation with `text` as its editable draft: a new one in the
119
- * current (or most recent) workspace, or the given session.
120
- */
121
- async function startChat({ text, session }) {
122
- const workspace = ctx.get('uiWorkspace')
123
- if (workspace === undefined) throw new Error(t('noWorkspace'))
124
- if (session === undefined || session === 'new') {
125
- workspace.startSession(undefined, { prompt: text, whenDraftExists: 'replace' })
126
- return
127
- }
128
- workspace.openSession(session)
129
- const sessions = ctx.get('sessions')
130
- const conversation = ctx.get('conversation')
131
- for (let i = 0; i < 30 && sessions && conversation; i += 1) {
132
- const binding = sessions.binding(session)
133
- if (binding !== undefined) {
134
- try {
135
- conversation.input.requestDraftInitialization(binding, { prompt: text, whenDraftExists: 'append' })
136
- } catch {
137
- // the session moved on before the draft landed; it is open, the person can type
138
- }
139
- return
140
- }
141
- await new Promise(resolve => setTimeout(resolve, 100))
142
- }
143
- }
144
-
145
- function SnoozeMenu({ onPick, onClose }) {
146
- const [picking, setPicking] = useState(false)
147
- const [value, setValue] = useState('')
148
- const ref = useRef(null)
149
- useEffect(() => {
150
- const away = event => { if (ref.current && !ref.current.contains(event.target)) onClose() }
151
- const escape = event => { if (event.key === 'Escape') onClose() }
152
- document.addEventListener('pointerdown', away)
153
- document.addEventListener('keydown', escape)
154
- return () => { document.removeEventListener('pointerdown', away); document.removeEventListener('keydown', escape) }
155
- }, [onClose])
156
- return h('div', { className: 'ua-menu', ref, role: 'menu' },
157
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(new Date(Date.now() + 3 * 3600 * 1000).toISOString()) }, t('in3h')),
158
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(tomorrowMorning()) }, t('tomorrow')),
159
- !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => setPicking(true) }, t('pick')),
160
- picking && h('input', { type: 'datetime-local', value, autoFocus: true, onChange: event => setValue(event.target.value) }),
161
- picking && h('div', { className: 'ua-menuRow' },
162
- h('button', { type: 'button', onClick: onClose }, t('cancel')),
163
- h('button', { type: 'button', disabled: value === '', onClick: () => onPick(new Date(value).toISOString()) }, t('set'))))
164
- }
165
-
166
- /**
167
- * One action as a button. `state` is the server's view of the last press
168
- * (pending, done, unhandled); `compact` draws an icon only.
169
- */
170
- function ActionButton({ action, state, compact, chat, onPress }) {
171
- const [local, setLocal] = useState(null)
172
- const [error, setError] = useState(null)
173
- const [menu, setMenu] = useState(false)
174
- useEffect(() => { if (state) setLocal(null) }, [state])
175
- const shown = local ?? state
176
- const label = action.label ?? t(action.kind)
177
- const title = shown === 'sending' ? t('sending') : shown === 'pending' ? t('pending') : shown === 'done' ? t('handled') : shown === 'unhandled' ? t('unhandled') : error ?? label
178
- const icon = shown === 'done' ? 'done' : shown === 'unhandled' ? 'unhandled' : action.kind
179
- const className = `ua-btn${compact ? ' ua-icon' : ''}`
180
- const content = [h(Icon, { key: 'i', name: icon }), !compact && h('span', { key: 'l' }, label)]
181
-
182
- if (action.kind === 'link') {
183
- const url = action.payload?.url
184
- const external = /^https?:/i.test(url ?? '')
185
- return h('a', { className, href: url, title: label, 'aria-label': label, ...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {}) }, content)
186
- }
187
- const send = async extra => {
188
- setMenu(false)
189
- setError(null)
190
- setLocal('sending')
191
- try {
192
- if (action.kind === 'chat') {
193
- await chat(action)
194
- setLocal(null)
195
- } else {
196
- await (onPress ?? press)(action, extra ?? {})
197
- setLocal('pending')
198
- }
199
- } catch (reason) {
200
- setLocal(null)
201
- setError(t('failed', { message: reason?.message ?? String(reason) }))
202
- }
203
- }
204
- const onClick = () => {
205
- if (action.kind === 'snooze' && action.payload?.until === undefined) setMenu(open => !open)
206
- else send()
207
- }
208
- const busy = shown === 'sending' || shown === 'pending'
209
- return h('span', { className: 'ua-wrap' },
210
- h('button', { type: 'button', className, title, 'aria-label': `${label}${title !== label ? ` (${title})` : ''}`, 'data-state': shown ?? undefined, disabled: busy, onClick }, content),
211
- menu && h(SnoozeMenu, { onPick: until => send({ until }), onClose: () => setMenu(false) }),
212
- error && !compact && h('span', { className: 'ua-error', role: 'alert' }, error))
213
- }
214
-
215
- /**
216
- * A row of action buttons.
217
- * @param {object} props
218
- * @param {object[]} props.actions - the item's actions, as the data declares them
219
- * @param {Record<string, string>} [props.states] - press state by action id
220
- * @param {boolean} [props.compact] - icons only (for rows)
221
- * @param {(action: object) => Promise<void>} props.chat - opens the chat for a chat action
222
- * @param {(action: object, extra: object) => Promise<unknown>} [props.onPress] - this bar's press call, instead of the one given to createActions
223
- */
224
- function ActionBar({ actions, states = {}, compact = false, chat, onPress }) {
225
- if (!actions || actions.length === 0) return null
226
- return h('div', { className: 'ua-bar' }, actions.map(action =>
227
- h(ActionButton, { key: action.id, action, state: states[action.id], compact, chat, onPress })))
228
- }
229
-
230
- return { ActionBar, ActionButton, Icon, startChat, chatText, t }
231
- }
232
-
233
- window.__ModuleLoader__.load({ id: OWNER, chunk: 'client.actions.js', factory: () => ({ createActions, chatText, KEYS }) })
234
- })()