@microvac/plugin-openui-cards 0.0.0-stage → 0.1.0-rc.22

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/src/client.tsx ADDED
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Client face of the `openui-cards` plugin: registers the renderer of
3
+ * `openui-cards` cards in the Microvac UI card body registry (ADR 0015). The
4
+ * body is drawn by `@openuidev/react-lang` with the card library and the
5
+ * renderers below, built on Microvac UI components (dark mode, 400 px wide).
6
+ *
7
+ * Local state only: tabs, folds and field values live in the card; the card
8
+ * queries nothing and calls nothing. A button sends its id, the field values
9
+ * and the optional note through the host's `answer`.
10
+ */
11
+ import { Renderer, type ComponentRenderProps } from "@openuidev/react-lang";
12
+ import {
13
+ Badge,
14
+ Button,
15
+ Checkbox,
16
+ Collapsible,
17
+ CollapsibleContent,
18
+ CollapsibleTrigger,
19
+ Input,
20
+ Label,
21
+ MarkdownBody,
22
+ Tabs,
23
+ TabsContent,
24
+ TabsList,
25
+ TabsTrigger,
26
+ Textarea,
27
+ cards,
28
+ cn,
29
+ type CardRendererProps,
30
+ } from "@microvac/ui";
31
+ import { createContext, useContext, useEffect, useId, useMemo, useRef, useState, type FC } from "react";
32
+ import { CARD_TYPE, PLUGIN_KEY, createCardLibrary } from "./library.js";
33
+ import { BarChart, LineChart, type ChartProps } from "./charts.js";
34
+
35
+ export const name = "@microvac/plugin-openui-cards";
36
+ export const inject = [];
37
+
38
+ type Values = Record<string, unknown>;
39
+ type FieldMeta = { name: string; required: boolean; initial: unknown };
40
+
41
+ interface CardState {
42
+ answerable: boolean;
43
+ values: Values;
44
+ setValue(name: string, value: unknown): void;
45
+ register(meta: FieldMeta): () => void;
46
+ submit(actionId: string): void;
47
+ missing: string[];
48
+ }
49
+
50
+ const CardStateContext = createContext<CardState | null>(null);
51
+
52
+ function useCardState(): CardState {
53
+ const state = useContext(CardStateContext);
54
+ if (!state) throw new Error("openui-cards: a card component is drawn outside its card");
55
+ return state;
56
+ }
57
+
58
+ type Props<P> = ComponentRenderProps<P>;
59
+ type Element<P = Record<string, unknown>> = { type: "element"; typeName: string; props: P };
60
+
61
+ function isElement<P>(value: unknown): value is Element<P> {
62
+ return typeof value === "object" && value !== null && (value as { type?: unknown }).type === "element";
63
+ }
64
+
65
+ function isEmpty(value: unknown) {
66
+ return value === undefined || value === null || value === "" || (Array.isArray(value) && value.length === 0);
67
+ }
68
+
69
+ /** A field's value: what the human set, else the card's initial value. */
70
+ function useField(name: string, initial: unknown, required: boolean | undefined) {
71
+ const state = useCardState();
72
+ const { register } = state;
73
+ useEffect(() => register({ name, required: required === true, initial }), [register, name, required, initial]);
74
+ const value = name in state.values ? state.values[name] : initial;
75
+ return {
76
+ value,
77
+ disabled: !state.answerable,
78
+ invalid: state.missing.includes(name),
79
+ set: (next: unknown) => state.setValue(name, next),
80
+ };
81
+ }
82
+
83
+ function FieldLabel({ htmlFor, label, required }: { htmlFor?: string; label: string; required?: boolean | null }) {
84
+ return (
85
+ <Label htmlFor={htmlFor} className="text-sm font-medium">
86
+ {label}
87
+ {required ? <span className="text-muted-foreground"> *</span> : null}
88
+ </Label>
89
+ );
90
+ }
91
+
92
+ function CardRoot({ props, renderNode }: Props<{ children: unknown[] }>) {
93
+ return <div className="grid min-w-0 gap-3">{renderNode(props.children)}</div>;
94
+ }
95
+
96
+ function Text({ props }: Props<{ markdown: string }>) {
97
+ return (
98
+ <MarkdownBody className="min-w-0 text-sm" mediaMode="omit">
99
+ {props.markdown}
100
+ </MarkdownBody>
101
+ );
102
+ }
103
+
104
+ function List({ props }: Props<{ items: string[]; ordered?: boolean | null }>) {
105
+ const Tag = props.ordered ? "ol" : "ul";
106
+ return (
107
+ <Tag className={cn("grid gap-1 pl-5 text-sm", props.ordered ? "list-decimal" : "list-disc")}>
108
+ {props.items.map((item, index) => (
109
+ <li key={index} className="break-words">
110
+ {item}
111
+ </li>
112
+ ))}
113
+ </Tag>
114
+ );
115
+ }
116
+
117
+ function Badges({ props }: Props<{ labels: string[] }>) {
118
+ return (
119
+ <div className="flex flex-wrap gap-1.5">
120
+ {props.labels.map((label, index) => (
121
+ <Badge key={index} variant="secondary">
122
+ {label}
123
+ </Badge>
124
+ ))}
125
+ </div>
126
+ );
127
+ }
128
+
129
+ function Callout({ props }: Props<{ tone: "info" | "risk"; markdown: string; title?: string | null }>) {
130
+ const risk = props.tone === "risk";
131
+ return (
132
+ <div
133
+ role={risk ? "alert" : "note"}
134
+ className={cn("grid gap-1 rounded-md border border-l-4 bg-muted/40 p-3", risk ? "border-l-destructive" : "border-l-primary")}
135
+ >
136
+ {props.title ? <p className={cn("text-sm font-medium", risk && "text-destructive")}>{props.title}</p> : null}
137
+ <MarkdownBody className="min-w-0 text-sm" mediaMode="omit">
138
+ {props.markdown}
139
+ </MarkdownBody>
140
+ </div>
141
+ );
142
+ }
143
+
144
+ function Table({ props }: Props<{ columns: string[]; rows: (string | number)[][] }>) {
145
+ return (
146
+ <div className="max-w-full overflow-x-auto rounded-md border">
147
+ <table className="w-full border-collapse text-xs">
148
+ <thead className="bg-muted/50">
149
+ <tr>
150
+ {props.columns.map((column, index) => (
151
+ <th key={index} scope="col" className="px-2 py-1.5 text-left font-medium whitespace-nowrap">
152
+ {column}
153
+ </th>
154
+ ))}
155
+ </tr>
156
+ </thead>
157
+ <tbody>
158
+ {props.rows.map((row, rowIndex) => (
159
+ <tr key={rowIndex} className="border-t">
160
+ {props.columns.map((_, cellIndex) => {
161
+ const cell = row[cellIndex];
162
+ return (
163
+ <td key={cellIndex} className={cn("px-2 py-1.5 align-top", typeof cell === "number" && "text-right tabular-nums")}>
164
+ {cell ?? ""}
165
+ </td>
166
+ );
167
+ })}
168
+ </tr>
169
+ ))}
170
+ </tbody>
171
+ </table>
172
+ </div>
173
+ );
174
+ }
175
+
176
+ function Options({ props, renderNode }: Props<{ options: unknown[] }>) {
177
+ return <div className="grid gap-2 sm:grid-cols-2">{renderNode(props.options)}</div>;
178
+ }
179
+
180
+ type OptionProps = { title: string; summary?: string | null; pros?: string[] | null; cons?: string[] | null; recommended?: boolean | null };
181
+
182
+ function Option({ props }: Props<OptionProps>) {
183
+ return (
184
+ <div className={cn("grid content-start gap-1.5 rounded-md border p-3", props.recommended && "border-primary bg-primary/5")}>
185
+ <div className="flex flex-wrap items-center gap-2">
186
+ <p className="text-sm font-medium">{props.title}</p>
187
+ {props.recommended ? <Badge>Recommended</Badge> : null}
188
+ </div>
189
+ {props.summary ? <p className="text-sm text-muted-foreground">{props.summary}</p> : null}
190
+ {props.pros?.length ? (
191
+ <ul className="grid gap-0.5 text-sm" aria-label="Pros">
192
+ {props.pros.map((pro, index) => (
193
+ <li key={index}>
194
+ <span aria-hidden="true">+ </span>
195
+ {pro}
196
+ </li>
197
+ ))}
198
+ </ul>
199
+ ) : null}
200
+ {props.cons?.length ? (
201
+ <ul className="grid gap-0.5 text-sm text-muted-foreground" aria-label="Cons">
202
+ {props.cons.map((con, index) => (
203
+ <li key={index}>
204
+ <span aria-hidden="true">− </span>
205
+ {con}
206
+ </li>
207
+ ))}
208
+ </ul>
209
+ ) : null}
210
+ </div>
211
+ );
212
+ }
213
+
214
+ type ChartNodeProps = Omit<ChartProps, "series"> & { series: unknown[] };
215
+
216
+ function chartProps(props: ChartNodeProps): ChartProps {
217
+ return {
218
+ ...props,
219
+ series: props.series.filter(isElement<{ name: string; values: number[] }>).map((series) => series.props),
220
+ };
221
+ }
222
+
223
+ function BarChartNode({ props }: Props<ChartNodeProps>) {
224
+ return <BarChart {...chartProps(props)} />;
225
+ }
226
+
227
+ function LineChartNode({ props }: Props<ChartNodeProps>) {
228
+ return <LineChart {...chartProps(props)} />;
229
+ }
230
+
231
+ type ChoiceProps = { name: string; label: string; options: string[]; value?: string | null; required?: boolean | null };
232
+
233
+ function Choice({ props }: Props<ChoiceProps>) {
234
+ const field = useField(props.name, props.value ?? undefined, props.required ?? undefined);
235
+ const id = useId();
236
+ return (
237
+ <fieldset className="grid gap-1.5" aria-invalid={field.invalid || undefined}>
238
+ <legend className="mb-1.5">
239
+ <FieldLabel label={props.label} required={props.required} />
240
+ </legend>
241
+ {props.options.map((option, index) => (
242
+ <label
243
+ key={index}
244
+ htmlFor={`${id}-${index}`}
245
+ className={cn(
246
+ "flex min-h-9 cursor-pointer items-center gap-2 rounded-md border px-3 py-1.5 text-sm",
247
+ field.value === option && "border-primary bg-primary/5",
248
+ field.disabled && "cursor-default opacity-70",
249
+ )}
250
+ >
251
+ <input
252
+ id={`${id}-${index}`}
253
+ type="radio"
254
+ name={`${id}-${props.name}`}
255
+ className="accent-primary"
256
+ checked={field.value === option}
257
+ disabled={field.disabled}
258
+ onChange={() => field.set(option)}
259
+ />
260
+ <span className="min-w-0 break-words">{option}</span>
261
+ </label>
262
+ ))}
263
+ {field.invalid ? <p className="text-xs text-destructive">Required</p> : null}
264
+ </fieldset>
265
+ );
266
+ }
267
+
268
+ type CheckboxesProps = { name: string; label: string; options: string[]; value?: string[] | null; required?: boolean | null };
269
+
270
+ function Checkboxes({ props }: Props<CheckboxesProps>) {
271
+ const field = useField(props.name, props.value ?? undefined, props.required ?? undefined);
272
+ const id = useId();
273
+ const checked = Array.isArray(field.value) ? (field.value as string[]) : [];
274
+ return (
275
+ <fieldset className="grid gap-1.5" aria-invalid={field.invalid || undefined}>
276
+ <legend className="mb-1.5">
277
+ <FieldLabel label={props.label} required={props.required} />
278
+ </legend>
279
+ {props.options.map((option, index) => (
280
+ <div key={index} className="flex min-h-8 items-center gap-2 text-sm">
281
+ <Checkbox
282
+ id={`${id}-${index}`}
283
+ checked={checked.includes(option)}
284
+ disabled={field.disabled}
285
+ onCheckedChange={(next: boolean | "indeterminate") =>
286
+ field.set(next === true ? props.options.filter((item) => item === option || checked.includes(item)) : checked.filter((item) => item !== option))
287
+ }
288
+ />
289
+ <label htmlFor={`${id}-${index}`} className="min-w-0 cursor-pointer break-words">
290
+ {option}
291
+ </label>
292
+ </div>
293
+ ))}
294
+ {field.invalid ? <p className="text-xs text-destructive">Required</p> : null}
295
+ </fieldset>
296
+ );
297
+ }
298
+
299
+ type TextFieldProps = { name: string; label: string; placeholder?: string | null; multiline?: boolean | null; required?: boolean | null };
300
+
301
+ function TextField({ props }: Props<TextFieldProps>) {
302
+ const field = useField(props.name, undefined, props.required ?? undefined);
303
+ const id = useId();
304
+ const Control = props.multiline ? Textarea : Input;
305
+ return (
306
+ <div className="grid gap-1.5">
307
+ <FieldLabel htmlFor={id} label={props.label} required={props.required} />
308
+ <Control
309
+ id={id}
310
+ value={typeof field.value === "string" ? field.value : ""}
311
+ placeholder={props.placeholder ?? undefined}
312
+ disabled={field.disabled}
313
+ aria-invalid={field.invalid || undefined}
314
+ onChange={(event: { target: { value: string } }) => field.set(event.target.value)}
315
+ />
316
+ </div>
317
+ );
318
+ }
319
+
320
+ type NumberFieldProps = {
321
+ name: string;
322
+ label: string;
323
+ min?: number | null;
324
+ max?: number | null;
325
+ step?: number | null;
326
+ value?: number | null;
327
+ required?: boolean | null;
328
+ };
329
+
330
+ function NumberField({ props }: Props<NumberFieldProps>) {
331
+ const field = useField(props.name, props.value ?? undefined, props.required ?? undefined);
332
+ const id = useId();
333
+ return (
334
+ <div className="grid gap-1.5">
335
+ <FieldLabel htmlFor={id} label={props.label} required={props.required} />
336
+ <Input
337
+ id={id}
338
+ type="number"
339
+ inputMode="decimal"
340
+ min={props.min ?? undefined}
341
+ max={props.max ?? undefined}
342
+ step={props.step ?? "any"}
343
+ value={typeof field.value === "number" ? field.value : ""}
344
+ disabled={field.disabled}
345
+ aria-invalid={field.invalid || undefined}
346
+ onChange={(event: { target: { value: string } }) =>
347
+ field.set(event.target.value === "" ? undefined : Number(event.target.value))
348
+ }
349
+ />
350
+ </div>
351
+ );
352
+ }
353
+
354
+ function Actions({ props }: Props<{ buttons: unknown[] }>) {
355
+ const state = useCardState();
356
+ const buttons = props.buttons.filter(isElement<{ id: string; label: string; primary?: boolean | null }>);
357
+ return (
358
+ <div className="flex flex-wrap gap-2">
359
+ {buttons.map((button) => (
360
+ <Button
361
+ key={button.props.id}
362
+ type="button"
363
+ size="sm"
364
+ variant={button.props.primary ? "default" : "outline"}
365
+ disabled={!state.answerable}
366
+ onClick={() => state.submit(button.props.id)}
367
+ >
368
+ {button.props.label}
369
+ </Button>
370
+ ))}
371
+ </div>
372
+ );
373
+ }
374
+
375
+ function Fold({ props, renderNode }: Props<{ title: string; children: unknown[]; open?: boolean | null }>) {
376
+ const [open, setOpen] = useState(props.open === true);
377
+ return (
378
+ <Collapsible open={open} onOpenChange={setOpen} className="rounded-md border">
379
+ <CollapsibleTrigger className="flex w-full min-h-9 items-center justify-between gap-2 px-3 py-2 text-left text-sm font-medium">
380
+ <span className="min-w-0 break-words">{props.title}</span>
381
+ <span aria-hidden="true" className="text-muted-foreground">
382
+ {open ? "−" : "+"}
383
+ </span>
384
+ </CollapsibleTrigger>
385
+ <CollapsibleContent className="grid gap-3 border-t px-3 py-3">{renderNode(props.children)}</CollapsibleContent>
386
+ </Collapsible>
387
+ );
388
+ }
389
+
390
+ function TabsNode({ props, renderNode }: Props<{ tabs: unknown[] }>) {
391
+ const tabs = props.tabs.filter(isElement<{ label: string; children: unknown[] }>);
392
+ if (tabs.length === 0) return null;
393
+ return (
394
+ <Tabs defaultValue="0" className="min-w-0">
395
+ <TabsList className="max-w-full overflow-x-auto">
396
+ {tabs.map((tab, index) => (
397
+ <TabsTrigger key={index} value={String(index)}>
398
+ {tab.props.label}
399
+ </TabsTrigger>
400
+ ))}
401
+ </TabsList>
402
+ {tabs.map((tab, index) => (
403
+ <TabsContent key={index} value={String(index)} className="grid gap-3 pt-2">
404
+ {renderNode(tab.props.children)}
405
+ </TabsContent>
406
+ ))}
407
+ </Tabs>
408
+ );
409
+ }
410
+
411
+ /** A Tab or a Series is drawn by its parent; alone, it draws nothing. */
412
+ function DrawnByParent() {
413
+ return null;
414
+ }
415
+
416
+ export const library = createCardLibrary<FC<Props<any>>>({
417
+ Card: CardRoot,
418
+ Text,
419
+ List,
420
+ Badges,
421
+ Callout,
422
+ Table,
423
+ Options,
424
+ Option,
425
+ BarChart: BarChartNode,
426
+ LineChart: LineChartNode,
427
+ Series: DrawnByParent,
428
+ Choice,
429
+ Checkboxes,
430
+ TextField,
431
+ NumberField,
432
+ Actions,
433
+ Button: DrawnByParent,
434
+ Fold,
435
+ Tabs: TabsNode,
436
+ Tab: DrawnByParent,
437
+ });
438
+
439
+ /** The body of an `openui-cards` card: the program, its local state and the answer. */
440
+ export function OpenUICard({ card, answerable, answer }: CardRendererProps) {
441
+ const [values, setValues] = useState<Values>(() => ({ ...(card.result?.values ?? {}) }));
442
+ const [missing, setMissing] = useState<string[]>([]);
443
+ const [noteOpen, setNoteOpen] = useState(false);
444
+ const [note, setNote] = useState("");
445
+ const fields = useRef(new Map<string, FieldMeta>());
446
+ const noteId = useId();
447
+ const decision = !card.presentation;
448
+
449
+ const state = useMemo<CardState>(
450
+ () => ({
451
+ answerable: answerable && decision,
452
+ values,
453
+ missing,
454
+ setValue(name, value) {
455
+ setValues((current) => ({ ...current, [name]: value }));
456
+ setMissing((current) => current.filter((item) => item !== name));
457
+ },
458
+ register(meta) {
459
+ fields.current.set(meta.name, meta);
460
+ return () => {
461
+ if (fields.current.get(meta.name) === meta) fields.current.delete(meta.name);
462
+ };
463
+ },
464
+ submit(actionId) {
465
+ const collected: Values = {};
466
+ for (const meta of fields.current.values()) {
467
+ const value = meta.name in values ? values[meta.name] : meta.initial;
468
+ if (!isEmpty(value)) collected[meta.name] = value;
469
+ }
470
+ const absent = [...fields.current.values()].filter((meta) => meta.required && isEmpty(collected[meta.name])).map((meta) => meta.name);
471
+ setMissing(absent);
472
+ if (absent.length > 0) return;
473
+ void answer({ actionId, values: collected, note: note.trim() || null }).catch(() => {});
474
+ },
475
+ }),
476
+ [answerable, decision, values, missing, note, answer],
477
+ );
478
+
479
+ return (
480
+ <CardStateContext.Provider value={state}>
481
+ <div className="grid min-w-0 gap-3" data-openui-card={card.id}>
482
+ <Renderer response={card.body} library={library} />
483
+ {missing.length > 0 ? (
484
+ <p role="alert" className="text-sm text-destructive">
485
+ Fill in the required fields first.
486
+ </p>
487
+ ) : null}
488
+ {decision && answerable ? (
489
+ noteOpen ? (
490
+ <div className="grid gap-1.5">
491
+ <Label htmlFor={noteId} className="text-sm font-medium">
492
+ Note (optional)
493
+ </Label>
494
+ <Textarea id={noteId} value={note} onChange={(event: { target: { value: string } }) => setNote(event.target.value)} />
495
+ </div>
496
+ ) : (
497
+ <div>
498
+ <Button type="button" size="sm" variant="ghost" onClick={() => setNoteOpen(true)}>
499
+ Add a note
500
+ </Button>
501
+ </div>
502
+ )
503
+ ) : null}
504
+ </div>
505
+ </CardStateContext.Provider>
506
+ );
507
+ }
508
+
509
+ type ClientContext = { effect(execute: () => () => void, label?: string): unknown };
510
+
511
+ export function apply(ctx: ClientContext) {
512
+ ctx.effect(() => cards.register(PLUGIN_KEY, CARD_TYPE, OpenUICard), "openui-cards/renderer");
513
+ }
package/src/index.js ADDED
@@ -0,0 +1,52 @@
1
+ // @ts-check
2
+ /**
3
+ * Host face of the `openui-cards` plugin (ADR 0015, `docs/microvac/openui-cards.md`):
4
+ * fills the `interaction.pluginCard.validate` hook for cards whose
5
+ * `payload.plugin` is `openui-cards`. At creation it parses the OpenUI Lang
6
+ * body against the card library and declares the card's buttons as its
7
+ * actions (none: a presentation card); at `/respond` it checks the values
8
+ * against the card's fields and writes the readable summary.
9
+ * Its client face (`src/client.tsx`, built into `lib/client.js`) draws the cards.
10
+ *
11
+ * # microvac.yml
12
+ * - id: openui-cards
13
+ * name: "@microvac/plugin-openui-cards"
14
+ */
15
+ import z from "@deepseek-ai/schemastery";
16
+ import { PLUGIN_KEY } from "./library.js";
17
+ import { checkAnswer, checkCard } from "./validate.js";
18
+
19
+ export const name = "@microvac/plugin-openui-cards";
20
+
21
+ export const inject = ["hooks"];
22
+
23
+ export const Config = z.object({});
24
+
25
+ /**
26
+ * @typedef {{ status: "unhandled" } | { status: "valid", actions?: string[], summary?: string | null } | { status: "invalid", errors: string[] }} Verdict
27
+ * @typedef {{ phase: "create" | "respond", payload: { plugin: string, type: string, body: string }, response?: { actionId: string | null, values: Record<string, unknown>, note?: string | null } }} VerdictContext
28
+ */
29
+
30
+ /**
31
+ * The hook handler: answers only for this plugin's cards.
32
+ * @param {Verdict} value
33
+ * @param {VerdictContext} context
34
+ * @returns {Verdict}
35
+ */
36
+ export function validatePluginCard(value, context) {
37
+ if (context.payload.plugin !== PLUGIN_KEY) return value;
38
+ if (context.phase === "create") {
39
+ const card = checkCard(context.payload.body);
40
+ return card.ok ? { status: "valid", actions: card.buttons.map((button) => button.id) } : { status: "invalid", errors: card.errors };
41
+ }
42
+ if (!context.response) return { status: "invalid", errors: ["No answer to check."] };
43
+ const answer = checkAnswer(context.payload.body, context.response);
44
+ return answer.ok ? { status: "valid", summary: answer.summary } : { status: "invalid", errors: answer.errors };
45
+ }
46
+
47
+ /**
48
+ * @param {{ hooks: { register(name: string, handler: (value: any, context: any) => any): unknown } }} ctx
49
+ */
50
+ export function apply(ctx) {
51
+ ctx.hooks.register("interaction.pluginCard.validate", validatePluginCard);
52
+ }