@tbox.cn/app-agent-ui-kit 1.0.0-alpha.7 → 1.0.0-alpha.8

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,245 @@
1
+ /**
2
+ * ViewCard:视图卡的通用渲染器(L1)。
3
+ *
4
+ * 一张卡 = 一份 CardView JSON;版式、动作路径、确认弹层、历史禁用都由平台实现一次。
5
+ * 应用只写 view(data) 函数(服务端),客户端不再有手写 tsx。
6
+ */
7
+ import { useEffect, useRef, useState, type ReactNode } from 'react';
8
+ import { normalizeCardView } from '@tbox.cn/app-contracts';
9
+ import type { CardView, CardViewAction, CardViewBlock } from '@tbox.cn/app-contracts';
10
+ import {
11
+ ActionList,
12
+ Bill,
13
+ Card,
14
+ CardButton,
15
+ CardHeader,
16
+ ConfirmSheet,
17
+ EmptyState,
18
+ EntityRow,
19
+ Hero,
20
+ KeyValueList,
21
+ Notice,
22
+ StatusTag,
23
+ Steps,
24
+ TagList,
25
+ Ticket,
26
+ Timeline,
27
+ } from './primitives';
28
+ import type { CardActionSpec } from './primitives';
29
+ import { useCardActions } from './use-card-actions';
30
+
31
+ type Api = ReturnType<typeof useCardActions>;
32
+
33
+ function toSpec(action: CardViewAction): CardActionSpec {
34
+ return {
35
+ label: action.label,
36
+ ...(action.send !== undefined ? { send: action.send } : {}),
37
+ ...(action.invoke ? { invoke: action.invoke } : {}),
38
+ ...(action.confirm ? { confirm: action.confirm } : {}),
39
+ ...(action.style ? { style: action.style } : {}),
40
+ };
41
+ }
42
+
43
+ /** 列表项内联动作:与卡级动作共用确认弹层语义,但不占整行。 */
44
+ function useInlineRunner(api: Api) {
45
+ const [pending, setPending] = useState<CardViewAction | null>(null);
46
+ const [running, setRunning] = useState(false);
47
+ const runningRef = useRef(false);
48
+ const wasGenerating = useRef(false);
49
+ useEffect(() => {
50
+ if (!running) return undefined;
51
+ const timer = setTimeout(() => {
52
+ runningRef.current = false;
53
+ setRunning(false);
54
+ }, 20000);
55
+ return () => clearTimeout(timer);
56
+ }, [running]);
57
+ useEffect(() => {
58
+ if (api.isGenerating) {
59
+ wasGenerating.current = true;
60
+ return;
61
+ }
62
+ if (!wasGenerating.current) return;
63
+ wasGenerating.current = false;
64
+ if (runningRef.current) {
65
+ runningRef.current = false;
66
+ setRunning(false);
67
+ }
68
+ }, [api.isGenerating]);
69
+ const run = (action: CardViewAction) => {
70
+ if (!action.invoke && !action.send) return;
71
+ runningRef.current = true;
72
+ setRunning(true);
73
+ if (action.invoke) {
74
+ api.invoke(action.invoke.id, action.invoke.input);
75
+ return;
76
+ }
77
+ if (action.send) {
78
+ if (typeof action.send === 'string') api.send(action.send);
79
+ else api.send(action.send.text, { displayText: action.send.displayText });
80
+ }
81
+ };
82
+ const trigger = (action: CardViewAction) => {
83
+ if (api.disabled || runningRef.current || pending !== null) return;
84
+ if (action.confirm) {
85
+ setPending(action);
86
+ return;
87
+ }
88
+ run(action);
89
+ };
90
+ const sheet =
91
+ pending && pending.confirm ? (
92
+ <ConfirmSheet
93
+ open
94
+ title={pending.confirm.title}
95
+ {...(pending.confirm.description ? { description: pending.confirm.description } : {})}
96
+ {...(pending.confirm.confirmText ? { confirmText: pending.confirm.confirmText } : {})}
97
+ {...(pending.confirm.cancelText ? { cancelText: pending.confirm.cancelText } : {})}
98
+ onConfirm={() => {
99
+ const action = pending;
100
+ setPending(null);
101
+ run(action);
102
+ }}
103
+ onCancel={() => setPending(null)}
104
+ />
105
+ ) : null;
106
+ return { trigger, sheet, busy: api.disabled || running || pending !== null };
107
+ }
108
+
109
+ function renderBlock(
110
+ block: CardViewBlock,
111
+ trigger: (action: CardViewAction) => void,
112
+ disabled: boolean,
113
+ ): ReactNode {
114
+ switch (block.kind) {
115
+ case 'hero':
116
+ return (
117
+ <Hero
118
+ {...(block.eyebrow ? { eyebrow: block.eyebrow } : {})}
119
+ title={block.title}
120
+ {...(block.value ? { value: block.value } : {})}
121
+ {...(block.unit ? { unit: block.unit } : {})}
122
+ {...(block.footnote ? { footnote: block.footnote } : {})}
123
+ {...(block.tone ? { tone: block.tone } : {})}
124
+ />
125
+ );
126
+ case 'facts':
127
+ return <KeyValueList items={block.items.map(([label, value]) => ({ label, value }))} />;
128
+ case 'bill':
129
+ return (
130
+ <Bill
131
+ lines={block.lines.map(([label, value, muted]) => ({ label, value, ...(muted ? { muted: true } : {}) }))}
132
+ {...(block.total ? { total: { label: block.total[0], value: block.total[1] } } : {})}
133
+ />
134
+ );
135
+ case 'notice':
136
+ return <Notice {...(block.tone ? { tone: block.tone } : {})}>{block.text}</Notice>;
137
+ case 'tags':
138
+ return <TagList tags={block.tags} {...(block.tone ? { tone: block.tone } : {})} />;
139
+ case 'steps':
140
+ return <Steps steps={block.steps} />;
141
+ case 'ticket':
142
+ return (
143
+ <Ticket
144
+ amount={block.amount}
145
+ {...(block.condition ? { condition: block.condition } : {})}
146
+ {...(block.meta ? { meta: block.meta } : {})}
147
+ {...(block.status ? { status: block.status } : {})}
148
+ {...(block.tone ? { tone: block.tone } : {})}
149
+ />
150
+ );
151
+ case 'timeline':
152
+ return (
153
+ <Timeline
154
+ items={block.items.map((item) => ({
155
+ label: item.label,
156
+ ...(item.amount ? { amount: item.amount } : {}),
157
+ ...(item.time ? { time: item.time } : {}),
158
+ ...(item.tone ? { tone: item.tone } : {}),
159
+ }))}
160
+ />
161
+ );
162
+ case 'empty':
163
+ return <EmptyState title={block.title} {...(block.description ? { description: block.description } : {})} />;
164
+ case 'list':
165
+ return (
166
+ <div className="tbox-view-list flex flex-col gap-2.5">
167
+ {block.items.map((item, index) => (
168
+ <EntityRow
169
+ key={item.title + '-' + index}
170
+ title={item.title}
171
+ {...(item.meta ? { meta: item.meta } : {})}
172
+ {...(item.price ? { price: item.price } : {})}
173
+ {...(item.description ? { description: item.description } : {})}
174
+ {...(item.tags && item.tags.length > 0 ? { tags: <TagList tags={item.tags} /> } : {})}
175
+ {...(item.action
176
+ ? {
177
+ action: (
178
+ <CardButton
179
+ variant={item.action.style === 'primary' ? 'primary' : 'secondary'}
180
+ disabled={disabled}
181
+ onClick={() => trigger(item.action as CardViewAction)}
182
+ >
183
+ {item.action.label}
184
+ </CardButton>
185
+ ),
186
+ }
187
+ : {})}
188
+ />
189
+ ))}
190
+ </div>
191
+ );
192
+ default: {
193
+ const unknown = block as { kind?: string };
194
+ console.warn('[ViewCard] 未知积木,已跳过:' + String(unknown.kind));
195
+ return null;
196
+ }
197
+ }
198
+ }
199
+
200
+ export function ViewCard({
201
+ view,
202
+ cardId,
203
+ isHistory,
204
+ actionTokens,
205
+ }: {
206
+ view: CardView;
207
+ cardId: string;
208
+ isHistory?: boolean;
209
+ actionTokens?: Record<string, string>;
210
+ }) {
211
+ let safeView: CardView;
212
+ try {
213
+ safeView = normalizeCardView(view);
214
+ } catch {
215
+ return (
216
+ <Card>
217
+ <Notice tone="error">卡片数据不可用,请重新触发一次</Notice>
218
+ </Card>
219
+ );
220
+ }
221
+ const api = useCardActions({
222
+ cardId,
223
+ isHistory: isHistory === true,
224
+ ...(actionTokens ? { actionTokens } : {}),
225
+ });
226
+ const inline = useInlineRunner(api);
227
+ return (
228
+ <Card>
229
+ <CardHeader
230
+ title={safeView.header.title}
231
+ {...(safeView.header.eyebrow ? { eyebrow: safeView.header.eyebrow } : {})}
232
+ {...(safeView.header.status
233
+ ? { status: <StatusTag tone={safeView.header.status.tone ?? 'neutral'}>{safeView.header.status.text}</StatusTag> }
234
+ : {})}
235
+ />
236
+ {safeView.blocks.map((block, index) => (
237
+ <div key={block.kind + '-' + index}>{renderBlock(block, inline.trigger, inline.busy)}</div>
238
+ ))}
239
+ {safeView.actions && safeView.actions.length > 0 ? (
240
+ <ActionList api={api} actions={safeView.actions.map(toSpec)} />
241
+ ) : null}
242
+ {inline.sheet}
243
+ </Card>
244
+ );
245
+ }
@@ -208,7 +208,7 @@ export function ChatInput({
208
208
  />
209
209
  ) : (
210
210
  <textarea
211
- className="tbox-chat-input__field min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
211
+ className="tbox-chat-input__field min-h-11 min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
212
212
  value={text}
213
213
  placeholder={blocked?.message ?? '有什么需要问我的吗'}
214
214
  rows={1}
@@ -29,11 +29,11 @@ export default function HistoryEntry({
29
29
  <div className="history-entry flex justify-center p-0">
30
30
  <button
31
31
  type="button"
32
- className="history-entry__button inline-flex appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-[rgba(15,64,113,0.06)] px-3 py-[3px] text-xs font-normal leading-[16px] text-muted-foreground transition-[background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(15,64,113,0.1)] disabled:cursor-default"
32
+ className="history-entry__button inline-flex min-h-11 appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-muted px-4 py-1 text-sm font-normal leading-[18px] text-muted-foreground transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-border disabled:cursor-default"
33
33
  disabled={disabled}
34
34
  onClick={onLoad}
35
35
  >
36
- {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-[rgba(15,64,113,0.18)] border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
36
+ {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-border border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
37
  {labelOf(pullStatus, loading)}
38
38
  </button>
39
39
  </div>
@@ -27,7 +27,9 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
27
27
  const sendMessage = useChatStore((s) => s.sendMessage);
28
28
  const generating = useChatStore((s) => s.isGenerating);
29
29
  const isUser = message.role === 'user';
30
- const roleName = isUser ? '你' : 'AI 助手';
30
+ // 发送者名取应用身份(chat.json identity.name),没有配置才回落通用名。
31
+ const identity = useChatConfigStore((s) => s.identity);
32
+ const roleName = isUser ? '你' : (identity?.name ?? 'AI 助手');
31
33
  const timeLabel = new Date(message.createdAt).toLocaleTimeString('zh-CN', {
32
34
  hour: '2-digit',
33
35
  minute: '2-digit',
@@ -70,7 +72,11 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
70
72
  }
71
73
 
72
74
  return (
73
- <div className={`msg-row mb-2.5 flex items-start px-page ${isUser ? 'msg-row--user flex-row-reverse' : 'msg-row--bot flex-row'}`}>
75
+ <div
76
+ className={`msg-row mb-2.5 flex items-start px-page ${isUser ? 'msg-row--user flex-row-reverse' : 'msg-row--bot flex-row'}`}
77
+ data-message-id={message.id}
78
+ data-message-role={message.role}
79
+ >
74
80
  <div className={isUser ? 'msg-main min-w-0' : 'msg-main min-w-0 flex-1'}>
75
81
  <div
76
82
  className={`msg-meta flex items-center ${isUser ? 'msg-meta--user justify-end' : 'msg-meta--bot justify-start'} ${!showBubble && messageCards.length > 0 ? 'msg-meta--solo-card mb-1.5' : 'mb-[3px]'}`}
@@ -104,17 +110,17 @@ export function MessageBubble({ message }: { message: ChatMessage }) {
104
110
  className={`msg-bubble leading-[1.6] ${isUser ? 'msg-bubble--user mb-1 ml-auto mr-0 flex min-h-6 w-fit max-w-full items-center rounded-[24px_4px_24px_24px] bg-[rgba(255,255,255,0.9)] px-[11px] py-[9px] shadow-[0_2px_8px_rgba(50,65,92,0.08)]' : 'msg-bubble--bot relative mb-1.5 rounded-[4px_24px_24px] border-[0.5px] border-[#edf0f6] bg-[rgba(255,255,255,0.4)] p-[11px] text-base text-foreground shadow-[0_1.5px_4px_2.5px_rgba(1,112,254,0.0392),0_1px_2px_rgba(72,78,86,0.0706)]'}`}
105
111
  >
106
112
  {isUser ? (
107
- <span className="msg-bubble__text text-xs leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
113
+ <span className="msg-bubble__text text-base leading-[1.6] font-medium text-foreground [overflow-wrap:break-word]">{message.content}</span>
108
114
  ) : (
109
115
  <>
110
116
  {message.content && (
111
- <div className="msg-markdown text-xs leading-[1.6] text-foreground [overflow-wrap:anywhere] [&_h1]:mt-2! [&_h1]:mb-1! [&_h1]:text-lg [&_h1]:font-semibold [&_h1]:leading-[1.4] [&_h2]:mt-2! [&_h2]:mb-1! [&_h2]:text-base [&_h2]:font-semibold [&_h2]:leading-[1.4] [&_h3]:mt-2! [&_h3]:mb-1! [&_h3]:text-base [&_h3]:font-semibold [&_h3]:leading-[1.4] [&_h4]:mt-2! [&_h4]:mb-1! [&_h4]:text-sm [&_h4]:font-semibold [&_h4]:leading-[1.4] [&_h5]:mt-2! [&_h5]:mb-1! [&_h5]:font-semibold [&_h5]:leading-[1.4] [&_h6]:mt-2! [&_h6]:mb-1! [&_h6]:font-semibold [&_h6]:leading-[1.4] [&_p]:my-1! [&_strong]:font-semibold [&_em]:italic [&_a]:text-primary [&_a]:underline [&_ul]:my-1! [&_ul]:pl-4 [&_ol]:my-1! [&_ol]:pl-4 [&_li]:my-0.5 [&_blockquote]:my-1.5 [&_blockquote]:border-l-2 [&_blockquote]:border-l-[#667eea] [&_blockquote]:pl-2 [&_blockquote]:text-secondary-foreground [&_code]:rounded-[3px] [&_code]:bg-[rgba(0,0,0,0.06)] [&_code]:px-1 [&_code]:py-[1px] [&_code]:text-sm [&_code]:leading-[1.6] [&_code]:font-mono [&_pre]:my-1.5 [&_pre]:overflow-x-auto [&_pre]:rounded-[6px] [&_pre]:bg-[#1e1e2e] [&_pre]:p-2.5 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-xs [&_pre_code]:leading-[1.6] [&_pre_code]:text-[#cdd6f4] [&_table]:my-1.5 [&_table]:w-full [&_table]:border-collapse [&_th]:border-[0.5px] [&_th]:border-border [&_th]:bg-muted [&_th]:px-1.5 [&_th]:py-1 [&_th]:text-left [&_th]:text-sm [&_th]:leading-[1.6] [&_th]:font-semibold [&_td]:border-[0.5px] [&_td]:border-border [&_td]:px-1.5 [&_td]:py-1 [&_td]:text-left [&_td]:text-sm [&_td]:leading-[1.6]">
117
+ <div className="msg-markdown text-base leading-[1.6] text-foreground [overflow-wrap:anywhere] [&_h1]:mt-2! [&_h1]:mb-1! [&_h1]:text-lg [&_h1]:font-semibold [&_h1]:leading-[1.4] [&_h2]:mt-2! [&_h2]:mb-1! [&_h2]:text-base [&_h2]:font-semibold [&_h2]:leading-[1.4] [&_h3]:mt-2! [&_h3]:mb-1! [&_h3]:text-base [&_h3]:font-semibold [&_h3]:leading-[1.4] [&_h4]:mt-2! [&_h4]:mb-1! [&_h4]:text-sm [&_h4]:font-semibold [&_h4]:leading-[1.4] [&_h5]:mt-2! [&_h5]:mb-1! [&_h5]:font-semibold [&_h5]:leading-[1.4] [&_h6]:mt-2! [&_h6]:mb-1! [&_h6]:font-semibold [&_h6]:leading-[1.4] [&_p]:my-1! [&_strong]:font-semibold [&_em]:italic [&_a]:text-primary [&_a]:underline [&_ul]:my-1! [&_ul]:pl-4 [&_ol]:my-1! [&_ol]:pl-4 [&_li]:my-0.5 [&_blockquote]:my-1.5 [&_blockquote]:border-l-2 [&_blockquote]:border-l-primary [&_blockquote]:pl-2 [&_blockquote]:text-secondary-foreground [&_code]:rounded-[3px] [&_code]:bg-[rgba(0,0,0,0.06)] [&_code]:px-1 [&_code]:py-[1px] [&_code]:text-sm [&_code]:leading-[1.6] [&_code]:font-mono [&_pre]:my-1.5 [&_pre]:overflow-x-auto [&_pre]:rounded-[6px] [&_pre]:bg-[#1e1e2e] [&_pre]:p-2.5 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-xs [&_pre_code]:leading-[1.6] [&_pre_code]:text-[#cdd6f4] [&_table]:my-1.5 [&_table]:w-full [&_table]:border-collapse [&_th]:border-[0.5px] [&_th]:border-border [&_th]:bg-muted [&_th]:px-1.5 [&_th]:py-1 [&_th]:text-left [&_th]:text-sm [&_th]:leading-[1.6] [&_th]:font-semibold [&_td]:border-[0.5px] [&_td]:border-border [&_td]:px-1.5 [&_td]:py-1 [&_td]:text-left [&_td]:text-sm [&_td]:leading-[1.6]">
112
118
  <ReactMarkdown remarkPlugins={[remarkGfm]}>{message.content}</ReactMarkdown>
113
119
  </div>
114
120
  )}
115
121
  {message.error && (
116
122
  <div
117
- className={`msg-bubble__error whitespace-pre-wrap text-xs leading-[1.6] text-destructive [overflow-wrap:anywhere] ${message.content ? 'msg-bubble__error--with-content mt-[7px] border-t-[0.5px] border-t-destructive pt-[7px]' : ''}`}
123
+ className={`msg-bubble__error whitespace-pre-wrap text-sm leading-[1.6] text-destructive [overflow-wrap:anywhere] ${message.content ? 'msg-bubble__error--with-content mt-[7px] border-t-[0.5px] border-t-destructive pt-[7px]' : ''}`}
118
124
  role="alert"
119
125
  >
120
126
  {message.error}
@@ -76,7 +76,9 @@ describe('QuickCommands 快捷胶囊', () => {
76
76
  const buttons = [...container.querySelectorAll<HTMLButtonElement>('.quick-commands__item')];
77
77
  expect(buttons.map((button) => button.textContent)).toEqual(['今日优惠', '品牌导览', '活动中心']);
78
78
  expect(container.textContent).not.toContain('找门店');
79
- expect(buttons[1]?.querySelector('img')?.src).toContain('6-OCR5kWFa');
79
+ // 图标走 CSS mask + currentColor(换品牌色不再残留固定蓝),断言 mask 的图片地址。
80
+ const iconUrl = buttons[1]?.querySelector<HTMLElement>('.quick-commands__icon')?.getAttribute('data-icon') ?? '';
81
+ expect(iconUrl).toContain('6-OCR5kWFa');
80
82
  flushSync(() => buttons[1]!.click());
81
83
  expect(onCommand).toHaveBeenCalledWith('服务端品牌导览');
82
84
  });
@@ -1,6 +1,9 @@
1
1
  // 输入框上方的快捷指令;文案由 chatConfig 驱动,服务端下发不含 icon 时按 label 合并本地配置。
2
2
  // 011 I2:服务端 HelloAck.chatConfig.quickCommands 优先(单一真源),本地 chat.json 为 fallback。
3
3
  // label 只写纯文字;前面的星标由本组件渲染(icon 字段或默认 ✦),不要把 ✦/emoji 写进 label。
4
+ //
5
+ // 两种排布:空会话用 grid(两列、全可见、每个 44px 命中区),对话态用 row(底部单行、可横滚)。
6
+ // 颜色只用语义令牌:换品牌色后不残留固定蓝。
4
7
  import { useChatConfigStore } from '../../chat-config';
5
8
  import { useChatStore } from '../../store-context';
6
9
  import starIcon from '../../../assets/quick-command-star.svg';
@@ -8,9 +11,11 @@ import starIcon from '../../../assets/quick-command-star.svg';
8
11
  export function QuickCommands({
9
12
  onCommand,
10
13
  hidden = false,
14
+ variant = 'row',
11
15
  }: {
12
16
  onCommand: (query: string) => void;
13
17
  hidden?: boolean;
18
+ variant?: 'row' | 'grid';
14
19
  }) {
15
20
  const staticCommands = useChatConfigStore((s) => s.quickCommands);
16
21
  // chatConfig 可选链:旧 server 的 HELLO_ACK 可能不带该段(与「ack 缺席回落静态」同语义)
@@ -26,25 +31,43 @@ export function QuickCommands({
26
31
  : staticCommands;
27
32
  if (!commands.length) return null;
28
33
 
34
+ const grid = variant === 'grid';
29
35
  return (
30
36
  <div
31
- className={`quick-commands relative z-[1] mx-auto flex w-full max-w-content gap-2 overflow-x-auto px-page pb-[9px] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`}
37
+ className={
38
+ grid
39
+ ? `quick-commands quick-commands--grid relative z-[1] mx-auto grid w-full max-w-content grid-cols-2 gap-2 px-page ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`
40
+ : `quick-commands relative z-[1] mx-auto flex w-full max-w-content gap-2 overflow-x-auto px-page pb-[9px] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`
41
+ }
32
42
  aria-hidden={hidden || undefined}
33
43
  >
34
44
  {commands.map((cmd) => (
35
45
  <button
36
46
  key={cmd.label}
37
- className="quick-commands__item inline-flex h-[34px] flex-[1_0_auto] appearance-none items-center justify-center gap-[5px] rounded-[25px] border border-[rgba(15,64,113,0.14)] bg-[rgba(255,255,255,0.92)] px-[13px] py-0 shadow-[0_4px_16px_rgba(38,59,92,0.05)] transition-[background,border-color] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:border-primary"
47
+ className={
48
+ grid
49
+ ? 'quick-commands__item inline-flex min-h-11 w-full appearance-none items-center justify-start gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 text-left text-foreground shadow-sm transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] active:border-primary'
50
+ : 'quick-commands__item inline-flex min-h-11 flex-[1_0_auto] appearance-none items-center justify-center gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 text-foreground shadow-sm transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] active:border-primary'
51
+ }
38
52
  disabled={hidden}
39
53
  onClick={() => onCommand(cmd.query)}
40
54
  >
41
- <img
42
- className="quick-commands__icon size-4 object-contain"
43
- src={cmd.icon ?? starIcon}
44
- alt=""
45
- onError={(event) => { event.currentTarget.src = starIcon; }}
55
+ <span
56
+ className="quick-commands__icon size-4 shrink-0 bg-primary"
57
+ aria-hidden="true"
58
+ data-icon={cmd.icon ?? starIcon}
59
+ style={{
60
+ maskImage: `url(${cmd.icon ?? starIcon})`,
61
+ WebkitMaskImage: `url(${cmd.icon ?? starIcon})`,
62
+ maskSize: 'contain',
63
+ WebkitMaskSize: 'contain',
64
+ maskRepeat: 'no-repeat',
65
+ WebkitMaskRepeat: 'no-repeat',
66
+ maskPosition: 'center',
67
+ WebkitMaskPosition: 'center',
68
+ }}
46
69
  />
47
- <span className="quick-commands__label whitespace-nowrap text-sm font-medium leading-[18px] text-foreground">{cmd.label}</span>
70
+ <span className={`quick-commands__label text-sm font-medium leading-[18px] text-foreground ${grid ? 'line-clamp-2 text-left' : 'whitespace-nowrap'}`}>{cmd.label}</span>
48
71
  </button>
49
72
  ))}
50
73
  </div>
package/src/index.ts CHANGED
@@ -21,6 +21,9 @@ export {
21
21
  useClientSlots,
22
22
  } from './store-context';
23
23
  export type { KitChatContextValue } from './store-context';
24
+ export { KitPreviewProvider, createPreviewStore } from './preview-provider';
25
+ export { createSurfaceHarness } from './surface';
26
+ export type { SurfaceHarness, SurfaceHarnessOptions } from './surface';
24
27
 
25
28
  // ── chat 设置(构建期快照 + HELLO_ACK 水合) ──
26
29
  export { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
@@ -38,6 +41,7 @@ export { CardRenderer, RawCardRenderer } from './components/CardRenderer';
38
41
 
39
42
  // ── 应用级卡片工厂与卡片内交互 ──
40
43
  export { defineCard } from './card/define-card';
44
+ export { ViewCard } from './card/view-card';
41
45
  export type { CardRenderProps, DefinedCard } from './card/define-card';
42
46
  export { useCardActions } from './card/use-card-actions';
43
47
  export type { CardActions, UseCardActionsOptions } from './card/use-card-actions';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * KitPreviewProvider:卡片预览面的最小装配根。
3
+ *
4
+ * 预览页直接渲染 SDK CardRenderer,没有应用 store——kit 卡片的 `useCardActions`
5
+ * 会因「KitChatProvider 缺席」抛错(预览 7/7 全红)。这里给一个只读预览 store:
6
+ * 动作写通道是空实现(预览页自己的动作通道另经 bindCardActionChannel 接管),
7
+ * 卡片能渲染、按钮能显示、历史/禁用态照常。
8
+ *
9
+ * 应用接线:app.config.ts 的 `wrapPreview` 返回 `createElement(KitPreviewProvider, null, node)`。
10
+ */
11
+ import { useMemo, type ReactNode } from 'react';
12
+ import { useStore } from 'zustand';
13
+ import { createStore } from 'zustand/vanilla';
14
+ import type { CardComponent } from '@tbox.cn/app-contracts';
15
+ import type { CoreChatState, CoreChatStore } from '@tbox.cn/app-agent-sdk-client';
16
+ import { KitChatProvider } from './store-context';
17
+
18
+ /** 预览用 store:只满足壳与卡片的读取(sendUiAction 空实现、不在生成中)。 */
19
+ export function createPreviewStore(state: Partial<CoreChatState> = {}): CoreChatStore {
20
+ const vanilla = createStore<CoreChatState>(() => ({
21
+ sendUiAction: () => {},
22
+ isGenerating: false,
23
+ ...state,
24
+ } as unknown as CoreChatState));
25
+ const hook = ((selector: (state: CoreChatState) => unknown) =>
26
+ useStore(vanilla, selector)) as unknown as CoreChatStore;
27
+ hook.getState = vanilla.getState;
28
+ hook.setState = vanilla.setState;
29
+ hook.subscribe = vanilla.subscribe;
30
+ return hook;
31
+ }
32
+
33
+ export function KitPreviewProvider({
34
+ cards = {},
35
+ children,
36
+ }: {
37
+ /** 预览页的卡片注册表(缺省空表;动作由预览页接管) */
38
+ cards?: Record<string, CardComponent>;
39
+ children: ReactNode;
40
+ }) {
41
+ const store = useMemo(() => createPreviewStore(), []);
42
+ return (
43
+ <KitChatProvider store={store} cards={cards} rawCards={cards}>
44
+ {children}
45
+ </KitChatProvider>
46
+ );
47
+ }
@@ -0,0 +1,35 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createElement } from 'react';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
4
+ import { Card, CardButton, CardHeader, defineCard, useCardActions } from './index';
5
+ import { createSurfaceHarness } from './surface';
6
+
7
+ /** 一张用 kit 动作的卡:没有 provider 会抛「KitChatProvider 缺席」。 */
8
+ const DemoCard = defineCard({ type: 'demo-card' }, ({ data, cardId, isHistory }) => {
9
+ const api = useCardActions({ cardId, isHistory });
10
+ return (
11
+ <Card>
12
+ <CardHeader title={String((data as { title: string }).title)} />
13
+ <CardButton onClick={() => api.send('继续')}>继续</CardButton>
14
+ </Card>
15
+ );
16
+ });
17
+
18
+ describe('createSurfaceHarness', () => {
19
+ it('给出与运行时同形的 provider,kit 卡片可直接渲染', () => {
20
+ const harness = createSurfaceHarness({ cards: { 'demo-card': DemoCard } });
21
+ const html = renderToStaticMarkup(
22
+ harness.wrap(createElement(DemoCard, { data: { title: '停车订单' }, cardId: 'c1', isHistory: false })),
23
+ );
24
+ expect(html).toContain('停车订单');
25
+ expect(html).toContain('继续');
26
+ });
27
+
28
+ it('历史态可渲染且动作禁用', () => {
29
+ const harness = createSurfaceHarness({ cards: { 'demo-card': DemoCard } });
30
+ const html = renderToStaticMarkup(
31
+ harness.wrap(createElement(DemoCard, { data: { title: '停车订单' }, cardId: 'c1', isHistory: true })),
32
+ );
33
+ expect(html).toContain('disabled');
34
+ });
35
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * SurfaceHarness:卡片/聊天表面的唯一装配入口。
3
+ *
4
+ * 证据(check:fast)、截图(card render)、预览页都要渲染真实组件——但每个入口都手搭
5
+ * provider 栈,就会出现「预览崩、证据过、运行时坏」的分裂。这里把 store + provider 收成
6
+ * 一个工厂:看到的就是运行时看到的。
7
+ *
8
+ * 用法:
9
+ * const harness = createSurfaceHarness({ cards, state });
10
+ * renderToStaticMarkup(harness.wrap(<MyCard ... />));
11
+ */
12
+ import type { ReactNode } from 'react';
13
+ import type { CardComponent } from '@tbox.cn/app-contracts';
14
+ import type { ClientSlotRegistry, CoreChatState } from '@tbox.cn/app-agent-sdk-client';
15
+ import { KitChatProvider } from './store-context';
16
+ import { createPreviewStore } from './preview-provider';
17
+
18
+ export interface SurfaceHarnessOptions {
19
+ /** cards = 组合层注册表(含覆盖);rawCards 缺省同 cards。 */
20
+ cards?: Record<string, CardComponent>;
21
+ rawCards?: Record<string, CardComponent>;
22
+ /** 客户端槽(home);缺省无。 */
23
+ slots?: ClientSlotRegistry;
24
+ /** store 初值覆盖(如 isGenerating / 历史态)。 */
25
+ state?: Partial<CoreChatState>;
26
+ }
27
+
28
+ export interface SurfaceHarness {
29
+ store: ReturnType<typeof createPreviewStore>;
30
+ /** 把一个元素包进与运行时同形的 provider 树。 */
31
+ wrap: (node: ReactNode) => ReactNode;
32
+ }
33
+
34
+ export function createSurfaceHarness(options: SurfaceHarnessOptions = {}): SurfaceHarness {
35
+ const cards = options.cards ?? {};
36
+ const rawCards = options.rawCards ?? cards;
37
+ const store = createPreviewStore(options.state);
38
+ const wrap = (node: ReactNode): ReactNode => (
39
+ <KitChatProvider store={store} cards={cards} rawCards={rawCards} {...(options.slots ? { slots: options.slots } : {})}>
40
+ {node}
41
+ </KitChatProvider>
42
+ );
43
+ return { store, wrap };
44
+ }
@@ -45,7 +45,7 @@
45
45
  - 间距:卡片与上下元素(工具调用 / 气泡)的间距,与 .tool-calls 一致;
46
46
  - 外观:默认背景(白) / 1px 边框 / 圆角 / 阴影;`overflow:hidden` 把内容裁进圆角;
47
47
  - 入场动效:mount 即播(0.36s 上浮淡入,对齐 mall-vis 消息卡节奏)。
48
- 值为物理 px(大写 PX,不再经 pxtorem 折半):圆角 var(--tbox-radius-lg)=24、边框 1、阴影 var(--tbox-shadow-sm)=0 4 13。
48
+ 值为物理 px(大写 PX):圆角 var(--tbox-radius-lg)=24、边框 1、阴影 var(--tbox-shadow-sm)=0 4 13。
49
49
  ⚠️ **内边距不在卡框里**——由卡片自己写。卡框给 padding 会让「自带背景色的卡」在外面露一圈白边(卡里套卡)。
50
50
  宽度也不在卡框里:默认占满整列(≈移动端 350~400px 设计宽),紧凑卡自己写 max-width。
51
51
  单卡组件(.tbox-<type>)只画内容;**要整卡换底色 / 出血图,直接在自己 root 上 `background:<色>` 或铺满图**——
@@ -104,6 +104,14 @@
104
104
  --adm-z-index-mask: 1200;
105
105
  }
106
106
 
107
+ /* 表单控件继承排版:模板不引 preflight,原生 button/input 否则落到浏览器默认 13.33px(越档字号)。
108
+ 作用域限定在壳与卡片内,工具类仍可覆写。 */
109
+ :where(.tbox-app, .chat-page, .tbox-card) :where(button, input, textarea, select) {
110
+ font: inherit;
111
+ color: inherit;
112
+ letter-spacing: inherit;
113
+ }
114
+
107
115
  /* 基元/模块迁移后不再各自写 margin reset:标题、段落、列表统一归零(在 base 层,工具类可覆写)。 */
108
116
  h1, h2, h3, h4, h5, h6, p, dl, dd, dt, ul, ol {
109
117
  margin: 0;
@@ -120,13 +128,3 @@
120
128
  -webkit-touch-callout: none !important;
121
129
  -webkit-user-drag: none !important;
122
130
  }
123
-
124
- /* 顶部历史入口在场时欢迎区不再叠加自身顶部留白(壳的跨组件规则)。 */
125
- .history-entry ~ .mall-home {
126
- padding-top: 0;
127
- }
128
-
129
- /* 顶部历史入口在场时商圈主屏不再叠加自身顶部留白(ChatPage 槽位包裹层)。 */
130
- .history-entry ~ .chat-page__home-slot .mall-home {
131
- padding-top: 0;
132
- }
@@ -1,5 +1,5 @@
1
1
  {
2
- "$comment": "主题可覆写变量封闭清单(主题轨 W-T2;doctor theme-package-structure 消费——超集即 error;theme-contract.test.ts 锁 tokens.css+motion.css 的平台键 ⊆ platform 段)。domains 段 = 域色两段式通道(identity/surface/border 三角色,v1 封闭;promotion 按域色矩阵无描边列)。assets 段 = 素材变量链语义位(W-T3 铺开,铺开后逐一核对)。",
2
+ "$comment": "主题可覆写变量封闭清单(主题轨 W-T2;doctor theme-package-structure 消费——超集即 error;theme-contract.test.ts 锁 tokens.css+motion.css 的平台键 ⊆ platform 段)。domains 段 = 域色两段式通道(identity/surface/border 三角色,v1 封闭;promotion 按域色矩阵无描边列)。assets 段 = 素材变量链语义位(W-T3 铺开,铺开后逐一核对)。 pairs 段 = 对比度对账清单(fg/bg 都是 platform 键;min 为 WCAG 阈值;color-mix 派生的由浏览器车道补验)。",
3
3
  "platform": [
4
4
  "--tbox-accent",
5
5
  "--tbox-accent-light",
@@ -68,5 +68,49 @@
68
68
  "--tbox-asset-promotion-activity-header",
69
69
  "--tbox-asset-promotion-coupon-header",
70
70
  "--tbox-asset-sg-header"
71
+ ],
72
+ "pairs": [
73
+ {
74
+ "fg": "--tbox-text-primary",
75
+ "bg": "--tbox-bg-card",
76
+ "min": 4.5,
77
+ "usage": "正文"
78
+ },
79
+ {
80
+ "fg": "--tbox-text-primary",
81
+ "bg": "--tbox-bg-page",
82
+ "min": 4.5,
83
+ "usage": "正文"
84
+ },
85
+ {
86
+ "fg": "--tbox-text-secondary",
87
+ "bg": "--tbox-bg-card",
88
+ "min": 4.5,
89
+ "usage": "次要文字"
90
+ },
91
+ {
92
+ "fg": "--tbox-text-secondary",
93
+ "bg": "--tbox-bg-page",
94
+ "min": 4.5,
95
+ "usage": "次要文字"
96
+ },
97
+ {
98
+ "fg": "--tbox-text-muted",
99
+ "bg": "--tbox-bg-card",
100
+ "min": 4.5,
101
+ "usage": "说明文字"
102
+ },
103
+ {
104
+ "fg": "--tbox-text-muted",
105
+ "bg": "--tbox-bg-page",
106
+ "min": 4.5,
107
+ "usage": "说明文字"
108
+ },
109
+ {
110
+ "fg": "--tbox-primary",
111
+ "bg": "--tbox-bg-card",
112
+ "min": 4.5,
113
+ "usage": "链接与主色文字"
114
+ }
71
115
  ]
72
116
  }