Skip to content

Commit

Permalink
refactor: 部分重构
Browse files Browse the repository at this point in the history
  • Loading branch information
maotoumao committed Aug 28, 2023
1 parent ccb06c1 commit af417a2
Show file tree
Hide file tree
Showing 14 changed files with 170 additions and 41 deletions.
2 changes: 2 additions & 0 deletions src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ipcRendererDelegate from "./internal/ipc-renderer-delegate";
import fsDelegate from "./internal/fs-delegate";
import themepack from "./internal/themepack";
import path from 'path';
import { rimraf } from "rimraf";
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts


Expand All @@ -14,3 +15,4 @@ contextBridge.exposeInMainWorld('ipcRenderer', ipcRendererDelegate);
contextBridge.exposeInMainWorld('fs', fsDelegate);
contextBridge.exposeInMainWorld('themepack', themepack);
contextBridge.exposeInMainWorld('path', path);
contextBridge.exposeInMainWorld('rimraf', rimraf)
1 change: 1 addition & 0 deletions src/renderer/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@

& .tab-panel-container {
height: 100%;
outline: none;
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/renderer/components/MusicList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ function _MusicList(props: IMusicListProps) {
return () => {
hotkeys.unbind('Shift', musiclistScope);
}
})
}, [])

return (
<div className="music-list-container" ref={tableContainerRef}>
Expand Down Expand Up @@ -241,6 +241,7 @@ function _MusicList(props: IMusicListProps) {
>
{virtualController.virtualItems.map((virtualItem) => {
const row = virtualItem.dataItem;
// todo 拆出一个组件
return (
<tr
key={row.id}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
getInternalData,
getMediaPrimaryKey,
isSameMedia,
setInternalData,
Expand All @@ -8,12 +9,15 @@ import {
getUserPerferenceIDB,
setUserPerferenceIDB,
} from "@/renderer/utils/user-perference";
import musicSheetDB from "./db";
import musicSheetDB from "../music-sheet/internal/db";
import { internalDataKey, musicRefSymbol } from "@/common/constant";
import { useEffect, useState } from "react";
import Evt from "../events";

const downloadedMusicListStore = new Store<IMedia.IMediaBase[]>([]);
const downloadedSet = new Set<string>();

// 在初始化歌单时一起初始化
export async function setupDownloadedMusicList() {
const downloaded = (await getUserPerferenceIDB("downloadedList")) ?? [];
downloadedMusicListStore.setValue(downloaded);
Expand All @@ -23,14 +27,14 @@ export async function setupDownloadedMusicList() {
}

function primaryKeyMap(media: IMedia.IMediaBase) {
return {
platform: media.platform,
id: media.id
}
return {
platform: media.platform,
id: media.id,
};
}

// 添加到已下载完成的列表中
export async function addDownloadedMusic(
export async function addDownloadedMusicToList(
musicItems: IMusic.IMusicItem | IMusic.IMusicItem[]
) {
const _musicItems = Array.isArray(musicItems) ? musicItems : [musicItems];
Expand Down Expand Up @@ -61,10 +65,14 @@ export async function addDownloadedMusic(
}
});
await musicSheetDB.musicStore.bulkPut(allMusic);
downloadedMusicListStore.setValue((prev) => [...prev, ...(allMusic.map(primaryKeyMap))]);
downloadedMusicListStore.setValue((prev) => [
...prev,
...allMusic.map(primaryKeyMap),
]);
allMusic.forEach((it) => {
downloadedSet.add(getMediaPrimaryKey(it));
});
Evt.emit("MUSIC_DOWNLOADED", allMusic);
setUserPerferenceIDB(
"downloadedList",
downloadedMusicListStore.getValue()
Expand All @@ -76,7 +84,8 @@ export async function addDownloadedMusic(
}

export async function removeDownloadedMusic(
musicItems: IMusic.IMusicItem | IMusic.IMusicItem[]
musicItems: IMusic.IMusicItem | IMusic.IMusicItem[],
removeFile = false
) {
const _musicItems = Array.isArray(musicItems) ? musicItems : [musicItems];

Expand All @@ -88,23 +97,37 @@ export async function removeDownloadedMusic(
);
const needDelete: any[] = [];
const needUpdate: any[] = [];
toBeRemovedMusicDetail.forEach((musicItem) => {
if (!musicItem) {
return;
}
musicItem[musicRefSymbol]--;
if (musicItem[musicRefSymbol] === 0) {
needDelete.push([musicItem.platform, musicItem.id]);
} else {
// 清空下载
setInternalData<IMusic.IMusicItemInternalData>(
musicItem,
"downloadData",
null
);
needUpdate.push(musicItem);
}
});
await Promise.all(
toBeRemovedMusicDetail.map(async (musicItem) => {
if (!musicItem) {
return;
}
// 1. 如果要删除本地文件
if (removeFile) {
const internalPath = getInternalData<IMusic.IMusicItemInternalData>(
musicItem,
"downloadData"
)?.path;
const rmResult = await window.rimraf(internalPath);
if (!rmResult) {
return;
}
}
// 只从歌单中删除,引用-1
musicItem[musicRefSymbol]--;
if (musicItem[musicRefSymbol] === 0) {
needDelete.push([musicItem.platform, musicItem.id]);
} else {
// 清空下载
setInternalData<IMusic.IMusicItemInternalData>(
musicItem,
"downloadData",
null
);
needUpdate.push(musicItem);
}
})
);
await musicSheetDB.musicStore.bulkDelete(needDelete);
await musicSheetDB.musicStore.bulkPut(needUpdate);

Expand All @@ -113,7 +136,8 @@ export async function removeDownloadedMusic(
(it) => -1 === _musicItems.findIndex((_) => isSameMedia(_, it))
)
);

// 触发事件
Evt.emit("MUSIC_REMOVE_DOWNLOADED", _musicItems);
_musicItems.forEach((it) => {
downloadedSet.delete(getMediaPrimaryKey(it));
});
Expand All @@ -128,6 +152,46 @@ export async function removeDownloadedMusic(
}
}

export function isDownloadeed(musicItem: IMedia.IMediaBase) {
return downloadedSet.has(getMediaPrimaryKey(musicItem));
export function isDownloaded(musicItem: IMedia.IMediaBase) {
return musicItem ? downloadedSet.has(getMediaPrimaryKey(musicItem)) : false;
}

export const useDownloadedMusicList = downloadedMusicListStore.useValue;

export function useDownloaded(musicItem: IMedia.IMediaBase) {
const [downloaded, setDownloaded] = useState(isDownloaded(musicItem));

useEffect(() => {
const dlCb = (musicItems: IMusic.IMusicItem | IMusic.IMusicItem[]) => {
if (Array.isArray(musicItems)) {
setDownloaded(
(prev) =>
prev ||
musicItems.findIndex((it) => isSameMedia(it, musicItem)) !== -1
);
} else {
setDownloaded((prev) => prev || isSameMedia(musicItem, musicItems));
}
};

const rmCb = (musicItems: IMusic.IMusicItem | IMusic.IMusicItem[]) => {
if (Array.isArray(musicItems)) {
setDownloaded(
(prev) =>
prev &&
musicItems.findIndex((it) => isSameMedia(it, musicItem)) === -1
);
} else {
setDownloaded((prev) => prev && !isSameMedia(musicItem, musicItems));
}
};

Evt.on("MUSIC_DOWNLOADED", dlCb);
Evt.on("MUSIC_REMOVE_DOWNLOADED", rmCb);

return () => {
Evt.off("MUSIC_DOWNLOADED", dlCb);
Evt.off("MUSIC_REMOVE_DOWNLOADED", rmCb);
};
}, [musicItem]);
}
7 changes: 4 additions & 3 deletions src/renderer/core/downloader/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import * as Comlink from "comlink";
import { callPluginDelegateMethod } from "../plugin-delegate";
import { DownloadState, localPluginName } from "@/common/constant";
import PQueue from "p-queue";
import MusicSheet from "../music-sheet";
import { downloadingQueueStore } from "./store";
import throttle from "lodash.throttle";
import { addDownloadedMusicToList, isDownloaded, setupDownloadedMusicList } from "./downloaded-sheet";

type ProxyMarkedFunction<T extends (...args: any) => void> = T &
Comlink.ProxyMarked;
Expand All @@ -34,6 +34,7 @@ let downloaderWorker: IDownloaderWorker;

async function setupDownloader() {
setupDownloaderWorker();
setupDownloadedMusicList();
}

function forceUpdatePendingQueue() {
Expand Down Expand Up @@ -69,7 +70,7 @@ async function generateDownloadMusicTask(
const _musicItems = Array.isArray(musicItems) ? musicItems : [musicItems];
// 过滤掉已下载的
const _validMusicItems = _musicItems.filter(
(it) => !MusicSheet.isDownloadeed(it) && it.platform !== localPluginName
(it) => !isDownloaded(it) && it.platform !== localPluginName
);
// @ts-ignore
downloadingQueueStore.setValue((prev) => {
Expand Down Expand Up @@ -161,7 +162,7 @@ async function downloadMusic(
Comlink.proxy((dataState) => {
onStateChange(dataState);
if (dataState.state === DownloadState.DONE) {
MusicSheet.addDownloadedMusic(
addDownloadedMusicToList(
setInternalData<IMusic.IMusicItemInternalData>(
musicItem as any,
"downloadData",
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/core/events/types/common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,9 @@ declare namespace IEventType {
interface IEvents {
/** 路由导航 */
NAVIGATE: string;
// 音乐下载完成
MUSIC_DOWNLOADED: IMedia.IMediaBase | IMedia.IMediaBase[];
// 音乐被移除
MUSIC_REMOVE_DOWNLOADED: IMedia.IMediaBase | IMedia.IMediaBase[];
}
}
6 changes: 1 addition & 5 deletions src/renderer/core/music-sheet/internal/sheets-method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import defaultSheet from "./default-sheet";
import { getMediaPrimaryKey, isSameMedia } from "@/common/media-util";
import { useEffect, useState } from "react";
import { getUserPerferenceIDB, setUserPerferenceIDB } from "@/renderer/utils/user-perference";
import { setupDownloadedMusicList } from "./downloaded-sheet";

// 默认歌单,快速判定是否在列表中
const favoriteMusicListIds = new Set<string>();
Expand Down Expand Up @@ -44,7 +43,6 @@ export async function setupSheets() {
// 收藏歌单
const starredSheets = await getUserPerferenceIDB('starredMusicSheets');
starredSheetsStore.setValue(starredSheets ?? []);
await setupDownloadedMusicList();
} catch (e) {
console.log(e);
}
Expand Down Expand Up @@ -467,6 +465,4 @@ export async function unstarMusicSheet(sheet: IMedia.IMediaBase) {
const newSheets = starredSheetsStore.getValue().filter(item => !isSameMedia(item, sheet));
await setUserPerferenceIDB('starredMusicSheets', newSheets);
starredSheetsStore.setValue(newSheets);
}

export {addDownloadedMusic, removeDownloadedMusic, isDownloadeed} from './downloaded-sheet'
}
4 changes: 3 additions & 1 deletion src/renderer/core/shortcut/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ const shortCutKeysEvts: Record<IShortCutKeys, keyof IEventType.IEvents> = {

const baseShortCutFunction = (
evt: keyof IEventType.IEvents,
global: boolean
global: boolean,
originalEvt: KeyboardEvent
) => {
originalEvt.preventDefault();
if (global && rendererAppConfig.getAppConfigPath("shortCut.enableGlobal")) {
} else if (rendererAppConfig.getAppConfigPath("shortCut.enableLocal")) {
Evt.emit(evt);
Expand Down
2 changes: 2 additions & 0 deletions src/renderer/document/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import Evt from "../core/events";
import { ipcRendererInvoke } from "@/common/ipc-util/renderer";

import * as Comlink from 'comlink';
import Downloader from "../core/downloader";

setAutoFreeze(false);

Expand All @@ -29,6 +30,7 @@ export default async function () {
dropHandler();
clearDefaultBehavior();
setupEvents();
await Downloader.setupDownloader();

}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import MusicSheet from '@/renderer/core/music-sheet'
import React from 'react'

export default function Downloaded() {

// const downloadedMusic = MusicSheet.addDownloadedMusic



return (
<div>Downloaded</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import React from 'react'

export default function Downloading() {
return (
<div>Downloading</div>
)
}
13 changes: 13 additions & 0 deletions src/renderer/pages/main-page/views/download-view/index.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.download-view--container {
& .header {
font-weight: 600;
font-size: 1.5rem;
margin-top: 1.5rem;
margin-bottom: 1.2rem;
letter-spacing: 0.05rem;
user-select: none;
}


}

28 changes: 25 additions & 3 deletions src/renderer/pages/main-page/views/download-view/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
import React from 'react'
import { Tab } from "@headlessui/react";
import "./index.scss";
import Downloaded from "./components/Downloaded";
import Downloading from "./components/Downloading";

export default function DownloadView() {
return (
<div>Download</div>
)
<div className="download-view--container">
<Tab.Group>
<Tab.List className="tab-list-container">
<Tab as="div" className="tab-list-item">
已下载
</Tab>
<Tab as="div" className="tab-list-item">
下载中
</Tab>
</Tab.List>
<Tab.Panels className={"tab-panels-container"}>
<Tab.Panel className="tab-panel-container">
<Downloaded></Downloaded>
</Tab.Panel>
<Tab.Panel className="tab-panel-container">
<Downloading></Downloading>
</Tab.Panel>
</Tab.Panels>
</Tab.Group>
</div>
);
}
Loading

0 comments on commit af417a2

Please sign in to comment.