@ruckc/truss-chat 1.18.3 → 1.20.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.
@@ -6,6 +6,8 @@
6
6
  let {
7
7
  value = $bindable(''),
8
8
  onsend,
9
+ onkeydown: hook,
10
+ trim = true,
9
11
  busy = false,
10
12
  sendOn = 'enter',
11
13
  placeholder = 'Message',
@@ -16,11 +18,15 @@
16
18
  actions,
17
19
  class: klass = '',
18
20
  ...rest
19
- }: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'onkeydown'> & {
21
+ }: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class'> & {
20
22
  /** The draft text. Bindable; cleared after a send. */
21
23
  value?: string;
22
- /** Called with the trimmed text when the user sends. Not called while `busy` or when the draft is blank. */
23
- onsend?: (text: string) => void;
24
+ /** Called with the text when the user sends (trimmed unless `trim` is false) and, as the second argument, the raw draft. Not called while `busy` or when the draft is blank. */
25
+ onsend?: (text: string, raw: string) => void;
26
+ /** Called first on every keydown in the field, also during an IME composition (check `e.isComposing`). Call `e.preventDefault()` to skip the built-in send/newline handling, e.g. for history or completion keys. */
27
+ onkeydown?: (e: KeyboardEvent) => void;
28
+ /** Trim the text passed to `onsend`. Set false to keep leading/trailing whitespace and newlines (the blank check still ignores whitespace-only drafts). */
29
+ trim?: boolean;
24
30
  /** A reply is in progress: the send button shows a spinner and is disabled, and sending does nothing. The text stays editable. */
25
31
  busy?: boolean;
26
32
  /** `enter`: Enter sends and Shift+Enter adds a newline. `mod-enter`: Ctrl/Cmd+Enter sends and Enter adds a newline. Enter never sends while an IME composition is in progress. */
@@ -44,12 +50,28 @@
44
50
 
45
51
  function send() {
46
52
  if (busy || disabled || empty) return;
47
- const text = value.trim();
53
+ const raw = value;
48
54
  value = '';
49
- onsend?.(text);
55
+ onsend?.(trim ? raw.trim() : raw, raw);
56
+ }
57
+
58
+ let root: HTMLDivElement;
59
+ const field = () => root.querySelector('textarea')!;
60
+ /** Focus the text field, e.g. after a dialog closes. */
61
+ export function focus(options?: FocusOptions) {
62
+ field().focus(options);
63
+ }
64
+ /** Select a range of the text, or put the caret at `start` (the end when omitted), e.g. after completing a command. Focuses the field. */
65
+ export function select(start?: number, end?: number) {
66
+ const el = field();
67
+ const a = start ?? el.value.length;
68
+ el.focus();
69
+ el.setSelectionRange(a, end ?? a);
50
70
  }
51
71
 
52
72
  function onkeydown(e: KeyboardEvent) {
73
+ hook?.(e);
74
+ if (e.defaultPrevented) return;
53
75
  // keyCode 229 is the IME's "processing" key on browsers that report isComposing too late
54
76
  if (e.key !== 'Enter' || e.isComposing || e.keyCode === 229) return;
55
77
  const wanted = sendOn === 'enter' ? !e.shiftKey : e.ctrlKey || e.metaKey;
@@ -59,7 +81,7 @@
59
81
  }
60
82
  </script>
61
83
 
62
- <div {...rest} class={['composer', klass]} aria-busy={busy}>
84
+ <div {...rest} bind:this={root} class={['composer', klass]} aria-busy={busy}>
63
85
  <Textarea bind:value minRows={1} {maxRows} autosize {placeholder} {disabled} aria-label={label} {onkeydown} class="field" />
64
86
  {#if actions}<div class="actions">{@render actions()}</div>{/if}
65
87
  <Button icon="send" aria-label={sendLabel} loading={busy} disabled={disabled || busy || empty} onclick={send} />
@@ -1,10 +1,14 @@
1
1
  import type { Snippet } from 'svelte';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
- type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'onkeydown'> & {
3
+ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class'> & {
4
4
  /** The draft text. Bindable; cleared after a send. */
5
5
  value?: string;
6
- /** Called with the trimmed text when the user sends. Not called while `busy` or when the draft is blank. */
7
- onsend?: (text: string) => void;
6
+ /** Called with the text when the user sends (trimmed unless `trim` is false) and, as the second argument, the raw draft. Not called while `busy` or when the draft is blank. */
7
+ onsend?: (text: string, raw: string) => void;
8
+ /** Called first on every keydown in the field, also during an IME composition (check `e.isComposing`). Call `e.preventDefault()` to skip the built-in send/newline handling, e.g. for history or completion keys. */
9
+ onkeydown?: (e: KeyboardEvent) => void;
10
+ /** Trim the text passed to `onsend`. Set false to keep leading/trailing whitespace and newlines (the blank check still ignores whitespace-only drafts). */
11
+ trim?: boolean;
8
12
  /** A reply is in progress: the send button shows a spinner and is disabled, and sending does nothing. The text stays editable. */
9
13
  busy?: boolean;
10
14
  /** `enter`: Enter sends and Shift+Enter adds a newline. `mod-enter`: Ctrl/Cmd+Enter sends and Enter adds a newline. Enter never sends while an IME composition is in progress. */
@@ -23,6 +27,9 @@ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class
23
27
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
24
28
  class?: string;
25
29
  };
26
- declare const ChatComposer: import("svelte").Component<$$ComponentProps, {}, "value">;
30
+ declare const ChatComposer: import("svelte").Component<$$ComponentProps, {
31
+ focus: (options?: FocusOptions) => void;
32
+ select: (start?: number, end?: number) => void;
33
+ }, "value">;
27
34
  type ChatComposer = ReturnType<typeof ChatComposer>;
28
35
  export default ChatComposer;
@@ -0,0 +1,62 @@
1
+ <script lang="ts">
2
+ import type { HTMLAttributes } from 'svelte/elements';
3
+ import type { Question, QuestionAnswer } from './QuestionForm.svelte';
4
+
5
+ let {
6
+ questions,
7
+ answers = [],
8
+ declined = false,
9
+ label = 'You answered',
10
+ declinedLabel = 'You declined to answer',
11
+ emptyLabel = 'No answer',
12
+ class: klass = '',
13
+ ...rest
14
+ }: Omit<HTMLAttributes<HTMLElement>, 'children' | 'class'> & {
15
+ /** The questions that were asked: the same array given to `QuestionForm`. */
16
+ questions: Question[];
17
+ /** What was answered, one entry per question in order: the array `QuestionForm`'s `onsubmit` returned. Missing entries (or an empty `selected` without `other`) read as unanswered. */
18
+ answers?: QuestionAnswer[];
19
+ /** The whole form was skipped (`onskip`): shows `declinedLabel` instead of `label`, and every question as unanswered. */
20
+ declined?: boolean;
21
+ /** The heading of an answered form. Replace it for another language. */
22
+ label?: string;
23
+ /** The heading of a declined form. */
24
+ declinedLabel?: string;
25
+ /** Shown for a question without an answer (an `optional` one that was passed, or any question when `declined`). */
26
+ emptyLabel?: string;
27
+ /** Other attributes (`data-testid`, `id`, ...) go to the root `<section>`. `class` is added to it. */
28
+ class?: string;
29
+ } = $props();
30
+
31
+ const parts = (a: QuestionAnswer | undefined) => (declined || !a ? [] : [...a.selected, ...(a.other ? [`Other: ${a.other}`] : [])]);
32
+ const uid = $props.id();
33
+ </script>
34
+
35
+ <!-- a read-only record of an exchange, aligned and tinted like the user's own message so the thread reads question, then answer -->
36
+ <section {...rest} class={['qa', klass]} data-declined={declined} aria-labelledby="{uid}-h">
37
+ <p class="who" id="{uid}-h">{declined ? declinedLabel : label}</p>
38
+ <dl class="list">
39
+ {#each questions as item, i (i)}
40
+ {@const shown = parts(answers[i])}
41
+ <div class="item">
42
+ <dt class="q">{#if item.header}<span class="header">{item.header}</span>{/if}{item.question}</dt>
43
+ {#if shown.length}
44
+ {#each shown as s, j (j)}<dd class="a">{s}</dd>{/each}
45
+ {:else}
46
+ <dd class="a empty">{emptyLabel}</dd>
47
+ {/if}
48
+ </div>
49
+ {/each}
50
+ </dl>
51
+ </section>
52
+
53
+ <style>
54
+ .qa { align-self: flex-end; display: flex; flex-direction: column; gap: var(--tr-space-2); box-sizing: border-box; min-width: 0; max-width: min(85%, 60ch); padding: var(--tr-space-2) var(--tr-space-3); border-radius: var(--tr-radius-lg) var(--tr-radius-lg) var(--tr-radius-sm) var(--tr-radius-lg); background: var(--tr-primary-container); color: var(--tr-on-primary-container); overflow-wrap: anywhere; }
55
+ .who { margin: 0; font-size: var(--tr-text-sm); font-weight: 600; }
56
+ .list { display: flex; flex-direction: column; gap: var(--tr-space-2); margin: 0; }
57
+ .item { display: flex; flex-direction: column; min-width: 0; }
58
+ .header { display: block; font-size: var(--tr-text-sm); font-weight: 600; opacity: 0.8; }
59
+ .q { font-size: var(--tr-text-sm); opacity: 0.85; }
60
+ .a { margin: 0; font-weight: 600; }
61
+ .empty { font-weight: 400; font-style: italic; opacity: 0.85; }
62
+ </style>
@@ -0,0 +1,21 @@
1
+ import type { HTMLAttributes } from 'svelte/elements';
2
+ import type { Question, QuestionAnswer } from './QuestionForm.svelte';
3
+ type $$ComponentProps = Omit<HTMLAttributes<HTMLElement>, 'children' | 'class'> & {
4
+ /** The questions that were asked: the same array given to `QuestionForm`. */
5
+ questions: Question[];
6
+ /** What was answered, one entry per question in order: the array `QuestionForm`'s `onsubmit` returned. Missing entries (or an empty `selected` without `other`) read as unanswered. */
7
+ answers?: QuestionAnswer[];
8
+ /** The whole form was skipped (`onskip`): shows `declinedLabel` instead of `label`, and every question as unanswered. */
9
+ declined?: boolean;
10
+ /** The heading of an answered form. Replace it for another language. */
11
+ label?: string;
12
+ /** The heading of a declined form. */
13
+ declinedLabel?: string;
14
+ /** Shown for a question without an answer (an `optional` one that was passed, or any question when `declined`). */
15
+ emptyLabel?: string;
16
+ /** Other attributes (`data-testid`, `id`, ...) go to the root `<section>`. `class` is added to it. */
17
+ class?: string;
18
+ };
19
+ declare const QuestionAnswers: import("svelte").Component<$$ComponentProps, {}, "">;
20
+ type QuestionAnswers = ReturnType<typeof QuestionAnswers>;
21
+ export default QuestionAnswers;
@@ -4,7 +4,7 @@
4
4
  /** A short topic shown above the question, e.g. "Auth method". */
5
5
  header?: string;
6
6
  question: string;
7
- options: { label: string; description?: string }[];
7
+ options: { label: string; description?: string; /** Marks the suggested choice: " (Recommended)" is appended to its label (the answer still holds the plain label). */ recommended?: boolean }[];
8
8
  /** Several options can be chosen. Otherwise exactly one. */
9
9
  multiSelect?: boolean;
10
10
  /** The question can be passed without an answer. */
@@ -15,9 +15,9 @@
15
15
  </script>
16
16
 
17
17
  <script lang="ts">
18
- import { tick, untrack } from 'svelte';
18
+ import { tick, untrack, type Snippet } from 'svelte';
19
19
  import type { HTMLAttributes } from 'svelte/elements';
20
- import { Button, Checkbox, RadioGroup, Textarea } from '@ruckc/truss-ui';
20
+ import { Button, Checkbox, Icon, Kbd, RadioGroup, Textarea } from '@ruckc/truss-ui';
21
21
 
22
22
  let {
23
23
  questions,
@@ -25,6 +25,11 @@
25
25
  onsubmit,
26
26
  onskip,
27
27
  submitLabel = 'Submit',
28
+ mode = 'wizard',
29
+ review = 'auto',
30
+ header,
31
+ numberKeys = false,
32
+ submitOnModEnter = false,
28
33
  class: klass = '',
29
34
  ...rest
30
35
  }: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'onkeydown' | 'onsubmit'> & {
@@ -38,20 +43,48 @@
38
43
  onskip?: () => void;
39
44
  /** Text of the final button on the review page. */
40
45
  submitLabel?: string;
46
+ /**
47
+ * `wizard` (default): one question per page, then a review page.
48
+ * `tabs`: the questions are tabs (ARIA tabs pattern: Left/Right/Home/End move between them, an answered one shows a tick) and a Submit button is always there, enabled once every required question is answered; there is no review page.
49
+ * Alt+Left/Right switches tabs from anywhere in the form. Read once, like `questions`.
50
+ */
51
+ mode?: 'wizard' | 'tabs';
52
+ /**
53
+ * `wizard` mode: whether a review page comes before the final submit. `auto` (default): only when there is more than one question (or none).
54
+ * With one question and no review page, choosing an option of a single-choice question submits at once (picking with the arrow keys does not: confirm with Enter), and a multiple-choice question or an Other answer ends in the Submit button.
55
+ * `always` keeps the review page; `never` makes the last question's button Submit. Read once. Ignored in `tabs` mode.
56
+ */
57
+ review?: 'auto' | 'always' | 'never';
58
+ /** A header row above the form inside the attention frame, e.g. an icon and "Claude needs your answer". Without it only the frame shows. */
59
+ header?: Snippet;
60
+ /** `tabs` mode: the keys 1-9 pick the Nth option of the current question (toggle it for multiple choice). Ignored while typing in a text field. */
61
+ numberKeys?: boolean;
62
+ /** `tabs` mode: Ctrl/Cmd+Enter submits from anywhere, once every required question is answered. */
63
+ submitOnModEnter?: boolean;
41
64
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
42
65
  class?: string;
43
66
  } = $props();
44
67
 
45
68
  const uid = $props.id();
46
69
  const qs = untrack(() => questions);
70
+ const tabs = untrack(() => mode) === 'tabs';
71
+ const reviewMode = untrack(() => review);
72
+ /** The review page exists: always for `always` and for an empty form, never for `never`, otherwise only for several questions. */
73
+ const withReview = !tabs && (qs.length === 0 || reviewMode === 'always' || (reviewMode === 'auto' && qs.length > 1));
74
+ /** One question and no review page: a single-choice pick submits at once. */
75
+ const instant = !tabs && !withReview && qs.length === 1;
76
+ let arrowed = false; // a radio picked with the arrow keys is only moved to: it is confirmed with Enter
47
77
  const total = qs.length;
78
+ /** "Question N of M" is shown unless it would only say "1 of 1" without a review page. */
79
+ const numbered = total > 1 || withReview;
48
80
  let page = $state(0); // `total` is the review page
49
81
  let editing = $state(false);
50
82
  let picked = $state<string[][]>(qs.map(() => []));
51
83
  let others = $state<string[]>(qs.map(() => ''));
52
84
  let head = $state<HTMLElement>();
53
85
 
54
- const review = $derived(page === total);
86
+ const lastPage = $derived(page === total - 1);
87
+ const reviewing = $derived(withReview && page === total);
55
88
  const q = $derived(qs[page]);
56
89
  const isAnswered = (i: number) => picked[i].length > 0 || others[i].trim() !== '';
57
90
  const canNext = $derived(isAnswered(page) || !!q.optional);
@@ -63,6 +96,7 @@
63
96
  }
64
97
  const next = () => {
65
98
  if (!canNext) return;
99
+ if (!withReview && lastPage) return submit();
66
100
  if (editing) {
67
101
  editing = false;
68
102
  go(total);
@@ -81,6 +115,7 @@
81
115
  const setSingle = (i: number, v: string) => {
82
116
  picked[i] = [v];
83
117
  others[i] = '';
118
+ if (instant && !arrowed) submit();
84
119
  };
85
120
  const toggle = (i: number, label: string, on: boolean) => {
86
121
  picked[i] = order(i, on ? [...picked[i], label] : picked[i].filter((l) => l !== label));
@@ -98,23 +133,58 @@
98
133
  );
99
134
  const summary = (a: QuestionAnswer) => [...a.selected, ...(a.other ? [`Other: ${a.other}`] : [])].join(', ') || 'No answer';
100
135
  const submit = () => onsubmit?.($state.snapshot(answers));
136
+ const canSubmit = $derived(qs.every((item, i) => item.optional || isAnswered(i)));
137
+ const optionLabel = (o: Question['options'][number]) => (o.recommended ? `${o.label} (Recommended)` : o.label);
138
+ const tabLabel = (i: number) => qs[i].header ?? `Question ${i + 1}`;
139
+ const selectTab = (i: number, focus = false) => {
140
+ page = (i + total) % total;
141
+ if (focus) document.getElementById(`${uid}-tab-${page}`)?.focus();
142
+ };
143
+
144
+ function onTabKey(e: KeyboardEvent) {
145
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
146
+ const to = { ArrowRight: page + 1, ArrowLeft: page - 1, Home: 0, End: total - 1 }[e.key];
147
+ if (to === undefined) return;
148
+ e.preventDefault();
149
+ selectTab(to, true);
150
+ }
101
151
 
102
152
  function onkeydown(e: KeyboardEvent) {
153
+ arrowed = e.key.startsWith('Arrow');
103
154
  if (e.key === 'Escape') {
104
155
  if (!onskip) return;
105
156
  e.preventDefault();
106
157
  onskip();
107
158
  return;
108
159
  }
160
+ if (tabs) return onTabsKey(e);
109
161
  if (e.key !== 'Enter' || e.isComposing || e.keyCode === 229 || e.shiftKey) return;
110
162
  const t = e.target as HTMLElement;
111
163
  // buttons activate themselves; a multi-line "Other" answer keeps its Enter for the newline
112
164
  if (t.closest('button') || (t instanceof HTMLTextAreaElement && t.value.includes('\n'))) return;
113
165
  e.preventDefault();
114
- if (review) submit();
166
+ if (reviewing) submit();
115
167
  else next();
116
168
  }
117
169
 
170
+ function onTabsKey(e: KeyboardEvent) {
171
+ if (e.isComposing || e.keyCode === 229) return;
172
+ if (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
173
+ e.preventDefault();
174
+ selectTab(page + (e.key === 'ArrowRight' ? 1 : -1), true); // the focused option is replaced with the panel, so focus goes to the tab
175
+ } else if (e.key === 'Enter' && submitOnModEnter && (e.ctrlKey || e.metaKey)) {
176
+ e.preventDefault();
177
+ if (canSubmit) submit();
178
+ } else if (numberKeys && /^[1-9]$/.test(e.key) && !e.altKey && !e.ctrlKey && !e.metaKey) {
179
+ const t = e.target as HTMLElement;
180
+ const o = q.options[Number(e.key) - 1];
181
+ if (!o || t instanceof HTMLTextAreaElement) return;
182
+ e.preventDefault();
183
+ if (q.multiSelect) toggle(page, o.label, !picked[page].includes(o.label));
184
+ else setSingle(page, o.label);
185
+ }
186
+ }
187
+
118
188
  /** Checkboxes have no arrow-key behaviour of their own: Up/Down (and Left/Right) move between the options. */
119
189
  function arrows(node: HTMLElement) {
120
190
  const onArrow = (e: KeyboardEvent) => {
@@ -130,9 +200,40 @@
130
200
  }
131
201
  </script>
132
202
 
203
+ {#snippet question()}
204
+ {#if q.header}<p class="header">{q.header}</p>{/if}
205
+ <h3 class="title" id="{uid}-q" tabindex="-1" bind:this={head}>{q.question}</h3>
206
+ {#if q.multiSelect}
207
+ <fieldset class="opts" aria-labelledby="{uid}-q" {@attach arrows}>
208
+ {#each q.options as o (o.label)}
209
+ <Checkbox label={optionLabel(o)} description={o.description} bind:checked={() => picked[page].includes(o.label), (on) => toggle(page, o.label, on)} />
210
+ {/each}
211
+ </fieldset>
212
+ {:else}
213
+ <RadioGroup
214
+ aria-labelledby="{uid}-q"
215
+ options={q.options.map((o) => ({ value: o.label, label: optionLabel(o), description: o.description }))}
216
+ bind:value={() => picked[page][0], (v) => setSingle(page, v as string)}
217
+ />
218
+ {/if}
219
+ {#if allowOther}
220
+ <Textarea label="Other" placeholder="Type your own answer" rows={1} autosize bind:value={() => others[page], (v) => setOther(page, v)} />
221
+ {/if}
222
+ {/snippet}
223
+
133
224
  <!-- the keydown handler lives on the wrapper so Enter and Escape work from any control inside -->
134
- <div {...rest} class={['qf', klass]} role="group" aria-label="Questions" {onkeydown}>
135
- {#if review}
225
+ <div {...rest} class={['qf', klass]} role="group" aria-label="Questions" {onkeydown} onkeyup={() => (arrowed = false)}>
226
+ {#if header}<div class="attn">{@render header()}</div>{/if}
227
+ {#if tabs}
228
+ <div class="tabs" role="tablist" aria-label="Questions" aria-orientation="horizontal">
229
+ {#each qs as _, i (i)}
230
+ <button type="button" role="tab" class="tab" id="{uid}-tab-{i}" aria-selected={page === i} aria-controls="{uid}-panel" tabindex={page === i ? 0 : -1} onclick={() => selectTab(i)} onkeydown={onTabKey}>
231
+ {tabLabel(i)}{#if isAnswered(i)}<span class="tick"><Icon name="tick" /></span><span class="tr-visually-hidden"> (answered)</span>{/if}
232
+ </button>
233
+ {/each}
234
+ </div>
235
+ {/if}
236
+ {#if reviewing}
136
237
  <p class="step">Review</p>
137
238
  <h3 class="title" tabindex="-1" bind:this={head}>Review your answers</h3>
138
239
  <ol class="review">
@@ -148,24 +249,11 @@
148
249
  </ol>
149
250
  {:else}
150
251
  {#key page}
151
- <p class="step">Question {page + 1} of {total}{#if q.optional} · optional{/if}</p>
152
- {#if q.header}<p class="header">{q.header}</p>{/if}
153
- <h3 class="title" id="{uid}-q" tabindex="-1" bind:this={head}>{q.question}</h3>
154
- {#if q.multiSelect}
155
- <fieldset class="opts" aria-labelledby="{uid}-q" {@attach arrows}>
156
- {#each q.options as o (o.label)}
157
- <Checkbox label={o.label} description={o.description} bind:checked={() => picked[page].includes(o.label), (on) => toggle(page, o.label, on)} />
158
- {/each}
159
- </fieldset>
252
+ {#if tabs}
253
+ <div class="panel" role="tabpanel" id="{uid}-panel" aria-labelledby="{uid}-tab-{page}">{@render question()}</div>
160
254
  {:else}
161
- <RadioGroup
162
- aria-labelledby="{uid}-q"
163
- options={q.options.map((o) => ({ value: o.label, label: o.label, description: o.description }))}
164
- bind:value={() => picked[page][0], (v) => setSingle(page, v as string)}
165
- />
166
- {/if}
167
- {#if allowOther}
168
- <Textarea label="Other" placeholder="Type your own answer" rows={1} autosize bind:value={() => others[page], (v) => setOther(page, v)} />
255
+ {#if numbered || q.optional}<p class="step">{#if numbered}Question {page + 1} of {total}{/if}{#if q.optional}{numbered ? ' · ' : ''}optional{/if}</p>{/if}
256
+ {@render question()}
169
257
  {/if}
170
258
  {/key}
171
259
  {/if}
@@ -173,18 +261,23 @@
173
261
  <div class="nav">
174
262
  {#if onskip}<Button variant="minimal" onclick={onskip}>Skip</Button>{/if}
175
263
  <span class="grow"></span>
176
- {#if review}
264
+ {#if tabs}
265
+ {#if submitOnModEnter}<span class="hint"><Kbd keys="mod+enter" /></span>{/if}
266
+ <Button disabled={!canSubmit} onclick={submit}>{submitLabel}</Button>
267
+ {:else if reviewing}
177
268
  <Button variant="outlined" onclick={() => go(total - 1)}>Back</Button>
178
269
  <Button onclick={submit}>{submitLabel}</Button>
179
270
  {:else}
180
271
  <Button variant="outlined" disabled={page === 0} onclick={back}>Back</Button>
181
- <Button disabled={!canNext} onclick={next}>Next</Button>
272
+ <Button disabled={!canNext} onclick={next}>{!withReview && lastPage ? submitLabel : 'Next'}</Button>
182
273
  {/if}
183
274
  </div>
184
275
  </div>
185
276
 
186
277
  <style>
187
- .qf { display: flex; flex-direction: column; gap: var(--tr-space-3); min-width: 0; max-width: 100%; padding: var(--tr-space-4); border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-lg); background: var(--tr-surface-container-low); }
278
+ /* an open question asks for attention: an accent frame, and an optional header row */
279
+ .qf { display: flex; flex-direction: column; gap: var(--tr-space-3); min-width: 0; max-width: 100%; box-sizing: border-box; padding: var(--tr-space-4); border: 2px solid var(--tr-primary); border-radius: var(--tr-radius-lg); background: var(--tr-surface-container-low); }
280
+ .attn { display: flex; align-items: center; gap: var(--tr-space-2); min-width: 0; margin: calc(-1 * var(--tr-space-4)) calc(-1 * var(--tr-space-4)) 0; padding: var(--tr-space-2) var(--tr-space-4); border-radius: calc(var(--tr-radius-lg) - 2px) calc(var(--tr-radius-lg) - 2px) 0 0; background: var(--tr-primary-container); color: var(--tr-on-primary-container); font-weight: 600; overflow-wrap: anywhere; }
188
281
  .step { margin: 0; color: var(--tr-on-surface-variant); font-size: var(--tr-text-sm); font-variant-numeric: tabular-nums; }
189
282
  .header { margin: 0; color: var(--tr-primary-text, var(--tr-primary)); font-size: var(--tr-text-sm); font-weight: 600; }
190
283
  .title { margin: 0; font-size: var(--tr-text-lg); line-height: 1.3; overflow-wrap: anywhere; }
@@ -193,6 +286,13 @@
193
286
  /* long labels wrap inside the narrowest column instead of widening the form */
194
287
  .qf :global(.cb), .qf :global(.opt) { max-width: 100%; }
195
288
  .qf :global(.text) { min-width: 0; overflow-wrap: anywhere; }
289
+ .tabs { display: flex; flex-wrap: wrap; gap: var(--tr-space-1); border-bottom: 1px solid var(--tr-outline-variant); }
290
+ .tab { display: inline-flex; align-items: center; gap: var(--tr-space-1); min-height: var(--tr-control-h-sm); padding: 0 var(--tr-space-3); border: 0; border-bottom: 2px solid transparent; background: none; color: var(--tr-on-surface-variant); font: inherit; cursor: pointer; }
291
+ .tab[aria-selected='true'] { color: var(--tr-on-surface); border-bottom-color: var(--tr-primary); font-weight: 600; }
292
+ .tab:focus-visible { outline: none; box-shadow: var(--tr-focus-ring); }
293
+ .tick { display: inline-flex; color: var(--tr-success); }
294
+ .panel { display: flex; flex-direction: column; gap: var(--tr-space-3); min-width: 0; }
295
+ .hint { color: var(--tr-on-surface-variant); }
196
296
  .review { display: flex; flex-direction: column; gap: var(--tr-space-2); margin: 0; padding: 0; list-style: none; }
197
297
  .review li { display: flex; align-items: center; justify-content: space-between; gap: var(--tr-space-2); padding-bottom: var(--tr-space-2); border-bottom: 1px solid var(--tr-outline-variant); }
198
298
  .ra { display: flex; flex-direction: column; min-width: 0; overflow-wrap: anywhere; }
@@ -5,7 +5,8 @@ export type Question = {
5
5
  question: string;
6
6
  options: {
7
7
  label: string;
8
- description?: string;
8
+ description?: string; /** Marks the suggested choice: " (Recommended)" is appended to its label (the answer still holds the plain label). */
9
+ recommended?: boolean;
9
10
  }[];
10
11
  /** Several options can be chosen. Otherwise exactly one. */
11
12
  multiSelect?: boolean;
@@ -17,6 +18,7 @@ export type QuestionAnswer = {
17
18
  selected: string[];
18
19
  other?: string;
19
20
  };
21
+ import { type Snippet } from 'svelte';
20
22
  import type { HTMLAttributes } from 'svelte/elements';
21
23
  type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'onkeydown' | 'onsubmit'> & {
22
24
  /** The questions, shown one per page. Read once when the form mounts: to ask a different set, mount a new form (for example in a `{#key}`). */
@@ -29,6 +31,24 @@ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class
29
31
  onskip?: () => void;
30
32
  /** Text of the final button on the review page. */
31
33
  submitLabel?: string;
34
+ /**
35
+ * `wizard` (default): one question per page, then a review page.
36
+ * `tabs`: the questions are tabs (ARIA tabs pattern: Left/Right/Home/End move between them, an answered one shows a tick) and a Submit button is always there, enabled once every required question is answered; there is no review page.
37
+ * Alt+Left/Right switches tabs from anywhere in the form. Read once, like `questions`.
38
+ */
39
+ mode?: 'wizard' | 'tabs';
40
+ /**
41
+ * `wizard` mode: whether a review page comes before the final submit. `auto` (default): only when there is more than one question (or none).
42
+ * With one question and no review page, choosing an option of a single-choice question submits at once (picking with the arrow keys does not: confirm with Enter), and a multiple-choice question or an Other answer ends in the Submit button.
43
+ * `always` keeps the review page; `never` makes the last question's button Submit. Read once. Ignored in `tabs` mode.
44
+ */
45
+ review?: 'auto' | 'always' | 'never';
46
+ /** A header row above the form inside the attention frame, e.g. an icon and "Claude needs your answer". Without it only the frame shows. */
47
+ header?: Snippet;
48
+ /** `tabs` mode: the keys 1-9 pick the Nth option of the current question (toggle it for multiple choice). Ignored while typing in a text field. */
49
+ numberKeys?: boolean;
50
+ /** `tabs` mode: Ctrl/Cmd+Enter submits from anywhere, once every required question is answered. */
51
+ submitOnModEnter?: boolean;
32
52
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
33
53
  class?: string;
34
54
  };
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import { onDestroy, type Snippet } from 'svelte';
2
+ import { onDestroy, untrack, type Snippet } from 'svelte';
3
3
  import type { HTMLAttributes } from 'svelte/elements';
4
4
  import { Button, Dialog, Icon, Tooltip } from '@ruckc/truss-ui';
5
5
  import { formatValue, previewInput } from './chat.js';
@@ -17,6 +17,9 @@
17
17
  error,
18
18
  open = $bindable(false),
19
19
  details,
20
+ leading,
21
+ maxOutputLines,
22
+ inputOpen = true,
20
23
  class: klass = '',
21
24
  ...rest
22
25
  }: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class'> & {
@@ -45,6 +48,12 @@
45
48
  * - A `Snippet` is a custom body (shown after the status line, before the Input, Output and Error sections) and uses the default mode for the variant.
46
49
  */
47
50
  details?: 'dialog' | 'inline' | Snippet;
51
+ /** Content shown before the name, e.g. an icon per tool kind. Sits beside the status icon (the status stays visible, it is not replaced). */
52
+ leading?: Snippet;
53
+ /** Show at most this many lines of the Output and the Input, with a "Show all (N more lines)" button that toggles the rest (`aria-expanded`, linked to the text). Unset shows everything. */
54
+ maxOutputLines?: number;
55
+ /** Whether the Input section starts unfolded. With `false` it is a "Show input" / "Hide input" disclosure. */
56
+ inputOpen?: boolean;
48
57
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
49
58
  class?: string;
50
59
  } = $props();
@@ -65,6 +74,15 @@
65
74
  !!error && { key: 'error', title: 'Error', text: error }
66
75
  ].filter((s) => !!s)
67
76
  );
77
+ const limit = $derived(maxOutputLines !== undefined && maxOutputLines >= 1 ? Math.floor(maxOutputLines) : undefined);
78
+ let expanded = $state<Record<string, boolean>>({});
79
+ let inputShown = $state(untrack(() => inputOpen));
80
+ const cut = (text: string, key: string) => {
81
+ const lines = text.split('\n');
82
+ if (limit === undefined || lines.length <= limit) return { text, hidden: 0, open: false };
83
+ const open = !!expanded[key];
84
+ return { text: open ? text : lines.slice(0, limit).join('\n'), hidden: lines.length - limit, open };
85
+ };
68
86
  const hasBody = $derived(!!custom || sections.length > 0);
69
87
  const preview = $derived(previewInput(input));
70
88
  const tip = $derived(preview ? `${statusText}: ${preview}` : statusText);
@@ -98,16 +116,32 @@
98
116
  <span class="icon"><Icon name={ICONS[status]} spin={status === 'in_progress'} /></span>
99
117
  {/snippet}
100
118
 
119
+ {#snippet lead()}
120
+ {@render icon()}{#if leading}<span class="leading">{@render leading()}</span>{/if}
121
+ {/snippet}
122
+
101
123
  {#snippet body()}
102
124
  <p class="line">Status: <strong>{statusText}</strong></p>
103
125
  {#if custom}{@render custom()}{/if}
104
126
  {#each sections as s (s.key)}
127
+ {@const c = cut(s.text, s.key)}
128
+ {@const folded = s.key === 'input' && !inputShown}
105
129
  <section class="sec" data-section={s.key}>
106
130
  <div class="sec-head">
107
131
  <span class="sec-title">{s.title}</span>
108
- <Button variant="minimal" size="sm" icon={copied?.key === s.key && copied.ok ? 'tick' : 'copy'} aria-label="Copy {s.title.toLowerCase()}" onclick={() => copy(s.key, s.text)} />
132
+ <span class="sec-actions">
133
+ {#if s.key === 'input' && !inputOpen}
134
+ <Button variant="minimal" size="sm" aria-expanded={inputShown} aria-controls="{uid}-{s.key}" onclick={() => (inputShown = !inputShown)}>{inputShown ? 'Hide input' : 'Show input'}</Button>
135
+ {/if}
136
+ <Button variant="minimal" size="sm" icon={copied?.key === s.key && copied.ok ? 'tick' : 'copy'} aria-label="Copy {s.title.toLowerCase()}" onclick={() => copy(s.key, s.text)} />
137
+ </span>
109
138
  </div>
110
- <pre {@attach focusable} role="region" aria-label={s.title}>{s.text}</pre>
139
+ {#if !folded}
140
+ <pre id="{uid}-{s.key}" {@attach focusable} role="region" aria-label={s.title}>{c.text}</pre>
141
+ {#if c.hidden}
142
+ <Button variant="minimal" size="sm" aria-expanded={c.open} aria-controls="{uid}-{s.key}" onclick={() => (expanded[s.key] = !c.open)}>{c.open ? 'Show less' : `Show all (${c.hidden} more ${c.hidden === 1 ? 'line' : 'lines'})`}</Button>
143
+ {/if}
144
+ {/if}
111
145
  </section>
112
146
  {/each}
113
147
  <span class="tr-visually-hidden" role="status" aria-live="polite">{copied ? (copied.ok ? 'Copied' : 'Copy failed') : ''}</span>
@@ -126,10 +160,10 @@
126
160
  aria-controls={mode === 'inline' ? `${uid}-details` : undefined}
127
161
  onclick={() => (open = !open)}
128
162
  >
129
- {@render icon()}<span class="name">{shown}</span>
163
+ {@render lead()}<span class="name">{shown}</span>
130
164
  </button>
131
165
  {:else}
132
- <span class="chip" role="group" aria-label="{shown}, {statusText}">{@render icon()}<span class="name">{shown}</span></span>
166
+ <span class="chip" role="group" aria-label="{shown}, {statusText}">{@render lead()}<span class="name">{shown}</span></span>
133
167
  {/if}
134
168
  </Tooltip>
135
169
  {:else if hasBody}
@@ -141,11 +175,11 @@
141
175
  aria-controls={mode === 'inline' ? `${uid}-details` : undefined}
142
176
  onclick={() => (open = !open)}
143
177
  >
144
- {@render icon()}<span class="name">{shown}</span><span class="status">{statusText}</span>
178
+ {@render lead()}<span class="name">{shown}</span><span class="status">{statusText}</span>
145
179
  {#if mode === 'inline'}<span class="chev" data-open={open}><Icon name="chevron-down" /></span>{/if}
146
180
  </button>
147
181
  {:else}
148
- <div class="row">{@render icon()}<span class="name">{shown}</span><span class="status">{statusText}</span></div>
182
+ <div class="row">{@render lead()}<span class="name">{shown}</span><span class="status">{statusText}</span></div>
149
183
  {/if}
150
184
  {#if hasBody && mode === 'inline' && open}
151
185
  <div class="details" id="{uid}-details">{@render body()}</div>
@@ -166,6 +200,8 @@
166
200
  button.row { cursor: pointer; border-radius: var(--tr-radius-md); }
167
201
  button.row:hover { background: var(--tr-surface-container); }
168
202
  button.row:focus-visible, button.chip:focus-visible { outline: none; box-shadow: var(--tr-focus-ring); }
203
+ .leading { display: inline-flex; flex: none; color: var(--tr-on-surface-variant); }
204
+ .sec-actions { display: inline-flex; align-items: center; gap: var(--tr-space-1); }
169
205
  .icon { display: inline-flex; flex: none; color: var(--tr-on-surface-variant); }
170
206
  [data-status='completed'] .icon { color: var(--tr-success); }
171
207
  [data-status='failed'] .icon { color: var(--tr-danger); }
@@ -27,6 +27,12 @@ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class
27
27
  * - A `Snippet` is a custom body (shown after the status line, before the Input, Output and Error sections) and uses the default mode for the variant.
28
28
  */
29
29
  details?: 'dialog' | 'inline' | Snippet;
30
+ /** Content shown before the name, e.g. an icon per tool kind. Sits beside the status icon (the status stays visible, it is not replaced). */
31
+ leading?: Snippet;
32
+ /** Show at most this many lines of the Output and the Input, with a "Show all (N more lines)" button that toggles the rest (`aria-expanded`, linked to the text). Unset shows everything. */
33
+ maxOutputLines?: number;
34
+ /** Whether the Input section starts unfolded. With `false` it is a "Show input" / "Hide input" disclosure. */
35
+ inputOpen?: boolean;
30
36
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
31
37
  class?: string;
32
38
  };
package/dist/index.d.ts CHANGED
@@ -5,5 +5,6 @@ export { default as ToolCalls } from './ToolCalls.svelte';
5
5
  export { default as ChatComposer } from './ChatComposer.svelte';
6
6
  export { default as ChatStatus } from './ChatStatus.svelte';
7
7
  export { default as QuestionForm } from './QuestionForm.svelte';
8
+ export { default as QuestionAnswers } from './QuestionAnswers.svelte';
8
9
  export type { Question, QuestionAnswer } from './QuestionForm.svelte';
9
10
  export { formatToolName, previewInput, formatValue } from './chat.js';
package/dist/index.js CHANGED
@@ -5,4 +5,5 @@ export { default as ToolCalls } from './ToolCalls.svelte';
5
5
  export { default as ChatComposer } from './ChatComposer.svelte';
6
6
  export { default as ChatStatus } from './ChatStatus.svelte';
7
7
  export { default as QuestionForm } from './QuestionForm.svelte';
8
+ export { default as QuestionAnswers } from './QuestionAnswers.svelte';
8
9
  export { formatToolName, previewInput, formatValue } from './chat.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-chat",
3
- "version": "1.18.3",
3
+ "version": "1.20.0",
4
4
  "description": "Chat building blocks for Truss UI: thread, messages, tool calls, composer, status line and a question form",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -26,7 +26,7 @@
26
26
  "@ruckc/truss-ui": "^1.0.0"
27
27
  },
28
28
  "dependencies": {
29
- "@ruckc/truss-markdown": "^1.18.3"
29
+ "@ruckc/truss-markdown": "^1.20.0"
30
30
  },
31
31
  "author": "Curtis Ruck",
32
32
  "homepage": "https://truss.ruck.io",