refactor: share compact opening controls for files and directories

This commit is contained in:
creatixchu committed 2026-09-20 11:46:50 +08:00
1 parent c6c9da3eba
commit e969aaff58
14 files changed
+328 -567

No files matched your search

+4 -3
View File
@@ -748,7 +748,7 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action }) +
'## Unviewable binary', '',
'- State: unsupported',
`- Line: ${unsupportedLine.trim()}`,
`- Header control: ${await headerOpen.innerText()}`,
`- Header control has no text: ${String(await headerOpen.innerText() === '')}`,
`- Empty-state control: ${await emptyOpen.innerText()}`,
].join('\n'))
if (STUB_OPENER) {
@@ -757,10 +757,11 @@ fs.appendFileSync(${JSON.stringify(openLog)}, JSON.stringify({ path, action }) +
await emptyOpen.click()
await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(1)
await unsupported.locator('[data-open-path-more]').click()
await page.getByRole('menuitem', { name: 'Show file location', exact: true }).click()
await page.getByRole('menuitem', { name: /^Show file location/ }).click()
await expect.poll(async () => (await opened()).length, { timeout: 15_000 }).toBe(2)
const gestures = await opened()
expect(gestures[0]).toEqual({ path: clip, action: 'open' })
expect(gestures[0]?.action).toBe(process.platform === 'darwin' ? 'open' : 'reveal')
expect([clip, cwd]).toContain(gestures[0]?.path)
expect(gestures[1]?.action).toBe('reveal')
expect([clip, cwd]).toContain(gestures[1]?.path)
if (process.platform === 'darwin') {
@@ -1,64 +0,0 @@
/* Compact Session-header split button beside the round icon buttons. */
.split {
display: inline-flex;
align-items: stretch;
box-sizing: border-box;
height: 24px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: 9px;
overflow: hidden;
font-family: var(--dsw-font-family);
}
.main,
.chevron {
display: inline-flex;
align-items: center;
gap: 3px;
border: 0;
background: none;
color: var(--dsw-alias-label-primary);
font-size: 11px;
font-weight: 400;
line-height: 16px;
cursor: pointer;
white-space: nowrap;
}
.main {
padding: 3px 5px;
}
.main:hover:not(:disabled),
.main:focus-visible,
.chevron:hover,
.chevron:focus-visible {
background: var(--dsw-alias-interactive-bg-hover);
}
.main:disabled {
color: var(--dsw-alias-label-dimmed);
cursor: wait;
}
.main[data-state='error'] {
color: var(--dsw-alias-state-error-primary);
box-shadow: inset 0 0 0 1px var(--dsw-alias-state-error-primary);
}
.chevron {
padding: 3px 4px 3px 3px;
border-left: 0.5px solid var(--dsw-alias-border-l4);
color: var(--dsw-alias-label-secondary);
}
.icon {
flex: none;
}
img.icon {
display: block;
object-fit: contain;
user-select: none;
}
@@ -1,10 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { IconChevronDownOutlineRegular, Menu, Tooltip, type MenuItem } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { NS, type OpenInAppKey } from './locales.ts'
import css from './OpenInAppAction.module.css'
import { OpenTargetButton } from './OpenTargetButton.tsx'
/** Browser operations and state injected into the Session Header contribution. */
export interface OpenInAppActionInjected {
@@ -65,162 +63,36 @@ const APP_LABEL_KEY: Record<string, OpenInAppKey | undefined> = {
konsole: 'app.konsole',
}
/** App ids whose icon image already failed this page; a 404 icon is fetched once, not per menu open. */
const failedIcons = new Set<string>()
/**
* One application's real bundle icon (host-served PNG) with an inline generic
* app-square fallback while the host has none.
* @param props - catalog id, host icon URL, and rendered size.
* @returns the icon image or its fallback glyph.
*/
function AppIcon({ id, url, size }: { id: string; url: string; size: number }): React.JSX.Element {
const [failed, setFailed] = useState(failedIcons.has(id))
if (failed) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
className={css.icon}
aria-hidden
>
<path d="M16 3H8C5.23858 3 3 5.23858 3 8V16C3 18.7614 5.23858 21 8 21H16C18.7614 21 21 18.7614 21 16V8C21 5.23858 18.7614 3 16 3Z" fill="currentColor" fillOpacity="0.05" />
</svg>
)
}
return (
<img
src={url}
width={size}
height={size}
className={css.icon}
alt=""
aria-hidden
draggable={false}
onError={() => {
failedIcons.add(id)
setFailed(true)
}}
/>
)
}
/**
* Quick launches settle well under this delay, so their busy dress never
* paints — the visible dim-and-wait treatment is reserved for launches that
* are actually taking a while, instead of flashing on every click.
*/
const BUSY_DRESS_DELAY_MS = 250
/**
* Session-header split button: the main button opens the session's workspace
* directory in the remembered application, the chevron opens the menu of
* every application the host probed as installed. It renders nothing until
* the host reported at least one nameable application and the session has a
* known workspace directory, so a host without the capability never grows
* the control.
* @param props - session runtime, injected controller face, and localized copy.
* @returns the split button and its menu, or null when there is nothing to offer.
* Adapt the installed directory catalog to the shared opening control.
* @param props - workspace state, installed catalog, and launch operations.
* @returns the shared control, or null without an eligible application and directory.
*/
export function OpenInAppAction(props: OpenInAppActionProps): React.JSX.Element | null {
const { sessionId, useSessions, useOpenInAppApps, useOpenInAppChoice, t } = props
const cwd = useSessions(state => state.byId[sessionId]?.cwd)
const available = useOpenInAppApps(apps => apps)
const choice = useOpenInAppChoice(id => id)
const [open, setOpen] = useState(false)
const [phase, setPhase] = useState<'idle' | 'busy' | 'error'>('idle')
const inFlight = useRef(false)
const busyTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
const errorTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
useEffect(() => () => {
clearTimeout(busyTimer.current)
clearTimeout(errorTimer.current)
}, [])
const apps = (available ?? [])
.map(id => ({ id, labelKey: APP_LABEL_KEY[id] }))
.filter((entry): entry is { id: string; labelKey: OpenInAppKey } => entry.labelKey !== undefined)
const currentEntry = apps.find(entry => entry.id === choice) ?? apps[0]
if (currentEntry === undefined || cwd === undefined || cwd === '') return null
const current = currentEntry.id
const currentLabel = t(currentEntry.labelKey)
const title = phase === 'error' ? t('open.error') : t('open.title', { app: currentLabel })
const launch = (appId: string): void => {
if (inFlight.current) return
inFlight.current = true
// A pending error decay must not flip the button back to idle mid-launch.
clearTimeout(errorTimer.current)
clearTimeout(busyTimer.current)
busyTimer.current = setTimeout(() => { setPhase('busy') }, BUSY_DRESS_DELAY_MS)
props.launch(appId, cwd).then(() => {
inFlight.current = false
clearTimeout(busyTimer.current)
setPhase('idle')
}, () => {
inFlight.current = false
clearTimeout(busyTimer.current)
setPhase('error')
clearTimeout(errorTimer.current)
errorTimer.current = setTimeout(() => { setPhase('idle') }, 2_000)
})
}
const items: MenuItem[] = apps.map(entry => ({
id: entry.id,
label: t(entry.labelKey),
icon: <AppIcon id={entry.id} url={props.iconUrl(entry.id)} size={14} />,
}))
const apps = (available ?? []).flatMap((id) => {
const key = APP_LABEL_KEY[id]
return key === undefined ? [] : [{ id, name: t(key), icon: props.iconUrl(id) }]
})
const preferred = apps.find(app => app.id === choice) ?? apps[0]
if (preferred === undefined || cwd === undefined || cwd === '') return null
return (
<Menu
open={open}
align="end"
dense
selection="fill"
onClose={() => { setOpen(false) }}
items={items}
selectedId={current}
onSelect={(id) => {
setOpen(false)
// A pick while a launch is in flight is ignored whole: persisting the
// choice without launching would leave the button naming an app the
// gesture never opened.
if (inFlight.current) return
props.choose(id)
launch(id)
<OpenTargetButton
key={cwd} kind="directory" applications={apps} defaultId={preferred.id} failed={false} t={t}
execute={async (operation) => {
const id = operation.kind === 'application' ? operation.id : preferred.id
try {
await props.launch(id, cwd)
} catch (_error) {
// Native launch failure is announced by the shared control.
return 'openError'
}
if (operation.kind === 'application') props.choose(id)
return null
}}
anchor={(
<div className={css.split}>
<Tooltip label={phase === 'error' ? t('open.error') : t('open.tooltip')} side="bottom">
<button
type="button"
className={css.main}
data-state={phase}
disabled={phase === 'busy'}
aria-label={title}
onClick={() => { launch(current) }}
>
<AppIcon id={current} url={props.iconUrl(current)} size={13} />
</button>
</Tooltip>
<button
type="button"
className={css.chevron}
aria-expanded={open}
aria-haspopup="menu"
title={t('menu.toggle')}
aria-label={t('menu.toggle')}
onClick={() => { setOpen(value => !value) }}
>
<IconChevronDownOutlineRegular size={10} />
</button>
</div>
)}
/>
)
}
@@ -1,21 +1,13 @@
/**
* Document-header split button: the main button opens the previewed file in
* its default application, the chevron's menu adds the file-manager reveal.
* Both path controls share the gesture hook declared here.
*/
import { useEffect, useRef, useState } from 'react'
/** File association adapter for the shared file/directory opening control. */
import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import {
IconChevronDownOutlineRegular, IconFolderOpenOutlineRegular, IconRightUpOutlineRegular, Menu, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { InjectFace, PropsLocale, PropsRuntime, TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
import type { OpenInAppPathAction, OpenInAppPathFailure } from './open-path.ts'
import { useOpenFailureToast } from './open-failure-toast.tsx'
import { OpenTargetButton } from './OpenTargetButton.tsx'
import type { NS } from './locales.ts'
import css from './OpenPathAction.module.css'
/** Desktop availability and the gesture carrier injected into both path controls. */
export interface OpenPathInjected {
@@ -33,130 +25,52 @@ export type OpenPathActionProps =
& PropsLocale<typeof NS>
& InjectFace<OpenPathInjected>
/** What one path control needs from its props: the file, the injected face, and copy. */
type PathGestureProps = Pick<OpenPathActionProps, 'absolutePath' | 'useOpenInAppDesktop' | 'loadDesktop' | 'openPath'> & {
t: TranslateNS<typeof NS>
/** File inputs shared by the document header and its unpreviewable state. */
type FileOpenTargetProps = Pick<OpenPathActionProps, 'absolutePath' | 'useOpenInAppDesktop' | 'loadDesktop' | 'openPath' | 'applications' | 't'> & {
empty?: boolean
}
/**
* Desktop availability, this control's own pending state, and a gesture
* runner announcing failures through this control's toast. Only the control
* that ran the gesture disables while it settles; failure never persists on
* the control.
* @param props - the file's Host path, the injected face, and copy.
* @returns availability, pending, the toast to render, and the runner.
* Resolve file associations and adapt operations without embedding platform behavior in the control.
* @param props - verified file path, desktop query, native operations, and display variant.
* @returns the shared opening control, or null without a desktop.
*/
export function usePathGesture({ absolutePath, useOpenInAppDesktop, loadDesktop, openPath, t }: PathGestureProps): {
available: boolean
pending: boolean
toast: ReactNode
act: (action: OpenInAppPathAction, application?: string) => void
} {
const desktop = useOpenInAppDesktop(value => value)
const [pending, setPending] = useState(false)
const inFlight = useRef(false)
const { toast, show } = useOpenFailureToast()
useEffect(() => {
if (desktop === null) void loadDesktop()
}, [desktop, loadDesktop])
return {
available: desktop === true,
pending,
toast,
act: (action, application) => {
if (inFlight.current) return
inFlight.current = true
setPending(true)
void openPath(absolutePath, action, application).then((failure) => {
if (failure !== null) show(t(`path.${failure}`))
}).finally(() => { inFlight.current = false; setPending(false) })
},
}
}
/**
* Render the split button, or nothing until the Host reports a desktop.
* @param props - the previewed file, the injected face, and copy.
* @returns the split button with its menu and toast, or null.
*/
export function OpenPathAction(props: OpenPathActionProps): ReactNode {
const { t } = props
const [menuOpen, setMenuOpen] = useState(false)
const { available, pending, toast, act } = usePathGesture(props)
export function FileOpenTarget(props: FileOpenTargetProps): ReactNode {
const desktop = props.useOpenInAppDesktop(value => value)
const [revision, setRevision] = useState(0)
const [association, setAssociation] = useState<{
path: string
apps: readonly SessionWorkspacePathApplication[] | null
} | null>(null)
useEffect(() => {
if (!available) return
if (desktop === null) void props.loadDesktop()
}, [desktop, props.loadDesktop])
useEffect(() => {
if (desktop !== true) return
const controller = new AbortController()
void props.applications(props.absolutePath, controller.signal).then((apps) => {
if (!controller.signal.aborted) setAssociation({ path: props.absolutePath, apps })
})
return () => { controller.abort() }
}, [available, props.absolutePath, props.applications, menuOpen])
}, [desktop, props.absolutePath, props.applications, revision])
if (desktop !== true) return null
const apps = association?.path === props.absolutePath ? association.apps : null
const preferred = apps?.find(app => app.default)
if (!available) return null
const run = (action: OpenInAppPathAction, application?: string): void => {
setMenuOpen(false)
act(action, application)
}
return (
<>
<Menu
className={css.menuAnchor}
open={menuOpen && !pending}
autoFocus
portal
dense
align="end"
onClose={() => { setMenuOpen(false) }}
items={[
{ id: 'open', icon: <IconRightUpOutlineRegular />, label: t('path.defaultApp') },
...(apps ?? []).map(app => ({
id: `app:${app.id}`,
icon: app.icon === null ? <IconRightUpOutlineRegular /> : <img src={app.icon} className={css.appIcon} alt="" />,
label: app.default ? t('path.appDefault', { app: app.name }) : app.name,
})),
...(association?.path === props.absolutePath && apps === null
? [{ id: 'unavailable', label: t('path.appsError'), disabled: true }] : []),
{ id: 'reveal', icon: <IconFolderOpenOutlineRegular />, label: t('path.reveal') },
]}
onSelect={(id) => {
if (id.startsWith('app:')) run('open', id.slice(4))
else run(id === 'reveal' ? 'reveal' : 'open')
}}
anchor={(
<div className={css.split} data-open-path data-state={pending ? 'busy' : 'idle'}>
<Tooltip label={t('path.open.tooltip')} side="bottom" delayMs={500}>
<button
type="button"
className={css.main}
disabled={pending}
data-open-path-open
onClick={() => { run('open') }}
>
{preferred?.icon != null && <img src={preferred.icon} className={css.appIcon} alt="" />}
{t('path.open')}
</button>
</Tooltip>
<button
type="button"
className={css.chevron}
disabled={pending}
aria-haspopup="menu"
aria-expanded={menuOpen && !pending}
aria-label={t('path.more')}
data-open-path-more
onClick={() => { setMenuOpen(value => !value) }}
>
<IconChevronDownOutlineRegular size={11} />
</button>
</div>
)}
/>
{toast}
</>
<OpenTargetButton
key={props.absolutePath} kind="file" applications={apps ?? []} defaultId={apps?.find(app => app.default)?.id}
failed={association?.path === props.absolutePath && apps === null} empty={props.empty} t={props.t}
refresh={() => { setRevision(value => value + 1) }}
execute={operation => props.openPath(props.absolutePath, operation.kind === 'reveal' ? 'reveal' : 'open',
operation.kind === 'application' ? operation.id : undefined)}
/>
)
}
/**
* Render the file adapter in the document header.
* @param props - document owner inputs and injected opening capabilities.
* @returns the shared split button.
*/
export function OpenPathAction(props: OpenPathActionProps): ReactNode {
return <FileOpenTarget {...props} />
}
@@ -1,26 +0,0 @@
/* The empty state's capsule, sized like the preview's own Retry
(ui-sidebar-documentpreview TextPreview `.retry`) so the two recourses read
as one family. */
.open {
display: inline-flex;
flex: none;
gap: 6px;
align-items: center;
height: 32px;
padding: 0 12px 0 14px;
color: var(--dsw-alias-label-primary);
font-size: var(--dsh-content-font-size-secondary, 13px);
font-family: inherit;
background: transparent;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: 16px;
cursor: pointer;
}
.open:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
}
.open:disabled {
cursor: default;
}
@@ -1,11 +1,9 @@
/** Empty-state contribution: open a file the document preview cannot render in its default application. */
/** File opening action in an unpreviewable document's empty state. */
import type { ReactNode } from 'react'
import { IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'
import type { NS } from './locales.ts'
import { usePathGesture, type OpenPathInjected } from './OpenPathAction.tsx'
import css from './OpenPathEmptyAction.module.css'
import { FileOpenTarget, type OpenPathInjected } from './OpenPathAction.tsx'
/** Full props of the unpreviewable empty-state contribution. */
export type OpenPathEmptyActionProps =
@@ -14,27 +12,10 @@ export type OpenPathEmptyActionProps =
& InjectFace<OpenPathInjected>
/**
* Render the default-application open button, or nothing until the Host reports a desktop.
* @param props - the unpreviewable file, the injected face, and copy.
* @returns the open button and its toast, or null.
* Render the same file default action without a dropdown.
* @param props - unpreviewable file and injected opening capabilities.
* @returns the shared file opening action.
*/
export function OpenPathEmptyAction(props: OpenPathEmptyActionProps): ReactNode {
const { t } = props
const { available, pending, toast, act } = usePathGesture(props)
if (!available) return null
return (
<>
<button
type="button"
className={css.open}
disabled={pending}
data-open-path-unpreviewable
onClick={() => { act('open') }}
>
{t('path.unpreviewable')}
<IconRightUpOutlineRegular size={14} />
</button>
{toast}
</>
)
return <FileOpenTarget {...props} empty />
}
@@ -1,4 +1,4 @@
/* Sized to sit in the document header's 28px control row beside its round
/* Sized to sit in the document header's 24px control row beside its round
icon buttons: a hairline pill with a 12px label and a narrow chevron half. */
.menuAnchor {
@@ -11,10 +11,10 @@
display: inline-flex;
align-items: stretch;
box-sizing: border-box;
height: 28px;
height: 24px;
overflow: hidden;
border: 0.5px solid var(--dsw-alias-border-l3);
border-radius: 14px;
border: 0.5px solid var(--dsw-alias-border-l4);
border-radius: 9px;
font-family: var(--dsw-font-family);
}
@@ -26,7 +26,7 @@
border: 0;
background: none;
color: var(--dsw-alias-label-primary);
font-size: 12px;
font-size: 11px;
line-height: 16px;
white-space: nowrap;
cursor: pointer;
@@ -34,12 +34,12 @@
.main {
gap: 4px;
padding: 5px 8px 5px 10px;
padding: 3px 5px;
}
.chevron {
padding: 5px 6px 5px 4px;
border-left: 0.5px solid var(--dsw-alias-border-l3);
padding: 3px 4px 3px 3px;
border-left: 0.5px solid var(--dsw-alias-border-l4);
color: var(--dsw-alias-label-secondary);
}
@@ -57,7 +57,32 @@
}
.appIcon {
width: 16px;
height: 16px;
object-fit: contain;
}
/* The empty state's capsule, sized like the preview's own Retry
(ui-sidebar-documentpreview TextPreview `.retry`) so the two recourses read
as one family. */
.empty {
display: inline-flex;
flex: none;
gap: 6px;
align-items: center;
height: 32px;
padding: 0 12px 0 14px;
color: var(--dsw-alias-label-primary);
font-size: var(--dsh-content-font-size-secondary, 13px);
font-family: inherit;
background: transparent;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: 16px;
cursor: pointer;
}
.empty:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
}
.empty:disabled {
cursor: default;
}
@@ -0,0 +1,143 @@
/** Shared file and directory opener: one default action, application menu, and per-gesture feedback. */
import { useRef, useState } from 'react'
import type { ReactNode } from 'react'
import {
IconChevronDownOutlineRegular, IconFolderOpenOutlineRegular, IconRightUpOutlineRegular, Menu, Tooltip,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import type { OpenInAppPathFailure } from './open-path.ts'
import { useOpenFailureToast } from './open-failure-toast.tsx'
import type { NS } from './locales.ts'
import css from './OpenTargetButton.module.css'
/** Application metadata supplied by either the directory catalog or a file association query. */
export interface OpenTargetApplication {
readonly id: string
readonly name: string
readonly icon: string | null
}
/** Opening intent; default selection remains owned by the target's adapter. */
export type OpenTargetOperation = { readonly kind: 'default' } | { readonly kind: 'application'; readonly id: string } | { readonly kind: 'reveal' }
/** Inputs shared by both target adapters and the file empty-state action. */
export interface OpenTargetButtonProps {
readonly kind: 'file' | 'directory'
readonly applications: readonly OpenTargetApplication[]
readonly defaultId: string | undefined
readonly failed: boolean
readonly empty?: boolean
readonly t: TranslateNS<typeof NS>
readonly execute: (operation: OpenTargetOperation) => Promise<OpenInAppPathFailure | null>
readonly refresh?: () => void
}
/**
* Serialize gestures and announce their failures through the initiating control's toast.
* @param execute - target adapter that returns the failure to announce, or null.
* @param t - localized control copy.
* @returns the pending state, feedback, and guarded action callback.
*/
export function useOpenTargetGesture(execute: OpenTargetButtonProps['execute'], t: TranslateNS<typeof NS>): {
pending: boolean
toast: ReactNode
act: (operation: OpenTargetOperation) => void
} {
const [pending, setPending] = useState(false)
const inFlight = useRef(false)
const { toast, show } = useOpenFailureToast()
return {
pending,
toast,
act: (operation) => {
if (inFlight.current) return
inFlight.current = true
setPending(true)
void execute(operation).then((failure) => {
if (failure !== null) show(t(`path.${failure}`))
}).finally(() => { inFlight.current = false; setPending(false) })
},
}
}
/** One application image with a per-image fallback, shared by main and menu buttons. */
function ApplicationIcon({ source, size = 14 }: { source: string | null; size?: number }): ReactNode {
const [failed, setFailed] = useState(false)
return source === null || failed
? <IconRightUpOutlineRegular size={size} />
: <img src={source} width={size} height={size} className={css.appIcon} alt="" draggable={false} onError={() => { setFailed(true) }} />
}
/**
* Render identical split buttons for files and directories. File reveal always stays last and becomes the default when no app is selected.
* @param props - target applications, default selection, and operations.
* @returns the control and its transient failure feedback.
*/
export function OpenTargetButton(props: OpenTargetButtonProps): ReactNode {
const { applications, defaultId, kind, t } = props
const [menuOpen, setMenuOpen] = useState(false)
const { pending, toast, act } = useOpenTargetGesture(props.execute, t)
const preferred = applications.find(app => app.id === defaultId)
const revealDefault = kind === 'file' && preferred === undefined
const primaryLabel = revealDefault ? t('path.reveal') : t('open.title', { app: preferred?.name ?? '' })
const run = (operation: OpenTargetOperation): void => { setMenuOpen(false); act(operation) }
const primary = (): void => { run({ kind: revealDefault ? 'reveal' : 'default' }) }
const icon = revealDefault
? <IconFolderOpenOutlineRegular size={13} />
: <ApplicationIcon key={preferred?.icon} source={preferred?.icon ?? null} size={13} />
if (props.empty === true) return (
<>
<button type="button" className={css.empty} disabled={pending} data-open-path-unpreviewable onClick={primary}>
{t('path.open')}{icon}
</button>
{toast}
</>
)
return (
<>
<Menu
className={css.menuAnchor}
open={menuOpen && !pending}
autoFocus
portal
dense
align="end"
onClose={() => { setMenuOpen(false) }}
items={[
...applications.map(app => ({
id: `app:${app.id}`,
icon: <ApplicationIcon key={app.icon} source={app.icon} />,
label: app.id === defaultId ? t('path.appDefault', { app: app.name }) : app.name,
})),
...(props.failed ? [{ id: 'unavailable', label: t('path.appsError'), disabled: true }] : []),
...(kind === 'file' ? [{
id: 'reveal', icon: <IconFolderOpenOutlineRegular />,
label: revealDefault ? t('path.appDefault', { app: t('path.reveal') }) : t('path.reveal'),
}] : []),
]}
onSelect={(id) => { run(id === 'reveal' ? { kind: 'reveal' } : { kind: 'application', id: id.slice(4) }) }}
anchor={(
<div className={css.split} data-open-target={kind} data-open-path={kind === 'file' ? '' : undefined} data-state={pending ? 'busy' : 'idle'}>
<Tooltip label={revealDefault ? t('path.reveal') : t('open.tooltip')} side="bottom" delayMs={500}>
<button type="button" className={css.main} disabled={pending} aria-label={primaryLabel} data-open-path-open={kind === 'file' ? '' : undefined} onClick={primary}>
{icon}
</button>
</Tooltip>
<button
type="button" className={css.chevron} disabled={pending}
aria-haspopup="menu" aria-expanded={menuOpen && !pending} aria-label={t('path.more')}
data-open-path-more={kind === 'file' ? '' : undefined}
onClick={() => {
if (!menuOpen) props.refresh?.()
setMenuOpen(value => !value)
}}
>
<IconChevronDownOutlineRegular size={10} />
</button>
</div>
)}
/>
{toast}
</>
)
}
@@ -39,7 +39,7 @@ const PRODUCT_NAMES = {
/** Simplified Chinese dictionary (the key-set source of truth). */
export const zh = {
'open.title': '在 {app} 中打开工作目录',
'open.title': '在 {app} 中打开',
'open.tooltip': '在本地打开',
'open.error': '打开失败',
'menu.toggle': '选择打开方式',
@@ -63,7 +63,7 @@ export const zh = {
/** English dictionary, key-identical to the Chinese source of truth. */
export const en: Record<OpenInAppKey, string> = {
'open.title': 'Open workspace in {app}',
'open.title': 'Open in {app}',
'open.tooltip': 'Open locally',
'open.error': 'Failed to open',
'menu.toggle': 'Choose an app to open in',
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, act } from '@testing-library/react'
import { cleanup, fireEvent, render, screen, act } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
@@ -37,7 +37,7 @@ function bench(over: {
projectionsBySession: {},
jobsBySession: {},
currentAddress: undefined,
} as unknown as SessionListState
} as SessionListState
const apps = createSnapshotStore<readonly string[] | null>(over.apps ?? null)
const choice = createSnapshotStore<string>(over.choice ?? '')
const launch = vi.fn(over.launch ?? (async () => {}))
@@ -57,7 +57,7 @@ function bench(over: {
choose,
iconUrl: (appId: string) => `open-in-app/icon/${appId}`,
t,
} as unknown as OpenInAppActionProps
} as OpenInAppActionProps
return { props, launch, choose }
}
@@ -88,156 +88,57 @@ describe('OpenInAppAction visibility', () => {
})
describe('OpenInAppAction launching', () => {
it('launches without painting the busy dress when the launch settles quickly', async () => {
let resolve: () => void = () => {}
const b = bench({
apps: ['finder'],
cwd: '/w/dir',
launch: () => new Promise((r) => { resolve = r }),
})
it('disables both buttons and ignores duplicate gestures until the launch settles', async () => {
const pending = Promise.withResolvers<undefined>()
const b = bench({ apps: ['finder', 'cursor'], cwd: '/w/dir', launch: () => pending.promise })
const view = render(<OpenInAppAction {...b.props} />)
const main = screen.getByRole('button', { name: t('open.title', { app: zh['app.finder'] }) })
fireEvent.click(main)
expect(main).toHaveProperty('disabled', true)
expect(screen.getByRole('button', { name: zh['path.more'] })).toHaveProperty('disabled', true)
fireEvent.click(main)
expect(b.launch).toHaveBeenCalledOnce()
expect(view.container.querySelector('[data-open-target]')?.getAttribute('data-state')).toBe('busy')
await act(async () => { pending.resolve(undefined) })
expect(main).toHaveProperty('disabled', false)
})
it('announces launch failure without changing the remembered application', async () => {
const b = bench({ apps: ['finder', 'cursor'], cwd: '/w', launch: async () => { throw new Error('gone') } })
render(<OpenInAppAction {...b.props} />)
const main = screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })
fireEvent.click(main)
expect(b.launch).toHaveBeenCalledWith('finder', '/w/dir')
// No flash: the button keeps its idle dress while the launch is fast.
expect((main as HTMLButtonElement).disabled).toBe(false)
expect(main.getAttribute('data-state')).toBe('idle')
// A second click while in flight is ignored rather than double-launching.
fireEvent.click(main)
expect(b.launch).toHaveBeenCalledTimes(1)
resolve()
await waitFor(() => {
fireEvent.click(main)
expect(b.launch).toHaveBeenCalledTimes(2)
})
fireEvent.click(screen.getByRole('button', { name: zh['path.more'] }))
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: 'Cursor' })) })
expect(screen.getByRole('alert').textContent).toContain(zh['path.openError'])
expect(b.choose).not.toHaveBeenCalled()
})
it('dresses a slow launch as busy, then shows the error state on failure', async () => {
vi.useFakeTimers()
let reject: (error: Error) => void = () => {}
const b = bench({
apps: ['finder'],
cwd: '/w/dir',
launch: () => new Promise((_, r) => { reject = r }),
})
render(<OpenInAppAction {...b.props} />)
const main = screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })
fireEvent.click(main)
// The busy dress appears only after the launch has taken a while.
act(() => { vi.advanceTimersByTime(300) })
expect((main as HTMLButtonElement).disabled).toBe(true)
expect(main.getAttribute('data-state')).toBe('busy')
act(() => { reject(new Error('launch failed')) })
await act(async () => { await vi.runOnlyPendingTimersAsync() })
expect(screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })).toBeDefined()
})
it('shows the error state and decays back to idle after a fast failure', async () => {
const b = bench({
apps: ['finder'],
cwd: '/w/dir',
launch: () => Promise.reject(new Error('launch failed')),
})
render(<OpenInAppAction {...b.props} />)
const main = screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })
fireEvent.click(main)
await waitFor(() => {
expect(screen.getByRole('button', { name: zh['open.error'] })).toBeDefined()
})
// The error state decays back to idle.
await waitFor(() => {
expect(screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })).toBeDefined()
}, { timeout: 4_000 })
})
it('shows the product tooltip on hover instead of a native title', async () => {
render(<OpenInAppAction {...bench({ apps: ['finder'], cwd: '/w/dir' }).props} />)
const main = screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })
expect(main.getAttribute('title')).toBeNull()
fireEvent.mouseEnter(main)
expect(await screen.findByText(zh['open.tooltip'])).toBeDefined()
fireEvent.mouseLeave(main)
await waitFor(() => {
expect(screen.queryByText(zh['open.tooltip'])).toBeNull()
})
})
it('opens the menu from the chevron, launches and persists a picked app', async () => {
it('lists only applications, marks the remembered default, and remembers a successful choice', async () => {
const b = bench({ apps: ['finder', 'cursor', 'terminal'], cwd: '/w/dir' })
render(<OpenInAppAction {...b.props} />)
fireEvent.click(screen.getByRole('button', { name: zh['menu.toggle'] }))
const cursorItem = await screen.findByText('Cursor')
fireEvent.click(cursorItem)
expect(b.choose).toHaveBeenCalledWith('cursor')
fireEvent.click(screen.getByRole('button', { name: zh['path.more'] }))
expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['访达(默认)', 'Cursor', '终端'])
expect(screen.queryByText(zh['path.reveal'])).toBeNull()
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: 'Cursor' })) })
expect(b.launch).toHaveBeenCalledWith('cursor', '/w/dir')
expect(b.choose).toHaveBeenCalledWith('cursor')
})
it('ignores a menu pick while a launch is in flight', async () => {
let resolve: () => void = () => {}
const b = bench({
apps: ['finder', 'cursor'],
cwd: '/w/dir',
launch: () => new Promise((r) => { resolve = r }),
})
render(<OpenInAppAction {...b.props} />)
fireEvent.click(screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) }))
expect(b.launch).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByRole('button', { name: zh['menu.toggle'] }))
fireEvent.click(await screen.findByText('Cursor'))
// Mid-flight the pick is ignored whole: no persisted choice, no launch.
expect(b.choose).not.toHaveBeenCalled()
expect(b.launch).toHaveBeenCalledTimes(1)
resolve()
await act(async () => {})
})
it('clears a pending error decay when a retry starts', async () => {
vi.useFakeTimers()
const outcomes: Array<() => Promise<void>> = [
() => Promise.reject(new Error('launch failed')),
// The retry stays in flight past the original decay deadline.
() => new Promise(() => {}),
]
const b = bench({
apps: ['finder'],
cwd: '/w/dir',
launch: () => (outcomes.shift() ?? (() => Promise.resolve()))(),
})
render(<OpenInAppAction {...b.props} />)
fireEvent.click(screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) }))
await act(async () => {})
fireEvent.click(screen.getByRole('button', { name: zh['open.error'] }))
// Past the first failure's 2s decay: the stale timer must not flip the
// in-flight retry's busy dress back to a clickable idle button.
act(() => { vi.advanceTimersByTime(2_500) })
const main = screen.getByRole('button', { name: zh['open.title'].replace('{app}', zh['app.finder']) })
expect(main.getAttribute('data-state')).toBe('busy')
expect((main as HTMLButtonElement).disabled).toBe(true)
})
it('closes an open menu on Escape without launching', async () => {
const b = bench({ apps: ['finder', 'terminal'], cwd: '/w/dir' })
render(<OpenInAppAction {...b.props} />)
fireEvent.click(screen.getByRole('button', { name: zh['menu.toggle'] }))
await screen.findByText(zh['app.terminal'])
fireEvent.keyDown(document, { key: 'Escape' })
await waitFor(() => {
expect(screen.queryByText(zh['app.terminal'])).toBeNull()
})
it('closes on Escape without launching and falls back after an icon fails', async () => {
const b = bench({ apps: ['finder', 'terminal'], cwd: '/w' })
const view = render(<OpenInAppAction {...b.props} />)
fireEvent.click(screen.getByRole('button', { name: zh['path.more'] }))
fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' })
expect(screen.queryByRole('menu')).toBeNull()
expect(b.launch).not.toHaveBeenCalled()
const image = view.container.querySelector('img')!
fireEvent.error(image)
expect(view.container.querySelector('img')).toBeNull()
expect(view.container.querySelector('svg')).not.toBeNull()
})
it('falls back to the generic icon after a failed image load', async () => {
const b = bench({ apps: ['terminal'], cwd: '/w/dir' })
const { container } = render(<OpenInAppAction {...b.props} />)
const img = container.querySelector('img')
if (img !== null) fireEvent.error(img)
await waitFor(() => {
expect(container.querySelector('img')).toBeNull()
expect(container.querySelector('svg path[fill-opacity="0.05"]')).not.toBeNull()
})
it('uses the shared product tooltip', async () => {
render(<OpenInAppAction {...bench({ apps: ['finder'], cwd: '/w' }).props} />)
fireEvent.mouseEnter(screen.getByRole('button', { name: t('open.title', { app: zh['app.finder'] }) }))
expect(await screen.findByText(zh['open.tooltip'])).toBeTruthy()
})
})
@@ -8,9 +8,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import { OpenPathAction, usePathGesture, type OpenPathActionProps } from '../src/client/OpenPathAction.tsx'
import { OpenPathAction, type OpenPathActionProps } from '../src/client/OpenPathAction.tsx'
import { OpenPathEmptyAction, type OpenPathEmptyActionProps } from '../src/client/OpenPathEmptyAction.tsx'
import type { OpenInAppPathAction, OpenInAppPathFailure } from '../src/client/open-path.ts'
import { useOpenTargetGesture } from '../src/client/OpenTargetButton.tsx'
import { zh } from '../src/client/locales.ts'
afterEach(() => {
@@ -40,7 +41,7 @@ function bench(over: { desktop?: boolean | null; openPath?: Bench['openPath'] }
absolutePath: ABSOLUTE_PATH,
useOpenInAppDesktop: useSelector(desktop),
loadDesktop,
applications: vi.fn(async () => []),
applications: vi.fn(async () => [{ id: '/Music.app', name: 'Music', default: true, icon: null }]),
openPath,
t,
} as Bench['props']
@@ -64,7 +65,7 @@ describe('OpenPathAction gestures', () => {
it('opens the file in its default application from the main button and reveals it from the menu', async () => {
const b = bench()
render(<OpenPathAction {...b.props} />)
const main = screen.getByRole('button', { name: zh['path.open'] })
const main = await screen.findByRole('button', { name: t('open.title', { app: 'Music' }) })
await act(async () => { fireEvent.click(main) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', undefined)
fireEvent.click(screen.getByRole('button', { name: zh['path.more'] }))
@@ -76,6 +77,7 @@ describe('OpenPathAction gestures', () => {
it('offers the default application from the menu too, and Escape closes the menu without a gesture', async () => {
const b = bench()
render(<OpenPathAction {...b.props} />)
await act(async () => {})
const more = screen.getByRole('button', { name: zh['path.more'] })
fireEvent.click(more)
expect(more.getAttribute('aria-expanded')).toBe('true')
@@ -83,15 +85,15 @@ describe('OpenPathAction gestures', () => {
expect(screen.queryByRole('menu')).toBeNull()
expect(b.openPath).not.toHaveBeenCalled()
fireEvent.click(more)
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: zh['path.defaultApp'] })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', undefined)
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: 'Music(默认)' })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', '/Music.app')
})
it('disables both halves while its own gesture settles and leaves no failure on the control', async () => {
const settled = Promise.withResolvers<OpenInAppPathFailure | null>()
const b = bench({ openPath: vi.fn(() => settled.promise) })
const { container } = render(<OpenPathAction {...b.props} />)
const main = screen.getByRole('button', { name: zh['path.open'] })
const main = await screen.findByRole('button', { name: t('open.title', { app: 'Music' }) })
fireEvent.click(main)
expect(main).toHaveProperty('disabled', true)
expect(screen.getByRole('button', { name: zh['path.more'] })).toHaveProperty('disabled', true)
@@ -112,7 +114,8 @@ describe('OpenPathEmptyAction', () => {
cleanup()
const b = bench()
render(<OpenPathEmptyAction {...b.props} />)
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.unpreviewable'] })) })
await act(async () => {})
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.open'] })) })
expect(b.openPath).toHaveBeenCalledWith(ABSOLUTE_PATH, 'open', undefined)
expect(screen.queryByRole('alert')).toBeNull()
})
@@ -121,7 +124,8 @@ describe('OpenPathEmptyAction', () => {
vi.useFakeTimers()
const b = bench({ openPath: vi.fn(async () => 'openError' as const) })
render(<OpenPathEmptyAction {...b.props} />)
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.unpreviewable'] })) })
await act(async () => {})
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.open'] })) })
expect(screen.getAllByRole('alert')).toHaveLength(1)
expect(screen.getByRole('alert').textContent).toContain(zh['path.openError'])
act(() => { vi.advanceTimersByTime(4_000) })
@@ -133,9 +137,11 @@ it('dismisses a failure on schedule even when its owner rerenders', async () =>
vi.useFakeTimers()
const b = bench({ openPath: vi.fn(async () => 'openError' as const) })
const view = render(<OpenPathEmptyAction {...b.props} />)
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.unpreviewable'] })) })
await act(async () => {})
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.open'] })) })
act(() => { vi.advanceTimersByTime(2_000) })
view.rerender(<OpenPathEmptyAction {...b.props} />)
await act(async () => {})
act(() => { vi.advanceTimersByTime(1_999) })
expect(screen.getByRole('alert')).toBeTruthy()
act(() => { vi.advanceTimersByTime(1) })
@@ -157,7 +163,7 @@ it('shows the default icon and current application list, and selects an applicat
expect(screen.getByRole('menuitem', { name: 'Music(默认)' })).toBeTruthy()
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: 'Player' })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', '/Player.app')
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.open'] })) })
await act(async () => { fireEvent.click(screen.getByRole('button', { name: t('open.title', { app: 'Music' }) })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', undefined)
})
@@ -178,21 +184,34 @@ it('ignores an obsolete file query and refreshes the default application when th
expect(applications).toHaveBeenLastCalledWith('/other.mp3', expect.any(AbortSignal))
})
it('keeps default opening available when application discovery fails', async () => {
it('keeps reveal last and makes it the default when the file query fails', async () => {
const b = bench()
render(<OpenPathAction {...b.props} applications={async () => null} />)
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.more'] })) })
expect(screen.getByRole('menuitem', { name: zh['path.appsError'] }).hasAttribute('disabled')).toBe(true)
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: zh['path.defaultApp'] })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'open', undefined)
const items = screen.getAllByRole('menuitem')
expect(items.map(item => item.textContent)).toEqual([zh['path.appsError'], '显示文件位置(默认)'])
expect(items[0]).toHaveProperty('disabled', true)
await act(async () => { fireEvent.click(items[1]!) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'reveal', undefined)
})
it.each([[], [{ id: '/Player.app', name: 'Player', default: false, icon: null }]])('uses reveal as the default after the available applications when none is default', async (apps) => {
const b = bench()
render(<OpenPathAction {...b.props} applications={async () => apps} />)
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.more'] })) })
expect(screen.getAllByRole('menuitem').at(-1)?.textContent).toBe('显示文件位置(默认)')
expect(screen.queryByText('用默认应用打开')).toBeNull()
fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' })
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['path.reveal'] })) })
expect(b.openPath).toHaveBeenLastCalledWith(ABSOLUTE_PATH, 'reveal', undefined)
})
it('coalesces repeated gestures before the busy state renders', async () => {
const pending = Promise.withResolvers<OpenInAppPathFailure | null>()
const b = bench({ openPath: vi.fn(() => pending.promise) })
const { result } = renderHook(() => usePathGesture(b.props))
act(() => { result.current.act('open'); result.current.act('open') })
const { result } = renderHook(() => useOpenTargetGesture(() => b.openPath(ABSOLUTE_PATH, 'open'), t))
act(() => { result.current.act({ kind: 'default' }); result.current.act({ kind: 'default' }) })
expect(b.openPath).toHaveBeenCalledOnce()
await act(async () => { pending.resolve(null) })
expect(result.current.pending).toBe(false)
-4
View File
@@ -628,10 +628,6 @@
"eee35b4d8641824c6eaacfe03ed60d353d81d5257d1111132f34d46a7b13ef35": 2,
"ff65b54ee69109a8b059fc2a2136c71a5476b47115120c7c92a01171d517f3d7": 1
},
"packages/client/ui-open-in-app/tests/open-in-app-action.client.spec.tsx": {
"d6ca469f487b05b19564776f9a8f8288b1f0d9fb5b7fb6681e68f063fb021f38": 1,
"fdc0ec545dc17a50bdc1c64102915706cfbfdbb65a2165ae4691f29d577063cd": 1
},
"packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts": {
"dc36dd8f678695e3b84ce0573968470941c5b6fc5efe529cba17acb1f2799d1c": 1
},
@@ -1,5 +1,4 @@
- menu:
- menuitem "Open in default app"
- menuitem "Test Player (default)"
- menuitem "Other Player"
- menuitem "Show file location"
@@ -81,5 +81,5 @@
- State: unsupported
- Line: Preview is not available for this file type yet.
- Header control: Open
- Empty-state control: Open in default app
- Header control has no text: true
- Empty-state control: Open