@tbox.cn/app-agent-ui-kit 1.0.0-alpha.12 → 1.0.0-alpha.14
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 +3 -3
- package/src/ChatPage.tsx +77 -151
- package/src/card/action-list-pending.test.tsx +96 -31
- package/src/card/primitives.test.tsx +20 -7
- package/src/card/primitives.tsx +54 -41
- package/src/card/use-card-actions.ts +23 -14
- package/src/card/view-card-inline.test.tsx +34 -2
- package/src/card/view-card.test.tsx +3 -3
- package/src/card/view-card.tsx +24 -29
- package/src/chat-config.test.ts +13 -8
- package/src/chat-config.ts +29 -8
- package/src/components/ChatInput/index.test.tsx +37 -0
- package/src/components/ChatInput/index.tsx +19 -6
- package/src/components/ChatInput/use-auto-rows.test.tsx +78 -0
- package/src/components/ChatInput/use-auto-rows.ts +68 -0
- package/src/components/HistoryEntry/index.tsx +3 -1
- package/src/components/HistoryList.tsx +52 -0
- package/src/components/MessageBubble/index.tsx +2 -3
- package/src/components/QuickCommands/index.test.tsx +25 -5
- package/src/components/QuickCommands/index.tsx +30 -27
- package/src/hooks/use-pull-down-history.ts +3 -4
- package/src/hooks/use-pull-down-wheel-native.test.ts +4 -8
- package/src/hooks/use-stick-to-bottom.test.tsx +142 -0
- package/src/hooks/use-stick-to-bottom.ts +218 -0
- package/src/index.ts +1 -2
- package/src/preview-provider.tsx +2 -1
- package/src/shell.contract.json +12 -13
- package/src/shell.test.ts +107 -11
- package/src/shell.ts +13 -10
- package/src/test/setup.ts +31 -0
- package/src/theme/base.css +5 -0
- package/src/theme/contract.json +1 -0
- package/src/theme/tokens.css +1 -0
- package/src/components/ChatHeader/index.test.tsx +0 -74
- package/src/components/ChatHeader/index.tsx +0 -77
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.
|
|
3
|
+
"version": "1.0.0-alpha.14",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Agent 对话壳 UI 组件包(源码发布,单一模板统一化 W2-1):ChatPage/壳组件族/主题 tokens。",
|
|
6
6
|
"exports": {
|
|
@@ -44,8 +44,8 @@
|
|
|
44
44
|
"remark-gfm": "4.0.1",
|
|
45
45
|
"yet-another-react-lightbox": "3.33.1",
|
|
46
46
|
"zustand": "4.5.7",
|
|
47
|
-
"@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.
|
|
48
|
-
"@tbox.cn/app-contracts": "1.0.0-alpha.
|
|
47
|
+
"@tbox.cn/app-agent-sdk-client": "1.0.0-alpha.14",
|
|
48
|
+
"@tbox.cn/app-contracts": "1.0.0-alpha.14"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"react": "18.3.1",
|
package/src/ChatPage.tsx
CHANGED
|
@@ -6,10 +6,7 @@
|
|
|
6
6
|
* 空态恒挂载——域自持其显隐);缺席 → chat 流(空态为空体,landing 槽已退役);
|
|
7
7
|
* - 域自持段(首屏数据/门禁/详情弹层/活动预热)经槽渲染函数自带——本页零域语义。
|
|
8
8
|
*/
|
|
9
|
-
import { useCallback, useEffect,
|
|
10
|
-
|
|
11
|
-
// SSR(预览/探针)没有 DOM 可量:useLayoutEffect 会打印不可消除的告警,服务端退化为 useEffect。
|
|
12
|
-
const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
|
|
9
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
13
10
|
import { consumeAutoSendQuery, runAutoSend } from '@tbox.cn/app-agent-sdk-client';
|
|
14
11
|
import { usePullDownHistory } from './hooks/use-pull-down-history';
|
|
15
12
|
import { registerScrollHost } from './overlay';
|
|
@@ -17,11 +14,12 @@ import type { TboxCardPayload } from '@tbox.cn/app-contracts';
|
|
|
17
14
|
import { CardRenderer } from './components/CardRenderer';
|
|
18
15
|
import { ChatInput } from './components/ChatInput';
|
|
19
16
|
import HistoryEntry from './components/HistoryEntry';
|
|
17
|
+
import { HistoryList } from './components/HistoryList';
|
|
20
18
|
import { MessageBubble } from './components/MessageBubble';
|
|
21
19
|
import { QuickCommands } from './components/QuickCommands';
|
|
22
20
|
import ScrollToBottomButton from './components/ScrollToBottomButton';
|
|
23
21
|
import { useChatConfigStore } from './chat-config';
|
|
24
|
-
import {
|
|
22
|
+
import { useStickToBottom } from './hooks/use-stick-to-bottom';
|
|
25
23
|
import {
|
|
26
24
|
KitChatProvider,
|
|
27
25
|
useChatStore,
|
|
@@ -72,14 +70,13 @@ function ChatPageInner() {
|
|
|
72
70
|
const runtimeStatus = useChatStore((s) => s.runtimeStatus);
|
|
73
71
|
const authBlocked = useChatStore((s) => s.authBlocked);
|
|
74
72
|
const orphanCards = useChatStore((s) => s.orphanCards);
|
|
75
|
-
const cardsByMessageId = useChatStore((s) => s.cardsByMessageId);
|
|
76
73
|
const initConversation = useChatStore((s) => s.initConversation);
|
|
77
74
|
const destroy = useChatStore((s) => s.destroy);
|
|
78
75
|
const sendMessage = useChatStore((s) => s.sendMessage);
|
|
79
76
|
const cancelGeneration = useChatStore((s) => s.cancelGeneration);
|
|
80
77
|
const newConversation = useChatStore((s) => s.newConversation);
|
|
81
78
|
const retryBootstrap = useChatStore((s) => s.retryBootstrap);
|
|
82
|
-
//
|
|
79
|
+
// 商场名来自 HELLO_ACK.mallScope,由首页槽用于问候。
|
|
83
80
|
const mallName = useChatStore((s) => s.helloAck?.mallScope?.mallName);
|
|
84
81
|
// chat settings 水合:HELLO_ACK 服务端真源 → 静态 store(ack 未达/键缺席保留构建期快照;
|
|
85
82
|
// 重连/新会话产生新 helloAck 再水合——applyServerSettings 幂等)
|
|
@@ -91,15 +88,15 @@ function ChatPageInner() {
|
|
|
91
88
|
|
|
92
89
|
const slots = useClientSlots();
|
|
93
90
|
const homeSlot = slots?.resolve('home');
|
|
91
|
+
// 主题在应用挂载前就位,布局从首帧起固定。
|
|
92
|
+
const [compactLayout] = useState(() => typeof window !== 'undefined'
|
|
93
|
+
&& window.getComputedStyle(document.documentElement).getPropertyValue('--tbox-compact-chat').trim() === '1');
|
|
94
94
|
const conversationOverlay = slots?.resolve('conversationOverlay');
|
|
95
|
-
const identity = useChatConfigStore((s) => s.identity);
|
|
96
95
|
const welcome = useChatConfigStore((s) => s.welcome);
|
|
97
96
|
|
|
98
|
-
//
|
|
97
|
+
// 主题色跟主题走(页面标题归 page.title,壳不改写文档标题)。
|
|
99
98
|
useEffect(() => {
|
|
100
99
|
if (typeof document === 'undefined') return;
|
|
101
|
-
const name = identity?.name;
|
|
102
|
-
if (name) document.title = name;
|
|
103
100
|
const bg = getComputedStyle(document.documentElement).getPropertyValue('--tbox-bg-page').trim();
|
|
104
101
|
if (bg) {
|
|
105
102
|
let meta = document.querySelector('meta[name="theme-color"]');
|
|
@@ -110,13 +107,12 @@ function ChatPageInner() {
|
|
|
110
107
|
}
|
|
111
108
|
meta.setAttribute('content', bg);
|
|
112
109
|
}
|
|
113
|
-
}, [
|
|
114
|
-
// 常驻品牌条:chat.json identity.name → HELLO_ACK 的 mallName → 不渲染(壳契约见 shell.ts)
|
|
115
|
-
const brandName = resolveBrandName(identity, mallName);
|
|
110
|
+
}, []);
|
|
116
111
|
|
|
117
|
-
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
|
118
112
|
const [voiceActive, setVoiceActive] = useState(false);
|
|
119
113
|
const bodyRef = useRef<HTMLDivElement>(null);
|
|
114
|
+
/** 内容容器:跟随时观察它的尺寸(流式文字、卡片挂载、图片加载) */
|
|
115
|
+
const contentRef = useRef<HTMLDivElement>(null);
|
|
120
116
|
|
|
121
117
|
// 弹层滚动锁要锁的是应用自己的滚动宿主(body 在本壳里并不滚动):登记给 kit overlay 内核,
|
|
122
118
|
// 业务弹层因此不再需要读 `.chat-page__body` 这类壳内部类名。
|
|
@@ -127,30 +123,29 @@ function ChatPageInner() {
|
|
|
127
123
|
}, []);
|
|
128
124
|
// 底部输入区(QuickCommands + ChatInput)高度测量:底部避让消费(如半屏 sheet)
|
|
129
125
|
const chatBottomRef = useRef<HTMLDivElement>(null);
|
|
130
|
-
// 历史前插视口锚:home 槽位占位(历史插入发生在其上,保持用户看到的位置)
|
|
131
|
-
const historyAnchorRef = useRef<HTMLDivElement>(null);
|
|
132
126
|
const historyLoadInFlightRef = useRef<Promise<void> | null>(null);
|
|
133
|
-
const pendingHistoryViewportRef = useRef<{ anchorTop: number } | null>(null);
|
|
134
127
|
const isAtTopRef = useRef(true);
|
|
135
|
-
|
|
128
|
+
|
|
129
|
+
const stick = useStickToBottom({ scrollRef: bodyRef, contentRef });
|
|
136
130
|
|
|
137
131
|
const startNewConversation = useCallback(() => {
|
|
138
132
|
void newConversation();
|
|
139
133
|
const el = bodyRef.current;
|
|
140
134
|
if (el) el.scrollTop = 0;
|
|
141
135
|
isAtTopRef.current = true;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
136
|
+
// 新会话从跟随开始,但**不要**在此刻贴底:旧内容还在,写 bottom 会把用户拽到旧对话底部。
|
|
137
|
+
// resume 只置跟随状态,随后的内容清空/长高按跟随便处理。
|
|
138
|
+
stick.resume();
|
|
139
|
+
}, [newConversation, stick]);
|
|
145
140
|
|
|
146
141
|
const send = useCallback((input: string | ChatInputMessage) => {
|
|
147
142
|
// 主动发送代表用户要回到最新对话;待消息 DOM 提交后由下方 effect 落底。
|
|
148
143
|
// 生成中 store 会拒绝新消息,此时不改变用户正在查看的滚动位置。
|
|
149
144
|
if (isGenerating) return;
|
|
150
|
-
|
|
151
|
-
|
|
145
|
+
// 主动发送 = 用户要看最新对话:回到跟随,内容增长时一路跟到底
|
|
146
|
+
stick.follow();
|
|
152
147
|
sendMessage(input);
|
|
153
|
-
}, [isGenerating, sendMessage]);
|
|
148
|
+
}, [isGenerating, sendMessage, stick]);
|
|
154
149
|
|
|
155
150
|
// 连接终态阻断(登录失败/scope 拒绝):禁用输入 + 提示条 + 重试。
|
|
156
151
|
// 门控仅 runtimeStatus=failed 或 authBlocked——bootstrapping 等过渡态不闪现横幅
|
|
@@ -163,51 +158,28 @@ function ChatPageInner() {
|
|
|
163
158
|
: undefined;
|
|
164
159
|
|
|
165
160
|
const scrollToBottom = useCallback(() => {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
isNearBottomRef.current = true;
|
|
169
|
-
setShowScrollToBottom(false);
|
|
170
|
-
}, []);
|
|
161
|
+
stick.follow();
|
|
162
|
+
}, [stick]);
|
|
171
163
|
|
|
172
|
-
|
|
164
|
+
// 滚动只更新「是否在顶部」(下拉加载历史用);跟随与浮标由 stick 状态机负责。
|
|
173
165
|
const onScroll = useCallback(() => {
|
|
174
166
|
const el = bodyRef.current;
|
|
175
167
|
if (!el) return;
|
|
176
168
|
isAtTopRef.current = el.scrollTop <= 5;
|
|
177
|
-
const distanceToBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
|
|
178
|
-
isNearBottomRef.current = distanceToBottom < NEAR_BOTTOM;
|
|
179
|
-
setShowScrollToBottom(!isNearBottomRef.current);
|
|
180
169
|
}, []);
|
|
181
170
|
|
|
182
171
|
// 顶部入口与轻量下拉共用同一加载任务;同一周期复用 Promise,避免点击/手势重复请求。
|
|
183
172
|
const onLoadHistory = useCallback(() => {
|
|
184
173
|
if (historyLoadInFlightRef.current) return historyLoadInFlightRef.current;
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
anchorTop: anchor.getBoundingClientRect().top,
|
|
189
|
-
};
|
|
190
|
-
}
|
|
174
|
+
// 用户要看历史:长高的是历史区,视线应停在历史条目上,别被贴底跟随拉回去。
|
|
175
|
+
// 历史列表自己按「最近一条可见消息」定位(HistoryList componentDidUpdate),这里只让出滚动权。
|
|
176
|
+
stick.hold();
|
|
191
177
|
const task = loadMoreHistory().finally(() => {
|
|
192
178
|
if (historyLoadInFlightRef.current === task) historyLoadInFlightRef.current = null;
|
|
193
179
|
});
|
|
194
180
|
historyLoadInFlightRef.current = task;
|
|
195
181
|
return task;
|
|
196
|
-
}, [loadMoreHistory]);
|
|
197
|
-
|
|
198
|
-
// 历史插入发生在当前内容上方:绘制前只补一次新增高度,保持用户原本看到的位置。
|
|
199
|
-
// 不设置定时器、不钉住 scrollTop;补偿后下一次滚动立即由用户接管。
|
|
200
|
-
useIsomorphicLayoutEffect(() => {
|
|
201
|
-
const pending = pendingHistoryViewportRef.current;
|
|
202
|
-
const anchor = historyAnchorRef.current;
|
|
203
|
-
if (!pending || !anchor) return;
|
|
204
|
-
pendingHistoryViewportRef.current = null;
|
|
205
|
-
const anchorDelta = anchor.getBoundingClientRect().top - pending.anchorTop;
|
|
206
|
-
if (Math.abs(anchorDelta) > 0.5) {
|
|
207
|
-
const el = bodyRef.current;
|
|
208
|
-
if (el) el.scrollTop += anchorDelta;
|
|
209
|
-
}
|
|
210
|
-
}, [historyMessages]);
|
|
182
|
+
}, [loadMoreHistory, stick]);
|
|
211
183
|
|
|
212
184
|
const filterInlineCards = useInlineCardFilter();
|
|
213
185
|
const inlineOrphanCards = useMemo(
|
|
@@ -221,13 +193,6 @@ function ChatPageInner() {
|
|
|
221
193
|
&& messages.length === 0
|
|
222
194
|
&& inlineOrphanCards.length === 0;
|
|
223
195
|
|
|
224
|
-
const liveCardSignature = useMemo(
|
|
225
|
-
() => messages
|
|
226
|
-
.map((message) => `${message.id}:${(cardsByMessageId[message.id] ?? []).map((card) => card.id).join(',')}`)
|
|
227
|
-
.join('|'),
|
|
228
|
-
[messages, cardsByMessageId],
|
|
229
|
-
);
|
|
230
|
-
|
|
231
196
|
const showHistoryEntry = historyHasMore && historyMessages.length === 0;
|
|
232
197
|
|
|
233
198
|
// 空会话欢迎区:没有 home 槽时给首屏一个落点(标题来自 chat.json welcome,缺省「开始对话」)
|
|
@@ -235,10 +200,10 @@ function ChatPageInner() {
|
|
|
235
200
|
&& historyMessages.length === 0
|
|
236
201
|
&& messages.length === 0
|
|
237
202
|
&& inlineOrphanCards.length === 0;
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
const
|
|
203
|
+
// 欢迎区是身份的唯一位:身份写进 welcome.title / subtitle,壳不再有页头
|
|
204
|
+
const welcomeTitle = welcome?.title ?? '开始对话';
|
|
205
|
+
const welcomeSubtitle = welcome?.subtitle ?? '可以直接提问,也可以从下面的问题开始';
|
|
206
|
+
const showGridCommands = showWelcome || (showHome && !compactLayout);
|
|
242
207
|
|
|
243
208
|
const pull = usePullDownHistory({
|
|
244
209
|
isAtTopRef,
|
|
@@ -272,53 +237,14 @@ function ChatPageInner() {
|
|
|
272
237
|
return () => ro.disconnect();
|
|
273
238
|
}, []);
|
|
274
239
|
|
|
275
|
-
// 回合锚定:新回合把本轮用户消息置顶,流式期间不追底。
|
|
276
|
-
// 贴底滚动会把问题顶出视口(实测卡片 648px 时问题上移 244px),用户看不到自己在问什么。
|
|
277
|
-
const turnAnchorRef = useRef<string | null>(null);
|
|
278
|
-
useEffect(() => {
|
|
279
|
-
const lastUser = [...messages].reverse().find((message) => message.role === 'user');
|
|
280
|
-
if (!lastUser || turnAnchorRef.current === lastUser.id) return;
|
|
281
|
-
turnAnchorRef.current = lastUser.id;
|
|
282
|
-
const body = bodyRef.current;
|
|
283
|
-
const element = body?.querySelector(`[data-message-id="${lastUser.id}"]`);
|
|
284
|
-
if (!body || !element) return;
|
|
285
|
-
const delta = element.getBoundingClientRect().top - body.getBoundingClientRect().top;
|
|
286
|
-
body.scrollTop += delta - 8;
|
|
287
|
-
isNearBottomRef.current = false;
|
|
288
|
-
// 回合锚定后内容通常超出视口:必须让「回到底部」入口出现,否则用户只能靠手势找底。
|
|
289
|
-
if (body.scrollHeight > body.clientHeight + 8) setShowScrollToBottom(true);
|
|
290
|
-
}, [messages]);
|
|
291
|
-
|
|
292
|
-
// 已脱离底部时内容继续变高(流式回复、卡片后挂载):保持浮标可见,不追底。
|
|
293
|
-
useEffect(() => {
|
|
294
|
-
if (isNearBottomRef.current) return;
|
|
295
|
-
const el = bodyRef.current;
|
|
296
|
-
if (el && el.scrollHeight > el.clientHeight + 8) setShowScrollToBottom(true);
|
|
297
|
-
}, [messages, liveCardSignature, orphanCards]);
|
|
298
|
-
|
|
299
|
-
// 没有新回合、但卡片在文字之后挂载时,内容会继续变高:只在用户本来就在底部时补滚,
|
|
300
|
-
// 且不改变「本轮问题已在视口内」的锚点。
|
|
301
|
-
useEffect(() => {
|
|
302
|
-
if (!isNearBottomRef.current) return;
|
|
303
|
-
const el = bodyRef.current;
|
|
304
|
-
if (el && messages.length === 0 && orphanCards.length > 0) el.scrollTop = el.scrollHeight;
|
|
305
|
-
}, [orphanCards, liveCardSignature, messages.length]);
|
|
306
|
-
|
|
307
240
|
return (
|
|
308
241
|
<div className={`chat-page relative flex h-full w-full min-h-0 flex-col overflow-hidden bg-background ${showHome ? '' : ' chat-page--conversation'}`}>
|
|
309
242
|
{/* 整页背景独立于滚动内容,覆盖历史入口、首页与底部输入区;图片按视口居中铺满、不重复。 */}
|
|
310
243
|
<div className="chat-page__bg pointer-events-none absolute inset-0 z-0 bg-background bg-center bg-cover bg-no-repeat" />
|
|
311
244
|
|
|
312
|
-
{brandName ? (
|
|
313
|
-
<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}>
|
|
314
|
-
<span className="chat-page__brand-name text-base font-bold tracking-wide text-foreground">{brandName}</span>
|
|
315
|
-
{identity?.tagline ? <span className="chat-page__brand-tagline text-xs text-muted-foreground">{identity.tagline}</span> : null}
|
|
316
|
-
</div>
|
|
317
|
-
) : null}
|
|
318
|
-
|
|
319
245
|
<div className="chat-page__body-wrapper relative z-10 flex min-h-0 flex-1 flex-col">
|
|
320
246
|
<div
|
|
321
|
-
className=
|
|
247
|
+
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))] ${historyMessages.length ? '' : '[overflow-anchor:none]'} [scrollbar-width:none] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden`}
|
|
322
248
|
ref={bodyRef}
|
|
323
249
|
onScroll={onScroll}
|
|
324
250
|
onWheel={pull.handleWheel}
|
|
@@ -327,61 +253,61 @@ function ChatPageInner() {
|
|
|
327
253
|
onTouchEnd={pull.handleTouchEnd}
|
|
328
254
|
onTouchCancel={pull.handleTouchCancel}
|
|
329
255
|
>
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
256
|
+
{/* 内容容器:贴底跟随观察它的尺寸变化(流式文字 / 卡片挂载 / 图片加载) */}
|
|
257
|
+
<div className="chat-page__content" ref={contentRef}>
|
|
258
|
+
<HistoryEntry
|
|
259
|
+
compact={compactLayout}
|
|
260
|
+
visible={showHistoryEntry}
|
|
261
|
+
loading={isLoadingHistory}
|
|
262
|
+
disabled={runtimeStatus !== 'ready' || isLoadingHistory}
|
|
263
|
+
pullStatus={pull.pullStatus}
|
|
264
|
+
onLoad={() => void onLoadHistory()}
|
|
265
|
+
/>
|
|
266
|
+
|
|
267
|
+
<HistoryList messages={historyMessages} scrollRef={bodyRef} />
|
|
268
|
+
|
|
269
|
+
{/* 空会话欢迎区:没有 home 槽时的首屏落点(文案来自 chat.json welcome) */}
|
|
270
|
+
{showWelcome ? (
|
|
271
|
+
<div className="chat-page__welcome flex flex-col items-center justify-center gap-2 px-page pb-4 pt-6 text-center">
|
|
272
|
+
<h2 className="chat-page__welcome-title m-0 text-xl font-bold text-foreground">{welcomeTitle}</h2>
|
|
273
|
+
{welcomeSubtitle ? <p className="chat-page__welcome-subtitle m-0 text-sm leading-normal text-muted-foreground">{welcomeSubtitle}</p> : null}
|
|
274
|
+
</div>
|
|
275
|
+
) : null}
|
|
276
|
+
|
|
277
|
+
{/* home 槽渲染位(域自持显隐;缺席则不渲染)。flow-root 让首页子元素
|
|
278
|
+
的外边距留在槽内,不折叠到历史入口与首页之间。 */}
|
|
279
|
+
<div className="chat-page__home-slot flow-root">
|
|
280
|
+
{homeSlot?.({ onSend: send, ...(mallName ? { mallName } : {}) })}
|
|
281
|
+
</div>
|
|
337
282
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
283
|
+
{!blocked && showGridCommands ? (
|
|
284
|
+
<div className="chat-page__home-actions mt-6 flex w-full flex-col items-center">
|
|
285
|
+
<QuickCommands variant="grid" hidden={voiceActive} onCommand={send} />
|
|
286
|
+
</div>
|
|
287
|
+
) : null}
|
|
288
|
+
|
|
289
|
+
{/* 业务旁路 emit 的卡片(如欢迎卡) */}
|
|
290
|
+
{inlineOrphanCards.map((card) => (
|
|
291
|
+
<div key={card.id} className="chat-page__orphan-card mx-page">
|
|
292
|
+
<CardRenderer card={card} />
|
|
293
|
+
</div>
|
|
341
294
|
))}
|
|
342
|
-
</div>
|
|
343
|
-
|
|
344
|
-
{/* 空会话欢迎区:没有 home 槽时的首屏落点(文案来自 chat.json welcome / identity) */}
|
|
345
|
-
{showWelcome ? (
|
|
346
|
-
<div className="chat-page__welcome flex flex-col items-center justify-center gap-2 px-page pb-4 pt-6 text-center">
|
|
347
|
-
<h2 className="chat-page__welcome-title m-0 text-xl font-bold text-foreground">{welcomeTitle}</h2>
|
|
348
|
-
{welcomeSubtitle ? <p className="chat-page__welcome-subtitle m-0 text-sm leading-normal text-muted-foreground">{welcomeSubtitle}</p> : null}
|
|
349
|
-
</div>
|
|
350
|
-
) : null}
|
|
351
295
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
296
|
+
{/* 消息(每条消息下的卡片由 MessageBubble 内部渲染) */}
|
|
297
|
+
{messages.map((msg) => (
|
|
298
|
+
<MessageBubble key={msg.id} message={msg} />
|
|
299
|
+
))}
|
|
356
300
|
</div>
|
|
357
|
-
|
|
358
|
-
{/* 空会话的服务入口:快捷问题与欢迎区成组居中,两列全可见(不再贴底单行溢出)。 */}
|
|
359
|
-
{!blocked && isEmptyState ? (
|
|
360
|
-
<div className="chat-page__home-actions mt-6 flex w-full flex-col items-center">
|
|
361
|
-
<QuickCommands variant="grid" hidden={voiceActive} onCommand={send} />
|
|
362
|
-
</div>
|
|
363
|
-
) : null}
|
|
364
|
-
|
|
365
|
-
{/* 业务旁路 emit 的卡片(如欢迎卡) */}
|
|
366
|
-
{inlineOrphanCards.map((card) => (
|
|
367
|
-
<div key={card.id} className="chat-page__orphan-card mx-page">
|
|
368
|
-
<CardRenderer card={card} />
|
|
369
|
-
</div>
|
|
370
|
-
))}
|
|
371
|
-
|
|
372
|
-
{/* 消息(每条消息下的卡片由 MessageBubble 内部渲染) */}
|
|
373
|
-
{messages.map((msg) => (
|
|
374
|
-
<MessageBubble key={msg.id} message={msg} />
|
|
375
|
-
))}
|
|
376
301
|
</div>
|
|
377
302
|
|
|
378
|
-
<ScrollToBottomButton visible={
|
|
303
|
+
<ScrollToBottomButton visible={stick.showJump} onClick={scrollToBottom} />
|
|
379
304
|
</div>
|
|
380
305
|
|
|
381
|
-
{/*
|
|
306
|
+
{/* 紧凑商场首页和对话态共用这组快捷胶囊,随输入区一起测量。 */}
|
|
382
307
|
<div ref={chatBottomRef}>
|
|
383
|
-
{!blocked && !
|
|
308
|
+
{!blocked && !showGridCommands && <QuickCommands variant={compactLayout ? 'compact' : 'row'} hidden={voiceActive} onCommand={send} />}
|
|
384
309
|
<ChatInput
|
|
310
|
+
compact={compactLayout}
|
|
385
311
|
generating={isGenerating}
|
|
386
312
|
blocked={blocked}
|
|
387
313
|
onSend={send}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// @vitest-environment happy-dom
|
|
2
|
-
import { act } from 'react';
|
|
3
|
-
import { afterEach, describe, expect, it
|
|
2
|
+
import { act, StrictMode } from 'react';
|
|
3
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
4
4
|
import { flushSync } from 'react-dom';
|
|
5
5
|
import { createRoot, type Root } from 'react-dom/client';
|
|
6
6
|
import { ActionList } from './primitives';
|
|
7
7
|
import type { CardActions } from './use-card-actions';
|
|
8
|
+
import type { ActionOutcome } from '@tbox.cn/app-agent-sdk-client';
|
|
8
9
|
|
|
9
10
|
const roots: Root[] = [];
|
|
10
11
|
|
|
@@ -12,7 +13,6 @@ afterEach(() => {
|
|
|
12
13
|
for (const root of roots) root.unmount();
|
|
13
14
|
roots.length = 0;
|
|
14
15
|
document.body.innerHTML = '';
|
|
15
|
-
vi.useRealTimers();
|
|
16
16
|
});
|
|
17
17
|
|
|
18
18
|
function render(node: React.ReactElement): HTMLElement {
|
|
@@ -24,68 +24,133 @@ function render(node: React.ReactElement): HTMLElement {
|
|
|
24
24
|
return el;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
/** 受控结算的 api:返回值由测试决定何时兑现。 */
|
|
28
|
+
function makeApi(calls: string[], opts: { generating?: boolean } = {}) {
|
|
29
|
+
const pending: Array<(o: ActionOutcome) => void> = [];
|
|
30
|
+
const api: CardActions & { settleAll(o: ActionOutcome): void } = {
|
|
31
|
+
send: (text: string) => {
|
|
32
|
+
calls.push('send:' + text);
|
|
33
|
+
return new Promise<ActionOutcome>((resolve) => pending.push(resolve));
|
|
34
|
+
},
|
|
35
|
+
invoke: (id: string) => {
|
|
36
|
+
calls.push('invoke:' + id);
|
|
37
|
+
return new Promise<ActionOutcome>((resolve) => pending.push(resolve));
|
|
38
|
+
},
|
|
39
|
+
disabled: opts.generating === true,
|
|
32
40
|
isHistory: false,
|
|
33
|
-
isGenerating: generating,
|
|
41
|
+
isGenerating: opts.generating === true,
|
|
42
|
+
settleAll: (outcome) => {
|
|
43
|
+
while (pending.length) pending.shift()!(outcome);
|
|
44
|
+
},
|
|
34
45
|
};
|
|
46
|
+
return api;
|
|
35
47
|
}
|
|
36
48
|
|
|
37
49
|
const actions = [{ label: '领券', invoke: { id: 'claim' } }];
|
|
38
50
|
|
|
39
|
-
describe('ActionList
|
|
40
|
-
it('
|
|
41
|
-
vi.useFakeTimers();
|
|
51
|
+
describe('ActionList 挂起结算(结束信号驱动)', () => {
|
|
52
|
+
it('点击后按钮禁用并带 aria-busy;结算到达即解锁(不等超时)', async () => {
|
|
42
53
|
const calls: string[] = [];
|
|
43
|
-
const
|
|
54
|
+
const api = makeApi(calls);
|
|
55
|
+
const el = render(<ActionList api={api} actions={actions} />);
|
|
44
56
|
const button = el.querySelector('button')!;
|
|
45
57
|
flushSync(() => button.click());
|
|
46
58
|
expect(calls).toEqual(['invoke:claim']);
|
|
47
59
|
expect(button.disabled).toBe(true);
|
|
48
60
|
expect(button.getAttribute('aria-busy')).toBe('true');
|
|
61
|
+
// 连点被单飞拦下
|
|
49
62
|
flushSync(() => button.click());
|
|
50
63
|
expect(calls.length).toBe(1);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
});
|
|
64
|
+
// 结算
|
|
65
|
+
await act(async () => api.settleAll({ status: 'settled', outcome: 'updated' }));
|
|
54
66
|
expect(el.querySelector('button')!.disabled).toBe(false);
|
|
55
67
|
});
|
|
56
68
|
|
|
57
69
|
it('同一 tick 连点两次只执行一次(ref 同步判重)', () => {
|
|
58
70
|
const calls: string[] = [];
|
|
59
|
-
const
|
|
71
|
+
const api = makeApi(calls);
|
|
72
|
+
const el = render(<ActionList api={api} actions={actions} />);
|
|
60
73
|
const button = el.querySelector('button')!;
|
|
61
|
-
|
|
74
|
+
flushSync(() => {
|
|
62
75
|
button.click();
|
|
63
76
|
button.click();
|
|
64
77
|
});
|
|
65
78
|
expect(calls).toEqual(['invoke:claim']);
|
|
66
79
|
});
|
|
67
80
|
|
|
68
|
-
it('
|
|
81
|
+
it('加载中(isGenerating)时新点击不触发动作', () => {
|
|
82
|
+
const calls: string[] = [];
|
|
83
|
+
const api = makeApi(calls, { generating: true });
|
|
84
|
+
const el = render(<ActionList api={api} actions={actions} />);
|
|
85
|
+
flushSync(() => el.querySelector('button')!.click());
|
|
86
|
+
expect(calls).toEqual([]);
|
|
87
|
+
expect(el.querySelector('button')!.disabled).toBe(true);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('确认弹层确认后才派发;取消不派发', () => {
|
|
91
|
+
const calls: string[] = [];
|
|
92
|
+
const api = makeApi(calls);
|
|
93
|
+
const el = render(
|
|
94
|
+
<ActionList api={api} actions={[{ label: '删除', invoke: { id: 'del' }, confirm: { title: '确认删除?' } }]} />,
|
|
95
|
+
);
|
|
96
|
+
flushSync(() => el.querySelector('button')!.click());
|
|
97
|
+
expect(calls).toEqual([]);
|
|
98
|
+
const sheetButtons = [...document.querySelectorAll('.tbox-sheet button')] as HTMLButtonElement[];
|
|
99
|
+
const cancel = sheetButtons.find((b) => b.textContent?.includes('取消')) ?? sheetButtons[0]!;
|
|
100
|
+
flushSync(() => cancel.click());
|
|
101
|
+
expect(calls).toEqual([]);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('转圈跟着动作走:卡片原地刷新后不再显示原动作的转圈', async () => {
|
|
105
|
+
const calls: string[] = [];
|
|
106
|
+
const api = makeApi(calls);
|
|
107
|
+
const el = document.createElement('div');
|
|
108
|
+
document.body.appendChild(el);
|
|
109
|
+
const root = createRoot(el);
|
|
110
|
+
roots.push(root);
|
|
111
|
+
flushSync(() => root.render(<ActionList api={api} actions={actions} />));
|
|
112
|
+
flushSync(() => el.querySelector('button')!.click());
|
|
113
|
+
expect(el.querySelector('.tbox-btn__spinner')).not.toBeNull();
|
|
114
|
+
// 卡片原地更新:按钮组换成另一组动作(同一个组件实例,props 变化)
|
|
115
|
+
flushSync(() => root.render(<ActionList api={api} actions={[{ label: '查看积分', invoke: { id: 'points' } }]} />));
|
|
116
|
+
// 被点的动作已不在列表:不显示转圈,也不再把新按钮当成挂起
|
|
117
|
+
expect(el.querySelector('.tbox-btn__spinner')).toBeNull();
|
|
118
|
+
await act(async () => api.settleAll({ status: 'settled', outcome: 'updated' }));
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
describe('ActionList 卸载语义(StrictMode 双挂载回归)', () => {
|
|
122
|
+
it('StrictMode 下挂载后结算仍会解锁(mountedRef 必须被 effect 体置回 true)', async () => {
|
|
69
123
|
const calls: string[] = [];
|
|
124
|
+
const api = makeApi(calls);
|
|
70
125
|
const el = document.createElement('div');
|
|
71
126
|
document.body.appendChild(el);
|
|
72
127
|
const root = createRoot(el);
|
|
73
128
|
roots.push(root);
|
|
74
|
-
|
|
75
|
-
act(() => root.render(<ActionList api={makeApi(calls, true)} actions={actions} />));
|
|
76
|
-
act(() => root.render(<ActionList api={makeApi(calls, false)} actions={actions} />));
|
|
129
|
+
flushSync(() => root.render(<StrictMode><ActionList api={api} actions={actions} /></StrictMode>));
|
|
77
130
|
const button = el.querySelector('button')!;
|
|
78
|
-
|
|
79
|
-
expect(
|
|
131
|
+
flushSync(() => button.click());
|
|
132
|
+
expect(button.disabled).toBe(true);
|
|
133
|
+
await act(async () => api.settleAll({ status: 'settled', outcome: 'updated' }));
|
|
134
|
+
expect(el.querySelector('button')!.disabled).toBe(false);
|
|
80
135
|
});
|
|
81
136
|
|
|
82
|
-
it('
|
|
83
|
-
const
|
|
84
|
-
const
|
|
137
|
+
it('实现方 reject 时不产生 unhandledrejection,且按钮解锁', async () => {
|
|
138
|
+
const seen: unknown[] = [];
|
|
139
|
+
const onUnhandled = (event: PromiseRejectionEvent) => { seen.push(event.reason); };
|
|
140
|
+
window.addEventListener('unhandledrejection', onUnhandled);
|
|
141
|
+
const api: CardActions = {
|
|
142
|
+
send: () => new Promise<ActionOutcome>((_resolve, reject) => setTimeout(() => reject(new Error('boom')), 0)),
|
|
143
|
+
invoke: () => new Promise<ActionOutcome>((_resolve, reject) => setTimeout(() => reject(new Error('boom')), 0)),
|
|
144
|
+
disabled: false,
|
|
145
|
+
isHistory: false,
|
|
146
|
+
isGenerating: false,
|
|
147
|
+
};
|
|
148
|
+
const el = render(<ActionList api={api} actions={actions} />);
|
|
85
149
|
const button = el.querySelector('button')!;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
expect(
|
|
150
|
+
flushSync(() => button.click());
|
|
151
|
+
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
|
|
152
|
+
window.removeEventListener('unhandledrejection', onUnhandled);
|
|
153
|
+
expect(el.querySelector('button')!.disabled).toBe(false);
|
|
154
|
+
expect(seen).toEqual([]);
|
|
90
155
|
});
|
|
91
156
|
});
|
|
@@ -30,12 +30,12 @@ describe('卡片基元', () => {
|
|
|
30
30
|
const markup = html(
|
|
31
31
|
<Card footer="数据更新于刚刚">
|
|
32
32
|
<CardHeader eyebrow="订单" title="待支付" status={<StatusTag tone="warning">待支付</StatusTag>} />
|
|
33
|
-
<KeyValueList items={[{ label: '车牌', value: '
|
|
33
|
+
<KeyValueList items={[{ label: '车牌', value: '京A·00000' }, { label: '入场', value: '12:01' }]} />
|
|
34
34
|
</Card>,
|
|
35
35
|
);
|
|
36
36
|
expect(markup).toContain('tbox-card-primitive');
|
|
37
37
|
expect(markup).toContain('待支付');
|
|
38
|
-
expect(markup).toContain('
|
|
38
|
+
expect(markup).toContain('京A·00000');
|
|
39
39
|
expect(markup).toContain('数据更新于刚刚');
|
|
40
40
|
});
|
|
41
41
|
|
|
@@ -73,7 +73,7 @@ describe('卡片基元', () => {
|
|
|
73
73
|
it('票券、步骤、图文条目可渲染', () => {
|
|
74
74
|
expect(html(<Ticket amount="20 元" condition="满 100 可用" meta="有效期至 12-31" />)).toContain('tbox-ticket__amount');
|
|
75
75
|
expect(html(<Steps steps={[{ title: 'B2 层', detail: '靠近 3 号电梯' }, { title: '取车' }]} />)).toContain('tbox-steps__index');
|
|
76
|
-
expect(html(<MediaRow title="
|
|
76
|
+
expect(html(<MediaRow title="示例餐厅" meta="B1 · 人均 60" action={<CardButton variant="link">去看看</CardButton>} />)).toContain('示例餐厅');
|
|
77
77
|
});
|
|
78
78
|
});
|
|
79
79
|
|
|
@@ -107,7 +107,7 @@ describe('第二版基元', () => {
|
|
|
107
107
|
it('EntityRow 支持价格与说明,EmptyState 给下一步', () => {
|
|
108
108
|
const markup = html(
|
|
109
109
|
<>
|
|
110
|
-
<EntityRow title="
|
|
110
|
+
<EntityRow title="示例餐厅" meta="餐饮 · L1" price="¥80/人" tags={<TagList tags={['满100减15']} />} />
|
|
111
111
|
<EmptyState title="暂无停车券" description="缴费或参加活动可攒积分" />
|
|
112
112
|
</>,
|
|
113
113
|
);
|
|
@@ -124,9 +124,16 @@ describe('第二版基元', () => {
|
|
|
124
124
|
|
|
125
125
|
it('ActionList 点击前确认时先开弹层,确认后才调用动作', () => {
|
|
126
126
|
const calls: string[] = [];
|
|
127
|
+
const settled = { status: 'settled' as const, outcome: 'updated' as const };
|
|
127
128
|
const api = {
|
|
128
|
-
send: (text: string) =>
|
|
129
|
-
|
|
129
|
+
send: (text: string) => {
|
|
130
|
+
calls.push(`send:${text}`);
|
|
131
|
+
return Promise.resolve(settled);
|
|
132
|
+
},
|
|
133
|
+
invoke: (id: string, input?: Record<string, unknown>) => {
|
|
134
|
+
calls.push(`invoke:${id}:${JSON.stringify(input ?? {})}`);
|
|
135
|
+
return Promise.resolve(settled);
|
|
136
|
+
},
|
|
130
137
|
disabled: false,
|
|
131
138
|
isHistory: false,
|
|
132
139
|
isGenerating: false,
|
|
@@ -148,7 +155,13 @@ describe('第二版基元', () => {
|
|
|
148
155
|
it('ActionList 禁用时按钮带 disabled', () => {
|
|
149
156
|
const markup = html(
|
|
150
157
|
<ActionList
|
|
151
|
-
api={{
|
|
158
|
+
api={{
|
|
159
|
+
send: () => Promise.resolve({ status: 'rejected' as const, reason: 'generating' as const }),
|
|
160
|
+
invoke: () => Promise.resolve({ status: 'rejected' as const, reason: 'generating' as const }),
|
|
161
|
+
disabled: true,
|
|
162
|
+
isHistory: false,
|
|
163
|
+
isGenerating: false,
|
|
164
|
+
}}
|
|
152
165
|
actions={[{ label: '领券', invoke: { id: 'claim' } }]}
|
|
153
166
|
/>,
|
|
154
167
|
);
|