Skip to content

The only downloader you need. 下载器的集大成者。

feat(Browser Extension): 任务面板支持搜索、排序和移除已完成的任务

XiaoYouChR4a9de13a0651
diff --git a/browser_extension/app/public/_locales/en/messages.json b/browser_extension/app/public/_locales/en/messages.json
index dc24d230..89f7bc84 100644
--- a/browser_extension/app/public/_locales/en/messages.json
+++ b/browser_extension/app/public/_locales/en/messages.json
@@ -727,5 +727,38 @@
},
"clearFilters": {
"message": "Clear filters"
+ },
+ "sortByStatus": {
+ "message": "Status"
+ },
+ "sortAscending": {
+ "message": "Ascending"
+ },
+ "sortDescending": {
+ "message": "Descending"
+ },
+ "searchTasksPlaceholder": {
+ "message": "Search task name"
+ },
+ "noMatchingTasksTitle": {
+ "message": "No matching tasks"
+ },
+ "noMatchingTasksDescription": {
+ "message": "Try another keyword."
+ },
+ "moreOptions": {
+ "message": "More options"
+ },
+ "removeCompletedTasks": {
+ "message": "Remove completed tasks"
+ },
+ "errorRemoveTasksFailed": {
+ "message": "Failed to remove $1 tasks",
+ "placeholders": {
+ "1": {
+ "content": "$1",
+ "example": "3"
+ }
+ }
}
}
diff --git a/browser_extension/app/public/_locales/zh_CN/messages.json b/browser_extension/app/public/_locales/zh_CN/messages.json
index 3f9ab4a6..e3f7bdee 100644
--- a/browser_extension/app/public/_locales/zh_CN/messages.json
+++ b/browser_extension/app/public/_locales/zh_CN/messages.json
@@ -827,5 +827,38 @@
},
"clearFilters": {
"message": "清除筛选"
+ },
+ "sortByStatus": {
+ "message": "状态"
+ },
+ "sortAscending": {
+ "message": "正序"
+ },
+ "sortDescending": {
+ "message": "倒序"
+ },
+ "searchTasksPlaceholder": {
+ "message": "搜索任务名称"
+ },
+ "noMatchingTasksTitle": {
+ "message": "没有匹配的任务"
+ },
+ "noMatchingTasksDescription": {
+ "message": "换个关键词试试。"
+ },
+ "moreOptions": {
+ "message": "更多选项"
+ },
+ "removeCompletedTasks": {
+ "message": "移除已完成的任务"
+ },
+ "errorRemoveTasksFailed": {
+ "message": "$1 个任务移除失败",
+ "placeholders": {
+ "1": {
+ "content": "$1",
+ "example": "3"
+ }
+ }
}
}
diff --git a/browser_extension/app/src/popup/App.tsx b/browser_extension/app/src/popup/App.tsx
index 3bf78172..2631dad5 100644
--- a/browser_extension/app/src/popup/App.tsx
+++ b/browser_extension/app/src/popup/App.tsx
@@ -69,9 +69,11 @@ export function App({
<main className={styles.content}>
{currentView === "tasks" ? (
<DownloadsPage
- tasks={bridge.sortedTasks}
+ tasks={bridge.tasks}
+ connected={bridge.isConnected}
isTaskBusy={bridge.isTaskBusy}
onTaskAction={(taskId, action) => void bridge.sendTaskAction(taskId, action)}
+ onRemoveTasks={(taskIds) => void bridge.removeTasks(taskIds)}
/>
) : null}
diff --git a/browser_extension/app/src/popup/pages/DownloadsPage.tsx b/browser_extension/app/src/popup/pages/DownloadsPage.tsx
index 0a98cb78..a8f03214 100644
--- a/browser_extension/app/src/popup/pages/DownloadsPage.tsx
+++ b/browser_extension/app/src/popup/pages/DownloadsPage.tsx
@@ -1,23 +1,48 @@
-import {ArrowDownloadRegular} from "@fluentui/react-icons";
-import {makeStyles} from "@fluentui/react-components";
+import {useEffect, useMemo, useState} from "react";
+import {
+ Button,
+ makeStyles,
+ Menu,
+ MenuButton,
+ MenuDivider,
+ MenuItem,
+ MenuItemRadio,
+ MenuList,
+ MenuPopover,
+ MenuTrigger,
+ SearchBox,
+ Tooltip,
+} from "@fluentui/react-components";
+import {
+ ArrowDownloadRegular,
+ ArrowSortDownRegular,
+ ArrowSortUpRegular,
+ DeleteRegular,
+ MoreHorizontalRegular,
+ SearchRegular,
+} from "@fluentui/react-icons";
-import type {TaskSummary, TaskAction} from "../../shared/types";
+import type {SortDirection, TaskAction, TaskSort, TaskSortField, TaskSummary} from "../../shared/types";
import {EmptyState} from "../components/EmptyState";
import {TaskCard} from "../components/TaskCard";
+import {buildTaskView} from "../task-view";
const useStyles = makeStyles({
- empty: {
+ root: {
display: "flex",
flexDirection: "column",
flex: 1,
- padding: "14px",
+ gap: "8px",
+ padding: "12px 16px",
},
- root: {
+ toolbar: {
display: "flex",
- flexDirection: "column",
+ alignItems: "center",
+ gap: "8px",
+ },
+ searchBox: {
flex: 1,
- gap: "10px",
- padding: "14px",
+ minWidth: 0,
},
list: {
display: "flex",
@@ -26,20 +51,76 @@ const useStyles = makeStyles({
},
});
+const SORT_FIELD_LABELS: Record<TaskSortField, string> = {
+ time: chrome.i18n.getMessage("sortByTime"),
+ status: chrome.i18n.getMessage("sortByStatus"),
+ name: chrome.i18n.getMessage("sortByName"),
+ size: chrome.i18n.getMessage("sortBySize"),
+};
+
+const SORT_DIRECTION_LABELS: Record<SortDirection, string> = {
+ asc: chrome.i18n.getMessage("sortAscending"),
+ desc: chrome.i18n.getMessage("sortDescending"),
+};
+
+const DEFAULT_SORT: TaskSort = { field: "time", direction: "desc" };
+
+const SORT_STORAGE_KEY = "gd4bTaskSort";
+
+function isTaskSort(value: unknown): value is TaskSort {
+ if (typeof value !== "object" || value === null) {
+ return false;
+ }
+ const { field, direction } = value as Record<string, unknown>;
+ return typeof field === "string" && Object.hasOwn(SORT_FIELD_LABELS, field)
+ && typeof direction === "string" && Object.hasOwn(SORT_DIRECTION_LABELS, direction);
+}
+
export function DownloadsPage({
tasks,
+ connected,
isTaskBusy,
onTaskAction,
+ onRemoveTasks,
}: {
tasks: TaskSummary[];
+ connected: boolean;
isTaskBusy: (taskId: string) => boolean;
onTaskAction: (taskId: string, action: TaskAction) => void;
+ onRemoveTasks: (taskIds: string[]) => void;
}) {
const styles = useStyles();
+ const [text, setText] = useState("");
+ const [sort, setSort] = useState<TaskSort>(DEFAULT_SORT);
+
+ const visibleTasks = useMemo(() => buildTaskView(tasks, { text, sort }), [tasks, text, sort]);
+ const completedTaskIds = useMemo(
+ () => tasks.filter((task) => task.status === "completed").map((task) => task.taskId),
+ [tasks],
+ );
+
+ useEffect(() => {
+ void chrome.storage.local
+ .get(SORT_STORAGE_KEY)
+ .then((stored) => {
+ const value = stored[SORT_STORAGE_KEY];
+ if (isTaskSort(value)) {
+ setSort(value);
+ }
+ })
+ .catch(() => {
+ // Keep the default sort when storage is unavailable.
+ });
+ }, []);
+
+ function saveSort(next: TaskSort) {
+ setSort(next);
+ void chrome.storage.local.set({ [SORT_STORAGE_KEY]: next });
+ }
if (tasks.length === 0) {
return (
- <div className={styles.empty}>
+ <div className={styles.root}>
<EmptyState
icon={<ArrowDownloadRegular />}
title={chrome.i18n.getMessage("emptyTasksTitle")}
@@ -51,16 +132,80 @@ export function DownloadsPage({
return (
<div className={styles.root}>
- <section className={styles.list}>
- {tasks.map((task) => (
- <TaskCard
- key={task.taskId}
- task={task}
- busy={isTaskBusy(task.taskId)}
- onAction={(action) => onTaskAction(task.taskId, action)}
- />
- ))}
- </section>
+ <div className={styles.toolbar}>
+ <SearchBox
+ className={styles.searchBox}
+ placeholder={chrome.i18n.getMessage("searchTasksPlaceholder")}
+ size="small"
+ value={text}
+ onChange={(_e, data) => setText(data.value)}
+ />
+ <Menu
+ checkedValues={{ field: [sort.field], direction: [sort.direction] }}
+ onCheckedValueChange={(_e, data) => saveSort(data.name === "field"
+ ? { ...sort, field: data.checkedItems[0] as TaskSortField }
+ : { ...sort, direction: data.checkedItems[0] as SortDirection })}
+ >
+ <MenuTrigger disableButtonEnhancement>
+ <MenuButton
+ appearance="subtle"
+ icon={sort.direction === "asc" ? <ArrowSortUpRegular /> : <ArrowSortDownRegular />}
+ size="small"
+ >
+ {SORT_FIELD_LABELS[sort.field]}
+ </MenuButton>
+ </MenuTrigger>
+ <MenuPopover>
+ <MenuList>
+ {(Object.keys(SORT_FIELD_LABELS) as TaskSortField[]).map((field) => (
+ <MenuItemRadio key={field} name="field" value={field}>{SORT_FIELD_LABELS[field]}</MenuItemRadio>
+ ))}
+ <MenuDivider />
+ {(Object.keys(SORT_DIRECTION_LABELS) as SortDirection[]).map((direction) => (
+ <MenuItemRadio key={direction} name="direction" value={direction}>{SORT_DIRECTION_LABELS[direction]}</MenuItemRadio>
+ ))}
+ </MenuList>
+ </MenuPopover>
+ </Menu>
+ <Menu>
+ <MenuTrigger disableButtonEnhancement>
+ <Tooltip content={chrome.i18n.getMessage("moreOptions")} relationship="label">
+ <Button appearance="subtle" icon={<MoreHorizontalRegular />} size="small" />
+ </Tooltip>
+ </MenuTrigger>
+ <MenuPopover>
+ <MenuList>
+ <MenuItem
+ icon={<DeleteRegular />}
+ secondaryContent={String(completedTaskIds.length)}
+ disabled={!connected || completedTaskIds.length === 0}
+ onClick={() => onRemoveTasks(completedTaskIds)}
+ >
+ {chrome.i18n.getMessage("removeCompletedTasks")}
+ </MenuItem>
+ </MenuList>
+ </MenuPopover>
+ </Menu>
+ </div>
+
+ {visibleTasks.length === 0 ? (
+ <EmptyState
+ icon={<SearchRegular />}
+ title={chrome.i18n.getMessage("noMatchingTasksTitle")}
+ description={chrome.i18n.getMessage("noMatchingTasksDescription")}
+ />
+ ) : (
+ <section className={styles.list}>
+ {visibleTasks.map((task) => (
+ <TaskCard
+ key={task.taskId}
+ task={task}
+ busy={isTaskBusy(task.taskId)}
+ onAction={(action) => onTaskAction(task.taskId, action)}
+ />
+ ))}
+ </section>
+ )}
</div>
);
}
diff --git a/browser_extension/app/src/popup/task-view.ts b/browser_extension/app/src/popup/task-view.ts
new file mode 100644
index 00000000..b640538c
--- /dev/null
+++ b/browser_extension/app/src/popup/task-view.ts
@@ -0,0 +1,42 @@
+import type {TaskSort, TaskSortField, TaskSummary} from "../shared/types";
+
+export interface TaskQuery {
+ text: string;
+ sort: TaskSort;
+}
+
+const STATUS_ORDER = ["running", "waiting", "paused", "failed", "completed"];
+
+function statusRank(task: TaskSummary): number {
+ if (task.status === "completed" && !task.canOpenFile) {
+ return STATUS_ORDER.length;
+ }
+ return STATUS_ORDER.indexOf(task.status);
+}
+
+function byNewest(left: TaskSummary, right: TaskSummary): number {
+ return right.createdAt - left.createdAt;
+}
+
+const ASCENDING: Record<TaskSortField, (left: TaskSummary, right: TaskSummary) => number> = {
+ time: (left, right) => left.createdAt - right.createdAt,
+ status: (left, right) => statusRank(left) - statusRank(right),
+ name: (left, right) => left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" }),
+ size: (left, right) => left.fileSize - right.fileSize,
+};
+
+function hasUnknownSize(task: TaskSummary): number {
+ return task.fileSize > 0 ? 0 : 1;
+}
+
+/** Unknown sizes stay last and ties fall back to newest first, whichever the direction. */
+export function buildTaskView(tasks: TaskSummary[], { text, sort }: TaskQuery): TaskSummary[] {
+ const words = text.toLowerCase().split(/\s+/).filter(Boolean);
+ const sign = sort.direction === "asc" ? 1 : -1;
+ return tasks
+ .filter((task) => words.every((word) => task.name.toLowerCase().includes(word)))
+ .sort((left, right) =>
+ (sort.field === "size" ? hasUnknownSize(left) - hasUnknownSize(right) : 0)
+ || sign * ASCENDING[sort.field](left, right)
+ || byNewest(left, right));
+}
diff --git a/browser_extension/app/src/popup/usePopupBridge.ts b/browser_extension/app/src/popup/usePopupBridge.ts
index e1e24628..90cb6d61 100644
--- a/browser_extension/app/src/popup/usePopupBridge.ts
+++ b/browser_extension/app/src/popup/usePopupBridge.ts
@@ -1,5 +1,5 @@
import type {Dispatch, SetStateAction} from "react";
-import {useCallback, useEffect, useMemo, useRef, useState} from "react";
+import {useCallback, useEffect, useRef, useState} from "react";
import {ADVANCED_FEATURES} from "../shared/constants";
import type {
@@ -13,7 +13,6 @@ import type {
ScannedImage,
TaskAction,
} from "../shared/types";
-import {sortTasks} from "../shared/utils";
import type {ActionCommand, PopupCommand, StateCommand} from "../shared/popup-protocol";
import type {ToastIntent} from "./components/ToastHost";
@@ -416,6 +415,28 @@ export function usePopupBridge(activeView: PopupView) {
[refreshState, showToast],
);
+ const removeTasks = useCallback(
+ async (taskIds: string[]) => {
+ for (const taskId of taskIds) {
+ updateBusyState(setBusyTaskIds, taskId, true);
+ }
+ const results = await Promise.allSettled(taskIds.map(async (taskId) => {
+ try {
+ await sendActionCommand({ type: "popup_task_action", taskId, action: "remove" }, chrome.i18n.getMessage("errorTaskActionFailed"));
+ } finally {
+ updateBusyState(setBusyTaskIds, taskId, false);
+ }
+ }));
+ const failedCount = results.filter((result) => result.status === "rejected").length;
+ if (failedCount > 0) {
+ showToast(chrome.i18n.getMessage("errorRemoveTasksFailed", [String(failedCount)]), "error");
+ }
+ // The periodic refresh retries if this one fails.
+ await refreshState(activeViewRef.current).catch(() => undefined);
+ },
+ [refreshState, showToast],
+ );
+
const sendResource = useCallback(
async (resourceId: string) => {
updateBusyState(setBusyResourceIds, resourceId, true);
@@ -561,8 +582,6 @@ export function usePopupBridge(activeView: PopupView) {
[showToast],
);
- const sortedTasks = useMemo(() => sortTasks(payload.tasks), [payload.tasks]);
-
return {
...payload,
toastMessage,
@@ -581,12 +600,12 @@ export function usePopupBridge(activeView: PopupView) {
setShouldTakeDownloads,
setMediaButtonEnabled,
sendTaskAction,
+ removeTasks,
sendResource,
mergeResources,
toggleFeature,
setMediaIndex,
sendMediaAction,
- sortedTasks,
isTaskBusy: (taskId: string) => busyTaskIds.has(taskId),
sendImages,
isResourceBusy: (resourceId: string) => busyResourceIds.has(resourceId),
diff --git a/browser_extension/app/src/shared/types.ts b/browser_extension/app/src/shared/types.ts
index b2ad471d..98bd1850 100644
--- a/browser_extension/app/src/shared/types.ts
+++ b/browser_extension/app/src/shared/types.ts
@@ -22,6 +22,13 @@ export type DesktopConnectionState =
export type ResourceKind = "video" | "audio" | "pdf" | "image" | "archive" | "document" | "spreadsheet" | "other";
export type ResourceSort = "time" | "size" | "name";
+export type TaskSortField = "time" | "status" | "name" | "size";
+export type SortDirection = "asc" | "desc";
+
+export interface TaskSort {
+ field: TaskSortField;
+ direction: SortDirection;
+}
export type ResourceScope = "current" | "other";
export type ResourceCollectionState = "restoring" | "ready" | "unavailable";
diff --git a/browser_extension/app/src/shared/utils.ts b/browser_extension/app/src/shared/utils.ts
index 3e7c07ba..45379ef5 100644
--- a/browser_extension/app/src/shared/utils.ts
+++ b/browser_extension/app/src/shared/utils.ts
@@ -7,7 +7,6 @@ import {
isCatCatchMpd,
} from "./cat-catch";
-const ACTIVE_STATUSES = new Set(["running", "waiting", "paused", "failed"]);
const IMAGE_EXTENSIONS = new Set(["jpg", "jpeg", "png", "gif", "webp", "bmp", "svg", "avif", "heic"]);
const ARCHIVE_EXTENSIONS = new Set(["zip", "7z", "rar", "tar", "gz", "bz2", "xz"]);
const PDF_EXTENSIONS = new Set(["pdf"]);
@@ -54,17 +53,6 @@ interface ResourcePresentation {
};
}
-export function sortTasks(tasks: TaskSummary[]): TaskSummary[] {
- return [...tasks].sort((left, right) => {
- const leftActive = ACTIVE_STATUSES.has(left.status);
- const rightActive = ACTIVE_STATUSES.has(right.status);
- if (leftActive !== rightActive) {
- return leftActive ? -1 : 1;
- }
- return right.createdAt - left.createdAt;
- });
-}
-
export function formatBytes(value: number): string {
if (!Number.isFinite(value) || value <= 0) {
return "0 B";