mirror of
https://git.um-react.app/um/um-react.git
synced 2026-11-27 23:56:59 +00:00
feat: implement one-click import feature for settings
- Added `PanelOneClick` component to facilitate one-click import of keys from native applications. - Integrated capability checks to conditionally render the one-click import tab based on platform capabilities. - Refactored settings tab management to include one-click import when applicable. - Introduced utility functions for determining available settings tabs based on platform capabilities. - Added tests for the new one-click import functionality and its integration within the settings management system.
This commit is contained in:
1 parent
b9c8d5b3cd
commit
4d688af4ca
8 files changed
+426
-10
No files matched your search
@@ -1,4 +1,4 @@
|
|||||||
import { NavLink, Route, Routes } from 'react-router';
|
import { NavLink, Navigate, Route, Routes } from 'react-router';
|
||||||
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
|
import { MdHome, MdQuestionAnswer, MdSettings } from 'react-icons/md';
|
||||||
import { Bounce, ToastContainer } from 'react-toastify';
|
import { Bounce, ToastContainer } from 'react-toastify';
|
||||||
|
|
||||||
@@ -6,7 +6,8 @@ import { Footer } from '~/components/Footer';
|
|||||||
import { FaqHome } from '~/faq/FaqHome';
|
import { FaqHome } from '~/faq/FaqHome';
|
||||||
import { FAQ_PAGES } from '~/faq/FAQPages';
|
import { FAQ_PAGES } from '~/faq/FAQPages';
|
||||||
import { SettingsHome } from '~/features/settings/SettingsHome';
|
import { SettingsHome } from '~/features/settings/SettingsHome';
|
||||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs';
|
import { getSettingsTabs, hasOneClickImportCapability, ONE_CLICK_TAB_ID } from '~/features/settings/settingsTabs';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
import { FaqTab } from '~/tabs/FaqTab';
|
import { FaqTab } from '~/tabs/FaqTab';
|
||||||
import { MainTab } from '~/tabs/MainTab';
|
import { MainTab } from '~/tabs/MainTab';
|
||||||
import { SettingsTab } from '~/tabs/SettingsTab';
|
import { SettingsTab } from '~/tabs/SettingsTab';
|
||||||
@@ -15,6 +16,10 @@ const tabClassNames = ({ isActive }: { isActive: boolean }) => `mb-[-2px] tab ${
|
|||||||
|
|
||||||
/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
|
/** Main chrome (nav / routes / toast / footer). Render only after platform `init()` resolves. */
|
||||||
export function AppLayout() {
|
export function AppLayout() {
|
||||||
|
const { capabilities } = usePlatform();
|
||||||
|
const settingsTabs = getSettingsTabs(capabilities);
|
||||||
|
const showOneClick = hasOneClickImportCapability(capabilities);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
<div role="tablist" className="tabs tabs-border w-full justify-center border-b-2 border-base-200 box-content">
|
||||||
@@ -37,9 +42,10 @@ export function AppLayout() {
|
|||||||
<Route path="/" Component={MainTab} />
|
<Route path="/" Component={MainTab} />
|
||||||
<Route path="/settings" Component={SettingsTab}>
|
<Route path="/settings" Component={SettingsTab}>
|
||||||
<Route index Component={SettingsHome} />
|
<Route index Component={SettingsHome} />
|
||||||
{Object.entries(SETTINGS_TABS).map(([key, { Tab }]) => (
|
{Object.entries(settingsTabs).map(([key, { Tab }]) => (
|
||||||
<Route key={key} path={key} Component={Tab} />
|
<Route key={key} path={key} Component={Tab} />
|
||||||
))}
|
))}
|
||||||
|
{!showOneClick && <Route path={ONE_CLICK_TAB_ID} element={<Navigate to="/settings/general" replace />} />}
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="/questions" Component={FaqTab}>
|
<Route path="/questions" Component={FaqTab}>
|
||||||
<Route index Component={FaqHome} />
|
<Route index Component={FaqHome} />
|
||||||
|
|||||||
@@ -2,14 +2,17 @@ import { useAppDispatch, useAppSelector } from '~/hooks';
|
|||||||
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
import { commitStagingChange, discardStagingChanges } from './settingsSlice';
|
||||||
import { selectIsSettingsNotSaved } from './settingsSelector';
|
import { selectIsSettingsNotSaved } from './settingsSelector';
|
||||||
import { Outlet } from 'react-router';
|
import { Outlet } from 'react-router';
|
||||||
import { SETTINGS_TABS } from '~/features/settings/settingsTabs.tsx';
|
import { getSettingsTabs } from '~/features/settings/settingsTabs.tsx';
|
||||||
import { MdOutlineSettingsBackupRestore } from 'react-icons/md';
|
import { MdOutlineSettingsBackupRestore } from 'react-icons/md';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
import { ResponsiveNav } from '../nav/ResponsiveNav';
|
||||||
import { TabNavLink } from '../nav/TabNavLink';
|
import { TabNavLink } from '../nav/TabNavLink';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
|
|
||||||
export function Settings() {
|
export function Settings() {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
const { capabilities } = usePlatform();
|
||||||
|
const settingsTabs = getSettingsTabs(capabilities);
|
||||||
|
|
||||||
const handleResetSettings = () => {
|
const handleResetSettings = () => {
|
||||||
dispatch(discardStagingChanges());
|
dispatch(discardStagingChanges());
|
||||||
@@ -35,7 +38,7 @@ export function Settings() {
|
|||||||
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
navigationClassName="overflow-x-auto pb-[2px] md:pb-0 h-full items-start [&]:md:flex"
|
||||||
navigation={
|
navigation={
|
||||||
<div role="tablist" className="tabs gap-1 flex-nowrap md:flex-col grow items-center">
|
<div role="tablist" className="tabs gap-1 flex-nowrap md:flex-col grow items-center">
|
||||||
{Object.entries(SETTINGS_TABS).map(([id, { name }]) => (
|
{Object.entries(settingsTabs).map(([id, { name }]) => (
|
||||||
<TabNavLink key={id} to={`/settings/${id}`}>
|
<TabNavLink key={id} to={`/settings/${id}`}>
|
||||||
{name}
|
{name}
|
||||||
</TabNavLink>
|
</TabNavLink>
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||||
|
import type { PlatformCapabilities } from '~/platform/types';
|
||||||
|
import { getSettingsTabs, hasOneClickImportCapability, ONE_CLICK_TAB_ID } from '../settingsTabs';
|
||||||
|
|
||||||
|
const baseCaps = (overrides: Partial<PlatformCapabilities> = {}): PlatformCapabilities => ({
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
directFsAccess: false,
|
||||||
|
androidKeyAccess: AndroidImportType.None,
|
||||||
|
nativeKeyAccess: [],
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('settingsTabs', () => {
|
||||||
|
test('hasOneClickImportCapability is false for browser defaults', () => {
|
||||||
|
expect(hasOneClickImportCapability(baseCaps())).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hasOneClickImportCapability is true with nativeKeyAccess', () => {
|
||||||
|
expect(hasOneClickImportCapability(baseCaps({ nativeKeyAccess: [NativeImportType.QQMusic] }))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hasOneClickImportCapability is true with Adb', () => {
|
||||||
|
expect(hasOneClickImportCapability(baseCaps({ androidKeyAccess: AndroidImportType.Adb }))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getSettingsTabs omits one-click without capability', () => {
|
||||||
|
const tabs = getSettingsTabs(baseCaps());
|
||||||
|
expect(Object.keys(tabs)).toEqual(['general', 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||||
|
expect(tabs[ONE_CLICK_TAB_ID]).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getSettingsTabs inserts one-click after general when capable', () => {
|
||||||
|
const tabs = getSettingsTabs(baseCaps({ nativeKeyAccess: [NativeImportType.Kugou] }));
|
||||||
|
expect(Object.keys(tabs)).toEqual(['general', ONE_CLICK_TAB_ID, 'qmc', 'kwm', 'kgg', 'qtfm']);
|
||||||
|
expect(tabs[ONE_CLICK_TAB_ID]?.name).toBe('一键导入');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import {
|
||||||
|
kugouImportKeys,
|
||||||
|
kwm2ImportKeys,
|
||||||
|
qmc2ImportKeys,
|
||||||
|
qtfmAndroidUpdateKey,
|
||||||
|
} from '~/features/settings/settingsSlice';
|
||||||
|
import type { NativeImportResult } from '~/platform/types';
|
||||||
|
import type { AppDispatch } from '~/store';
|
||||||
|
|
||||||
|
/** Apply native/ADB import payload into staging. Caller may commit immediately (one-click import). */
|
||||||
|
export function applyNativeImportResult(dispatch: AppDispatch, result: NativeImportResult): number {
|
||||||
|
let count = 0;
|
||||||
|
if (result.qmc2?.length) {
|
||||||
|
dispatch(qmc2ImportKeys(result.qmc2));
|
||||||
|
count += result.qmc2.length;
|
||||||
|
}
|
||||||
|
if (result.kwm2?.length) {
|
||||||
|
dispatch(kwm2ImportKeys(result.kwm2));
|
||||||
|
count += result.kwm2.length;
|
||||||
|
}
|
||||||
|
if (result.kugou?.length) {
|
||||||
|
dispatch(kugouImportKeys(result.kugou));
|
||||||
|
count += result.kugou.length;
|
||||||
|
}
|
||||||
|
if (result.qtfm?.android !== undefined) {
|
||||||
|
dispatch(qtfmAndroidUpdateKey({ deviceKey: result.qtfm.android }));
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { useId, useMemo, useState } from 'react';
|
||||||
|
import { Navigate } from 'react-router';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
|
import { useAppDispatch } from '~/hooks';
|
||||||
|
import { applyNativeImportResult } from '~/features/settings/applyNativeImportResult';
|
||||||
|
import { commitStagingChange } from '~/features/settings/settingsSlice';
|
||||||
|
import { hasOneClickImportCapability } from '~/features/settings/settingsTabs';
|
||||||
|
import { AndroidImportType, NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { usePlatform } from '~/platform/PlatformContext';
|
||||||
|
|
||||||
|
const NATIVE_IMPORT_LABELS: Record<NativeImportType, string> = {
|
||||||
|
[NativeImportType.QQMusic]: 'QQ 音乐',
|
||||||
|
[NativeImportType.Kuwo]: '酷我音乐',
|
||||||
|
[NativeImportType.Kugou]: '酷狗音乐',
|
||||||
|
[NativeImportType.QingTing]: '蜻蜓 FM',
|
||||||
|
};
|
||||||
|
|
||||||
|
function selectedFromCaps(types: readonly NativeImportType[]): Record<NativeImportType, boolean> {
|
||||||
|
return {
|
||||||
|
[NativeImportType.QQMusic]: types.includes(NativeImportType.QQMusic),
|
||||||
|
[NativeImportType.Kuwo]: types.includes(NativeImportType.Kuwo),
|
||||||
|
[NativeImportType.Kugou]: types.includes(NativeImportType.Kugou),
|
||||||
|
[NativeImportType.QingTing]: types.includes(NativeImportType.QingTing),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PanelOneClick() {
|
||||||
|
const dispatch = useAppDispatch();
|
||||||
|
const { capabilities, keys } = usePlatform();
|
||||||
|
const nativeTypes = capabilities.nativeKeyAccess;
|
||||||
|
const canAdb = capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||||
|
const canShow = hasOneClickImportCapability(capabilities);
|
||||||
|
|
||||||
|
const [selected, setSelected] = useState(() => selectedFromCaps(nativeTypes));
|
||||||
|
const [importingNative, setImportingNative] = useState(false);
|
||||||
|
const [importingAdb, setImportingAdb] = useState(false);
|
||||||
|
|
||||||
|
const nativeTargets = useMemo(() => nativeTypes.filter((type) => selected[type]), [nativeTypes, selected]);
|
||||||
|
|
||||||
|
const idNative = useId();
|
||||||
|
const idAdb = useId();
|
||||||
|
|
||||||
|
if (!canShow) {
|
||||||
|
return <Navigate to="/settings/general" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const finishImport = (count: number, emptyMessage: string) => {
|
||||||
|
if (count === 0) {
|
||||||
|
toast.info(emptyMessage);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dispatch(commitStagingChange());
|
||||||
|
toast.success(`成功导入 ${count} 项密钥`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportNative = async () => {
|
||||||
|
if (nativeTargets.length === 0) {
|
||||||
|
toast.warning('请至少勾选一个客户端');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setImportingNative(true);
|
||||||
|
try {
|
||||||
|
const result = await keys.importNative(nativeTargets);
|
||||||
|
finishImport(applyNativeImportResult(dispatch, result), '未导入到新密钥');
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`一键导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
} finally {
|
||||||
|
setImportingNative(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleImportAdb = async () => {
|
||||||
|
setImportingAdb(true);
|
||||||
|
try {
|
||||||
|
const targets = nativeTargets.length > 0 ? nativeTargets : undefined;
|
||||||
|
const result = await keys.importAndroidAdb({ targets });
|
||||||
|
finishImport(applyNativeImportResult(dispatch, result), 'ADB 未导入到新密钥');
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(`ADB 导入失败: ${e instanceof Error ? e.message : String(e)}`);
|
||||||
|
} finally {
|
||||||
|
setImportingAdb(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-0 flex-col grow px-1">
|
||||||
|
<h2 className="text-2xl font-bold mb-4">一键导入</h2>
|
||||||
|
<p className="text-sm text-base-content/80 mb-4">
|
||||||
|
从本机已安装的客户端读取密钥并立即保存生效。各格式页的「导入数据库…」仍可单独使用。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{nativeTypes.length > 0 && (
|
||||||
|
<section className="mb-8" aria-labelledby={idNative}>
|
||||||
|
<h3 id={idNative} className="text-xl font-semibold mb-2">
|
||||||
|
本机客户端
|
||||||
|
</h3>
|
||||||
|
<div className="flex flex-col gap-3 mb-4">
|
||||||
|
{nativeTypes.map((type) => {
|
||||||
|
const checkboxId = `${idNative}-${type}`;
|
||||||
|
return (
|
||||||
|
<label key={type} className="flex items-start gap-2" htmlFor={checkboxId}>
|
||||||
|
<input
|
||||||
|
id={checkboxId}
|
||||||
|
type="checkbox"
|
||||||
|
className="checkbox checkbox-sm mt-0.5"
|
||||||
|
checked={selected[type]}
|
||||||
|
onChange={(e) => setSelected((prev) => ({ ...prev, [type]: e.target.checked }))}
|
||||||
|
/>
|
||||||
|
<span className="font-medium">{NATIVE_IMPORT_LABELS[type]}</span>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary btn-sm"
|
||||||
|
disabled={importingNative || nativeTargets.length === 0}
|
||||||
|
onClick={() => void handleImportNative()}
|
||||||
|
>
|
||||||
|
{importingNative ? '导入中…' : '开始导入'}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{canAdb && (
|
||||||
|
<section aria-labelledby={idAdb}>
|
||||||
|
<h3 id={idAdb} className="text-xl font-semibold mb-2">
|
||||||
|
Android ADB
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm text-base-content/70 mb-4">
|
||||||
|
通过 ADB 从已连接设备拉取密钥。若上方已勾选客户端,将仅导入对应格式;未勾选时导入全部支持项。
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-outline btn-sm"
|
||||||
|
disabled={importingAdb}
|
||||||
|
onClick={() => void handleImportAdb()}
|
||||||
|
>
|
||||||
|
{importingAdb ? '导入中…' : '从 ADB 导入'}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { MemoryRouter, Route, Routes } from 'react-router';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import { AndroidImportType, BatchDownloadType, NativeImportType } from '~/platform/capabilities';
|
||||||
|
import { createBrowserProvider } from '~/platform/browser/BrowserProvider';
|
||||||
|
import type { NativeImportResult } from '~/platform/types';
|
||||||
|
import { renderWithProviders, screen, waitFor } from '~/test-utils/test-helper';
|
||||||
|
import { PanelOneClick } from '../PanelOneClick';
|
||||||
|
import { Settings } from '~/features/settings/Settings';
|
||||||
|
|
||||||
|
vi.mock('react-toastify', () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
info: vi.fn(),
|
||||||
|
warning: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const stubCrypto = {
|
||||||
|
request: () => Promise.resolve(null as never),
|
||||||
|
enqueueDecrypt: () => Promise.reject(new Error('unused')),
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderPanel(platform = createBrowserProvider({ crypto: stubCrypto })) {
|
||||||
|
return renderWithProviders(
|
||||||
|
<MemoryRouter initialEntries={['/settings/one-click']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/settings/one-click" element={<PanelOneClick />} />
|
||||||
|
<Route path="/settings/general" element={<div>通用设置页</div>} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>,
|
||||||
|
{ platform },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('redirects to general when platform has no one-click capability', async () => {
|
||||||
|
renderPanel();
|
||||||
|
expect(await screen.findByText('通用设置页')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole('heading', { name: '一键导入' })).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders native checkboxes, commits production, and reports import count', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const importNative = vi.fn().mockImplementation((targets: readonly NativeImportType[]) => {
|
||||||
|
const result: NativeImportResult = {};
|
||||||
|
if (targets.includes(NativeImportType.QQMusic)) {
|
||||||
|
result.qmc2 = [{ name: 'a.mflac', ekey: 'ekey-1' }];
|
||||||
|
}
|
||||||
|
if (targets.includes(NativeImportType.Kugou)) {
|
||||||
|
result.kugou = [{ audioHash: 'hash-1', ekey: 'ekey-2' }];
|
||||||
|
}
|
||||||
|
if (targets.includes(NativeImportType.QingTing)) {
|
||||||
|
result.qtfm = { android: 'deadbeef' };
|
||||||
|
}
|
||||||
|
return Promise.resolve(result);
|
||||||
|
});
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
downloadTypes: [BatchDownloadType.PackZip],
|
||||||
|
nativeKeyAccess: [NativeImportType.QQMusic, NativeImportType.Kugou, NativeImportType.QingTing],
|
||||||
|
keys: {
|
||||||
|
importNative,
|
||||||
|
importAndroidAdb: vi.fn(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { store } = renderPanel(platform);
|
||||||
|
|
||||||
|
expect(screen.getByRole('heading', { name: '一键导入' })).toBeInTheDocument();
|
||||||
|
expect(screen.getByLabelText('QQ 音乐')).toBeChecked();
|
||||||
|
expect(screen.getByLabelText('酷狗音乐')).toBeChecked();
|
||||||
|
expect(screen.getByLabelText('蜻蜓 FM')).toBeChecked();
|
||||||
|
expect(screen.queryByRole('button', { name: '从 ADB 导入' })).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await user.click(screen.getByLabelText('酷狗音乐'));
|
||||||
|
await user.click(screen.getByRole('button', { name: '开始导入' }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(importNative).toHaveBeenCalledWith([NativeImportType.QQMusic, NativeImportType.QingTing]);
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(store.getState().settings.production.qmc2.keys).toMatchObject({ 'a.mflac': 'ekey-1' });
|
||||||
|
});
|
||||||
|
expect(store.getState().settings.production.kugou.keys).toEqual({});
|
||||||
|
expect(store.getState().settings.production.qtfm.android).toBe('deadbeef');
|
||||||
|
expect(store.getState().settings.dirty).toBe(false);
|
||||||
|
expect(toast.success).toHaveBeenCalledWith('成功导入 2 项密钥');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows ADB block, auto-saves importAndroidAdb result', async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const importAndroidAdb = vi.fn().mockResolvedValue({
|
||||||
|
kwm2: [{ rid: '1', quality: '2000', ekey: 'k' }],
|
||||||
|
} satisfies NativeImportResult);
|
||||||
|
const platform = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
androidKeyAccess: AndroidImportType.Adb,
|
||||||
|
nativeKeyAccess: [NativeImportType.Kuwo],
|
||||||
|
keys: {
|
||||||
|
importNative: vi.fn(),
|
||||||
|
importAndroidAdb,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const { store } = renderPanel(platform);
|
||||||
|
|
||||||
|
expect(screen.getByRole('button', { name: '从 ADB 导入' })).toBeInTheDocument();
|
||||||
|
await user.click(screen.getByRole('button', { name: '从 ADB 导入' }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(importAndroidAdb).toHaveBeenCalledWith({ targets: [NativeImportType.Kuwo] });
|
||||||
|
});
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(store.getState().settings.production.kwm2.keys).toMatchObject({ '1-2000': 'k' });
|
||||||
|
});
|
||||||
|
expect(store.getState().settings.dirty).toBe(false);
|
||||||
|
expect(toast.success).toHaveBeenCalledWith('成功导入 1 项密钥');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('settings sidebar omits 一键导入 without capability and includes it when capable', () => {
|
||||||
|
const without = createBrowserProvider({ crypto: stubCrypto });
|
||||||
|
const { unmount } = renderWithProviders(
|
||||||
|
<MemoryRouter initialEntries={['/settings/general']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/settings" element={<Settings />}>
|
||||||
|
<Route path="general" element={<div />} />
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>,
|
||||||
|
{ platform: without },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.queryByRole('tab', { name: '一键导入' })).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('tab', { name: '通用设置' })).toBeInTheDocument();
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
const withNative = createBrowserProvider({
|
||||||
|
crypto: stubCrypto,
|
||||||
|
nativeKeyAccess: [NativeImportType.QQMusic],
|
||||||
|
});
|
||||||
|
renderWithProviders(
|
||||||
|
<MemoryRouter initialEntries={['/settings/general']}>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/settings" element={<Settings />}>
|
||||||
|
<Route path="general" element={<div />} />
|
||||||
|
<Route path="one-click" element={<div />} />
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>,
|
||||||
|
{ platform: withNative },
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByRole('tab', { name: '一键导入' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
import type { FC } from 'react';
|
import type { FC } from 'react';
|
||||||
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
|
import { PanelGeneral } from '~/features/settings/panels/PanelGeneral.tsx';
|
||||||
|
import { PanelOneClick } from '~/features/settings/panels/PanelOneClick.tsx';
|
||||||
import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
|
import { PanelQMCv2Key } from '~/features/qmc/panel/PanelQMCv2Key.tsx';
|
||||||
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
import { PanelKWMv2Key } from '~/features/kwm/panel/PanelKWMv2Key.tsx';
|
||||||
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
import { PanelKGGKey } from '~/features/kugou/panel/PanelKGGKey.tsx';
|
||||||
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
||||||
|
import { AndroidImportType } from '~/platform/capabilities';
|
||||||
|
import type { PlatformCapabilities } from '~/platform/types';
|
||||||
|
|
||||||
|
export type SettingsTabDef = { name: string; Tab: FC };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Settings UI route ids → panels.
|
* Settings UI route ids → panels.
|
||||||
@@ -13,11 +18,38 @@ import { PanelQingTing } from '~/features/qtfm/panel/PanelQingTing.tsx';
|
|||||||
* - `kwm` ↔ state `kwm2`
|
* - `kwm` ↔ state `kwm2`
|
||||||
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
* - `kgg` ↔ state `kugou` (persist key stays `kugou`)
|
||||||
* - `qtfm` ↔ state `qtfm`
|
* - `qtfm` ↔ state `qtfm`
|
||||||
|
* - `one-click` ↔ platform native / ADB key import (only when capable)
|
||||||
*/
|
*/
|
||||||
export const SETTINGS_TABS: Record<string, { name: string; Tab: FC }> = {
|
export const ONE_CLICK_TAB_ID = 'one-click';
|
||||||
|
|
||||||
|
const CORE_SETTINGS_TABS: Record<string, SettingsTabDef> = {
|
||||||
general: { name: '通用设置', Tab: PanelGeneral },
|
general: { name: '通用设置', Tab: PanelGeneral },
|
||||||
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },
|
||||||
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
kwm: { name: 'KWMv2 密钥', Tab: PanelKWMv2Key },
|
||||||
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
kgg: { name: 'KGG 密钥', Tab: PanelKGGKey },
|
||||||
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
|
qtfm: { name: '蜻蜓 FM', Tab: PanelQingTing },
|
||||||
} as const;
|
};
|
||||||
|
|
||||||
|
const ONE_CLICK_TAB: SettingsTabDef = { name: '一键导入', Tab: PanelOneClick };
|
||||||
|
|
||||||
|
/** True when the platform can show the one-click import settings tab. */
|
||||||
|
export function hasOneClickImportCapability(capabilities: PlatformCapabilities): boolean {
|
||||||
|
return capabilities.nativeKeyAccess.length > 0 || capabilities.androidKeyAccess === AndroidImportType.Adb;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings tabs for the current platform.
|
||||||
|
* Registers `one-click` only when `nativeKeyAccess` or ADB import is available.
|
||||||
|
*/
|
||||||
|
export function getSettingsTabs(capabilities: PlatformCapabilities): Record<string, SettingsTabDef> {
|
||||||
|
if (!hasOneClickImportCapability(capabilities)) {
|
||||||
|
return CORE_SETTINGS_TABS;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { general, ...rest } = CORE_SETTINGS_TABS;
|
||||||
|
return {
|
||||||
|
general,
|
||||||
|
[ONE_CLICK_TAB_ID]: ONE_CLICK_TAB,
|
||||||
|
...rest,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -29,6 +29,12 @@ export interface BrowserProviderOptions {
|
|||||||
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
downloadTypes?: PlatformCapabilities['downloadTypes'];
|
||||||
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
/** Override `directFsAccess` (tests). Browser default is `false`. */
|
||||||
directFsAccess?: boolean;
|
directFsAccess?: boolean;
|
||||||
|
/** Override `nativeKeyAccess` (tests). Browser default is `[]`. */
|
||||||
|
nativeKeyAccess?: PlatformCapabilities['nativeKeyAccess'];
|
||||||
|
/** Override `androidKeyAccess` (tests). Browser default is `None`. */
|
||||||
|
androidKeyAccess?: PlatformCapabilities['androidKeyAccess'];
|
||||||
|
/** Override `keys` backend (tests). Defaults to `NotSupportedMethod` for both methods. */
|
||||||
|
keys?: PlatformProvider['keys'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,8 +52,8 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
|||||||
const capabilities: PlatformCapabilities = Object.freeze({
|
const capabilities: PlatformCapabilities = Object.freeze({
|
||||||
downloadTypes,
|
downloadTypes,
|
||||||
directFsAccess: options.directFsAccess ?? false,
|
directFsAccess: options.directFsAccess ?? false,
|
||||||
androidKeyAccess: AndroidImportType.None,
|
androidKeyAccess: options.androidKeyAccess ?? AndroidImportType.None,
|
||||||
nativeKeyAccess: Object.freeze([] as NativeImportType[]),
|
nativeKeyAccess: Object.freeze(options.nativeKeyAccess ? [...options.nativeKeyAccess] : ([] as NativeImportType[])),
|
||||||
});
|
});
|
||||||
|
|
||||||
const settingsIo = createBrowserSettingsIo(
|
const settingsIo = createBrowserSettingsIo(
|
||||||
@@ -102,7 +108,7 @@ export function createBrowserProvider(options: BrowserProviderOptions = {}): Pla
|
|||||||
|
|
||||||
download,
|
download,
|
||||||
|
|
||||||
keys: {
|
keys: options.keys ?? {
|
||||||
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
importNative: (_targets: readonly NativeImportType[]): Promise<NativeImportResult> =>
|
||||||
notSupported('keys.importNative'),
|
notSupported('keys.importNative'),
|
||||||
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> =>
|
importAndroidAdb: (_opts: AndroidAdbImportOptions): Promise<NativeImportResult> =>
|
||||||
|
|||||||
Reference in new issue
Block a user