@soffits/dsh-card-board 0.4.2 → 0.5.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,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0
4
+
5
+ - 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.
6
+ - 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.
7
+ - 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>".
8
+
3
9
  ## 0.4.2
4
10
 
5
11
  - 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
@@ -225,7 +225,7 @@ A card, a list row or a status row can carry up to six buttons:
225
225
  ]
226
226
  ```
227
227
 
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.
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 ("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.
229
229
  - `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
230
  - `link` opens `payload.url`.
231
231
 
@@ -250,7 +250,7 @@ It's appended to the action log, emitted in-process as the Cordis event `card-bo
250
250
 
251
251
  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
252
 
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.
253
+ 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
254
 
255
255
  ## Writing cards: the CLI
256
256
 
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
 
@@ -685,7 +691,7 @@ window.__ModuleLoader__.load({
685
691
  h('path', { d: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5' }))
686
692
  }
687
693
 
688
- function Card({ entry, boardId, assistant, columns, now, active, locale, t, actions }) {
694
+ function Card({ entry, boardId, assistant, columns, now, active, locale, t, actions, press }) {
689
695
  const size = { w: Math.min(entry.w ?? 1, columns), h: entry.h ?? 1 }
690
696
  const style = { gridColumn: `span ${size.w}`, gridRow: size.h > 1 && columns > 1 ? `span ${size.h}` : undefined }
691
697
  if (!entry.card) {
@@ -699,40 +705,36 @@ window.__ModuleLoader__.load({
699
705
  const age = Math.max(0, (now - updated) / 1000)
700
706
  const stale = typeof card.staleAfter === 'number' && age > card.staleAfter
701
707
  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,
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 },
712
714
  })
713
715
  // 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 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)
716
718
  const rowActions = actions && ((row, list, line) => h(actions.ActionBar, {
717
719
  actions: named(list),
718
720
  states: statesOf(entry.presses, row),
719
721
  compact: true,
720
- chat: action => chat(action, row, line),
721
- onPress: (action, extra) => actions.press(action, extra, { card: entry.id, row }),
722
+ about: about(row, line),
723
+ onPress: (action, extra) => press(action, extra, { card: entry.id, row }),
722
724
  }))
723
725
  return h('section', { className: `cb-card${stale ? ' cb-cardStale' : ''}`, style, 'data-type': card.type },
724
726
  h('header', { className: 'cb-cardHead' },
725
727
  h(Trunc, { as: 'h3', text: card.title }),
726
728
  stale && h('span', { className: 'cb-staleChip', title: new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(updated) }, t('stale', { age: formatAge(age, locale) })),
727
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)),
728
- actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: defaultChat, compact: true, chat: action => chat(action) }))),
730
+ actions && h('span', { className: 'cb-cardChat' }, h(actions.ActionButton, { action: { kind: 'chat', id: '_chat', label: askName }, compact: true, about: about() }))),
729
731
  card.stat && h(StatBlock, { data: card.stat, locale, compact: true }),
730
732
  h('div', { className: 'cb-cardBody' }, h(CardBody, { card, size, narrow: columns === 1, locale, t, rowActions })),
731
733
  actions && card.actions && h('footer', { className: 'cb-cardActions' }, h(actions.ActionBar, {
732
734
  actions: named(card.actions),
733
735
  states: statesOf(entry.presses, undefined),
734
- chat: action => chat(action),
735
- onPress: (action, extra) => actions.press(action, extra, { card: entry.id }),
736
+ about: about(),
737
+ onPress: (action, extra) => press(action, extra, { card: entry.id }),
736
738
  })))
737
739
  }
738
740
 
@@ -774,7 +776,7 @@ window.__ModuleLoader__.load({
774
776
  const [now, setNow] = useState(() => Date.now())
775
777
  const etag = useRef(null)
776
778
  const [gridRef, columns] = useColumns()
777
- const [actions, setActions] = useState(null)
779
+ const actions = useButtons()
778
780
  const currentRef = useRef(null)
779
781
  // The buttons ask for words at render time, so a language switch reaches them without rebuilding them.
780
782
  const translateRef = useRef(t)
@@ -810,27 +812,18 @@ window.__ModuleLoader__.load({
810
812
 
811
813
  useEffect(() => { loadList() }, [loadList])
812
814
 
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 }
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
834
827
  }, [loadBoard])
835
828
 
836
829
  useEffect(() => {
@@ -878,7 +871,7 @@ window.__ModuleLoader__.load({
878
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)))),
879
872
  board.cards.length === 0 && h('p', { className: 'cb-muted' }, t('noCards')),
880
873
  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 }))))
874
+ board.cards.map(entry => h(Card, { key: entry.id, entry, boardId: board.id, assistant: board.assistant, columns, now, active, locale, t, actions, press }))))
882
875
 
883
876
  return h('div', { className: 'cb-page' },
884
877
  h('div', { className: 'cb-content', ref: gridRef },
@@ -1019,16 +1012,26 @@ h3.cb-truncOpen{overflow:visible}
1019
1012
  .cb-list li .cb-listMeta{grid-column:2/-1;grid-row:2;margin-top:2px}
1020
1013
  }
1021
1014
  @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}
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}
1024
1020
  .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
1021
  .cb-status li>.cb-spark{grid-column:2/-1;grid-row:3}
1029
1022
  .cb-spark:empty{display:none}
1023
+ }
1024
+ @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}
1030
1032
  .cb-statusActions li .cb-rowActions{grid-column:2/-1;grid-row:4;justify-content:flex-start}
1031
1033
  }
1034
+ }
1032
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}}
1033
1036
  @media (width<=768px),(pointer:coarse){
1034
1037
  .cb-cardLink{width:40px;height:40px;margin:-9px 0}
@@ -1068,11 +1071,21 @@ h3.cb-truncOpen{overflow:visible}
1068
1071
  }, 'card-board: sidebar words')
1069
1072
  const sidebarT = ctx.locale.bind(NS)
1070
1073
 
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
+ })
1083
+
1071
1084
  ctx.effect(() => {
1072
1085
  if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return () => {}
1073
1086
  const tag = document.createElement('style')
1074
1087
  tag.id = STYLE_ID
1075
- tag.dataset.plugin = '@soffits/dsh-card-board'
1088
+ tag.dataset.plugin = OWNER
1076
1089
  tag.textContent = CSS
1077
1090
  document.head.appendChild(tag)
1078
1091
  return () => tag.remove()
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.5.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/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
- })()