@soffits/dsh-card-board 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,259 @@
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; the
8
+ * file has no imports and takes React and the client context as arguments.
9
+ *
10
+ * const { createActions } = await require.async('./client.actions.js')
11
+ * const ui = createActions({ React, ctx, locale: 'en', press })
12
+ * h(ui.ActionBar, { actions, states, chat, onPress })
13
+ *
14
+ * `press(action, extra)` is the plugin's own server call for done, snooze and
15
+ * event (extra carries `until` for a snooze); it should resolve once the
16
+ * server has accepted the press. `chat` and `link` never reach the server:
17
+ * chat opens a conversation with a prefilled, editable draft through the Web
18
+ * UI's own workspace service (so the person sends it themselves, signed in as
19
+ * themselves), and link opens the URL.
20
+ */
21
+ const OWNER = '@soffits/dsh-card-board'
22
+
23
+ const WORDS = {
24
+ en: {
25
+ chat: 'Ask',
26
+ chatAbout: 'Chat about this',
27
+ done: 'Done',
28
+ snooze: 'Snooze',
29
+ open: 'Open',
30
+ in3h: 'In 3 hours',
31
+ tomorrow: 'Tomorrow 9:00',
32
+ pick: 'Pick a time…',
33
+ set: 'Snooze',
34
+ cancel: 'Cancel',
35
+ sending: 'Sending…',
36
+ pending: 'Waiting for it to be picked up',
37
+ handled: 'Done',
38
+ unhandled: 'Nothing picked this up yet',
39
+ failed: 'Didn’t go through: {message}',
40
+ noWorkspace: 'Open a conversation once first, then try again.',
41
+ },
42
+ zh: {
43
+ chat: '问问',
44
+ chatAbout: '聊聊这个',
45
+ done: '完成',
46
+ snooze: '稍后提醒',
47
+ open: '打开',
48
+ in3h: '3 小时后',
49
+ tomorrow: '明天 9:00',
50
+ pick: '选个时间…',
51
+ set: '稍后提醒',
52
+ cancel: '取消',
53
+ sending: '发送中…',
54
+ pending: '等待处理',
55
+ handled: '已处理',
56
+ unhandled: '还没有被处理',
57
+ failed: '没有成功:{message}',
58
+ noWorkspace: '请先打开一次对话,再试一次。',
59
+ },
60
+ }
61
+
62
+ const CSS = `
63
+ .ua-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
64
+ .ua-btn{box-sizing:border-box;display:inline-flex;align-items:center;gap:5px;height:28px;padding:0 10px;border:0;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;line-height:18px;cursor:pointer;white-space:nowrap;text-decoration:none;box-shadow:inset 0 0 0 .5px var(--dsw-alias-border-l3)}
65
+ .ua-btn svg{flex:none;width:14px;height:14px}
66
+ .ua-btn:disabled{cursor:default;opacity:.7}
67
+ @media (hover:hover){.ua-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-primary)}}
68
+ .ua-icon{width:26px;height:26px;padding:0;justify-content:center;box-shadow:none;color:var(--dsw-alias-label-tertiary)}
69
+ .ua-btn[data-state=pending] svg,.ua-btn[data-state=sending] svg{animation:ua-pulse 1.2s ease-in-out infinite}
70
+ .ua-btn[data-state=done]{color:var(--dsw-alias-state-success-primary)}
71
+ .ua-btn[data-state=unhandled]{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}
72
+ @keyframes ua-pulse{50%{opacity:.35}}
73
+ .ua-wrap{position:relative;display:inline-flex}
74
+ .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}
75
+ .ua-menu button{display:flex;align-items:center;gap:8px;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}
76
+ @media (hover:hover){.ua-menu button:hover{background:var(--dsw-alias-interactive-bg-hover)}}
77
+ .ua-menu input{margin:4px 6px;padding:6px 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:8px;background:transparent;color:inherit;font:inherit;font-size:13px}
78
+ .ua-menuRow{display:flex;justify-content:flex-end;gap:4px;padding:2px 4px}
79
+ .ua-error{color:var(--dsw-alias-state-error-primary);font-size:12px}
80
+ `
81
+
82
+ const ICONS = {
83
+ 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',
84
+ done: 'M3.5 8.5l3 3 6-7',
85
+ 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',
86
+ event: 'M8.8 2.5 4 9h4l-.8 4.5L12 7H8z',
87
+ link: 'M6 3.5H3.5v9h9V10M9 3h4v4M13 3 7.5 8.5',
88
+ pending: 'M8 8m-2 0a2 2 0 1 0 4 0a2 2 0 1 0-4 0',
89
+ unhandled: 'M8 3.5v5.5M8 12v.5',
90
+ }
91
+
92
+ function fill(text, params) {
93
+ return String(text).replace(/\{(\w+)\}/g, (match, key) => (key in params ? String(params[key]) : match))
94
+ }
95
+
96
+ /** The next 09:00 after now, as an ISO string. */
97
+ function tomorrowMorning(now = new Date()) {
98
+ const date = new Date(now)
99
+ date.setDate(date.getDate() + 1)
100
+ date.setHours(9, 0, 0, 0)
101
+ return date.toISOString()
102
+ }
103
+
104
+ /**
105
+ * The draft for a chat about an item: the person's question goes first (a
106
+ * prompt from the data, or nothing yet), then the item quoted, then its
107
+ * context as JSON for the agent.
108
+ */
109
+ function chatText({ prompt = '', title, lines = [], context }) {
110
+ const quote = [title ? `**${title}**` : null, ...lines].filter(Boolean).map(line => `> ${line}`).join('\n')
111
+ const parts = [prompt, quote]
112
+ if (context !== undefined) parts.push(`\`\`\`json\n${JSON.stringify(context, null, 2)}\n\`\`\``)
113
+ return `${parts.filter(Boolean).join('\n\n')}\n`
114
+ }
115
+
116
+ /**
117
+ * @param {object} options
118
+ * @param {object} options.React - the page's React
119
+ * @param {object} options.ctx - the plugin's client context (ctx.get reaches the Web UI's services)
120
+ * @param {string} [options.locale] - 'zh…' picks Chinese words, anything else English
121
+ * @param {(action: object, extra: object) => Promise<unknown>} [options.press] - the server call for done, snooze and event
122
+ */
123
+ function createActions({ React, ctx, locale = 'en', press }) {
124
+ const h = React.createElement
125
+ const { useState, useEffect, useRef } = React
126
+ const words = WORDS[String(locale).toLowerCase().startsWith('zh') ? 'zh' : 'en']
127
+ const t = key => words[key] ?? WORDS.en[key] ?? key
128
+
129
+ if (typeof document !== 'undefined' && !document.getElementById('dsh-actions-ui-style')) {
130
+ const style = document.createElement('style')
131
+ style.id = 'dsh-actions-ui-style'
132
+ style.dataset.plugin = OWNER
133
+ style.textContent = CSS
134
+ document.head.appendChild(style)
135
+ }
136
+
137
+ function Icon({ name }) {
138
+ 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 }))
139
+ }
140
+
141
+ /**
142
+ * Open a conversation with `text` as its editable draft: a new one in the
143
+ * current (or most recent) workspace, or the given session.
144
+ */
145
+ async function startChat({ text, session }) {
146
+ const workspace = ctx.get('uiWorkspace')
147
+ if (workspace === undefined) throw new Error(t('noWorkspace'))
148
+ if (session === undefined || session === 'new') {
149
+ workspace.startSession(undefined, { prompt: text, whenDraftExists: 'replace' })
150
+ return
151
+ }
152
+ workspace.openSession(session)
153
+ const sessions = ctx.get('sessions')
154
+ const conversation = ctx.get('conversation')
155
+ for (let i = 0; i < 30 && sessions && conversation; i += 1) {
156
+ const binding = sessions.binding(session)
157
+ if (binding !== undefined) {
158
+ try {
159
+ conversation.input.requestDraftInitialization(binding, { prompt: text, whenDraftExists: 'append' })
160
+ } catch {
161
+ // the session moved on before the draft landed; it is open, the person can type
162
+ }
163
+ return
164
+ }
165
+ await new Promise(resolve => setTimeout(resolve, 100))
166
+ }
167
+ }
168
+
169
+ function SnoozeMenu({ onPick, onClose }) {
170
+ const [picking, setPicking] = useState(false)
171
+ const [value, setValue] = useState('')
172
+ const ref = useRef(null)
173
+ useEffect(() => {
174
+ const away = event => { if (ref.current && !ref.current.contains(event.target)) onClose() }
175
+ const escape = event => { if (event.key === 'Escape') onClose() }
176
+ document.addEventListener('pointerdown', away)
177
+ document.addEventListener('keydown', escape)
178
+ return () => { document.removeEventListener('pointerdown', away); document.removeEventListener('keydown', escape) }
179
+ }, [onClose])
180
+ return h('div', { className: 'ua-menu', ref, role: 'menu' },
181
+ !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(new Date(Date.now() + 3 * 3600 * 1000).toISOString()) }, t('in3h')),
182
+ !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => onPick(tomorrowMorning()) }, t('tomorrow')),
183
+ !picking && h('button', { type: 'button', role: 'menuitem', onClick: () => setPicking(true) }, t('pick')),
184
+ picking && h('input', { type: 'datetime-local', value, autoFocus: true, onChange: event => setValue(event.target.value) }),
185
+ picking && h('div', { className: 'ua-menuRow' },
186
+ h('button', { type: 'button', onClick: onClose }, t('cancel')),
187
+ h('button', { type: 'button', disabled: value === '', onClick: () => onPick(new Date(value).toISOString()) }, t('set'))))
188
+ }
189
+
190
+ /**
191
+ * One action as a button. `state` is the server's view of the last press
192
+ * (pending, done, unhandled); `compact` draws an icon only.
193
+ */
194
+ function ActionButton({ action, state, compact, chat, onPress }) {
195
+ const [local, setLocal] = useState(null)
196
+ const [error, setError] = useState(null)
197
+ const [menu, setMenu] = useState(false)
198
+ useEffect(() => { if (state) setLocal(null) }, [state])
199
+ const shown = local ?? state
200
+ const label = action.label ?? t(action.kind === 'chat' ? 'chat' : action.kind === 'link' ? 'open' : action.kind)
201
+ const title = shown === 'sending' ? t('sending') : shown === 'pending' ? t('pending') : shown === 'done' ? t('handled') : shown === 'unhandled' ? t('unhandled') : error ?? label
202
+ const icon = shown === 'done' ? 'done' : shown === 'unhandled' ? 'unhandled' : action.kind
203
+ const className = `ua-btn${compact ? ' ua-icon' : ''}`
204
+ const content = [h(Icon, { key: 'i', name: icon }), !compact && h('span', { key: 'l' }, label)]
205
+
206
+ if (action.kind === 'link') {
207
+ const url = action.payload?.url
208
+ const external = /^https?:/i.test(url ?? '')
209
+ return h('a', { className, href: url, title: label, 'aria-label': label, ...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {}) }, content)
210
+ }
211
+ const send = async extra => {
212
+ setMenu(false)
213
+ setError(null)
214
+ setLocal('sending')
215
+ try {
216
+ if (action.kind === 'chat') {
217
+ await chat(action)
218
+ setLocal(null)
219
+ } else {
220
+ await (onPress ?? press)(action, extra ?? {})
221
+ setLocal('pending')
222
+ }
223
+ } catch (reason) {
224
+ setLocal(null)
225
+ setError(fill(t('failed'), { message: reason?.message ?? String(reason) }))
226
+ }
227
+ }
228
+ const onClick = () => {
229
+ if (action.kind === 'snooze' && action.payload?.until === undefined) setMenu(open => !open)
230
+ else send()
231
+ }
232
+ const busy = shown === 'sending' || shown === 'pending'
233
+ return h('span', { className: 'ua-wrap' },
234
+ h('button', { type: 'button', className, title, 'aria-label': `${label}${title !== label ? ` (${title})` : ''}`, 'data-state': shown ?? undefined, disabled: busy, onClick }, content),
235
+ menu && h(SnoozeMenu, { onPick: until => send({ until }), onClose: () => setMenu(false) }),
236
+ error && !compact && h('span', { className: 'ua-error', role: 'alert' }, error))
237
+ }
238
+
239
+ /**
240
+ * A row of action buttons.
241
+ * @param {object} props
242
+ * @param {object[]} props.actions - the item's actions, as the data declares them
243
+ * @param {Record<string, string>} [props.states] - press state by action id
244
+ * @param {boolean} [props.compact] - icons only (for rows)
245
+ * @param {(action: object) => Promise<void>} props.chat - opens the chat for a chat action
246
+ * @param {(action: object, extra: object) => Promise<unknown>} [props.onPress] - this bar's press call, instead of the one given to createActions
247
+ */
248
+ function ActionBar({ actions, states = {}, compact = false, chat, onPress }) {
249
+ if (!actions || actions.length === 0) return null
250
+ return h('div', { className: 'ua-bar' }, actions.map(action =>
251
+ h(ActionButton, { key: action.id, action, state: states[action.id], compact, chat, onPress })))
252
+ }
253
+
254
+ return { ActionBar, ActionButton, Icon, startChat, chatText, t }
255
+ }
256
+
257
+ if (typeof window !== 'undefined' && window.__ModuleLoader__) {
258
+ window.__ModuleLoader__.load({ id: `${OWNER}/client.actions.js`, factory: () => ({ createActions, chatText }) })
259
+ }