@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-agent-ui-kit",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.8",
4
4
  "type": "module",
5
5
  "description": "Agent 对话壳 UI 组件包(源码发布,单一模板统一化 W2-1):ChatPage/壳组件族/主题 tokens。",
6
6
  "exports": {
@@ -32,8 +32,8 @@
32
32
  "react-markdown": "9.1.0",
33
33
  "remark-gfm": "4.0.1",
34
34
  "zustand": "4.5.7",
35
- "@tbox.cn/app-contracts": "1.0.0-alpha.7",
36
- "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.7"
35
+ "@tbox.cn/app-contracts": "1.0.0-alpha.8",
36
+ "@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.8"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "react": "18.3.1",
package/src/ChatPage.tsx CHANGED
@@ -206,7 +206,9 @@ function ChatPageInner() {
206
206
  && messages.length === 0
207
207
  && inlineOrphanCards.length === 0;
208
208
  const welcomeTitle = welcome?.title ?? identity?.name ?? '开始对话';
209
- const welcomeSubtitle = welcome?.subtitle ?? identity?.tagline;
209
+ const welcomeSubtitle = welcome?.subtitle ?? identity?.tagline ?? '可以直接提问,也可以从下面的问题开始';
210
+ // 空会话(有 home 槽或无 home 槽)走同一套构图:欢迎区 + 快捷问题成组居中。
211
+ const isEmptyState = showHome || showWelcome;
210
212
 
211
213
  const pull = usePullDownHistory({
212
214
  isAtTopRef,
@@ -240,19 +242,33 @@ function ChatPageInner() {
240
242
  return () => ro.disconnect();
241
243
  }, []);
242
244
 
243
- // 仅在已有对话内容且贴近底部时自动滚动,避免打断用户上翻查看历史。
244
- // 依赖含 cardsByMessageId:主卡在文字完成后挂载、消息行增高,需补滚避免卡片截出视口
245
+ // 回合锚定:新回合把本轮用户消息置顶,流式期间不追底。
246
+ // 贴底滚动会把问题顶出视口(实测卡片 648px 时问题上移 244px),用户看不到自己在问什么。
247
+ const turnAnchorRef = useRef<string | null>(null);
245
248
  useEffect(() => {
246
- const hasLiveContent = messages.length > 0 || orphanCards.length > 0;
247
- if (hasLiveContent && isNearBottomRef.current) {
248
- const el = bodyRef.current;
249
- if (el) el.scrollTop = el.scrollHeight;
250
- }
251
- }, [messages, orphanCards, liveCardSignature]);
249
+ const lastUser = [...messages].reverse().find((message) => message.role === 'user');
250
+ if (!lastUser || turnAnchorRef.current === lastUser.id) return;
251
+ turnAnchorRef.current = lastUser.id;
252
+ const body = bodyRef.current;
253
+ const element = body?.querySelector(`[data-message-id="${lastUser.id}"]`);
254
+ if (!body || !element) return;
255
+ const delta = element.getBoundingClientRect().top - body.getBoundingClientRect().top;
256
+ body.scrollTop += delta - 8;
257
+ isNearBottomRef.current = false;
258
+ }, [messages]);
259
+
260
+ // 没有新回合、但卡片在文字之后挂载时,内容会继续变高:只在用户本来就在底部时补滚,
261
+ // 且不改变「本轮问题已在视口内」的锚点。
262
+ useEffect(() => {
263
+ if (!isNearBottomRef.current) return;
264
+ const el = bodyRef.current;
265
+ if (el && messages.length === 0 && orphanCards.length > 0) el.scrollTop = el.scrollHeight;
266
+ }, [orphanCards, liveCardSignature, messages.length]);
252
267
 
253
268
  return (
254
269
  <div className={`chat-page relative flex h-full w-full min-h-0 flex-col overflow-hidden bg-background ${showHome ? '' : ' chat-page--conversation'}`}>
255
- <div className="chat-page__bg pointer-events-none absolute inset-0 z-0 bg-background" />
270
+ {/* 整页背景独立于滚动内容,覆盖历史入口、首页与底部输入区;图片按视口居中铺满、不重复。 */}
271
+ <div className="chat-page__bg pointer-events-none absolute inset-0 z-0 bg-background bg-center bg-cover bg-no-repeat" />
256
272
 
257
273
  {brandName ? (
258
274
  <div className="chat-page__brand relative z-10 flex items-baseline justify-center gap-3 border-b border-border bg-background px-page pb-3 pt-[calc(16px+env(safe-area-inset-top))]" aria-label={brandName}>
@@ -263,7 +279,7 @@ function ChatPageInner() {
263
279
 
264
280
  <div className="chat-page__body-wrapper relative z-10 flex min-h-0 flex-1 flex-col">
265
281
  <div
266
- className="chat-page__body mx-auto w-full max-w-content flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain pb-6 pt-[calc(12px+env(safe-area-inset-top))] [overflow-anchor:none] [scrollbar-width:none] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden"
282
+ className={`chat-page__body mx-auto w-full max-w-content flex-1 min-h-0 overflow-y-auto overflow-x-hidden overscroll-contain pb-6 pt-[calc(12px+env(safe-area-inset-top))] [overflow-anchor:none] [scrollbar-width:none] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden ${isEmptyState ? 'flex flex-col justify-center' : ''}`}
267
283
  ref={bodyRef}
268
284
  onScroll={onScroll}
269
285
  onWheel={pull.handleWheel}
@@ -288,17 +304,25 @@ function ChatPageInner() {
288
304
 
289
305
  {/* 空会话欢迎区:没有 home 槽时的首屏落点(文案来自 chat.json welcome / identity) */}
290
306
  {showWelcome ? (
291
- <div className="chat-page__welcome flex flex-col items-center justify-center gap-2 px-page pb-5 pt-15 text-center">
307
+ <div className="chat-page__welcome flex flex-col items-center justify-center gap-2 px-page pb-4 pt-6 text-center">
292
308
  <h2 className="chat-page__welcome-title m-0 text-xl font-bold text-foreground">{welcomeTitle}</h2>
293
309
  {welcomeSubtitle ? <p className="chat-page__welcome-subtitle m-0 text-sm leading-normal text-muted-foreground">{welcomeSubtitle}</p> : null}
294
310
  </div>
295
311
  ) : null}
296
312
 
297
- {/* 历史前插视口锚 + home 槽渲染位(域自持显隐;缺席则不渲染) */}
298
- <div className="chat-page__home-slot" ref={historyAnchorRef}>
313
+ {/* 历史前插视口锚 + home 槽渲染位(域自持显隐;缺席则不渲染)。flow-root 让首页子元素
314
+ 的外边距留在槽内,不折叠到历史入口与首页之间。 */}
315
+ <div className="chat-page__home-slot flow-root" ref={historyAnchorRef}>
299
316
  {homeSlot?.({ onSend: send, ...(mallName ? { mallName } : {}) })}
300
317
  </div>
301
318
 
319
+ {/* 空会话的服务入口:快捷问题与欢迎区成组居中,两列全可见(不再贴底单行溢出)。 */}
320
+ {!blocked && isEmptyState ? (
321
+ <div className="chat-page__home-actions mt-6 flex w-full flex-col items-center">
322
+ <QuickCommands variant="grid" hidden={voiceActive} onCommand={send} />
323
+ </div>
324
+ ) : null}
325
+
302
326
  {/* 业务旁路 emit 的卡片(如欢迎卡) */}
303
327
  {inlineOrphanCards.map((card) => (
304
328
  <div key={card.id} className="chat-page__orphan-card mx-page">
@@ -315,9 +339,9 @@ function ChatPageInner() {
315
339
  <ScrollToBottomButton visible={showScrollToBottom} onClick={scrollToBottom} />
316
340
  </div>
317
341
 
318
- {/* 首页与对话态都保留快捷指令;语音活跃时只隐去胶囊并保留灰底占位,阻断时才卸载。 */}
342
+ {/* 对话态保留底部快捷指令;空会话的快捷问题在正文里成组展示(不重复渲染)。 */}
319
343
  <div ref={chatBottomRef}>
320
- {!blocked && <QuickCommands hidden={voiceActive} onCommand={send} />}
344
+ {!blocked && !isEmptyState && <QuickCommands hidden={voiceActive} onCommand={send} />}
321
345
  <ChatInput
322
346
  generating={isGenerating}
323
347
  blocked={blocked}
@@ -0,0 +1,91 @@
1
+ // @vitest-environment happy-dom
2
+ import { act } from 'react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import { flushSync } from 'react-dom';
5
+ import { createRoot, type Root } from 'react-dom/client';
6
+ import { ActionList } from './primitives';
7
+ import type { CardActions } from './use-card-actions';
8
+
9
+ const roots: Root[] = [];
10
+
11
+ afterEach(() => {
12
+ for (const root of roots) root.unmount();
13
+ roots.length = 0;
14
+ document.body.innerHTML = '';
15
+ vi.useRealTimers();
16
+ });
17
+
18
+ function render(node: React.ReactElement): HTMLElement {
19
+ const el = document.createElement('div');
20
+ document.body.appendChild(el);
21
+ const root = createRoot(el);
22
+ roots.push(root);
23
+ flushSync(() => root.render(node));
24
+ return el;
25
+ }
26
+
27
+ function makeApi(calls: string[], generating = false): CardActions {
28
+ return {
29
+ send: (text: string) => calls.push('send:' + text),
30
+ invoke: (id: string) => calls.push('invoke:' + id),
31
+ disabled: generating,
32
+ isHistory: false,
33
+ isGenerating: generating,
34
+ };
35
+ }
36
+
37
+ const actions = [{ label: '领券', invoke: { id: 'claim' } }];
38
+
39
+ describe('ActionList pending(方案 A:不改协议)', () => {
40
+ it('点击后只执行一次、按钮禁用并带 aria-busy;20 秒后解除', () => {
41
+ vi.useFakeTimers();
42
+ const calls: string[] = [];
43
+ const el = render(<ActionList api={makeApi(calls)} actions={actions} />);
44
+ const button = el.querySelector('button')!;
45
+ flushSync(() => button.click());
46
+ expect(calls).toEqual(['invoke:claim']);
47
+ expect(button.disabled).toBe(true);
48
+ expect(button.getAttribute('aria-busy')).toBe('true');
49
+ flushSync(() => button.click());
50
+ expect(calls.length).toBe(1);
51
+ flushSync(() => {
52
+ vi.advanceTimersByTime(20000);
53
+ });
54
+ expect(el.querySelector('button')!.disabled).toBe(false);
55
+ });
56
+
57
+ it('同一 tick 连点两次只执行一次(ref 同步判重)', () => {
58
+ const calls: string[] = [];
59
+ const el = render(<ActionList api={makeApi(calls)} actions={actions} />);
60
+ const button = el.querySelector('button')!;
61
+ act(() => {
62
+ button.click();
63
+ button.click();
64
+ });
65
+ expect(calls).toEqual(['invoke:claim']);
66
+ });
67
+
68
+ it('生成一轮结束后第一次点击仍进入 pending', () => {
69
+ const calls: string[] = [];
70
+ const el = document.createElement('div');
71
+ document.body.appendChild(el);
72
+ const root = createRoot(el);
73
+ roots.push(root);
74
+ act(() => root.render(<ActionList api={makeApi(calls, false)} actions={actions} />));
75
+ act(() => root.render(<ActionList api={makeApi(calls, true)} actions={actions} />));
76
+ act(() => root.render(<ActionList api={makeApi(calls, false)} actions={actions} />));
77
+ const button = el.querySelector('button')!;
78
+ act(() => button.click());
79
+ expect(el.querySelector('button')!.getAttribute('aria-busy')).toBe('true');
80
+ });
81
+
82
+ it('没有 send / invoke 的动作不进入 pending', () => {
83
+ const calls: string[] = [];
84
+ const el = render(<ActionList api={makeApi(calls)} actions={[{ label: '占位' }]} />);
85
+ const button = el.querySelector('button')!;
86
+ act(() => button.click());
87
+ expect(calls).toEqual([]);
88
+ expect(button.disabled).toBe(false);
89
+ expect(button.getAttribute('aria-busy')).toBeNull();
90
+ });
91
+ });
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { defineCard } from './define-card';
3
+
4
+ describe('defineCard', () => {
5
+ const Component = () => null;
6
+
7
+ it('默认交回 SDK 默认按钮条(存量卡兼容)', () => {
8
+ const card = defineCard({ type: 'demo-card' }, Component);
9
+ expect(card.type).toBe('demo-card');
10
+ expect(card.selfRendersActions).toBe(false);
11
+ expect(card.actionsMode).toBe('default');
12
+ });
13
+
14
+ it("actions: 'self' 表示卡片自己渲染动作", () => {
15
+ const card = defineCard({ type: 'view-card', actions: 'self' }, Component);
16
+ expect(card.selfRendersActions).toBe(true);
17
+ expect(card.actionsMode).toBe('self');
18
+ });
19
+
20
+ it("actions: 'auto' 显式交回 SDK 默认条", () => {
21
+ const card = defineCard({ type: 'legacy-card', actions: 'auto' }, Component);
22
+ expect(card.selfRendersActions).toBe(false);
23
+ expect(card.actionsMode).toBe('auto');
24
+ });
25
+ });
@@ -5,6 +5,10 @@
5
5
  * - app-build 扫描器要求 `export const card = defineCard({ type: '…' }, …)` 的首参是对象字面量;
6
6
  * - 生成 registry 把导出值直接当 `CardComponent` 注册,所以运行期必须是组件且带 `.type`。
7
7
  * 手写 Object.assign 每张卡重复一遍形态,且容易漏掉 `.type`——本工厂是唯一写法。
8
+ *
9
+ * 动作所有权:默认 `auto`——SDK 用服务端下发的按钮条渲染动作,保持旧卡兼容;
10
+ * 卡片自己渲染动作(`ActionList` / `ViewCard`)时显式 `actions: 'self'`,SDK 不再叠加
11
+ *(确认弹层、入参、历史禁用都由卡内实现)。视图卡自动派生时由生成器写 `self`。
8
12
  */
9
13
  import type { ComponentType } from 'react';
10
14
  import type { CardComponent } from '@tbox.cn/app-contracts';
@@ -17,18 +21,27 @@ export interface CardRenderProps<T> {
17
21
  actionTokens?: Record<string, string>;
18
22
  }
19
23
 
20
- /** `defineCard` 的返回类型:既是可注册的卡片组件,也带静态 `type`。 */
21
- export type DefinedCard<T> = CardComponent<T> & { type: string };
24
+ /** `defineCard` 的返回类型:既是可注册的卡片组件,也带静态 `type` 与动作所有权标记。 */
25
+ export type DefinedCard<T> = CardComponent<T> & {
26
+ type: string;
27
+ selfRendersActions: boolean;
28
+ /** 动作所有权来源:default = 未显式声明(SDK 默认条),auto / self = 显式 */
29
+ actionsMode: 'default' | 'auto' | 'self';
30
+ };
22
31
 
23
32
  /**
24
33
  * 声明一张应用级卡片。
25
34
  *
26
- * @param meta 卡片类型声明;`type` 必须与同 base 的服务端 meta 的 `cardType` 一致
35
+ * @param meta 卡片类型声明;`type` 必须与同 base 的服务端 meta 的 `cardType` 一致。
36
+ * `actions` 缺省 `'auto'`(SDK 默认按钮条,兼容旧卡);自己渲染动作的卡写 `'self'`,
37
+ * 否则会出现两条按钮或动作被禁用。
27
38
  * @param Component 渲染组件,入参为 `CardRenderProps`
28
39
  */
29
40
  export function defineCard<T>(
30
- meta: { type: string },
41
+ meta: { type: string; actions?: 'self' | 'auto' },
31
42
  Component: ComponentType<CardRenderProps<T>>,
32
43
  ): DefinedCard<T> {
33
- return Object.assign(Component, { type: meta.type }) as unknown as DefinedCard<T>;
44
+ const selfRendersActions = meta.actions === 'self';
45
+ const actionsMode = meta.actions ?? 'default';
46
+ return Object.assign(Component, { type: meta.type, selfRendersActions, actionsMode }) as unknown as DefinedCard<T>;
34
47
  }
@@ -3,13 +3,13 @@
3
3
  *
4
4
  * 设计约束:
5
5
  * - 全部走主题 token(`--tbox-*`),换主题自动跟随;不写死品牌色;
6
- * - 尺寸用 750 设计稿 px(构建期转 rem),屏幕像素约为其一半;
6
+ * - 尺寸与字号一律物理 px(没有 rem 换算,也没有动态根字号);
7
7
  * - 不引入新的交互语义:按钮一律由调用方决定 `onClick`,禁用由 `useCardActions().disabled` 统一控制。
8
8
  *
9
9
  * 信息类卡片(明细、票据、状态、路线)用这些积木拼即可,不必自写结构与样式;
10
10
  * 需要完全自定义布局时再写组件,规则见 `docs/agent/style.md`。
11
11
  */
12
- import { useState } from 'react';
12
+ import { useEffect, useRef, useState } from 'react';
13
13
  import type { ReactNode } from 'react';
14
14
  import type { CardActions } from './use-card-actions';
15
15
 
@@ -191,9 +191,9 @@ export function ActionRow({ primary, secondary, disabled }: ActionRowProps) {
191
191
  * @behavior primary 撑满整行;secondary 与 link 宽度随内容;禁用态不触发点击。
192
192
  */
193
193
  const BUTTON_VARIANT = {
194
- primary: 'w-full bg-primary px-3 py-2.5 text-sm text-white',
195
- secondary: 'w-auto border border-border bg-transparent px-3 py-2.5 text-sm text-primary',
196
- link: 'w-auto bg-transparent px-0 py-1 text-xs text-primary',
194
+ primary: 'w-full bg-primary px-4 py-2.5 text-sm text-white',
195
+ secondary: 'w-full border border-border bg-transparent px-4 py-2.5 text-sm text-primary',
196
+ link: 'w-auto bg-transparent px-1 py-1 text-sm text-primary',
197
197
  } as const;
198
198
 
199
199
  export function CardButton({
@@ -201,18 +201,22 @@ export function CardButton({
201
201
  onClick,
202
202
  variant = 'primary',
203
203
  disabled,
204
+ busy,
204
205
  }: {
205
206
  children: ReactNode;
206
207
  onClick?: () => void;
207
208
  variant?: 'primary' | 'secondary' | 'link';
208
209
  disabled?: boolean;
210
+ /** 动作进行中:只影响可访问性语义,视觉由调用方给 spinner */
211
+ busy?: boolean;
209
212
  }) {
210
213
  return (
211
214
  <button
212
- className={`tbox-btn tbox-btn--${variant} inline-flex cursor-pointer items-center justify-center rounded-full border-0 leading-tight disabled:cursor-not-allowed ${BUTTON_VARIANT[variant]}`}
215
+ className={`tbox-btn tbox-btn--${variant} inline-flex min-h-11 cursor-pointer items-center justify-center rounded-full border-0 leading-tight outline-offset-2 focus-visible:outline-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-55 ${BUTTON_VARIANT[variant]}`}
213
216
  type="button"
214
217
  onClick={onClick}
215
218
  disabled={disabled}
219
+ aria-busy={busy || undefined}
216
220
  >
217
221
  {children}
218
222
  </button>
@@ -239,22 +243,40 @@ export function ConfirmSheet({
239
243
  onConfirm,
240
244
  onCancel,
241
245
  }: ConfirmSheetProps) {
246
+ useEffect(() => {
247
+ if (!open) return undefined;
248
+ const onKey = (event: KeyboardEvent) => {
249
+ if (event.key === 'Escape') onCancel();
250
+ };
251
+ document.addEventListener('keydown', onKey);
252
+ return () => document.removeEventListener('keydown', onKey);
253
+ }, [open, onCancel]);
242
254
  if (!open) return null;
243
- return (
244
- <div className="tbox-sheet fixed inset-0 z-50" role="dialog" aria-modal="true">
255
+ // 就地渲染 fixed 弹层:卡框已不再用 filter(filter 会给 fixed 子元素造新的定位基准),
256
+ // 因此弹层相对视口定位;保留 SSR 可渲染(证据包用 renderToStaticMarkup 断言内容)。
257
+ const sheet = (
258
+ <div
259
+ className="tbox-sheet fixed inset-0 z-50"
260
+ role="dialog"
261
+ aria-modal="true"
262
+ aria-label={typeof title === 'string' ? title : undefined}
263
+ >
245
264
  <div className="tbox-sheet__mask absolute inset-0 bg-scrim" onClick={onCancel} />
246
- <div className="tbox-sheet__panel absolute inset-x-0 bottom-0 flex flex-col gap-2.5 rounded-t-xl bg-card px-4 pb-5 pt-4">
265
+ <div className="tbox-sheet__panel absolute inset-x-0 bottom-0 flex flex-col gap-2.5 rounded-t-xl bg-card px-4 pb-[calc(20px+env(safe-area-inset-bottom))] pt-4">
247
266
  <h5 className="tbox-sheet__title m-0 text-base">{title}</h5>
248
- {description ? <p className="tbox-sheet__desc m-0 text-xs text-secondary-foreground">{description}</p> : null}
249
- <div className="tbox-sheet__actions flex gap-2">
267
+ {description ? <p className="tbox-sheet__desc m-0 text-sm text-secondary-foreground">{description}</p> : null}
268
+ <div className="tbox-sheet__actions mt-1 grid grid-cols-2 gap-2">
250
269
  <CardButton variant="secondary" onClick={onCancel}>
251
- {cancelText}
270
+ <span className="whitespace-nowrap">{cancelText}</span>
271
+ </CardButton>
272
+ <CardButton onClick={onConfirm}>
273
+ <span className="whitespace-nowrap">{confirmText}</span>
252
274
  </CardButton>
253
- <CardButton onClick={onConfirm}>{confirmText}</CardButton>
254
275
  </div>
255
276
  </div>
256
277
  </div>
257
278
  );
279
+ return sheet;
258
280
  }
259
281
 
260
282
  const TICKET_TONE = {
@@ -575,11 +597,47 @@ export interface CardActionSpec {
575
597
  *
576
598
  * 用法:`const api = useCardActions({ cardId, isHistory, actionTokens }); <ActionList api={api} actions={[...]} />`
577
599
  *
578
- * @behavior 纵向排列,每个按钮独占一行;confirm 走 ConfirmSheet;disabled 自动接 api.disabled。
600
+ * @behavior 首个动作为整行主按钮,其余并排一行;confirm 走挂到 body 的 ConfirmSheet;disabled 自动接 api.disabled。
579
601
  */
602
+ const PENDING_TIMEOUT_MS = 20000;
603
+
580
604
  export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: CardActions }) {
581
- const [pending, setPending] = useState<number | null>(null);
582
- const run = (spec: CardActionSpec) => {
605
+ const [confirmIndex, setConfirmIndex] = useState<number | null>(null);
606
+ const [running, setRunning] = useState<number | null>(null);
607
+ // 单飞用 ref 同步判重:state 要等重渲染,连点两下会都通过。
608
+ const runningRef = useRef<number | null>(null);
609
+ const wasGenerating = useRef(false);
610
+
611
+ // 兜底解除:没有回执(方案 A 不改协议)时,按钮不能永远转圈。
612
+ useEffect(() => {
613
+ if (running === null) return undefined;
614
+ const timer = setTimeout(() => {
615
+ runningRef.current = null;
616
+ setRunning(null);
617
+ }, PENDING_TIMEOUT_MS);
618
+ return () => clearTimeout(timer);
619
+ }, [running]);
620
+
621
+ // 生成态从 true 回到 false = 这一轮有结果,解除 pending。
622
+ // 无论点击发生在生成前还是生成后,标记都要在当前这一轮结束时复位。
623
+ useEffect(() => {
624
+ if (api.isGenerating) {
625
+ wasGenerating.current = true;
626
+ return;
627
+ }
628
+ if (!wasGenerating.current) return;
629
+ wasGenerating.current = false;
630
+ if (runningRef.current !== null) {
631
+ runningRef.current = null;
632
+ setRunning(null);
633
+ }
634
+ }, [api.isGenerating]);
635
+
636
+ const run = (spec: CardActionSpec, index: number) => {
637
+ // 没有 send / invoke 的动作不进入 pending,否则只会空转。
638
+ if (!spec.invoke && !spec.send) return;
639
+ runningRef.current = index;
640
+ setRunning(index);
583
641
  if (spec.invoke) {
584
642
  api.invoke(spec.invoke.id, spec.invoke.input);
585
643
  return;
@@ -590,22 +648,58 @@ export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: C
590
648
  }
591
649
  };
592
650
  const trigger = (spec: CardActionSpec, index: number) => {
593
- if (api.disabled) return;
651
+ if (api.disabled || runningRef.current !== null || confirmIndex !== null) return;
594
652
  if (spec.confirm) {
595
- setPending(index);
653
+ setConfirmIndex(index);
596
654
  return;
597
655
  }
598
- run(spec);
656
+ run(spec, index);
599
657
  };
600
- const pendingSpec = pending === null ? undefined : actions[pending];
658
+ const pendingSpec = confirmIndex === null ? undefined : actions[confirmIndex];
659
+ const busy = api.disabled || running !== null || confirmIndex !== null;
660
+ const label = (text: string, index: number) => (
661
+ <span className="inline-flex items-center gap-2">
662
+ {running === index ? (
663
+ <span
664
+ className="tbox-btn__spinner inline-block size-4 animate-spin rounded-full border-2 border-current border-t-transparent"
665
+ aria-hidden="true"
666
+ />
667
+ ) : null}
668
+ {text}
669
+ </span>
670
+ );
601
671
  return (
602
672
  <>
603
673
  <div className="tbox-action-list mt-2.5 flex flex-col gap-2">
604
- {actions.map((spec, index) => (
605
- <CardButton key={`${spec.label}-${index}`} variant={spec.style ?? (index === 0 ? 'primary' : 'secondary')} disabled={api.disabled} onClick={() => trigger(spec, index)}>
606
- {spec.label}
674
+ {actions[0] ? (
675
+ <CardButton
676
+ variant={actions[0].style ?? 'primary'}
677
+ disabled={busy}
678
+ busy={running === 0}
679
+ onClick={() => trigger(actions[0], 0)}
680
+ >
681
+ {label(actions[0].label, 0)}
607
682
  </CardButton>
608
- ))}
683
+ ) : null}
684
+ {actions.length > 1 ? (
685
+ <div className="tbox-action-list__row flex gap-2">
686
+ {actions.slice(1).map((spec, index) => {
687
+ const actionIndex = index + 1;
688
+ return (
689
+ <div key={spec.label + '-' + actionIndex} className="min-w-0 flex-1">
690
+ <CardButton
691
+ variant={spec.style ?? 'secondary'}
692
+ disabled={busy}
693
+ busy={running === actionIndex}
694
+ onClick={() => trigger(spec, actionIndex)}
695
+ >
696
+ {label(spec.label, actionIndex)}
697
+ </CardButton>
698
+ </div>
699
+ );
700
+ })}
701
+ </div>
702
+ ) : null}
609
703
  </div>
610
704
  {pendingSpec?.confirm ? (
611
705
  <ConfirmSheet
@@ -616,10 +710,11 @@ export function ActionList({ actions, api }: { actions: CardActionSpec[]; api: C
616
710
  {...(pendingSpec.confirm.cancelText ? { cancelText: pendingSpec.confirm.cancelText } : {})}
617
711
  onConfirm={() => {
618
712
  const spec = pendingSpec;
619
- setPending(null);
620
- run(spec);
713
+ const index = confirmIndex ?? 0;
714
+ setConfirmIndex(null);
715
+ run(spec, index);
621
716
  }}
622
- onCancel={() => setPending(null)}
717
+ onCancel={() => setConfirmIndex(null)}
623
718
  />
624
719
  ) : null}
625
720
  </>
@@ -0,0 +1,42 @@
1
+ // @vitest-environment happy-dom
2
+ import { act } from 'react';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { afterEach, describe, expect, it } from 'vitest';
5
+ import type { CardView } from '@tbox.cn/app-contracts';
6
+ import { createSurfaceHarness } from '../surface';
7
+ import { ViewCard } from './view-card';
8
+
9
+ const view: CardView = {
10
+ header: { title: '活动' },
11
+ blocks: [
12
+ {
13
+ kind: 'list',
14
+ items: [{ title: '亲子手作', action: { label: '报名', invoke: { id: 'register' } } }],
15
+ },
16
+ ],
17
+ };
18
+
19
+ const roots: ReturnType<typeof createRoot>[] = [];
20
+ afterEach(async () => {
21
+ await act(async () => {
22
+ for (const root of roots) root.unmount();
23
+ });
24
+ roots.length = 0;
25
+ document.body.innerHTML = '';
26
+ });
27
+
28
+ describe('ViewCard 列表内联动作', () => {
29
+ it('点击后进入单飞状态,按钮禁用', async () => {
30
+ const harness = createSurfaceHarness({});
31
+ const el = document.createElement('div');
32
+ document.body.appendChild(el);
33
+ const root = createRoot(el);
34
+ roots.push(root);
35
+ act(() => root.render(harness.wrap(<ViewCard view={view} cardId="c1" actionTokens={{ register: 'token' }} />)));
36
+ const button = [...el.querySelectorAll('button')].find((item) => item.textContent?.includes('报名'))!;
37
+ await act(async () => {
38
+ button.click();
39
+ });
40
+ expect(el.querySelector('button')!.disabled).toBe(true);
41
+ });
42
+ });
@@ -0,0 +1,79 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createElement } from 'react';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
4
+ import type { CardView } from '@tbox.cn/app-contracts';
5
+ import { createSurfaceHarness } from '../surface';
6
+ import { ViewCard } from './view-card';
7
+
8
+ const parking: CardView = {
9
+ header: { title: '停车订单', eyebrow: 'PARKING', status: { text: '待支付', tone: 'warning' } },
10
+ blocks: [
11
+ { kind: 'facts', items: [['车牌', '浙A·12345'], ['停车时长', '2 小时 20 分钟']] },
12
+ { kind: 'bill', lines: [['停车费', '¥15'], ['停车券', '-¥10', true]], total: ['应付', '¥5'] },
13
+ { kind: 'notice', text: '已为你选好停车券', tone: 'info' },
14
+ ],
15
+ actions: [
16
+ { label: '确认支付 ¥5', invoke: { id: 'pay-parking', input: { plate: '浙A·12345' } }, confirm: { title: '确认支付?' } },
17
+ { label: '用积分换停车券', send: '用积分兑换停车券' },
18
+ ],
19
+ };
20
+
21
+ const activity: CardView = {
22
+ header: { title: '近期活动', status: { text: '2 个推荐', tone: 'info' } },
23
+ blocks: [
24
+ {
25
+ kind: 'list',
26
+ items: [
27
+ { title: '亲子手作', meta: '今天 15:00 · L2 连廊', tags: ['亲子'], description: '剩 8 组名额', action: { label: '报名', invoke: { id: 'register' } } },
28
+ { title: '积分加倍', meta: '今天 10:00 · L1 中庭' },
29
+ ],
30
+ },
31
+ ],
32
+ actions: [{ label: '看第一个详情', send: '第一个活动的详情', style: 'secondary' }],
33
+ };
34
+
35
+ const harness = createSurfaceHarness({});
36
+ const render = (view: CardView, isHistory = false) =>
37
+ renderToStaticMarkup(harness.wrap(createElement(ViewCard, { view, cardId: 'c1', isHistory })));
38
+
39
+ describe('ViewCard', () => {
40
+ it('积木与动作渲染一次,标题/明细/提示都在', () => {
41
+ const html = render(parking);
42
+ expect(html).toContain('停车订单');
43
+ expect(html).toContain('浙A·12345');
44
+ expect(html).toContain('应付');
45
+ expect(html).toContain('已为你选好停车券');
46
+ expect(html.match(/确认支付 ¥5/g)?.length).toBe(1);
47
+ expect(html.match(/用积分换停车券/g)?.length).toBe(1);
48
+ expect(html).toContain('tbox-btn');
49
+ });
50
+
51
+ it('列表积木渲染实体与内联动作', () => {
52
+ const html = render(activity);
53
+ expect(html).toContain('亲子手作');
54
+ expect(html).toContain('报名');
55
+ expect(html).toContain('2 个推荐');
56
+ });
57
+
58
+ it('渲染前归一化:超预算积木只渲染前 4 个', () => {
59
+ const over = {
60
+ header: { title: '超预算' },
61
+ blocks: Array.from({ length: 5 }, (_, index) => ({ kind: 'tags' as const, tags: ['tag-' + index] })),
62
+ } as unknown as CardView;
63
+ const html = render(over);
64
+ expect(html).toContain('tag-0');
65
+ expect(html).toContain('tag-3');
66
+ expect(html).not.toContain('tag-4');
67
+ });
68
+
69
+ it('坏数据回退为可读提示,不抛错', () => {
70
+ const broken = { header: { title: '坏卡' }, blocks: null } as unknown as CardView;
71
+ const html = render(broken);
72
+ expect(html).toContain('卡片数据不可用');
73
+ });
74
+
75
+ it('历史态禁用动作', () => {
76
+ const html = render(parking, true);
77
+ expect(html).toContain('disabled');
78
+ });
79
+ });