feat: add direct write settings to enhance file saving options

- Introduced `DirectWriteSettings` and integrated it into the settings model for improved file saving capabilities.
- Implemented merging logic for direct write settings in `mergeSettings` to ensure defaults are applied correctly.
- Updated `PanelGeneral` component to allow users to configure direct write options, including output mode and directory path.
- Enhanced selectors to retrieve staging and production direct write settings.
- Added tests to validate the functionality of direct write settings and their integration within the settings management system.
This commit is contained in:
鲁树人 committed 2026-11-06 04:05:47 +09:00
1 parent 79e5b45e6b
commit b9c8d5b3cd
10 files changed
+291 -5

No files matched your search

+98 -3
View File
@@ -1,7 +1,12 @@
import { useCallback, useEffect, useId, useState, type ReactNode } from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import { selectStagingBatchDownloadSettings } from '../settingsSelector';
import { BatchDownloadSettings, updateBatchDownloadSetting } from '../settingsSlice';
import { selectStagingBatchDownloadSettings, selectStagingDirectWriteSettings } from '../settingsSelector';
import {
BatchDownloadSettings,
DirectWriteOutputMode,
updateBatchDownloadSetting,
updateDirectWriteSetting,
} from '../settingsSlice';
import { BatchDownloadType } from '~/platform/capabilities';
import { usePlatform } from '~/platform/PlatformContext';
import { clearRememberedDirectoryHandle, hasRememberedDirectoryHandle } from '~/util/downloadDirectoryHandle';
@@ -10,12 +15,15 @@ import { toast } from 'react-toastify';
export function PanelGeneral() {
const dispatch = useAppDispatch();
const batch = useAppSelector(selectStagingBatchDownloadSettings);
const { capabilities } = usePlatform();
const directWrite = useAppSelector(selectStagingDirectWriteSettings);
const { capabilities, download } = usePlatform();
const downloadTypes = new Set(capabilities.downloadTypes);
const canDirectoryPicker = downloadTypes.has(BatchDownloadType.SelectDirectory);
const canStreamingZip = downloadTypes.has(BatchDownloadType.StreamZip);
const canBlobZip = downloadTypes.has(BatchDownloadType.PackZip);
const canDirectWrite = capabilities.directFsAccess;
const [hasRememberedDir, setHasRememberedDir] = useState(false);
const [pickingDirectory, setPickingDirectory] = useState(false);
const refreshRemembered = useCallback(() => {
hasRememberedDirectoryHandle()
@@ -37,10 +45,27 @@ export function PanelGeneral() {
toast.info('已清除记住的输出目录');
};
const handlePickDirectory = async () => {
setPickingDirectory(true);
try {
const path = await download.pickDirectory();
if (path) {
dispatch(updateDirectWriteSetting({ fixedDirectoryPath: path, outputMode: 'fixedDirectory' }));
}
} catch (e) {
toast.error(`无法选择文件夹: ${e instanceof Error ? e.message : String(e)}`);
} finally {
setPickingDirectory(false);
}
};
const idDir = useId();
const idRemember = useId();
const idStreamZip = useId();
const idBlobZip = useId();
const idOutputMode = useId();
const idFixedPath = useId();
const idDeleteSource = useId();
return (
<div className="min-h-0 flex-col grow px-1">
@@ -121,6 +146,76 @@ export function PanelGeneral() {
onChange={(checked) => setBatch('blobZip', checked)}
/>
</div>
<h3 className="text-xl font-semibold mt-8 mb-2">解密后自动保存</h3>
<p className="text-sm text-base-content/80 mb-4">
{canDirectWrite
? '解密完成后直接保存到本机,无需再手动下载。'
: '当前环境无法直接保存到本机,请使用上方的批量下载。此项设置会保留,在桌面客户端中生效。'}
</p>
<div className={`flex flex-col gap-3 ${canDirectWrite ? '' : 'opacity-50'}`}>
<div className="flex flex-col gap-1">
<label htmlFor={idOutputMode} className="font-medium">
保存位置
</label>
<select
id={idOutputMode}
className="select select-bordered select-sm w-full max-w-md"
value={directWrite.outputMode}
disabled={!canDirectWrite}
onChange={(e) =>
dispatch(updateDirectWriteSetting({ outputMode: e.target.value as DirectWriteOutputMode }))
}
>
<option value="besideSource">原文件所在文件夹</option>
<option value="fixedDirectory">指定文件夹</option>
</select>
<span className="text-sm text-base-content/70">
{directWrite.outputMode === 'besideSource'
? '解密后的文件保存在加密文件旁边。'
: '解密后的文件保存到下方指定的文件夹。'}
</span>
</div>
<div className="flex flex-col gap-1">
<label htmlFor={idFixedPath} className="font-medium">
文件夹路径
</label>
<div className="flex flex-wrap items-center gap-2 max-w-xl">
<input
id={idFixedPath}
type="text"
className="input input-bordered input-sm min-w-0 flex-1"
placeholder="/path/to/output"
value={directWrite.fixedDirectoryPath ?? ''}
disabled={!canDirectWrite || directWrite.outputMode !== 'fixedDirectory'}
onChange={(e) =>
dispatch(
updateDirectWriteSetting({ fixedDirectoryPath: e.target.value === '' ? null : e.target.value }),
)
}
/>
<button
type="button"
className="btn btn-sm btn-outline"
disabled={!canDirectWrite || pickingDirectory}
onClick={() => void handlePickDirectory()}
>
{pickingDirectory ? '选择中…' : '选择文件夹'}
</button>
</div>
</div>
<BatchOption
id={idDeleteSource}
checked={directWrite.deleteSourceAfterDecrypt}
disabled={!canDirectWrite}
title="保存成功后删除加密文件"
description="仅在写出成功后删除;请先确认已有备份。"
onChange={(checked) => dispatch(updateDirectWriteSetting({ deleteSourceAfterDecrypt: checked }))}
/>
</div>
</div>
);
}
@@ -1,3 +1,4 @@
import userEvent from '@testing-library/user-event';
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral';
import { BatchDownloadType } from '~/platform/capabilities';
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
@@ -33,3 +34,61 @@ test('disables pack-zip when capability is absent', () => {
expect(screen.getByLabelText(/流式生成 ZIP/)).toBeDisabled();
expect(screen.getByLabelText(/生成单个 ZIP 并触发下载/)).toBeDisabled();
});
test('disables DirectWrite controls when directFsAccess is false', () => {
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: false,
});
renderWithProviders(<PanelGeneral />, { platform });
expect(screen.getByLabelText('保存位置')).toBeDisabled();
expect(screen.getByLabelText('文件夹路径')).toBeDisabled();
expect(screen.getByRole('button', { name: '选择文件夹' })).toBeDisabled();
expect(screen.getByLabelText(/保存成功后删除加密文件/)).toBeDisabled();
});
test('enables DirectWrite controls when directFsAccess is true', () => {
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: true,
});
renderWithProviders(<PanelGeneral />, { platform });
expect(screen.getByLabelText('保存位置')).not.toBeDisabled();
// Path stays disabled until outputMode is fixedDirectory (default besideSource).
expect(screen.getByLabelText('文件夹路径')).toBeDisabled();
expect(screen.getByRole('button', { name: '选择文件夹' })).not.toBeDisabled();
expect(screen.getByLabelText(/保存成功后删除加密文件/)).not.toBeDisabled();
});
test('pickDirectory button writes path into fixedDirectoryPath', async () => {
const user = userEvent.setup();
const pickDirectory = vi.fn().mockResolvedValue('/music/unlocked');
const platform = createBrowserProvider({
crypto: stubCrypto,
downloadTypes: [BatchDownloadType.PackZip],
directFsAccess: true,
download: {
saveOne: vi.fn(),
saveMany: vi.fn(),
pickDirectory,
},
});
const { store } = renderWithProviders(<PanelGeneral />, { platform });
await user.click(screen.getByRole('button', { name: '选择文件夹' }));
expect(pickDirectory).toHaveBeenCalledOnce();
expect(store.getState().settings.staging.general.directWrite).toEqual({
outputMode: 'fixedDirectory',
fixedDirectoryPath: '/music/unlocked',
deleteSourceAfterDecrypt: false,
});
expect(screen.getByLabelText('文件夹路径')).toHaveValue('/music/unlocked');
});