From a9a937bc5ecda4080e7cd902fc2b3b2335a6c196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B2=81=E6=A0=91=E4=BA=BA?= Date: Sat, 31 Oct 2026 23:37:55 +0900 Subject: [PATCH] docs: enhance comments and documentation for KuGou/KGG settings - Added detailed comments and documentation for KuGou/KGG key formats and settings in keyFormats.ts, persistSettings.ts, settingsSelector.ts, settingsSlice.ts, and settingsTabs.tsx. - Improved clarity on UI route identifiers and Redux persist keys for better understanding and maintenance. --- .../__tests__/settingsConverters.test.ts | 207 ++++++++++++++++++ .../settings/createKeyListReducers.ts | 78 +++++++ src/features/settings/keyFormats.ts | 5 +- src/features/settings/persistSettings.ts | 3 +- src/features/settings/settingsSelector.ts | 2 + src/features/settings/settingsSlice.ts | 130 +++-------- src/features/settings/settingsTabs.tsx | 9 + 7 files changed, 335 insertions(+), 99 deletions(-) create mode 100644 src/features/settings/__tests__/settingsConverters.test.ts create mode 100644 src/features/settings/createKeyListReducers.ts diff --git a/src/features/settings/__tests__/settingsConverters.test.ts b/src/features/settings/__tests__/settingsConverters.test.ts new file mode 100644 index 0000000..573ebca --- /dev/null +++ b/src/features/settings/__tests__/settingsConverters.test.ts @@ -0,0 +1,207 @@ +import { configureStore } from '@reduxjs/toolkit'; + +import { + commitStagingChange, + discardStagingChanges, + productionToStaging, + qmc2AddKey, + qmc2ImportKeys, + qmc2UpdateKey, + settingsSlice, + stagingToProduction, + type ProductionSettings, + type StagingSettings, +} from '../settingsSlice'; +import { mergeSettings } from '../persistSettings'; +import { + kwm2StagingToProductionKey, + productionKeyToStaging, + qmc2ProductionToStaging, + qmc2StagingToProductionKey, + qmc2StagingToProductionValue, + stagingKeyToProduction, +} from '../keyFormats'; + +function createSettingsStore(preloaded?: ReturnType) { + return configureStore({ + reducer: { settings: settingsSlice.reducer }, + preloadedState: preloaded ? { settings: preloaded } : undefined, + }); +} + +describe('stagingToProduction / productionToStaging', () => { + test('stagingToProduction maps qmc2/kwm2/kugou keys and copies scalars', () => { + const staging: StagingSettings = { + general: { + batchDownload: { + directoryPicker: false, + rememberDirectory: false, + streamingZip: true, + blobZip: false, + }, + }, + qmc2: { + allowFuzzyNameSearch: false, + keys: [{ id: 'q1', name: 'a.mflac', ekey: ' ek1 ' }], + }, + kwm2: { + keys: [{ id: 'k1', rid: '123', quality: '2000k', ekey: 'kw' }], + }, + kugou: { + keys: [{ id: 'g1', audioHash: 'hash1', ekey: 'kg' }], + }, + qtfm: { android: 'abcd' }, + }; + + expect(stagingToProduction(staging)).toEqual({ + general: { + batchDownload: { + directoryPicker: false, + rememberDirectory: false, + streamingZip: true, + blobZip: false, + }, + }, + qmc2: { + allowFuzzyNameSearch: false, + keys: { 'a.mflac': 'ek1' }, + }, + kwm2: { + keys: { [kwm2StagingToProductionKey(staging.kwm2.keys[0])]: 'kw' }, + }, + kugou: { + keys: { hash1: 'kg' }, + }, + qtfm: { android: 'abcd' }, + }); + }); + + test('productionToStaging round-trips values via keyFormats helpers', () => { + const production: ProductionSettings = { + general: settingsSlice.getInitialState().production.general, + qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } }, + kwm2: { keys: { '42-2000': 'kw' } }, + kugou: { keys: { abcd: 'kg' } }, + qtfm: { android: 'ff00' }, + }; + + const staging = productionToStaging(production); + expect(staging.qmc2.allowFuzzyNameSearch).toBe(true); + expect(staging.qmc2.keys).toHaveLength(1); + expect(staging.qmc2.keys[0]).toMatchObject({ name: 'song.mflac', ekey: 'ek' }); + expect(staging.qmc2.keys[0].id).toEqual(expect.any(String)); + + expect(staging.kwm2.keys).toEqual([expect.objectContaining({ rid: '42', quality: '2000', ekey: 'kw' })]); + expect(staging.kugou.keys).toEqual([expect.objectContaining({ audioHash: 'abcd', ekey: 'kg' })]); + expect(staging.qtfm.android).toBe('ff00'); + + // Same mapping as productionKeyToStaging for qmc2 + expect(staging.qmc2.keys.map(({ name, ekey }) => ({ name, ekey }))).toEqual( + productionKeyToStaging(production.qmc2.keys, qmc2ProductionToStaging).map(({ name, ekey }) => ({ name, ekey })), + ); + }); + + test('stagingKeyToProduction matches stagingToProduction for qmc2 keys', () => { + const keys = [{ id: '1', name: 'x.mflac', ekey: ' e ' }]; + expect(stagingKeyToProduction(keys, qmc2StagingToProductionKey, qmc2StagingToProductionValue)).toEqual( + stagingToProduction({ + ...settingsSlice.getInitialState().staging, + qmc2: { allowFuzzyNameSearch: true, keys }, + }).qmc2.keys, + ); + }); +}); + +describe('commitStagingChange', () => { + test('does not regenerate staging key ids', () => { + const store = createSettingsStore(); + store.dispatch(qmc2AddKey()); + const id = store.getState().settings.staging.qmc2.keys[0].id; + + store.dispatch(qmc2UpdateKey({ id, field: 'name', value: 'track.mflac' })); + store.dispatch(qmc2UpdateKey({ id, field: 'ekey', value: 'secret' })); + store.dispatch(commitStagingChange()); + + const { dirty, staging, production } = store.getState().settings; + expect(dirty).toBe(false); + expect(staging.qmc2.keys[0].id).toBe(id); + expect(production.qmc2.keys).toEqual({ 'track.mflac': 'secret' }); + }); + + test('keeps ids stable across multiple commits', () => { + const store = createSettingsStore(); + store.dispatch(qmc2ImportKeys([{ name: 'a.mflac', ekey: '1' }])); + const id = store.getState().settings.staging.qmc2.keys[0].id; + + store.dispatch(commitStagingChange()); + store.dispatch(qmc2UpdateKey({ id, field: 'ekey', value: '2' })); + store.dispatch(commitStagingChange()); + + expect(store.getState().settings.staging.qmc2.keys[0].id).toBe(id); + expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': '2' }); + }); +}); + +describe('discardStagingChanges', () => { + test('restores staging from production (ids may change)', () => { + const store = createSettingsStore(); + store.dispatch(qmc2ImportKeys([{ name: 'a.mflac', ekey: '1' }])); + store.dispatch(commitStagingChange()); + + store.dispatch( + qmc2UpdateKey({ id: store.getState().settings.staging.qmc2.keys[0].id, field: 'ekey', value: 'dirty' }), + ); + expect(store.getState().settings.dirty).toBe(true); + + store.dispatch(discardStagingChanges()); + + expect(store.getState().settings.dirty).toBe(false); + expect(store.getState().settings.staging.qmc2.keys).toEqual([ + expect.objectContaining({ name: 'a.mflac', ekey: '1' }), + ]); + expect(store.getState().settings.production.qmc2.keys).toEqual({ 'a.mflac': '1' }); + }); +}); + +describe('mergeSettings', () => { + test('fills defaults and keeps valid production keys', () => { + const merged = mergeSettings({ + qmc2: { allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } }, + kwm2: { keys: { '1-2000': 'kw', bad: 'x', '2-hi': 'y' } }, + kugou: { keys: { hash: 'kg', nested: { nope: true } } }, + qtfm: { android: 'zz11!!aa' }, + } as unknown as ProductionSettings); + + expect(merged.general.batchDownload).toEqual(settingsSlice.getInitialState().production.general.batchDownload); + expect(merged.qmc2).toEqual({ allowFuzzyNameSearch: false, keys: { 'a.mflac': 'ek' } }); + // only keys matching /^(\d+)-(\w+)$/ + expect(merged.kwm2.keys).toEqual({ '1-2000': 'kw', '2-hi': 'y' }); + expect(merged.kugou.keys).toEqual({ hash: 'kg' }); + // non-hex stripped (`z` is not hex) + expect(merged.qtfm.android).toBe('11aa'); + }); + + test('merged production round-trips through productionToStaging → stagingToProduction', () => { + const merged = mergeSettings({ + general: { + batchDownload: { + directoryPicker: false, + rememberDirectory: true, + streamingZip: false, + blobZip: true, + }, + }, + qmc2: { allowFuzzyNameSearch: true, keys: { 'song.mflac': 'ek' } }, + kwm2: { keys: { '9-1000': 'kw' } }, + kugou: { keys: { h1: 'kg' } }, + qtfm: { android: 'abc' }, + }); + + const roundTrip = stagingToProduction(productionToStaging(merged)); + expect(roundTrip.general).toEqual(merged.general); + expect(roundTrip.qmc2).toEqual(merged.qmc2); + expect(roundTrip.kwm2).toEqual(merged.kwm2); + expect(roundTrip.kugou).toEqual(merged.kugou); + expect(roundTrip.qtfm).toEqual(merged.qtfm); + }); +}); diff --git a/src/features/settings/createKeyListReducers.ts b/src/features/settings/createKeyListReducers.ts new file mode 100644 index 0000000..e6fe05c --- /dev/null +++ b/src/features/settings/createKeyListReducers.ts @@ -0,0 +1,78 @@ +import type { PayloadAction, WritableDraft } from '@reduxjs/toolkit'; +import { nanoid } from 'nanoid'; + +import type { StagingKWMv2Key, StagingKugouKey, StagingQMCv2Key } from './keyFormats'; + +/** Formats that store keys as a staging list (array with stable `id`). */ +export type KeyListFormat = 'qmc2' | 'kwm2' | 'kugou'; + +type StagingKeyByFormat = { + qmc2: StagingQMCv2Key; + kwm2: StagingKWMv2Key; + kugou: StagingKugouKey; +}; + +/** Minimal state shape so this module does not import settingsSlice (avoids cycles). */ +type KeyListSettingsState = { + dirty: boolean; + staging: { + qmc2: { keys: StagingQMCv2Key[] }; + kwm2: { keys: StagingKWMv2Key[] }; + kugou: { keys: StagingKugouKey[] }; + }; +}; + +/** + * Shared Add / Import / Delete / Update / Clear reducers for staging key lists. + * Action names are wired by the caller (`qmc2AddKey`, `kwm2AddKey`, …). + * + * Returns arrow-function reducers so they can be assigned into `createSlice` without + * unbound-method lint issues. + */ +export function createKeyListReducers( + path: F, + emptyItem: () => Omit, +) { + type T = StagingKeyByFormat[F]; + type Field = Exclude; + type DraftState = WritableDraft; + + const getKeys = (state: DraftState): T[] => state.staging[path].keys as T[]; + + const setKeys = (state: DraftState, keys: T[]) => { + // Generic path makes TS widen the union; cast is safe for a fixed `path`. + (state.staging[path] as { keys: T[] }).keys = keys; + }; + + return { + addKey: (state: DraftState) => { + getKeys(state).push({ id: nanoid(), ...emptyItem() } as T); + state.dirty = true; + }, + importKeys: (state: DraftState, { payload }: PayloadAction[]>) => { + getKeys(state).push(...payload.map((item) => ({ id: nanoid(), ...item }) as T)); + state.dirty = true; + }, + deleteKey: (state: DraftState, { payload: { id } }: PayloadAction<{ id: string }>) => { + setKeys( + state, + getKeys(state).filter((item) => item.id !== id), + ); + state.dirty = true; + }, + updateKey: ( + state: DraftState, + { payload: { id, field, value } }: PayloadAction<{ id: string; field: Field; value: string }>, + ) => { + const keyItem = getKeys(state).find((item) => item.id === id); + if (keyItem) { + (keyItem as Record)[field] = value; + state.dirty = true; + } + }, + clearKeys: (state: DraftState) => { + setKeys(state, []); + state.dirty = true; + }, + }; +} diff --git a/src/features/settings/keyFormats.ts b/src/features/settings/keyFormats.ts index 559e3c9..4a75b6d 100644 --- a/src/features/settings/keyFormats.ts +++ b/src/features/settings/keyFormats.ts @@ -79,7 +79,10 @@ export const kwm2ProductionToStaging = ( return { id: nanoid(), rid, quality, ekey: value }; }; -// KuGou (kgg, kgm v5) +/** + * KuGou / KGG (kgm v5). + * UI settings tab route: `kgg`. Redux + localStorage production field: `kugou`. + */ export interface StagingKugouKey { id: string; audioHash: string; diff --git a/src/features/settings/persistSettings.ts b/src/features/settings/persistSettings.ts index b3e32a3..aa25749 100644 --- a/src/features/settings/persistSettings.ts +++ b/src/features/settings/persistSettings.ts @@ -28,7 +28,8 @@ function mergeBatchDownload(source: Partial | undefined): return result; } -function mergeSettings(settings: ProductionSettings): ProductionSettings { +/** Normalize / sanitize loaded production settings against defaults. Exported for tests. */ +export function mergeSettings(settings: ProductionSettings): ProductionSettings { const draft = deepClone(settingsSlice.getInitialState().production); draft.general.batchDownload = mergeBatchDownload(settings?.general?.batchDownload); diff --git a/src/features/settings/settingsSelector.ts b/src/features/settings/settingsSelector.ts index a05ff10..5646db4 100644 --- a/src/features/settings/settingsSelector.ts +++ b/src/features/settings/settingsSelector.ts @@ -12,7 +12,9 @@ export const selectFinalQMCv2Settings = (state: RootState) => state.settings.pro export const selectStagingKWMv2Keys = (state: RootState) => state.settings.staging.kwm2.keys; export const selectFinalKWMv2Keys = (state: RootState) => state.settings.production.kwm2.keys; +/** Staging KuGou/KGG keys (`state.settings.staging.kugou`; UI tab `kgg`). */ export const selectStagingKugouV5Keys = (state: RootState) => state.settings.staging.kugou.keys; +/** Production KuGou/KGG keys (`state.settings.production.kugou`; persist key `kugou`). */ export const selectFinalKugouV5Keys = (state: RootState) => state.settings.production.kugou.keys; export const selectQMCv2KeyByFileName = (state: RootState, name: string): string | undefined => { diff --git a/src/features/settings/settingsSlice.ts b/src/features/settings/settingsSlice.ts index c638b9a..3d56f47 100644 --- a/src/features/settings/settingsSlice.ts +++ b/src/features/settings/settingsSlice.ts @@ -1,6 +1,5 @@ import { createSlice } from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit'; -import { nanoid } from 'nanoid'; import { ProductionKWMv2Keys, ProductionQMCv2Keys, @@ -20,6 +19,7 @@ import { kugouStagingToProductionValue, StagingKugouKey, } from './keyFormats'; +import { createKeyListReducers } from './createKeyListReducers'; export interface BatchDownloadSettings { directoryPicker: boolean; @@ -39,6 +39,10 @@ export interface StagingSettings { kwm2: { keys: StagingKWMv2Key[]; }; + /** + * KuGou / KGG keys. + * UI route tab id is `kgg`; Redux / production persist key remains `kugou`. + */ kugou: { keys: StagingKugouKey[]; }; @@ -58,6 +62,10 @@ export interface ProductionSettings { kwm2: { keys: ProductionKWMv2Keys; // { [`${rid}-${quality}`]: ekey } }; + /** + * KuGou / KGG keys. + * UI route tab id is `kgg`; localStorage production shape key remains `kugou` (do not rename). + */ kugou: { keys: ProductionKugouKey; // { [fileName]: ekey } }; @@ -97,7 +105,7 @@ const initialState: SettingsState = { }, }; -const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({ +export const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({ general: { batchDownload: { ...staging.general.batchDownload }, }, @@ -114,7 +122,7 @@ const stagingToProduction = (staging: StagingSettings): ProductionSettings => ({ qtfm: staging.qtfm, }); -const productionToStaging = (production: ProductionSettings): StagingSettings => ({ +export const productionToStaging = (production: ProductionSettings): StagingSettings => ({ general: { batchDownload: { ...production.general.batchDownload }, }, @@ -131,6 +139,10 @@ const productionToStaging = (production: ProductionSettings): StagingSettings => qtfm: production.qtfm, }); +const qmc2KeyList = createKeyListReducers('qmc2', () => ({ name: '', ekey: '' })); +const kwm2KeyList = createKeyListReducers('kwm2', () => ({ ekey: '', quality: '', rid: '' })); +const kugouKeyList = createKeyListReducers('kugou', () => ({ audioHash: '', ekey: '' })); + export const settingsSlice = createSlice({ name: 'settings', initialState, @@ -142,96 +154,25 @@ export const settingsSlice = createSlice({ staging: productionToStaging(payload), }; }, - // - qmc2AddKey(state) { - state.staging.qmc2.keys.push({ id: nanoid(), name: '', ekey: '' }); - state.dirty = true; - }, - qmc2ImportKeys(state, { payload }: PayloadAction[]>) { - const newItems = payload.map((item) => ({ id: nanoid(), ...item })); - state.staging.qmc2.keys.push(...newItems); - state.dirty = true; - }, - qmc2DeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) { - const qmc2 = state.staging.qmc2; - qmc2.keys = qmc2.keys.filter((item) => item.id !== id); - state.dirty = true; - }, - qmc2UpdateKey( - state, - { payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingQMCv2Key; value: string }>, - ) { - const keyItem = state.staging.qmc2.keys.find((item) => item.id === id); - if (keyItem) { - keyItem[field] = value; - state.dirty = true; - } - }, - qmc2ClearKeys(state) { - state.staging.qmc2.keys = []; - state.dirty = true; - }, + qmc2AddKey: qmc2KeyList.addKey, + qmc2ImportKeys: qmc2KeyList.importKeys, + qmc2DeleteKey: qmc2KeyList.deleteKey, + qmc2UpdateKey: qmc2KeyList.updateKey, + qmc2ClearKeys: qmc2KeyList.clearKeys, qmc2AllowFuzzyNameSearch(state, { payload: { enable } }: PayloadAction<{ enable: boolean }>) { state.staging.qmc2.allowFuzzyNameSearch = enable; state.dirty = true; }, - // TODO: reuse the logic somehow? - kwm2AddKey(state) { - state.staging.kwm2.keys.push({ id: nanoid(), ekey: '', quality: '', rid: '' }); - state.dirty = true; - }, - kwm2ImportKeys(state, { payload }: PayloadAction[]>) { - const newItems = payload.map((item) => ({ id: nanoid(), ...item })); - state.staging.kwm2.keys.push(...newItems); - state.dirty = true; - }, - kwm2DeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) { - const kwm2 = state.staging.kwm2; - kwm2.keys = kwm2.keys.filter((item) => item.id !== id); - state.dirty = true; - }, - kwm2UpdateKey( - state, - { payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingKWMv2Key; value: string }>, - ) { - const keyItem = state.staging.kwm2.keys.find((item) => item.id === id); - if (keyItem) { - keyItem[field] = value; - state.dirty = true; - } - }, - kwm2ClearKeys(state) { - state.staging.kwm2.keys = []; - state.dirty = true; - }, - kugouAddKey(state) { - state.staging.kugou.keys.push({ id: nanoid(), audioHash: '', ekey: '' }); - state.dirty = true; - }, - kugouImportKeys(state, { payload }: PayloadAction[]>) { - const newItems = payload.map((item) => ({ id: nanoid(), ...item })); - state.staging.kugou.keys.push(...newItems); - state.dirty = true; - }, - kugouDeleteKey(state, { payload: { id } }: PayloadAction<{ id: string }>) { - const kugou = state.staging.kugou; - kugou.keys = kugou.keys.filter((item) => item.id !== id); - state.dirty = true; - }, - kugouUpdateKey( - state, - { payload: { id, field, value } }: PayloadAction<{ id: string; field: keyof StagingKugouKey; value: string }>, - ) { - const keyItem = state.staging.kugou.keys.find((item) => item.id === id); - if (keyItem) { - keyItem[field] = value; - state.dirty = true; - } - }, - kugouClearKeys(state) { - state.staging.kugou.keys = []; - state.dirty = true; - }, + kwm2AddKey: kwm2KeyList.addKey, + kwm2ImportKeys: kwm2KeyList.importKeys, + kwm2DeleteKey: kwm2KeyList.deleteKey, + kwm2UpdateKey: kwm2KeyList.updateKey, + kwm2ClearKeys: kwm2KeyList.clearKeys, + kugouAddKey: kugouKeyList.addKey, + kugouImportKeys: kugouKeyList.importKeys, + kugouDeleteKey: kugouKeyList.deleteKey, + kugouUpdateKey: kugouKeyList.updateKey, + kugouClearKeys: kugouKeyList.clearKeys, qtfmAndroidUpdateKey(state, { payload: { deviceKey } }: PayloadAction<{ deviceKey: string }>) { state.staging.qtfm.android = deviceKey; state.dirty = true; @@ -243,19 +184,14 @@ export const settingsSlice = createSlice({ state.staging.general.batchDownload[key] = value; state.dirty = true; }, - // discardStagingChanges: (state) => { state.dirty = false; state.staging = productionToStaging(state.production); }, + /** Apply staging → production. Staging list row `id`s are kept (no productionToStaging round-trip). */ commitStagingChange: (state) => { - const production = stagingToProduction(state.staging); - return { - dirty: false, - // Sync back to staging - staging: productionToStaging(production), - production, - }; + state.production = stagingToProduction(state.staging); + state.dirty = false; }, resetConfig: () => { return initialState; diff --git a/src/features/settings/settingsTabs.tsx b/src/features/settings/settingsTabs.tsx index c4417de..855ada7 100644 --- a/src/features/settings/settingsTabs.tsx +++ b/src/features/settings/settingsTabs.tsx @@ -5,6 +5,15 @@ import { PanelKWMv2Key } from '~/features/settings/panels/PanelKWMv2Key.tsx'; import { PanelKGGKey } from '~/features/settings/panels/PanelKGGKey.tsx'; import { PanelQingTing } from '~/features/settings/panels/PanelQingTing.tsx'; +/** + * Settings UI route ids → panels. + * + * Naming aliases (route vs Redux / persist): + * - `qmc` ↔ state `qmc2` + * - `kwm` ↔ state `kwm2` + * - `kgg` ↔ state `kugou` (persist key stays `kugou`; Phase 2 may align paths) + * - `qtfm` ↔ state `qtfm` + */ export const SETTINGS_TABS: Record = { general: { name: '通用设置', Tab: PanelGeneral }, qmc: { name: 'QMCv2 密钥', Tab: PanelQMCv2Key },