xref: /MusicFree/src/utils/mediaItem.ts (revision 6704747af84cebd842b258efac7143542722fac5)
1import {internalSerialzeKey, internalSymbolKey} from '@/constants/commonConst';
2import produce from 'immer';
3
4/** 获取mediakey */
5export function getMediaKey(mediaItem: ICommon.IMediaBase) {
6  return `${mediaItem.platform}@${mediaItem.id}`;
7}
8
9/** 解析mediakey */
10export function parseMediaKey(key: string): ICommon.IMediaBase {
11  try {
12    const str = JSON.parse(key.trim());
13    let platform, id;
14    if (typeof str === 'string') {
15      [platform, id] = str.split('@');
16    } else {
17      platform = str?.platform;
18      id = str?.id;
19    }
20    if(!platform || !id) {
21      throw new Error('mediakey不完整')
22    }
23    return {
24      platform,
25      id,
26    };
27  } catch (e: any) {
28    throw e;
29  }
30}
31
32/** 比较两歌media是否相同 */
33export function isSameMediaItem(
34  a: ICommon.IMediaBase | null | undefined,
35  b: ICommon.IMediaBase | null | undefined,
36) {
37  return a && b && a.id === b.id && a.platform === b.platform;
38}
39
40/** 获取复位的mediaItem */
41export function resetMediaItem<T extends ICommon.IMediaBase>(
42  mediaItem: T,
43  platform?: string,
44  newObj?: boolean,
45): T {
46  if (!newObj) {
47    mediaItem.platform = platform ?? mediaItem.platform;
48    mediaItem[internalSerialzeKey] = undefined;
49    return mediaItem;
50  } else {
51    return produce(mediaItem, _ => {
52      _.platform = platform ?? mediaItem.platform;
53      _[internalSerialzeKey] = undefined;
54    });
55  }
56}
57
58export function mergeProps(
59  mediaItem: ICommon.IMediaBase,
60  props: Record<string, any> | undefined,
61) {
62  return props
63    ? {
64        ...mediaItem,
65        ...props,
66      }
67    : mediaItem;
68}
69