A full-featured download manager.
fix(downloads): close inspector when selection clears (#2174)
Dr_rOot24d0353fdb23
diff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.tsindex 6ffc1aa1..ba108385 100644--- a/e2e/downloads-visibility.spec.ts+++ b/e2e/downloads-visibility.spec.ts@@ -493,6 +493,7 @@ test('remembers a manual sort across app restarts and clears it when restoring tawait page.getByRole('button', { name: 'List View', exact: true }).click()await page.getByRole('menuitemcheckbox', { name: 'Date completed' }).click()await page.keyboard.press('Escape')+ await list.locator('[data-task-id]').first().click()await page.getByRole('button', { name: 'Show Inspector', exact: true }).click()@@ -510,6 +511,20 @@ test('remembers a manual sort across app restarts and clears it when restoring tawait expect(list.getByRole('button', { name: 'Date completed', exact: true })).toHaveCount(0)+ await expect(+ list.page().getByRole('dialog', { name: 'Task Inspector' })+ ).toBeHidden()+ await expect(+ list.page().getByRole('button', { name: 'Show Inspector', exact: true })+ ).toBeDisabled()+ await list.locator('[data-task-id]').first().click()+ await expect(+ list.page().getByRole('dialog', { name: 'Task Inspector' })+ ).toBeHidden()+ await list+ .page()+ .getByRole('button', { name: 'Show Inspector', exact: true })+ .click()await expect(list.page().getByRole('dialog', { name: 'Task Inspector' })).toBeVisible()@@ -792,7 +807,7 @@ test('clears selection with modifier clicks, Escape and list whitespace', asynctest('opens details by double click and keeps selection separate from inspector visibility', async ({electronApp,mainWindow,-}) => {+}, testInfo) => {await waitForEngineReady(mainWindow)await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()@@ -855,6 +870,32 @@ test('opens details by double click and keeps selection separate from inspector'aria-valuenow',String(Math.round(viewportHeight * 0.75)))+ await testInfo.attach('inspector-open', {+ body: await mainWindow.screenshot({ animations: 'disabled' }),+ contentType: 'image/png',+ })+ await grid.press('Escape')+ await expect(selected).toHaveCount(0)+ await expect(drawer).toBeHidden()+ await expect(+ mainWindow.getByRole('button', { name: 'Show Inspector', exact: true })+ ).toBeDisabled()+ await testInfo.attach('inspector-selection-cleared', {+ body: await mainWindow.screenshot({ animations: 'disabled' }),+ contentType: 'image/png',+ })+ await rows.nth(0).click()+ await expect(drawer).toBeHidden()+ await testInfo.attach('inspector-reselected-stays-closed', {+ body: await mainWindow.screenshot({ animations: 'disabled' }),+ contentType: 'image/png',+ })+ await rows.nth(0).dblclick()+ await expect(drawer).toBeVisible()+ await expect(handle).toHaveAttribute(+ 'aria-valuenow',+ String(Math.round(viewportHeight * 0.75))+ )await drawer.getByRole('button', { name: 'Close', exact: true }).click()await expect(drawer).toHaveCount(0)await expect(selected).toHaveText([/Details 0/])diff --git a/src/renderer/components/desktop-kit/inspector-drawer.tsx b/src/renderer/components/desktop-kit/inspector-drawer.tsxindex 09c41906..3c4abaf3 100644--- a/src/renderer/components/desktop-kit/inspector-drawer.tsx+++ b/src/renderer/components/desktop-kit/inspector-drawer.tsx@@ -106,9 +106,23 @@ export function InspectorDrawer({<DrawerPopupref={popupRef}initialFocus={false}- finalFocus={() =>- container.querySelector<HTMLElement>('[data-downloads-grid]')- }+ finalFocus={() => {+ const active = container.ownerDocument.activeElement+ // Filtering can hide the inspector while the user is typing.+ // Preserve focus outside the drawer instead of stealing it.+ if (+ active &&+ active !== container.ownerDocument.body &&+ !popupRef.current?.contains(active)+ )+ return false+ return (+ container.querySelector<HTMLElement>('[data-downloads-grid]') ??+ container.querySelector<HTMLElement>(+ '[data-slot="toolbar-button"]'+ )+ )+ }}aria-label={title}className="downloads-inspector-popup pointer-events-auto w-full shadow-[0_-3px_12px_rgba(15,23,42,0.08)]"style={{diff --git a/src/renderer/routes/downloads/downloads-page.test.tsx b/src/renderer/routes/downloads/downloads-page.test.tsxindex 5aeb45a0..da8ea3a6 100644--- a/src/renderer/routes/downloads/downloads-page.test.tsx+++ b/src/renderer/routes/downloads/downloads-page.test.tsx@@ -194,6 +194,50 @@ beforeEach(() => {})describe('DownloadsPage', () => {+ it('keeps the toolbar in sync with empty selection and requires an explicit reopen', async () => {+ setTaskList({+ tasks: [task('a', TaskStatus.Paused), task('b', TaskStatus.Paused)],+ })+ useDownloadsView.setState({ inspectorVisible: true })+ renderAt('/downloads/all')++ const toggle = screen.getByRole('button', { name: 'Show Inspector' })+ expect(toggle).toBeDisabled()+ expect(toggle).toHaveAttribute('aria-pressed', 'false')+ expect(toggle).toHaveAttribute(+ 'title',+ 'Select a task to view its details.'+ )++ act(() => useDownloadsSelection.getState().select('a'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Show Inspector' }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(+ screen.getByRole('button', { name: 'Hide Inspector' })+ ).toHaveAttribute('aria-pressed', 'true')++ act(() => useDownloadsSelection.getState().clearSelection())+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ expect(+ screen.getByRole('button', { name: 'Show Inspector' })+ ).toBeDisabled()++ act(() => useDownloadsSelection.getState().select('b'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Show Inspector' }))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'Hide Inspector' }))+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ act(() => useDownloadsSelection.getState().select('a'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Show Inspector' })).toBeEnabled()+ })+it('renders the status title heading and search trigger', () => {renderAt('/downloads/all')expect(diff --git a/src/renderer/routes/downloads/downloads-toolbar.tsx b/src/renderer/routes/downloads/downloads-toolbar.tsxindex 54fc50c2..0298c97e 100644--- a/src/renderer/routes/downloads/downloads-toolbar.tsx+++ b/src/renderer/routes/downloads/downloads-toolbar.tsx@@ -11,6 +11,7 @@ import {} from './filter-search-command'import { InspectorToggle, ListViewMenu } from './list-view-menu'import { TaskActionsMenu } from './task-actions-menu'+import { useTaskInspectorState } from './use-task-inspector-state'// Match the 30px / 24px targets, 4px gaps and capsule padding in both densities.const actionWidth = (count: number, compact: boolean) =>@@ -49,6 +50,7 @@ export function DownloadsToolbar({}) {const compact = useCompactHeader()const { t } = useTranslation()+ const inspector = useTaskInspectorState(selection, tasks)const rootRef = useRef<HTMLDivElement>(null)const moreRef = useRef<HTMLButtonElement>(null)const viewRef = useRef<HTMLButtonElement>(null)@@ -111,7 +113,12 @@ export function DownloadsToolbar({<ListViewMenu triggerRef={viewRef} onOpenChange={setViewMenuOpen} />)}{count >= 2 && (- <InspectorToggle triggerRef={inspectorRef} onHide={onHideInspector} />+ <InspectorToggle+ triggerRef={inspectorRef}+ onHide={onHideInspector}+ visible={inspector.open}+ disabled={inspector.selected.length === 0}+ />)}</ToolbarGroup><FilterSearchCommanddiff --git a/src/renderer/routes/downloads/list-view-menu.tsx b/src/renderer/routes/downloads/list-view-menu.tsxindex 76317c97..c5ba3de7 100644--- a/src/renderer/routes/downloads/list-view-menu.tsx+++ b/src/renderer/routes/downloads/list-view-menu.tsx@@ -155,19 +155,24 @@ export function ListViewMenu({}export function InspectorMenuItem({+ visible,+ disabled,onHide,onShow,shortcut,}: {+ visible: boolean+ disabled: booleanonHide?: () => voidonShow?: () => voidshortcut?: TaskMenuShortcut}) {const { t } = useTranslation()- const visible = useDownloadsView((state) => state.inspectorVisible)const setVisible = useDownloadsView((state) => state.setInspectorVisible)return (<DropdownMenuItem+ disabled={disabled}+ title={disabled ? t('panel.downloads.view.selectToInspect') : undefined}aria-keyshortcuts={shortcut?.aria}onClick={() => {if (visible) onHide?.()@@ -186,14 +191,17 @@ export function InspectorMenuItem({}export function InspectorToggle({+ visible,+ disabled,onHide,triggerRef,}: {+ visible: boolean+ disabled: booleanonHide?: () => voidtriggerRef?: Ref<HTMLButtonElement>}) {const { t } = useTranslation()- const visible = useDownloadsView((state) => state.inspectorVisible)const setVisible = useDownloadsView((state) => state.setInspectorVisible)const label = t(`panel.downloads.view.${visible ? 'hideInspector' : 'showInspector'}`@@ -202,7 +210,8 @@ export function InspectorToggle({<DownloadsToolbarButtonref={triggerRef}aria-label={label}- title={label}+ title={disabled ? t('panel.downloads.view.selectToInspect') : label}+ disabled={disabled}aria-pressed={visible}onClick={() => {if (visible) onHide?.()diff --git a/src/renderer/routes/downloads/task-actions-menu.test.tsx b/src/renderer/routes/downloads/task-actions-menu.test.tsxindex 1ff8bd19..300146ac 100644--- a/src/renderer/routes/downloads/task-actions-menu.test.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.test.tsx@@ -102,6 +102,19 @@ function setup(context = true, items = tasks) {}describe('TaskActionsMenu', () => {+ it('disables the inspector menu and shortcut without changing the saved intent when selection is empty', async () => {+ const selection = setup(false)+ act(() => {+ useDownloadsView.getState().setInspectorVisible(true)+ selection.getState().clearSelection()+ })+ await userEvent.click(screen.getByRole('button', { name: 'More' }))+ const item = await screen.findByRole('menuitem', { name: 'Show Inspector' })+ expect(item).toHaveAttribute('aria-disabled', 'true')+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'i', metaKey: true })+ expect(useDownloadsView.getState().inspectorVisible).toBe(true)+ })+it.each([['Pause All', CommandIds.TaskPauseAll, Commands.PauseAllTasks],['Resume All', CommandIds.TaskResumeAll, Commands.ResumeAllTasks],diff --git a/src/renderer/routes/downloads/task-actions-menu.tsx b/src/renderer/routes/downloads/task-actions-menu.tsxindex fae51713..e7e5f267 100644--- a/src/renderer/routes/downloads/task-actions-menu.tsx+++ b/src/renderer/routes/downloads/task-actions-menu.tsx@@ -56,6 +56,7 @@ import {matchesTaskMenuShortcut,taskMenuShortcuts,} from './task-menu-shortcuts'+import { useTaskInspectorState } from './use-task-inspector-state'import { useDownloadsView } from './view-preferences'function GlobalTransferMenuItems({@@ -127,7 +128,7 @@ export function TaskActionsMenu({single?.status === TaskStatus.MetadataReady ||canChooseFiles ||actions.moveCount > 0- const inspectorVisible = useDownloadsView((state) => state.inspectorVisible)+ const { open: inspectorVisible } = useTaskInspectorState(selection, tasks)const macOS =transport.platform === 'darwin' ||(transport.platform === 'web' && /Mac|iPhone|iPad/.test(navigator.platform))@@ -219,13 +220,7 @@ export function TaskActionsMenu({? 'remove': nullif (!action || (action !== 'inspector' && selected.length === 0)) return- if (- action === 'inspector' &&- children &&- !selected.length &&- !inspectorVisible- )- return+ if (action === 'inspector' && !selected.length && !inspectorVisible) returnevent.preventDefault()event.stopPropagation()if (event.repeat) return@@ -299,6 +294,8 @@ export function TaskActionsMenu({</DropdownMenuItem>)}<InspectorMenuItem+ visible={inspectorVisible}+ disabled={!inspectorVisible && selected.length === 0}onHide={onHideInspector}onShow={restoreSelection}shortcut={shortcuts.inspector}diff --git a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx b/src/renderer/routes/downloads/task-inspector-drawer.test.tsxindex e5abcf27..719af336 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.test.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.test.tsx@@ -12,7 +12,7 @@ import {type TaskInspectorActivitySnapshot,} from '@shared/types/task-inspector-activity'import { makeDownloadTask } from '@test-utils/task'-import { act, render, screen } from '@testing-library/react'+import { act, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -175,7 +175,10 @@ describe('TaskInspectorDrawer', () => {try {const user = userEvent.setup()const selection = createSelectionStore<DownloadTask>((task) => task.id)- render(<TestHarness selection={selection} tasks={[]} />)+ const tasks = [fake()]+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ render(<TestHarness selection={selection} tasks={tasks} />)const resize = screen.getByRole('separator', { name: 'Resize Inspector' })expect(resize).toHaveAttribute('aria-valuenow', '220')expect(useDownloadsView.getState().inspectorSnap).toBe('medium')@@ -212,6 +215,102 @@ describe('TaskInspectorDrawer', () => {expect(screen.queryByRole('dialog')).toBeNull()})+ it('closes a restored inspector with no selection and keeps a subsequent single selection closed', () => {+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const tasks = [fake()]+ selection.getState().setItems(tasks)+ render(<TestHarness selection={selection} tasks={tasks} />)++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)+ act(() => selection.getState().select('a'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it('closes on empty selection and preserves tab and height for an explicit reopen', async () => {+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const tasks = [fake({ id: 'a' }), fake({ id: 'b' })]+ const onDismiss = vi.fn()+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ useDownloadsView.setState({+ inspectorSnap: 'expanded',+ inspectorTab: 'activity',+ })+ render(+ <TestHarness selection={selection} tasks={tasks} onDismiss={onDismiss} />+ )++ act(() => selection.getState().clearSelection())+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)+ expect(onDismiss).not.toHaveBeenCalled()++ act(() => selection.getState().select('b'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ act(() => useDownloadsView.getState().setInspectorVisible(true))+ expect(screen.getByRole('tab', { name: 'Activity' })).toHaveAttribute(+ 'aria-selected',+ 'true'+ )+ expect(useDownloadsView.getState().inspectorSnap).toBe('expanded')++ act(() => screen.getByRole('button', { name: 'Close' }).click())+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ act(() => selection.getState().select('a'))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ expect(onDismiss).toHaveBeenCalledOnce()+ })++ it.each(['missing', 'removed'] as const)(+ 'hides when the selected task becomes %s',+ async (mode) => {+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const tasks = [fake()]+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ const view = render(<TestHarness selection={selection} tasks={tasks} />)++ view.rerender(+ <TestHarness+ selection={selection}+ tasks={+ mode === 'missing' ? [] : [fake({ status: TaskStatus.Removed })]+ }+ />+ )+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ expect(useDownloadsView.getState().inspectorVisible).toBe(false)+ }+ )++ it('does not move focus away from an input when selection is cleared', async () => {+ const selection = createSelectionStore<DownloadTask>((task) => task.id)+ const tasks = [fake()]+ selection.getState().setItems(tasks)+ selection.getState().select('a')+ render(+ <>+ <input aria-label="Search" />+ <TestHarness selection={selection} tasks={tasks} />+ </>+ )++ const search = screen.getByRole('textbox', { name: 'Search' })+ search.focus()+ act(() => selection.getState().clearSelection())+ await waitFor(() =>+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ )+ expect(search).toHaveFocus()+ })+it('renders single-mode body with Overview tab active when one task selected', () => {const selection = createSelectionStore<DownloadTask>((t) => t.id)const tasks = [fake({ id: 'a' })]@@ -409,7 +508,7 @@ describe('TaskInspectorDrawer', () => {expect(useDownloadsView.getState().inspectorSnap).toBe('medium')})- it.each(['empty', 'single', 'multiple', 'finalizing'] as const)(+ it.each(['single', 'multiple', 'finalizing'] as const)('resizes from the %s header without consuming button keys',async (mode) => {const user = userEvent.setup()@@ -424,7 +523,7 @@ describe('TaskInspectorDrawer', () => {]selection.getState().setItems(tasks)if (mode === 'multiple') selection.getState().selectAll()- else if (mode !== 'empty') selection.getState().select('a')+ else selection.getState().select('a')render(<TestHarness selection={selection} tasks={tasks} />)const resize = screen.getByRole('separator', { name: 'Resize Inspector' })diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsxindex 86cc655a..324e3d6c 100644--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx@@ -29,9 +29,8 @@ import {RadioTower,SquareActivity,UsersRound,- X,} from 'lucide-react'-import { useCallback, useMemo } from 'react'+import { useCallback, useLayoutEffect, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { ActivityTab } from './inspector/activity-tab'import { canRevealTaskFolder } from './inspector/can-reveal-task-folder'@@ -43,6 +42,7 @@ import { PiecesTab } from './inspector/pieces-tab'import { TaskInspectorActionBar } from './inspector/task-inspector-action-bar'import { TrackersTab } from './inspector/trackers-tab'import { StatusPill } from './status-pill'+import { useTaskInspectorState } from './use-task-inspector-state'import { type InspectorTab, useDownloadsView } from './view-preferences'export interface TaskInspectorDrawerProps {@@ -53,14 +53,6 @@ export interface TaskInspectorDrawerProps {onDismiss?: () => void}-function useSelectedTasks(- selection: SelectionStore<DownloadTask>,- tasks: readonly DownloadTask[]-): DownloadTask[] {- const ids = selection((s) => s.committedSelectedIds)- return useMemo(() => tasks.filter((t) => ids.has(t.id)), [ids, tasks])-}-export function TaskInspectorDrawer({selection,tasks,@@ -68,8 +60,8 @@ export function TaskInspectorDrawer({onDismiss,}: TaskInspectorDrawerProps) {const { t } = useTranslation()- const selected = useSelectedTasks(selection, tasks)- const open = useDownloadsView((s) => s.inspectorVisible)+ const { selected, open } = useTaskInspectorState(selection, tasks)+ const visible = useDownloadsView((state) => state.inspectorVisible)const snap = useDownloadsView((s) => s.inspectorSnap)const setSnap = useDownloadsView((s) => s.setInspectorSnap)const single = selected.length === 1 ? selected[0] : null@@ -82,6 +74,14 @@ export function TaskInspectorDrawer({[])+ useLayoutEffect(() => {+ // Clearing selection closes the inspector. Selecting another task later+ // must not reopen it without an explicit request to view its details.+ if (visible && selected.length === 0) {+ useDownloadsView.getState().setInspectorVisible(false)+ }+ }, [visible, selected.length])+const onClose = useCallback(() => {onDismiss?.()useDownloadsView.getState().setInspectorVisible(false)@@ -101,30 +101,13 @@ export function TaskInspectorDrawer({onClose={onClose}title={t('panel.downloads.view.inspector')}resizeLabel={t('panel.downloads.view.resizeInspector')}- renderHeader={(resizeHandle) =>- selected.length > 0 ? (- <TaskInspectorActionBar- selected={selected}- onClose={onClose}- resizeHandle={resizeHandle}- />- ) : (- <div className="flex shrink-0 items-center justify-between border-b border-border/50 px-4 py-2">- <span className="text-xs font-medium">- {t('panel.downloads.view.inspector')}- </span>- {resizeHandle}- <Button- size="icon-xs"- variant="ghost"- aria-label={t('common.close')}- onClick={onClose}- >- <X />- </Button>- </div>- )- }+ renderHeader={(resizeHandle) => (+ <TaskInspectorActionBar+ selected={selected}+ onClose={onClose}+ resizeHandle={resizeHandle}+ />+ )}><ScrollArea className="min-h-0 flex-1"><ScrollAreaViewport@@ -274,11 +257,7 @@ export function TaskInspectorDrawer({</>) : selected.length > 0 ? (<MultiSelectionSummary tasks={selected} />- ) : (- <p className="py-8 text-center text-sm text-muted-foreground">- {t('panel.downloads.view.selectToInspect')}- </p>- )}+ ) : null}</ScrollAreaContent></ScrollAreaViewport><ScrollBar />diff --git a/src/renderer/routes/downloads/use-task-inspector-state.ts b/src/renderer/routes/downloads/use-task-inspector-state.tsnew file mode 100644index 00000000..490efe4a--- /dev/null+++ b/src/renderer/routes/downloads/use-task-inspector-state.ts@@ -0,0 +1,21 @@+import type { SelectionStore } from '@renderer/components/desktop-kit/selection/types'+import { isTaskAvailable } from '@shared/lib/task-navigation'+import type { DownloadTask } from '@shared/types/task'+import { useMemo } from 'react'+import { useDownloadsView } from './view-preferences'++export function useTaskInspectorState(+ selection: SelectionStore<DownloadTask>,+ tasks: readonly DownloadTask[]+) {+ const ids = selection((state) => state.committedSelectedIds)+ const requested = useDownloadsView((state) => state.inspectorVisible)+ const selected = useMemo(+ () =>+ tasks.filter((task) => ids.has(task.id) && isTaskAvailable(task.status)),+ [ids, tasks]+ )++ // Committed selection keeps marquee previews from toggling the drawer.+ return { selected, open: requested && selected.length > 0 }+}