@tbox.cn/app-agent-ui-kit 1.0.0-alpha.13 → 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.
Files changed (35) hide show
  1. package/package.json +3 -3
  2. package/src/ChatPage.tsx +77 -151
  3. package/src/card/action-list-pending.test.tsx +96 -31
  4. package/src/card/primitives.test.tsx +20 -7
  5. package/src/card/primitives.tsx +54 -41
  6. package/src/card/use-card-actions.ts +23 -14
  7. package/src/card/view-card-inline.test.tsx +34 -2
  8. package/src/card/view-card.test.tsx +3 -3
  9. package/src/card/view-card.tsx +24 -29
  10. package/src/chat-config.test.ts +13 -8
  11. package/src/chat-config.ts +29 -8
  12. package/src/components/ChatInput/index.test.tsx +37 -0
  13. package/src/components/ChatInput/index.tsx +19 -6
  14. package/src/components/ChatInput/use-auto-rows.test.tsx +78 -0
  15. package/src/components/ChatInput/use-auto-rows.ts +68 -0
  16. package/src/components/HistoryEntry/index.tsx +3 -1
  17. package/src/components/HistoryList.tsx +52 -0
  18. package/src/components/MessageBubble/index.tsx +2 -3
  19. package/src/components/QuickCommands/index.test.tsx +25 -5
  20. package/src/components/QuickCommands/index.tsx +30 -27
  21. package/src/hooks/use-pull-down-history.ts +3 -4
  22. package/src/hooks/use-pull-down-wheel-native.test.ts +4 -8
  23. package/src/hooks/use-stick-to-bottom.test.tsx +142 -0
  24. package/src/hooks/use-stick-to-bottom.ts +218 -0
  25. package/src/index.ts +1 -2
  26. package/src/preview-provider.tsx +2 -1
  27. package/src/shell.contract.json +12 -13
  28. package/src/shell.test.ts +107 -11
  29. package/src/shell.ts +13 -10
  30. package/src/test/setup.ts +31 -0
  31. package/src/theme/base.css +5 -0
  32. package/src/theme/contract.json +1 -0
  33. package/src/theme/tokens.css +1 -0
  34. package/src/components/ChatHeader/index.test.tsx +0 -74
  35. package/src/components/ChatHeader/index.tsx +0 -77
@@ -0,0 +1,78 @@
1
+ // @vitest-environment happy-dom
2
+ import { act, useRef } from 'react';
3
+ import { createRoot, type Root } from 'react-dom/client';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { useAutoRows } from './use-auto-rows';
6
+
7
+ /**
8
+ * 输入框行数规格锁:空值 = 行高 × minRows(出厂 1 行),随内容长高到 maxRows,
9
+ * 超过上限后框内滚动。写死 min-height 会把单行框撑成 1.83 行——旧缺陷的回归锁。
10
+ */
11
+
12
+ const NL = String.fromCharCode(10);
13
+ const TWO_LINES = ['a', 'b'].join(NL);
14
+ const SIX_LINES = ['a', 'b', 'c', 'd', 'e', 'f'].join(NL);
15
+
16
+ const roots: Root[] = [];
17
+ afterEach(async () => {
18
+ await act(async () => {
19
+ for (const root of roots) root.unmount();
20
+ });
21
+ roots.length = 0;
22
+ document.body.innerHTML = '';
23
+ vi.restoreAllMocks();
24
+ });
25
+
26
+ function Probe({ value, minRows, maxRows }: {
27
+ value: string;
28
+ minRows: number;
29
+ maxRows: number;
30
+ }) {
31
+ const ref = useRef<HTMLTextAreaElement>(null);
32
+ useAutoRows(ref, value, { minRows, maxRows });
33
+ return <textarea ref={ref} defaultValue={value} />;
34
+ }
35
+
36
+ async function mount(node: React.ReactElement, scrollHeight: number) {
37
+ const el = document.createElement('div');
38
+ document.body.appendChild(el);
39
+ const root = createRoot(el);
40
+ roots.push(root);
41
+ // 计算样式无 CSS 文件:直接给行高(mock 里不要再调 getComputedStyle,会自递归)
42
+ const original = window.getComputedStyle.bind(window);
43
+ vi.spyOn(window, 'getComputedStyle').mockImplementation((target: Element, pseudo?: string | null) => {
44
+ const style = original(target, pseudo ?? undefined);
45
+ Object.defineProperty(style, 'lineHeight', { value: '24px', configurable: true });
46
+ return style;
47
+ });
48
+ Object.defineProperty(HTMLTextAreaElement.prototype, 'scrollHeight', {
49
+ configurable: true,
50
+ get: () => scrollHeight,
51
+ });
52
+ await act(async () => root.render(node));
53
+ return el.querySelector('textarea')!;
54
+ }
55
+
56
+ describe('输入框自适应高度', () => {
57
+ it('空值占一行(等于行高),不是两行', async () => {
58
+ const ta = await mount(<Probe value="" minRows={1} maxRows={4} />, 24);
59
+ expect(ta.style.height).toBe('24px');
60
+ expect(ta.style.overflowY).toBe('hidden');
61
+ });
62
+
63
+ it('内容两行时长高到两行', async () => {
64
+ const ta = await mount(<Probe value={TWO_LINES} minRows={1} maxRows={4} />, 48);
65
+ expect(ta.style.height).toBe('48px');
66
+ });
67
+
68
+ it('超过 maxRows 时封顶并改为框内滚动', async () => {
69
+ const ta = await mount(<Probe value={SIX_LINES} minRows={1} maxRows={3} />, 144);
70
+ expect(ta.style.height).toBe('72px');
71
+ expect(ta.style.overflowY).toBe('auto');
72
+ });
73
+
74
+ it('minRows=2 时空值占两行(用户明确要求的偏离形态)', async () => {
75
+ const ta = await mount(<Probe value="" minRows={2} maxRows={4} />, 24);
76
+ expect(ta.style.height).toBe('48px');
77
+ });
78
+ });
@@ -0,0 +1,68 @@
1
+ import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react';
2
+
3
+ /** SSR 下 useLayoutEffect 会告警(kit 可被服务端渲染:壳探针 renderToStaticMarkup 直渲 ChatPage)。 */
4
+ const useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
5
+
6
+ /** 行数夹取:NaN/负数/小数一律回落到缺省,避免写进 height: 'NaNpx'。 */
7
+ function rowsOf(value: number, fallback: number): number {
8
+ if (!Number.isFinite(value)) return fallback;
9
+ return Math.max(1, Math.floor(value));
10
+ }
11
+
12
+ /**
13
+ * 输入框自适应高度:空值占 minRows 行,随内容长高到 maxRows,超过后框内滚动。
14
+ *
15
+ * 高度只由本 hook 决定(CSS 侧不再写 min-height / max-height):写死的最小高度会把
16
+ * 单行输入框撑成 1.83 行,而 max-height 又管不住自动长高。
17
+ */
18
+ export interface UseAutoRowsOptions {
19
+ /** 空输入框占几行(chat.json input.minRows,出厂 1) */
20
+ minRows: number;
21
+ /** 长高上限行数(chat.json input.maxRows) */
22
+ maxRows: number;
23
+ /** 行高(px);缺省从计算样式读 */
24
+ lineHeight?: number;
25
+ }
26
+
27
+ export function useAutoRows(
28
+ ref: RefObject<HTMLTextAreaElement | null>,
29
+ value: string,
30
+ opts: UseAutoRowsOptions,
31
+ ): void {
32
+ const { minRows, maxRows, lineHeight } = opts;
33
+ // 元素身份:语音模式切回文本时 textarea 会重新挂载,依赖没变也要重算高度
34
+ const elementRef = useRef<HTMLTextAreaElement | null>(null);
35
+
36
+ useIsoLayoutEffect(() => {
37
+ const el = ref.current;
38
+ if (!el) return;
39
+ elementRef.current = el;
40
+ const computed = Number.parseFloat(getComputedStyle(el).lineHeight);
41
+ const line = lineHeight ?? (Number.isFinite(computed) && computed > 0 ? computed : 24);
42
+ const minRowCount = rowsOf(minRows, 1);
43
+ const maxRowCount = Math.max(minRowCount, rowsOf(maxRows, 4));
44
+ const min = line * minRowCount;
45
+ const max = line * maxRowCount;
46
+ // 先归零再读 scrollHeight:否则拿到的包含上一次的高度
47
+ el.style.height = 'auto';
48
+ const needed = Math.max(min, el.scrollHeight);
49
+ const height = Math.min(needed, max);
50
+ el.style.height = height + 'px';
51
+ // 超过上限才允许框内滚动;否则隐藏滚动条
52
+ el.style.overflowY = needed > max ? 'auto' : 'hidden';
53
+ }, [ref, value, minRows, maxRows, lineHeight]);
54
+
55
+ // 元素被替换(同 ref、新节点)时补算一次:上一次 effect 的依赖全没变,不会再跑
56
+ useIsoLayoutEffect(() => {
57
+ const el = ref.current;
58
+ if (!el || el === elementRef.current) return;
59
+ el.style.height = 'auto';
60
+ const computed = Number.parseFloat(getComputedStyle(el).lineHeight);
61
+ const line = lineHeight ?? (Number.isFinite(computed) && computed > 0 ? computed : 24);
62
+ const minRowCount = rowsOf(minRows, 1);
63
+ const maxRowCount = Math.max(minRowCount, rowsOf(maxRows, 4));
64
+ const height = Math.min(Math.max(line * minRowCount, el.scrollHeight), line * maxRowCount);
65
+ el.style.height = height + 'px';
66
+ el.style.overflowY = el.scrollHeight > line * maxRowCount ? 'auto' : 'hidden';
67
+ });
68
+ }
@@ -11,12 +11,14 @@ function labelOf(status: PullStatus, loading: boolean): string {
11
11
  }
12
12
 
13
13
  export default function HistoryEntry({
14
+ compact = false,
14
15
  visible,
15
16
  loading,
16
17
  disabled,
17
18
  pullStatus,
18
19
  onLoad,
19
20
  }: {
21
+ compact?: boolean;
20
22
  visible: boolean;
21
23
  loading: boolean;
22
24
  disabled: boolean;
@@ -30,7 +32,7 @@ export default function HistoryEntry({
30
32
  <button
31
33
  type="button"
32
34
  data-tbox-control="history"
33
- 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"
35
+ className={`history-entry__button inline-flex appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-muted font-normal 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 ${compact ? 'px-3 py-[3px] text-xs leading-4' : 'min-h-11 px-4 py-1 text-sm leading-[18px]'}`}
34
36
  disabled={disabled}
35
37
  onClick={onLoad}
36
38
  >
@@ -0,0 +1,52 @@
1
+ import { Component, createRef, type RefObject } from 'react';
2
+ import type { ChatMessage } from '../types';
3
+ import { MessageBubble } from './MessageBubble';
4
+
5
+ type Props = { messages: readonly ChatMessage[]; scrollRef: RefObject<HTMLDivElement | null> };
6
+ type Snapshot = { element: Element; top: number } | 'open-latest-turn' | null;
7
+
8
+ /** React 在改动 DOM 前提供旧布局,在同一次绘制前完成前插补偿。 */
9
+ export class HistoryList extends Component<Props, Record<string, never>, Snapshot> {
10
+ private listRef = createRef<HTMLDivElement>();
11
+
12
+ getSnapshotBeforeUpdate(previous: Props): Snapshot {
13
+ const body = this.props.scrollRef.current;
14
+ const list = this.listRef.current;
15
+ const added = this.props.messages.length - previous.messages.length;
16
+ if (!body || !list || added <= 0) return null;
17
+ if (previous.messages.length && previous.messages[0]?.id !== this.props.messages[added]?.id) return null;
18
+
19
+ const viewport = body.getBoundingClientRect();
20
+ for (const row of body.querySelectorAll('[data-message-id]')) {
21
+ const rect = row.getBoundingClientRect();
22
+ if (rect.bottom > viewport.top && rect.top < viewport.bottom) return { element: row, top: rect.top };
23
+ }
24
+ // 首次从顶部打开,还没有可见对话。最新历史问题给这次主动查看一个可读的起点。
25
+ if (previous.messages.length === 0 && body.scrollTop <= 5) return 'open-latest-turn';
26
+
27
+ // 等待时用户可能已滑到问候区或服务卡;历史末端与这段内容一起移动。
28
+ return { element: list, top: list.getBoundingClientRect().bottom };
29
+ }
30
+
31
+ componentDidUpdate(_previous: Props, _state: Record<string, never>, snapshot: Snapshot) {
32
+ const body = this.props.scrollRef.current;
33
+ const list = this.listRef.current;
34
+ if (!snapshot || !body || !list) return;
35
+ if (snapshot === 'open-latest-turn') {
36
+ const latest = Array.from(list.querySelectorAll('[data-message-role="user"]')).pop() ?? list.lastElementChild;
37
+ if (latest) body.scrollTop += latest.getBoundingClientRect().top - body.getBoundingClientRect().top - 8;
38
+ return;
39
+ }
40
+ const rect = snapshot.element.getBoundingClientRect();
41
+ const delta = (snapshot.element === list ? rect.bottom : rect.top) - snapshot.top;
42
+ if (Math.abs(delta) > 0.5) body.scrollTop += delta;
43
+ }
44
+
45
+ render() {
46
+ return (
47
+ <div className="chat-page__history" ref={this.listRef}>
48
+ {this.props.messages.map((message) => <MessageBubble key={message.id} message={message} />)}
49
+ </div>
50
+ );
51
+ }
52
+ }
@@ -27,9 +27,8 @@ 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
- // 发送者名取应用身份(chat.json identity.name),没有配置才回落通用名。
31
- const identity = useChatConfigStore((s) => s.identity);
32
- const roleName = isUser ? '你' : (identity?.name ?? 'AI 助手');
30
+ // 发送者名固定:身份不是配置项(应用名归 page.title,介绍文案归 welcome)
31
+ const roleName = isUser ? '你' : 'AI 助手';
33
32
  const timeLabel = new Date(message.createdAt).toLocaleTimeString('zh-CN', {
34
33
  hour: '2-digit',
35
34
  minute: '2-digit',
@@ -12,6 +12,7 @@ import type { CoreChatStore } from '@tbox.cn/app-agent-sdk-client';
12
12
  import { configureChatConfigDefaults, useChatConfigStore } from '../../chat-config';
13
13
  import { KitChatProvider } from '../../store-context';
14
14
  import { QuickCommands } from './index';
15
+ import starIcon from '../../../assets/quick-command-star.svg';
15
16
 
16
17
  /** 最小测试 store(仅 helloAck 消费面);注入形式经 KitChatProvider。 */
17
18
  const testStore = create<{ helloAck: unknown }>(() => ({ helloAck: null })) as unknown as CoreChatStore;
@@ -56,12 +57,12 @@ afterEach(() => {
56
57
  });
57
58
 
58
59
  describe('QuickCommands 快捷胶囊', () => {
59
- it('按服务端顺序渲染三项、合并本地图标并发送服务端 prompt', () => {
60
+ it('优先渲染服务端图标,兼容本地配置,并发送服务端 prompt', () => {
60
61
  testStore.setState({
61
62
  helloAck: {
62
63
  chatConfig: {
63
64
  quickCommands: [
64
- { label: '今日优惠', prompt: '服务端优惠查询' },
65
+ { label: '今日优惠', prompt: '服务端优惠查询', icon: '/offer.png' },
65
66
  { label: '品牌导览', prompt: '服务端品牌导览' },
66
67
  { label: '活动中心', prompt: '服务端活动查询' },
67
68
  ],
@@ -76,9 +77,13 @@ describe('QuickCommands 快捷胶囊', () => {
76
77
  const buttons = [...container.querySelectorAll<HTMLButtonElement>('.quick-commands__item')];
77
78
  expect(buttons.map((button) => button.textContent)).toEqual(['今日优惠', '品牌导览', '活动中心']);
78
79
  expect(container.textContent).not.toContain('找门店');
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
+ const icons = buttons.map((button) => button.querySelector<HTMLImageElement>('img.quick-commands__icon'));
81
+ expect(icons.map((icon) => icon?.getAttribute('src'))).toEqual([
82
+ '/offer.png', STATIC_COMMANDS[1].icon, STATIC_COMMANDS[2].icon,
83
+ ]);
84
+ expect(icons.map((icon) => icon?.alt)).toEqual(['', '', '']);
85
+ icons[1]!.dispatchEvent(new Event('error'));
86
+ expect(icons[1]?.getAttribute('src')).toBe(starIcon);
82
87
  flushSync(() => buttons[1]!.click());
83
88
  expect(onCommand).toHaveBeenCalledWith('服务端品牌导览');
84
89
  });
@@ -98,4 +103,19 @@ describe('QuickCommands 快捷胶囊', () => {
98
103
  flushSync(() => button?.click());
99
104
  expect(onCommand).not.toHaveBeenCalled();
100
105
  });
106
+
107
+ it('活动可以用内置日历图标,其他配置图标照常显示', () => {
108
+ configureChatConfigDefaults({
109
+ quickCommands: [...STATIC_COMMANDS.slice(0, 2), { ...STATIC_COMMANDS[2], icon: 'icon:calendar' }],
110
+ });
111
+ const container = document.createElement('div');
112
+ document.body.appendChild(container);
113
+ renderWithKit(container, <QuickCommands onCommand={vi.fn()} />);
114
+
115
+ const buttons = [...container.querySelectorAll('button')];
116
+ expect(buttons.map((button) => button.textContent)).toEqual(STATIC_COMMANDS.map(({ label }) => label));
117
+ expect(buttons[0]?.querySelector('img')?.getAttribute('src')).toBe(STATIC_COMMANDS[0].icon);
118
+ expect(buttons[1]?.querySelector('img')?.getAttribute('src')).toBe(STATIC_COMMANDS[1].icon);
119
+ expect(buttons[2]?.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
120
+ });
101
121
  });
@@ -1,13 +1,28 @@
1
- // 输入框上方的快捷指令;文案由 chatConfig 驱动,服务端下发不含 icon 时按 label 合并本地配置。
2
- // 011 I2:服务端 HelloAck.chatConfig.quickCommands 优先(单一真源),本地 chat.json 为 fallback。
1
+ // 服务端 HelloAck.chatConfig.quickCommands 优先;旧服务端缺省 icon 时按 label 合并本地配置。
3
2
  // label 只写纯文字;前面的星标由本组件渲染(icon 字段或默认 ✦),不要把 ✦/emoji 写进 label。
4
3
  //
5
- // 两种排布:空会话用 grid(两列、全可见、每个 44px 命中区),对话态用 row(底部单行、可横滚)。
6
- // 颜色只用语义令牌:换品牌色后不残留固定蓝。
4
+ // 欢迎区用两列;主题选择紧凑布局时输入区使用紧凑单行。
7
5
  import { useChatConfigStore } from '../../chat-config';
6
+ import { Calendar } from '../../icons';
8
7
  import { useChatStore } from '../../store-context';
9
8
  import starIcon from '../../../assets/quick-command-star.svg';
10
9
 
10
+ function QuickCommandIcon({ icon }: { icon?: string }) {
11
+ if (icon === 'icon:calendar') {
12
+ return <Calendar size={16} weight="fill" className="quick-commands__icon shrink-0 text-secondary-foreground" aria-hidden="true" />;
13
+ }
14
+ return (
15
+ <img
16
+ className="quick-commands__icon size-4 shrink-0 object-contain"
17
+ src={icon || starIcon}
18
+ alt=""
19
+ onError={({ currentTarget }) => {
20
+ if (currentTarget.getAttribute('src') !== starIcon) currentTarget.src = starIcon;
21
+ }}
22
+ />
23
+ );
24
+ }
25
+
11
26
  export function QuickCommands({
12
27
  onCommand,
13
28
  hidden = false,
@@ -15,7 +30,7 @@ export function QuickCommands({
15
30
  }: {
16
31
  onCommand: (query: string) => void;
17
32
  hidden?: boolean;
18
- variant?: 'row' | 'grid';
33
+ variant?: 'row' | 'grid' | 'compact';
19
34
  }) {
20
35
  const staticCommands = useChatConfigStore((s) => s.quickCommands);
21
36
  // chatConfig 可选链:旧 server 的 HELLO_ACK 可能不带该段(与「ack 缺席回落静态」同语义)
@@ -26,47 +41,35 @@ export function QuickCommands({
26
41
  ? serverCommands.map((command) => ({
27
42
  label: command.label,
28
43
  query: command.prompt,
29
- icon: staticByLabel.get(command.label)?.icon,
44
+ icon: command.icon || staticByLabel.get(command.label)?.icon,
30
45
  }))
31
46
  : staticCommands;
32
47
  if (!commands.length) return null;
33
48
 
34
49
  const grid = variant === 'grid';
50
+ const compact = variant === 'compact';
51
+ const buttonStyle = {
52
+ grid: 'w-full justify-start gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 text-left shadow-sm active:border-primary',
53
+ row: 'flex-[1_0_auto] justify-center gap-1.5 rounded-[22px] border border-border bg-card px-3 py-2 shadow-sm active:border-primary',
54
+ compact: 'relative isolate flex-[1_0_auto] justify-center gap-[5px] rounded-full border-0 bg-transparent px-3 before:pointer-events-none before:absolute before:inset-x-0 before:inset-y-[5px] before:-z-10 before:rounded-full before:border before:border-border before:bg-card before:shadow-[0_4px_16px_rgba(38,59,92,0.05)] before:transition-colors active:before:border-primary',
55
+ }[variant];
35
56
  return (
36
57
  <div
37
58
  className={
38
59
  grid
39
60
  ? `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' : ''}`
61
+ : `quick-commands relative z-[1] mx-auto flex w-full max-w-content gap-2 overflow-x-auto px-page [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden ${compact ? 'pb-1' : 'pb-[9px]'} ${hidden ? ' quick-commands--hidden invisible pointer-events-none' : ''}`
41
62
  }
42
63
  aria-hidden={hidden || undefined}
43
64
  >
44
65
  {commands.map((cmd) => (
45
66
  <button
46
67
  key={cmd.label}
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
- }
68
+ className={`quick-commands__item inline-flex min-h-11 appearance-none items-center text-foreground transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] ${buttonStyle}`}
52
69
  disabled={hidden}
53
70
  onClick={() => onCommand(cmd.query)}
54
71
  >
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
- }}
69
- />
72
+ <QuickCommandIcon icon={cmd.icon} />
70
73
  <span className={`quick-commands__label text-sm font-medium leading-[18px] text-foreground ${grid ? 'line-clamp-2 text-left' : 'whitespace-nowrap'}`}>{cmd.label}</span>
71
74
  </button>
72
75
  ))}
@@ -172,11 +172,10 @@ export function usePullDownHistory(opts: UsePullDownHistoryOptions): {
172
172
  const advanceWheel = useCallback(
173
173
  (deltaY: number): boolean => {
174
174
  if (disabled) return false;
175
- // 触发后到滚动停止之间:吞掉惯性。加载会把 scrollTop 抬到前插位置,
176
- // 上方随即出现可滚空间,残余惯性会继续把它带走——落位就白设了。
175
+ // 同一段惯性只触发一次请求,后续位移仍交给浏览器,用户可顺势读到前插的消息。
177
176
  if (wheelLockedRef.current) {
178
177
  scheduleWheelIdle();
179
- return true;
178
+ return false;
180
179
  }
181
180
  const { shouldLoad } = machineRef.current.wheel({
182
181
  deltaY,
@@ -198,7 +197,7 @@ export function usePullDownHistory(opts: UsePullDownHistoryOptions): {
198
197
  );
199
198
 
200
199
  // 原生非 passive 绑定:React 的 onWheel 同样是 passive,preventDefault 无效,
201
- // 吞不掉惯性。与 touch 通道同理(见 use-drag-gesture 文件头)。
200
+ // 无法阻止越阈的触发事件。与 touch 通道同理(见 use-drag-gesture 文件头)。
202
201
  useEffect(() => {
203
202
  const el = scrollRef?.current;
204
203
  if (!el || disabled) return undefined;
@@ -1,8 +1,4 @@
1
1
  // @vitest-environment happy-dom
2
- /**
3
- * wheel 原生通道用例。核心契约:触发加载后到滚动停止之间,惯性 wheel 必须被 preventDefault
4
- * 吞掉——加载会把 scrollTop 抬到前插位置,上方随即出现可滚空间,残余惯性会把落位带走。
5
- */
6
2
  import { describe, expect, it, vi } from 'vitest';
7
3
  import { createRoot } from 'react-dom/client';
8
4
  import { flushSync } from 'react-dom';
@@ -44,7 +40,7 @@ describe('usePullDownHistory:wheel 原生通道', () => {
44
40
  expect(e.defaultPrevented).toBe(false);
45
41
  });
46
42
 
47
- it('N2 越阈触发后吞掉后续惯性,落位不被带走', async () => {
43
+ it('N2 越阈后允许继续滚动,同一段惯性只触发一次', async () => {
48
44
  const onLoad = vi.fn(async () => {});
49
45
  const el = setup(onLoad);
50
46
 
@@ -53,11 +49,11 @@ describe('usePullDownHistory:wheel 原生通道', () => {
53
49
  expect(onLoad).toHaveBeenCalledTimes(1);
54
50
  expect(trigger.defaultPrevented).toBe(true);
55
51
 
56
- // 惯性尾巴:既不得二次触发,也不得让原生滚动继续
52
+ // 用户继续上滑或反向滚动时,容器都可以原生滚动。
57
53
  for (let i = 0; i < 5; i += 1) {
58
- const inertia = wheelEvent(-80);
54
+ const inertia = wheelEvent(i % 2 ? 80 : -80);
59
55
  el.dispatchEvent(inertia);
60
- expect(inertia.defaultPrevented).toBe(true);
56
+ expect(inertia.defaultPrevented).toBe(false);
61
57
  }
62
58
  expect(onLoad).toHaveBeenCalledTimes(1);
63
59
  });
@@ -0,0 +1,142 @@
1
+ // @vitest-environment happy-dom
2
+ import { act, useRef } from 'react';
3
+ import { createRoot, type Root } from 'react-dom/client';
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { useStickToBottom } from './use-stick-to-bottom';
6
+ import { triggerResizeObservers } from '../test/setup';
7
+
8
+ /**
9
+ * 跟随状态机的规格锁:内容长高一律跟到底;只有用户手势能脱离;点浮标回到跟随。
10
+ * 旧实现按「离底 <150px」判定,内容一长高就被误判成用户离开——这些用例锁住新语义。
11
+ */
12
+
13
+ const roots: Root[] = [];
14
+ afterEach(async () => {
15
+ await act(async () => {
16
+ for (const root of roots) root.unmount();
17
+ });
18
+ roots.length = 0;
19
+ document.body.innerHTML = '';
20
+ vi.restoreAllMocks();
21
+ });
22
+
23
+ /** 可控滚动容器:scrollHeight/clientHeight 由测试设定 */
24
+ function makeScrollable(initial: { scrollHeight: number; clientHeight: number }) {
25
+ const scroll = document.createElement('div');
26
+ const content = document.createElement('div');
27
+ scroll.appendChild(content);
28
+ document.body.appendChild(scroll);
29
+ let scrollHeight = initial.scrollHeight;
30
+ const clientHeight = initial.clientHeight;
31
+ Object.defineProperty(scroll, 'scrollHeight', { get: () => scrollHeight });
32
+ Object.defineProperty(scroll, 'clientHeight', { get: () => clientHeight });
33
+ let scrollTop = 0;
34
+ Object.defineProperty(scroll, 'scrollTop', {
35
+ get: () => scrollTop,
36
+ set: (value: number) => {
37
+ scrollTop = Math.max(0, Math.min(value, scrollHeight - clientHeight));
38
+ scroll.dispatchEvent(new Event('scroll'));
39
+ },
40
+ });
41
+ return {
42
+ scroll,
43
+ content,
44
+ grow(px: number) {
45
+ scrollHeight += px;
46
+ },
47
+ get top() {
48
+ return scrollTop;
49
+ },
50
+ };
51
+ }
52
+
53
+ function Probe({ target }: { target: ReturnType<typeof makeScrollable> }) {
54
+ const scrollRef = useRef<HTMLElement | null>(target.scroll);
55
+ const contentRef = useRef<HTMLElement | null>(target.content);
56
+ const stick = useStickToBottom({ scrollRef, contentRef });
57
+ // showJump 是 state:脱离跟随且离底超阈值时才为真,用作可渲染的状态探针
58
+ return (
59
+ <div>
60
+ <span data-testid="jump">{String(stick.showJump)}</span>
61
+ <button type="button" onClick={() => stick.follow()}>go</button>
62
+ </div>
63
+ );
64
+ }
65
+
66
+ /** 冲刷一轮 ResizeObserver 回调 + 等 happy-dom 的 rAF 真正执行 */
67
+ async function flushFrame() {
68
+ await act(async () => {
69
+ triggerResizeObservers();
70
+ await new Promise((resolve) => setTimeout(resolve, 40));
71
+ });
72
+ }
73
+
74
+ describe('贴底跟随', () => {
75
+ it('内容长高时一路跟到底(不看离底距离)', async () => {
76
+ const scroller = makeScrollable({ scrollHeight: 400, clientHeight: 300 });
77
+ const el = document.createElement('div');
78
+ document.body.appendChild(el);
79
+ const root = createRoot(el);
80
+ roots.push(root);
81
+ await act(async () => root.render(<Probe target={scroller} />));
82
+ await flushFrame();
83
+ expect(scroller.top).toBe(100);
84
+ // 一次长高 500px(远超旧实现的 150px 阈值):仍然跟到底
85
+ scroller.grow(500);
86
+ await flushFrame();
87
+ expect(scroller.top).toBe(600);
88
+ });
89
+
90
+ it('用户滚轮向上后脱离跟随,内容增长不再拉回,浮标出现', async () => {
91
+ const scroller = makeScrollable({ scrollHeight: 400, clientHeight: 300 });
92
+ const el = document.createElement('div');
93
+ document.body.appendChild(el);
94
+ const root = createRoot(el);
95
+ roots.push(root);
96
+ await act(async () => root.render(<Probe target={scroller} />));
97
+ await flushFrame();
98
+ await act(async () => {
99
+ scroller.scroll.dispatchEvent(new WheelEvent('wheel', { deltaY: -120 }));
100
+ });
101
+ scroller.grow(400);
102
+ await flushFrame();
103
+ // 不再写入滚动位置
104
+ expect(scroller.top).toBe(100);
105
+ expect(el.querySelector('[data-testid="jump"]')!.textContent).toBe('true');
106
+ });
107
+
108
+ it('点浮标后回到跟随并贴底', async () => {
109
+ const scroller = makeScrollable({ scrollHeight: 400, clientHeight: 300 });
110
+ const el = document.createElement('div');
111
+ document.body.appendChild(el);
112
+ const root = createRoot(el);
113
+ roots.push(root);
114
+ await act(async () => root.render(<Probe target={scroller} />));
115
+ await flushFrame();
116
+ scroller.grow(300);
117
+ await act(async () => {
118
+ scroller.scroll.dispatchEvent(new WheelEvent('wheel', { deltaY: -120 }));
119
+ });
120
+ await flushFrame();
121
+ expect(el.querySelector('[data-testid="jump"]')!.textContent).toBe('true');
122
+ await act(async () => {
123
+ el.querySelector('button')!.click();
124
+ });
125
+ await flushFrame();
126
+ expect(scroller.top).toBe(400);
127
+ expect(el.querySelector('[data-testid="jump"]')!.textContent).toBe('false');
128
+ });
129
+
130
+ it('程序写入引起的 scroll 事件不改变跟随状态', async () => {
131
+ const scroller = makeScrollable({ scrollHeight: 800, clientHeight: 300 });
132
+ const el = document.createElement('div');
133
+ document.body.appendChild(el);
134
+ const root = createRoot(el);
135
+ roots.push(root);
136
+ await act(async () => root.render(<Probe target={scroller} />));
137
+ await flushFrame();
138
+ // 挂载即贴底,且程序写入不触发脱离
139
+ expect(scroller.top).toBe(500);
140
+ expect(el.querySelector('[data-testid="jump"]')!.textContent).toBe('false');
141
+ });
142
+ });