Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
".command": true,
".babelrc": true
},
"files.autoSave": "onFocusChange",
"prettier.singleQuote": true
"files.autoSave": "afterDelay",
"prettier.singleQuote": true,
"typescript.tsdk": "node_modules/typescript/lib"
}
5 changes: 0 additions & 5 deletions extension/src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,3 @@ export type OptionProps = {
en: boolean;
jp: boolean;
};

export interface BGWindow extends Window {
setOptions<K extends keyof OptionProps>(key: K, val: OptionProps[K]): void;
getOptions(): OptionProps;
}
21 changes: 9 additions & 12 deletions extension/src/background/main.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,18 @@
import { BackgroundAction } from '../shared/enums';
import { PageScriptAction } from '../shared/enums';
import getOptions from './options';
import notify from './notifics';
import { host } from '../fetch';
import Fetch from '../fetch';
import play from './player';

type Message = { action: PageScriptAction; data: any };

chrome.runtime.onMessage.addListener(
({ action, data }: Message, sender, sendRes) => {
({ action, data }: Message, _, sendRes: (worddata: any[]) => void) => {
const { on, jp } = getOptions();
if (!on) {
return false;
}
switch (action) {
case PageScriptAction.PLAY_SOUND:
play(data, data => {
chrome.tabs.sendMessage(sender.tab!.id!, {
action: BackgroundAction.PLAY_ERROR,
data,
});
});
return false;
case PageScriptAction.SEARCH_TEXT:
Fetch.search(data).then(worddata => {
if (!jp && data.lang === 'zh') {
Expand Down Expand Up @@ -51,7 +42,13 @@ chrome.runtime.onMessage.addListener(
case PageScriptAction.WORD_VIEWED:
return false;
default:
throw `Unknown action: ${action}`;
return false;
}
}
);

chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: [chrome.offscreen.Reason.AUDIO_PLAYBACK],
justification: 'play audio', // details for using the API
});
2 changes: 1 addition & 1 deletion extension/src/background/notifics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default (title: string, message: string, buttons: Button[] = []) => {
listeners[notificationId] = buttons.map(({ onClick }) => onClick);
}
chrome.notifications.create(notificationId, {
iconUrl: chrome.extension.getURL('enabled/icon32.png'),
iconUrl: chrome.runtime.getURL('enabled/icon32.png'),
buttons: buttons.map(({ title }) => ({ title })),
type: 'basic',
silent: true,
Expand Down
14 changes: 5 additions & 9 deletions extension/src/background/options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { BGWindow, OptionProps } from '.';

declare const window: BGWindow;
import { OptionProps } from '.';

let options: OptionProps = {
on: true,
Expand All @@ -19,22 +17,20 @@ const dIcons = {
const { icons: eIcons } = chrome.runtime.getManifest();

function setIcon(enabled: boolean) {
chrome.browserAction.setIcon({
chrome.action.setIcon({
path: enabled ? eIcons : dIcons,
});
}

chrome.browserAction.onClicked.addListener(() => {
window.setOptions('on', !options.on);
chrome.action.onClicked.addListener(() => {
setOptions('on', !options.on);
});

export default function getOptions() {
return options;
}

window.getOptions = getOptions;

window.setOptions = (key, val) => {
const setOptions = (key, val) => {
if (key === 'on') {
setIcon(val);
}
Expand Down
49 changes: 0 additions & 49 deletions extension/src/background/player.ts

This file was deleted.

23 changes: 10 additions & 13 deletions extension/src/content/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BackgroundData, Fetcher, Entry, Rect } from '../shared/types';
import { dePinv, dePron, deJyut } from './decoder';
import { Fetcher, Entry, Rect } from '../shared/types';
import { DICTDOM, ensureDomAttached } from './dictdom';
import { dePinv, dePron, deJyut } from './decoder';
import postitle from '../shared/postitle';
import SECRET from '../shared/common';
import cookup from './cookup';
Expand Down Expand Up @@ -216,9 +216,14 @@ export default function(fetcher: Fetcher) {
: '粤语';
button.addEventListener('mouseup', event => {
event.stopPropagation();
fetcher.playme({
code: button.dataset.code!,
});
fetcher
.playme({
code: button.dataset.code!,
})
.catch(() => {
button.setAttribute('disabled', 'disabled');
button.setAttribute('title', '播放失败');
});
});
button.setAttribute('title', `播放${mark} » [${button.innerText}]`);
});
Expand Down Expand Up @@ -405,13 +410,5 @@ export default function(fetcher: Fetcher) {
return {
hideDict,
tryToShowDict,
onPlayError({ code }: BackgroundData.OnPlayError) {
for (const target of View.querySelectorAll(`[data-code="${code}"]`)) {
if (target) {
target.setAttribute('disabled', 'disabled');
target.setAttribute('title', '播放失败');
}
}
},
};
}
21 changes: 10 additions & 11 deletions extension/src/content/main.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { PageScriptAction, BackgroundAction } from '../shared/enums';
import trigger from './trigger';

type Message = { action: BackgroundAction; data: any };

const { onPlayError } = trigger({
trigger({
playme(data) {
const action = PageScriptAction.PLAY_SOUND;
chrome.runtime.sendMessage({ action, data });
return chrome.runtime
.sendMessage({ action, data })
.then(({ action, data }: Message) => {
if (action === BackgroundAction.PLAY_ERROR) {
throw new Error();
}
});
},
search(data) {
const action = PageScriptAction.SEARCH_TEXT;
return new Promise(resolve =>
chrome.runtime.sendMessage({ action, data }, resolve)
);
return chrome.runtime.sendMessage({ action, data });
},
define(data) {
const action = PageScriptAction.DEFINE_WORD;
Expand All @@ -22,9 +27,3 @@ const { onPlayError } = trigger({
chrome.runtime.sendMessage({ action, data });
},
});

chrome.runtime.onMessage.addListener(({ action, data }: Message) => {
if (action === BackgroundAction.PLAY_ERROR) {
onPlayError(data);
}
});
3 changes: 1 addition & 2 deletions extension/src/content/trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { shorten, staticText } from './utility';
import handler from './handler';

export default function(fetcher: Fetcher) {
const { tryToShowDict, hideDict, onPlayError } = handler(fetcher);
const { tryToShowDict, hideDict } = handler(fetcher);
let mousedownTargetIsNotLanxEdit = true;
let mouseupEnabled = true;
let dictEnabled = true;
Expand Down Expand Up @@ -65,7 +65,6 @@ export default function(fetcher: Fetcher) {
});

return {
onPlayError,
toggleDictEnabled() {
return (dictEnabled = !dictEnabled);
},
Expand Down
15 changes: 5 additions & 10 deletions extension/src/copy/manifest.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
{
"manifest_version": 2,
"manifest_version": 3,
"name": "__MSG_name__",
"description": "__MSG_description__",
"version": "1.2.0",
"author": "李鸿章<paindo@163.com>",
"default_locale": "en",
"browser_action": {
"action": {
"default_icon": "static/icon19.png"
},
"background": {
"page": "background.html"
"service_worker": "background.js"
},
"permissions": [
"notifications",
"https://*/*",
"http://*/*",
"<all_urls>",
"tabs"
],
"host_permissions": ["https://*/*", "http://*/*", "<all_urls>"],
"permissions": ["notifications", "offscreen", "tabs"],
"icons": {
"16": "enabled/icon16.png",
"32": "enabled/icon32.png",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="background.js"></script>
<script type="text/javascript" src="offscreen.js"></script>
</head>
</html>
File renamed without changes.
19 changes: 19 additions & 0 deletions extension/src/offscreen/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { PageScriptAction } from '../shared/enums';
import play from './player';

type Message = { action: PageScriptAction; data: any };

chrome.runtime.onMessage.addListener(
({ action, data }: Message, _, sendRes) => {
if (action === PageScriptAction.PLAY_SOUND) {
play(data).then(action =>
sendRes({
action,
data,
})
);
return true;
}
return false;
}
);
55 changes: 55 additions & 0 deletions extension/src/offscreen/player.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { PageScriptData } from '../shared/types';
import { BackgroundAction } from '../shared/enums';

import { Cache } from './cache';
import { host } from '../fetch';

const URLXD = {
zh: [`${host}/static/pron/zh/`, `.ogg`],
uk: [`${host}/static/pron/uk/`, `.mp3`],
us: [`${host}/static/pron/us/`, `.mp3`],
jp: [`${host}/static/pron/jp/`, `.wav`],
};

const cache = new Cache<HTMLAudioElement>(128);
/**
* `code` formats:
*
* 1. `zh:pin1`
* 2. `uk:C7IZLO-RJ`
* 3. `us:F7I-NLO-KJ`
* 3. `jp:sik6`
*
* `onerror` when playing failed.
*/
export default function play({ code }: PageScriptData.Playme) {
return new Promise<BackgroundAction>(resolve => {
const oldAudio = cache.get(code);
if (oldAudio) {
if (!oldAudio.getAttribute('disabled')) {
oldAudio.play();
resolve(BackgroundAction.PLAY_OKAY);
} else {
resolve(BackgroundAction.PLAY_ERROR);
}
} else {
const [lang, file] = code.split(':');
if (URLXD[lang]) {
const newAudio = document.createElement('audio');
cache.add(code, newAudio);
newAudio.preload = 'auto';
newAudio.autoplay = true;
const [dir, ext] = URLXD[lang];
newAudio.src = dir + file + ext;
newAudio.onerror = (event: ErrorEvent) => {
event.stopPropagation();
newAudio.setAttribute('disabled', 'disabled');
resolve(BackgroundAction.PLAY_ERROR);
};
newAudio.oncanplay = () => {
resolve(BackgroundAction.PLAY_OKAY);
};
}
}
});
}
11 changes: 1 addition & 10 deletions extension/src/shared/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,5 @@ export const enum PageScriptAction {
// Note: set `string` initializers using as `string` key as well.
export const enum BackgroundAction {
PLAY_ERROR = 'PLAY_ERROR',
}

/** 语言代号,用于请求_查词接口_等 */
export const enum LanguageCode {
/** 汉语代号 */
ZH = 'zh',
/** 英语代号 */
EN = 'en',
/** 粤语代号 */
JP = 'jp',
PLAY_OKAY = 'PLAY_OKAY',
}
Loading