From 0c673d916f81fec386ba7bb2d58a0d4b0dcee84f Mon Sep 17 00:00:00 2001 From: zhc Date: Mon, 9 Nov 2026 12:57:10 +0800 Subject: [PATCH] fix(ui): let model menu detail pages own focus and group semantics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pane 改为带 kind 标签的可辨识联合,ModelMenuPage 更名为 ModelMenuPageRef - 二级页由页面自行设置初始焦点:Switch 新增 autoFocus/describedBy,Team 开关进页即聚焦并关联说明文字;owner 不再查找 [role="switch"] - 二级页容器改用 role="group",菜单 surface 增加 data-model-menu 供测试定位 - 外部按下同时监听 pointerdown,覆盖 WebKit 触摸点击空白区域不派发 mousedown 的情况 - 删除 .page 中多余的 gap: 0 --- apps/web/tests/agent-team-panel.e2e.ts | 12 +-- .../collaboration.zh.expected.md | 2 +- .../agent-team-panel/info.expected.md | 2 +- .../client/ui-agent-team/README.i18n.yaml | 4 +- packages/client/ui-agent-team/README.md | 2 +- packages/client/ui-agent-team/README.zh.md | 2 +- .../src/client/TeamModeToggle.module.css | 1 - .../src/client/TeamModeToggle.tsx | 7 +- .../tests/team-mode.client.spec.tsx | 3 +- .../ui-model-selection/README.i18n.yaml | 4 +- packages/client/ui-model-selection/README.md | 2 +- .../client/ui-model-selection/README.zh.md | 2 +- .../src/client/ModelSelect.tsx | 97 +++++++++++-------- .../ui-model-selection/src/client/slots.ts | 12 ++- .../tests/model-menu-page.client.spec.tsx | 25 ++++- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- packages/client/ui-primitives/src/Switch.tsx | 8 +- .../tests/switch.client.spec.tsx | 6 ++ .../src/client/slot-catalog.ts | 10 +- .../tests/providers.client.spec.ts | 2 +- 22 files changed, 133 insertions(+), 78 deletions(-) diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index 860bd3bf97..957930cfaa 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -131,7 +131,7 @@ describe('web e2e: agent teamwork panel', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) const trigger = page.getByRole('button', { name: /^Select model/u }) await trigger.click() - const menu = page.getByRole('menu') + const menu = page.locator('[data-model-menu]') const summary = menu.getByRole('menuitem', { name: 'Agent teamwork Off', exact: true }) await summary.waitFor() const stateColor = await summary.getByText('Off', { exact: true }).evaluate(element => getComputedStyle(element).color) @@ -146,7 +146,7 @@ describe('web e2e: agent teamwork panel', () => { expect(await summary.locator('svg').evaluate(inspectArrow)).toEqual(await peerArrow.evaluate(inspectArrow)) expect(await menu.getByRole('switch').count()).toBe(0) expect(await page.getByRole('button', { name: 'About agent teamwork', exact: true }).count()).toBe(0) - const rootSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const rootSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) const original = await menu.elementHandle() if (original === null) throw new Error('Model menu is missing') try { @@ -166,7 +166,7 @@ describe('web e2e: agent teamwork panel', () => { descriptionGap: element.parentElement!.nextElementSibling!.getBoundingClientRect().top - element.parentElement!.getBoundingClientRect().bottom, }))).toEqual({ rowBackground: 'rgba(0, 0, 0, 0)', focusVisible: true, outline: 'solid', descriptionGap: 0 }) - const settingsSnapshot = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const settingsSnapshot = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), `## Root\n\n${rootSnapshot}\n\n## Team settings\n\n${settingsSnapshot}`, MODE) await page.keyboard.press('Escape') @@ -192,7 +192,7 @@ describe('web e2e: agent teamwork panel', () => { const viewport = page.viewportSize()! try { await openTeamSettings(page) - const menu = page.getByRole('menu') + const menu = page.locator('[data-model-menu]') const toggle = menu.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) const description = menu.getByText('Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', { exact: true }) await description.click() @@ -867,7 +867,7 @@ describe('web e2e: agent teamwork panel', () => { await openConfirmation() const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) await assertWarningDialogLayout(dialog) - expect(await page.getByRole('menu', { name: 'Agent teamwork', exact: true }).count()).toBe(0) + expect(await page.getByRole('group', { name: 'Agent teamwork', exact: true }).count()).toBe(0) expect(await page.getByRole('button', { name: /^Select model/u }).getAttribute('aria-expanded')).toBe('false') expect(await dialog.getByRole('checkbox').count()).toBe(0) expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) @@ -1091,7 +1091,7 @@ it('uses the Chinese collaboration name in the switch and disable confirmation', await page.getByText('通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', { exact: true }).waitFor() expect(await page.getByRole('tooltip').count()).toBe(0) expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) - const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + const menu = await captureStableAria(page, '[data-model-menu]', scaffold.workspaceCwd) await toggle.click() const dialog = page.getByRole('dialog', { name: '确认关闭智能体团队协作?', exact: true }) await dialog.waitFor() diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md index c48d2d2ab0..ceb1d1097a 100644 --- a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -1,6 +1,6 @@ ## Menu -- menu "智能体团队协作": +- group "智能体团队协作": - text: 开启智能体团队协作 - switch "开启智能体团队协作" [checked] - paragraph: 通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。 diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md index d1171d7e32..23af3abb18 100644 --- a/apps/web/tests/snapshots/agent-team-panel/info.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -6,7 +6,7 @@ ## Team settings -- menu "Agent teamwork": +- group "Agent teamwork": - text: Enable agent teamwork - switch "Enable agent teamwork" - paragraph: Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs. diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml index 0b307a4d15..d4db291eb9 100644 --- a/packages/client/ui-agent-team/README.i18n.yaml +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-agent-team/use-this-package: - en: c5fe6c80b2979db7 - zh: 6f4640b369c9d22a + en: 39906df046b7fa3b + zh: 9a79438ab5c0811f /deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: en: 2f606827b3ab14bc zh: 7f713d10268e7498 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md index b5a3b9ff52..d6dbd2a057 100644 --- a/packages/client/ui-agent-team/README.md +++ b/packages/client/ui-agent-team/README.md @@ -25,7 +25,7 @@ This package displays shared tasks below the Subagent tree in one header panel. ## Use this package -In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings page shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text, without an information tooltip. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. +In the root conversation’s model and reasoning menu, select **Agent teamwork** to open its settings page, then turn on **Enable agent teamwork**. The root row shows the saved On/Off state without changing it. The settings page shows the switch above the shared-task coordination, complex-task results, and token-cost explanation as ordinary text that describes the switch, without an information tooltip. Opening the page focuses the enabled switch. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire switch row highlights on hover and toggles the selection when clicked. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md index 650a9f2b63..e3ce5014d4 100644 --- a/packages/client/ui-agent-team/README.zh.md +++ b/packages/client/ui-agent-team/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置页将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,不使用信息 tooltip。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 +在根会话的模型与推理等级菜单中选择**智能体团队协作**,进入二级设置页后打开**开启智能体团队协作**。一级行显示已保存的开启/关闭状态,不改变选择。设置页将开关放在共享任务协调、复杂任务效果与 token 开销的说明上方;说明使用普通正文,并作为开关的描述,不使用信息 tooltip。打开设置页时聚焦可用的开关。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。开关所在整行在悬停时高亮,点击可切换状态。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。 会话记录过模型请求后,从菜单开关关闭团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css index b312ccfce5..f05212b2d6 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -54,7 +54,6 @@ .page { display: flex; flex-direction: column; - gap: 0; min-width: 0; } diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx index 90cfc4ebcd..aff18015a7 100644 --- a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -1,6 +1,6 @@ /** Session-owned Agent Teams summary and settings inside the model menu. */ -import { useState } from 'react' +import { useId, useState } from 'react' import { IconChevronRightOutlineRegular, Switch } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' @@ -74,6 +74,7 @@ function RootTeamModePage({ const mode = useProjection('agentTeam') const modelSelection = useProjection('modelSelection') const [pending, setPending] = useState(false) + const descriptionId = useId() if (mode === undefined) return null const select = (enabled: boolean): void => { if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { @@ -92,9 +93,9 @@ function RootTeamModePage({
{t('mode.label')} - +
-

{t('mode.description')}

+

{t('mode.description')}

) } diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx index d1c1b40aa3..11d0a253b2 100644 --- a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -110,7 +110,8 @@ it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dic expect(description.tagName).toBe('P') expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() expect(screen.queryByRole('button')).toBeNull() - const toggle = screen.getByRole('switch', { name: dictionary['mode.label'] }) + const toggle = screen.getByRole('switch', { name: dictionary['mode.label'], description: dictionary['mode.description'] }) + expect(document.activeElement === toggle).toBe(!locked) expect(toggle.compareDocumentPosition(description) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() expect(toggle.hasAttribute('disabled')).toBe(locked) expect(toggle.getAttribute('aria-checked')).toBe('false') diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index 334d05939c..a3a5c13bdf 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 6f790bbbca533c64 - zh: c46d46a94a34dc2c + en: 353daeed6290d445 + zh: b5f0febc130c8a8b /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: en: c1d14a925c92950f zh: f80f8169bc283c60 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index f5077d3c21..27a6529389 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -61,7 +61,7 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. -The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPage({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.page` slot; the invoking button's `data-model-menu-page` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail pages share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu uses `title` as the accessible page name and focuses its first enabled switch on entry. Escape returns focus to the invoking row; Tab closes a detail page without activating its switch. +The session-scoped `conversation.input.model.options` list appends root controls below model and reasoning options. Entries call `openPage({ key, title })` to show content registered in the session-scoped keyed `conversation.input.model.page` slot; the invoking button's `data-model-menu-page` must match the key. Root and detail entries receive `locked`, `reportFailure(message)`, and `dismiss()`: the lock includes model or effort saves, failures use the menu owner's toast, and dismissal focuses its trigger synchronously before another overlay opens. Contributing plugins own settings and confirmation logic. Root and detail pages share a 240px width within 12px viewport insets; model and effort lists remain content-sized. The menu exposes a detail page as a group named by `title`; the page places its own initial focus, and focus otherwise stays on the menu surface. Escape returns focus to the invoking row; Tab closes a detail page without activating its switch. ----- diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index fd870fe115..7337e1136c 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -61,7 +61,7 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 -会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPage({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.page` 的内容;入口按钮的 `data-model-menu-page` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级页共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单以 `title` 作为页面无障碍名称,进入时聚焦首个可用开关。Escape 将焦点还给入口行;Tab 关闭二级页而不激活开关。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。贡献项调用 `openPage({ key, title })`,显示注册到会话级 keyed slot `conversation.input.model.page` 的内容;入口按钮的 `data-model-menu-page` 必须与注册键一致。一级与二级贡献项均收到 `locked`、`reportFailure(message)` 和 `dismiss()`:锁定包含模型或推理等级保存中状态,失败由菜单宿主的 toast 提示,关闭时同步聚焦触发按钮,供贡献方随后打开其他浮层。设置与确认逻辑由贡献插件负责。一级与二级页共用 240px 宽度,并保持视口两侧的 12px 边距;模型与推理等级列表仍按内容定宽。菜单把二级页呈现为以 `title` 命名的分组;页面自行设置初始焦点,未设置时焦点停留在菜单容器上。Escape 将焦点还给入口行;Tab 关闭二级页而不激活开关。 ----- diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index 0b4734d324..f062b4d8ba 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -40,12 +40,23 @@ import { IconDataOutlineRegular, IconWarningOutlineRegular, Input, isMobileDevice, rankByName, StateDot, Tag, Toast, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type { ModelLabelOwner, ModelMenuControls, ModelMenuPage, ModelSelectInjected } from './slots.ts' +import type { ModelLabelOwner, ModelMenuControls, ModelMenuPageRef, ModelSelectInjected } from './slots.ts' import css from './ModelSelect.module.css' import { orderModelProviders } from './provider-order.ts' -/** Which pane the dropdown shows: the two-row root or one drilled-in list. */ -type Pane = 'root' | 'model' | 'effort' | ModelMenuPage +/** Which pane the dropdown shows: the root menu, one drilled-in list, or a plugin-owned detail page. */ +type Pane = + | { kind: 'root' } + | { kind: 'model' } + | { kind: 'effort' } + | { kind: 'page'; page: ModelMenuPageRef } + +/** Any pane reached by drilling from the root menu. */ +type DrilledPane = Exclude + +const ROOT_PANE: Pane = { kind: 'root' } +const MODEL_PANE: DrilledPane = { kind: 'model' } +const EFFORT_PANE: DrilledPane = { kind: 'effort' } /** One dynamic effort row; undefined means preserve the provider default. */ interface EffortChoice { @@ -70,7 +81,7 @@ export function ModelSelect( () => directory.getSnapshot(), ) const [open, setOpen] = useState(false) - const [pane, setPane] = useState('root') + const [pane, setPane] = useState(ROOT_PANE) const [query, setQuery] = useState('') const [highlightedIndex, setHighlightedIndex] = useState(null) const [selectionFocus, setSelectionFocus] = useState(false) @@ -163,8 +174,13 @@ export function ModelSelect( if (menuRef.current?.contains(event.target as Node) === true) return setOpen(false) } + // WebKit touch taps on non-clickable areas dispatch pointerdown without mousedown. + document.addEventListener('pointerdown', closeOutside) document.addEventListener('mousedown', closeOutside) - return () => { document.removeEventListener('mousedown', closeOutside) } + return () => { + document.removeEventListener('pointerdown', closeOutside) + document.removeEventListener('mousedown', closeOutside) + } }, [open]) useLayoutEffect(() => { @@ -176,21 +192,22 @@ export function ModelSelect( // Pane switches unmount the focused row; restore focus inside the menu so // keyboard navigation remains available. - const paneFocus = useRef<'drill' | Exclude | null>(null) + const paneFocus = useRef<'drill' | DrilledPane | null>(null) const previousShowSearch = useRef(showSearch) useEffect(() => { const changedSearchMode = previousShowSearch.current !== showSearch previousShowSearch.current = showSearch - const intent = paneFocus.current ?? (changedSearchMode && pane === 'model' ? 'drill' : null) + const intent = paneFocus.current ?? (changedSearchMode && pane.kind === 'model' ? 'drill' : null) paneFocus.current = null if (!open || intent === null) return if (intent === 'drill') { - if (typeof pane === 'object') { - const first = menuRef.current?.querySelector('[role="switch"]:not([disabled])') - ;(first ?? menuRef.current ?? triggerRef.current)?.focus() + if (pane.kind === 'page') { + // A detail page places its own initial focus (autoFocus commits before + // this effect); otherwise the surface keeps the menu's keys reachable. + if (menuRef.current?.contains(document.activeElement) !== true) (menuRef.current ?? triggerRef.current)?.focus() return } - if (pane === 'model' && showSearch && !isMobileDevice()) { + if (pane.kind === 'model' && showSearch && !isMobileDevice()) { searchRef.current?.focus() return } @@ -203,10 +220,10 @@ export function ModelSelect( ;(target ?? triggerRef.current)?.focus() return } - const cell = typeof intent === 'object' + const cell = intent.kind === 'page' ? Array.from(menuRef.current?.querySelectorAll('[data-model-menu-page]') ?? []) - .find(button => button.dataset.modelMenuPage === intent.key) - : itemRefs.current[intent === 'effort' ? 1 : 0] + .find(button => button.dataset.modelMenuPage === intent.page.key) + : itemRefs.current[intent.kind === 'effort' ? 1 : 0] ;(cell !== null && cell !== undefined && !cell.disabled ? cell : triggerRef.current)?.focus() }, [open, pane, showSearch]) @@ -217,7 +234,7 @@ export function ModelSelect( }, [available, open, pane, filteredGroups]) useLayoutEffect(() => { - if (open && pane === 'model' && activeModelIndex >= 0) { + if (open && pane.kind === 'model' && activeModelIndex >= 0) { itemRefs.current[activeModelIndex]?.scrollIntoView({ block: 'nearest' }) } }, [open, pane, activeModelIndex, visibleModels]) @@ -230,7 +247,7 @@ export function ModelSelect( setQuery('') setHighlightedIndex(null) if (currentChoice === undefined) paneFocus.current = 'drill' - setPane(currentChoice === undefined ? 'model' : 'root') + setPane(currentChoice === undefined ? MODEL_PANE : ROOT_PANE) setOpen(true) reload() } @@ -242,7 +259,7 @@ export function ModelSelect( const close = (restoreFocus = false): void => { setOpen(false) - setPane('root') + setPane(ROOT_PANE) if (restoreFocus) queueMicrotask(() => { triggerRef.current?.focus() }) } @@ -251,7 +268,7 @@ export function ModelSelect( close(true) } - const drill = (next: Pane): void => { + const drill = (next: DrilledPane): void => { setQuery('') setHighlightedIndex(null) paneFocus.current = 'drill' @@ -259,9 +276,9 @@ export function ModelSelect( } /** Leave a drilled pane for the root one, handing the keyboard back to its cell. */ - const back = (from: Exclude): void => { + const back = (from: DrilledPane): void => { paneFocus.current = from - setPane('root') + setPane(ROOT_PANE) } const controls: ModelMenuControls = { @@ -293,17 +310,17 @@ export function ModelSelect( if (event.key === 'Escape' && open) { event.preventDefault() // Escape backs out of a drilled pane first, then closes. - if (typeof pane === 'object' || (pane !== 'root' && currentChoice !== undefined)) back(pane) + if (pane.kind === 'page' || (pane.kind !== 'root' && currentChoice !== undefined)) back(pane) else close(true) return } if (!open) return - if (typeof pane === 'object' && event.key === 'Tab') { + if (pane.kind === 'page' && event.key === 'Tab') { event.preventDefault() close(true) return } - if (pane === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { + if (pane.kind === 'model' && showSearch && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) { event.preventDefault() if (!busy && visibleModels.length > 0) { const direction = event.key === 'ArrowDown' ? 1 : -1 @@ -312,7 +329,7 @@ export function ModelSelect( } return } - if (pane === 'model' && showSearch && event.target instanceof HTMLInputElement + if (pane.kind === 'model' && showSearch && event.target instanceof HTMLInputElement && (event.key === 'Enter' || (event.key === 'Tab' && !event.shiftKey))) { if (event.key === 'Tab' && visibleModels.length === 0) return event.preventDefault() @@ -326,7 +343,7 @@ export function ModelSelect( if (event.key === 'Tab') { if (event.shiftKey) { event.preventDefault() - if (pane !== 'root' && currentChoice !== undefined) back(pane) + if (pane.kind !== 'root' && currentChoice !== undefined) back(pane) else close(true) return } @@ -345,7 +362,7 @@ export function ModelSelect( } if (focused !== triggerRef.current) return event.preventDefault() - if (pane === 'model' && showSearch) { + if (pane.kind === 'model' && showSearch) { setHighlightedIndex(null) searchRef.current?.focus() return @@ -362,7 +379,7 @@ export function ModelSelect( const onBlur = (event: FocusEvent): void => { // Clicking explanation text can clear focus without leaving its page. - if (typeof pane === 'object' && event.relatedTarget === null) return + if (pane.kind === 'page' && event.relatedTarget === null) return if (event.relatedTarget instanceof Node && ( rootRef.current?.contains(event.relatedTarget) === true || menuRef.current?.contains(event.relatedTarget) === true @@ -503,17 +520,19 @@ export function ModelSelect( {open && createPortal( - {pane === 'root' && ( + {pane.kind === 'root' && ( <> - {reasoning !== undefined && ( - )} - {renderSlot('conversation.input.model.options', { ...controls, openPage: drill })} + {renderSlot('conversation.input.model.options', { ...controls, openPage: (page) => { drill({ kind: 'page', page }) } })} )} - {pane === 'model' && ( + {pane.kind === 'model' && ( <> {showSearch &&
)} - {pane === 'effort' && ( + {pane.kind === 'effort' && ( <> {state.error !== null && lastActionRef.current === 'load' && (
@@ -670,9 +689,9 @@ export function ModelSelect(
)} - {typeof pane === 'object' && ( + {pane.kind === 'page' && (
- {renderSlot('conversation.input.model.page', controls, { entryKey: pane.key })} + {renderSlot('conversation.input.model.page', controls, { entryKey: pane.page.key })}
)} , diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 491cb030f8..3f1670f236 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -17,8 +17,8 @@ export interface ModelLabelOwner { selected: boolean } -/** A keyed contribution displayed as a second page of the model menu. */ -export interface ModelMenuPage { +/** Data identifying a keyed contribution displayed as a second page of the model menu. */ +export interface ModelMenuPageRef { /** Registration key in conversation.input.model.page; also marks its root button's data-model-menu-page. */ key: string /** Localized accessible name of the detail page. */ @@ -41,7 +41,7 @@ export type ModelMenuOptions = ModelMenuControls & { * Open page.key in conversation.input.model.page with page.title as its localized accessible name. * The root button's data-model-menu-page must match page.key for focus return. */ - openPage: (page: ModelMenuPage) => void + openPage: (page: ModelMenuPageRef) => void } declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -52,7 +52,11 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { scope: 'session' owner: ModelMenuOptions } - /** Plugin-owned content displayed as a model-menu detail page. */ + /** + * Plugin-owned content displayed as a model-menu detail page. + * The page places its own initial focus, for example with `autoFocus`; without one, + * focus stays on the menu surface, where Escape and Shift+Tab still return to the root menu. + */ 'conversation.input.model.page': { kind: 'keyed' scope: 'session' diff --git a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx index 126d89c119..c37e850291 100644 --- a/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-menu-page.client.spec.tsx @@ -11,7 +11,7 @@ import { en } from '../src/client/locales.ts' afterEach(cleanup) -function setup() { +function setup(autoFocus = true) { const directory = createSnapshotStore({ current: { provider: 'fixture', model: 'fixture' }, routable: true, groups: [{ id: 'fixture', name: 'Fixture', models: [{ id: 'fixture', name: 'Fixture' }] }], @@ -29,7 +29,7 @@ function setup() { const controls = owner as object as OwnerOf<'conversation.input.model.page'> expect(options?.entryKey).toBe('fixture') return <>

Fixture explanation

+ autoFocus={autoFocus} onClick={change}>Fixture setting

Fixture explanation

} return options?.fallback ?? null } @@ -45,7 +45,7 @@ it('dispatches a keyed page and returns focus to its invoking summary on Escape' fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) const toggle = screen.getByRole('switch') expect(document.activeElement).toBe(toggle) - expect(screen.getByRole('menu', { name: 'Fixture settings' })).toBeTruthy() + expect(screen.getByRole('group', { name: 'Fixture settings' })).toBeTruthy() fireEvent.blur(toggle, { relatedTarget: null }) expect(screen.getByText('Fixture explanation')).toBeTruthy() fireEvent.keyDown(toggle, { key: 'Escape' }) @@ -57,6 +57,25 @@ it('dispatches a keyed page and returns focus to its invoking summary on Escape' expect(select).not.toHaveBeenCalled() }) +it('keeps focus on the page surface when the page places none, so Escape still returns', () => { + setup(false) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + const surface = screen.getByRole('group', { name: 'Fixture settings' }) + expect(document.activeElement).toBe(surface) + fireEvent.keyDown(surface, { key: 'Escape' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Fixture settings' })) +}) + +it('closes a detail page on an outside touch press that dispatches no mousedown', () => { + const { trigger } = setup() + fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) + fireEvent.blur(screen.getByRole('switch'), { relatedTarget: null }) + fireEvent.pointerDown(screen.getByText('Fixture explanation')) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + fireEvent.pointerDown(document.body) + expect(trigger.getAttribute('aria-expanded')).toBe('false') +}) + it.each([false, true])('closes a detail page on Tab without changing its setting (shift: %s)', async (shiftKey) => { const { trigger, change } = setup() fireEvent.click(screen.getByRole('menuitem', { name: 'Fixture settings' })) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 662fc787a4..ab419ad832 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: ead6be55c7c9d7cf zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 54c5085d03bf4c53 - zh: 6b5114206ca545f3 + en: 11686b52743a702d + zh: d865bb79d8f56ee1 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: 8265fa792c6fd9ec zh: 600d2af4d5a3d183 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 5c817b94b2..87d319ed09 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -43,7 +43,7 @@ Check this table before writing a control in a feature package. A plugin cannot | Export | What it is | |---|---| | `Button` | Clickable action; `variant` selects `primary`, `ghost`, `outline`, or `toolbar`. Outlined actions use an inset hairline. Its ref targets the native button for focus and overlay anchoring. | -| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. | +| `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. Optional `autoFocus` and `describedBy` forward to the native button. | | `SegmentedControl` | Tablist of two or more equal-width segments with one sliding indicator, for switching a card or panel between a few modes; the owner holds the selection and `label` names the list. `id` seeds each tab's id (`-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index f3e1c1719a..a7258c74dc 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -43,7 +43,7 @@ kind: "package-library" | 导出 | 是什么 | |---|---| | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | -| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | +| `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。可选的 `autoFocus` 与 `describedBy` 直接传给原生按钮。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | diff --git a/packages/client/ui-primitives/src/Switch.tsx b/packages/client/ui-primitives/src/Switch.tsx index 980a08f6be..8816e1975a 100644 --- a/packages/client/ui-primitives/src/Switch.tsx +++ b/packages/client/ui-primitives/src/Switch.tsx @@ -13,9 +13,11 @@ import css from './Switch.module.css' * while a write is in flight, not only when a deployment locks the toggle. * @param props.title - localized hover text, typically why the toggle is locked. * @param props.className - extra class for layout placement. + * @param props.autoFocus - whether the control takes focus when it mounts enabled. + * @param props.describedBy - id of the element that describes the control. * @returns the switch element. */ -export function Switch({ checked, onChange, label, disabled = false, title, className }: { +export function Switch({ checked, onChange, label, disabled = false, title, className, autoFocus, describedBy }: { checked: boolean onChange: (next: boolean) => void label: string @@ -24,6 +26,8 @@ export function Switch({ checked, onChange, label, disabled = false, title, clas // `| undefined` so a caller can forward an optional class straight through // under exactOptionalPropertyTypes (a CSS-module lookup is string|undefined). className?: string | undefined + autoFocus?: boolean + describedBy?: string | undefined }) { return (