fix(client): clarify context menu ownership and render icon groups
This commit is contained in:
1 parent
6f8c0a55d1
commit
076b0e5881
68 files changed
+821
-383
No files matched your search
@@ -66,8 +66,8 @@
|
||||
en: 182a9c6705213e13
|
||||
zh: 681762f83490f4c6
|
||||
/deepseek-harness-desktop/updates/local-updater-qualification:
|
||||
en: 939fd8795e9609cd
|
||||
zh: a54564960c638321
|
||||
en: 4127e6a9824d6b85
|
||||
zh: a52b3cc634528bb6
|
||||
/deepseek-harness-desktop/low-level-development-overrides:
|
||||
en: 8264b135871e8978
|
||||
zh: 0939aafb1b2961fc
|
||||
|
||||
@@ -356,7 +356,7 @@ The command builds the Desktop shell and runs its coordinator with real Electron
|
||||
|
||||
The downloaded bytes are inert, and the installation call is recorded rather than executed. The test substitutes browser opening and clipboard writing to avoid external navigation and clipboard changes. It does not boot the full product workspace, qualify a real installer or restart, verify publisher signatures, or exercise differential updates or macOS. Stalled policy requests, feed requests, and payload transfers exercise real deadlines and recovery. The actual ordinary dialog verifies isolated preload loading, card geometry, an unfiltered parent page, cancellation, task-warning choices, and explicit installation approval; account-row component tests provide separate evidence. The [local qualification decision](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.md) and [verification record](tests/README.md) preserve these limits; production release requirements remain unchanged.
|
||||
|
||||
Native original-file operations accept only the trusted application frame. Saved paths stay in the main process and references expire on window reload or close. Remote image reads omit credentials, validate every redirect, reject the application Host and its loopback aliases, stop on main-frame navigation, and use `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS` (30000 ms) and `DSH_DESKTOP_IMAGE_READ_MAX_BYTES` (67108864 bytes). Image clipboard input uses the same byte limit. Other reachable HTTP(S) destinations follow deployment network isolation. [File actions](../../packages/client/ui-file-actions/README.md) defines saving and clipboard behavior.
|
||||
Native original-file operations accept only the trusted application frame. Saved paths stay in the main process and references expire on window reload or close. Remote image reads omit credentials, validate every redirect, reject the application Host and its loopback aliases, stop on main-frame navigation, and use `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS` (30000 ms) and `DSH_DESKTOP_IMAGE_READ_MAX_BYTES` (67108864 bytes). Image copying uses the renderer Clipboard API after PNG conversion. Other reachable HTTP(S) destinations follow deployment network isolation. [File actions](../../packages/client/ui-file-actions/README.md) defines saving and clipboard behavior.
|
||||
|
||||
<a id="low-level-development-overrides"></a>
|
||||
|
||||
|
||||
@@ -356,7 +356,7 @@ node apps/desktop/node_modules/pnpm/bin/pnpm.mjs --dir apps/desktop run test:upd
|
||||
|
||||
下载内容是不可执行的测试字节,安装调用仅记录而不执行。测试替换浏览器打开与剪贴板写入,避免外部导航和剪贴板修改。它不启动完整产品工作区,不验证真实安装器或重启,不验证发布者签名,也不覆盖差分更新或 macOS。停滞的策略请求、清单请求和负载传输会执行真实截止时间及恢复。真实常规弹窗验证隔离预加载、卡片尺寸、未施加模糊的父页面、取消、任务警告选项与显式安装批准;账户行组件测试另行提供证据。[本地验证决策](../../.agents/notes/implemented/testing/2026-09-10-desktop-local-updater-qualification.zh.md)和[验证记录](tests/README.zh.md)保留这些限制;生产发布要求保持不变。
|
||||
|
||||
原生原始文件操作仅接受可信应用页面。保存路径保留在主进程,窗口刷新或关闭后引用失效。远程图片读取不携带凭据,逐次校验重定向,拒绝应用 Host 及其回环别名,在主框架导航时终止,并使用 `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS`(30000 毫秒)与 `DSH_DESKTOP_IMAGE_READ_MAX_BYTES`(67108864 字节)。图片剪贴板输入使用相同的字节上限。其他可达的 HTTP(S) 目标遵循部署侧网络隔离。[文件操作](../../packages/client/ui-file-actions/README.zh.md) 定义保存和剪贴板行为。
|
||||
原生原始文件操作仅接受可信应用页面。保存路径保留在主进程,窗口刷新或关闭后引用失效。远程图片读取不携带凭据,逐次校验重定向,拒绝应用 Host 及其回环别名,在主框架导航时终止,并使用 `DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS`(30000 毫秒)与 `DSH_DESKTOP_IMAGE_READ_MAX_BYTES`(67108864 字节)。图片复制在转换为 PNG 后使用渲染进程的 Clipboard API。其他可达的 HTTP(S) 目标遵循部署侧网络隔离。[文件操作](../../packages/client/ui-file-actions/README.zh.md) 定义保存和剪贴板行为。
|
||||
|
||||
<a id="low-level-development-overrides"></a>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Trusted-window original-file saves and clipboard transfers. Saved paths stay in the main process. */
|
||||
import { app, clipboard, ClipboardItem, dialog, ipcMain, nativeImage, shell } from 'electron'
|
||||
/** Trusted-window original-file saves and image reads. Saved paths stay in the main process. */
|
||||
import { app, dialog, ipcMain, shell } from 'electron'
|
||||
import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
|
||||
import { open, rename, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { basename, dirname, extname, join } from 'node:path'
|
||||
@@ -103,13 +103,6 @@ export function installFileActions(
|
||||
assertOwner(event)
|
||||
shell.showItemInFolder(entry.path)
|
||||
})
|
||||
ipcMain.handle(DESKTOP_IPC.imageCopy, async (event, bytes: unknown) => {
|
||||
assertOwner(event)
|
||||
if (!(bytes instanceof Uint8Array) || bytes.byteLength > maxBytes) throw new Error('Invalid clipboard image')
|
||||
const image = nativeImage.createFromBuffer(Buffer.from(bytes))
|
||||
if (image.isEmpty()) throw new Error('Image cannot be decoded')
|
||||
await clipboard.write([new ClipboardItem({ 'image/png': new Blob([new Uint8Array(image.toPNG())]) })])
|
||||
})
|
||||
ipcMain.handle(DESKTOP_IPC.imageRead, async (event, value: unknown) => {
|
||||
const owner = assertOwner(event)
|
||||
if (typeof value !== 'string') throw new Error('Invalid image URL')
|
||||
|
||||
@@ -8,8 +8,9 @@ import type { DesktopFileDrag } from '@deepseek-ai/dsh-util-file-drag'
|
||||
|
||||
/** IPC channel names kept private to the desktop application bundle. */
|
||||
export const DESKTOP_IPC = {
|
||||
fileSave: 'dsh-desktop:file-save', fileReveal: 'dsh-desktop:file-reveal',
|
||||
imageCopy: 'dsh-desktop:image-copy', imageRead: 'dsh-desktop:image-read',
|
||||
fileSave: 'dsh-desktop:file-save',
|
||||
fileReveal: 'dsh-desktop:file-reveal',
|
||||
imageRead: 'dsh-desktop:image-read',
|
||||
shortcutsInput: 'dsh-desktop:shortcuts-input',
|
||||
shortcutsCloseWindow: 'dsh-desktop:shortcuts-close-window',
|
||||
shortcutsGet: 'dsh-desktop:shortcuts-get',
|
||||
|
||||
@@ -18,7 +18,6 @@ function createProductApi(): DshDesktopProductApi {
|
||||
fileActions: {
|
||||
save: request => ipcRenderer.invoke(DESKTOP_IPC.fileSave, request) as Promise<FileSaveResult>,
|
||||
reveal: id => ipcRenderer.invoke(DESKTOP_IPC.fileReveal, id) as Promise<void>,
|
||||
copyImage: bytes => ipcRenderer.invoke(DESKTOP_IPC.imageCopy, bytes) as Promise<void>,
|
||||
readImage: url => ipcRenderer.invoke(DESKTOP_IPC.imageRead, url) as Promise<{ bytes: Uint8Array; mediaType: string }>,
|
||||
},
|
||||
browser: createDesktopBrowserBridge(),
|
||||
|
||||
@@ -10,8 +10,7 @@ import { DESKTOP_IPC } from '../src/ipc.ts'
|
||||
|
||||
const electron = vi.hoisted(() => ({
|
||||
app: { getPath: vi.fn() }, ipcMain: { handle: vi.fn() }, dialog: { showSaveDialog: vi.fn() },
|
||||
shell: { showItemInFolder: vi.fn() }, nativeImage: { createFromBuffer: vi.fn() }, clipboard: { write: vi.fn() },
|
||||
ClipboardItem: class { constructor(readonly content: object) {} },
|
||||
shell: { showItemInFolder: vi.fn() },
|
||||
}))
|
||||
vi.mock('electron', () => electron)
|
||||
const roots: string[] = []
|
||||
@@ -96,7 +95,7 @@ it('preserves saved references across iframe and same-document navigation', asyn
|
||||
f.owner.emit('closed')
|
||||
})
|
||||
|
||||
it('rejects redirects to the application Host and bounds clipboard decoding', async () => {
|
||||
it('rejects redirects to the application Host', async () => {
|
||||
const root = await directory()
|
||||
const owner = Object.assign(new EventEmitter(), { webContents: new EventEmitter(), isDestroyed: () => false })
|
||||
installFileActions(() => owner as BrowserWindow, () => 'http://127.0.0.1:19321')
|
||||
@@ -107,7 +106,5 @@ it('rejects redirects to the application Host and bounds clipboard decoding', as
|
||||
const event = {} as IpcMainInvokeEvent
|
||||
await expect(handler(DESKTOP_IPC.imageRead)(event, 'https://images.example/photo')).rejects.toThrow('Invalid image URL')
|
||||
expect(fetchImage).toHaveBeenCalledOnce()
|
||||
await expect(handler(DESKTOP_IPC.imageCopy)(event, new Uint8Array(64 * 1024 * 1024 + 1))).rejects.toThrow('Invalid clipboard image')
|
||||
expect(electron.nativeImage.createFromBuffer).not.toHaveBeenCalled()
|
||||
expect(await readdir(root)).toEqual([])
|
||||
})
|
||||
@@ -38,18 +38,16 @@ it('exposes onboarding size activation to the application document', async () =>
|
||||
expect(electron.ipcRenderer.send.mock.calls).toEqual([[DESKTOP_IPC.onboardingActive, true], [DESKTOP_IPC.onboardingActive, false]])
|
||||
})
|
||||
|
||||
it('routes original-file and clipboard requests through the trusted application bridge', async () => {
|
||||
it('routes original-file requests through the trusted application bridge', async () => {
|
||||
vi.stubGlobal('location', new URL('dsh-app://app/'))
|
||||
await import('../src/preload-app.ts')
|
||||
const api = electron.contextBridge.exposeInMainWorld.mock.calls.find(([name]) => name === 'dshDesktop')?.[1] as DshDesktopProductApi
|
||||
const request = { bytes: new Uint8Array([1, 2]), name: 'image.gif', mode: 'download' as const }
|
||||
await api.fileActions.save(request)
|
||||
await api.fileActions.readImage('https://images.example/original.gif')
|
||||
await api.fileActions.copyImage(request.bytes)
|
||||
expect(electron.ipcRenderer.invoke.mock.calls).toEqual([
|
||||
[DESKTOP_IPC.fileSave, request],
|
||||
[DESKTOP_IPC.imageRead, 'https://images.example/original.gif'],
|
||||
[DESKTOP_IPC.imageCopy, request.bytes],
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -144,9 +144,11 @@ describe('web context menus', () => {
|
||||
await page.keyboard.press('Shift+F10')
|
||||
await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).waitFor()
|
||||
await page.keyboard.press('End')
|
||||
await page.keyboard.press('ArrowUp')
|
||||
const saveAs = page.getByRole('menuitem', { name: 'Save as…', exact: true })
|
||||
if (!await saveAs.isDisabled()) await page.keyboard.press('ArrowUp')
|
||||
expect(await page.getByRole('menuitem', { name: 'Copy file path', exact: true }).evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await page.keyboard.press('Enter')
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(join(scaffold.workspaceCwd, 'first.txt'))
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(join(scaffold.workspaceCwd, 'first.txt'))
|
||||
expect(await file.evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.style.setProperty('--dsh-frame-overlay-top', '100px')
|
||||
|
||||
@@ -99,6 +99,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| Event string | Dispatchers | Listeners |
|
||||
| --- | --- | --- |
|
||||
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) |
|
||||
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
|
||||
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
|
||||
@@ -106,7 +107,9 @@ This matrix shows which packages dispatch each harness-owned event and which pac
|
||||
| `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) |
|
||||
| `internal/update` | - | [`app-boot`](../packages/boot/app-boot) |
|
||||
| `loader/volatile-update` | - | [`cua`](../packages/experimental/cua), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` |
|
||||
| `locale/change` | `locale` (`emit`) | `locale` |
|
||||
| `slots/changed` | `ui-renderer` (`emit`) | - |
|
||||
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
|
||||
<!-- END GENERATED event-producer-consumer:undeclared -->
|
||||
|
||||
Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program.
|
||||
@@ -101,6 +101,7 @@
|
||||
| Event string | Dispatchers | Listeners |
|
||||
| --- | --- | --- |
|
||||
| `agent/request` | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic) |
|
||||
| `connection/reset` | `gateway` (`emit`) | `terminal-controller`, `ui-settings` |
|
||||
| `internal/config` | - | [`llm-pi-ai`](../packages/llm/llm-pi-ai) |
|
||||
| `internal/dispatch` | - | [`terminal-bash`](../packages/terminal/terminal-bash) |
|
||||
| `internal/plugin` | - | `computer-use-cua-driver-native`, `inspector`, `loader`, [`lsp-stdio`](../packages/lsp/lsp-stdio), [`mcp-client`](../packages/mcp/mcp-client), `modules` |
|
||||
@@ -108,7 +109,9 @@
|
||||
| `internal/status` | - | [`agent`](../packages/core/agent), `inspector`, `translator`, [`web`](../packages/web/web) |
|
||||
| `internal/update` | - | [`app-boot`](../packages/boot/app-boot) |
|
||||
| `loader/volatile-update` | - | [`cua`](../packages/experimental/cua), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`plugin-market`](../packages/boot/plugin-market), `product-analytics`, `speech-to-text` |
|
||||
| `locale/change` | `locale` (`emit`) | `locale` |
|
||||
| `slots/changed` | `ui-renderer` (`emit`) | - |
|
||||
| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` |
|
||||
<!-- END GENERATED event-producer-consumer:undeclared -->
|
||||
|
||||
Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program.
|
||||
@@ -21,8 +21,8 @@
|
||||
en: cbf1f0a2205046a5
|
||||
zh: 2e59d0815351349f
|
||||
/deepseek-ai-dsh-client-ui-chat/command-and-failure-rows:
|
||||
en: 5ada67393e11644f
|
||||
zh: 30f6538942dd742b
|
||||
en: 38e9af25761d8860
|
||||
zh: aab4c04d43520460
|
||||
/deepseek-ai-dsh-client-ui-chat/turn-token-usage:
|
||||
en: cfdfe3d99d3f4e09
|
||||
zh: 9330bad3d3f7a689
|
||||
@@ -36,8 +36,8 @@
|
||||
en: a14c74ed7de0ef9c
|
||||
zh: d5e618b2ef809150
|
||||
/deepseek-ai-dsh-client-ui-chat/scroll-ownership:
|
||||
en: 3c437cbcc09621d8
|
||||
zh: 17830fa01842143a
|
||||
en: 461cd577ac6d5e5b
|
||||
zh: a17a833e069cbfe4
|
||||
/deepseek-ai-dsh-client-ui-chat/model-experience:
|
||||
en: c17b4dd43a61c569
|
||||
zh: f7414309810c3a08
|
||||
|
||||
@@ -61,7 +61,7 @@ When an Assistant attempt retires without a visible message, Chat hides its alre
|
||||
|
||||
Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions this Client has bound and materialized publish; quota failures in Sessions it never opened do not. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped.
|
||||
|
||||
Reference and tool-file context gestures use the recorded target path rather than its display label. Shift+F10 and the context key open the focused reference menu; images and editable controls keep their own handlers.
|
||||
Reference and tool-file components declare their context-menu targets through the scoped delegate, using the recorded path rather than a display label. Chat supplies Session and path context without interpreting plugin DOM attributes or undeclared links. Shift+F10 and the context key open the focused reference menu; images and editable controls keep their own handlers.
|
||||
|
||||
-----
|
||||
|
||||
@@ -182,7 +182,7 @@ The Chat view detects selection and context-menu gestures on business nodes mark
|
||||
|
||||
`ctx.uiConversation.interactions` dispatches eligible gestures to plugin registrations and supplies their component to the Chat view. The action surface is absolutely positioned inside the existing Chat column, above the composer seat and its dock. Its wrapper preserves the component's outer stroke and shadow; components own internal scrolling. Scrolling the selection outside that visible region temporarily hides the surface; returning restores it. Chat owns viewport visibility, placement, outside pointer presses, Escape, new selections, source invalidation, and disposal; explicit dismissal preserves browser selection and layout changes do not reopen the surface. [Message quotes](../../session/message-quotes/README.md) owns quotation eligibility and insertion.
|
||||
|
||||
Markdown files, links, and images forward explicit right-click targets to [ui-context-menu](../ui-context-menu/README.md). File targets retain their working directory and line; ordinary link clicks retain the configured opening preference.
|
||||
Markdown files, links, images, reference chips, and tool-file controls forward explicit right-click targets to [ui-context-menu](../ui-context-menu/README.md). File targets retain their working directory and line; ordinary link clicks retain the configured opening preference.
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
@@ -61,7 +61,7 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node,
|
||||
|
||||
通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有本 Client 已绑定并已物化的 Session 会发布提示;它从未打开的 Session 中的欠费不会发布。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。
|
||||
|
||||
引用与工具文件的右键操作使用记录的目标路径,而非显示标签。Shift+F10 和菜单键打开已聚焦引用的菜单;图片与可编辑控件保留自己的处理器。
|
||||
引用与工具文件组件通过作用域内的委托声明右键菜单目标,使用记录的路径而非显示标签。Chat 提供 Session 与路径上下文,不解释插件 DOM 属性或未声明的链接。Shift+F10 和菜单键打开已聚焦引用的菜单;图片与可编辑控件保留自己的处理器。
|
||||
|
||||
-----
|
||||
|
||||
@@ -182,7 +182,7 @@ Chat view 在标记了 `data-text-interaction-source` 的业务节点上检测
|
||||
|
||||
`ctx.uiConversation.interactions` 将有效手势分发给插件注册项,并把对应组件交给 Chat view。操作展示位置在已有 Chat 列内绝对定位,限制在 composer seat 及其 dock 上方。外层容器保留组件的外描边与阴影,内部滚动由组件负责。选区滚出该可见范围时暂时隐藏操作,滚回后恢复。Chat 负责视口可见性、定位、外部指针按下、Escape、新选区、来源失效与卸载清理;主动关闭保留浏览器选区,布局变化不会重新打开操作。[Message quotes](../../session/message-quotes/README.zh.md) 负责引用的接管条件和插入。
|
||||
|
||||
Markdown 文件、链接和图片将明确的右键目标转发给 [ui-context-menu](../ui-context-menu/README.zh.md)。文件目标保留工作目录和行号;普通链接点击仍遵循配置的打开偏好。
|
||||
Markdown 文件、链接、图片、引用 chip 和工具文件控件将明确的右键目标转发给 [ui-context-menu](../ui-context-menu/README.zh.md)。文件目标保留工作目录和行号;普通链接点击仍遵循配置的打开偏好。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
@@ -76,9 +76,8 @@ export const CHAT_NODE_INJECT: ChatNodeInjected = {
|
||||
|
||||
/** Services required by the Chat target and its presentation registrations. */
|
||||
export const inject = [
|
||||
'menus',
|
||||
'slots', 'sessions', 'uiWorkspace', 'uiSession', 'uiConversation', 'locale',
|
||||
'configForms', 'connection', 'remote', 'remote.session', 'sidebarRight', 'fileDrag',
|
||||
'configForms', 'connection', 'remote', 'remote.session', 'sidebarRight', 'fileDrag', 'menus',
|
||||
]
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// An enclosing `[data-conversation-scroll]` owns scrolling when present;
|
||||
// otherwise this view owns it. Each row subscribes to one stable node key.
|
||||
|
||||
import { openChatContextMenu, chatContextKey } from './context-menu.ts'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type {
|
||||
NodeKey, RenderEntry,
|
||||
@@ -215,8 +214,6 @@ export function ChatView({
|
||||
<div className={css.root} data-chat-following-tail={scroll.followingTail ? '' : undefined}>
|
||||
<div ref={scroll.listRef} className={css.scroll}>
|
||||
<div ref={scroll.columnRef} className={css.column} data-chat-flow=""
|
||||
onContextMenu={(event) => { openChatContextMenu(event, openContextMenu) }}
|
||||
onKeyDown={(event) => { chatContextKey(event, openContextMenu) }}
|
||||
data-chat-motion={deferCompletedTurns && scroll.initialized
|
||||
&& (running || motionTail || pendingInputs.length > 0) ? '' : undefined}>
|
||||
{openState === 'loading' && <div className={css.hint}>{t('chat.loadingHistory')}</div>}
|
||||
@@ -233,7 +230,11 @@ export function ChatView({
|
||||
</div>
|
||||
)}
|
||||
<MarkdownDelegateProvider
|
||||
openContextMenu={openContextMenu} openFile={requestOpenFile} openExternalLink={openExternalLink} fileImages={fileImages}>
|
||||
openContextMenu={openContextMenu}
|
||||
openFile={requestOpenFile}
|
||||
openExternalLink={openExternalLink}
|
||||
fileImages={fileImages}
|
||||
>
|
||||
{renderSlot('conversation.chat.flow', {
|
||||
entries, pendingInputs, lastInputTurn, deferCollapse,
|
||||
cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage, fileMentions,
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
/** Delegate reference and tool-file gestures to the shared context-menu capability. */
|
||||
import type { KeyboardEvent, MouseEvent, SyntheticEvent } from 'react'
|
||||
import type { ChatViewInjected } from '../contract/slots.ts'
|
||||
|
||||
function show(event: SyntheticEvent<HTMLElement>, open: ChatViewInjected['openContextMenu'], point?: { x: number; y: number }): void {
|
||||
if (event.defaultPrevented || !(event.target instanceof Element)) return
|
||||
if (event.target.closest('img, input, textarea, [contenteditable="true"], [role="menu"]')) return
|
||||
const source = event.target.closest<HTMLElement>('[data-file-path], a[href]')
|
||||
if (source === null || !event.currentTarget.contains(source)) return
|
||||
const path = source.getAttribute('data-file-path')
|
||||
const url = source.getAttribute('href')
|
||||
if (!path && (!url || !/^https?:\/\//iu.test(url))) return
|
||||
event.preventDefault(); event.stopPropagation()
|
||||
const rect = source.getBoundingClientRect()
|
||||
const position = point ?? { x: rect.left, y: rect.bottom }
|
||||
source.focus({ preventScroll: true })
|
||||
if (path) {
|
||||
const line = Number(source.getAttribute('data-file-line'))
|
||||
open({ kind: 'file', path,
|
||||
...(Number.isSafeInteger(line) && line > 0 ? { line } : {}),
|
||||
...(source.getAttribute('data-file-base') === 'workspace' ? { base: 'workspace' as const } : {}),
|
||||
}, position)
|
||||
}
|
||||
else if (url) open({ kind: 'url', url }, position)
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the menu of a rendered file reference or URL.
|
||||
* @param event - bubbled pointer gesture.
|
||||
* @param open - captured Session menu callback.
|
||||
*/
|
||||
export function openChatContextMenu(event: MouseEvent<HTMLElement>, open: ChatViewInjected['openContextMenu']): void {
|
||||
show(event, open, event.clientX === 0 && event.clientY === 0 ? undefined : { x: event.clientX, y: event.clientY })
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a focused reference with the context key or Shift+F10.
|
||||
* @param event - keyboard menu request.
|
||||
* @param open - captured Session menu callback.
|
||||
*/
|
||||
export function chatContextKey(event: KeyboardEvent<HTMLElement>, open: ChatViewInjected['openContextMenu']): void {
|
||||
if (event.repeat || event.nativeEvent.isComposing || event.ctrlKey || event.altKey || event.metaKey) return
|
||||
if (event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey)) show(event, open)
|
||||
}
|
||||
@@ -4617,3 +4617,21 @@ const fileDrag = { prepare: vi.fn(async () => ({ start: () => true, release: ()
|
||||
it('formats Portuguese elapsed minutes with numeric units', () => {
|
||||
expect(formatRunDuration(90_000, key => pt[key])).toBe('1m 30s')
|
||||
})
|
||||
|
||||
it('does not infer menu targets from links or data attributes inside a plugin flow slot', () => {
|
||||
const h = makeHarness()
|
||||
const custom = vi.fn()
|
||||
const view = render(<ChatView {...h.props} renderSlot={() => <>
|
||||
<a href="https://example.com/plugin">Plugin link</a>
|
||||
<button data-file-path="/plugin/private.txt">Undeclared file</button>
|
||||
<button onContextMenu={(event) => {
|
||||
event.preventDefault()
|
||||
custom()
|
||||
}}>Custom target</button>
|
||||
</>} />)
|
||||
expect(fireEvent.contextMenu(view.getByRole('link', { name: 'Plugin link' }))).toBe(true)
|
||||
expect(fireEvent.contextMenu(view.getByRole('button', { name: 'Undeclared file' }))).toBe(true)
|
||||
fireEvent.contextMenu(view.getByRole('button', { name: 'Custom target' }))
|
||||
expect(custom).toHaveBeenCalledOnce()
|
||||
expect(h.props.openContextMenu).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -1,41 +1,48 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { chatContextKey, openChatContextMenu } from '../src/client/chat/context-menu.ts'
|
||||
import { contextMenuTrigger, MarkdownDelegateProvider, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
it('copies the recorded path target rather than a tool or reference display label, and preserves URL query and fragment', () => {
|
||||
it('leaves undeclared plugin links alone and binds only explicitly rendered Markdown targets', () => {
|
||||
const open = vi.fn()
|
||||
const view = render(<div onContextMenu={(event) => { openChatContextMenu(event, open) }}>
|
||||
<button data-file-path="/workspace/output.txt" data-file-line="42">output.txt:42</button>
|
||||
<a href="https://example.com/path?q=1#fragment">Website</a>
|
||||
</div>)
|
||||
fireEvent.contextMenu(view.getByRole('button'), { clientX: 50, clientY: 70 })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: '/workspace/output.txt', line: 42 }, { x: 50, y: 70 })
|
||||
fireEvent.contextMenu(view.getByRole('link'), { clientX: 80, clientY: 90 })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'url', url: 'https://example.com/path?q=1#fragment' }, { x: 80, y: 90 })
|
||||
const custom = vi.fn()
|
||||
const view = render(<MarkdownDelegateProvider openContextMenu={open} openFile={() => {}}>
|
||||
<a href="https://example.com/plugin">Plugin link</a>
|
||||
<MarkdownText text="[File](docs/file.ts#L42)" labels={{ code: { copyLabel: 'Copy', copiedLabel: 'Copied' }, footnotes: 'Footnotes' }} />
|
||||
<button {...contextMenuTrigger((point) => { custom({ kind: 'pluginDocument', id: 'one' }, point) })}>Plugin target</button>
|
||||
</MarkdownDelegateProvider>)
|
||||
expect(fireEvent.contextMenu(view.getByRole('link', { name: 'Plugin link' }))).toBe(true)
|
||||
expect(open).not.toHaveBeenCalled()
|
||||
const file = view.getByRole('button', { name: 'File' })
|
||||
fireEvent.contextMenu(file, { clientX: 40, clientY: 50 })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: 'docs/file.ts', line: 42 }, { x: 40, y: 50 })
|
||||
file.getBoundingClientRect = () => new DOMRect(30, 40, 100, 20)
|
||||
fireEvent.keyDown(file, { key: 'F10', shiftKey: true })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: 'docs/file.ts', line: 42 }, { x: 30, y: 60 })
|
||||
expect(document.activeElement).toBe(file)
|
||||
fireEvent.contextMenu(view.getByRole('button', { name: 'Plugin target' }), { clientX: 70, clientY: 80 })
|
||||
expect(custom).toHaveBeenCalledExactlyOnceWith({ kind: 'pluginDocument', id: 'one' }, { x: 70, y: 80 })
|
||||
expect(open).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('opens keyboard menus from their focused reference and leaves images, editors, and unrelated gestures alone', () => {
|
||||
const open = vi.fn()
|
||||
const view = render(<div onKeyDown={(event) => { chatContextKey(event, open) }}
|
||||
onContextMenu={(event) => { openChatContextMenu(event, open) }}>
|
||||
<button data-file-path="/workspace/folder">Folder</button>
|
||||
<a href="https://example.com"><img alt="Image" /></a>
|
||||
<textarea defaultValue="Editor" />
|
||||
it('keeps nested, cancelled and portaled gestures with their explicit owner', () => {
|
||||
const outer = vi.fn(), inner = vi.fn()
|
||||
const view = render(<div {...contextMenuTrigger(outer)}>
|
||||
<button {...contextMenuTrigger(inner)}>Inner</button>
|
||||
<button onContextMenu={(event) => { event.preventDefault() }}>Native</button>
|
||||
{createPortal(<button {...contextMenuTrigger(inner)}>Portal</button>, document.body)}
|
||||
</div>)
|
||||
const source = view.getByRole('button')
|
||||
source.getBoundingClientRect = () => new DOMRect(30, 40, 100, 20)
|
||||
fireEvent.keyDown(source, { key: 'F10', shiftKey: true })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'file', path: '/workspace/folder' }, { x: 30, y: 60 })
|
||||
expect(document.activeElement).toBe(source)
|
||||
fireEvent.keyDown(source, { key: 'ContextMenu' })
|
||||
expect(open).toHaveBeenCalledTimes(2)
|
||||
fireEvent.keyDown(source, { key: 'F10' })
|
||||
fireEvent.keyDown(source, { key: 'F10', shiftKey: true, repeat: true })
|
||||
fireEvent.keyDown(source, { key: 'F10', shiftKey: true, isComposing: true })
|
||||
fireEvent.contextMenu(view.getByRole('img'))
|
||||
fireEvent.contextMenu(view.getByRole('textbox'))
|
||||
expect(open).toHaveBeenCalledTimes(2)
|
||||
fireEvent.contextMenu(view.getByText('Inner'))
|
||||
fireEvent.contextMenu(view.getByText('Native'))
|
||||
fireEvent.keyDown(view.getByText('Portal'), { key: 'ContextMenu' })
|
||||
expect(inner).toHaveBeenCalledTimes(2)
|
||||
expect(outer).not.toHaveBeenCalled()
|
||||
for (const options of [{}, { repeat: true, shiftKey: true }, { isComposing: true, shiftKey: true },
|
||||
{ ctrlKey: true, shiftKey: true }, { altKey: true, shiftKey: true }, { metaKey: true, shiftKey: true }]) {
|
||||
fireEvent.keyDown(view.getByText('Inner'), { key: 'F10', ...options })
|
||||
}
|
||||
expect(inner).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 725b47765ee8f30b
|
||||
/deepseek-ai-dsh-client-ui-context-menu/use-this-package:
|
||||
en: ba9957a952b22a97
|
||||
zh: e2cc29bb9682eaa3
|
||||
en: bd5f0f5f2e139aca
|
||||
zh: d7cd513040085c09
|
||||
/deepseek-ai-dsh-client-ui-context-menu/use-this-package/register-actions:
|
||||
en: cda6f46f88fa6312
|
||||
zh: c3cb474252e81b1f
|
||||
en: fbe1f64e26d47dbb
|
||||
zh: 957d50bc0b063870
|
||||
/deepseek-ai-dsh-client-ui-context-menu/understand-the-implementation:
|
||||
en: 5b7717fad8457145
|
||||
zh: 19a06fca8060cf62
|
||||
|
||||
@@ -27,6 +27,8 @@ Add actions to right-click menus without importing a React component. Targets re
|
||||
|
||||
The Web application bundle mounts this Client plugin. External Client plugins declare the package in `dsh.client.inject`, import its `/client` types, and inject the `menus` service. `resolutionTimeoutMs` bounds each provider’s preparation (1000ms by default); timed-out providers are aborted and omitted with visible failure feedback.
|
||||
|
||||
Ordinary React controls bind `contextMenuTrigger(open)` from ui-primitives to their actual DOM element. The callback supplies an explicit target to `ctx.menus.open()`; no DOM attributes are interpreted as target metadata. Nested controls can prevent handling, and portals bind at their rendered element. Special editors and canvases can call `open()` directly.
|
||||
|
||||
### Register actions
|
||||
|
||||
Call `ctx.effect(() => ctx.menus.register({ id, target, order, resolve }))` in the contributing plugin. `resolve` receives the captured target and its cancellation signal; return localized actions with stable IDs, optional icons, disabled state, submenus, and execution callbacks. Contributions sort by `order`, then ID. Duplicate contribution IDs within one target family fail registration; duplicate action paths reject that provider’s result. IDs are encoded by segment before publication.
|
||||
@@ -35,7 +37,7 @@ Extend `MenuTargetMap` through declaration merging on `@deepseek-ai/dsh-client-u
|
||||
|
||||
`ctx.menus.resolve(target)` gives a separate occurrence for another renderer. Subscribe to its immutable action views, select a published ID, and dispose it when its owner closes. Views contain presentation fields only. Callbacks remain in the registry and execute at most once. Dismissal and replacement cancel metadata, but an action already selected owns its own execution and cancellation. Rejected providers and actions produce a persistent overlay toast; an action’s localized `failureLabel` supplies operation-specific recovery guidance.
|
||||
|
||||
Shared popups wait for every contribution to settle or time out before appearing. A repeated gesture within four CSS pixels closes the same target; a farther gesture replaces it with a separate fade. `ready` gives custom renderers the same preparation point. Standard action `symbol` values use existing glyphs; custom icon URLs take precedence. Icons align within each divider group, including component contributions. Normal dismissal retains the popup for 80ms, replacement for 10ms; opening waits at least 20ms and fades in over 40ms. Reduced motion suppresses the fade.
|
||||
Shared popups wait for every contribution to settle or time out before appearing. A repeated gesture within four CSS pixels closes the same target; a farther gesture replaces it with a separate fade. `ready` gives custom renderers the same preparation point. Standard action `symbol` values use existing glyphs; custom icon URLs take precedence. Structured action icons align within each divider group; component contributions retain their own layout. Normal dismissal retains the popup for 80ms, replacement for 10ms; opening waits at least 20ms and fades in over 40ms. Reduced motion suppresses the fade.
|
||||
|
||||
The optional keyed `contextMenu.content` Slot hosts component contributions. Existing Session and tab Slot names remain owned by their feature adapters. Keyboard context keys and Shift+F10 use the focused trigger’s lower edge. `afterContent` places a data action after those rows; ordinary actions render before them.
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ kind: "package-reference"
|
||||
|
||||
Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.client.inject` 声明本包,导入 `/client` 类型,并注入 `menus` 服务。`resolutionTimeoutMs` 限制每个提供方的准备时长(默认 1000ms);超时后取消并忽略该提供方,显示失败提示。
|
||||
|
||||
普通 React 控件将 ui-primitives 的 `contextMenuTrigger(open)` 绑定到实际 DOM 元素。回调向 `ctx.menus.open()` 提供显式目标;DOM 属性不作为目标元数据解释。嵌套控件可以阻止处理,Portal 在实际渲染元素上绑定。特殊编辑器和 Canvas 可直接调用 `open()`。
|
||||
|
||||
### 注册操作
|
||||
|
||||
在贡献插件中调用 `ctx.effect(() => ctx.menus.register({ id, target, order, resolve }))`。`resolve` 接收捕获的目标和取消信号;返回本地化操作,包含稳定 ID、可选图标、禁用状态、子菜单和执行回调。贡献项先按 `order`、再按 ID 排序。同类目标的贡献 ID 重复会导致注册失败;操作路径重复会拒绝该提供方的结果。发布前会逐段编码 ID。
|
||||
@@ -35,7 +37,7 @@ Web 应用 bundle 挂载此客户端插件。外部客户端插件在 `dsh.clien
|
||||
|
||||
`ctx.menus.resolve(target)` 为其他渲染器提供独立菜单实例。订阅不可变操作视图,选择已发布的 ID,并在所属界面关闭时释放。视图仅包含展示字段。回调保留在注册表中,最多执行一次。关闭和替换菜单会取消元数据查询,已选中操作则自行管理执行与取消。提供方或操作拒绝时由持久的覆盖层提示;操作的本地化 `failureLabel` 提供具体的恢复建议。
|
||||
|
||||
共享弹窗等待全部贡献项完成或超时后才显示。同一目标在四个 CSS 像素以内重复触发会关闭菜单;更远的触发以独立淡入淡出替换菜单。`ready` 向自定义渲染器提供同一个准备完成时点。标准操作 `symbol` 使用既有图标,自定义图标 URL 优先。每个分隔线组内的图标统一对齐,也适用于组件贡献项。普通关闭保留弹窗 80ms,替换保留 10ms;打开至少等待 20ms,再用 40ms 淡入。减少动态效果偏好会禁用淡入淡出。
|
||||
共享弹窗等待全部贡献项完成或超时后才显示。同一目标在四个 CSS 像素以内重复触发会关闭菜单;更远的触发以独立淡入淡出替换菜单。`ready` 向自定义渲染器提供同一个准备完成时点。标准操作 `symbol` 使用既有图标,自定义图标 URL 优先。结构化操作的图标按分隔线组对齐;组件贡献保留自己的布局。普通关闭保留弹窗 80ms,替换保留 10ms;打开至少等待 20ms,再用 40ms 淡入。减少动态效果偏好会禁用淡入淡出。
|
||||
|
||||
可选的 keyed Slot `contextMenu.content` 承载组件贡献。现有会话和标签菜单 Slot 名称仍由各自功能适配器维护。键盘菜单键和 Shift+F10 使用焦点触发元素的下边缘定位。`afterContent` 将数据操作放在这些行之后;普通操作排在之前。
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { MENU_TRANSITION_MS } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { menuTargetKey } from './target-key.ts'
|
||||
import { MenuRegistry } from './registry.ts'
|
||||
import { createMenuStore } from './store.ts'
|
||||
import { dictionaries } from './locales.ts'
|
||||
import { MenuOverlay } from './View.tsx'
|
||||
import type { ContextMenus, MenuResolution, MenuTarget } from './types.ts'
|
||||
|
||||
@@ -35,14 +36,7 @@ export const Config: z<Config> = z.object({ resolutionTimeoutMs: z.natural().min
|
||||
export const inject = ['slots', 'locale']
|
||||
/** @param ctx - plugin-owned Client context. @param config - validated preparation budget. */
|
||||
export function apply(ctx: Context, config: Config = Config({})): void {
|
||||
ctx.effect(() => ctx.locale.register('contextMenu', {
|
||||
zh: { failed: '操作失败,请重试' }, en: { failed: 'Could not complete the action. Try again.' }, ja: { failed: '操作に失敗しました。再試行してください。' },
|
||||
es: { failed: 'No se pudo completar la acción. Inténtelo de nuevo.' },
|
||||
fr: { failed: 'Impossible de terminer l’action. Réessayez.' },
|
||||
de: { failed: 'Die Aktion konnte nicht abgeschlossen werden. Versuchen Sie es erneut.' },
|
||||
ru: { failed: 'Не удалось выполнить действие. Повторите попытку.' },
|
||||
pt: { failed: 'Não foi possível concluir a ação. Tente novamente.' },
|
||||
}), 'context menu: locale')
|
||||
ctx.effect(() => ctx.locale.register('contextMenu', dictionaries), 'context menu: locale')
|
||||
const t = ctx.locale.bind('contextMenu')
|
||||
const handle = createMenuStore()
|
||||
const instance = handle.create()
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Context-menu operation feedback, separate from plugin display metadata. */
|
||||
export const dictionaries = {
|
||||
zh: { failed: '操作失败,请重试' },
|
||||
en: { failed: 'Could not complete the action. Try again.' },
|
||||
ja: { failed: '操作に失敗しました。再試行してください。' },
|
||||
es: { failed: 'No se pudo completar la acción. Inténtelo de nuevo.' },
|
||||
fr: { failed: 'Impossible de terminer l’action. Réessayez.' },
|
||||
de: { failed: 'Die Aktion konnte nicht abgeschlossen werden. Versuchen Sie es erneut.' },
|
||||
ru: { failed: 'Не удалось выполнить действие. Повторите попытку.' },
|
||||
pt: { failed: 'Não foi possível concluir a ação. Tente novamente.' },
|
||||
} satisfies Record<string, { failed: string }>
|
||||
@@ -15,11 +15,11 @@
|
||||
en: d152484eb41ac6b4
|
||||
zh: 725b47765ee8f30b
|
||||
/deepseek-ai-dsh-client-ui-file-actions/use-this-package:
|
||||
en: 059ae802e4decfac
|
||||
zh: dbffbfb23f907189
|
||||
en: 7390e2d40fbb4ac6
|
||||
zh: c1eb624030f91c92
|
||||
/deepseek-ai-dsh-client-ui-file-actions/use-this-package/original-content:
|
||||
en: 88a591debb51981f
|
||||
zh: bf6902f65486526a
|
||||
en: 1d28741e05f0cc79
|
||||
zh: 4110261f8e3ef744
|
||||
/deepseek-ai-dsh-client-ui-file-actions/understand-the-implementation:
|
||||
en: f13d217fc555ef53
|
||||
zh: 97c8e374ce0ef5a6
|
||||
|
||||
@@ -25,7 +25,7 @@ Download and save original files without changing their encoding. Copy images as
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
The Web application bundle mounts this Client plugin without configuration fields. Consumers import `/client` types and inject `fileActions`. Desktop supplies an optional trusted-frame adapter; ordinary Web uses its browser clipboard and download APIs.
|
||||
The Web application bundle mounts this Client plugin without configuration fields. Consumers import `/client` types and inject `fileActions`. Desktop supplies an optional trusted-frame adapter for saves and remote image reads. Both Desktop and Web write PNG images through the browser Clipboard API.
|
||||
|
||||
### Original content
|
||||
|
||||
@@ -35,9 +35,9 @@ Pass an original URL, optional filename and MIME, or an authorized `read(signal)
|
||||
|
||||
Filename and MIME normalization reuse the file-drag utility, so saving and dragging retain the same original format and filename policy.
|
||||
|
||||
Response MIME takes precedence over a suggested filename or media type when naming downloaded originals. Image copying decodes the original into PNG for clipboard interoperability. Downloads and save-as never use that conversion. Callers own localized success and failure feedback. Rejected reads do not start writes; native download writes reserve a unique filename and remove partial files on failure. Explicit replacements write a sibling temporary file before renaming. Plugin disposal aborts browser reads, discards references, and releases object URLs.
|
||||
Response MIME takes precedence over a suggested filename or media type when naming downloaded originals. Image copying decodes the original into PNG for clipboard interoperability. Downloads and save-as never use that conversion. The plugin contributes file and image copy, download, save-as, saved-file reveal, and localized feedback through `ctx.menus`, independently of `ui-open-in-app`. Other service callers own their feedback. Rejected reads do not start writes; native download writes reserve a unique filename and remove partial files on failure. Explicit replacements write a sibling temporary file before renaming. Plugin disposal aborts browser reads, discards references, and releases object URLs.
|
||||
|
||||
Desktop remote reads follow HTTP(S) redirects without credentials or referrers, rejecting the application Host at every hop. Other destinations use the machine’s network policy. The configured byte limit also bounds native clipboard input before decoding. Ordinary Web reads require the remote server to allow browser CORS; a denied response produces failure feedback without starting a save.
|
||||
Desktop remote reads follow HTTP(S) redirects without credentials or referrers, rejecting the application Host at every hop. Other destinations use the machine’s network policy. Ordinary Web reads require the remote server to allow browser CORS; a denied response produces failure feedback without starting a save.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
Web 应用 bundle 无配置字段地挂载此客户端插件。使用方导入 `/client` 类型并注入 `fileActions`。Desktop 提供可选的可信页面适配器;普通 Web 使用浏览器剪贴板和下载 API。
|
||||
Web 应用 bundle 无配置字段地挂载此客户端插件。使用方导入 `/client` 类型并注入 `fileActions`。Desktop 为保存和远程图片读取提供可选的可信页面适配器。Desktop 与 Web 均通过浏览器 Clipboard API 写入 PNG 图片。
|
||||
|
||||
### 原始内容
|
||||
|
||||
@@ -35,9 +35,9 @@ Web 应用 bundle 无配置字段地挂载此客户端插件。使用方导入 `
|
||||
|
||||
文件名与 MIME 规范化复用文件拖动工具,因此保存与拖动采用相同的原始格式和文件名规则。
|
||||
|
||||
下载原始内容时,响应 MIME 优先于建议文件名或媒体类型。图片复制会将原始内容解码为 PNG,保证剪贴板互通。下载与另存为不使用该转换。调用方负责本地化成功与失败提示。读取失败不会开始写入;原生下载独占创建唯一文件名,写入失败时删除残留文件。显式替换先写入同目录临时文件,再重命名。插件释放时取消浏览器读取、清除引用并释放对象 URL。
|
||||
下载原始内容时,响应 MIME 优先于建议文件名或媒体类型。图片复制会将原始内容解码为 PNG,保证剪贴板互通。下载与另存为不使用该转换。本插件通过 `ctx.menus` 贡献文件和图片的复制、下载、另存为、已保存文件定位及本地化提示,不依赖 `ui-open-in-app`。其他服务调用方负责自己的提示。读取失败不会开始写入;原生下载独占创建唯一文件名,写入失败时删除残留文件。显式替换先写入同目录临时文件,再重命名。插件释放时取消浏览器读取、清除引用并释放对象 URL。
|
||||
|
||||
Desktop 远程读取不带凭据或来源信息地跟随 HTTP(S) 重定向,每一跳均禁止访问应用 Host。其他目标遵循本机网络策略。配置的字节上限同样在解码前约束原生剪贴板输入。普通 Web 读取要求远端服务允许浏览器 CORS;响应被拒绝时显示失败提示,不开始保存。
|
||||
Desktop 远程读取不带凭据或来源信息地跟随 HTTP(S) 重定向,每一跳均禁止访问应用 Host。其他目标遵循本机网络策略。普通 Web 读取要求远端服务允许浏览器 CORS;响应被拒绝时显示失败提示,不开始保存。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -31,7 +31,11 @@
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"inject": [],
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-context-menu",
|
||||
"@deepseek-ai/dsh-api-workspace-files"
|
||||
],
|
||||
"platform": "web"
|
||||
}
|
||||
},
|
||||
@@ -48,7 +52,13 @@
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
|
||||
"@deepseek-ai/dsh-brand": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-test-runtime": "workspace:*",
|
||||
"@deepseek-ai/dsh-util-file-drag": "workspace:*"
|
||||
"@deepseek-ai/dsh-util-file-drag": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-locale": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-context-menu": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-workspace-files": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-util-workspace-path": "workspace:*",
|
||||
"mime": "^4.1.0"
|
||||
},
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/** Original-file menu contributions owned by the file-action capability. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-files/remote'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { FileActions, FileActionSource } from '../types.ts'
|
||||
import { fileMediaUrl } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import mime from 'mime'
|
||||
import type { FileActionKey } from './locales.ts'
|
||||
|
||||
/**
|
||||
* Register original-byte operations without requiring an application-opening plugin.
|
||||
* @param ctx - menu and authorized file-read services.
|
||||
* @param actions - file-action owner.
|
||||
* @param t - localized labels and feedback.
|
||||
*/
|
||||
export function registerFileMenus(ctx: Context, actions: FileActions, t: (key: FileActionKey) => string): void {
|
||||
const read = (sessionId: SessionId, path: string, mediaType: string, error: string) => async (signal: AbortSignal): Promise<Blob> => {
|
||||
const result = await ctx.remote.workspaceFiles.readBytes(sessionId, path, {}, signal)
|
||||
if (!result.ok) throw new Error(error)
|
||||
return new Blob([new Uint8Array(result.value.data)], { type: mediaType })
|
||||
}
|
||||
const save = async (source: FileActionSource, mode: 'download' | 'saveAs'): Promise<void> => {
|
||||
const result = await actions.save(source, mode)
|
||||
if (result.status !== 'cancelled') ctx.menus.notify(t(result.status === 'requested'
|
||||
? 'menu.downloadStarted' : mode === 'download' ? 'menu.downloaded' : 'menu.saved'), true)
|
||||
}
|
||||
const copy = async (source: FileActionSource): Promise<void> => {
|
||||
await actions.copyImage(source)
|
||||
ctx.menus.notify(t('menu.copied'), true)
|
||||
}
|
||||
ctx.effect(() => ctx.menus.register({
|
||||
id: 'file-actions.file', target: 'file', order: 200,
|
||||
resolve: async ({ sessionId, path }, signal) => {
|
||||
let absolutePath: string | undefined
|
||||
try {
|
||||
const result = await ctx.remote.workspaceFiles.stat(sessionId, path, signal)
|
||||
absolutePath = result.ok ? result.value.absolutePath : undefined
|
||||
} catch (_error) {
|
||||
// Failed metadata disables operations that require the source file.
|
||||
signal.throwIfAborted()
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
const available = absolutePath !== undefined
|
||||
const mediaType = mime.getType(path) ?? ''
|
||||
const source: FileActionSource = {
|
||||
url: fileMediaUrl(document.baseURI, absolutePath ?? path) ?? path,
|
||||
name: path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1),
|
||||
mediaType,
|
||||
read: read(sessionId, path, mediaType, 'Original file unavailable'),
|
||||
}
|
||||
return [
|
||||
...mediaType.startsWith('image/') ? [
|
||||
{ id: 'copyImage', symbol: 'copy' as const, separatorBefore: true, failureLabel: t('menu.copyFailed'),
|
||||
label: t('menu.copyImage'), disabled: !available, run: () => copy(source) },
|
||||
{ id: 'download', symbol: 'download' as const, failureLabel: t('menu.saveFailed'),
|
||||
label: t('menu.download'), disabled: !available, run: () => save(source, 'download') },
|
||||
] : [],
|
||||
{ id: 'saveAs', symbol: 'save', failureLabel: t('menu.saveFailed'), label: t('menu.saveAs'),
|
||||
disabled: !available || !actions.canSaveAs, run: () => save(source, 'saveAs') },
|
||||
]
|
||||
},
|
||||
}), 'file actions: file menu')
|
||||
ctx.effect(() => ctx.menus.register({
|
||||
id: 'file-actions.image', target: 'image', order: 100,
|
||||
resolve: (target) => {
|
||||
const { sessionId, path } = target
|
||||
const name = target.name ?? path?.split(/[\\/]/u).pop()
|
||||
const mediaType = target.mediaType || mime.getType(name ?? target.url) || undefined
|
||||
const source: FileActionSource = {
|
||||
...target,
|
||||
...(name === undefined ? {} : { name }),
|
||||
...(mediaType === undefined ? {} : { mediaType }),
|
||||
...(path === undefined || sessionId === undefined ? {} : {
|
||||
read: read(sessionId, path, mediaType ?? '', 'Original image unavailable'),
|
||||
}),
|
||||
}
|
||||
const saved = actions.savedFile(source.url)
|
||||
return [
|
||||
{ id: 'copy', symbol: 'copy', failureLabel: t('menu.copyFailed'), label: t('menu.copyImage'), run: () => copy(source) },
|
||||
{ id: 'download', symbol: 'download', failureLabel: t('menu.saveFailed'), label: t('menu.download'), run: () => save(source, 'download') },
|
||||
{ id: 'saveAs', symbol: 'save', failureLabel: t('menu.saveFailed'), label: t('menu.saveAs'),
|
||||
disabled: !actions.canSaveAs, run: () => save(source, 'saveAs') },
|
||||
...saved === undefined ? [] : [{
|
||||
id: 'reveal', symbol: 'folder' as const,
|
||||
label: t(document.documentElement.dataset.platform === 'darwin' ? 'menu.finder' : 'menu.reveal'),
|
||||
failureLabel: t('path.revealError'), run: () => actions.reveal(saved),
|
||||
}],
|
||||
]
|
||||
},
|
||||
}), 'file actions: image menu')
|
||||
}
|
||||
@@ -81,6 +81,7 @@ export class BrowserFileActions implements FileActions {
|
||||
}
|
||||
async copyImage(source: FileActionSource): Promise<void> {
|
||||
const png = this.read(source).then(async (blob) => {
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
if (blob.type === 'image/png') return blob
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const image = new Image()
|
||||
@@ -100,12 +101,6 @@ export class BrowserFileActions implements FileActions {
|
||||
})
|
||||
} finally { URL.revokeObjectURL(objectUrl) }
|
||||
})
|
||||
if (this.desktop !== undefined) {
|
||||
const bytes = new Uint8Array(await (await png).arrayBuffer())
|
||||
this.lifetime.signal.throwIfAborted()
|
||||
await this.desktop.copyImage(bytes)
|
||||
return
|
||||
}
|
||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
|
||||
}
|
||||
/** Cancel reads and release browser download URLs when the plugin unloads. */
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
/** Original-file actions independent of menu or image component ownership. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { DesktopFileActions, FileActions } from '../types.ts'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { registerFileMenus } from './context-menus.ts'
|
||||
import { zh, en, ja, es, fr, de, ru, pt, type FileActionKey } from './locales.ts'
|
||||
import { BrowserFileActions } from './files.ts'
|
||||
|
||||
export type { FileActions, FileActionSource, FileSaveResult, SavedFileId } from '../types.ts'
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context { /** Original-file saving and image clipboard commands. */ fileActions: FileActions }
|
||||
}
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** Original-file action labels and feedback. */
|
||||
fileActions: FileActionKey
|
||||
}
|
||||
}
|
||||
/** The native adapter is optional; Web uses its own download and save capabilities. */
|
||||
export const inject = []
|
||||
/** @param ctx - plugin-owned Client context. */
|
||||
@@ -15,4 +24,8 @@ export function apply(ctx: Context): void {
|
||||
const actions = new BrowserFileActions(desktop)
|
||||
ctx.provide('fileActions', actions)
|
||||
ctx.effect(() => () => { actions.dispose() }, 'file actions: lifetime')
|
||||
ctx.inject(['menus', 'locale', 'remote', 'remote.workspaceFiles'], (child) => {
|
||||
child.effect(() => child.locale.register('fileActions', { zh, en, ja, es, fr, de, ru, pt }), 'file actions: locale')
|
||||
registerFileMenus(child, actions, child.locale.bind('fileActions'))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/** Original-file actions and completion feedback. */
|
||||
|
||||
/** zh file-action labels. */
|
||||
export const zh = {
|
||||
'menu.finder': '在 Finder 中显示',
|
||||
'menu.reveal': '在文件夹显示',
|
||||
'menu.saveAs': '另存为…',
|
||||
'menu.copied': '已复制',
|
||||
'menu.copyImage': '复制图片',
|
||||
'menu.download': '下载',
|
||||
'menu.saveFailed': '无法保存文件,请检查源文件和目标位置后重试',
|
||||
'menu.copyFailed': '无法复制,请检查内容是否可用后重试',
|
||||
'menu.saved': '已保存',
|
||||
'menu.downloadStarted': '已开始下载',
|
||||
'menu.downloaded': '下载完成',
|
||||
'path.revealError': '无法显示文件位置,请重试',
|
||||
} satisfies Record<string, string>
|
||||
|
||||
/** File-action dictionary keys. */
|
||||
export type FileActionKey = keyof typeof zh
|
||||
|
||||
/** en file-action labels. */
|
||||
export const en = {
|
||||
'menu.finder': 'Show in Finder',
|
||||
'menu.reveal': 'Show in folder',
|
||||
'menu.saveAs': 'Save as…',
|
||||
'menu.copied': 'Copied',
|
||||
'menu.copyImage': 'Copy image',
|
||||
'menu.download': 'Download',
|
||||
'menu.saveFailed': 'Could not save. Check the source and destination, then retry.',
|
||||
'menu.copyFailed': 'Could not copy. Check that the content is available, then retry.',
|
||||
'menu.saved': 'Saved',
|
||||
'menu.downloadStarted': 'Download started',
|
||||
'menu.downloaded': 'Download complete',
|
||||
'path.revealError': 'Could not show the file location. Try again.',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** ja file-action labels. */
|
||||
export const ja = {
|
||||
'menu.finder': 'Finder に表示',
|
||||
'menu.reveal': 'フォルダーに表示',
|
||||
'menu.saveAs': '名前を付けて保存…',
|
||||
'menu.copied': 'コピーしました',
|
||||
'menu.copyImage': '画像をコピー',
|
||||
'menu.download': 'ダウンロード',
|
||||
'menu.saveFailed': '保存できません。元のファイルと保存先を確認して再試行してください。',
|
||||
'menu.copyFailed': 'コピーできません。内容を確認して再試行してください。',
|
||||
'menu.saved': '保存しました',
|
||||
'menu.downloadStarted': 'ダウンロードを開始しました',
|
||||
'menu.downloaded': 'ダウンロードしました',
|
||||
'path.revealError': 'ファイルの場所を表示できませんでした。もう一度お試しください。',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** es file-action labels. */
|
||||
export const es = {
|
||||
'menu.finder': 'Mostrar en Finder',
|
||||
'menu.reveal': 'Mostrar en la carpeta',
|
||||
'menu.saveAs': 'Guardar como…',
|
||||
'menu.copied': 'Copiado',
|
||||
'menu.copyImage': 'Copiar imagen',
|
||||
'menu.download': 'Descargar',
|
||||
'menu.saveFailed': 'No se pudo guardar. Compruebe el origen y el destino e inténtelo de nuevo.',
|
||||
'menu.copyFailed': 'No se pudo copiar. Compruebe que el contenido esté disponible e inténtelo de nuevo.',
|
||||
'menu.saved': 'Guardado',
|
||||
'menu.downloadStarted': 'Descarga iniciada',
|
||||
'menu.downloaded': 'Descarga completada',
|
||||
'path.revealError': 'No se pudo mostrar la ubicación del archivo. Intentar otra vez.',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** fr file-action labels. */
|
||||
export const fr = {
|
||||
'menu.finder': 'Afficher dans le Finder',
|
||||
'menu.reveal': 'Afficher dans le dossier',
|
||||
'menu.saveAs': 'Enregistrer sous…',
|
||||
'menu.copied': 'Copié',
|
||||
'menu.copyImage': 'Copier l’image',
|
||||
'menu.download': 'Télécharger',
|
||||
'menu.saveFailed': 'Impossible d’enregistrer. Vérifiez la source et la destination, puis réessayez.',
|
||||
'menu.copyFailed': 'Impossible de copier. Vérifiez que le contenu est disponible, puis réessayez.',
|
||||
'menu.saved': 'Enregistré',
|
||||
'menu.downloadStarted': 'Téléchargement démarré',
|
||||
'menu.downloaded': 'Téléchargement terminé',
|
||||
'path.revealError': "Impossible d'afficher l'emplacement du fichier. Essayer à nouveau.",
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** de file-action labels. */
|
||||
export const de = {
|
||||
'menu.finder': 'Im Finder anzeigen',
|
||||
'menu.reveal': 'Im Ordner anzeigen',
|
||||
'menu.saveAs': 'Speichern unter…',
|
||||
'menu.copied': 'Kopiert',
|
||||
'menu.copyImage': 'Bild kopieren',
|
||||
'menu.download': 'Herunterladen',
|
||||
'menu.saveFailed': 'Speichern fehlgeschlagen. Prüfen Sie Quelle und Ziel und versuchen Sie es erneut.',
|
||||
'menu.copyFailed': 'Kopieren fehlgeschlagen. Prüfen Sie, ob der Inhalt verfügbar ist, und versuchen Sie es erneut.',
|
||||
'menu.saved': 'Gespeichert',
|
||||
'menu.downloadStarted': 'Download gestartet',
|
||||
'menu.downloaded': 'Download abgeschlossen',
|
||||
'path.revealError': 'Der Dateispeicherort konnte nicht angezeigt werden. Versuchen Sie es erneut.',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** ru file-action labels. */
|
||||
export const ru = {
|
||||
'menu.finder': 'Показать в Finder',
|
||||
'menu.reveal': 'Показать в папке',
|
||||
'menu.saveAs': 'Сохранить как…',
|
||||
'menu.copied': 'Скопировано',
|
||||
'menu.copyImage': 'Копировать изображение',
|
||||
'menu.download': 'Скачать',
|
||||
'menu.saveFailed': 'Не удалось сохранить. Проверьте источник и место сохранения и повторите попытку.',
|
||||
'menu.copyFailed': 'Не удалось скопировать. Проверьте доступность содержимого и повторите попытку.',
|
||||
'menu.saved': 'Сохранено',
|
||||
'menu.downloadStarted': 'Скачивание началось',
|
||||
'menu.downloaded': 'Скачивание завершено',
|
||||
'path.revealError': 'Не удалось показать местоположение файла. Попробуйте еще раз.',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
|
||||
/** pt file-action labels. */
|
||||
export const pt = {
|
||||
'menu.finder': 'Mostrar no Finder',
|
||||
'menu.reveal': 'Mostrar na pasta',
|
||||
'menu.saveAs': 'Salvar como…',
|
||||
'menu.copied': 'Copiado',
|
||||
'menu.copyImage': 'Copiar imagem',
|
||||
'menu.download': 'Baixar',
|
||||
'menu.saveFailed': 'Não foi possível salvar. Verifique a origem e o destino e tente novamente.',
|
||||
'menu.copyFailed': 'Não foi possível copiar. Verifique se o conteúdo está disponível e tente novamente.',
|
||||
'menu.saved': 'Salvo',
|
||||
'menu.downloadStarted': 'Download iniciado',
|
||||
'menu.downloaded': 'Download concluído',
|
||||
'path.revealError': 'Não foi possível mostrar o local do arquivo. Tente novamente.',
|
||||
} satisfies Record<FileActionKey, string>
|
||||
@@ -27,11 +27,6 @@ export interface DesktopFileActions {
|
||||
* @returns original bytes and response MIME.
|
||||
*/
|
||||
readImage(this: void, url: string): Promise<{ bytes: Uint8Array; mediaType: string }>
|
||||
/**
|
||||
* @param bytes - PNG-encoded clipboard image.
|
||||
* @returns after native clipboard accepts the decoded image.
|
||||
*/
|
||||
copyImage(this: void, bytes: Uint8Array): Promise<void>
|
||||
/**
|
||||
* @param id - reference returned by save.
|
||||
* @returns after the file manager accepts the request.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
import { Blob as NodeBlob } from 'node:buffer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { BrowserFileActions, exportName } from '../src/client/files.ts'
|
||||
import type { DesktopFileActions, SavedFileId } from '../src/types.ts'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
@@ -9,6 +9,15 @@ import { apply as hostApply } from '../src/index.ts'
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ClipboardItem', class {
|
||||
constructor(readonly content: Record<string, Promise<Blob>>) {}
|
||||
})
|
||||
vi.stubGlobal('navigator', { clipboard: { write: vi.fn(async (items: { content: Record<string, Promise<Blob>> }[]) => {
|
||||
await items[0]!.content['image/png']
|
||||
}) } })
|
||||
})
|
||||
|
||||
function fakeImage(width: number, height: number) {
|
||||
const image = { naturalWidth: width, naturalHeight: height, src: '', decode: vi.fn(async () => {}) }
|
||||
vi.stubGlobal('Image', function Image() { return image })
|
||||
@@ -22,7 +31,7 @@ function fakeImage(width: number, height: number) {
|
||||
function native(): DesktopFileActions {
|
||||
return { save: vi.fn(async () => ({ status: 'saved' as const, fileId: 'saved' as SavedFileId })),
|
||||
readImage: vi.fn(async () => ({ bytes: new Uint8Array([1, 2, 3]), mediaType: 'image/webp' })),
|
||||
copyImage: vi.fn(async () => {}), reveal: vi.fn(async () => {}) }
|
||||
reveal: vi.fn(async () => {}) }
|
||||
}
|
||||
|
||||
describe('original filenames', () => {
|
||||
@@ -100,7 +109,7 @@ describe('file actions', () => {
|
||||
await expect(pending).rejects.toThrow()
|
||||
expect(bridge.save).not.toHaveBeenCalled()
|
||||
})
|
||||
it('converts a browser-decodable original to PNG before handing it to the native clipboard', async () => {
|
||||
it('converts a browser-decodable original to PNG for the browser clipboard in Desktop', async () => {
|
||||
vi.stubGlobal('Blob', NodeBlob)
|
||||
const bitmap = fakeImage(2, 3)
|
||||
const drawImage = vi.fn()
|
||||
@@ -108,10 +117,11 @@ describe('file actions', () => {
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ drawImage } as never)
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation((callback) => { callback(new Blob(['PNG'], { type: 'image/png' })) })
|
||||
const bridge = native(), actions = new BrowserFileActions(bridge)
|
||||
const write = vi.spyOn(navigator.clipboard, 'write')
|
||||
await actions.copyImage({ url: 'https://example.org/image' })
|
||||
expect(drawImage).toHaveBeenCalledWith(bitmap, 0, 0)
|
||||
expect(vi.mocked(URL).revokeObjectURL).toHaveBeenCalledWith('blob:conversion')
|
||||
expect(bridge.copyImage).toHaveBeenCalledWith(new Uint8Array([80, 78, 71]))
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
await expect(actions.save({ url: 'file:///private/path' }, 'download')).rejects.toThrow('Unsupported')
|
||||
actions.dispose()
|
||||
})
|
||||
@@ -162,17 +172,16 @@ describe('file actions', () => {
|
||||
const bridge = native(), actions = new BrowserFileActions(bridge)
|
||||
await expect(actions.copyImage({ url: 'identity', read: async () => new Blob([], { type: 'image/gif' }) })).rejects.toThrow('conversion')
|
||||
expect(vi.mocked(URL).revokeObjectURL).toHaveBeenCalledWith('blob:conversion')
|
||||
expect(bridge.copyImage).not.toHaveBeenCalled()
|
||||
actions.dispose()
|
||||
})
|
||||
|
||||
it('passes a PNG promise to the browser clipboard during the gesture', async () => {
|
||||
it.each([false, true])('passes a PNG promise to the browser clipboard during the gesture (Desktop: %s)', async (desktop) => {
|
||||
const blob = new Blob(['png'], { type: 'image/png' })
|
||||
let content!: Record<string, Promise<Blob>>
|
||||
vi.stubGlobal('ClipboardItem', function ClipboardItem(value: Record<string, Promise<Blob>>) { content = value })
|
||||
const write = vi.fn(async () => { await content['image/png'] })
|
||||
vi.stubGlobal('navigator', { clipboard: { write } })
|
||||
const actions = new BrowserFileActions(undefined)
|
||||
const actions = new BrowserFileActions(desktop ? native() : undefined)
|
||||
await actions.copyImage({ url: 'identity', read: async () => blob })
|
||||
expect(await content['image/png']).toBe(blob)
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment jsdom
|
||||
/** File-operation contributions survive removal of application-opening providers. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts'
|
||||
import { apply } from '../src/client/index.ts'
|
||||
import type { FileActionSource } from '../src/types.ts'
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals() })
|
||||
|
||||
it('contributes file and image operations without open-in-app and withdraws them on unload', async () => {
|
||||
const ctx = new Context()
|
||||
const failure = vi.fn(), notify = vi.fn()
|
||||
const registry = new MenuRegistry(failure)
|
||||
ctx.provide('menus', { register: registry.register.bind(registry), notify } as never)
|
||||
const registerLocale = vi.fn(() => () => {})
|
||||
ctx.provide('locale', { register: registerLocale, bind: () => (key: string) => key } as never)
|
||||
const readBytes = vi.fn(async () => ({ ok: true as const, value: { data: [1, 2, 3] } }))
|
||||
const workspaceFiles = {
|
||||
stat: async () => ({ ok: true, value: { absolutePath: '/workspace/image.png' } }),
|
||||
readBytes,
|
||||
}
|
||||
ctx.provide('remote', { workspaceFiles } as never)
|
||||
ctx.provide('remote.workspaceFiles', workspaceFiles as never)
|
||||
const fiber = ctx.plugin({ apply })
|
||||
await fiber.await()
|
||||
try {
|
||||
await vi.waitFor(() => { expect(registerLocale).toHaveBeenCalledOnce() })
|
||||
const file = registry.resolve({ kind: 'file', value: { sessionId: SessionId('files'), path: 'image.png' } })
|
||||
await file.ready
|
||||
expect(file.source.getSnapshot().map(action => action.id)).toEqual([
|
||||
'file-actions.file/copyImage', 'file-actions.file/download', 'file-actions.file/saveAs',
|
||||
])
|
||||
expect(file.source.getSnapshot().find(action => action.id.endsWith('/download'))?.disabled).toBe(false)
|
||||
const save = vi.spyOn(ctx.fileActions, 'save').mockImplementation(async (source: FileActionSource) => {
|
||||
await source.read!(new AbortController().signal)
|
||||
return { status: 'requested' }
|
||||
})
|
||||
const downloading = registry.resolve({ kind: 'file', value: { sessionId: SessionId('files'), path: 'image.png' } })
|
||||
await downloading.ready
|
||||
downloading.select('file-actions.file/download')
|
||||
await vi.waitFor(() => { expect(notify).toHaveBeenCalledWith('menu.downloadStarted', true) })
|
||||
expect(save).toHaveBeenCalledOnce()
|
||||
expect(readBytes).toHaveBeenCalledWith(SessionId('files'), 'image.png', {}, expect.any(AbortSignal))
|
||||
save.mockRestore()
|
||||
const image = registry.resolve({ kind: 'image', value: { url: 'https://example.com/image.png' } })
|
||||
await image.ready
|
||||
expect(image.source.getSnapshot().map(action => action.id)).toEqual([
|
||||
'file-actions.image/copy', 'file-actions.image/download', 'file-actions.image/saveAs',
|
||||
])
|
||||
expect(image.source.getSnapshot().find(action => action.id.endsWith('/saveAs'))?.disabled).toBe(true)
|
||||
await fiber.dispose()
|
||||
expect(file.source.getSnapshot()).toEqual([])
|
||||
expect(image.source.getSnapshot()).toEqual([])
|
||||
file.dispose()
|
||||
image.dispose()
|
||||
expect(failure).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
registry.dispose()
|
||||
await ctx.fiber.dispose()
|
||||
}
|
||||
})
|
||||
@@ -16,6 +16,21 @@
|
||||
},
|
||||
{
|
||||
"path": "../../util/file-drag"
|
||||
},
|
||||
{
|
||||
"path": "../locale/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../ui-context-menu"
|
||||
},
|
||||
{
|
||||
"path": "../../api/workspace-files/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../../core/session"
|
||||
},
|
||||
{
|
||||
"path": "../../util/workspace-path"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 056e2bd9e3c78dd8
|
||||
zh: be35d2ba53be0442
|
||||
/deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect:
|
||||
en: 687e4e7a95c6744b
|
||||
zh: 1ded47434a03336f
|
||||
en: 2e42f479425a0095
|
||||
zh: f49a84b27f04706a
|
||||
/deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation:
|
||||
en: a0304e1bd9b44370
|
||||
zh: af0fdfd01c296dce
|
||||
|
||||
@@ -37,9 +37,9 @@ File menus list the discovered associated applications without a separate “Ope
|
||||
|
||||
Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control.
|
||||
|
||||
Workspace context menus open the captured folder through the same directory application catalog as the Session header. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. Save as… indicates the destination picker that follows.
|
||||
Workspace context menus open the captured folder through the same directory application catalog as the Session header. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save.
|
||||
|
||||
Context menus contribute file preview, native application and reveal, original save, URL navigation and copying, and image actions through [ui-context-menu](../ui-context-menu/README.md). Session reveal follows the installed file-manager catalog and registers at order 500 in `sidebar.workspaces.session.menu.item`, between Copy session ID and Archive. Its failures use the shared Toast after dismissal. Native file actions resolve Session paths through authorized metadata before querying applications. Missing files disable path actions; image reveal requires an actual Host file or native saved reference. [ui-file-actions](../ui-file-actions/README.md) owns original bytes and clipboard encoding.
|
||||
Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session reveal follows the installed file-manager catalog and registers at order 500 in `sidebar.workspaces.session.menu.item`, between Copy session ID and Archive. Its failures use the shared Toast after dismissal. Native file actions resolve Session paths through authorized metadata before querying applications. Missing files disable path actions; image reveal requires an actual Host file or native saved reference. [ui-file-actions](../ui-file-actions/README.md) contributes copy, download, save-as, saved-file reveal, and their feedback. A saved-file reference suppresses the original-file reveal contribution, so an image menu has one reveal action.
|
||||
|
||||
File menus copy absolute paths without line numbers; URL copying preserves query and fragment. Image files also expose image copy and original download, alongside the existing file actions. Successful downloads and saves show the shared Toast; picker cancellation is silent.
|
||||
|
||||
|
||||
@@ -37,9 +37,9 @@ kind: "package-reference"
|
||||
|
||||
使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。
|
||||
|
||||
工作区右键菜单通过与会话标题相同的目录应用列表打开被点击的文件夹。文件树目录提供本机显示位置和复制文件夹路径,不提供文件预览或保存。「另存为…」表示接下来需要选择保存位置。
|
||||
工作区右键菜单通过与会话标题相同的目录应用列表打开被点击的文件夹。文件树目录提供本机显示位置和复制文件夹路径,不提供文件预览或保存。
|
||||
|
||||
右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开与定位、原始文件保存、链接导航与复制、图片操作。会话定位沿用已安装文件管理器目录,以顺序 500 注册在 `sidebar.workspaces.session.menu.item`,位于复制 Session ID 与归档之间。失败提示通过共享 Toast 在菜单关闭后显示。原生文件操作先通过授权元数据解析会话路径,再查询关联应用。文件不存在时禁用路径操作;图片定位要求实际 Host 文件或原生保存引用。[ui-file-actions](../ui-file-actions/README.zh.md) 负责原始字节与剪贴板编码。
|
||||
右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话定位沿用已安装文件管理器目录,以顺序 500 注册在 `sidebar.workspaces.session.menu.item`,位于复制 Session ID 与归档之间。失败提示通过共享 Toast 在菜单关闭后显示。原生文件操作先通过授权元数据解析会话路径,再查询关联应用。文件不存在时禁用路径操作;图片定位要求实际 Host 文件或原生保存引用。[ui-file-actions](../ui-file-actions/README.zh.md) 贡献复制、下载、另存为、已保存文件定位及其提示。存在已保存文件引用时不再贡献原文件定位,使图片菜单只有一个定位动作。
|
||||
|
||||
文件菜单复制不含行号的绝对路径;网址复制保留查询参数与锚点。图片文件在既有文件操作之外,还提供复制图片与下载原图。下载和保存成功后显示共享 Toast,取消选择器时不提示。
|
||||
|
||||
|
||||
@@ -90,7 +90,6 @@
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-workspace-files": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar-browser": "workspace:*",
|
||||
"mime": "^4.1.0",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
/** Native path and original-image menu contributions, independent of their trigger components. */
|
||||
import mime from 'mime'
|
||||
/** Native path and URL menu contributions, independent of their trigger components. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
@@ -8,27 +7,25 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-files/remote'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { FileActionSource } from '@deepseek-ai/dsh-client-ui-file-actions/client'
|
||||
import type { OpenInAppController } from './controller.ts'
|
||||
import { fileAddressFor, fileMediaUrl, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'
|
||||
import type { OpenInAppPathController } from './open-path.ts'
|
||||
import type { OpenInAppKey } from './locales.ts'
|
||||
|
||||
/**
|
||||
* Register native path and original content actions.
|
||||
* Register native opening, original-path reveal, and URL actions.
|
||||
* @param ctx - declared plugin dependencies.
|
||||
* @param paths - existing native file actions.
|
||||
* @param t - localized action labels.
|
||||
* @param directories - installed directory applications.
|
||||
*/
|
||||
export function registerContextMenus(ctx: Context, paths: OpenInAppPathController,
|
||||
t: (key: OpenInAppKey, values?: Record<string, string>) => string, directories: OpenInAppController): void {
|
||||
export function registerContextMenus(
|
||||
ctx: Context,
|
||||
paths: OpenInAppPathController,
|
||||
t: (key: OpenInAppKey, values?: Record<string, string>) => string,
|
||||
directories: OpenInAppController,
|
||||
): void {
|
||||
const fileManager = () => t(directories.apps.getSnapshot()?.includes('finder') ? 'menu.finder' : 'menu.reveal')
|
||||
const save = async (source: FileActionSource, mode: 'download' | 'saveAs'): Promise<void> => {
|
||||
const result = await ctx.fileActions.save(source, mode)
|
||||
if (result.status !== 'cancelled') ctx.menus.notify(t(result.status === 'requested'
|
||||
? 'menu.downloadStarted' : mode === 'download' ? 'menu.downloaded' : 'menu.saved'), true)
|
||||
}
|
||||
const open = async (path: string, action: 'open' | 'reveal', application?: string): Promise<void> => {
|
||||
const failure = await paths.openPath(path, action, application)
|
||||
if (failure !== null) ctx.menus.notify(t(`path.${failure}`))
|
||||
@@ -83,15 +80,6 @@ export function registerContextMenus(ctx: Context, paths: OpenInAppPathControlle
|
||||
const apps = desktop ? await paths.applications(absolutePath, signal) : []
|
||||
signal.throwIfAborted()
|
||||
const application = apps?.find(app => app.default)
|
||||
const url = fileMediaUrl(document.baseURI, absolutePath ?? path)
|
||||
const mediaType = mime.getType(path) ?? ''
|
||||
const source: FileActionSource = { url: url ?? path, name: path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1), mediaType,
|
||||
read: async (signal) => {
|
||||
const result = await ctx.remote.workspaceFiles.readBytes(sessionId, path, {}, signal)
|
||||
if (!result.ok) throw new Error('Original file unavailable')
|
||||
return new Blob([new Uint8Array(result.value.data)], { type: mediaType })
|
||||
},
|
||||
}
|
||||
return [
|
||||
{ id: 'sidebar', symbol: 'sidebar', label: t('menu.sidebar'), disabled: !available,
|
||||
run: () => {
|
||||
@@ -111,14 +99,6 @@ export function registerContextMenus(ctx: Context, paths: OpenInAppPathControlle
|
||||
await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path))
|
||||
ctx.menus.notify(t('menu.copied'), true)
|
||||
} },
|
||||
...mediaType.startsWith('image/') ? [
|
||||
{ id: 'copyImage', symbol: 'copy' as const, separatorBefore: true, failureLabel: t('menu.copyFailed'), label: t('menu.copyImage'), disabled: !available,
|
||||
run: async () => { await ctx.fileActions.copyImage(source); ctx.menus.notify(t('menu.copied'), true) } },
|
||||
{ id: 'download', symbol: 'download' as const, failureLabel: t('menu.saveFailed'), label: t('menu.download'), disabled: !available,
|
||||
run: () => save(source, 'download') },
|
||||
] : [],
|
||||
{ id: 'saveAs', symbol: 'save', failureLabel: t('menu.saveFailed'), label: t('menu.saveAs'), disabled: !available || !ctx.fileActions.canSaveAs,
|
||||
run: () => save(source, 'saveAs') },
|
||||
]
|
||||
},
|
||||
}), 'open-in-app: file context menu')
|
||||
@@ -135,33 +115,17 @@ export function registerContextMenus(ctx: Context, paths: OpenInAppPathControlle
|
||||
],
|
||||
}), 'open-in-app: URL context menu')
|
||||
ctx.effect(() => ctx.menus.register({
|
||||
id: 'open-in-app.image', target: 'image', order: 100,
|
||||
id: 'open-in-app.image', target: 'image', order: 200,
|
||||
resolve: async (target, signal) => {
|
||||
const { sessionId, path } = target
|
||||
const name = target.name ?? target.path?.split(/[\\/]/u).pop()
|
||||
const mediaType = target.mediaType || mime.getType(name ?? target.url) || undefined
|
||||
const source: FileActionSource = { ...target, ...(name === undefined ? {} : { name }),
|
||||
...(mediaType === undefined ? {} : { mediaType }),
|
||||
...(path === undefined || sessionId === undefined ? {} : { read: async (signal: AbortSignal) => {
|
||||
const result = await ctx.remote.workspaceFiles.readBytes(sessionId, path, {}, signal)
|
||||
if (!result.ok) throw new Error('Original image unavailable')
|
||||
return new Blob([new Uint8Array(result.value.data)], { type: mediaType ?? '' })
|
||||
} }),
|
||||
}
|
||||
if (ctx.fileActions.savedFile(target.url) !== undefined) return []
|
||||
await paths.load()
|
||||
const saved = ctx.fileActions.savedFile(source.url)
|
||||
const local = target.path !== undefined && target.sessionId !== undefined && paths.desktop.getSnapshot() === true
|
||||
? await resolvePath(target.sessionId, target.path, signal) : undefined
|
||||
const local = path !== undefined && sessionId !== undefined && paths.desktop.getSnapshot() === true
|
||||
? await resolvePath(sessionId, path, signal) : undefined
|
||||
signal.throwIfAborted()
|
||||
return [
|
||||
{ id: 'copy', symbol: 'copy', failureLabel: t('menu.copyFailed'), label: t('menu.copyImage'), run: async () => {
|
||||
await ctx.fileActions.copyImage(source); ctx.menus.notify(t('menu.copied'), true)
|
||||
} },
|
||||
{ id: 'download', symbol: 'download', failureLabel: t('menu.saveFailed'), label: t('menu.download'), run: () => save(source, 'download') },
|
||||
{ id: 'saveAs', symbol: 'save', failureLabel: t('menu.saveFailed'), label: t('menu.saveAs'), disabled: !ctx.fileActions.canSaveAs,
|
||||
run: () => save(source, 'saveAs') },
|
||||
{ id: 'reveal', symbol: 'folder', label: fileManager(), disabled: !local && saved === undefined,
|
||||
...saved !== undefined ? { run: () => ctx.fileActions.reveal(saved) } : local !== undefined ? { run: () => open(local, 'reveal') } : {} },
|
||||
{ id: 'reveal', symbol: 'folder', label: fileManager(), disabled: local === undefined,
|
||||
...local !== undefined ? { run: () => open(local, 'reveal') } : {} },
|
||||
]
|
||||
},
|
||||
}), 'open-in-app: image context menu')
|
||||
|
||||
@@ -43,19 +43,12 @@ export const zh = {
|
||||
'menu.finder': '在 Finder 中显示',
|
||||
'menu.reveal': '在文件夹显示',
|
||||
'menu.defaultApp': '使用默认应用打开',
|
||||
'menu.saveAs': '另存为…',
|
||||
'menu.external': '外部浏览器打开',
|
||||
'menu.copyLink': '复制链接地址',
|
||||
'menu.copyPath': '复制文件路径',
|
||||
'menu.copyDirectoryPath': '复制文件夹路径',
|
||||
'menu.copied': '已复制',
|
||||
'menu.copyImage': '复制图片',
|
||||
'menu.download': '下载',
|
||||
'menu.saveFailed': '无法保存文件,请检查源文件和目标位置后重试',
|
||||
'menu.copyFailed': '无法复制,请检查内容是否可用后重试',
|
||||
'menu.saved': '已保存',
|
||||
'menu.downloadStarted': '已开始下载',
|
||||
'menu.downloaded': '下载完成',
|
||||
|
||||
'open.title': '用 {app} 打开',
|
||||
'path.appDefault': '{app}(默认)',
|
||||
@@ -81,19 +74,12 @@ export const en: Record<OpenInAppKey, string> = {
|
||||
'menu.finder': 'Show in Finder',
|
||||
'menu.reveal': 'Show in folder',
|
||||
'menu.defaultApp': 'Open in default application',
|
||||
'menu.saveAs': 'Save as…',
|
||||
'menu.external': 'Open in external browser',
|
||||
'menu.copyLink': 'Copy link address',
|
||||
'menu.copyPath': 'Copy file path',
|
||||
'menu.copyDirectoryPath': 'Copy folder path',
|
||||
'menu.copied': 'Copied',
|
||||
'menu.copyImage': 'Copy image',
|
||||
'menu.download': 'Download',
|
||||
'menu.saveFailed': 'Could not save. Check the source and destination, then retry.',
|
||||
'menu.copyFailed': 'Could not copy. Check that the content is available, then retry.',
|
||||
'menu.saved': 'Saved',
|
||||
'menu.downloadStarted': 'Download started',
|
||||
'menu.downloaded': 'Download complete',
|
||||
|
||||
'open.title': 'Open in {app}',
|
||||
'path.appDefault': '{app} (default)',
|
||||
@@ -122,19 +108,12 @@ export const ja = {
|
||||
'menu.finder': 'Finder に表示',
|
||||
'menu.reveal': 'フォルダーに表示',
|
||||
'menu.defaultApp': '既定のアプリで開く',
|
||||
'menu.saveAs': '名前を付けて保存…',
|
||||
'menu.external': '外部ブラウザーで開く',
|
||||
'menu.copyLink': 'リンクアドレスをコピー',
|
||||
'menu.copyPath': 'ファイルパスをコピー',
|
||||
'menu.copyDirectoryPath': 'フォルダーパスをコピー',
|
||||
'menu.copied': 'コピーしました',
|
||||
'menu.copyImage': '画像をコピー',
|
||||
'menu.download': 'ダウンロード',
|
||||
'menu.saveFailed': '保存できません。元のファイルと保存先を確認して再試行してください。',
|
||||
'menu.copyFailed': 'コピーできません。内容を確認して再試行してください。',
|
||||
'menu.saved': '保存しました',
|
||||
'menu.downloadStarted': 'ダウンロードを開始しました',
|
||||
'menu.downloaded': 'ダウンロードしました',
|
||||
|
||||
...PRODUCT_NAMES,
|
||||
'open.title': '{app}で開く',
|
||||
@@ -160,19 +139,12 @@ export const es = {
|
||||
'menu.finder': 'Mostrar en Finder',
|
||||
'menu.reveal': 'Mostrar en la carpeta',
|
||||
'menu.defaultApp': 'Abrir en la aplicación predeterminada',
|
||||
'menu.saveAs': 'Guardar como…',
|
||||
'menu.external': 'Abrir en un navegador externo',
|
||||
'menu.copyLink': 'Copiar dirección del enlace',
|
||||
'menu.copyPath': 'Copiar ruta del archivo',
|
||||
'menu.copyDirectoryPath': 'Copiar ruta de la carpeta',
|
||||
'menu.copied': 'Copiado',
|
||||
'menu.copyImage': 'Copiar imagen',
|
||||
'menu.download': 'Descargar',
|
||||
'menu.saveFailed': 'No se pudo guardar. Compruebe el origen y el destino e inténtelo de nuevo.',
|
||||
'menu.copyFailed': 'No se pudo copiar. Compruebe que el contenido esté disponible e inténtelo de nuevo.',
|
||||
'menu.saved': 'Guardado',
|
||||
'menu.downloadStarted': 'Descarga iniciada',
|
||||
'menu.downloaded': 'Descarga completada',
|
||||
'open.title': 'Abrir en {app}',
|
||||
'path.appDefault': '{app} (predeterminado)',
|
||||
'path.appsError': 'No se pudieron cargar aplicaciones',
|
||||
@@ -197,19 +169,12 @@ export const fr = {
|
||||
'menu.finder': 'Afficher dans le Finder',
|
||||
'menu.reveal': 'Afficher dans le dossier',
|
||||
'menu.defaultApp': 'Ouvrir dans l’application par défaut',
|
||||
'menu.saveAs': 'Enregistrer sous…',
|
||||
'menu.external': 'Ouvrir dans un navigateur externe',
|
||||
'menu.copyLink': 'Copier l’adresse du lien',
|
||||
'menu.copyPath': 'Copier le chemin du fichier',
|
||||
'menu.copyDirectoryPath': 'Copier le chemin du dossier',
|
||||
'menu.copied': 'Copié',
|
||||
'menu.copyImage': 'Copier l’image',
|
||||
'menu.download': 'Télécharger',
|
||||
'menu.saveFailed': 'Impossible d’enregistrer. Vérifiez la source et la destination, puis réessayez.',
|
||||
'menu.copyFailed': 'Impossible de copier. Vérifiez que le contenu est disponible, puis réessayez.',
|
||||
'menu.saved': 'Enregistré',
|
||||
'menu.downloadStarted': 'Téléchargement démarré',
|
||||
'menu.downloaded': 'Téléchargement terminé',
|
||||
'open.title': 'Ouvrir dans {app}',
|
||||
'path.appDefault': '{app} (par défaut)',
|
||||
'path.appsError': 'Impossible de charger les applications',
|
||||
@@ -234,19 +199,12 @@ export const de = {
|
||||
'menu.finder': 'Im Finder anzeigen',
|
||||
'menu.reveal': 'Im Ordner anzeigen',
|
||||
'menu.defaultApp': 'In der Standardanwendung öffnen',
|
||||
'menu.saveAs': 'Speichern unter…',
|
||||
'menu.external': 'In einem externen Browser öffnen',
|
||||
'menu.copyLink': 'Linkadresse kopieren',
|
||||
'menu.copyPath': 'Dateipfad kopieren',
|
||||
'menu.copyDirectoryPath': 'Ordnerpfad kopieren',
|
||||
'menu.copied': 'Kopiert',
|
||||
'menu.copyImage': 'Bild kopieren',
|
||||
'menu.download': 'Herunterladen',
|
||||
'menu.saveFailed': 'Speichern fehlgeschlagen. Prüfen Sie Quelle und Ziel und versuchen Sie es erneut.',
|
||||
'menu.copyFailed': 'Kopieren fehlgeschlagen. Prüfen Sie, ob der Inhalt verfügbar ist, und versuchen Sie es erneut.',
|
||||
'menu.saved': 'Gespeichert',
|
||||
'menu.downloadStarted': 'Download gestartet',
|
||||
'menu.downloaded': 'Download abgeschlossen',
|
||||
'open.title': 'In {app} öffnen',
|
||||
'path.appDefault': '{app} (Standard)',
|
||||
'path.appsError': 'Anwendungen konnten nicht geladen werden',
|
||||
@@ -271,19 +229,12 @@ export const ru = {
|
||||
'menu.finder': 'Показать в Finder',
|
||||
'menu.reveal': 'Показать в папке',
|
||||
'menu.defaultApp': 'Открыть в приложении по умолчанию',
|
||||
'menu.saveAs': 'Сохранить как…',
|
||||
'menu.external': 'Открыть во внешнем браузере',
|
||||
'menu.copyLink': 'Копировать адрес ссылки',
|
||||
'menu.copyPath': 'Копировать путь к файлу',
|
||||
'menu.copyDirectoryPath': 'Копировать путь к папке',
|
||||
'menu.copied': 'Скопировано',
|
||||
'menu.copyImage': 'Копировать изображение',
|
||||
'menu.download': 'Скачать',
|
||||
'menu.saveFailed': 'Не удалось сохранить. Проверьте источник и место сохранения и повторите попытку.',
|
||||
'menu.copyFailed': 'Не удалось скопировать. Проверьте доступность содержимого и повторите попытку.',
|
||||
'menu.saved': 'Сохранено',
|
||||
'menu.downloadStarted': 'Скачивание началось',
|
||||
'menu.downloaded': 'Скачивание завершено',
|
||||
'open.title': 'Открыть в {app}',
|
||||
'path.appDefault': '{app} (по умолчанию)',
|
||||
'path.appsError': 'Не удалось загрузить приложения',
|
||||
@@ -308,19 +259,12 @@ export const pt = {
|
||||
'menu.finder': 'Mostrar no Finder',
|
||||
'menu.reveal': 'Mostrar na pasta',
|
||||
'menu.defaultApp': 'Abrir no aplicativo padrão',
|
||||
'menu.saveAs': 'Salvar como…',
|
||||
'menu.external': 'Abrir em um navegador externo',
|
||||
'menu.copyLink': 'Copiar endereço do link',
|
||||
'menu.copyPath': 'Copiar caminho do arquivo',
|
||||
'menu.copyDirectoryPath': 'Copiar caminho da pasta',
|
||||
'menu.copied': 'Copiado',
|
||||
'menu.copyImage': 'Copiar imagem',
|
||||
'menu.download': 'Baixar',
|
||||
'menu.saveFailed': 'Não foi possível salvar. Verifique a origem e o destino e tente novamente.',
|
||||
'menu.copyFailed': 'Não foi possível copiar. Verifique se o conteúdo está disponível e tente novamente.',
|
||||
'menu.saved': 'Salvo',
|
||||
'menu.downloadStarted': 'Download iniciado',
|
||||
'menu.downloaded': 'Download concluído',
|
||||
'open.title': 'Abrir em {app}',
|
||||
'path.appDefault': '{app} (padrão)',
|
||||
'path.appsError': 'Não foi possível carregar aplicativos',
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { MenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client'
|
||||
import type { FileActionSource, FileSaveResult, SavedFileId } from '@deepseek-ai/dsh-client-ui-file-actions/client'
|
||||
import { OpenInAppPathController } from '../src/client/open-path.ts'
|
||||
import { OpenInAppController } from '../src/client/controller.ts'
|
||||
import { registerFileMenus } from '@deepseek-ai/dsh-client-ui-file-actions/src/client/context-menus.ts'
|
||||
import { registerContextMenus } from '../src/client/context-menus.ts'
|
||||
|
||||
const sessionId = SessionId('menu-actions')
|
||||
@@ -52,7 +53,10 @@ async function boot() {
|
||||
ctx.provide('fileActions', fileActions as never)
|
||||
ctx.provide('sidebarRight', sidebar as never)
|
||||
ctx.provide('sidebarRightTabs', { get: browserTab } as never)
|
||||
const fiber = ctx.plugin({ apply: (plugin: Context) => { registerContextMenus(plugin, paths, key => key, directories) } })
|
||||
const fiber = ctx.plugin({ apply: (plugin: Context) => {
|
||||
registerContextMenus(plugin, paths, key => key, directories)
|
||||
registerFileMenus(plugin, ctx.fileActions, key => key)
|
||||
} })
|
||||
await fiber.await()
|
||||
onTestFinished(async () => { registry.dispose(); await ctx.fiber.dispose() })
|
||||
const resolve = async (target: MenuTarget) => {
|
||||
@@ -84,13 +88,13 @@ it('routes file actions through the captured pane, line, native association and
|
||||
expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/file.svg', application: 'preview' })
|
||||
await h.choose(file, 'open-in-app.file/reveal')
|
||||
expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/file.svg', action: 'reveal' })
|
||||
await h.choose(file, 'open-in-app.file/copyImage')
|
||||
await h.choose(file, 'file-actions.file/copyImage')
|
||||
await vi.waitFor(() => { expect(h.notify).toHaveBeenCalledWith('menu.copied', true) })
|
||||
const source = h.fileActions.copyImage.mock.calls[0]![0]
|
||||
expect(await (await source.read!(new AbortController().signal)).text()).toBe('<svg/>')
|
||||
h.remote.workspaceFiles.readBytes.mockResolvedValueOnce({ ok: false } as never)
|
||||
await expect(source.read!(new AbortController().signal)).rejects.toThrow('Original file unavailable')
|
||||
await h.choose(file, 'open-in-app.file/saveAs')
|
||||
await h.choose(file, 'file-actions.file/saveAs')
|
||||
await vi.waitFor(() => { expect(h.notify).toHaveBeenCalledWith('menu.saved', true) })
|
||||
const simple = { kind: 'file', value: { sessionId: SessionId('absent'), path: '/file.unknown' } } as const
|
||||
h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] })
|
||||
@@ -104,12 +108,12 @@ it('routes file actions through the captured pane, line, native association and
|
||||
it('keeps copy-path available on failed metadata and reports native action failures', async () => {
|
||||
const h = await boot()
|
||||
const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const
|
||||
h.remote.workspaceFiles.stat.mockResolvedValueOnce({ ok: false } as never)
|
||||
h.remote.workspaceFiles.stat.mockResolvedValueOnce({ ok: false } as never).mockResolvedValueOnce({ ok: false } as never)
|
||||
const menu = await h.resolve(file)
|
||||
expect(menu.source.getSnapshot().find(item => item.id.endsWith('/saveAs'))?.disabled).toBe(true)
|
||||
menu.select('open-in-app.file/copyPath')
|
||||
expect(h.writeText).toHaveBeenCalledWith('/workspace/file.svg')
|
||||
h.remote.workspaceFiles.stat.mockRejectedValueOnce(new Error('offline'))
|
||||
h.remote.workspaceFiles.stat.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('offline'))
|
||||
expect((await h.resolve(file)).source.getSnapshot().find(item => item.id.endsWith('/sidebar'))?.disabled).toBe(true)
|
||||
h.remote.session.openWorkspacePath.mockResolvedValueOnce({ ok: false } as never)
|
||||
await h.choose(file, 'open-in-app.file/reveal')
|
||||
@@ -143,19 +147,19 @@ it('distinguishes completed, requested and cancelled saves and surfaces rejected
|
||||
for (const [status, notice] of [['saved', 'menu.downloaded'], ['requested', 'menu.downloadStarted'], ['cancelled', undefined]] as const) {
|
||||
h.fileActions.save.mockResolvedValueOnce({ status })
|
||||
h.notify.mockClear()
|
||||
await h.choose(image, 'open-in-app.image/download')
|
||||
await h.choose(image, 'file-actions.image/download')
|
||||
if (notice === undefined) expect(h.notify).not.toHaveBeenCalled()
|
||||
else await vi.waitFor(() => { expect(h.notify).toHaveBeenCalledWith(notice, true) })
|
||||
}
|
||||
h.fileActions.save.mockRejectedValueOnce(new Error('disk full'))
|
||||
await h.choose(image, 'open-in-app.image/saveAs')
|
||||
await h.choose(image, 'file-actions.image/saveAs')
|
||||
await vi.waitFor(() => { expect(h.failure).toHaveBeenCalledWith('menu.saveFailed') })
|
||||
})
|
||||
|
||||
it('uses original image reads and enables reveal only for an actual local or saved file', async () => {
|
||||
const h = await boot()
|
||||
const local = { kind: 'image', value: { sessionId, path: 'file.svg', url: 'https://example.com/file', mediaType: 'image/svg+xml' } } as const
|
||||
await h.choose(local, 'open-in-app.image/copy')
|
||||
await h.choose(local, 'file-actions.image/copy')
|
||||
const source = h.fileActions.copyImage.mock.calls[0]![0]
|
||||
expect(source.name).toBe('file.svg')
|
||||
expect((await source.read!(new AbortController().signal)).type).toBe('image/svg+xml')
|
||||
@@ -164,11 +168,23 @@ it('uses original image reads and enables reveal only for an actual local or sav
|
||||
await h.choose(local, 'open-in-app.image/reveal')
|
||||
expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/file.svg', action: 'reveal' })
|
||||
const saved = 'saved-image' as SavedFileId
|
||||
h.fileActions.savedFile.mockReturnValueOnce(saved)
|
||||
await h.choose({ kind: 'image', value: { url: 'https://example.com/file.png', name: 'image.png' } }, 'open-in-app.image/reveal')
|
||||
h.fileActions.savedFile.mockReturnValue(saved)
|
||||
await h.choose({ kind: 'image', value: { url: 'https://example.com/file.png', name: 'image.png' } }, 'file-actions.image/reveal')
|
||||
expect(h.fileActions.reveal).toHaveBeenCalledOnce()
|
||||
const platform = document.documentElement.dataset.platform
|
||||
try {
|
||||
document.documentElement.dataset.platform = 'darwin'
|
||||
const menu = await h.resolve(local)
|
||||
expect(menu.source.getSnapshot().filter(item => item.id.endsWith('/reveal'))).toMatchObject([
|
||||
{ id: 'file-actions.image/reveal', label: 'menu.finder' },
|
||||
])
|
||||
} finally {
|
||||
if (platform === undefined) delete document.documentElement.dataset.platform
|
||||
else document.documentElement.dataset.platform = platform
|
||||
}
|
||||
h.fileActions.savedFile.mockReturnValue(undefined)
|
||||
const unknown = { kind: 'image', value: { sessionId, path: 'file.unknown', url: 'data:image/png;base64,eA==' } } as const
|
||||
await h.choose(unknown, 'open-in-app.image/saveAs')
|
||||
await h.choose(unknown, 'file-actions.image/saveAs')
|
||||
expect((await h.fileActions.save.mock.calls.at(-1)![0].read!(new AbortController().signal)).type).toBe('')
|
||||
h.fileActions.canSaveAs = false
|
||||
const remote = await h.resolve({ kind: 'image', value: { url: 'https://example.com/file.png' } })
|
||||
|
||||
@@ -7,6 +7,7 @@ import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts'
|
||||
import { OpenInAppPathController } from '../src/client/open-path.ts'
|
||||
import { OpenInAppController } from '../src/client/controller.ts'
|
||||
import { registerFileMenus } from '@deepseek-ai/dsh-client-ui-file-actions/src/client/context-menus.ts'
|
||||
import { registerContextMenus } from '../src/client/context-menus.ts'
|
||||
|
||||
afterEach(() => { vi.unstubAllGlobals() })
|
||||
@@ -36,7 +37,10 @@ it('offers image actions on file targets, copies absolute paths, and keeps save
|
||||
ctx.provide('fileActions', { save, copyImage: copy, canSaveAs: true, savedFile: () => undefined } as never)
|
||||
const paths = new OpenInAppPathController(remote)
|
||||
const directories = new OpenInAppController()
|
||||
const fiber = ctx.plugin({ apply: (plugin: Context) => { registerContextMenus(plugin, paths, key => key, directories) } })
|
||||
const fiber = ctx.plugin({ apply: (plugin: Context) => {
|
||||
registerContextMenus(plugin, paths, key => key, directories)
|
||||
registerFileMenus(plugin, ctx.fileActions, key => key)
|
||||
} })
|
||||
await fiber.await()
|
||||
try {
|
||||
const file = { kind: 'file' as const, value: { sessionId: id, path: 'original.svg', line: 42 } }
|
||||
@@ -44,13 +48,13 @@ it('offers image actions on file targets, copies absolute paths, and keeps save
|
||||
await copying.ready
|
||||
expect(copying.source.getSnapshot().map(action => action.id)).toEqual([
|
||||
'open-in-app.file/sidebar', 'open-in-app.file/reveal', 'open-in-app.file/open',
|
||||
'open-in-app.file/copyPath', 'open-in-app.file/copyImage', 'open-in-app.file/download', 'open-in-app.file/saveAs',
|
||||
'open-in-app.file/copyPath', 'file-actions.file/copyImage', 'file-actions.file/download', 'file-actions.file/saveAs',
|
||||
])
|
||||
copying.select('open-in-app.file/copyPath')
|
||||
expect(writeText).toHaveBeenCalledWith('/workspace/original.svg')
|
||||
const downloading = registry.resolve(file)
|
||||
await downloading.ready
|
||||
downloading.select('open-in-app.file/download')
|
||||
downloading.select('file-actions.file/download')
|
||||
downloading.dispose()
|
||||
await vi.waitFor(() => { expect(notify).toHaveBeenCalledWith('menu.downloaded', true) })
|
||||
const source = save.mock.calls[0]?.[0]
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
en: 31ed1a6239427512
|
||||
zh: cb489d77de109d3f
|
||||
/deepseek-ai-dsh-client-ui-primitives/use-this-package/localizing-copy:
|
||||
en: 76a6594fd868c349
|
||||
zh: 85a03e24da9d8e20
|
||||
en: 4d959b5b1d343536
|
||||
zh: 3de5780452dc7335
|
||||
/deepseek-ai-dsh-client-ui-primitives/understand-the-implementation:
|
||||
en: 846ac0f563a53a64
|
||||
zh: bb89d7647bdcc1ab
|
||||
|
||||
@@ -128,7 +128,7 @@ The nearest `MarkdownDelegateProvider` supplies optional `openExternalLink` and
|
||||
|
||||
The atoms cannot read the application locale, so every piece of user-facing copy arrives through required label props. `HoverCard`, `TerminalBlock`, `JsonTree`, `CodeBlock`, `MarkdownText`, `JsonBlock`, `ConnectionIndicator`, `Modal`, `DiffBlock`, `ReadBlock`, `SearchBlock`, `WebBlock`, and `ZoomControls` accept complete localized labels. The package owns no language fallback; omission fails typechecking, and each feature maps its typed `t` seat into the primitive's label interface.
|
||||
|
||||
`Menu.contextual` positions from the pointer without the frame inset, aligns icons per divider group, and closes on a right-click inside the popup. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. `menuPoint(event)` anchors keyboard context events to the trigger. Ordinary dropdowns retain their existing timing.
|
||||
`Menu.contextual` positions from the pointer without the frame inset and closes on a right-click inside the popup. Structured `items` reserve an icon column per divider group; `footer` and each submenu calculate their own groups. Opaque `children` retain their own layout. `exiting` retains an inert popup for its fade; `returnFocus` restores the original control after asynchronous preparation. `MenuSurface.phase` fades the material, direct content, and macOS backing separately so the material keeps blurring the page. `MENU_TRANSITION_MS` supplies both CSS timing and the popup lifecycle timers. `contextMenuTrigger(open)` binds pointer and keyboard gestures to an explicit callback, respects prevented events, and focuses the actual trigger, including in portals. `menuPoint(event)` anchors keyboard context events to the trigger. Ordinary dropdowns retain their existing timing.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ kind: "package-library"
|
||||
|
||||
这些原子组件无法读取应用 locale,因此每段面向用户的文案都必须通过 label prop 提供。`HoverCard`、`TerminalBlock`、`JsonTree`、`CodeBlock`、`MarkdownText`、`JsonBlock`、`ConnectionIndicator`、`Modal`、`DiffBlock`、`ReadBlock`、`SearchBlock`、`WebBlock` 与 `ZoomControls` 接收完整的本地化 label。本包不拥有语言回退;遗漏会导致类型检查失败,各功能会把带类型的 `t` 席位映射到 primitive 的 label 接口。
|
||||
|
||||
`Menu.contextual` 从指针位置定位而不避让顶部栏,按分隔线组对齐图标,并在弹窗内右键时关闭。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。`menuPoint(event)` 将键盘右键事件定位到触发元素。普通下拉菜单保留原有时序。
|
||||
`Menu.contextual` 从指针位置定位而不避让顶部栏,并在弹窗内右键时关闭。结构化 `items` 按分隔线组预留图标栏;`footer` 与各子菜单独立计算分组。不透明的 `children` 保留原有布局。`exiting` 在淡出期间保留不可交互的弹窗;`returnFocus` 在异步准备后恢复原控件焦点。`MenuSurface.phase` 分别对材质层、直接内容和 macOS 背景淡入淡出,让材质层继续模糊页面。`MENU_TRANSITION_MS` 同时提供 CSS 动画与弹窗生命周期计时。`contextMenuTrigger(open)` 将鼠标和键盘手势绑定到显式回调,尊重已阻止的事件,并聚焦实际触发元素,包括 Portal 内元素。`menuPoint(event)` 将键盘右键事件定位到触发元素。普通下拉菜单保留原有时序。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -297,10 +297,3 @@
|
||||
.list[data-menu-phase='dismiss'],
|
||||
.list[data-menu-phase='replace'] { pointer-events: none; }
|
||||
.list[data-context-menu].scrollable { max-height: calc(100vh - 24px); }
|
||||
|
||||
.item[data-menu-icon-space]:not(:has(> .itemIcon))::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 14px;
|
||||
}
|
||||
.compactList .item[data-menu-icon-space]:not(:has(> .itemIcon))::before { width: 12px; }
|
||||
@@ -115,6 +115,25 @@ function isLabel(entry: MenuEntry): entry is MenuLabel {
|
||||
return 'type' in entry && entry.type === 'label'
|
||||
}
|
||||
|
||||
/** Mark icon columns within each separator-delimited data group. */
|
||||
function iconColumns(entries: readonly MenuEntry[], contextual: boolean): ReadonlySet<MenuEntry> {
|
||||
const aligned = new Set<MenuEntry>()
|
||||
if (!contextual) return aligned
|
||||
let group: MenuEntry[] = []
|
||||
const finish = (): void => {
|
||||
if (group.some(entry => !isLabel(entry) && !isSeparator(entry) && entry.icon !== undefined)) {
|
||||
for (const entry of group) aligned.add(entry)
|
||||
}
|
||||
group = []
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (isSeparator(entry)) finish()
|
||||
else group.push(entry)
|
||||
}
|
||||
finish()
|
||||
return aligned
|
||||
}
|
||||
|
||||
/** Unplaced portal list: hidden but laid out at a fixed origin so offsetWidth/offsetHeight are real. */
|
||||
const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
|
||||
|
||||
@@ -462,7 +481,9 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
// scroll clip would crop it, so only submenu-free menus get the height cap.
|
||||
const scrollable = !items.some(entry => !isSeparator(entry) && !isLabel(entry) && entry.submenu !== undefined && entry.submenu.length > 0)
|
||||
|
||||
const renderEntry = (entry: MenuEntry) => {
|
||||
const itemColumns = iconColumns(items, contextual)
|
||||
const footerColumns = iconColumns(footer ?? [], contextual)
|
||||
const renderEntry = (entry: MenuEntry, columns: ReadonlySet<MenuEntry>) => {
|
||||
if (isSeparator(entry)) {
|
||||
return <div key={entry.id} className={css.separator} role="separator" />
|
||||
}
|
||||
@@ -471,6 +492,7 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
}
|
||||
const hasSub = entry.submenu !== undefined && entry.submenu.length > 0
|
||||
const subOpen = hasSub && openSubmenuId === entry.id
|
||||
const subColumns = iconColumns(entry.submenu ?? [], contextual)
|
||||
const selected = entry.id === selectedId || selectedIds?.includes(entry.id) === true
|
||||
return (
|
||||
<div
|
||||
@@ -496,7 +518,7 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
onSelect?.(entry.id)
|
||||
}}
|
||||
>
|
||||
{entry.icon !== undefined && <span className={css.itemIcon}>{entry.icon}</span>}
|
||||
{(entry.icon !== undefined || columns.has(entry)) && <span aria-hidden="true" className={css.itemIcon}>{entry.icon}</span>}
|
||||
<span className={css.itemLabel}>{entry.label}</span>
|
||||
{entry.shortcut !== undefined && <span aria-hidden="true" className={css.shortcut}><ShortcutKeys keys={entry.shortcut.keys} className={css.shortcutKeys} /></span>}
|
||||
{/* Selection marker is a trailing check (figma .Menu_cell) unless the fill mode carries it. */}
|
||||
@@ -516,7 +538,7 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
aria-keyshortcuts={sub.shortcut?.aria}
|
||||
onClick={() => { onSelect?.(sub.id); refocusAfterSelection() }}
|
||||
>
|
||||
{sub.icon !== undefined && <span className={css.itemIcon}>{sub.icon}</span>}
|
||||
{(sub.icon !== undefined || subColumns.has(sub)) && <span aria-hidden="true" className={css.itemIcon}>{sub.icon}</span>}
|
||||
<span className={css.itemLabel}>{sub.label}</span>
|
||||
{sub.shortcut !== undefined && <span aria-hidden="true" className={css.shortcut}><ShortcutKeys keys={sub.shortcut.keys} className={css.shortcutKeys} /></span>}
|
||||
</button>
|
||||
@@ -527,34 +549,6 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
)
|
||||
}
|
||||
|
||||
// Legacy Slot rows and separators are opaque React children. Inspect this popup before paint
|
||||
// to align mixed groups without a first-frame shift; CSS cannot group siblings by separators.
|
||||
// Child-list changes rescan only the open popup, including its mounted submenu.
|
||||
useLayoutEffect(() => {
|
||||
const list = listRef.current
|
||||
if (!open || !contextual || list === null) return
|
||||
const alignIcons = (): void => {
|
||||
const groups: HTMLElement[][] = []
|
||||
for (const container of list.querySelectorAll(`.${css.viewport}, .${css.footer}, .${css.submenu}`)) {
|
||||
let group: HTMLElement[] = []
|
||||
groups.push(group)
|
||||
for (const entry of container.querySelectorAll<HTMLElement>('[role="menuitem"], [role="separator"]')) {
|
||||
if (entry.closest(`.${css.viewport}, .${css.footer}, .${css.submenu}`) !== container) continue
|
||||
if (entry.getAttribute('role') === 'separator') { group = []; groups.push(group) }
|
||||
else group.push(entry)
|
||||
}
|
||||
}
|
||||
for (const group of groups) {
|
||||
const hasIcon = group.some(item => item.querySelector(`:scope > .${css.itemIcon}`) !== null)
|
||||
for (const item of group) item.toggleAttribute('data-menu-icon-space', hasIcon)
|
||||
}
|
||||
}
|
||||
alignIcons()
|
||||
const observer = new MutationObserver(alignIcons)
|
||||
observer.observe(list, { childList: true, subtree: true })
|
||||
return () => { observer.disconnect() }
|
||||
}, [open, contextual, items, children, footer, openSubmenuId])
|
||||
|
||||
// Submenu exclusivity is decided from the list's own bubble, by DOM:
|
||||
// reaching a top-level row that is not a submenu parent — by pointer or by
|
||||
// focus, data row or component row — closes the open card. A parent opens
|
||||
@@ -597,12 +591,12 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI
|
||||
onFocus={collapseSubmenuFrom}
|
||||
>
|
||||
<div className={css.viewport} role="presentation">
|
||||
{items.map(renderEntry)}
|
||||
{items.map(entry => renderEntry(entry, itemColumns))}
|
||||
{children}
|
||||
</div>
|
||||
{footer !== undefined && footer.length > 0 && (
|
||||
<div className={css.footer} role="presentation">
|
||||
{footer.map(renderEntry)}
|
||||
{footer.map(entry => renderEntry(entry, footerColumns))}
|
||||
</div>
|
||||
)}
|
||||
</MenuSurface>
|
||||
|
||||
@@ -118,7 +118,7 @@ export type {
|
||||
export { CodeBlock } from './markdown/CodeBlock.tsx'
|
||||
export type { CodeBlockProps } from './markdown/CodeBlock.tsx'
|
||||
export { JsonBlock } from './markdown/JsonBlock.tsx'
|
||||
export { MarkdownDelegateProvider } from './markdown/MarkdownDelegate.tsx'
|
||||
export { MarkdownDelegateProvider, useMarkdownDelegate } from './markdown/MarkdownDelegate.tsx'
|
||||
export type { MarkdownDelegate, MarkdownDelegateProviderProps, MarkdownExternalLinkHandler } from './markdown/MarkdownDelegate.tsx'
|
||||
export { DetailDocument, detailDocumentState, useDetailDocumentLabels } from './DetailDocument.tsx'
|
||||
export type { DetailDocumentCopy, DetailDocumentLabels, DetailDocumentRead, DetailDocumentState } from './DetailDocument.tsx'
|
||||
@@ -140,4 +140,4 @@ export { formatQuoteText } from './markdown/quote-text.ts'
|
||||
|
||||
export type { MarkdownMenuTarget } from './markdown/MarkdownDelegate.tsx'
|
||||
|
||||
export { menuPoint } from './menu-point.ts'
|
||||
export { menuPoint, contextMenuTrigger } from './menu-point.ts'
|
||||
@@ -1,4 +1,4 @@
|
||||
import { menuPoint } from '../menu-point.ts'
|
||||
import { menuPoint, contextMenuTrigger } from '../menu-point.ts'
|
||||
/**
|
||||
* Direct mdast→React markdown renderer. Replaces the react-markdown /
|
||||
* remark-rehype pipeline with one switch over parsed nodes so streaming can
|
||||
@@ -362,9 +362,7 @@ function renderNode(node: Md.RootContent, key: Key, context: MarkdownRenderConte
|
||||
aria-label={mention.label}
|
||||
data-file-path={mention.title}
|
||||
onClick={mention.open}
|
||||
onContextMenu={mention.openMenu === undefined ? undefined : (event) => {
|
||||
event.preventDefault(); event.stopPropagation(); mention.openMenu?.(menuPoint(event))
|
||||
}}
|
||||
{...contextMenuTrigger(mention.openMenu)}
|
||||
>
|
||||
<LinkIconMedium kind={classifyLinkPath(value)} className={css.linkIcon} />
|
||||
{value}
|
||||
@@ -600,10 +598,9 @@ function MarkdownAnchor({ href, glyph, children }: {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
onContextMenu={!external || openContextMenu === undefined ? undefined : (event) => {
|
||||
event.preventDefault(); event.stopPropagation()
|
||||
openContextMenu({ kind: 'url', url: href }, menuPoint(event))
|
||||
}}
|
||||
{...contextMenuTrigger(!external || openContextMenu === undefined ? undefined : (point) => {
|
||||
openContextMenu({ kind: 'url', url: href }, point)
|
||||
})}
|
||||
{...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
|
||||
onClick={open === undefined ? undefined : (event) => {
|
||||
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
|
||||
@@ -643,10 +640,9 @@ function MarkdownFileLink({ file, glyph, children }: {
|
||||
type="button"
|
||||
className={clsx(css.fileMention, css.fileLink)}
|
||||
title={src === undefined ? file.path : undefined}
|
||||
onContextMenu={openContextMenu === undefined ? undefined : (event) => {
|
||||
event.preventDefault(); event.stopPropagation()
|
||||
openContextMenu({ kind: 'file', ...file }, menuPoint(event))
|
||||
}}
|
||||
{...contextMenuTrigger(openContextMenu === undefined ? undefined : (point) => {
|
||||
openContextMenu({ kind: 'file', ...file }, point)
|
||||
})}
|
||||
data-file-path={file.path} data-file-line={file.line}
|
||||
onClick={() => { openFile(file.path, file.line === undefined ? undefined : { line: file.line }) }}
|
||||
>
|
||||
|
||||
@@ -10,3 +10,29 @@ export function menuPoint(event: { clientX: number; clientY: number; currentTarg
|
||||
const rect = event.currentTarget.getBoundingClientRect()
|
||||
return { x: rect.left, y: rect.bottom }
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a declared object to pointer and keyboard context gestures. Nested handlers
|
||||
* that prevent the event keep ownership; absent callbacks leave native behavior.
|
||||
* @param open - owner callback capturing the object, or undefined to opt out.
|
||||
* @returns handlers for the actual trigger element, including portaled elements.
|
||||
*/
|
||||
export function contextMenuTrigger(open: ((point: { x: number; y: number }) => void) | undefined):
|
||||
Pick<import('react').HTMLAttributes<HTMLElement>, 'onContextMenu' | 'onKeyDown'> {
|
||||
if (open === undefined) return {}
|
||||
const show = (event: import('react').SyntheticEvent<HTMLElement>, point: { x: number; y: number }): void => {
|
||||
if (event.defaultPrevented) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
event.currentTarget.focus({ preventScroll: true })
|
||||
open(point)
|
||||
}
|
||||
return {
|
||||
onContextMenu: (event) => { show(event, menuPoint(event)) },
|
||||
onKeyDown: (event) => {
|
||||
if (event.repeat || event.nativeEvent.isComposing || event.ctrlKey || event.altKey || event.metaKey) return
|
||||
if (event.key !== 'ContextMenu' && !(event.key === 'F10' && event.shiftKey)) return
|
||||
show(event, menuPoint({ clientX: 0, clientY: 0, currentTarget: event.currentTarget }))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Inline text and reference presentation; business rules supply resolved JSON data and actions. */
|
||||
import type { ReactNode } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import { contextMenuTrigger } from './menu-point.ts'
|
||||
import { ReferenceIconRegular, type ReferenceIconKind } from './ReferenceIcon.tsx'
|
||||
import css from './user-text.module.css'
|
||||
import markdownCss from './markdown/MarkdownText.module.css'
|
||||
@@ -26,6 +27,8 @@ export interface ReferenceChipProps {
|
||||
readonly filePath?: string
|
||||
/** Base used to interpret a relative file destination. */
|
||||
readonly fileBase?: 'workspace' | 'workingDirectory'
|
||||
/** Explicit object-menu callback; absent for display-only references. */
|
||||
readonly openContextMenu?: (point: { x: number; y: number }) => void
|
||||
readonly label: string
|
||||
readonly title: string
|
||||
/** Absent for display-only references and previews. */
|
||||
@@ -38,20 +41,33 @@ export interface ReferenceChipProps {
|
||||
* @param props - resolved visual fields and optional action from the owning renderer.
|
||||
* @returns an inline label, or a keyboard-accessible button when activation is supplied.
|
||||
*/
|
||||
export function ReferenceChip({ appearance, label, title, onActivate, filePath, fileBase }: ReferenceChipProps): ReactNode {
|
||||
export function ReferenceChip({
|
||||
appearance, label, title, onActivate, filePath, fileBase, openContextMenu,
|
||||
}: ReferenceChipProps): ReactNode {
|
||||
const slash = appearance === 'skill' || appearance === 'command'
|
||||
const contents = <>
|
||||
{!slash && <ReferenceIconRegular kind={appearance} size={16} className={css.refIcon} />}
|
||||
{label}
|
||||
</>
|
||||
const menu = contextMenuTrigger(openContextMenu)
|
||||
const className = clsx(css.refChip, slash && css.slashChip)
|
||||
return onActivate === undefined
|
||||
? <span className={className} data-ref-chip={appearance} data-file-path={filePath}
|
||||
data-file-base={fileBase} title={title}>{contents}</span>
|
||||
? <span
|
||||
{...menu}
|
||||
tabIndex={openContextMenu === undefined ? undefined : 0}
|
||||
className={className}
|
||||
data-ref-chip={appearance}
|
||||
data-file-path={filePath}
|
||||
data-file-base={fileBase}
|
||||
title={title}
|
||||
>{contents}</span>
|
||||
: <button
|
||||
type="button"
|
||||
{...menu}
|
||||
className={clsx(className, markdownCss.fileMention)}
|
||||
data-ref-chip={appearance} data-file-path={filePath} data-file-base={fileBase}
|
||||
data-ref-chip={appearance}
|
||||
data-file-path={filePath}
|
||||
data-file-base={fileBase}
|
||||
title={title}
|
||||
onClick={(event) => {
|
||||
if (event.detail > 1 || (event.detail !== 0 && event.currentTarget.ownerDocument.getSelection()?.isCollapsed === false)) return
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { Menu, MenuItemButton } from '../src/Menu.tsx'
|
||||
import { ReferenceChip } from '../src/user-text.tsx'
|
||||
|
||||
afterEach(() => { cleanup(); document.documentElement.style.removeProperty('--dsh-frame-top-clearance') })
|
||||
afterEach(() => { vi.restoreAllMocks(); cleanup(); document.documentElement.style.removeProperty('--dsh-frame-top-clearance') })
|
||||
|
||||
it('places pointer menus at the cursor above the frame inset and focuses after portal placement', async () => {
|
||||
document.documentElement.style.setProperty('--dsh-frame-top-clearance', '96px')
|
||||
@@ -24,11 +25,80 @@ it('groups data icons per divider, preserves component rows, and makes exit fram
|
||||
items: [{ id: 'first', label: 'First', icon: <svg /> }, { id: 'second', label: 'Second' },
|
||||
{ type: 'separator' as const, id: 'split' }, { id: 'third', label: 'Third' }] }
|
||||
const view = render(<Menu {...props}><MenuItemButton onSelect={() => {}}>Plugin</MenuItemButton></Menu>)
|
||||
expect(view.getByRole('menuitem', { name: 'First' }).hasAttribute('data-menu-icon-space')).toBe(true)
|
||||
expect(view.getByRole('menuitem', { name: 'Second' }).hasAttribute('data-menu-icon-space')).toBe(true)
|
||||
expect(view.getByRole('menuitem', { name: 'Third' }).hasAttribute('data-menu-icon-space')).toBe(false)
|
||||
expect(view.getByRole('menuitem', { name: 'Plugin' }).hasAttribute('data-menu-icon-space')).toBe(false)
|
||||
expect(view.getByRole('menuitem', { name: 'First' }).firstElementChild?.getAttribute('aria-hidden') === 'true').toBe(true)
|
||||
expect(view.getByRole('menuitem', { name: 'Second' }).firstElementChild?.getAttribute('aria-hidden') === 'true').toBe(true)
|
||||
expect(view.getByRole('menuitem', { name: 'Third' }).firstElementChild?.getAttribute('aria-hidden') === 'true').toBe(false)
|
||||
expect(view.getByRole('menuitem', { name: 'Plugin' }).firstElementChild?.getAttribute('aria-hidden') === 'true').toBe(false)
|
||||
view.rerender(<Menu {...props} exiting="replace" />)
|
||||
expect(view.queryByRole('menu')).toBeNull()
|
||||
expect(document.querySelector('[data-menu-phase="replace"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('aligns data groups, footers and submenus independently without modifying slot rows', () => {
|
||||
const hasColumn = (row: HTMLElement) => row.firstElementChild?.getAttribute('aria-hidden') === 'true'
|
||||
const view = render(<Menu open contextual anchor={null} onClose={() => {}}
|
||||
items={[{ id: 'plain', label: 'Plain' }, { type: 'separator', id: 'split' },
|
||||
{ type: 'label', id: 'heading', text: 'Actions' },
|
||||
{ id: 'icon', label: 'Icon', icon: <svg /> }, { id: 'aligned', label: 'Aligned' },
|
||||
{ id: 'parent', label: 'Parent', submenu: [
|
||||
{ id: 'child', label: 'Child' }, { type: 'separator', id: 'subsplit' },
|
||||
{ id: 'subicon', label: 'Sub icon', icon: <svg /> }, { id: 'subaligned', label: 'Sub aligned' },
|
||||
] }]}
|
||||
footer={[{ id: 'footer', label: 'Footer' }, { id: 'footerIcon', label: 'Footer icon', icon: <svg /> }]}
|
||||
>
|
||||
<MenuItemButton onSelect={() => {}}>Plugin plain</MenuItemButton>
|
||||
<MenuItemButton icon={<svg />} onSelect={() => {}}>Plugin icon</MenuItemButton>
|
||||
</Menu>)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Plain' }))).toBe(false)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Aligned' }))).toBe(true)
|
||||
expect(view.getByRole('menuitem', { name: 'Aligned' }).firstElementChild?.textContent).toBe('')
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Footer' }))).toBe(true)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Plugin plain' }))).toBe(false)
|
||||
expect(view.getByRole('menuitem', { name: 'Plugin icon' }).querySelector('svg')).not.toBeNull()
|
||||
fireEvent.focus(view.getByRole('menuitem', { name: 'Parent' }))
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Child' }))).toBe(false)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Sub aligned' }))).toBe(true)
|
||||
view.rerender(<Menu open contextual anchor={null} onClose={() => {}}
|
||||
items={[{ id: 'icon', label: 'Icon', icon: <svg /> }, { id: 'plain', label: 'Plain' }]}
|
||||
footer={[{ id: 'footer', label: 'Footer' }]} />)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Plain' }))).toBe(true)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Footer' }))).toBe(false)
|
||||
view.rerender(<Menu open anchor={null} onClose={() => {}}
|
||||
items={[{ id: 'icon', label: 'Icon', icon: <svg /> }, { id: 'plain', label: 'Plain' }]}
|
||||
footer={[{ id: 'footer', label: 'Footer' }]} />)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Plain' }))).toBe(false)
|
||||
expect(hasColumn(view.getByRole('menuitem', { name: 'Footer' }))).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a menu-only reference focusable without inventing an activation action', () => {
|
||||
const open = vi.fn()
|
||||
const view = render(<ReferenceChip appearance="file" label="Reference" title="File reference" openContextMenu={open} />)
|
||||
const chip = view.getByText('Reference')
|
||||
expect(chip.tabIndex).toBe(0)
|
||||
expect(chip.tagName).toBe('SPAN')
|
||||
fireEvent.keyDown(chip, { key: 'F10', shiftKey: true })
|
||||
expect(open).toHaveBeenCalledOnce()
|
||||
expect(document.activeElement).toBe(chip)
|
||||
})
|
||||
|
||||
it('keeps reference activation separate from selection and repeated clicks', () => {
|
||||
const activate = vi.fn()
|
||||
const open = vi.fn()
|
||||
const view = render(<ReferenceChip appearance="file" label="Reference" title="Reference" onActivate={activate} openContextMenu={open} />)
|
||||
const chip = view.getByRole('button')
|
||||
fireEvent.click(chip, { detail: 2 })
|
||||
const selection = document.getSelection()!
|
||||
selection.removeAllRanges()
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(chip)
|
||||
selection.addRange(range)
|
||||
try {
|
||||
expect(selection.isCollapsed).toBe(false)
|
||||
fireEvent.click(chip, { detail: 1 })
|
||||
expect(activate).not.toHaveBeenCalled()
|
||||
fireEvent.contextMenu(chip)
|
||||
expect(open).toHaveBeenCalledOnce()
|
||||
} finally { selection.removeAllRanges() }
|
||||
fireEvent.click(chip, { detail: 1 })
|
||||
expect(activate).toHaveBeenCalledOnce()
|
||||
})
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 0b41c33743e5b422
|
||||
zh: 551896094c03f57e
|
||||
/deepseek-ai-dsh-client-ui-reference/use-this-package/failure-behavior:
|
||||
en: 0b81041e08a1201d
|
||||
zh: 09c77eca4b7ede2d
|
||||
en: 260ee268bd8c61fa
|
||||
zh: 6ba46a38c5ad3ed1
|
||||
/deepseek-ai-dsh-client-ui-reference/understand-the-implementation:
|
||||
en: dbfe93987c800112
|
||||
zh: 200d477cc8cd8a1a
|
||||
|
||||
@@ -39,7 +39,7 @@ One unavailable or failed candidate domain yields no rows for that domain while
|
||||
|
||||
Click a file reference in the composer to preview its current contents in the right Sidebar. Quoted paths retain their spaces, and paths resolve in the composer Session. Folder and Session references retain their editing behavior.
|
||||
|
||||
File and folder chips expose their decoded path through `data-file-path` for the enclosing transcript menu.
|
||||
Interactive file chips declare workspace-relative menu targets through the scoped Markdown delegate. Display-only chips do not install context-menu handlers.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话
|
||||
|
||||
点击输入框中的文件引用,可在右侧栏预览文件当前的内容。带引号路径中的空格会保留,路径按输入框所属 Session 解析。文件夹和 Session 引用保留原有的编辑行为。
|
||||
|
||||
文件与目录标签通过 `data-file-path` 提供已解码路径,供外层 transcript 菜单使用。
|
||||
可交互文件 chip 通过作用域内的 Markdown 委托声明相对工作区的菜单目标。仅展示的 chip 不安装右键菜单处理器。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useState } from 'react'
|
||||
import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { Button, Modal, ReferenceChip, useMarkdownDelegate } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { NS } from './locales.ts'
|
||||
import type {} from './user-text-rules.ts'
|
||||
|
||||
@@ -24,6 +24,7 @@ type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace<FileReferenceIn
|
||||
* @returns an inline chip and, after a navigation failure, its body-portaled dialog.
|
||||
*/
|
||||
export function FileReference({ node, raw, interactive, openFile, t }: FileReferenceProps) {
|
||||
const { openContextMenu } = useMarkdownDelegate()
|
||||
const [failedPath, setFailedPath] = useState<string | null>(null)
|
||||
const { path, label } = node.data
|
||||
const close = () => { setFailedPath(null) }
|
||||
@@ -37,7 +38,17 @@ export function FileReference({ node, raw, interactive, openFile, t }: FileRefer
|
||||
setFailedPath(null)
|
||||
}
|
||||
return <>
|
||||
<ReferenceChip appearance="file" filePath={path} fileBase="workspace" label={label} title={raw} {...interactive ? { onActivate: open } : {}} />
|
||||
<ReferenceChip
|
||||
appearance="file"
|
||||
filePath={path}
|
||||
fileBase="workspace"
|
||||
label={label}
|
||||
title={raw}
|
||||
{...!interactive || openContextMenu === undefined ? {} : {
|
||||
openContextMenu: (point) => { openContextMenu({ kind: 'file', path, base: 'workspace' }, point) },
|
||||
}}
|
||||
{...interactive ? { onActivate: open } : {}}
|
||||
/>
|
||||
{interactive && failedPath === path && <Modal
|
||||
open
|
||||
onClose={close}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import type { ComponentProps } from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { MarkdownDelegateProvider } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { FileReference, FolderReference } from '../src/client/FileReference.tsx'
|
||||
import { en } from '../src/client/locales.ts'
|
||||
|
||||
@@ -55,3 +56,24 @@ describe('FileReference', () => {
|
||||
expect(view.getByRole('button', { name: 'a b.md' })).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
it('declares workspace-relative targets for pointer and keyboard gestures and leaves previews inert', () => {
|
||||
const open = vi.fn()
|
||||
const input = props(vi.fn())
|
||||
const view = render(<MarkdownDelegateProvider openContextMenu={open}>
|
||||
<FileReference {...input} />
|
||||
</MarkdownDelegateProvider>)
|
||||
const chip = view.getByRole('button', { name: 'a b.md' })
|
||||
chip.getBoundingClientRect = () => new DOMRect(20, 30, 100, 20)
|
||||
fireEvent.contextMenu(chip, { clientX: 40, clientY: 50 })
|
||||
fireEvent.keyDown(chip, { key: 'F10', shiftKey: true })
|
||||
expect(open.mock.calls).toEqual([
|
||||
[{ kind: 'file', path: 'docs/a b.md', base: 'workspace' }, { x: 40, y: 50 }],
|
||||
[{ kind: 'file', path: 'docs/a b.md', base: 'workspace' }, { x: 20, y: 50 }],
|
||||
])
|
||||
view.rerender(<MarkdownDelegateProvider openContextMenu={open}>
|
||||
<FileReference {...input} interactive={false} />
|
||||
</MarkdownDelegateProvider>)
|
||||
expect(fireEvent.contextMenu(view.getByText('a b.md'))).toBe(true)
|
||||
expect(open).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
@@ -8,7 +8,9 @@
|
||||
|
||||
/** Simplified Chinese dictionary and key-set source of truth. */
|
||||
export const zh = {
|
||||
'menu.close': '关闭', 'menu.closeOthers': '关闭其他标签页', 'menu.closeRight': '关闭右侧标签页',
|
||||
'menu.close': '关闭',
|
||||
'menu.closeOthers': '关闭其他标签页',
|
||||
'menu.closeRight': '关闭右侧标签页',
|
||||
'command.close': '关闭当前页面/窗口',
|
||||
'command.refresh': '刷新当前页面',
|
||||
'command.noRefresh': '当前页面不支持刷新',
|
||||
@@ -51,7 +53,9 @@ export type SidebarRightKey = keyof typeof zh
|
||||
|
||||
/** English dictionary, checked against the Chinese key set. */
|
||||
export const en = {
|
||||
'menu.close': 'Close', 'menu.closeOthers': 'Close Other Tabs', 'menu.closeRight': 'Close Tabs to the Right',
|
||||
'menu.close': 'Close',
|
||||
'menu.closeOthers': 'Close Other Tabs',
|
||||
'menu.closeRight': 'Close Tabs to the Right',
|
||||
'command.close': 'Close current page or window',
|
||||
'command.refresh': 'Refresh current page',
|
||||
'command.noRefresh': 'This page cannot be refreshed',
|
||||
@@ -91,7 +95,9 @@ export const en = {
|
||||
|
||||
/** Japanese copy, checked against the English keys. */
|
||||
export const ja = {
|
||||
'menu.close': '閉じる', 'menu.closeOthers': '他のタブを閉じる', 'menu.closeRight': '右側のタブを閉じる',
|
||||
'menu.close': '閉じる',
|
||||
'menu.closeOthers': '他のタブを閉じる',
|
||||
'menu.closeRight': '右側のタブを閉じる',
|
||||
'command.close': '現在のページまたはウィンドウを閉じる',
|
||||
'command.refresh': '現在のページを更新',
|
||||
'command.noRefresh': 'このページは更新できません',
|
||||
@@ -131,7 +137,9 @@ export const ja = {
|
||||
|
||||
/** Spanish dictionary, checked against the English keys. */
|
||||
export const es = {
|
||||
'menu.close': 'Cerrar', 'menu.closeOthers': 'Cerrar otras pestañas', 'menu.closeRight': 'Cerrar pestañas a la derecha',
|
||||
'menu.close': 'Cerrar',
|
||||
'menu.closeOthers': 'Cerrar otras pestañas',
|
||||
'menu.closeRight': 'Cerrar pestañas a la derecha',
|
||||
'command.close': 'Cerrar la página o ventana actual',
|
||||
'command.refresh': 'Actualizar la página actual',
|
||||
'command.noRefresh': 'Esta página no se puede actualizar',
|
||||
@@ -171,7 +179,9 @@ export const es = {
|
||||
|
||||
/** French dictionary, checked against the English keys. */
|
||||
export const fr = {
|
||||
'menu.close': 'Fermer', 'menu.closeOthers': 'Fermer les autres onglets', 'menu.closeRight': 'Fermer les onglets à droite',
|
||||
'menu.close': 'Fermer',
|
||||
'menu.closeOthers': 'Fermer les autres onglets',
|
||||
'menu.closeRight': 'Fermer les onglets à droite',
|
||||
'command.close': 'Fermer la page ou la fenêtre actuelle',
|
||||
'command.refresh': 'Actualiser la page actuelle',
|
||||
'command.noRefresh': 'Cette page ne peut pas être actualisée',
|
||||
@@ -211,7 +221,9 @@ export const fr = {
|
||||
|
||||
/** German dictionary, checked against the English keys. */
|
||||
export const de = {
|
||||
'menu.close': 'Schließen', 'menu.closeOthers': 'Andere Tabs schließen', 'menu.closeRight': 'Tabs rechts schließen',
|
||||
'menu.close': 'Schließen',
|
||||
'menu.closeOthers': 'Andere Tabs schließen',
|
||||
'menu.closeRight': 'Tabs rechts schließen',
|
||||
'command.close': 'Aktuelle Seite oder Fenster schließen',
|
||||
'command.refresh': 'Aktuelle Seite aktualisieren',
|
||||
'command.noRefresh': 'Diese Seite kann nicht aktualisiert werden',
|
||||
@@ -251,7 +263,9 @@ export const de = {
|
||||
|
||||
/** Russian dictionary, checked against the English keys. */
|
||||
export const ru = {
|
||||
'menu.close': 'Закрыть', 'menu.closeOthers': 'Закрыть другие вкладки', 'menu.closeRight': 'Закрыть вкладки справа',
|
||||
'menu.close': 'Закрыть',
|
||||
'menu.closeOthers': 'Закрыть другие вкладки',
|
||||
'menu.closeRight': 'Закрыть вкладки справа',
|
||||
'command.close': 'Закрыть текущую страницу или окно',
|
||||
'command.refresh': 'Обновить текущую страницу',
|
||||
'command.noRefresh': 'Эту страницу невозможно обновить',
|
||||
@@ -291,7 +305,9 @@ export const ru = {
|
||||
|
||||
/** Portuguese dictionary, checked against the English keys. */
|
||||
export const pt = {
|
||||
'menu.close': 'Fechar', 'menu.closeOthers': 'Fechar outras abas', 'menu.closeRight': 'Fechar abas à direita',
|
||||
'menu.close': 'Fechar',
|
||||
'menu.closeOthers': 'Fechar outras abas',
|
||||
'menu.closeRight': 'Fechar abas à direita',
|
||||
'command.close': 'Fechar a página ou janela atual',
|
||||
'command.refresh': 'Atualizar página atual',
|
||||
'command.noRefresh': 'Esta página não pode ser atualizada',
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 2e3c306b13d3bc25
|
||||
zh: 77127f01763b3976
|
||||
/deepseek-ai-dsh-client-ui-tool/use-this-package/built-in-views:
|
||||
en: ae24770ebec6835d
|
||||
zh: 26d798c30ecba409
|
||||
en: 4b32498f182a84cc
|
||||
zh: 1daa6a15d8df961b
|
||||
/deepseek-ai-dsh-client-ui-tool/understand-the-implementation:
|
||||
en: 00bc7b0c84edc603
|
||||
zh: 1cfcf5b435248a91
|
||||
|
||||
@@ -57,7 +57,7 @@ Question rows pair answers with questions by id, using the tool result or the `u
|
||||
|
||||
Answer-panel buttons belong to the question renderer. It composes `DisclosureRow` with its own action and transcript; generic `ToolRow` does not select or dispatch question actions.
|
||||
|
||||
Tool file buttons expose their recorded path through `data-file-path` for the enclosing transcript menu; display labels do not replace the target.
|
||||
File and URL controls declare context-menu targets through the scoped Markdown delegate. File targets carry their recorded path and line for both pointer and keyboard gestures.
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字
|
||||
|
||||
回答面板按钮归问题 renderer 所有。它使用 `DisclosureRow` 组合自己的操作与 transcript;通用 `ToolRow` 不选择或派发问题操作。
|
||||
|
||||
工具文件按钮通过 `data-file-path` 提供记录的路径,供外层 transcript 菜单使用;显示标签不会替代目标。
|
||||
文件与 URL 控件通过作用域内的 Markdown 委托声明右键菜单目标。鼠标和键盘手势的文件目标都携带记录的路径与行号。
|
||||
|
||||
-----
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import clsx from 'clsx'
|
||||
import {
|
||||
CodeBlock, DiffBlock, DisclosureRow, IconInspectOutlineRegular, ReadBlock, SearchBlock,
|
||||
TerminalBlock, TextShimmer, WebBlock,
|
||||
diffTotals,
|
||||
diffTotals, contextMenuTrigger, useMarkdownDelegate,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { PropsRenderSlots, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { OpenFileOptions, UseDisclosure } from '@deepseek-ai/dsh-client-ui-chat/client'
|
||||
@@ -151,6 +151,7 @@ export const ToolRow = memo(function ToolRow({
|
||||
useDisclosure,
|
||||
}: ToolRowProps) {
|
||||
const { expanded, toggle: toggleExpand } = useDisclosure()
|
||||
const { openContextMenu } = useMarkdownDelegate()
|
||||
const terminalLabels = useMemo(() => terminalBlockLabels(t), [t])
|
||||
const diffLabels = useMemo(() => diffBlockLabels(t), [t])
|
||||
const readLabels = useMemo(() => readBlockLabels(t), [t])
|
||||
@@ -208,6 +209,12 @@ export const ToolRow = memo(function ToolRow({
|
||||
// The code variant's program renders through CodeBlock (shiki), so only its
|
||||
// output joins the IN/OUT card; every other variant's input does too.
|
||||
const cardBody = variant === 'code' ? null : bodyText
|
||||
const fileMenu = useMemo(() => contextMenuTrigger(openContextMenu === undefined || filePath === undefined ? undefined : (point) => {
|
||||
openContextMenu({ kind: 'file', path: filePath, ...(filePathLine === undefined ? {} : { line: filePathLine }) }, point)
|
||||
}), [openContextMenu, filePath, filePathLine])
|
||||
const urlMenu = useMemo(() => contextMenuTrigger(openContextMenu === undefined || linkHref === undefined ? undefined : (point) => {
|
||||
openContextMenu({ kind: 'url', url: linkHref }, point)
|
||||
}), [openContextMenu, linkHref])
|
||||
const collapsedContent = useMemo(() => summaryText !== '' && (
|
||||
/* An empty summary drops the separator with it (a row that is only
|
||||
its title shows no trailing dot). */
|
||||
@@ -218,8 +225,12 @@ export const ToolRow = memo(function ToolRow({
|
||||
type="button"
|
||||
className={css.fileLink}
|
||||
data-file-path={filePath}
|
||||
{...fileMenu}
|
||||
onClick={openFile}
|
||||
onKeyDown={summaryLinkKeyDown}
|
||||
onKeyDown={(event) => {
|
||||
summaryLinkKeyDown(event)
|
||||
fileMenu.onKeyDown?.(event)
|
||||
}}
|
||||
>
|
||||
<TextShimmer>{summaryText}</TextShimmer>
|
||||
</button>
|
||||
@@ -227,10 +238,14 @@ export const ToolRow = memo(function ToolRow({
|
||||
<a
|
||||
className={css.fileLink}
|
||||
href={linkHref}
|
||||
{...urlMenu}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={stopLinkClick}
|
||||
onKeyDown={summaryLinkKeyDown}
|
||||
onKeyDown={(event) => {
|
||||
summaryLinkKeyDown(event)
|
||||
urlMenu.onKeyDown?.(event)
|
||||
}}
|
||||
>
|
||||
<TextShimmer>{summaryText}</TextShimmer>
|
||||
</a>
|
||||
@@ -255,7 +270,7 @@ export const ToolRow = memo(function ToolRow({
|
||||
</TextShimmer>
|
||||
)}
|
||||
</>
|
||||
), [summaryLinkKeyDown, linkHref, openFile, state, suffix, totals, summaryText, exitLabel])
|
||||
), [summaryLinkKeyDown, fileMenu, urlMenu, linkHref, openFile, state, suffix, totals, summaryText, exitLabel])
|
||||
const expandedContent = useMemo(() => open ? (
|
||||
<div className={clsx(css.bodyWrap, detailsBody !== null && css.detailsBodyWrap)}>
|
||||
{askQuestionBody !== null
|
||||
|
||||
@@ -10,6 +10,7 @@ import { localizeAutoReviewDenial, normalizeAutoReviewReason } from '../src/clie
|
||||
import {
|
||||
classifyTool, formatToolBody, resultText, toolRowModel,
|
||||
} from '../src/client/tool/models/tool-call-model.ts'
|
||||
import { MarkdownDelegateProvider } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { ToolRow } from '../src/client/tool/components/ToolRow.tsx'
|
||||
import { GenericToolCard, type GenericToolCardProps } from '../src/client/tool/toolviews/GenericToolCard.tsx'
|
||||
import { zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts'
|
||||
@@ -330,6 +331,27 @@ describe('ToolRow', () => {
|
||||
summary: 'List files', bodyRaw: '{"a":1}', state: 'ok' as const,
|
||||
}
|
||||
|
||||
it('declares file and URL menus without losing line numbers or toggling the row', () => {
|
||||
const open = vi.fn()
|
||||
const view = render(<MarkdownDelegateProvider openContextMenu={open}>
|
||||
<ToolRow {...rowProps} variant="read" summary="file.ts:42" filePath="/workspace/file.ts" filePathLine={42} onOpenFile={() => {}} />
|
||||
</MarkdownDelegateProvider>)
|
||||
const file = view.getByRole('button', { name: 'file.ts:42' })
|
||||
file.getBoundingClientRect = () => new DOMRect(10, 20, 100, 20)
|
||||
fireEvent.contextMenu(file, { clientX: 30, clientY: 40 })
|
||||
fireEvent.keyDown(file, { key: 'F10', shiftKey: true })
|
||||
expect(open.mock.calls).toEqual([
|
||||
[{ kind: 'file', path: '/workspace/file.ts', line: 42 }, { x: 30, y: 40 }],
|
||||
[{ kind: 'file', path: '/workspace/file.ts', line: 42 }, { x: 10, y: 40 }],
|
||||
])
|
||||
expect(view.container.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')).toBe('false')
|
||||
view.rerender(<MarkdownDelegateProvider openContextMenu={open}>
|
||||
<ToolRow {...rowProps} summary="Website" href="https://example.com?q=1#part" />
|
||||
</MarkdownDelegateProvider>)
|
||||
fireEvent.keyDown(view.getByRole('link'), { key: 'ContextMenu' })
|
||||
expect(open).toHaveBeenLastCalledWith({ kind: 'url', url: 'https://example.com?q=1#part' }, { x: 0, y: 0 })
|
||||
})
|
||||
|
||||
it('renders leading icon, title and summary while collapsed', () => {
|
||||
const view = render(<ToolRow {...rowProps} />)
|
||||
expect(view.queryByTestId('tool-icon')).not.toBeNull()
|
||||
|
||||
@@ -617,7 +617,8 @@ function SessionTree({
|
||||
onOpen={open}
|
||||
onRenameRequest={onSessionRenameRequest}
|
||||
renderSlot={renderSlot}
|
||||
openSessionMenu={openSessionMenu} useMenuTarget={useMenuTarget}
|
||||
openSessionMenu={openSessionMenu}
|
||||
useMenuTarget={useMenuTarget}
|
||||
onReveal={node.id === revealSessionId && group.key === revealGroup
|
||||
? () => { onSessionRevealed(node.id) }
|
||||
: undefined}
|
||||
@@ -750,7 +751,8 @@ function FlatList({
|
||||
onOpen={open}
|
||||
onRenameRequest={onSessionRenameRequest}
|
||||
renderSlot={renderSlot}
|
||||
openSessionMenu={openSessionMenu} useMenuTarget={useMenuTarget}
|
||||
openSessionMenu={openSessionMenu}
|
||||
useMenuTarget={useMenuTarget}
|
||||
onReveal={node.id === revealSessionId
|
||||
? () => { onSessionRevealed(node.id) }
|
||||
: undefined}
|
||||
@@ -1367,7 +1369,8 @@ export function WorkspaceBrowser({
|
||||
open={guardedOpen}
|
||||
onSessionRenameRequest={requestSessionRename}
|
||||
renderSlot={renderSlot}
|
||||
openSessionMenu={openSessionMenu} useMenuTarget={useMenuTarget}
|
||||
openSessionMenu={openSessionMenu}
|
||||
useMenuTarget={useMenuTarget}
|
||||
setSessionOrder={saveSessionOrder}
|
||||
revealSessionId={revealSessionId}
|
||||
onSessionRevealed={acknowledgeSessionReveal}
|
||||
@@ -1386,7 +1389,9 @@ export function WorkspaceBrowser({
|
||||
useSessionStatus={useSessionStatus}
|
||||
onSessionRenameRequest={requestSessionRename}
|
||||
renderSlot={renderSlot}
|
||||
openSessionMenu={openSessionMenu} openWorkspaceMenu={openWorkspaceMenu} useMenuTarget={useMenuTarget}
|
||||
openSessionMenu={openSessionMenu}
|
||||
openWorkspaceMenu={openWorkspaceMenu}
|
||||
useMenuTarget={useMenuTarget}
|
||||
workspaces={orderedWorkspaces}
|
||||
ungroupedSessionIds={orderedUngroupedSessionIds}
|
||||
workspaceReady={workspaceReady}
|
||||
|
||||
@@ -120,7 +120,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'contextMenu.content\', () => ctx.slots.register(\n { name: \'contextMenu.content\', key: \'<one key the owner dispatches>\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-context-menu/src/client/index.ts:24',
|
||||
source: 'packages/client/ui-context-menu/src/client/index.ts:25',
|
||||
},
|
||||
{
|
||||
key: 'conversation.approval.detail',
|
||||
|
||||
Generated
+18
-3
@@ -4474,18 +4474,36 @@ importers:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
version: link:../../../vendor/cordis
|
||||
'@deepseek-ai/dsh-api-workspace-files':
|
||||
specifier: workspace:*
|
||||
version: link:../../api/workspace-files
|
||||
'@deepseek-ai/dsh-brand':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/brand
|
||||
'@deepseek-ai/dsh-client-locale':
|
||||
specifier: workspace:*
|
||||
version: link:../locale
|
||||
'@deepseek-ai/dsh-client-test-runtime':
|
||||
specifier: workspace:*
|
||||
version: link:../../test-support/client-runtime
|
||||
'@deepseek-ai/dsh-client-ui-context-menu':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-context-menu
|
||||
'@deepseek-ai/dsh-client-ui-slots':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-slots
|
||||
'@deepseek-ai/dsh-session':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/session
|
||||
'@deepseek-ai/dsh-util-file-drag':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/file-drag
|
||||
'@deepseek-ai/dsh-util-workspace-path':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/workspace-path
|
||||
mime:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.1
|
||||
|
||||
packages/client/ui-file-drag:
|
||||
devDependencies:
|
||||
@@ -4918,9 +4936,6 @@ importers:
|
||||
'@deepseek-ai/dsh-util-workspace-path':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/workspace-path
|
||||
mime:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.1
|
||||
react:
|
||||
specifier: ^18.2.0
|
||||
version: 18.3.1
|
||||
|
||||
Reference in new issue
Block a user