Skip to content

Commit

Permalink
Closed #65, #86
Browse files Browse the repository at this point in the history
  • Loading branch information
mantou132 committed May 19, 2024
1 parent 7f035fe commit 83e2b99
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 27 deletions.
8 changes: 8 additions & 0 deletions public/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@
"description": "Lyrics use traditional chinese"
},

"optionsLyricsTransform": {
"message": "Lyrics transform"
},

"optionsLyricsTransformDetail": {
"message": "When using simplified Chinese, try to load the translated lyrics"
},

"optionsLyricsPosition": {
"message": "Where the lyrics show",
"description": "Lyrics position option"
Expand Down
8 changes: 8 additions & 0 deletions public/_locales/zh/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@
"message": "繁体中文歌词"
},

"optionsLyricsTransform": {
"message": "歌词转换"
},

"optionsLyricsTransformDetail": {
"message": "当使用简体中文时会尝试加载翻译的歌词"
},

"optionsLyricsPosition": {
"message": "歌词显示位置"
},
Expand Down
5 changes: 4 additions & 1 deletion src/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export enum ContextItems {
export const LyricsPositions = ['page', 'pip'] as const;
export const LyricsAlign = ['left', 'center'] as const;
export const LyricsFontFamily = ['CircularSp', 'Sans-Serif', 'Serif', 'Cursive'] as const;
export const LyricsTransform = ['Origin', 'Simplified', 'Traditional'] as const;
export interface Options {
cid: string;
'font-size': string;
Expand All @@ -48,8 +49,10 @@ export interface Options {
'use-unreviewed-lyrics': SwitchValue;
'show-on': (typeof LyricsPositions)[number];
'lyrics-align': (typeof LyricsAlign)[number];
/**@deprecated */
'traditional-chinese-lyrics': SwitchValue;
// Deprecated
'lyrics-transform': (typeof LyricsTransform)[number];
/**@deprecated */
'lyrics-smooth-scroll'?: SwitchValue;
'strict-mode'?: SwitchValue;
}
Expand Down
22 changes: 16 additions & 6 deletions src/options/app.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { customElement, refobject, RefObject } from '@mantou/gem/lib/decorators';
import { GemElement, html } from '@mantou/gem/lib/element';

import { Options, LyricsPositions, LyricsAlign, LyricsFontFamily } from '../common/constants';
import {
Options,
LyricsPositions,
LyricsAlign,
LyricsFontFamily,
LyricsTransform,
} from '../common/constants';
import { sendEvent, events } from '../common/ga';
import { theme } from '../common/theme';

Expand Down Expand Up @@ -131,11 +137,15 @@ export class OptionsApp extends GemElement<State> {
default-value=${options['clean-lyrics']}
></ele-switch>
</ele-form-item>
<ele-form-item label="${i18n.optionsTraditionalChineseLyrics()} *">
<ele-switch
name=${'traditional-chinese-lyrics' as keyof Options}
default-value=${options['traditional-chinese-lyrics']}
></ele-switch>
<ele-form-item
label="${i18n.optionsLyricsTransform()} *"
description=${i18n.optionsLyricsTransformDetail()}
>
<ele-select
name=${'lyrics-transform' as keyof Options}
default-value=${options['lyrics-transform']}
.options=${LyricsTransform.map((e) => ({ label: e, value: e }))}
></ele-select>
</ele-form-item>
<ele-form-item
?hidden=${!document.pictureInPictureEnabled}
Expand Down
1 change: 1 addition & 0 deletions src/options/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const defaultOptions: Options = {
'use-unreviewed-lyrics': 'on',
'toggle-shortcut': 'l',
'traditional-chinese-lyrics': uiLanguage === 'zh-TW' || uiLanguage === 'zh-HK' ? 'on' : 'off',
'lyrics-transform': 'Origin',
};

export async function getOptions() {
Expand Down
2 changes: 1 addition & 1 deletion src/page/lyrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('parse lyrics', () => {
expect(parseLyrics('[02:01]\n')).toEqual<Lyric>(null);
expect(parseLyrics('[02:01]编')).toEqual<Lyric>([{ startTime: 121, text: '编' }]);
expect(parseLyrics('[02:01]编:xx')).toEqual<Lyric>([{ startTime: 121, text: '编: xx' }]);
expect(parseLyrics('[02:01]编:', { useTChinese: true })).toEqual<Lyric>([
expect(parseLyrics('[02:01]编:', { lyricsTransform: 'Traditional' })).toEqual<Lyric>([
{ startTime: 121, text: '編:' },
]);
expect(parseLyrics('[02:01]编:', { cleanLyrics: true })).toEqual<Lyric>(null);
Expand Down
28 changes: 22 additions & 6 deletions src/page/lyrics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sify as toSimplified, tify as toTraditional } from 'chinese-conv';

import { isProd } from '../common/constants';
import { Options, isProd } from '../common/constants';

import { configPromise } from './config';
import { optionsPromise } from './options';
Expand Down Expand Up @@ -47,6 +47,9 @@ interface SongResult {
lrc?: {
lyric?: string;
};
tlyric?: {
lyric?: string;
};
}

// Convert all into English punctuation marks for processing
Expand Down Expand Up @@ -378,11 +381,12 @@ export async function matchingLyrics(

export async function fetchLyric(songId: number, fetchOptions?: RequestInit) {
const { API_HOST } = await configPromise;
const { lrc }: SongResult = await request(
const { lrc, tlyric }: SongResult = await request(
`${API_HOST}/lyric?${new URLSearchParams({ id: String(songId) })}`,
fetchOptions,
);
return lrc?.lyric || '';
const options = await optionsPromise;
return (options['lyrics-transform'] === 'Simplified' && tlyric?.lyric) || lrc?.lyric || '';
}

class Line {
Expand All @@ -399,7 +403,7 @@ export type Lyric = Line[] | null;

export interface ParseLyricsOptions {
cleanLyrics?: boolean;
useTChinese?: boolean;
lyricsTransform?: Options['lyrics-transform'];
keepPlainText?: boolean;
}

Expand Down Expand Up @@ -431,7 +435,7 @@ export function parseLyrics(lyricStr: string, options: ParseLyricsOptions = {})
if (textIndex > -1) {
text = matchResult.splice(textIndex, 1)[0];
text = capitalize(normalize(text, false));
text = toSimplified(text).replace(/\.|,|\?|!|;$/u, '');
text = text.replace(/\.|,|\?|!|;$/u, '');
}
if (!matchResult.length && options.keepPlainText) {
return [new Line(text)];
Expand All @@ -444,7 +448,19 @@ export function parseLyrics(lyricStr: string, options: ParseLyricsOptions = {})
if (!isNaN(min)) {
if (!options.cleanLyrics || !otherInfoRegexp.test(text)) {
result.startTime = min * 60 + sec;
result.text = options.useTChinese ? toTraditional(text) : text;
switch (options.lyricsTransform) {
case 'Simplified': {
result.text = toSimplified(text);
break;
}
case 'Traditional': {
result.text = toTraditional(text);
break;
}
default:
result.text = text;
break;
}
}
} else if (!options.cleanLyrics && key && value) {
result.text = `${key.toUpperCase()}: ${value}`;
Expand Down
31 changes: 18 additions & 13 deletions src/page/share-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class SharedData {
} else {
this._lyrics = parseLyrics(lyricsStr, {
cleanLyrics: options['clean-lyrics'] === 'on',
useTChinese: options['traditional-chinese-lyrics'] === 'on',
lyricsTransform: options['lyrics-transform'],
});
}
}
Expand Down Expand Up @@ -167,14 +167,17 @@ export class SharedData {
const options = await optionsPromise;
const parseLyricsOptions = {
cleanLyrics: options['clean-lyrics'] === 'on',
useTChinese: options['traditional-chinese-lyrics'] === 'on',
lyricsTransform: options['lyrics-transform'],
};
const { list, id } = await matchingLyrics(this.req, {
getAudioElement: () => audio,
fetchOptions,
});
const [{ list, id }, remoteData] = await Promise.all([
matchingLyrics(this.req, {
getAudioElement: () => audio,
fetchOptions,
}),
getSong(this.req, fetchOptions),
]);
if (id === 0 && (await this._restoreLyrics(true))) return;
this._list = list;
const remoteData = await getSong(this.req, fetchOptions);
const reviewed = options['use-unreviewed-lyrics'] === 'on' || remoteData?.reviewed;
const isSelf = remoteData?.user === options.cid;
if (isSelf && remoteData?.lyric) {
Expand Down Expand Up @@ -259,8 +262,7 @@ export class SharedData {
this._name = name;
this._artists = artists;
// case1: spotify metadata API call before of UI update
const succuss = await this._restoreCurrentTrackAndLyrics();
if (!succuss) {
if (!(await this._restoreLyrics())) {
await this._matching({ signal: this._abortController.signal });
}
} catch (e) {
Expand All @@ -276,23 +278,26 @@ export class SharedData {
if (getCache(info.name, info.artists)) return;
setCache(info);
// case2: spotify metadata API call after of UI update
// current behavior
if (this.name === info.name && this.artists === info.artists) {
const succuss = await this._restoreCurrentTrackAndLyrics();
if (succuss) {
if (await this._restoreLyrics()) {
this._cancelRequest();
}
}
}

private async _restoreCurrentTrackAndLyrics() {
private async _restoreLyrics(isForce = false) {
const cache = getCache(this.name, this.artists);
if (cache) {
this._duration = cache.duration;
if (cache.lyrics || cache.getLyrics) {
try {
const lyrics = cache.lyrics || (await (cache.promiseLyrics ||= cache.getLyrics?.()));
if (lyrics) {
this._lyrics = cache.lyrics = lyrics;
cache.lyrics = lyrics;
// 如果使用简体歌词,那么只更新缓存
if (!isForce && (await optionsPromise)['lyrics-transform'] === 'Simplified') return;
this._lyrics = lyrics;
return true;
}
} catch {
Expand Down

0 comments on commit 83e2b99

Please sign in to comment.