hash
stringlengths
40
40
date
stringdate
2018-01-15 01:43:19
2024-04-02 15:49:23
author
stringclasses
18 values
commit_message
stringlengths
10
72
is_merge
bool
1 class
git_diff
stringlengths
132
6.87M
type
stringclasses
11 values
masked_commit_message
stringlengths
4
58
2ec91ef7cf61856e5d1a9e3bc60b4b1e4f5ad1ab
2019-10-25 02:44:01
crimx
feat(dicts): add mojidict
false
diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index 5bf15295e..d96781df2 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -16,6 +16,7 @@ import jukuu from '@/components/dictionaries/jukuu/config' import liangan from '@/components/dictionaries/liangan/config' import longman from '@/components/dictionaries/longman/config' import macmillan from '@/components/dictionaries/macmillan/config' +import mojidict from '@/components/dictionaries/mojidict/config' import naver from '@/components/dictionaries/naver/config' import oald from '@/components/dictionaries/oald/config' import shanbay from '@/components/dictionaries/shanbay/config' @@ -51,6 +52,7 @@ export function getAllDicts() { liangan: liangan(), longman: longman(), macmillan: macmillan(), + mojidict: mojidict(), naver: naver(), oald: oald(), shanbay: shanbay(), diff --git a/src/app-config/profiles.ts b/src/app-config/profiles.ts index 320e774e0..86fc344fe 100644 --- a/src/app-config/profiles.ts +++ b/src/app-config/profiles.ts @@ -215,6 +215,7 @@ export function nihongo(): ProfileStorage { const profile = getDefaultProfile(idItem.id) as ProfileMutable profile.dicts.selected = [ + 'mojidict', 'hjdict', 'weblioejje', 'weblio', diff --git a/src/components/dictionaries/mojidict/View.tsx b/src/components/dictionaries/mojidict/View.tsx new file mode 100644 index 000000000..a735f714b --- /dev/null +++ b/src/components/dictionaries/mojidict/View.tsx @@ -0,0 +1,49 @@ +import React, { FC } from 'react' +import Speaker from '@/components/Speaker' +import EntryBox from '@/components/EntryBox' +import { MojidictResult } from './engine' +import { ViewPorps } from '@/components/dictionaries/helpers' + +export const DictMojidict: FC<ViewPorps<MojidictResult>> = ({ result }) => ( + <> + {result.word && ( + <div> + <h1>{result.word.spell}</h1> + <span>{result.word.pron}</span> <Speaker src={result.word.tts} /> + </div> + )} + {result.details && + result.details.map(detail => ( + <EntryBox key={detail.title} title={detail.title}> + {detail.subdetails && ( + <ul className="dictMojidict-Subdetails"> + {detail.subdetails.map(subdetail => ( + <li + key={subdetail.title} + className="dictMojidict-Subdetails_Item" + > + <p>{subdetail.title}</p> + {subdetail.examples && ( + <ul className="dictMojidict-Examples"> + {subdetail.examples.map(example => ( + <li key={example.title}> + <p className="dictMojidict-Examples_Title"> + {example.title} + </p> + <p className="dictMojidict-Examples_Trans"> + {example.trans} + </p> + </li> + ))} + </ul> + )} + </li> + ))} + </ul> + )} + </EntryBox> + ))} + </> +) + +export default DictMojidict diff --git a/src/components/dictionaries/mojidict/_locales.json b/src/components/dictionaries/mojidict/_locales.json new file mode 100644 index 000000000..60e89c3ca --- /dev/null +++ b/src/components/dictionaries/mojidict/_locales.json @@ -0,0 +1,7 @@ +{ + "name": { + "en": "MOJi辞書", + "zh-CN": "MOJi辞書", + "zh-TW": "MOJi辞書" + } +} diff --git a/src/components/dictionaries/mojidict/_style.shadow.scss b/src/components/dictionaries/mojidict/_style.shadow.scss new file mode 100644 index 000000000..39b1c5093 --- /dev/null +++ b/src/components/dictionaries/mojidict/_style.shadow.scss @@ -0,0 +1,21 @@ +.dictMojidict-Subdetails { + padding-left: 1em; +} + +.dictMojidict-Subdetails_Item { + list-style-type: disc; +} + +.dictMojidict-Examples { + padding-left: 0.5em; +} + +.dictMojidict-Examples_Title { + margin-bottom: 0; +} + +.dictMojidict-Examples_Trans { + margin-top: 0; + padding-left: 0.5em; + font-size: 0.9em; +} diff --git a/src/components/dictionaries/mojidict/config.ts b/src/components/dictionaries/mojidict/config.ts new file mode 100644 index 000000000..1ac97047d --- /dev/null +++ b/src/components/dictionaries/mojidict/config.ts @@ -0,0 +1,34 @@ +import { DictItem } from '@/app-config/dicts' + +export type LianganConfig = DictItem + +export default (): LianganConfig => ({ + lang: '10010000', + selectionLang: { + english: false, + chinese: true, + japanese: true, + korean: false, + french: false, + spanish: false, + deutsch: false, + others: false, + matchAll: false + }, + defaultUnfold: { + english: true, + chinese: true, + japanese: true, + korean: true, + french: true, + spanish: true, + deutsch: true, + others: true, + matchAll: false + }, + preferredHeight: 265, + selectionWC: { + min: 1, + max: 5 + } +}) diff --git a/src/components/dictionaries/mojidict/engine.ts b/src/components/dictionaries/mojidict/engine.ts new file mode 100644 index 000000000..e80d85d23 --- /dev/null +++ b/src/components/dictionaries/mojidict/engine.ts @@ -0,0 +1,175 @@ +import { + SearchFunction, + GetSrcPageFunction, + handleNoResult, + handleNetWorkError +} from '../helpers' +import axios from 'axios' + +const APPLICATION_ID = 'E62VyFVLMiW7kvbtVq3p' + +export const getSrcPage: GetSrcPageFunction = async text => { + return `https://www.mojidict.com/details/${await getTarId(text)}` +} + +interface FetchWordResult { + details?: Array<{ + objectId: string + title: string + wordId: string + }> + examples?: Array<{ + objectId: string + subdetailsId: string + title: string + trans: string + wordId: string + }> + subdetails?: Array<{ + detailsId: string + objectId: string + title: string + wordId: string + }> + word?: { + accent: string + objectId: string + pron: string + spell: string + tts: string + } +} + +export interface MojidictResult { + word?: { + spell: string + pron: string + tts: string + } + details?: Array<{ + title: string + subdetails?: Array<{ + title: string + examples?: Array<{ + title: string + trans: string + }> + }> + }> +} + +export const search: SearchFunction<MojidictResult> = async ( + text, + config, + profile, + payload +) => { + const response = await axios({ + method: 'post', + url: 'https://api.mojidict.com/parse/functions/fetchWord_v2', + data: { + wordId: await getTarId(text), + _ApplicationId: APPLICATION_ID, + _ClientVersion: 'js2.7.1', + _InstallationId: getInstallationId() + } + }) + + const result: FetchWordResult = response.data.result + + if (result && (result.details || result.word)) { + let word: MojidictResult['word'] + if (result.word) { + word = { + spell: result.word.spell, + pron: `${result.word.pron || ''} ${result.word.accent || ''}`, + tts: await getTTS(result.word.spell, result.word.objectId) + } + } + + let details: MojidictResult['details'] + if (result.details) { + details = result.details.map(detail => ({ + title: detail.title, + subdetails: + result.subdetails && + result.subdetails + .filter(subdetail => subdetail.detailsId === detail.objectId) + .map(subdetail => ({ + title: subdetail.title, + examples: + result.examples && + result.examples.filter( + example => example.subdetailsId === subdetail.objectId + ) + })) + })) + } + + return word && word.tts + ? { result: { word, details }, audio: { py: word.tts } } + : { result: { word, details } } + } + + return handleNoResult() +} + +async function getTarId(text: string): Promise<string> { + try { + const { data } = await axios({ + method: 'post', + url: 'https://api.mojidict.com/parse/functions/search_v2', + data: { + needWords: true, + searchText: text, + _ApplicationId: APPLICATION_ID, + _ClientVersion: 'js2.7.1', + _InstallationId: getInstallationId() + } + }) + + if ( + data.result && + data.result.searchResults && + data.result.searchResults[0] && + data.result.searchResults[0].tarId + ) { + return String(data.result.searchResults[0].tarId) + } + + return handleNoResult() + } catch (e) { + return handleNetWorkError() + } +} + +async function getTTS(text: string, wordId: string): Promise<string> { + try { + const { data } = await axios({ + method: 'post', + url: 'https://api.mojidict.com/parse/functions/fetchTts', + data: { + identity: wordId, + text, + _ApplicationId: APPLICATION_ID, + _ClientVersion: 'js2.7.1', + _InstallationId: getInstallationId() + } + }) + + if (data.result && data.result.url) { + return data.result.url + } + } catch (e) {} + return '' +} + +function getInstallationId() { + return s() + s() + '-' + s() + '-' + s() + '-' + s() + '-' + s() + s() + s() +} + +function s() { + return Math.floor(65536 * (1 + Math.random())) + .toString(16) + .substring(1) +} diff --git a/src/components/dictionaries/mojidict/favicon.png b/src/components/dictionaries/mojidict/favicon.png new file mode 100644 index 000000000..a9579a2e4 Binary files /dev/null and b/src/components/dictionaries/mojidict/favicon.png differ diff --git a/test/specs/components/dictionaries/mojidict/requests.mock.ts b/test/specs/components/dictionaries/mojidict/requests.mock.ts new file mode 100644 index 000000000..bfbb10b92 --- /dev/null +++ b/test/specs/components/dictionaries/mojidict/requests.mock.ts @@ -0,0 +1,13 @@ +import { MockRequest } from '@/components/dictionaries/helpers' + +export const mockSearchTexts = ['心'] + +export const mockRequest: MockRequest = mock => { + mock + .onPost(/mojidict.*fetchWord_v2/) + .reply(200, require(`./response/心/fetchWord_v2.json`)) + .onPost(/mojidict.*search_v2/) + .reply(200, require(`./response/心/search_v2.json`)) + .onPost(/mojidict.*fetchTts/) + .reply(200, require(`./response/心/fetchTts.json`)) +} diff --git "a/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchTts.json" "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchTts.json" new file mode 100644 index 000000000..652ae6bdf --- /dev/null +++ "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchTts.json" @@ -0,0 +1,9 @@ +{ + "result": { + "text": "心", + "url": "https://mojidict.oss-cn-hangzhou.aliyuncs.com/tts/198970803.wav?OSSAccessKeyId=LTAIiHqFUbjEEfqf&Expires=1571950630&Signature=dJWzgjDxgjuQnGcsIMsaiY0KwS4%3D", + "identity": "198970803", + "existed": true, + "msg": "success" + } +} diff --git "a/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchWord_v2.json" "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchWord_v2.json" new file mode 100644 index 000000000..5b089752c --- /dev/null +++ "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/fetchWord_v2.json" @@ -0,0 +1,467 @@ +{ + "result": { + "word": { + "excerpt": "[名·惯用语] 心,心里。(気持ち。) 心地,心田,心肠;居心;心术。(心根;おもわく;心に思うところ。) ", + "spell": "心", + "accent": "③②", + "pron": "こころ", + "romaji": "kokoro", + "createdAt": "2019-05-07T03:50:30.605Z", + "updatedAt": "2019-10-24T12:50:35.172Z", + "converted": true, + "objectId": "198970803" + }, + "details": [ + { + "title": "名", + "index": 0, + "createdAt": "2019-05-07T03:50:32.667Z", + "updatedAt": "2019-10-24T12:55:11.498Z", + "wordId": "198970803", + "converted": true, + "objectId": "59038" + }, + { + "title": "惯用语", + "index": 1, + "createdAt": "2019-05-07T03:50:32.707Z", + "updatedAt": "2019-10-24T12:55:11.549Z", + "wordId": "198970803", + "converted": true, + "objectId": "59039" + } + ], + "subdetails": [ + { + "title": "心,心里。(気持ち。)", + "index": 0, + "createdAt": "2019-05-07T03:50:33.623Z", + "updatedAt": "2019-10-24T13:01:12.316Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82233" + }, + { + "title": "心内にあれば色外に現る。/诚于中,形于外。", + "index": 0, + "createdAt": "2019-05-07T03:50:34.380Z", + "updatedAt": "2019-10-24T13:01:13.401Z", + "wordId": "198970803", + "detailsId": "59039", + "converted": true, + "objectId": "82244" + }, + { + "title": "心地,心田,心肠;居心;心术。(心根;おもわく;心に思うところ。)", + "index": 1, + "createdAt": "2019-05-07T03:50:34.800Z", + "updatedAt": "2019-10-24T13:01:20.535Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82234" + }, + { + "title": "度量,心胸,胸怀,气度。(度量。)", + "index": 2, + "createdAt": "2019-05-07T03:50:34.727Z", + "updatedAt": "2019-10-24T13:01:20.505Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82235" + }, + { + "title": "精神;灵魂,心灵。(精神;霊魂。)", + "index": 3, + "createdAt": "2019-05-07T03:50:34.322Z", + "updatedAt": "2019-10-24T13:01:13.284Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82236" + }, + { + "title": "心情,心绪,情绪。(心情。)", + "index": 4, + "createdAt": "2019-05-07T03:50:34.037Z", + "updatedAt": "2019-10-24T13:01:12.917Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82237" + }, + { + "title": "衷心,内心。(まごころ。)", + "index": 5, + "createdAt": "2019-05-07T03:50:33.856Z", + "updatedAt": "2019-10-24T13:01:12.630Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82238" + }, + { + "title": "心思,想法;念头。(考え;多く悪い考え。)", + "index": 6, + "createdAt": "2019-05-07T03:50:34.718Z", + "updatedAt": "2019-10-24T13:01:13.804Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82239" + }, + { + "title": "意志;心愿;意图;打算。(意志;希望;意図;心づもり。)", + "index": 7, + "createdAt": "2019-05-07T03:50:34.577Z", + "updatedAt": "2019-10-24T13:01:13.617Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82240" + }, + { + "title": "兴致,情趣;爱好。(興味;好み。)", + "index": 8, + "createdAt": "2019-05-07T03:50:33.823Z", + "updatedAt": "2019-10-24T13:01:12.581Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82241" + }, + { + "title": "意义,含意,意境。(芸術作品などの意義。)", + "index": 9, + "createdAt": "2019-05-07T03:50:33.508Z", + "updatedAt": "2019-10-24T13:01:12.167Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82242" + }, + { + "title": "感情;关怀。(なさけ。)", + "index": 10, + "createdAt": "2019-05-07T03:50:34.365Z", + "updatedAt": "2019-10-24T13:01:13.372Z", + "wordId": "198970803", + "detailsId": "59038", + "converted": true, + "objectId": "82243" + } + ], + "examples": [ + { + "title": "歌の心。", + "index": 0, + "trans": "和歌的主题思想。", + "createdAt": "2019-05-07T03:50:35.885Z", + "updatedAt": "2019-10-24T13:08:15.370Z", + "wordId": "198970803", + "subdetailsId": "82242", + "converted": true, + "objectId": "59923" + }, + { + "title": "心のままにふるまう。", + "index": 0, + "trans": "想怎样就怎样;任性。", + "createdAt": "2019-05-07T03:50:36.090Z", + "updatedAt": "2019-10-24T13:08:15.523Z", + "wordId": "198970803", + "subdetailsId": "82239", + "converted": true, + "objectId": "59916" + }, + { + "title": "悲しみで心が乱れる。", + "index": 0, + "trans": "悲伤得心烦意乱。", + "createdAt": "2019-05-07T03:50:36.189Z", + "updatedAt": "2019-10-24T13:08:15.607Z", + "wordId": "198970803", + "subdetailsId": "82237", + "converted": true, + "objectId": "59909" + }, + { + "title": "心が大きい。", + "index": 0, + "trans": "心胸宽;度量大。", + "createdAt": "2019-05-07T03:50:36.249Z", + "updatedAt": "2019-10-24T13:08:15.669Z", + "wordId": "198970803", + "subdetailsId": "82235", + "converted": true, + "objectId": "59905" + }, + { + "title": "温かい心。", + "index": 0, + "trans": "温暖的心;热情。", + "createdAt": "2019-05-07T03:50:36.313Z", + "updatedAt": "2019-10-24T13:08:23.225Z", + "wordId": "198970803", + "subdetailsId": "82233", + "converted": true, + "objectId": "59899" + }, + { + "title": "これが一番わたしの心にかなった品だ", + "index": 0, + "trans": "这是最合我意的东西。", + "createdAt": "2019-05-07T03:50:36.570Z", + "updatedAt": "2019-10-24T13:08:23.486Z", + "wordId": "198970803", + "subdetailsId": "82241", + "converted": true, + "objectId": "59922" + }, + { + "title": "心ないしうち。", + "index": 0, + "trans": "不通人情的作法。", + "createdAt": "2019-05-07T03:50:36.640Z", + "updatedAt": "2019-10-24T13:08:23.555Z", + "wordId": "198970803", + "subdetailsId": "82243", + "converted": true, + "objectId": "59926" + }, + { + "title": "心の糧。", + "index": 0, + "trans": "精神食粮。", + "createdAt": "2019-05-07T03:50:37.067Z", + "updatedAt": "2019-10-24T13:08:23.846Z", + "wordId": "198970803", + "subdetailsId": "82236", + "converted": true, + "objectId": "59907" + }, + { + "title": "心の優しい人。", + "index": 0, + "trans": "心肠好的人。", + "createdAt": "2019-05-07T03:50:37.107Z", + "updatedAt": "2019-10-24T13:08:23.846Z", + "wordId": "198970803", + "subdetailsId": "82234", + "converted": true, + "objectId": "59903" + }, + { + "title": "心を決める。", + "index": 0, + "trans": "下决心。", + "createdAt": "2019-05-07T03:50:37.337Z", + "updatedAt": "2019-10-24T13:08:24.135Z", + "wordId": "198970803", + "subdetailsId": "82240", + "converted": true, + "objectId": "59919" + }, + { + "title": "心を打ち明ける。", + "index": 0, + "trans": "吐露衷曲zhongqu;表明心迹。", + "createdAt": "2019-05-07T03:50:37.456Z", + "updatedAt": "2019-10-24T13:08:24.256Z", + "wordId": "198970803", + "subdetailsId": "82238", + "converted": true, + "objectId": "59912" + }, + { + "title": "人の心をうごかす。", + "index": 1, + "trans": "感动人;激动人心。", + "createdAt": "2019-05-07T03:50:35.868Z", + "updatedAt": "2019-10-24T13:08:15.349Z", + "wordId": "198970803", + "subdetailsId": "82237", + "converted": true, + "objectId": "59910" + }, + { + "title": "心から感謝する。", + "index": 1, + "trans": "从心里表示感谢;衷心感谢;由衷感谢。", + "createdAt": "2019-05-07T03:50:35.901Z", + "updatedAt": "2019-10-24T13:08:15.408Z", + "wordId": "198970803", + "subdetailsId": "82238", + "converted": true, + "objectId": "59913" + }, + { + "title": "これは彼の心から出たものではない。", + "index": 1, + "trans": "这不是出自他的心愿。", + "createdAt": "2019-05-07T03:50:36.313Z", + "updatedAt": "2019-10-24T13:08:15.700Z", + "wordId": "198970803", + "subdetailsId": "82240", + "converted": true, + "objectId": "59920" + }, + { + "title": "詩の心。", + "index": 1, + "trans": "诗的意境。", + "createdAt": "2019-05-07T03:50:36.417Z", + "updatedAt": "2019-10-24T13:08:23.299Z", + "wordId": "198970803", + "subdetailsId": "82242", + "converted": true, + "objectId": "59924" + }, + { + "title": "君の心はわかっていた。", + "index": 1, + "trans": "我早已明白你的心思。", + "createdAt": "2019-05-07T03:50:36.427Z", + "updatedAt": "2019-10-24T13:08:23.305Z", + "wordId": "198970803", + "subdetailsId": "82239", + "converted": true, + "objectId": "59917" + }, + { + "title": "心があせる。", + "index": 1, + "trans": "心慌;着急。", + "createdAt": "2019-05-07T03:50:36.513Z", + "updatedAt": "2019-10-24T13:08:23.376Z", + "wordId": "198970803", + "subdetailsId": "82233", + "converted": true, + "objectId": "59900" + }, + { + "title": "心はいたってよい男だ。", + "index": 1, + "trans": "是个心田极其善良的人。", + "createdAt": "2019-05-07T03:50:36.753Z", + "updatedAt": "2019-10-24T13:08:23.640Z", + "wordId": "198970803", + "subdetailsId": "82234", + "converted": true, + "objectId": "59904" + }, + { + "title": "心をひとつにする。", + "index": 1, + "trans": "一条心;同心协力。", + "createdAt": "2019-05-07T03:50:36.933Z", + "updatedAt": "2019-10-24T13:08:23.697Z", + "wordId": "198970803", + "subdetailsId": "82236", + "converted": true, + "objectId": "59908" + }, + { + "title": "心が小さい。", + "index": 1, + "trans": "心胸窄zhai;度量小。", + "createdAt": "2019-05-07T03:50:37.185Z", + "updatedAt": "2019-10-24T13:08:23.984Z", + "wordId": "198970803", + "subdetailsId": "82235", + "converted": true, + "objectId": "59906" + }, + { + "title": "心ひそかに考える。", + "index": 2, + "trans": "心中暗想。", + "createdAt": "2019-05-07T03:50:35.822Z", + "updatedAt": "2019-10-24T13:08:15.330Z", + "wordId": "198970803", + "subdetailsId": "82238", + "converted": true, + "objectId": "59914" + }, + { + "title": "わたしにはあの人の心がわからない。", + "index": 2, + "trans": "我不了解那个人的心理。", + "createdAt": "2019-05-07T03:50:36.202Z", + "updatedAt": "2019-10-24T13:08:15.638Z", + "wordId": "198970803", + "subdetailsId": "82239", + "converted": true, + "objectId": "59918" + }, + { + "title": "その知らせを聞いてわたしはひどく心を痛めた。", + "index": 2, + "trans": "听了那个消息使我非常痛心。", + "createdAt": "2019-05-07T03:50:36.204Z", + "updatedAt": "2019-10-24T13:08:15.658Z", + "wordId": "198970803", + "subdetailsId": "82237", + "converted": true, + "objectId": "59911" + }, + { + "title": "絵心。", + "index": 2, + "trans": "画意;绘画欣赏力。", + "createdAt": "2019-05-07T03:50:36.734Z", + "updatedAt": "2019-10-24T13:08:23.621Z", + "wordId": "198970803", + "subdetailsId": "82242", + "converted": true, + "objectId": "59925" + }, + { + "title": "心に留める。", + "index": 2, + "trans": "放在心上;介意;记在心里;记住。", + "createdAt": "2019-05-07T03:50:37.128Z", + "updatedAt": "2019-10-24T13:08:23.899Z", + "wordId": "198970803", + "subdetailsId": "82233", + "converted": true, + "objectId": "59901" + }, + { + "title": "わたしの心がおわかりでしょう。", + "index": 2, + "trans": "你明白我的意图了吧。", + "createdAt": "2019-05-07T03:50:37.337Z", + "updatedAt": "2019-10-24T13:08:24.128Z", + "wordId": "198970803", + "subdetailsId": "82240", + "converted": true, + "objectId": "59921" + }, + { + "title": "心を落ち着ける。", + "index": 3, + "trans": "沉下心去;镇静。", + "createdAt": "2019-05-07T03:50:36.417Z", + "updatedAt": "2019-10-24T13:08:23.292Z", + "wordId": "198970803", + "subdetailsId": "82233", + "converted": true, + "objectId": "59902" + }, + { + "title": "心をこめた贈り物。", + "index": 3, + "trans": "真诚的礼物。", + "createdAt": "2019-05-07T03:50:37.128Z", + "updatedAt": "2019-10-24T13:08:23.893Z", + "wordId": "198970803", + "subdetailsId": "82238", + "converted": true, + "objectId": "59915" + } + ] + } +} diff --git "a/test/specs/components/dictionaries/mojidict/response/\345\277\203/search_v2.json" "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/search_v2.json" new file mode 100644 index 000000000..f88193bbc --- /dev/null +++ "b/test/specs/components/dictionaries/mojidict/response/\345\277\203/search_v2.json" @@ -0,0 +1,30 @@ +{ + "result": { + "originalSearchText": "心", + "searchResults": [ + { + "searchText": "心", + "count": 1011, + "tarId": "198970803", + "title": "", + "type": 0, + "createdAt": "2019-05-07T03:29:26.749Z", + "updatedAt": "2019-05-07T03:29:26.749Z", + "objectId": "RMWk8WCsp2" + } + ], + "words": [ + { + "excerpt": "[名·惯用语] 心,心里。(気持ち。) 心地,心田,心肠;居心;心术。(心根;おもわく;心に思うところ。) ", + "spell": "心", + "accent": "③②", + "pron": "こころ", + "romaji": "kokoro", + "createdAt": "2019-05-07T03:50:30.605Z", + "updatedAt": "2019-10-24T12:50:35.172Z", + "converted": true, + "objectId": "198970803" + } + ] + } +}
feat
add mojidict
fe75c7a6c9431aeeaa63138b4fd1c1eff153124f
2020-08-30 22:44:26
crimx
feat: add Lingocloud trs
false
diff --git a/.neutrinorc.js b/.neutrinorc.js index 301e8c15f..15c8ad516 100644 --- a/.neutrinorc.js +++ b/.neutrinorc.js @@ -187,6 +187,13 @@ module.exports = { from: '+(antd|antd.dark).min.css', to: 'assets/', toType: 'dir' + }, + // caiyunapp + { + context: 'node_modules/trsjs/build/sala', + from: 'trs.js', + to: 'assets/', + toType: 'dir' } ] }), diff --git a/package.json b/package.json index 81e5732e2..e09871ca2 100644 --- a/package.json +++ b/package.json @@ -173,6 +173,7 @@ "storybook-addon-jsx": "7.1.15", "storybook-addon-react-docgen": "1.2.32", "to-string-loader": "^1.1.5", + "trsjs": "caiyunapp/trs.js", "typescript": "^3.8.2", "webpack": "^4", "webpack-bundle-analyzer": "^3.5.2", diff --git a/src/_locales/en/menus.ts b/src/_locales/en/menus.ts index 08f6120e6..a2d09fc40 100644 --- a/src/_locales/en/menus.ts +++ b/src/_locales/en/menus.ts @@ -5,6 +5,7 @@ export const locale: typeof _locale = { baidu_search: 'Baidu Search', bing_dict: 'Bing Dict', bing_search: 'Bing Search', + caiyuntrs: 'Lingocloud Page Translate', cambridge: 'Cambridge', copy_pdf_url: 'Copy PDF URL to Clipboard', dictcn: 'Dictcn', @@ -24,7 +25,7 @@ export const locale: typeof _locale = { microsoft_page_translate: 'Microsoft Page Translate', notebook_title: 'New Word List', notification_youdao_err: - 'Youdao Page Translation 2.0 not responding.\nSaladict might not have permission to access this page.\nIgnore this message if Youdao panal is shown.', + 'Youdao Page Translate 2.0 not responding.\nSaladict might not have permission to access this page.\nIgnore this message if Youdao panal is shown.', oxford: 'Oxford', page_translations: 'Page Translations', saladict: 'Saladict', diff --git a/src/_locales/zh-CN/menus.ts b/src/_locales/zh-CN/menus.ts index 083e82b7d..03f6168a7 100644 --- a/src/_locales/zh-CN/menus.ts +++ b/src/_locales/zh-CN/menus.ts @@ -3,6 +3,7 @@ export const locale = { baidu_search: '百度搜索', bing_dict: '必应词典', bing_search: '必应搜索', + caiyuntrs: '彩云小译网页翻译', cambridge: '剑桥词典', copy_pdf_url: '复制PDF链接到剪贴板', dictcn: '海词词典', diff --git a/src/_locales/zh-TW/menus.ts b/src/_locales/zh-TW/menus.ts index f12481e58..27883771b 100644 --- a/src/_locales/zh-TW/menus.ts +++ b/src/_locales/zh-TW/menus.ts @@ -5,6 +5,7 @@ export const locale: typeof _locale = { baidu_search: '百度搜尋', bing_dict: 'Bing 字典', bing_search: 'Bing 搜尋', + caiyuntrs: '彩雲小譯網頁翻譯', cambridge: '劍橋字典', copy_pdf_url: '複製PDF連結到剪貼簿', dictcn: '海詞字典', diff --git a/src/app-config/context-menus.ts b/src/app-config/context-menus.ts index db65acc69..917ed8c03 100644 --- a/src/app-config/context-menus.ts +++ b/src/app-config/context-menus.ts @@ -11,6 +11,7 @@ export function getAllContextMenus(): { [id: string]: ContextItem } { baidu_search: 'https://www.baidu.com/s?ie=utf-8&wd=%s', bing_dict: 'https://cn.bing.com/dict/?q=%s', bing_search: 'https://www.bing.com/search?q=%s', + caiyuntrs: 'x', cambridge: 'http://dictionary.cambridge.org/spellcheck/english-chinese-simplified/?q=%s', copy_pdf_url: 'x', diff --git a/src/app-config/index.ts b/src/app-config/index.ts index ab6eb6080..20208aeb8 100644 --- a/src/app-config/index.ts +++ b/src/app-config/index.ts @@ -45,7 +45,7 @@ export default getDefaultConfig function _getDefaultConfig() { return { - version: 13, + version: 14, /** activate app, won't affect triple-ctrl setting */ active: true, @@ -321,12 +321,7 @@ function _getDefaultConfig() { ] as [string, string][], contextMenus: { - selected: [ - 'view_as_pdf', - 'google_translate', - 'google_search', - 'saladict' - ], + selected: ['view_as_pdf', 'caiyuntrs', 'google_translate', 'saladict'], all: getAllContextMenus() }, diff --git a/src/app-config/merge-config.ts b/src/app-config/merge-config.ts index b061a27b1..8c878f95f 100644 --- a/src/app-config/merge-config.ts +++ b/src/app-config/merge-config.ts @@ -18,7 +18,9 @@ export function mergeConfig( ? JSON.parse(JSON.stringify(baseConfig)) : getDefaultConfig() - // pre-merge patch start + /* ----------------------------------------------- *\ + Pre-merge Patch Start + \* ----------------------------------------------- */ let oldVersion = oldConfig.version if (oldVersion < 13) { @@ -42,8 +44,9 @@ export function mergeConfig( rename('tripleCtrlHeight', 'qssaHeight') rename('tripleCtrlSidebar', 'qssaSidebar') rename('tripleCtrlPageSel', 'qssaPageSel') - - // pre-merge patch end + /* ----------------------------------------------- *\ + Pre-merge Patch End + \* ----------------------------------------------- */ Object.keys(base).forEach(key => { switch (key) { @@ -168,7 +171,9 @@ export function mergeConfig( } }) - // post-merge patch start + /* ----------------------------------------------- *\ + Post-merge Patch Start + \* ----------------------------------------------- */ oldVersion = oldConfig.version if (oldVersion <= 10) { @@ -182,6 +187,12 @@ export function mergeConfig( 'https://stackedit.io/*' ]) } + if (oldVersion <= 13) { + oldVersion = 14 + if (!base.contextMenus.selected.includes('caiyuntrs')) { + base.contextMenus.selected.unshift('caiyuntrs') + } + } if (oldConfig.language['minor'] === false) { base.language.japanese = false @@ -194,7 +205,9 @@ export function mergeConfig( if (base.panelMaxHeightRatio < 1) { base.panelMaxHeightRatio = Math.round(base.panelMaxHeightRatio * 100) } - // post-merge patch end + /* ----------------------------------------------- *\ + Post-merge Patch End + \* ----------------------------------------------- */ return base diff --git a/src/app-config/merge-profile.ts b/src/app-config/merge-profile.ts index d34c704ce..7fef200bb 100644 --- a/src/app-config/merge-profile.ts +++ b/src/app-config/merge-profile.ts @@ -146,12 +146,15 @@ export function mergeProfile( } /* ----------------------------------------------- *\ - Patch + Patch Start \* ----------------------------------------------- */ // hjdict changed korean location if ((base.dicts.all.hjdict.options.chsas as string) === 'kor') { base.dicts.all.hjdict.options.chsas = 'kr' } + /* ----------------------------------------------- *\ + Patch End + \* ----------------------------------------------- */ return base diff --git a/src/background/context-menus.ts b/src/background/context-menus.ts index d8174e2f3..4d16af0cc 100644 --- a/src/background/context-menus.ts +++ b/src/background/context-menus.ts @@ -68,6 +68,11 @@ export class ContextMenus { // }) } + static openCaiyunTrs() { + if (isFirefox) return + browser.tabs.executeScript({ file: '/assets/trs.js' }) + } + static openYoudao() { // FF policy if (isFirefox) return @@ -158,6 +163,9 @@ export class ContextMenus { case 'google_page_translate': ContextMenus.openGoogle() break + case 'caiyuntrs': + ContextMenus.openCaiyunTrs() + break case 'google_cn_page_translate': ContextMenus.openGoogle() break @@ -259,6 +267,7 @@ export class ContextMenus { let contexts: browser.contextMenus.ContextType[] switch (id) { + case 'caiyuntrs': case 'google_page_translate': case 'google_cn_page_translate': case 'youdao_page_translate': diff --git a/src/background/index.ts b/src/background/index.ts index 95f308fc8..8af91bc36 100644 --- a/src/background/index.ts +++ b/src/background/index.ts @@ -11,6 +11,7 @@ import { init as initPdf } from './pdf-sniffer' import { ContextMenus } from './context-menus' import { BackgroundServer } from './server' import { initBadge } from './badge' +import { setupCaiyunTrsBackend } from './page-translate/caiyun' import './types' // init first to recevice self messaging @@ -21,6 +22,8 @@ startSyncServiceInterval() ContextMenus.init() BackgroundServer.init() +setupCaiyunTrsBackend() + getConfig().then(async config => { window.appConfig = config initPdf(config) diff --git a/src/background/page-translate/caiyun.ts b/src/background/page-translate/caiyun.ts new file mode 100644 index 000000000..21fc23f72 --- /dev/null +++ b/src/background/page-translate/caiyun.ts @@ -0,0 +1,34 @@ +export function setupCaiyunTrsBackend() { + browser.runtime.onMessage.addListener(msg => { + if (msg.contentScriptQuery === 'fetchUrl') { + const requestInit: RequestInit = { + method: msg.method || 'GET', + credentials: 'include', + headers: { + ...(msg.headers || {}), + 'content-type': 'application/json' + } + } + + if (msg.data) { + try { + requestInit.body = JSON.stringify(msg.data) + } catch (error) { + if (process.env.DEBUG) { + console.error('Caiyun trs message data error:', error) + } + } + } + + return fetch(msg.url, requestInit) + .then(response => response.text()) + .then(text => ({ status: 'ok', data: text })) + .catch(error => { + if (process.env.DEBUG) { + console.error('Caiyun trs requestAuthURL error:', error) + } + return { status: 'error', error: error } + }) + } + }) +} diff --git a/yarn.lock b/yarn.lock index f4136dfa0..9686ce284 100644 --- a/yarn.lock +++ b/yarn.lock @@ -14771,6 +14771,10 @@ [email protected]: resolved "https://registry.yarnpkg.com/trim/-/trim-0.0.1.tgz#5858547f6b290757ee95cccc666fb50084c460dd" integrity sha1-WFhUf2spB1fulczMZm+1AITEYN0= +trsjs@caiyunapp/trs.js: + version "0.1.0" + resolved "https://codeload.github.com/caiyunapp/trs.js/tar.gz/3dd6611fd49b7daab6f62326e4b15710da7d3486" + "true-case-path@^1.0.2": version "1.0.3" resolved "https://registry.yarnpkg.com/true-case-path/-/true-case-path-1.0.3.tgz#f813b5a8c86b40da59606722b144e3225799f47d"
feat
add Lingocloud trs
14942d4b54789f14706a0ff5bdcfb4588653badf
2019-07-12 15:18:12
CRIMX
refactor: split SaladBowl to prevent docgen bug
false
diff --git a/src/content/components/SaladBowl/SaladBowl.portal.tsx b/src/content/components/SaladBowl/SaladBowl.portal.tsx new file mode 100644 index 000000000..ed4fa3a05 --- /dev/null +++ b/src/content/components/SaladBowl/SaladBowl.portal.tsx @@ -0,0 +1,26 @@ +import React, { FC, useRef } from 'react' +import ReactDOM from 'react-dom' +import { SaladBowlShadow, SaladBowlShadowProps } from './SaladBowl.shadow' + +export type SaladBowlPortalProps = SaladBowlShadowProps + +/** + * React portal wrapped SaladBowlShadow. + * Detach from DOM when not visible. + */ +export const SaladBowlPortal: FC<SaladBowlPortalProps> = props => { + const nodeRef = useRef(document.createElement('div')) + nodeRef.current.className = 'saladict-div' + + if (props.show) { + if (!nodeRef.current.parentElement) { + document.body.appendChild(nodeRef.current) + } + } else { + if (nodeRef.current.parentElement) { + nodeRef.current.remove() + } + } + + return ReactDOM.createPortal(<SaladBowlShadow {...props} />, nodeRef.current) +} diff --git a/src/content/components/SaladBowl/SaladBowl.shadow.tsx b/src/content/components/SaladBowl/SaladBowl.shadow.tsx new file mode 100644 index 000000000..64a3975cc --- /dev/null +++ b/src/content/components/SaladBowl/SaladBowl.shadow.tsx @@ -0,0 +1,27 @@ +import React, { FC } from 'react' +import root from 'react-shadow' +import { CSSTransition } from 'react-transition-group' +import { SaladBowl, SaladBowlProps } from './SaladBowl' + +export interface SaladBowlShadowProps extends SaladBowlProps { + /** Visibility */ + readonly show: boolean +} + +/** + * Shadow DOM wrapped SaladBowl with pop-up animation. + */ +export const SaladBowlShadow: FC<SaladBowlShadowProps> = props => ( + <root.div> + <style>{require('./style.shadow.scss').toString()}</style> + <CSSTransition + classNames="saladbowl" + in={props.show} + timeout={1000} + enter={props.withAnimation} + exit={false} + > + <SaladBowl {...props} /> + </CSSTransition> + </root.div> +) diff --git a/src/content/components/SaladBowl/stories/SaladBowl.stories.tsx b/src/content/components/SaladBowl/SaladBowl.stories.tsx similarity index 93% rename from src/content/components/SaladBowl/stories/SaladBowl.stories.tsx rename to src/content/components/SaladBowl/SaladBowl.stories.tsx index 9f71cbc95..21134bce9 100644 --- a/src/content/components/SaladBowl/stories/SaladBowl.stories.tsx +++ b/src/content/components/SaladBowl/SaladBowl.stories.tsx @@ -2,7 +2,9 @@ import React, { useState } from 'react' import { storiesOf } from '@storybook/react' import { action } from '@storybook/addon-actions' import { withKnobs, boolean, number } from '@storybook/addon-knobs' -import { SaladBowl, SaladBowlShadow, SaladBowlPortal } from '../index' +import { SaladBowl } from './SaladBowl' +import { SaladBowlShadow } from './SaladBowl.shadow' +import { SaladBowlPortal } from './SaladBowl.portal' storiesOf('Content|SaladBowl', module) .addDecorator(withKnobs) diff --git a/src/content/components/SaladBowl/index.tsx b/src/content/components/SaladBowl/SaladBowl.tsx similarity index 81% rename from src/content/components/SaladBowl/index.tsx rename to src/content/components/SaladBowl/SaladBowl.tsx index b43f7d22b..9e34a4844 100644 --- a/src/content/components/SaladBowl/index.tsx +++ b/src/content/components/SaladBowl/SaladBowl.tsx @@ -1,7 +1,4 @@ -import React, { FC, useMemo, useRef } from 'react' -import ReactDOM from 'react-dom' -import root from 'react-shadow' -import { CSSTransition } from 'react-transition-group' +import React, { FC, useMemo } from 'react' export interface SaladBowlProps { /** Viewport based coordinate. */ @@ -108,51 +105,3 @@ export const SaladBowl: FC<SaladBowlProps> = props => { </div> ) } - -export interface SaladBowlShadowProps extends SaladBowlProps { - /** Visibility */ - readonly show: boolean -} - -/** - * Shadow DOM wrapped SaladBowl with pop-up animation. - */ -export const SaladBowlShadow: FC<SaladBowlShadowProps> = props => ( - <root.div> - <style>{require('./style.shadow.scss').toString()}</style> - <CSSTransition - classNames="saladbowl" - in={props.show} - timeout={1000} - enter={props.withAnimation} - exit={false} - > - <SaladBowl {...props} /> - </CSSTransition> - </root.div> -) - -export type SaladBowlPortalProps = SaladBowlShadowProps - -/** - * React portal wrapped SaladBowlShadow. - * Detach from DOM when not visible. - */ -export const SaladBowlPortal: FC<SaladBowlPortalProps> = props => { - const nodeRef = useRef(document.createElement('div')) - nodeRef.current.className = 'saladict-div' - - if (props.show) { - if (!nodeRef.current.parentElement) { - document.body.appendChild(nodeRef.current) - } - } else { - if (nodeRef.current.parentElement) { - nodeRef.current.remove() - } - } - - return ReactDOM.createPortal(<SaladBowlShadow {...props} />, nodeRef.current) -} - -export default SaladBowlPortal
refactor
split SaladBowl to prevent docgen bug
a1c4fb64e3b00c0a981502b9e9cf0fd7f1154d14
2018-02-14 12:10:25
CRIMX
chore(typings): rename typings folder
false
diff --git a/config/webpack.config.prod.js b/config/webpack.config.prod.js index 7ba6ed728..0b04e910a 100644 --- a/config/webpack.config.prod.js +++ b/config/webpack.config.prod.js @@ -51,11 +51,11 @@ const extractTextPluginOptions = shouldUseRelativeAssetPaths : {} // Every folder in app src would generate a entry -// except 'manifest', 'assets','components' and name starts with '_' +// except 'manifest', 'assets','components', 'typings' and name starts with '_' const entries = fs.readdirSync(paths.appSrc) .filter(name => !name.startsWith('_')) .map(name => ({name, dirPath: path.join(paths.appSrc, name)})) - .filter(({name, dirPath}) => !/^assets|components|manifest$/.test(name) && fs.lstatSync(dirPath).isDirectory()) + .filter(({name, dirPath}) => !/^assets|components|manifest|typings$/.test(name) && fs.lstatSync(dirPath).isDirectory()) // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. diff --git a/src/selection/index.ts b/src/selection/index.ts index b2b4ef20f..291db6a12 100644 --- a/src/selection/index.ts +++ b/src/selection/index.ts @@ -3,7 +3,7 @@ import { message, storage } from '@/_helpers/browser-api' import { isContainChinese, isContainEnglish } from '@/_helpers/lang-check' import { createAppConfigStream } from '@/_helpers/config-manager' import * as selection from '@/_helpers/selection' -import { MsgSALADICT_SELECTION, MsgSELECTION } from '@/_typings/message' +import { MsgSALADICT_SELECTION, MsgSELECTION } from '@/typings/message' import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' diff --git a/src/_typings/message.ts b/src/typings/message.d.ts similarity index 100% rename from src/_typings/message.ts rename to src/typings/message.d.ts
chore
rename typings folder
76b62ec409ac0cc40e47642f1c95430f6b3f5104
2018-06-06 06:52:01
CRIMX
chore(release): 6.1.2
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index eee318058..87d464516 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.1.2"></a> +## [6.1.2](https://github.com/crimx/ext-saladict/compare/v6.1.1...v6.1.2) (2018-06-06) + + +### Bug Fixes + +* **panel:** fix null pointer ([dc3a41e](https://github.com/crimx/ext-saladict/commit/dc3a41e)), closes [#130](https://github.com/crimx/ext-saladict/issues/130) + + + <a name="6.1.1"></a> ## [6.1.1](https://github.com/crimx/ext-saladict/compare/v6.1.0...v6.1.1) (2018-06-05) diff --git a/package.json b/package.json index 5fdfcb788..513a272d0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.1.1", + "version": "6.1.2", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.1.2
3b38d19d25a984684f9f7d12746af25c252cf620
2019-11-02 21:03:13
crimx
fix(panel): reset text align
false
diff --git a/src/content/components/DictPanel/DictPanel.scss b/src/content/components/DictPanel/DictPanel.scss index 01cb33595..7aaff063f 100644 --- a/src/content/components/DictPanel/DictPanel.scss +++ b/src/content/components/DictPanel/DictPanel.scss @@ -9,6 +9,7 @@ top: 0; left: 0; overflow: hidden; + text-align: initial; box-shadow: rgba(0, 0, 0, 0.8) 0px 4px 23px -6px; } diff --git a/src/content/components/WordEditor/WordEditor.scss b/src/content/components/WordEditor/WordEditor.scss index 20216ea43..9d11a5960 100644 --- a/src/content/components/WordEditor/WordEditor.scss +++ b/src/content/components/WordEditor/WordEditor.scss @@ -11,6 +11,7 @@ margin: auto; background: rgba(0, 0, 0, 0.4); display: flex; + text-align: initial; } .wordEditor-PanelContainer {
fix
reset text align
5f1f0cc47297848af42076e1bee3c39a2e1d3616
2018-12-04 09:08:53
CRIMX
refactor(options): add more supported languages
false
diff --git a/src/_locales/options/messages.json b/src/_locales/options/messages.json index c05d483a8..e744f4436 100644 --- a/src/_locales/options/messages.json +++ b/src/_locales/options/messages.json @@ -204,6 +204,26 @@ "zh_CN": "繁", "zh_TW": "繁" }, + "dict_panel_lang_kor": { + "en": "Korean", + "zh_CN": "韩", + "zh_TW": "韩" + }, + "dict_panel_lang_fr": { + "en": "French", + "zh_CN": "法", + "zh_TW": "法" + }, + "dict_panel_lang_de": { + "en": "Deutsch", + "zh_CN": "德", + "zh_TW": "德" + }, + "dict_panel_lang_es": { + "en": "Español", + "zh_CN": "西", + "zh_TW": "西" + }, "dict_panel_title": { "en": "Dict Panel", "zh_CN": "查词面板", diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index de8bd9d3c..28f112e49 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -2,10 +2,10 @@ export function getALlDicts () { const allDicts = { bing: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1100', + lang: '11000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -44,10 +44,10 @@ export function getALlDicts () { }, cambridge: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1110', + lang: '11100000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -75,10 +75,10 @@ export function getALlDicts () { }, cobuild: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -113,10 +113,10 @@ export function getALlDicts () { }, etymonline: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -152,10 +152,10 @@ export function getALlDicts () { }, eudic: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1100', + lang: '11000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -190,10 +190,10 @@ export function getALlDicts () { }, google: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1111', + lang: '11110000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -234,10 +234,10 @@ export function getALlDicts () { }, googledict: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1111', + lang: '11110000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -272,10 +272,10 @@ export function getALlDicts () { }, guoyu: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '0010', + lang: '00100000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -303,10 +303,10 @@ export function getALlDicts () { }, liangan: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '0010', + lang: '00100000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -334,10 +334,10 @@ export function getALlDicts () { }, longman: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -378,10 +378,10 @@ export function getALlDicts () { }, macmillan: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -416,10 +416,10 @@ export function getALlDicts () { }, oald: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -454,10 +454,10 @@ export function getALlDicts () { }, sogou: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1111', + lang: '11110000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -497,10 +497,10 @@ export function getALlDicts () { }, urban: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -535,10 +535,10 @@ export function getALlDicts () { }, vocabulary: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -566,10 +566,10 @@ export function getALlDicts () { }, weblio: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '0001', + lang: '00010000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -597,10 +597,10 @@ export function getALlDicts () { }, websterlearner: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1000', + lang: '10000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -639,10 +639,10 @@ export function getALlDicts () { }, wikipedia: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1111', + lang: '11110000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -680,10 +680,10 @@ export function getALlDicts () { }, youdao: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '1100', + lang: '11000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -723,10 +723,10 @@ export function getALlDicts () { }, zdic: { /** - * Supported language: en, zh-CN, zh-TW, ja + * Supported language: en, zh-CN, zh-TW, ja, kor, fr, de, es * `1` for supported */ - lang: '0100', + lang: '01000000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. diff --git a/src/options/OptDicts.vue b/src/options/OptDicts.vue index 50d6dea7b..a40c69f53 100644 --- a/src/options/OptDicts.vue +++ b/src/options/OptDicts.vue @@ -26,9 +26,7 @@ <div class="panel-list__header" @click="handleAddDict(id)"> <img class="panel-list__icon" :src="dictsPanelInfo[id].favicon"> <strong class="panel-list__title">{{ $t('dict:' + id) }}</strong> - <span class="panel-list__title-lang" v-if="+allDicts[id].lang[0]">{{ $t('opt:dict_panel_lang_en') }}</span> - <span class="panel-list__title-lang" v-if="+allDicts[id].lang[1]">{{ $t('opt:dict_panel_lang_zhs') }}</span> - <span class="panel-list__title-lang" v-if="+allDicts[id].lang[2]">{{ $t('opt:dict_panel_lang_zht') }}</span> + <span class="panel-list__title-lang" v-for="(c, i) in allDicts[id].lang" v-if="+c" :key="i">{{ $t('opt:dict_panel_lang_' + supportedLang[i]) }}</span> <button type="button" class="close">&#10004;</button> </div> </div> @@ -156,6 +154,7 @@ export default { } }) return { + supportedLang: ['en', 'zhs', 'zht', 'ja', 'kor', 'fr', 'de', 'es'], dictsPanelInfo, isShowAddDictsPanel: false }
refactor
add more supported languages
8b2a2ac639ce2ba30104f98350f289e0c3e8d849
2020-05-17 10:39:14
crimx
refactor(panel): add saladict theme
false
diff --git a/package.json b/package.json index 05a4e55d0..a8d6dea8a 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "@opentranslate/tencent": "^1.1.2", "@opentranslate/translator": "^1.1.0", "@opentranslate/youdao": "^1.1.0", + "@types/classnames": "^2.2.10", "@types/dompurify": "0.0.32", "@types/firefox-webext-browser": "^67.0.2", "@types/i18next": "^12.1.0", @@ -70,6 +71,7 @@ "@types/wavesurfer.js": "^2.0.2", "antd": "^4.1.0", "axios": "^0.19.0", + "classnames": "^2.2.6", "dexie": "^2.0.4", "dompurify": "^1.0.11", "get-selection-more": "^1.0.2", diff --git a/src/_helpers/storybook.tsx b/src/_helpers/storybook.tsx index e036f68e7..0ba8a51f7 100644 --- a/src/_helpers/storybook.tsx +++ b/src/_helpers/storybook.tsx @@ -75,29 +75,6 @@ export function mockRuntimeMessage(fn: (message: Message) => Promise<any>) { } } } - -export function getThemeStyles(darkMode?: boolean) { - return darkMode - ? { - backgroundColor: '#222', - color: '#ddd', - '--color-brand': '#218c74', - '--color-background': '#222', - '--color-rgb-background': '34, 34, 34', - '--color-font': '#ddd', - '--color-divider': '#4d4748' - } - : { - backgroundColor: '#fff', - color: '#333', - '--color-brand': '#5caf9e', - '--color-background': '#fff', - '--color-rgb-background': '255, 255, 255', - '--color-font': '#333', - '--color-divider': '#ddd' - } -} - export interface WithSaladictPanelOptions { /** before the story component */ head?: React.ReactNode diff --git a/src/_sass_global/_theme.scss b/src/_sass_global/_theme.scss new file mode 100644 index 000000000..aa7eebcda --- /dev/null +++ b/src/_sass_global/_theme.scss @@ -0,0 +1,21 @@ +.saladict-theme { + background-color: #fff; + color: #333; + --color-brand: #5caf9e; + --color-background: #fff; + --color-rgb-background: 255, 255, 255; + --color-font: #333; + --color-font-grey: #666; + --color-divider: #ddd; + + &.darkMode { + background-color: #222; + color: #ddd; + --color-brand: #218c74; + --color-background: #222; + --color-rgb-background: 34, 34, 34; + --color-font: #ddd; + --color-font-grey: #aaa; + --color-divider: #4d4748; + } +} diff --git a/src/audio-control/audio-control.scss b/src/audio-control/audio-control.scss index 1b53689e2..c4b59db1b 100644 --- a/src/audio-control/audio-control.scss +++ b/src/audio-control/audio-control.scss @@ -6,4 +6,5 @@ body { padding: 0; } +@import '@/_sass_global/_theme.scss'; @import '@/components/Waveform/Waveform.scss'; diff --git a/src/audio-control/index.tsx b/src/audio-control/index.tsx index e13fbd8cd..1d699177b 100644 --- a/src/audio-control/index.tsx +++ b/src/audio-control/index.tsx @@ -8,27 +8,7 @@ const searchParams = new URL(document.URL).searchParams const darkMode = Boolean(searchParams.get('darkmode')) -const rootStyles: React.CSSProperties = darkMode - ? { - backgroundColor: '#222', - color: '#ddd', - '--color-brand': '#218c74', - '--color-background': '#222', - '--color-rgb-background': '34, 34, 34', - '--color-font': '#ddd', - '--color-divider': '#4d4748' - } - : { - backgroundColor: '#fff', - color: '#333', - '--color-brand': '#5caf9e', - '--color-background': '#fff', - '--color-rgb-background': '255, 255, 255', - '--color-font': '#333', - '--color-divider': '#ddd' - } - ReactDOM.render( - <Waveform darkMode={darkMode} rootStyles={rootStyles} />, + <Waveform darkMode={darkMode} />, document.getElementById('root') ) diff --git a/src/components/Waveform/Waveform.stories.tsx b/src/components/Waveform/Waveform.stories.tsx index cd81d16fd..a674ef359 100644 --- a/src/components/Waveform/Waveform.stories.tsx +++ b/src/components/Waveform/Waveform.stories.tsx @@ -6,8 +6,7 @@ import { withKnobs, boolean } from '@storybook/addon-knobs' import { withSaladictPanel, withSideEffect, - mockRuntimeMessage, - getThemeStyles + mockRuntimeMessage } from '@/_helpers/storybook' import { Waveform } from './Waveform' @@ -46,7 +45,5 @@ storiesOf('Content Scripts|Dict Panel', module) .add('Waveform', () => { const darkMode = boolean('Dark Mode', true) - const rootStyles: React.CSSProperties = getThemeStyles(darkMode) - - return <Waveform darkMode={darkMode} rootStyles={rootStyles} /> + return <Waveform darkMode={darkMode} /> }) diff --git a/src/components/Waveform/Waveform.tsx b/src/components/Waveform/Waveform.tsx index 40d951b8a..64838047e 100644 --- a/src/components/Waveform/Waveform.tsx +++ b/src/components/Waveform/Waveform.tsx @@ -1,4 +1,5 @@ import * as React from 'react' +import classNames from 'classnames' import WaveSurfer from 'wavesurfer.js' import RegionsPlugin from 'wavesurfer.js/dist/plugin/wavesurfer.regions.min.js' import NumberEditor from 'react-number-editor' @@ -12,7 +13,6 @@ interface AnyObject { interface WaveformProps { darkMode: boolean - rootStyles: React.CSSProperties } interface WaveformState { @@ -313,7 +313,11 @@ export class Waveform extends React.PureComponent< render() { return ( - <div className="saladict-waveformWrap" style={this.props.rootStyles}> + <div + className={classNames('saladict-waveformWrap', 'saladict-theme', { + darkMode: this.props.darkMode + })} + > <div ref={this.containerRef} /> <div className="saladict-waveformCtrl"> <button @@ -343,7 +347,7 @@ export class Waveform extends React.PureComponent< <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" - fill={this.props.rootStyles.color} + fill="var(--color-font)" > <path d="M23.242 388.417l162.59 120.596v-74.925h300.281l-.297-240.358-89.555-.239-.44 150.801H185.832l.81-75.934-163.4 120.06z" /> <path d="M490.884 120.747L328.294.15l.001 74.925H28.013l.297 240.358 89.555.239.44-150.801h209.99l-.81 75.934 163.4-120.06z" /> @@ -352,7 +356,7 @@ export class Waveform extends React.PureComponent< <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" - fill={this.props.rootStyles['--color-divider']} + fill="var(--color-divider)" > <path d="M 23.242 388.417 L 23.243 388.417 L 23.242 388.418 Z M 23.243 388.418 L 186.642 268.358 L 185.832 344.292 L 283.967 344.292 L 331.712 434.088 L 185.832 434.088 L 185.832 509.013 Z M 395.821 344.292 L 396.261 193.491 L 485.816 193.73 L 486.113 434.088 L 388.064 434.088 L 340.319 344.292 Z" /> <path d="M 490.884 120.747 L 490.883 120.746 L 490.885 120.745 Z M 490.883 120.746 L 327.485 240.805 L 328.295 164.871 L 244.267 164.871 L 196.521 75.075 L 328.295 75.075 L 328.294 0.15 Z M 118.305 164.871 L 117.865 315.672 L 28.31 315.433 L 28.013 75.075 L 141.077 75.075 L 188.823 164.871 Z" /> @@ -381,8 +385,8 @@ export class Waveform extends React.PureComponent< viewBox="0 0 467.987 467.987" fill={ this.state.pitchStretch - ? this.props.rootStyles.color - : this.props.rootStyles['--color-divider'] + ? 'var(--color-font)' + : 'var(--color-divider)' } > <path d="M70.01 146.717h47.924V321.27H70.01zM210.032 146.717h47.924V321.27h-47.924zM350.053 146.717h47.924V321.27h-47.924zM0 196.717h47.924v74.553H0zM280.042 196.717h47.924v74.553h-47.924zM420.063 196.717h47.924v74.553h-47.924zM140.021 96.717h47.924V371.27h-47.924z" /> diff --git a/src/content/components/DictPanel/DictPanel.container.tsx b/src/content/components/DictPanel/DictPanel.container.tsx index 9fdb4ad13..5d452a79f 100644 --- a/src/content/components/DictPanel/DictPanel.container.tsx +++ b/src/content/components/DictPanel/DictPanel.container.tsx @@ -33,7 +33,6 @@ const mapStateToProps: MapStateToProps< withAnimation: state.config.animation, panelCSS: state.config.panelCSS, darkMode: state.config.darkMode, - colors: state.colors, menuBar, mtaBox, dictList, diff --git a/src/content/components/DictPanel/DictPanel.scss b/src/content/components/DictPanel/DictPanel.scss index 7aaff063f..e8af57f3b 100644 --- a/src/content/components/DictPanel/DictPanel.scss +++ b/src/content/components/DictPanel/DictPanel.scss @@ -1,4 +1,5 @@ @import '@/_sass_global/_z-indices.scss'; +@import '@/_sass_global/_theme.scss'; .dictPanel-Root { display: flex; diff --git a/src/content/components/DictPanel/DictPanel.stories.tsx b/src/content/components/DictPanel/DictPanel.stories.tsx index 16c674786..2e40fbf4a 100644 --- a/src/content/components/DictPanel/DictPanel.stories.tsx +++ b/src/content/components/DictPanel/DictPanel.stories.tsx @@ -13,8 +13,7 @@ import { import { withLocalStyle, withSideEffect, - mockRuntimeMessage, - getThemeStyles + mockRuntimeMessage } from '@/_helpers/storybook' import faker from 'faker' import { DictPanel, DictPanelProps } from './DictPanel' @@ -127,7 +126,6 @@ function useDictPanelProps(): DictPanelProps { }, {}) const darkMode = boolean('Dark Mode', false) - const colors = getThemeStyles(darkMode) return { coord: { @@ -140,7 +138,6 @@ function useDictPanelProps(): DictPanelProps { maxHeight: number('Max Height', window.innerHeight - 40), withAnimation: withAnimation, darkMode, - colors, menuBar: ( <MenuBar text={text} @@ -158,6 +155,8 @@ function useDictPanelProps(): DictPanelProps { updateHistoryIndex={action('Update History Index')} isPinned={boolean('Is Pinned', false)} togglePin={action('Toggle Pin')} + isQSFocus={boolean('Is Quick Search Panel Focus', false)} + toggleQSFocus={action('Toggle Quick Search Panel Focus')} onClose={action('Close Panel')} profiles={profiles} activeProfileId={select( @@ -213,6 +212,7 @@ function useDictPanelProps(): DictPanelProps { openDictSrcPage={action('Open Source Page')} onSpeakerPlay={async src => action('Open Source Page')(src)} onHeightChanged={action('Dict List Height Changed')} + onUserFold={action('User Fold')} newSelection={action('New Selection')} /> ), diff --git a/src/content/components/DictPanel/DictPanel.tsx b/src/content/components/DictPanel/DictPanel.tsx index b5a4712ff..6b46798ae 100644 --- a/src/content/components/DictPanel/DictPanel.tsx +++ b/src/content/components/DictPanel/DictPanel.tsx @@ -1,4 +1,5 @@ import React, { FC, ReactNode, useRef, useState, useMemo } from 'react' +import classNames from 'classnames' import { useUpdateEffect } from 'react-use' import { getScrollbarWidth } from '@/_helpers/scrollbar-width' import { SALADICT_PANEL, isInternalPage } from '@/_helpers/saladict' @@ -18,7 +19,6 @@ export interface DictPanelProps { withAnimation: boolean darkMode: boolean - colors: React.CSSProperties menuBar: ReactNode mtaBox: ReactNode @@ -63,13 +63,16 @@ export const DictPanel: FC<DictPanelProps> = props => { return ( <div - className={ - `dictPanel-Root ${SALADICT_PANEL}` + - (props.withAnimation ? ' isAnimate' : '') + - (props.dragStartCoord ? ' isDragging' : '') - } + className={classNames( + `dictPanel-Root ${SALADICT_PANEL}`, + 'saladict-theme', + { + isAnimate: props.withAnimation, + isDragging: props.dragStartCoord, + darkMode: props.darkMode + } + )} style={{ - ...props.colors, left: x, top: y, zIndex: isInternalPage() ? 999 : 2147483647, // for popups on options page diff --git a/src/content/components/DictPanel/DictPanelStandalone.container.tsx b/src/content/components/DictPanel/DictPanelStandalone.container.tsx index be4a0964a..ac7afc693 100644 --- a/src/content/components/DictPanel/DictPanelStandalone.container.tsx +++ b/src/content/components/DictPanel/DictPanelStandalone.container.tsx @@ -25,7 +25,6 @@ const mapStateToProps = ( withAnimation: state.config.animation, darkMode: state.config.darkMode, panelCSS: state.config.panelCSS, - colors: state.colors, menuBar, mtaBox, dictList, diff --git a/src/content/components/DictPanel/DictPanelStandalone.tsx b/src/content/components/DictPanel/DictPanelStandalone.tsx index 01e3a97e7..7677fede7 100644 --- a/src/content/components/DictPanel/DictPanelStandalone.tsx +++ b/src/content/components/DictPanel/DictPanelStandalone.tsx @@ -1,4 +1,5 @@ import React, { FC, ReactNode } from 'react' +import classNames from 'classnames' import { SALADICT_PANEL } from '@/_helpers/saladict' export interface DictPanelStandaloneProps { @@ -7,7 +8,6 @@ export interface DictPanelStandaloneProps { withAnimation: boolean darkMode: boolean - colors: React.CSSProperties panelCSS?: string menuBar: ReactNode @@ -21,12 +21,16 @@ export const DictPanelStandalone: FC<DictPanelStandaloneProps> = props => { <React.Fragment> {props.panelCSS ? <style>{props.panelCSS}</style> : null} <div - className={ - `dictPanel-Root ${SALADICT_PANEL}` + - (props.withAnimation ? ' isAnimate' : '') - } + className={classNames( + SALADICT_PANEL, + 'dictPanel-Root', + 'saladict-theme', + { + isAnimate: props.withAnimation, + darkMode: props.darkMode + } + )} style={{ - ...props.colors, width: props.width, height: props.height, '--panel-width': props.width, diff --git a/src/content/components/MtaBox/MtaBox.tsx b/src/content/components/MtaBox/MtaBox.tsx index 542b28004..716edf8ce 100644 --- a/src/content/components/MtaBox/MtaBox.tsx +++ b/src/content/components/MtaBox/MtaBox.tsx @@ -1,4 +1,5 @@ import React, { FC, useRef, useState, useEffect } from 'react' +import classNames from 'classnames' import CSSTransition from 'react-transition-group/CSSTransition' import AutosizeTextarea from 'react-textarea-autosize' import { useObservableState } from 'observable-hooks' @@ -61,7 +62,7 @@ export const MtaBox: FC<MtaBoxProps> = props => { return ( <div> <div - className={`mtaBox-TextArea-Wrap${isTyping ? ' isTyping' : ''}`} + className={classNames('mtaBox-TextArea-Wrap', { isTyping })} style={{ height: props.expand ? height : 0, maxHeight: props.maxHeight @@ -107,7 +108,9 @@ export const MtaBox: FC<MtaBoxProps> = props => { width="10" height="10" viewBox="0 0 59.414 59.414" - className={`mtaBox-DrawerBtn_Arrow${props.expand ? ' isExpand' : ''}`} + className={classNames('mtaBox-DrawerBtn_Arrow', { + isExpand: props.expand + })} > <path d="M58 14.146L29.707 42.44 1.414 14.145 0 15.56 29.707 45.27 59.414 15.56" /> </svg> diff --git a/src/content/components/WordEditor/Notes.tsx b/src/content/components/WordEditor/Notes.tsx index 7029c7187..b039eba5d 100644 --- a/src/content/components/WordEditor/Notes.tsx +++ b/src/content/components/WordEditor/Notes.tsx @@ -37,7 +37,7 @@ import { CSSTransition } from 'react-transition-group' import { CtxTransList } from './CtxTransList' export interface NotesProps - extends Pick<WordEditorPanelProps, 'containerWidth' | 'colors'> { + extends Pick<WordEditorPanelProps, 'containerWidth'> { wordEditor: { word: Word translateCtx: boolean @@ -178,7 +178,6 @@ export const Notes: FC<NotesProps> = props => { <> <WordEditorPanel containerWidth={props.containerWidth} - colors={props.colors} title={t('content:wordEditor.title')} btns={panelBtns} onClose={closeEditor} @@ -298,7 +297,6 @@ export const Notes: FC<NotesProps> = props => { {() => ( <WordEditorPanel containerWidth={props.containerWidth - 100} - colors={props.colors} title={t('content:wordEditor.chooseCtxTitle')} onClose={() => setShowCtxTransList(false)} btns={[ diff --git a/src/content/components/WordEditor/WordEditor.container.tsx b/src/content/components/WordEditor/WordEditor.container.tsx index e9a065ac6..ea1ea7c1e 100644 --- a/src/content/components/WordEditor/WordEditor.container.tsx +++ b/src/content/components/WordEditor/WordEditor.container.tsx @@ -17,7 +17,6 @@ const mapStateToProps: MapStateToProps< show: state.wordEditor.isShow, darkMode: state.config.darkMode, withAnimation: state.config.animation, - colors: state.colors, containerWidth: window.innerWidth - state.config.panelWidth - 100, ctxTrans: state.config.ctxTrans, wordEditor: state.wordEditor diff --git a/src/content/components/WordEditor/WordEditor.scss b/src/content/components/WordEditor/WordEditor.scss index ece5007b8..a0e6a080c 100644 --- a/src/content/components/WordEditor/WordEditor.scss +++ b/src/content/components/WordEditor/WordEditor.scss @@ -1,12 +1,13 @@ /*-----------------------------------------------*\ Variables \*-----------------------------------------------*/ -@import '../../../_sass_global/variables'; -@import '../../../_sass_global/z-indices'; -@import '../../../_sass_global/interfaces'; +@import '@/_sass_global/_variables.scss'; +@import '@/_sass_global/_z-indices.scss'; +@import '@/_sass_global/_interfaces.scss'; +@import '@/_sass_global/_theme.scss'; /*-----------------------------------------------*\ - Libs +Libs \*-----------------------------------------------*/ @import '~normalize-scss'; diff --git a/src/content/components/WordEditor/WordEditor.stories.tsx b/src/content/components/WordEditor/WordEditor.stories.tsx index 2ee8ce024..f3b95219a 100644 --- a/src/content/components/WordEditor/WordEditor.stories.tsx +++ b/src/content/components/WordEditor/WordEditor.stories.tsx @@ -8,8 +8,7 @@ import { WordEditor } from './WordEditor' import { withLocalStyle, withSideEffect, - mockRuntimeMessage, - getThemeStyles + mockRuntimeMessage } from '@/_helpers/storybook' import faker from 'faker' import { newWord } from '@/_helpers/record-manager' @@ -49,13 +48,11 @@ storiesOf('Content Scripts|WordEditor', module) () => { const config = getDefaultConfig() const darkMode = boolean('Dark Mode', false) - const colors = getThemeStyles(darkMode) return ( <WordEditor containerWidth={number('Panel X', 450 + 100)} darkMode={darkMode} - colors={colors} wordEditor={{ word: newWord({ date: faker.date.past().valueOf(), @@ -82,14 +79,12 @@ storiesOf('Content Scripts|WordEditor', module) .add('WordEditorPortal', () => { const config = getDefaultConfig() const darkMode = boolean('Dark Mode', false) - const colors = getThemeStyles(darkMode) return ( <WordEditorPortal show={boolean('Show', true)} darkMode={darkMode} withAnimation={boolean('With Animation', true)} - colors={colors} containerWidth={number('Panel X', 450 + 100)} wordEditor={{ word: newWord({ diff --git a/src/content/components/WordEditor/WordEditor.tsx b/src/content/components/WordEditor/WordEditor.tsx index 7b41a3ecd..e1db382e8 100644 --- a/src/content/components/WordEditor/WordEditor.tsx +++ b/src/content/components/WordEditor/WordEditor.tsx @@ -1,4 +1,5 @@ import React, { FC } from 'react' +import classNames from 'classnames' import { Notes, NotesProps } from './Notes' import { SALADICT_EXTERNAL } from '@/_helpers/saladict' @@ -9,7 +10,9 @@ export interface WordEditorProps extends NotesProps { export const WordEditor: FC<WordEditorProps> = props => { const { darkMode, ...restProps } = props return ( - <div className={`${SALADICT_EXTERNAL}${darkMode ? ' darkMode' : ''}`}> + <div + className={classNames(SALADICT_EXTERNAL, 'saladict-theme', { darkMode })} + > <Notes {...restProps} /> </div> ) diff --git a/src/content/components/WordEditor/WordEditorPanel.stories.tsx b/src/content/components/WordEditor/WordEditorPanel.stories.tsx index b57d188f0..b63d0c371 100644 --- a/src/content/components/WordEditor/WordEditorPanel.stories.tsx +++ b/src/content/components/WordEditor/WordEditorPanel.stories.tsx @@ -8,8 +8,7 @@ import { WordEditorPanel } from './WordEditorPanel' import { withLocalStyle, withSideEffect, - mockRuntimeMessage, - getThemeStyles + mockRuntimeMessage } from '@/_helpers/storybook' import faker from 'faker' @@ -28,7 +27,6 @@ storiesOf('Content Scripts|WordEditor', module) 'WordEditorPanel', () => { const darkMode = boolean('Dark Mode', false) - const colors = getThemeStyles(darkMode) return ( <div @@ -41,7 +39,6 @@ storiesOf('Content Scripts|WordEditor', module) > <WordEditorPanel containerWidth={number('Panel X', 450 + 100)} - colors={colors} btns={ boolean('With Buttons', true) ? [ diff --git a/src/content/components/WordEditor/WordEditorPanel.tsx b/src/content/components/WordEditor/WordEditorPanel.tsx index 09226bb73..d62ed3360 100644 --- a/src/content/components/WordEditor/WordEditorPanel.tsx +++ b/src/content/components/WordEditor/WordEditorPanel.tsx @@ -3,7 +3,6 @@ import { isInternalPage } from '@/_helpers/saladict' export interface WordEditorPanelProps { containerWidth: number - colors: React.CSSProperties title: React.ReactNode btns?: ReadonlyArray<{ type?: 'normal' | 'primary' @@ -25,7 +24,7 @@ export const WordEditorPanel: FC<WordEditorPanelProps> = props => { className="wordEditorPanel-Container" style={{ width: props.containerWidth }} > - <div className="wordEditorPanel" style={props.colors}> + <div className="wordEditorPanel"> <header className="wordEditorPanel-Header"> <h1 className="wordEditorPanel-Title">{props.title}</h1> <button diff --git a/src/content/components/WordEditor/WordEditorStandalone.container.tsx b/src/content/components/WordEditor/WordEditorStandalone.container.tsx index 14f63b32e..ec0549c4b 100644 --- a/src/content/components/WordEditor/WordEditorStandalone.container.tsx +++ b/src/content/components/WordEditor/WordEditorStandalone.container.tsx @@ -12,7 +12,6 @@ const mapStateToProps: MapStateToProps< WordEditorProps > = state => ({ darkMode: state.config.darkMode, - colors: state.colors, containerWidth: window.innerWidth, ctxTrans: state.config.ctxTrans, wordEditor: state.wordEditor, diff --git a/src/content/redux/modules/action-handlers/index.ts b/src/content/redux/modules/action-handlers/index.ts index bef86a8df..ab97935cc 100644 --- a/src/content/redux/modules/action-handlers/index.ts +++ b/src/content/redux/modules/action-handlers/index.ts @@ -16,28 +16,6 @@ export const actionHandlers: ActionHandlers<State, ActionCatalog> = { const url = window.location.href const panelMaxHeight = (window.innerHeight * payload.panelMaxHeightRatio) / 100 - const colors = - payload.darkMode === state.config.darkMode - ? state.colors - : payload.darkMode - ? { - backgroundColor: '#222', - color: '#ddd', - '--color-brand': '#218c74', - '--color-background': '#222', - '--color-rgb-background': '34, 34, 34', - '--color-font': '#ddd', - '--color-divider': '#4d4748' - } - : { - backgroundColor: '#fff', - color: '#333', - '--color-brand': '#5caf9e', - '--color-background': '#fff', - '--color-rgb-background': '255, 255, 255', - '--color-font': '#333', - '--color-divider': '#ddd' - } return { ...state, @@ -47,8 +25,7 @@ export const actionHandlers: ActionHandlers<State, ActionCatalog> = { isQSFocus: payload.qsFocus, isTempDisabled: payload.blacklist.some(([r]) => new RegExp(r).test(url)) && - payload.whitelist.every(([r]) => !new RegExp(r).test(url)), - colors + payload.whitelist.every(([r]) => !new RegExp(r).test(url)) } }, diff --git a/src/content/redux/modules/state.ts b/src/content/redux/modules/state.ts index 110b2b327..e6bc019d1 100644 --- a/src/content/redux/modules/state.ts +++ b/src/content/redux/modules/state.ts @@ -81,16 +81,7 @@ export const initState = () => { historyIndex: -1, /** Record init coordinate on dragstart */ dragStartCoord: null as null | { x: number; y: number }, - lastPlayAudio: null as null | { src: string; timestamp: number }, - colors: { - backgroundColor: '#fff', - color: '#333', - '--color-brand': '#5caf9e', - '--color-background': '#fff', - '--color-rgb-background': '255, 255, 255', - '--color-font': '#333', - '--color-divider': '#ddd' - } as Readonly<React.CSSProperties> + lastPlayAudio: null as null | { src: string; timestamp: number } } } diff --git a/src/popup/Popup.tsx b/src/popup/Popup.tsx index b572cea53..9ebe87877 100644 --- a/src/popup/Popup.tsx +++ b/src/popup/Popup.tsx @@ -1,4 +1,5 @@ import React, { FC, useState, useRef, useEffect } from 'react' +import classNames from 'classnames' import QRCode from 'qrcode.react' import CSSTransition from 'react-transition-group/CSSTransition' import { AppConfig } from '@/app-config' @@ -66,7 +67,7 @@ export const Popup: FC<PopupProps> = props => { }, []) return ( - <div className={`popup-root${config.darkMode ? ' dark-mode' : ''}`}> + <div className={classNames('popup-root', { 'dark-mode': config.darkMode })}> <DictPanelStandaloneContainer width="100vw" height={dictPanelHeight + 'px'} diff --git a/src/popup/_style.scss b/src/popup/_style.scss index df90246aa..08f435972 100644 --- a/src/popup/_style.scss +++ b/src/popup/_style.scss @@ -1,4 +1,5 @@ @import '@/_sass_global/_z-indices.scss'; +@import '@/_sass_global/_theme.scss'; /*------------------------------------*\ Base diff --git a/yarn.lock b/yarn.lock index dc8ff49cf..e06842bc7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2389,6 +2389,11 @@ "@types/filesystem" "*" "@types/har-format" "*" +"@types/classnames@^2.2.10": + version "2.2.10" + resolved "https://registry.yarnpkg.com/@types/classnames/-/classnames-2.2.10.tgz#cc658ca319b6355399efc1f5b9e818f1a24bf999" + integrity sha512-1UzDldn9GfYYEsWWnn/P4wkTlkZDH7lDb0wBMGbtIQc9zXEQq7FlKBdZUn6OBqD8sKZZ2RQO2mAjGpXiDGoRmQ== + "@types/color-name@^1.1.1": version "1.1.1" resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0"
refactor
add saladict theme
4723505fadf9af1f4c6bfb2ab396a590e89c39f9
2018-01-15 17:32:17
greenkeeper[bot]
chore(package): update babel-jest to version 22.1.0
false
diff --git a/package.json b/package.json index bb93cebd6..5739c5734 100644 --- a/package.json +++ b/package.json @@ -45,7 +45,7 @@ "@types/jest": "^22.0.1", "autoprefixer": "7.2.5", "babel-core": "6.26.0", - "babel-jest": "22.0.6", + "babel-jest": "22.1.0", "babel-loader": "7.1.2", "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-preset-env": "^1.6.1",
chore
update babel-jest to version 22.1.0
45b0ee418c617c3cf69ce87e69909f6e4c5a0037
2020-04-20 08:16:51
crimx
refactor(options): add entry BlackWhiteList
false
diff --git a/src/_locales/en/options.ts b/src/_locales/en/options.ts index af9a13139..5435113d0 100644 --- a/src/_locales/en/options.ts +++ b/src/_locales/en/options.ts @@ -120,6 +120,9 @@ export const locale: typeof _locale = { uk: 'UK', us: 'US' }, + sel_blackwhitelist: 'Selection Black/White List', + sel_blackwhitelist_help: + 'Saladict will not react to selection in blacklisted pages.', pdf_blackwhitelist_help: 'Blacklisted PDF links will not jump to Saladict PDF Viewer.', contextMenus_description: @@ -322,10 +325,6 @@ export const locale: typeof _locale = { 'Cannot be turned off as it is the core functionality of Saladict.', profile_change: 'This option may change base on "Profile".', - sel_blackwhitelist: 'Selection Black/White List', - sel_blackwhitelist_help: - 'Saladict will not react to selection in blacklisted pages.', - update_check: 'Check Update', update_check_help: 'Automatically check update from Github' } diff --git a/src/_locales/zh-CN/options.ts b/src/_locales/zh-CN/options.ts index 62974c145..e520824a3 100644 --- a/src/_locales/zh-CN/options.ts +++ b/src/_locales/zh-CN/options.ts @@ -111,6 +111,8 @@ export const locale = { uk: '英式', us: '美式' }, + sel_blackwhitelist: '划词黑白名单', + sel_blackwhitelist_help: '黑名单匹配的页面 Saladict 将不会响应鼠标划词。', pdf_blackwhitelist_help: '黑名单匹配的 PDF 链接将不会跳转到 Saladict 打开。', contextMenus_description: @@ -307,8 +309,6 @@ export const locale = { third_party_privacy_extra: '本特性为沙拉查词核心功能,无法关闭。', profile_change: '此选项会因「情景模式」而改变。', - sel_blackwhitelist: '划词黑白名单', - sel_blackwhitelist_help: '黑名单匹配的页面 Saladict 将不会响应鼠标划词。', update_check: '检查更新', update_check_help: '自动检查 Github 更新' } diff --git a/src/_locales/zh-TW/options.ts b/src/_locales/zh-TW/options.ts index a7b875f00..0c60db1b1 100644 --- a/src/_locales/zh-TW/options.ts +++ b/src/_locales/zh-TW/options.ts @@ -114,6 +114,8 @@ export const locale: typeof _locale = { uk: '英式', us: '美式' }, + sel_blackwhitelist: '選詞黑白名單', + sel_blackwhitelist_help: '黑名單相符的頁面 Saladict 將不會響應滑鼠劃詞。', pdf_blackwhitelist_help: '黑名單相符的 PDF 連結將不會跳至 Saladict 開啟。', contextMenus_description: @@ -309,8 +311,6 @@ export const locale: typeof _locale = { '沙拉查詞不會收集更多資料,但在查詞時單詞以及相關 cookies 資料會發送給第三方詞典服務(與在該網站上查詞一樣),如果你不希望被該服務獲取資料,請在「詞典設定」中關閉相應詞典。', third_party_privacy_extra: '本特性為沙拉查詞核心功能,無法關閉。', profile_change: '此選項會因「情景模式」而改變。', - sel_blackwhitelist: '選詞黑白名單', - sel_blackwhitelist_help: '黑名單相符的頁面 Saladict 將不會響應滑鼠劃詞。', update_check: '檢查更新', update_check_help: '自動檢查 Github 更新' diff --git a/src/options/components/Entries/BlackWhiteList.tsx b/src/options/components/Entries/BlackWhiteList.tsx new file mode 100644 index 000000000..02aff0acb --- /dev/null +++ b/src/options/components/Entries/BlackWhiteList.tsx @@ -0,0 +1,65 @@ +import React, { FC, useMemo, useState } from 'react' +import { Button } from 'antd' +import { SaladictForm } from '@/options/components/SaladictForm' +import { useTranslate } from '@/_helpers/i18n' +import { MatchPatternModal } from '../MatchPatternModal' + +export const BlackWhiteList: FC = () => { + const { t, i18n, ready } = useTranslate(['options', 'common']) + const [editingArea, setEditingArea] = useState< + 'pdfWhitelist' | 'pdfBlacklist' | 'whitelist' | 'blacklist' | null + >(null) + + return ( + <> + <SaladictForm + hideFooter + items={useMemo( + () => [ + { + key: 'BlackWhiteList', + label: t('config.opt.sel_blackwhitelist'), + help: t('config.opt.sel_blackwhitelist_help'), + children: ( + <> + <Button + style={{ marginRight: 10 }} + onClick={() => setEditingArea('blacklist')} + > + {t('common:blacklist')} + </Button> + <Button onClick={() => setEditingArea('whitelist')}> + {t('common:whitelist')} + </Button> + </> + ) + }, + { + key: 'PDFBlackWhiteList', + label: 'PDF ' + t('nav.BlackWhiteList'), + help: t('config.opt.pdf_blackwhitelist_help'), + children: ( + <> + <Button + style={{ marginRight: 10 }} + onClick={() => setEditingArea('pdfBlacklist')} + > + PDF {t('common:blacklist')} + </Button> + <Button onClick={() => setEditingArea('pdfWhitelist')}> + PDF {t('common:whitelist')} + </Button> + </> + ) + } + ], + [ready, i18n.language] + )} + /> + <MatchPatternModal + area={editingArea} + onClose={() => setEditingArea(null)} + /> + </> + ) +}
refactor
add entry BlackWhiteList
ed55215f647e872c750ec34ea4f1a8d6b6e82be5
2020-04-05 15:36:14
crimx
refactor(i18n-manager): load ns before emitting fixed t
false
diff --git a/src/background/context-menus.ts b/src/background/context-menus.ts index 5f4152ae9..a330ee6e0 100644 --- a/src/background/context-menus.ts +++ b/src/background/context-menus.ts @@ -34,7 +34,6 @@ export class ContextMenus { ContextMenus.instance = instance const i18nManager = await I18nManager.getInstance() - await i18nManager.i18n.loadNamespaces('menus') const contextMenusChanged$ = createConfigStream().pipe( distinctUntilChanged( @@ -49,7 +48,7 @@ export class ContextMenus { filter(config => !!config) ) - combineLatest(contextMenusChanged$, i18nManager.getFixedT$$('menus')) + combineLatest(contextMenusChanged$, i18nManager.getFixedT$('menus')) .pipe(concatMap(instance.setContextMenus)) .subscribe() } diff --git a/src/background/i18n-manager.ts b/src/background/i18n-manager.ts index 75be1d91f..2c1866ff8 100644 --- a/src/background/i18n-manager.ts +++ b/src/background/i18n-manager.ts @@ -1,7 +1,7 @@ import i18next, { TFunction } from 'i18next' import { i18nLoader, Namespace } from '@/_helpers/i18n' import { BehaviorSubject, Observable } from 'rxjs' -import { map } from 'rxjs/operators' +import { switchMap } from 'rxjs/operators' export class I18nManager { private static instance: I18nManager @@ -32,8 +32,12 @@ export class I18nManager { }) } - getFixedT$$(ns: Namespace | Namespace[]): Observable<TFunction> { - this.i18n.loadNamespaces(ns) - return this.i18n$$.pipe(map(i18n => i18n.getFixedT(i18n.language, ns))) + getFixedT$(ns: Namespace | Namespace[]): Observable<TFunction> { + return this.i18n$$.pipe( + switchMap(async i18n => { + await this.i18n.loadNamespaces(ns) + return i18n.getFixedT(i18n.language, ns) + }) + ) } }
refactor
load ns before emitting fixed t
9633cd33f16fbfa92828ce3563f15787255a1df0
2020-04-20 09:38:53
crimx
refactor(options): remove old entries
false
diff --git a/src/options/components/options/BlackWhiteList/index.tsx b/src/options/components/options/BlackWhiteList/index.tsx deleted file mode 100644 index c8203c742..000000000 --- a/src/options/components/options/BlackWhiteList/index.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { formItemLayout } from '../helpers' -import MatchPatternModal from '../../MatchPatternModal' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Button } from 'antd' - -export type BlackWhiteListProps = Props & FormComponentProps - -interface BlackWhiteListState { - editingArea: '' | 'pdfWhitelist' | 'pdfBlacklist' | 'whitelist' | 'blacklist' -} - -export class BlackWhiteList extends React.Component< - BlackWhiteListProps, - BlackWhiteListState -> { - constructor(props: BlackWhiteListProps) { - super(props) - this.state = { - editingArea: '' - } - } - - closeModal = () => { - this.setState({ editingArea: '' }) - } - - render() { - const { t, config } = this.props - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.sel_blackwhitelist')} - help={t('opt.sel_blackwhitelist_help')} - > - <Button - style={{ marginRight: 10 }} - onClick={() => this.setState({ editingArea: 'blacklist' })} - > - {t('common:blacklist')} - </Button> - <Button onClick={() => this.setState({ editingArea: 'whitelist' })}> - {t('common:whitelist')} - </Button> - </Form.Item> - <Form.Item - {...formItemLayout} - label={`PDF ${t('nav.BlackWhiteList')}`} - help={t('opt.pdf_blackwhitelist_help')} - > - <Button - style={{ marginRight: 10 }} - onClick={() => this.setState({ editingArea: 'pdfBlacklist' })} - > - PDF {t('common:blacklist')} - </Button> - <Button - onClick={() => this.setState({ editingArea: 'pdfWhitelist' })} - > - PDF {t('common:whitelist')} - </Button> - </Form.Item> - <MatchPatternModal - t={t} - config={config} - area={this.state.editingArea} - onClose={this.closeModal} - /> - </Form> - ) - } -} - -export default BlackWhiteList diff --git a/src/options/components/options/ContextMenus/AddModal.tsx b/src/options/components/options/ContextMenus/AddModal.tsx deleted file mode 100644 index cf98aa9f3..000000000 --- a/src/options/components/options/ContextMenus/AddModal.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import React from 'react' -import { TFunction } from 'i18next' -import { AppConfig, AppConfigMutable } from '@/app-config' -import { updateConfig } from '@/_helpers/config-manager' -import AddNewItem from './AddNewItem' - -import { Modal, List, Card, Button } from 'antd' - -const isFirefox = navigator.userAgent.includes('Firefox') - -export type AddModalProps = { - t: TFunction - config: AppConfig - show: boolean - onClose?: () => void -} - -export class AddModal extends React.Component<AddModalProps> { - addItem = (id: string) => { - const { config } = this.props - ;(config as AppConfigMutable).contextMenus.selected.push(id) - updateConfig(config) - } - - deleteItem = (id: string) => { - const { config, t } = this.props - if (confirm(t('common:delete_confirm'))) { - delete (config as AppConfigMutable).contextMenus.all[id] - updateConfig(config) - } - } - - renderItem = (id: string) => { - const { t, config } = this.props - const item = config.contextMenus.all[id] - - return ( - <List.Item> - <div className="sortable-list-item"> - {typeof item === 'string' ? t(`menus:${id}`) : item.name} - <div> - <Button - title={t('common:add')} - className="sortable-list-item-btn" - shape="circle" - size="small" - icon="check" - onClick={() => this.addItem(id)} - /> - <Button - title={t('common:delete')} - disabled={item === 'x' /** internal options */} - className="sortable-list-item-btn" - shape="circle" - size="small" - icon="close" - onClick={() => this.deleteItem(id)} - /> - </div> - </div> - </List.Item> - ) - } - - render() { - const { onClose, show, t, config } = this.props - const selectedSet = new Set(config.contextMenus.selected as string[]) - const unselected = Object.keys(config.contextMenus.all).filter(id => { - // FF policy - if (isFirefox && id === 'youdao_page_translate') { - return false - } - return !selectedSet.has(id) - }) - - return ( - <Modal - visible={show} - title={t('common:add')} - destroyOnClose - onOk={onClose} - onCancel={onClose} - footer={null} - > - <Card> - <List - size="large" - dataSource={unselected} - renderItem={this.renderItem} - /> - </Card> - <AddNewItem t={t} config={config} /> - </Modal> - ) - } -} - -export default AddModal diff --git a/src/options/components/options/ContextMenus/AddNewItem.tsx b/src/options/components/options/ContextMenus/AddNewItem.tsx deleted file mode 100644 index 0d92b51e5..000000000 --- a/src/options/components/options/ContextMenus/AddNewItem.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import React from 'react' -import { TFunction } from 'i18next' -import { AppConfig, AppConfigMutable } from '@/app-config' -import { CustomContextItem } from '@/app-config/context-menus' -import { updateConfig } from '@/_helpers/config-manager' -import { genUniqueKey } from '@/_helpers/uniqueKey' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Input, Button, Icon, Row, Col } from 'antd' - -export interface AddNewItemProps extends FormComponentProps { - t: TFunction - config: AppConfig -} - -export class AddNewItem extends React.Component<AddNewItemProps> { - addNewItem = () => { - const { config, form } = this.props - - form.validateFields() - if ( - Object.values(form.getFieldsError()).some(errs => errs && errs.length > 0) - ) { - return - } - - const { name, url } = form.getFieldsValue() as CustomContextItem - if (name && url) { - const { contextMenus } = config as AppConfigMutable - const id = `c_${genUniqueKey()}` - contextMenus.all[id] = { name, url } - updateConfig(config) - } - } - - render() { - const { t } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <p style={{ marginTop: '1em' }}>{t('opt.context_menus_add_rules')}</p> - <Row gutter={5}> - <Col span={12}> - <Form.Item help="" style={{ marginBottom: 0 }}> - {getFieldDecorator('name', { - rules: [{ whitespace: true, required: true }] - })(<Input placeholder={t('common:name')} />)} - </Form.Item> - </Col> - <Col span={12}> - <Form.Item help="" style={{ marginBottom: 0 }}> - {getFieldDecorator('url', { - rules: [{ type: 'url', whitespace: true, required: true }] - })(<Input placeholder="URL" />)} - </Form.Item> - </Col> - </Row> - <Button - type="dashed" - style={{ width: '100%' }} - onClick={this.addNewItem} - > - <Icon type="plus" /> {t('common:add')} - </Button> - </Form> - ) - } -} - -export default Form.create<AddNewItemProps>()(AddNewItem) diff --git a/src/options/components/options/ContextMenus/EditModal.tsx b/src/options/components/options/ContextMenus/EditModal.tsx deleted file mode 100644 index d52a6a4a5..000000000 --- a/src/options/components/options/ContextMenus/EditModal.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react' -import { TFunction } from 'i18next' -import { CustomContextItem } from '@/app-config/context-menus' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Input, Modal } from 'antd' - -export interface EditModalItem { - name: string - url: string - id: string -} - -export interface EditModalProps extends FormComponentProps { - t: TFunction - title: string - item: EditModalItem | null - onClose: (item?: EditModalItem) => void -} - -export class EditModal extends React.Component<EditModalProps> { - render() { - const { title, onClose, item, t } = this.props - const { getFieldDecorator, getFieldsValue } = this.props.form - - return ( - <Modal - visible={!!item} - title={title} - destroyOnClose - onOk={() => - onClose({ - ...(getFieldsValue() as CustomContextItem), - id: item!.id - }) - } - onCancel={() => onClose()} - > - <Form> - <p style={{ marginTop: '1em' }}>{t('opt.context_menus_add_rules')}</p> - <Form.Item - labelCol={{ span: 4 }} - wrapperCol={{ span: 20 }} - label={t('common:name')} - style={{ marginBottom: 0 }} - > - {getFieldDecorator('name', { - initialValue: item ? item.name : '' - })(<Input autoFocus />)} - </Form.Item> - <Form.Item - labelCol={{ span: 4 }} - wrapperCol={{ span: 20 }} - label="URL" - style={{ marginBottom: 0 }} - > - {getFieldDecorator('url', { - initialValue: item ? item.url : '' - })(<Input />)} - </Form.Item> - </Form> - </Modal> - ) - } -} - -export default Form.create<EditModalProps>()(EditModal) diff --git a/src/options/components/options/ContextMenus/index.tsx b/src/options/components/options/ContextMenus/index.tsx deleted file mode 100644 index d01f3e1d8..000000000 --- a/src/options/components/options/ContextMenus/index.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import React from 'react' -import { AppConfigMutable } from '@/app-config' -import { updateConfig } from '@/_helpers/config-manager' -import { Props } from '../typings' -import { arrayMove } from '../helpers' -import SortableList, { SortableListItem, SortEnd } from '../../SortableList' -import EditModal, { EditModalItem } from './EditModal' -import AddModal from './AddModal' - -import { Row, Col, message } from 'antd' - -const isFirefox = navigator.userAgent.includes('Firefox') - -export type ContextMenusProps = Props - -interface ContextMenusState { - showAddModal: boolean - editingItem: EditModalItem | null -} - -export class ContextMenus extends React.Component< - ContextMenusProps, - ContextMenusState -> { - state: ContextMenusState = { - showAddModal: false, - editingItem: null - } - - openAddModal = () => { - this.setState({ showAddModal: true }) - } - - closeAddModal = () => { - this.setState({ showAddModal: false }) - } - - openEditModal = (index: number) => { - const { contextMenus } = this.props.config - const id = contextMenus.selected[index] - const item = contextMenus.all[id] - if (!item) { - if (process.env.DEBUG) { - console.error('menu not found', index, id) - } - return - } - this.setState({ - editingItem: - typeof item === 'string' - ? { - name: this.props.t(`menus:${id}`), - url: item, - id - } - : { - ...item, - id - } - }) - } - - deleteItem = async (index: number) => { - const { t, config } = this.props - ;(config as AppConfigMutable).contextMenus.selected.splice(index, 1) - await updateConfig(config) - message.destroy() - message.success(t('msg_updated')) - } - - disableEdit = (index: number, item: SortableListItem) => { - return this.props.config.contextMenus.all[item.value] === 'x' - } - - handleEditModalClose = async (item?: EditModalItem) => { - if (item) { - const config = this.props.config as AppConfigMutable - config.contextMenus.all[item.id] = { - name: item.name, - url: item.url - } - await updateConfig(config) - } - this.setState({ editingItem: null }) - } - - handleSortEnd = async ({ oldIndex, newIndex }: SortEnd) => { - if (oldIndex === newIndex) { - return - } - const { t, config } = this.props - const contextMenus = (config as AppConfigMutable).contextMenus - contextMenus.selected = arrayMove(contextMenus.selected, oldIndex, newIndex) - await updateConfig(config) - message.destroy() - message.success(t('msg_updated')) - } - - render() { - const { t, config } = this.props - const { editingItem, showAddModal } = this.state - const allMenus = config.contextMenus.all - - return ( - <Row> - <Col span={12}> - <SortableList - t={t} - title={t('nav.ContextMenus')} - description={<p>{t('opt.context_description')}</p>} - list={config.contextMenus.selected - .filter(id => { - // FF policy - if (isFirefox && id === 'youdao_page_translate') { - return false - } - return true - }) - .map(id => { - const item = allMenus[id] - return { - value: id, - title: typeof item === 'string' ? t(`menus:${id}`) : item.name - } - })} - disableEdit={this.disableEdit} - onAdd={this.openAddModal} - onEdit={this.openEditModal} - onDelete={this.deleteItem} - onSortEnd={this.handleSortEnd} - /> - <AddModal - t={t} - config={config} - show={showAddModal} - onClose={this.closeAddModal} - /> - <EditModal - t={t} - title={t('opt.context_menus_title')} - item={editingItem} - onClose={this.handleEditModalClose} - /> - </Col> - </Row> - ) - } -} - -export default ContextMenus diff --git a/src/options/components/options/DictPanel/index.tsx b/src/options/components/options/DictPanel/index.tsx deleted file mode 100644 index ba28e93d3..000000000 --- a/src/options/components/options/DictPanel/index.tsx +++ /dev/null @@ -1,141 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' -import { InputNumberGroup } from '../../InputNumberGroup' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Switch, Row, Col, Radio, Input } from 'antd' - -export type DictPanelProps = Props & FormComponentProps - -export class DictPanel extends React.Component<DictPanelProps> { - render() { - const { t, config, profile } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.mta')} - extra={t('opt.profile_change')} - required - > - {getFieldDecorator('profile#mtaAutoUnfold', { - initialValue: profile.mtaAutoUnfold - })( - <Radio.Group> - <Row> - <Col span={12}> - <Radio value="">{t('opt.mta_never')}</Radio> - </Col> - <Col span={12}> - <Radio value="once">{t('opt.mta_once')}</Radio> - </Col> - </Row> - <Row> - <Col span={12}> - <Radio value="always">{t('opt.mta_always')}</Radio> - </Col> - <Col span={12}> - <Radio value="popup">{t('opt.mta_popup')}</Radio> - </Col> - </Row> - </Radio.Group> - )} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.waveform')} - help={t('opt.waveform_help')} - extra={t('opt.profile_change')} - required - > - {getFieldDecorator('profile#waveform', { - initialValue: profile.waveform, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.search_suggests')}> - {getFieldDecorator('config#searchSuggests', { - initialValue: config.searchSuggests, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.animation')} - help={t('opt.animation_help')} - > - {getFieldDecorator('config#animation', { - initialValue: config.animation, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.dark_mode')}> - {getFieldDecorator('config#darkMode', { - initialValue: config.darkMode, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.dictPanel.height_ratio')}> - {getFieldDecorator('config#panelMaxHeightRatio', { - initialValue: config.panelMaxHeightRatio, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix="%" />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.dictPanel.width')}> - {getFieldDecorator('config#panelWidth', { - initialValue: config.panelWidth, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix="px" />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.dictPanel.font_size')}> - {getFieldDecorator('config#fontSize', { - initialValue: config.fontSize, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix="px" />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.bowl_offset.x')}> - {getFieldDecorator(`config#bowlOffsetX`, { - initialValue: config.bowlOffsetX, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup style={{ width: 80 }} suffix="px" />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.bowl_offset.y')}> - {getFieldDecorator(`config#bowlOffsetY`, { - initialValue: config.bowlOffsetY, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup style={{ width: 80 }} suffix="px" />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.dictPanel.custom_css')} - help={t('opt.dictPanel.custom_css_help')} - extra={ - <a - href="https://github.com/crimx/ext-saladict/wiki/PanelCSS#wiki-content" - target="_blank" - rel="nofollow noopener noreferrer" - > - Examples - </a> - } - > - {getFieldDecorator('config#panelCSS', { - initialValue: config.panelCSS - })( - <Input.TextArea - placeholder=".dictPanel-Root { }" - autosize={{ minRows: 4, maxRows: 15 }} - /> - )} - </Form.Item> - </Form> - ) - } -} - -export default Form.create<DictPanelProps>({ - onFieldsChange: updateConfigOrProfile as any -})(DictPanel) diff --git a/src/options/components/options/Dictionaries/AddDictModal.tsx b/src/options/components/options/Dictionaries/AddDictModal.tsx deleted file mode 100644 index 04581a6fa..000000000 --- a/src/options/components/options/Dictionaries/AddDictModal.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import React from 'react' -import { DictID } from '@/app-config' -import { updateProfile } from '@/_helpers/profile-manager' -import { Props } from '../typings' -import DictTitle from './DictTitle' - -import { Modal, List, Card, Button } from 'antd' - -export type AddDictModalProps = Props & { - show: boolean - onClose?: () => void -} - -export class AddDictModal extends React.Component<AddDictModalProps> { - addDict = (dictID: DictID) => { - const { profile } = this.props - ;(profile.dicts.selected as DictID[]).push(dictID) - updateProfile(profile) - } - - renderItem = (dictID: DictID) => { - const { t, profile } = this.props - - return ( - <List.Item> - <div className="sortable-list-item"> - <DictTitle - t={t} - dictID={dictID} - lang={profile.dicts.all[dictID].lang} - /> - <div> - <Button - title={t('common:add')} - className="sortable-list-item-btn" - shape="circle" - size="small" - icon="check" - onClick={() => this.addDict(dictID)} - /> - </div> - </div> - </List.Item> - ) - } - - render() { - const { onClose, show, t, profile } = this.props - const selectedSet = new Set(profile.dicts.selected as string[]) - const unselected = Object.keys(profile.dicts.all).filter( - (id): id is DictID => !selectedSet.has(id) - ) - - return ( - <Modal - visible={show} - title={t('dict.add')} - destroyOnClose - onOk={onClose} - onCancel={onClose} - footer={null} - > - <Card> - <List - size="large" - dataSource={unselected} - renderItem={this.renderItem} - /> - </Card> - </Modal> - ) - } -} - -export default AddDictModal diff --git a/src/options/components/options/Dictionaries/DictForm.tsx b/src/options/components/options/Dictionaries/DictForm.tsx deleted file mode 100644 index 2022a6e7b..000000000 --- a/src/options/components/options/Dictionaries/DictForm.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Select, Switch } from 'antd' - -export type DictFormProps = Props & FormComponentProps - -export class DictForm extends React.Component<DictFormProps> { - render() { - const { t, config, profile } = this.props - const { getFieldDecorator } = this.props.form - - const autopronCnList = profile.dicts.all.zdic.options.audio - ? config.autopron.cn.list - : config.autopron.cn.list.filter(id => id !== 'zdic') - - return ( - <Form> - <Form.Item {...formItemLayout} label={t('opt.autopron.cn')}> - {getFieldDecorator('config#autopron#cn#dict', { - initialValue: config.autopron.cn.dict - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - {autopronCnList.map(id => ( - <Select.Option key={id} value={id}> - {t(`dicts:${id}.name`)} - </Select.Option> - ))} - </Select> - )} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.autopron.en')}> - {getFieldDecorator('config#autopron#en#dict', { - initialValue: config.autopron.en.dict - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - {config.autopron.en.list.map(id => ( - <Select.Option key={id} value={id}> - {t(`dicts:${id}.name`)} - </Select.Option> - ))} - </Select> - )} - </Form.Item> - {config.autopron.en.dict && ( - <Form.Item {...formItemLayout} label={t('opt.autopron.accent')}> - {getFieldDecorator('config#autopron#en#accent', { - initialValue: config.autopron.en.accent - })( - <Select> - <Select.Option value="uk"> - {t('opt.autopron.accent_uk')} - </Select.Option> - <Select.Option value="us"> - {t('opt.autopron.accent_us')} - </Select.Option> - </Select> - )} - </Form.Item> - )} - <Form.Item {...formItemLayout} label={t('opt.autopron.machine')}> - {getFieldDecorator('config#autopron#machine#dict', { - initialValue: config.autopron.machine.dict - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - {config.autopron.machine.list.map(id => ( - <Select.Option key={id} value={id}> - {t(`dicts:${id}.name`)} - </Select.Option> - ))} - </Select> - )} - </Form.Item> - {config.autopron.machine.dict && ( - <Form.Item {...formItemLayout} label={t('opt.autopron.machine_src')}> - {getFieldDecorator('config#autopron#machine#src', { - initialValue: config.autopron.machine.src - })( - <Select> - <Select.Option value="trans"> - {t('opt.autopron.machine_src_trans')} - </Select.Option> - <Select.Option value="searchText"> - {t('opt.autopron.machine_src_search')} - </Select.Option> - </Select> - )} - </Form.Item> - )} - <Form.Item - {...formItemLayout} - label={t('opt.waveform')} - help={t('opt.waveform_help')} - extra={t('opt.profile_change')} - required - > - {getFieldDecorator('profile#waveform', { - initialValue: profile.waveform, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - </Form> - ) - } -} - -export default Form.create<DictFormProps>({ - onFieldsChange: updateConfigOrProfile as any -})(DictForm) diff --git a/src/options/components/options/Dictionaries/DictTitle.tsx b/src/options/components/options/Dictionaries/DictTitle.tsx deleted file mode 100644 index e92220541..000000000 --- a/src/options/components/options/Dictionaries/DictTitle.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import React from 'react' -import { DictID } from '@/app-config' -import { TFunction } from 'i18next' -import LangCodeList from './LangCodeList' - -interface DictTitleProps { - t: TFunction - dictID: DictID - lang: string -} - -const iconStyle: React.CSSProperties = { - width: '1.3em', - height: '1.3em', - marginRight: 5, - verticalAlign: 'text-bottom' -} - -export default class DictTitle extends React.PureComponent<DictTitleProps> { - render() { - const { t, dictID, lang } = this.props - const title = t(`dicts:${dictID}.name`) - return ( - <span> - <img - style={iconStyle} - src={require('@/components/dictionaries/' + dictID + '/favicon.png')} - alt={`logo ${title}`} - /> - {title} - <LangCodeList t={t} langs={lang} /> - </span> - ) - } -} diff --git a/src/options/components/options/Dictionaries/EditDictModal.tsx b/src/options/components/options/Dictionaries/EditDictModal.tsx deleted file mode 100644 index b15accfa1..000000000 --- a/src/options/components/options/Dictionaries/EditDictModal.tsx +++ /dev/null @@ -1,204 +0,0 @@ -import React from 'react' -import { DictID } from '@/app-config' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemModalLayout } from '../helpers' -import { DictItem } from '@/app-config/dicts' -import { supportedLangs } from '@/_helpers/lang-check' -import { InputNumberGroup } from '../../InputNumberGroup' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Modal, Switch, Checkbox, Radio } from 'antd' - -export type EditDictModalProps = Props & - FormComponentProps & { - dictID: DictID | '' - onClose?: () => void - } - -export class EditDictModal extends React.Component<EditDictModalProps> { - renderMoreOptions = (dictID: DictID) => { - const { t, i18n, profile } = this.props - const { getFieldDecorator } = this.props.form - const dict = profile.dicts.all[dictID] as DictItem - const options = dict['options'] - if (!options) { - return - } - - const optionPath = `profile#dicts#all#${dictID}#options#` - - return ( - <> - <p>{t('dict.more_options')}</p> - {Object.keys(options).map(optKey => { - // can be number | boolean | string(select) - const value = options[optKey] - switch (typeof value) { - case 'number': - return ( - <Form.Item - {...formItemModalLayout} - key={optKey} - label={t(`dicts:${dictID}.options.${optKey}`)} - help={ - i18n.exists(`dicts:${dictID}.helps.${optKey}`) - ? t(`dicts:${dictID}.helps.${optKey}`) - : null - } - > - {getFieldDecorator(optionPath + optKey, { - initialValue: value, - rules: [{ type: 'number' }] - })( - <InputNumberGroup - suffix={t(`dicts:${dictID}.options.${optKey}_unit`)} - /> - )} - </Form.Item> - ) - case 'boolean': - return ( - <Form.Item - {...formItemModalLayout} - key={optKey} - label={t(`dicts:${dictID}.options.${optKey}`)} - help={ - i18n.exists(`dicts:${dictID}.helps.${optKey}`) - ? t(`dicts:${dictID}.helps.${optKey}`) - : null - } - > - {getFieldDecorator(optionPath + optKey, { - initialValue: value, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - ) - case 'string': - return ( - <Form.Item - {...formItemModalLayout} - key={optKey} - label={t(`dicts:${dictID}.options.${optKey}`)} - help={ - i18n.exists(`dicts:${dictID}.helps.${optKey}`) - ? t(`dicts:${dictID}.helps.${optKey}`) - : null - } - style={{ marginBottom: 0 }} - > - {getFieldDecorator(optionPath + optKey, { - initialValue: value - })( - <Radio.Group> - {dict['options_sel'][optKey].map(option => ( - <Radio value={option} key={option}> - {optKey === 'tl' || optKey === 'tl2' - ? t(`langcode:${option}`) - : t(`dicts:${dictID}.options.${optKey}-${option}`)} - </Radio> - ))} - </Radio.Group> - )} - </Form.Item> - ) - } - })} - </> - ) - } - - render() { - const { onClose, dictID, t, profile } = this.props - const { getFieldDecorator } = this.props.form - const dictPath = `profile#dicts#all#${dictID}` - const allDict = profile.dicts.all - - return ( - <Modal - visible={!!dictID} - title={dictID && t(`dicts:${dictID}.name`)} - destroyOnClose - onOk={onClose} - onCancel={onClose} - footer={null} - > - {dictID && ( - <Form> - <Form.Item - {...formItemModalLayout} - label={t('dict.sel_lang')} - help={t('dict.sel_lang_help')} - extra={ - <span style={{ color: '#c0392b' }}> - {t('opt.sel_lang_warning')} - </span> - } - > - {supportedLangs.map(lang => ( - <Form.Item key={lang} className="form-item-inline"> - {getFieldDecorator(`${dictPath}#selectionLang#${lang}`, { - initialValue: allDict[dictID].selectionLang[lang], - valuePropName: 'checked' - })(<Checkbox>{t(`common:lang.${lang}`)}</Checkbox>)} - </Form.Item> - ))} - </Form.Item> - <Form.Item - {...formItemModalLayout} - label={t('dict.default_unfold')} - help={t('dict.default_unfold_help')} - extra={ - <span style={{ color: '#c0392b' }}> - {t('opt.sel_lang_warning')} - </span> - } - > - {supportedLangs.map(lang => ( - <Form.Item key={lang} className="form-item-inline"> - {getFieldDecorator(`${dictPath}#defaultUnfold#${lang}`, { - initialValue: allDict[dictID].defaultUnfold[lang], - valuePropName: 'checked' - })(<Checkbox>{t(`common:lang.${lang}`)}</Checkbox>)} - </Form.Item> - ))} - </Form.Item> - <Form.Item - {...formItemModalLayout} - label={t('dict.sel_word_count')} - help={t('dict.sel_word_count_help')} - > - <Form.Item className="form-item-inline" help=""> - {getFieldDecorator(`${dictPath}#selectionWC#min`, { - initialValue: allDict[dictID].selectionWC.min, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix={t('common:min')} />)} - </Form.Item> - <Form.Item className="form-item-inline" help=""> - {getFieldDecorator(`${dictPath}#selectionWC#max`, { - initialValue: allDict[dictID].selectionWC.max, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix={t('common:max')} />)} - </Form.Item> - </Form.Item> - <Form.Item - {...formItemModalLayout} - label={t('dict.default_height')} - help={t('dict.default_height_help')} - > - {getFieldDecorator(`${dictPath}#preferredHeight`, { - initialValue: allDict[dictID].preferredHeight, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix="px" />)} - </Form.Item> - {this.renderMoreOptions(dictID)} - </Form> - )} - </Modal> - ) - } -} - -export default Form.create<EditDictModalProps>({ - onFieldsChange: updateConfigOrProfile as any -})(EditDictModal) diff --git a/src/options/components/options/Dictionaries/LangCodeList/_style.scss b/src/options/components/options/Dictionaries/LangCodeList/_style.scss deleted file mode 100644 index 8d4297015..000000000 --- a/src/options/components/options/Dictionaries/LangCodeList/_style.scss +++ /dev/null @@ -1,9 +0,0 @@ - -.langcode-list-char { - margin-left: 5px; - padding: 0 2px; - font-size: 0.92em; - color: #777; - border: 1px solid #777; - border-radius: 2px; -} diff --git a/src/options/components/options/Dictionaries/LangCodeList/index.tsx b/src/options/components/options/Dictionaries/LangCodeList/index.tsx deleted file mode 100644 index f07012707..000000000 --- a/src/options/components/options/Dictionaries/LangCodeList/index.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import React from 'react' -import { TFunction } from 'i18next' - -import './_style.scss' - -export interface LangCodeListProps { - t: TFunction - langs: string -} - -const langCodes = ['en', 'zhs', 'zht', 'ja', 'kor', 'fr', 'de', 'es'] - -export default class LangCodeList extends React.PureComponent< - LangCodeListProps -> { - render() { - const { langs, t } = this.props - return langs.split('').map((c, i) => { - if (+c) { - return ( - <span className="langcode-list-char" key={langCodes[i]}> - {t(`dict.lang.${langCodes[i]}`)} - </span> - ) - } - }) - } -} diff --git a/src/options/components/options/Dictionaries/index.tsx b/src/options/components/options/Dictionaries/index.tsx deleted file mode 100644 index f87fc9aca..000000000 --- a/src/options/components/options/Dictionaries/index.tsx +++ /dev/null @@ -1,111 +0,0 @@ -import React from 'react' -import { updateProfile } from '@/_helpers/profile-manager' -import { Props } from '../typings' -import { arrayMove } from '../helpers' -import SortableList, { SortEnd } from '../../SortableList' -import AddDictModal from './AddDictModal' -import EditDictModal from './EditDictModal' -import DictTitle from './DictTitle' -import DictForm from './DictForm' - -import { Col, Row, Tooltip, Icon } from 'antd' -import { DictID } from '@/app-config' - -export type DictionariesProps = Props - -interface DictionariesState { - isShowAddDictModal: boolean - editingDictID: DictID | '' -} - -export class Dictionaries extends React.Component< - DictionariesProps, - DictionariesState -> { - state: DictionariesState = { - isShowAddDictModal: false, - editingDictID: '' - } - - openAddDictModal = () => { - this.setState({ isShowAddDictModal: true }) - } - - closeAddDictModal = () => { - this.setState({ isShowAddDictModal: false }) - } - - closeEditDictModal = () => { - this.setState({ editingDictID: '' }) - } - - deleteItem = async (index: number) => { - const { profile } = this.props - ;(profile.dicts.selected as DictID[]).splice(index, 1) - updateProfile(profile) - } - - handleSortEnd = ({ oldIndex, newIndex }: SortEnd) => { - if (oldIndex === newIndex) { - return - } - const { profile } = this.props - ;(profile.dicts.selected as DictID[]) = arrayMove( - profile.dicts.selected as DictID[], - oldIndex, - newIndex - ) - updateProfile(profile) - } - - render() { - const { t, profile } = this.props - const { selected } = profile.dicts - - return ( - <Row> - <Col> - <DictForm {...this.props} /> - </Col> - <Col span={13}> - <SortableList - t={t} - title={ - <Tooltip title={t('opt.profile_change')}> - <Icon type="question-circle-o" /> {t('opt.dict_selected')} - </Tooltip> - } - list={selected.map(id => { - return { - value: id, - title: ( - <DictTitle - t={t} - dictID={id} - lang={profile.dicts.all[id].lang} - /> - ) - } - })} - onAdd={this.openAddDictModal} - onEdit={index => this.setState({ editingDictID: selected[index] })} - onDelete={this.deleteItem} - onSortEnd={this.handleSortEnd} - /> - <EditDictModal - {...this.props} - dictID={this.state.editingDictID} - onClose={this.closeEditDictModal} - /> - <AddDictModal - {...this.props} - show={this.state.isShowAddDictModal} - onClose={this.closeAddDictModal} - /> - </Col> - </Row> - ) - } -} - -export default Dictionaries diff --git a/src/options/components/options/General/index.tsx b/src/options/components/options/General/index.tsx deleted file mode 100644 index 50baeed6f..000000000 --- a/src/options/components/options/General/index.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import React from 'react' -import { openURL } from '@/_helpers/browser-api' -import { resetConfig } from '@/_helpers/config-manager' -import { resetAllProfiles } from '@/_helpers/profile-manager' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Select, Switch, Button } from 'antd' - -export class General extends React.Component<Props & FormComponentProps> { - isReseted = false - - openShortcuts = () => { - if (navigator.userAgent.includes('Chrome')) { - openURL('chrome://extensions/shortcuts') - } else { - openURL('about:addons') - } - } - - resetConfigs = async () => { - if (confirm(this.props.t('opt.config.reset_confirm'))) { - await resetConfig() - this.isReseted = true - await resetAllProfiles() - this.isReseted = true - } - } - - componentDidUpdate() { - if (this.isReseted) { - this.isReseted = false - const { form, config } = this.props - form.setFieldsValue({ - 'config#active': config.active, - 'config#animation': config.animation, - 'config#analytics': config.analytics, - 'config#langCode': config.langCode - }) - } - } - - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Button onClick={this.openShortcuts}>{t('opt.shortcuts')}</Button> - <Form.Item - {...formItemLayout} - label={t('opt.active')} - help={t('opt.app_active_help')} - > - {getFieldDecorator('config#active', { - initialValue: config.active, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.animation')} - help={t('opt.animation_help')} - > - {getFieldDecorator('config#animation', { - initialValue: config.animation, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.language')}> - {getFieldDecorator('config#langCode', { - initialValue: config.langCode - })( - <Select> - <Select.Option value="zh-CN">简体中文</Select.Option> - <Select.Option value="zh-TW">繁體中文</Select.Option> - <Select.Option value="en">English</Select.Option> - </Select> - )} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.config.reset')}> - <Button type="danger" onClick={this.resetConfigs}> - {t('opt.config.reset')} - </Button> - </Form.Item> - </Form> - ) - } -} - -export default Form.create({ - onFieldsChange: updateConfigOrProfile as any -})(General) diff --git a/src/options/components/options/ImportExport/index.tsx b/src/options/components/options/ImportExport/index.tsx deleted file mode 100644 index 06f805e46..000000000 --- a/src/options/components/options/ImportExport/index.tsx +++ /dev/null @@ -1,181 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { AppConfig } from '@/app-config' -import { ProfileIDList, Profile } from '@/app-config/profiles' -import { mergeConfig } from '@/app-config/merge-config' -import { mergeProfile } from '@/app-config/merge-profile' -import { updateConfig, getConfig } from '@/_helpers/config-manager' -import { updateProfile, getProfile } from '@/_helpers/profile-manager' -import { storage } from '@/_helpers/browser-api' - -import { Upload, Icon, Row, Col, message } from 'antd' -import { RcFile } from 'antd/lib/upload/interface' - -export type ConfigStorage = { - baseconfig: AppConfig - activeProfileID: string - hasInstructionsShown: boolean - profileIDList: ProfileIDList -} & { - [id: string]: Profile -} - -export class ImportExport extends React.Component<Props> { - importConfig = async (file: RcFile) => { - const { t } = this.props - - const result = await new Promise<Partial<ConfigStorage> | null>(resolve => { - const fr = new FileReader() - fr.onload = () => { - try { - const json = JSON.parse(fr.result as string) - resolve(json) - } catch (err) { - /* */ - } - resolve() - } - fr.onerror = () => resolve() - fr.readAsText(file) - }) - - if (!result) { - message.error(t('opt.config.import_error')) - return - } - - let { - baseconfig, - activeProfileID, - hasInstructionsShown, - profileIDList, - syncConfig - } = result - - if ( - !baseconfig && - !activeProfileID && - !profileIDList && - hasInstructionsShown == null - ) { - message.error(t('opt.config.import_error')) - return - } - - await storage.sync.clear() - - if (baseconfig) { - await updateConfig(mergeConfig(baseconfig)) - } - - if (syncConfig) { - await storage.sync.set({ syncConfig }) - } - - if (hasInstructionsShown != null) { - await storage.sync.set({ hasInstructionsShown }) - } - - if (profileIDList) { - profileIDList = profileIDList.filter(({ id }) => result[id]) - if (profileIDList.length > 0) { - for (const { id } of profileIDList) { - await updateProfile(mergeProfile(result[id] as Profile)) - } - if ( - !activeProfileID || - profileIDList.every(({ id }) => id !== activeProfileID) - ) { - // use first item instead - activeProfileID = profileIDList[0].id - } - await storage.sync.set({ activeProfileID, profileIDList }) - } - } - } - - exportConfig = async () => { - const { t } = this.props - - const result = await storage.sync.get([ - 'activeProfileID', - 'hasInstructionsShown', - 'profileIDList', - 'syncConfig' - ]) - - result.baseconfig = await getConfig() - - if ( - !result.baseconfig || - !result.activeProfileID || - !result.profileIDList - ) { - message.error(t('opt.config.import_error')) - return - } - - for (const { id } of result.profileIDList) { - result[id] = await getProfile(id) - } - try { - let text = JSON.stringify(result) - const { os } = await browser.runtime.getPlatformInfo() - if (os === 'win') { - text = text.replace(/\r\n|\n/g, '\r\n') - } - const file = new Blob([text], { type: 'text/plain;charset=utf-8' }) - const a = document.createElement('a') - a.href = URL.createObjectURL(file) - a.download = `config-${Date.now()}.saladict` - - // firefox - a.target = '_blank' - document.body.appendChild(a) - - a.click() - } catch (err) { - message.error(t('opt.config.import_error')) - } - } - - render() { - const { t } = this.props - return ( - <Row> - <Col span={12}> - <Row gutter={10}> - <Col span={12}> - <Upload.Dragger - beforeUpload={file => { - this.importConfig(file) - return false - }} - > - <p className="ant-upload-drag-icon"> - <Icon type="download" /> - </p> - <p className="ant-upload-text">{t('opt.config.import')}</p> - </Upload.Dragger> - </Col> - <Col span={12}> - <button - className="ant-upload ant-upload-drag" - onClick={this.exportConfig} - > - <div className="ant-upload ant-upload-btn"> - <p className="ant-upload-drag-icon"> - <Icon type="upload" /> - </p> - <p className="ant-upload-text">{t('opt.config.export')}</p> - </div> - </button> - </Col> - </Row> - </Col> - </Row> - ) - } -} - -export default ImportExport diff --git a/src/options/components/options/Notebook/ShanbayModal.tsx b/src/options/components/options/Notebook/ShanbayModal.tsx deleted file mode 100644 index 89258e1d5..000000000 --- a/src/options/components/options/Notebook/ShanbayModal.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import React from 'react' -import { Service, SyncConfig } from '@/background/sync-manager/services/shanbay' -import { setSyncConfig } from '@/background/sync-manager/helpers' -import { formItemModalLayout } from '../helpers' -import { message } from '@/_helpers/browser-api' -import { TFunction } from 'i18next' -import { getWords } from '@/_helpers/record-manager' - -import { Form, Modal, Button, Switch, message as AntdMessage } from 'antd' - -export interface WebdavModalProps { - syncConfig?: SyncConfig - t: TFunction - show: boolean - onClose: () => void -} - -export interface ShanbayModalState { - syncConfig: SyncConfig -} - -export default class ShanbayModal extends React.Component< - WebdavModalProps, - ShanbayModalState -> { - state: ShanbayModalState = { - syncConfig: this.props.syncConfig || Service.getDefaultConfig() - } - - closeSyncService = () => { - this.props.onClose() - } - - handleEnableChanged = async (checked: boolean) => { - if (checked) { - const response = await message - .send<'SYNC_SERVICE_INIT', SyncConfig>({ - type: 'SYNC_SERVICE_INIT', - payload: { - serviceID: Service.id, - config: this.state.syncConfig - } - }) - .catch(e => ({ error: e })) - - if (response && response['error']) { - alert(this.props.t('sync.shanbay.login')) - Service.openLogin() - return - } - } else { - setSyncConfig('shanbay', { - ...this.state.syncConfig, - enable: false - }) - } - - this.setState(prevState => ({ - syncConfig: { - ...prevState.syncConfig, - enable: checked - } - })) - } - - handleSyncAll = async () => { - const { t } = this.props - const { total } = await getWords('notebook', { - itemsPerPage: 1, - filters: {} - }) - if (total > 50 && !confirm(t('sync.shanbay.sync_all_confirm'))) { - return - } - - AntdMessage.success(t('sync.start')) - - await message - .send<'SYNC_SERVICE_UPLOAD'>({ - type: 'SYNC_SERVICE_UPLOAD', - payload: { - op: 'ADD', - serviceID: Service.id, - force: true - } - }) - .catch(() => ({ error: 'unknown' })) - .then(e => { - if (e && e.error) { - AntdMessage.success(t('sync.failed')) - } - }) - - AntdMessage.success(t('sync.success')) - } - - handleSyncLast = async () => { - const { t } = this.props - const { words } = await getWords('notebook', { - itemsPerPage: 1, - filters: {} - }) - if (!words || words.length <= 0) { - return - } - - AntdMessage.success(t('sync.start')) - - await message - .send({ - type: 'SYNC_SERVICE_UPLOAD', - payload: { - op: 'ADD', - serviceID: Service.id, - force: true, - words - } - }) - .catch(() => ({ error: 'unknown' })) - .then(e => { - if (e && e.error) { - AntdMessage.success(t('sync.failed')) - } - }) - - AntdMessage.success(t('sync.success')) - } - - render() { - const { t, show } = this.props - - return ( - <Modal - visible={show} - title={t('sync.shanbay.title')} - destroyOnClose - onCancel={this.closeSyncService} - footer={[]} - > - <Form> - <p>{t('sync.shanbay.description')}</p> - <Form.Item {...formItemModalLayout} label={t('common:enable')}> - <Switch - checked={this.state.syncConfig.enable} - onChange={this.handleEnableChanged} - /> - </Form.Item> - {this.state.syncConfig.enable && ( - <div style={{ textAlign: 'center' }}> - <Button onClick={this.handleSyncAll} style={{ marginRight: 10 }}> - {t('sync.shanbay.sync_all')} - </Button> - <Button onClick={this.handleSyncLast}> - {t('sync.shanbay.sync_last')} - </Button> - </div> - )} - </Form> - </Modal> - ) - } -} diff --git a/src/options/components/options/Notebook/WebdavModal.tsx b/src/options/components/options/Notebook/WebdavModal.tsx deleted file mode 100644 index 701fc5888..000000000 --- a/src/options/components/options/Notebook/WebdavModal.tsx +++ /dev/null @@ -1,271 +0,0 @@ -import React from 'react' -import { Service, SyncConfig } from '@/background/sync-manager/services/webdav' -import { message } from '@/_helpers/browser-api' -import { removeSyncConfig } from '@/background/sync-manager/helpers' -import { InputNumberGroup } from '../../InputNumberGroup' -import { TFunction } from 'i18next' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Input, Modal, Button } from 'antd' - -type SyncConfigFormItem = { - [index in keyof SyncConfig]: { - name: string - value: any - errors?: any[] - dirty: boolean - touched: boolean - validating: boolean - } -} - -export type WebDAVFormProps = FormComponentProps & { - t: TFunction - configFormItems: SyncConfigFormItem - onChange: (config: SyncConfigFormItem) => void -} - -class WebDAVFormBase extends React.Component<WebDAVFormProps> { - formItemLayout = { - labelCol: { span: 5 }, - wrapperCol: { span: 18 } - } - - render() { - const { t, form } = this.props - const { getFieldDecorator } = form - - return ( - <Form> - <p dangerouslySetInnerHTML={{ __html: t('sync.webdav.explain') }} /> - <Form.Item - {...this.formItemLayout} - label={t('sync.webdav.url')} - hasFeedback - > - {getFieldDecorator('url', { - rules: [{ type: 'url', message: t('sync.error_url') }] - })(<Input />)} - </Form.Item> - <Form.Item {...this.formItemLayout} label={t('sync.webdav.user')}> - {getFieldDecorator('user', {})(<Input />)} - </Form.Item> - <Form.Item {...this.formItemLayout} label={t('sync.webdav.passwd')}> - {getFieldDecorator('passwd', {})(<Input type="password" />)} - </Form.Item> - <Form.Item - {...this.formItemLayout} - label={t('sync.webdav.duration')} - extra={t('sync.webdav.duration_help')} - > - {getFieldDecorator('duration', { - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix={t('common:unit.mins')} />)} - </Form.Item> - </Form> - ) - } -} - -const WebDAVForm = Form.create<WebDAVFormProps>({ - mapPropsToFields(props) { - return props.configFormItems - }, - onFieldsChange(props, field, allFields) { - props.onChange(allFields) - } -})(WebDAVFormBase) - -export interface WebdavModalProps { - syncConfig?: SyncConfig - t: TFunction - show: boolean - onClose: () => void -} - -export interface WebdavModalState { - isSyncServiceLoading: boolean - configFormItems: SyncConfigFormItem -} - -export default class WebdavModal extends React.Component< - WebdavModalProps, - WebdavModalState -> { - isSyncServiceTainted = false - - state: WebdavModalState = { - isSyncServiceLoading: false, - configFormItems: wrapFromItems( - this.props.syncConfig || Service.getDefaultConfig() - ) - } - - closeSyncService = () => { - if ( - !this.isSyncServiceTainted || - confirm(this.props.t('sync.close_confirm')) - ) { - this.props.onClose() - this.isSyncServiceTainted = false - } - } - - saveSyncService = async () => { - const { t } = this.props - const { configFormItems } = this.state - if (!configFormItems) { - return - } - let hasError = false - - this.setState({ isSyncServiceLoading: true }) - - const response = await message - .send<'SYNC_SERVICE_INIT', SyncConfig>({ - type: 'SYNC_SERVICE_INIT', - payload: { - serviceID: Service.id, - config: stripFromItems(configFormItems) - } - }) - .catch(() => ({})) - const error = response && response['error'] - if (error && error !== 'exist') { - alert(this.getErrorMsg(error)) - this.setState({ isSyncServiceLoading: false }) - return - } - - if (error === 'exist') { - if (confirm(t('sync.webdav.err_exist'))) { - await message - .send<'SYNC_SERVICE_DOWNLOAD'>({ - type: 'SYNC_SERVICE_DOWNLOAD', - payload: { - serviceID: Service.id, - noCache: true - } - }) - .catch(() => ({ error: 'unknown' })) - .then(e => { - if (e && e.error) { - hasError = true - alert(this.getErrorMsg(e.error)) - } - }) - } - } - - await message - .send<'SYNC_SERVICE_UPLOAD'>({ - type: 'SYNC_SERVICE_UPLOAD', - payload: { - op: 'ADD', - serviceID: Service.id, - force: true - } - }) - .catch(() => ({ error: 'unknown' })) - .then(e => { - if (e && e.error) { - hasError = true - alert(this.getErrorMsg(e.error)) - } - }) - - this.setState({ isSyncServiceLoading: false }) - - if (!hasError) { - this.isSyncServiceTainted = false - this.props.onClose() - } - } - - clearSyncService = async () => { - if (confirm(this.props.t('sync.delete_confirm'))) { - await removeSyncConfig(Service.id) - this.setState({ - configFormItems: wrapFromItems(Service.getDefaultConfig()) - }) - this.isSyncServiceTainted = false - this.props.onClose() - } - } - - getErrorMsg = (error: string | Error): string => { - const text = typeof error === 'string' ? error : String(error) - if (/^(network|unauthorized|mkcol|parse)$/.test(text)) { - return this.props.t('sync.webdav.err_' + text) - } else { - return this.props.t('sync.webdav.err_unknown', { error: text }) - } - } - - onSyncConfigChanged = (newConfigFormItems: SyncConfigFormItem) => { - this.isSyncServiceTainted = true - this.setState({ configFormItems: newConfigFormItems }) - } - - render() { - const { t, show } = this.props - const { configFormItems } = this.state - - const disableSaveBtn = - !show || - !configFormItems.url.value || - Object.values(configFormItems).some( - ({ errors }) => errors != null && errors.length > 0 - ) - - return ( - <Modal - visible={show} - title={t('sync.webdav.title')} - destroyOnClose - onOk={this.saveSyncService} - onCancel={this.closeSyncService} - footer={[ - <Button key="delete" type="danger" onClick={this.clearSyncService}> - {t('common:delete')} - </Button>, - <Button - key="save" - type="primary" - disabled={disableSaveBtn} - loading={this.state.isSyncServiceLoading} - onClick={this.saveSyncService} - > - {t('common:save')} - </Button>, - <Button key="cancel" onClick={this.closeSyncService}> - {t('common:cancel')} - </Button> - ]} - > - <WebDAVForm - t={t} - configFormItems={configFormItems} - onChange={this.onSyncConfigChanged} - /> - </Modal> - ) - } -} - -function wrapFromItems(config: SyncConfig): SyncConfigFormItem { - return Object.keys(config).reduce((o, k) => { - o[k] = Form.createFormField({ value: config[k] }) - return o - }, {}) as SyncConfigFormItem -} - -function stripFromItems(configFormItems: SyncConfigFormItem): SyncConfig { - return Object.keys(configFormItems).reduce((o, k) => { - o[k] = configFormItems[k].value - if (k === 'url' && o[k] && !o[k].endsWith('/')) { - o[k] += '/' - } - return o - }, {}) as SyncConfig -} diff --git a/src/options/components/options/Notebook/index.tsx b/src/options/components/options/Notebook/index.tsx deleted file mode 100644 index aaf7b9774..000000000 --- a/src/options/components/options/Notebook/index.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import React from 'react' -import { storage } from '@/_helpers/browser-api' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' -import WebdavModal from './WebdavModal' -import ShanbayModal from './ShanbayModal' -import { - Service as WebDAVService, - SyncConfig as WebDAVConfig -} from '@/background/sync-manager/services/webdav' -import { - Service as ShanbayService, - SyncConfig as ShanbayConfig -} from '@/background/sync-manager/services/shanbay' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Switch, Checkbox, Button } from 'antd' - -export type NotebookProps = Props & FormComponentProps - -interface SyncConfigs { - [WebDAVService.id]?: WebDAVConfig - [ShanbayService.id]?: ShanbayConfig -} - -export interface NotebookState { - isShowSyncServiceModal: { - [WebDAVService.id]: boolean - [ShanbayService.id]: boolean - } - syncConfigs: null | SyncConfigs -} - -export class Notebook extends React.Component<NotebookProps, NotebookState> { - state: NotebookState = { - isShowSyncServiceModal: { - [WebDAVService.id]: false, - [ShanbayService.id]: false - }, - syncConfigs: null - } - - constructor(props: NotebookProps) { - super(props) - - storage.sync.get('syncConfig').then(({ syncConfig }) => { - this.setState({ syncConfigs: syncConfig || {} }) - }) - storage.sync.addListener<SyncConfigs>('syncConfig', ({ syncConfig }) => { - this.setState({ syncConfigs: syncConfig.newValue || {} }) - }) - } - - showSyncServiceModal = ( - id: keyof NotebookState['isShowSyncServiceModal'], - isShow: boolean - ) => { - this.setState(prevState => ({ - isShowSyncServiceModal: { - ...prevState.isShowSyncServiceModal, - [id]: isShow - } - })) - } - - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - const { syncConfigs, isShowSyncServiceModal } = this.state - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.edit_on_fav')} - help={t('opt.edit_on_fav_help')} - > - {getFieldDecorator('config#editOnFav', { - initialValue: config.editOnFav, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.history')} - help={t('opt.history_help')} - > - {getFieldDecorator('config#searhHistory', { - initialValue: config.searhHistory, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - {config.searhHistory && ( - <Form.Item {...formItemLayout} label={t('opt.history_inco')}> - {getFieldDecorator('config#searhHistoryInco', { - initialValue: config.searhHistoryInco, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - )} - <Form.Item - {...formItemLayout} - label={t('opt.ctx_trans')} - help={t('opt.ctx_trans_help')} - > - {Object.keys(config.ctxTrans).map(id => ( - <Form.Item key={id} style={{ marginBottom: 0 }}> - {getFieldDecorator(`config#ctxTrans#${id}`, { - initialValue: config.ctxTrans[id], - valuePropName: 'checked' - })(<Checkbox>{t(`dicts:${id}.name`)}</Checkbox>)} - </Form.Item> - ))} - </Form.Item> - <Form.Item {...formItemLayout} label={t('sync.webdav.title')}> - <Button - onClick={() => this.showSyncServiceModal(WebDAVService.id, true)} - >{`${t('sync.webdav.title')} (${t( - syncConfigs && - syncConfigs[WebDAVService.id] && - syncConfigs[WebDAVService.id]!.url - ? 'common:enabled' - : 'common:disabled' - )})`}</Button> - </Form.Item> - <Form.Item {...formItemLayout} label={t('sync.shanbay.title')}> - <Button - onClick={() => this.showSyncServiceModal(ShanbayService.id, true)} - >{`${t('sync.shanbay.title')} (${t( - syncConfigs && - syncConfigs[ShanbayService.id] && - syncConfigs[ShanbayService.id]!.enable - ? 'common:enabled' - : 'common:disabled' - )})`}</Button> - </Form.Item> - {syncConfigs && ( - <> - <WebdavModal - syncConfig={syncConfigs[WebDAVService.id]} - t={t} - show={isShowSyncServiceModal[WebDAVService.id]} - onClose={() => this.showSyncServiceModal(WebDAVService.id, false)} - /> - <ShanbayModal - syncConfig={syncConfigs[ShanbayService.id]} - t={t} - show={isShowSyncServiceModal[ShanbayService.id]} - onClose={() => - this.showSyncServiceModal(ShanbayService.id, false) - } - /> - </> - )} - </Form> - ) - } -} - -export default Form.create<NotebookProps>({ - onFieldsChange: updateConfigOrProfile as any -})(Notebook) diff --git a/src/options/components/options/PDF/index.tsx b/src/options/components/options/PDF/index.tsx deleted file mode 100644 index f2d1753aa..000000000 --- a/src/options/components/options/PDF/index.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' -import MatchPatternModal from '../../MatchPatternModal' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Switch, Button } from 'antd' - -export type PDFProps = Props & FormComponentProps - -interface PDFState { - editingArea: '' | 'pdfWhitelist' | 'pdfBlacklist' -} - -export class PDF extends React.Component<PDFProps, PDFState> { - constructor(props: PDFProps) { - super(props) - - this.state = { - editingArea: '' - } - } - - closeModal = () => { - this.setState({ editingArea: '' }) - } - - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.pdf_sniff')} - help={t('opt.pdf_sniff_help')} - > - {getFieldDecorator('config#pdfSniff', { - initialValue: config.pdfSniff, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('nav.BlackWhiteList')} - help={t('opt.pdf_blackwhitelist_help')} - > - <Button - style={{ marginRight: 10 }} - onClick={() => this.setState({ editingArea: 'pdfBlacklist' })} - > - PDF {t('common:blacklist')} - </Button> - <Button - onClick={() => this.setState({ editingArea: 'pdfWhitelist' })} - > - PDF {t('common:whitelist')} - </Button> - </Form.Item> - <MatchPatternModal - t={t} - config={config} - area={this.state.editingArea} - onClose={this.closeModal} - /> - </Form> - ) - } -} - -export default Form.create<PDFProps>({ - onFieldsChange: updateConfigOrProfile as any -})(PDF) diff --git a/src/options/components/options/Popup/index.tsx b/src/options/components/options/Popup/index.tsx deleted file mode 100644 index d1d3958ca..000000000 --- a/src/options/components/options/Popup/index.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Select, Switch } from 'antd' - -export class Popup extends React.Component<Props & FormComponentProps> { - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.browserAction.open')} - help={t('opt.browserAction.openHelp')} - > - {getFieldDecorator('config#baOpen', { - initialValue: config.baOpen - })( - <Select> - <Select.Option value="popup_panel"> - {t('opt.browserAction.openDictPanel')} - </Select.Option> - <Select.Option value="popup_fav"> - {t('opt.browserAction.openFav')} - </Select.Option> - <Select.Option value="popup_options"> - {t('opt.browserAction.openOptions')} - </Select.Option> - <Select.Option value="popup_standalone"> - {t('opt.browserAction.openStandalone')} - </Select.Option> - {Object.keys(config.contextMenus.all).map(id => ( - <Select.Option key={id} value={id}> - {t(`menus:${id}`)} - </Select.Option> - ))} - </Select> - )} - </Form.Item> - {config.baOpen === 'popup_panel' && ( - <Form.Item - {...formItemLayout} - label={t('preload.title')} - help={t('preload.help')} - > - {getFieldDecorator('config#baPreload', { - initialValue: config.baPreload - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - <Select.Option value="clipboard"> - {t('preload.clipboard')} - </Select.Option> - <Select.Option value="selection"> - {t('preload.selection')} - </Select.Option> - </Select> - )} - </Form.Item> - )} - {config.baOpen === 'popup_panel' && config.baPreload !== '' && ( - <Form.Item - {...formItemLayout} - label={t('preload.auto')} - help={t('preload.auto_help')} - > - {getFieldDecorator('config#baAuto', { - initialValue: config.baAuto, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - )} - </Form> - ) - } -} - -export default Form.create({ - onFieldsChange: updateConfigOrProfile as any -})(Popup) diff --git a/src/options/components/options/Privacy/index.tsx b/src/options/components/options/Privacy/index.tsx deleted file mode 100644 index 5f1103a9b..000000000 --- a/src/options/components/options/Privacy/index.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Switch } from 'antd' - -export class Privacy extends React.Component<Props & FormComponentProps> { - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.update_check')} - help={t('opt.update_check_help')} - > - {getFieldDecorator('config#updateCheck', { - initialValue: config.updateCheck, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.analytics')} - help={t('opt.analytics_help')} - > - {getFieldDecorator('config#analytics', { - initialValue: config.analytics, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.history')} - help={t('opt.history_help')} - > - {getFieldDecorator('config#searhHistory', { - initialValue: config.searhHistory, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - {config.searhHistory && ( - <Form.Item {...formItemLayout} label={t('opt.history_inco')}> - {getFieldDecorator('config#searhHistoryInco', { - initialValue: config.searhHistoryInco, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - )} - <Form.Item - {...formItemLayout} - label={t('opt.third_party_privacy')} - help={t('opt.third_party_privacy_help')} - extra={t('opt.third_party_privacy_extra')} - > - <Switch checked disabled /> - </Form.Item> - </Form> - ) - } -} - -export default Form.create({ - onFieldsChange: updateConfigOrProfile as any -})(Privacy) diff --git a/src/options/components/options/Profiles/EditNameModal.tsx b/src/options/components/options/Profiles/EditNameModal.tsx deleted file mode 100644 index bf73d46b1..000000000 --- a/src/options/components/options/Profiles/EditNameModal.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import React from 'react' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Input, Modal } from 'antd' - -export interface EditNameModalProps extends FormComponentProps { - title: string - show: boolean - name: string - onClose: (value?: string) => void -} - -export class EditNameModal extends React.Component<EditNameModalProps> { - render() { - const { title, onClose, name, show } = this.props - const { getFieldDecorator, getFieldValue } = this.props.form - - return ( - <Modal - visible={show} - title={title} - destroyOnClose - onOk={() => onClose(getFieldValue('profile_name'))} - onCancel={() => onClose()} - > - <Form> - <Form.Item> - {getFieldDecorator('profile_name', { - initialValue: name - })(<Input autoFocus />)} - </Form.Item> - </Form> - </Modal> - ) - } -} - -export default Form.create<EditNameModalProps>()(EditNameModal) diff --git a/src/options/components/options/Profiles/index.tsx b/src/options/components/options/Profiles/index.tsx deleted file mode 100644 index 3f3eff4cc..000000000 --- a/src/options/components/options/Profiles/index.tsx +++ /dev/null @@ -1,193 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { arrayMove } from '../helpers' -import { ProfileID, getDefaultProfileID } from '@/app-config/profiles' -import { - getProfileName, - addProfile, - getProfileIDList, - getActiveProfileID, - updateActiveProfileID, - removeProfile, - updateProfileIDList -} from '@/_helpers/profile-manager' -import EditNameModal from './EditNameModal' -import SortableList, { SortEnd } from '../../SortableList' - -import { Row, Col, message } from 'antd' -import { RadioChangeEvent } from 'antd/lib/radio' - -export type ProfilesProps = Props - -interface ProfilesState { - selected: string - list: ProfileID[] - editingProfileID: ProfileID | null - showEditNameModal: boolean - showAddProfileModal: boolean -} - -export class Profiles extends React.Component<ProfilesProps, ProfilesState> { - state: ProfilesState = { - selected: '', - list: [], - editingProfileID: null, - showEditNameModal: false, - showAddProfileModal: false - } - - openAddProfileModal = () => { - this.setState({ showAddProfileModal: true }) - } - - editProfileName = (index: number) => { - this.setState({ - showEditNameModal: true, - editingProfileID: this.state.list[index] - }) - } - - handleProfileSelect = async ({ target: { value } }: RadioChangeEvent) => { - this.setState({ selected: value }) - await updateActiveProfileID(value) - message.destroy() - message.success(this.props.t('msg_updated')) - } - - deleteItem = async (index: number) => { - const { t } = this.props - const { name, id } = this.state.list[index] - if ( - confirm(t('profiles.delete_confirm', { name: getProfileName(name, t) })) - ) { - await removeProfile(id) - this.setState(({ list }) => ({ - list: list.filter(profileID => profileID.id !== id) - })) - message.destroy() - message.success(t('msg_updated')) - } - } - - handleAddProfileClose = async (name = '') => { - name = name.trim() - if (name) { - const profileID = getDefaultProfileID() - profileID.name = name - await addProfile(profileID) - this.setState(({ list }) => ({ - list: [...list, profileID], - showAddProfileModal: false - })) - message.destroy() - message.success(this.props.t('msg_updated')) - } else { - this.setState({ showAddProfileModal: false }) - } - } - - handleEditNameClose = async (name?: string) => { - const { editingProfileID, list, selected } = this.state - if (name && editingProfileID) { - const newProfileID = { - ...editingProfileID, - name - } - const newList = list.map(profile => - profile.id === newProfileID.id ? newProfileID : profile - ) - await updateProfileIDList(newList) - this.setState({ - list: newList, - editingProfileID: null, - showEditNameModal: false - }) - if (newProfileID.id !== selected) { - // active config alert is handled by global - message.destroy() - message.success(this.props.t('msg_updated')) - } - } else { - this.setState({ - editingProfileID: null, - showEditNameModal: false - }) - } - } - - handleSortEnd = ({ oldIndex, newIndex }: SortEnd) => { - if (oldIndex === newIndex) { - return - } - this.setState(({ list }) => { - const newList = arrayMove(list.slice(), oldIndex, newIndex) - updateProfileIDList(newList).then(() => { - message.destroy() - message.success(this.props.t('msg_updated')) - }) - return { list: newList } - }) - } - - componentDidMount() { - getProfileIDList().then(async idList => { - this.setState({ - list: idList.filter(Boolean) - }) - }) - getActiveProfileID().then(selected => { - this.setState({ selected }) - }) - } - - render() { - const { t } = this.props - const { - selected, - list, - editingProfileID, - showEditNameModal, - showAddProfileModal - } = this.state - - return ( - <Row> - <Col span={12}> - <SortableList - t={t} - title={t('nav.Profiles')} - description={ - <p dangerouslySetInnerHTML={{ __html: t('profiles.help') }} /> - } - list={list.map(profileID => ({ - value: profileID.id, - title: getProfileName(profileID.name, t) - }))} - selected={selected} - onSelect={this.handleProfileSelect} - onAdd={this.openAddProfileModal} - onEdit={this.editProfileName} - onDelete={this.deleteItem} - onSortEnd={this.handleSortEnd} - /> - <EditNameModal - title={t('profiles.add_name')} - show={showAddProfileModal} - name="" - onClose={this.handleAddProfileClose} - /> - <EditNameModal - title={t('profiles.edit_name')} - show={showEditNameModal} - name={ - editingProfileID ? getProfileName(editingProfileID.name, t) : '' - } - onClose={this.handleEditNameClose} - /> - </Col> - </Row> - ) - } -} - -export default Profiles diff --git a/src/options/components/options/QuickSearch/index.tsx b/src/options/components/options/QuickSearch/index.tsx deleted file mode 100644 index 039348ffa..000000000 --- a/src/options/components/options/QuickSearch/index.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { - updateConfigOrProfile, - formItemLayout, - formSubItemLayout -} from '../helpers' -import SearchMode from '../SearchModes/SearchMode' -import { InputNumberGroup } from '../../InputNumberGroup' -import { TCDirection } from '@/app-config' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Select, Switch, Card, Row, Col } from 'antd' - -const locLocale: Readonly<TCDirection[]> = [ - 'CENTER', - 'TOP', - 'RIGHT', - 'BOTTOM', - 'LEFT', - 'TOP_LEFT', - 'TOP_RIGHT', - 'BOTTOM_LEFT', - 'BOTTOM_RIGHT' -] - -type QuickSearchProps = Props & FormComponentProps - -export class QuickSearch extends React.Component<QuickSearchProps> { - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.quick_search')} - help={ - <span - dangerouslySetInnerHTML={{ - __html: t('quickSearch.help') - }} - /> - } - > - {getFieldDecorator('config#tripleCtrl', { - initialValue: config.tripleCtrl, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item {...formItemLayout} label={t('quickSearch.loc')}> - {getFieldDecorator('config#tripleCtrlLocation', { - initialValue: config.tripleCtrlLocation - })( - <Select> - {locLocale.map(locale => ( - <Select.Option key={locale} value={locale}> - {t(`quickSearch.locations.${locale}`)} - </Select.Option> - ))} - </Select> - )} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('preload.title')} - help={t('preload.help')} - > - {getFieldDecorator('config#tripleCtrlPreload', { - initialValue: config.tripleCtrlPreload - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - <Select.Option value="clipboard"> - {t('preload.clipboard')} - </Select.Option> - <Select.Option value="selection"> - {t('preload.selection')} - </Select.Option> - </Select> - )} - </Form.Item> - {config.tripleCtrlPreload !== '' && ( - <Form.Item - {...formItemLayout} - label={t('preload.auto')} - help={t('preload.auto_help')} - > - {getFieldDecorator('config#tripleCtrlAuto', { - initialValue: config.tripleCtrlAuto, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - )} - <Form.Item - {...formItemLayout} - label={t('quickSearch.standalone')} - help={ - <span - dangerouslySetInnerHTML={{ - __html: t('quickSearch.standalone_help') - }} - /> - } - > - {getFieldDecorator('config#tripleCtrlStandalone', { - initialValue: config.tripleCtrlStandalone, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - {config.tripleCtrlStandalone && ( - <Row> - <Col - xs={{ span: 24 }} - md={{ span: 20, offset: 2 }} - lg={{ span: 11, offset: 2 }} - > - <Card title={t('quickSearch.standalone')}> - <Form.Item - {...formSubItemLayout} - label={t('quickSearch.sidebar')} - help={t('quickSearch.sidebar_help')} - > - {getFieldDecorator('config#tripleCtrlSidebar', { - initialValue: config.tripleCtrlSidebar - })( - <Select> - <Select.Option value="">{t('common:none')}</Select.Option> - <Select.Option value="left"> - {t('quickSearch.locations.LEFT')} - </Select.Option> - <Select.Option value="right"> - {t('quickSearch.locations.RIGHT')} - </Select.Option> - </Select> - )} - </Form.Item> - {!config.tripleCtrlSidebar && ( - <Form.Item - {...formSubItemLayout} - label={t('quickSearch.height')} - > - {getFieldDecorator('config#tripleCtrlHeight', { - initialValue: config.tripleCtrlHeight, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix="px" />)} - </Form.Item> - )} - <Form.Item - {...formSubItemLayout} - label={t('quickSearch.page_sel')} - help={t('quickSearch.page_sel_help')} - > - {getFieldDecorator('config#tripleCtrlPageSel', { - initialValue: config.tripleCtrlPageSel, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - {config.tripleCtrlPageSel && ( - <SearchMode {...this.props} mode="qsPanelMode" sub={true} /> - )} - </Card> - </Col> - </Row> - )} - </Form> - ) - } -} - -export default Form.create<QuickSearchProps>({ - onFieldsChange: updateConfigOrProfile as any -})(QuickSearch) diff --git a/src/options/components/options/SearchModes/SearchMode.tsx b/src/options/components/options/SearchModes/SearchMode.tsx deleted file mode 100644 index 31e96d336..000000000 --- a/src/options/components/options/SearchModes/SearchMode.tsx +++ /dev/null @@ -1,212 +0,0 @@ -import React from 'react' -import { Props } from '../typings' -import { - updateConfigOrProfile, - formItemLayout, - formSubItemLayout -} from '../helpers' -import { InputNumberGroup } from '../../InputNumberGroup' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Checkbox, Select } from 'antd' - -const { Option } = Select - -export type SearchModeProps = Props & - FormComponentProps & { - mode: 'mode' | 'pinMode' | 'panelMode' | 'qsPanelMode' - /** sub panel */ - sub?: boolean - } - -interface SearchModeState { - isShowHolding: boolean -} - -export default class SearchMode extends React.Component< - SearchModeProps, - SearchModeState -> { - constructor(props: SearchModeProps) { - super(props) - - const { config, mode } = this.props - this.state = { - isShowHolding: - config[mode].holding.shift || - config[mode].holding.ctrl || - config[mode].holding.meta - } - } - - toggleHolding = () => - this.setState(({ isShowHolding }) => { - isShowHolding = !isShowHolding - const { mode } = this.props - updateConfigOrProfile(this.props, { - [`config#${mode}#holding#shift`]: { - name: `config#${mode}#holding#shift`, - touched: true, - dirty: false, - value: isShowHolding - } - }) - updateConfigOrProfile(this.props, { - [`config#${mode}#holding#ctrl`]: { - name: `config#${mode}#holding#ctrl`, - touched: true, - dirty: false, - value: isShowHolding - } - }) - updateConfigOrProfile(this.props, { - [`config#${mode}#holding#meta`]: { - name: `config#${mode}#holding#meta`, - touched: true, - dirty: false, - value: isShowHolding - } - }) - return { isShowHolding } - }) - - render() { - const { t, config, mode, sub } = this.props - const { isShowHolding } = this.state - const { getFieldDecorator } = this.props.form - - return ( - <Form.Item - {...(sub ? formSubItemLayout : formItemLayout)} - label={t(`opt.searchMode.${mode}`)} - > - {mode === 'mode' && ( - <> - <Form.Item help={t('opt.searchMode.iconHelp')}> - {getFieldDecorator(`config#${mode}#icon`, { - initialValue: config[mode].icon, - valuePropName: 'checked' - })(<Checkbox>{t('opt.searchMode.icon')}</Checkbox>)} - </Form.Item> - {config.mode.icon && ( - <> - <Form.Item help={t('opt.bowl_hover_help')}> - {getFieldDecorator(`config#bowlHover`, { - initialValue: config.bowlHover, - valuePropName: 'checked' - })(<Checkbox>{t('opt.bowl_hover')}</Checkbox>)} - </Form.Item> - <div> - <span>{t('opt.bowl_offset.x')}: </span> - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#bowlOffsetX`, { - initialValue: config.bowlOffsetX, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup style={{ width: 80 }} suffix="px" />)} - </Form.Item> - </div> - <div> - <span>{t('opt.bowl_offset.y')}: </span> - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#bowlOffsetY`, { - initialValue: config.bowlOffsetY, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup style={{ width: 80 }} suffix="px" />)} - </Form.Item> - </div> - </> - )} - </> - )} - <Form.Item help={t('opt.searchMode.direct_help')}> - {getFieldDecorator(`config#${mode}#direct`, { - initialValue: config[mode].direct, - valuePropName: 'checked' - })(<Checkbox>{t('opt.searchMode.direct')}</Checkbox>)} - </Form.Item> - <Form.Item help={t('opt.searchMode.double_help')}> - {getFieldDecorator(`config#${mode}#double`, { - initialValue: config[mode].double, - valuePropName: 'checked' - })(<Checkbox>{t('opt.searchMode.double')}</Checkbox>)} - </Form.Item> - <Form.Item help={t('opt.searchMode.holding_help')}> - <Checkbox checked={isShowHolding} onChange={this.toggleHolding}> - {t('opt.searchMode.holding')} - </Checkbox> - {isShowHolding && ( - <div> - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#${mode}#holding#shift`, { - initialValue: config[mode].holding.shift, - valuePropName: 'checked' - })( - <Checkbox> - <kbd>Shift</kbd> - </Checkbox> - )} - </Form.Item> - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#${mode}#holding#ctrl`, { - initialValue: config[mode].holding.ctrl, - valuePropName: 'checked' - })( - <Checkbox> - <kbd>Ctrl</kbd> - </Checkbox> - )} - </Form.Item> - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#${mode}#holding#meta`, { - initialValue: config[mode].holding.meta, - valuePropName: 'checked' - })( - <Checkbox> - <kbd>Meta(⌘/⊞)</kbd> - </Checkbox> - )} - </Form.Item> - </div> - )} - </Form.Item> - <Form.Item help={t('opt.searchMode.instantHelp')}> - {getFieldDecorator(`config#${mode}#instant#enable`, { - initialValue: config[mode].instant.enable, - valuePropName: 'checked' - })(<Checkbox>{t('opt.searchMode.instant')}</Checkbox>)} - {config[mode].instant.enable && ( - <div> - {t('opt.searchMode.instantKey') + ': '} - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#${mode}#instant#key`, { - initialValue: config[mode].instant.key - })( - <Select style={{ width: 100 }}> - <Option value="direct"> - {t('opt.searchMode.instantDirect')} - </Option> - <Option value="ctrl">Ctrl/⌘</Option> - <Option value="alt">Alt</Option> - <Option value="shift">Shift</Option> - </Select> - )} - </Form.Item> - {t('opt.searchMode.instantDelay')}:{' '} - <Form.Item className="form-item-inline"> - {getFieldDecorator(`config#${mode}#instant#delay`, { - initialValue: config[mode].instant.delay, - rules: [{ type: 'number', whitespace: true }] - })( - <InputNumberGroup - style={{ width: 60 }} - suffix={t('common:unit.ms')} - /> - )} - </Form.Item> - </div> - )} - </Form.Item> - </Form.Item> - ) - } -} diff --git a/src/options/components/options/SearchModes/index.tsx b/src/options/components/options/SearchModes/index.tsx deleted file mode 100644 index be43039d5..000000000 --- a/src/options/components/options/SearchModes/index.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import React from 'react' -import { supportedLangs } from '@/_helpers/lang-check' -import { Props } from '../typings' -import { updateConfigOrProfile, formItemLayout } from '../helpers' -import SearchMode from './SearchMode' -import { InputNumberGroup } from '../../InputNumberGroup' - -import { FormComponentProps } from 'antd/lib/form' -import { Form, Switch, Checkbox } from 'antd' - -export type SearchModesProps = Props & FormComponentProps - -export class SearchModes extends React.Component<SearchModesProps> { - render() { - const { t, config } = this.props - const { getFieldDecorator } = this.props.form - - return ( - <Form> - <Form.Item - {...formItemLayout} - label={t('opt.no_type_field')} - help={t('opt.no_type_field_help')} - > - {getFieldDecorator('config#noTypeField', { - initialValue: config.noTypeField, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.touch_mode')} - help={t('opt.touch_mode_help')} - > - {getFieldDecorator('config#touchMode', { - initialValue: config.touchMode, - valuePropName: 'checked' - })(<Switch />)} - </Form.Item> - <Form.Item - {...formItemLayout} - label={t('opt.sel_lang')} - help={t('opt.sel_lang_help')} - extra={ - <span style={{ color: '#c0392b' }}> - {t('opt.sel_lang_warning')} - </span> - } - > - {supportedLangs.map(lang => ( - <Form.Item key={lang} className="form-item-inline"> - {getFieldDecorator(`config#language#${lang}`, { - initialValue: config.language[lang], - valuePropName: 'checked' - })(<Checkbox>{t(`common:lang.${lang}`)}</Checkbox>)} - </Form.Item> - ))} - </Form.Item> - <Form.Item {...formItemLayout} label={t('opt.double_click_delay')}> - {getFieldDecorator('config#doubleClickDelay', { - initialValue: config.doubleClickDelay, - rules: [{ type: 'number', whitespace: true }] - })(<InputNumberGroup suffix={t('common:unit.ms')} />)} - </Form.Item> - <SearchMode {...this.props} mode="mode" /> - <SearchMode {...this.props} mode="pinMode" /> - <SearchMode {...this.props} mode="panelMode" /> - </Form> - ) - } -} - -export default Form.create<SearchModesProps>({ - onFieldsChange: updateConfigOrProfile as any -})(SearchModes) diff --git a/src/options/components/options/helpers.ts b/src/options/components/options/helpers.ts deleted file mode 100644 index ff958f796..000000000 --- a/src/options/components/options/helpers.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { updateConfig } from '@/_helpers/config-manager' -import { Props } from './typings' -import { updateProfile } from '@/_helpers/profile-manager' - -import set from 'lodash/set' -import get from 'lodash/get' - -import { message } from 'antd' - -export const formItemLayout = { - labelCol: { - xs: { span: 9 }, - sm: { span: 9 }, - lg: { span: 5 } - }, - wrapperCol: { - xs: { span: 15 }, - sm: { span: 15 }, - lg: { span: 8 } - } -} as const - -export const formSubItemLayout = { - labelCol: { span: 7 }, - wrapperCol: { span: 17 } -} as const - -export const formItemModalLayout = { - labelCol: { span: 7 }, - wrapperCol: { span: 17 } -} as const - -let updateConfigTimeout: any = null -let updateProfileTimeout: any = null - -export interface FormItemField { - dirty: boolean - name: string - touched: boolean - value: any - validating?: boolean - errors?: { - field: string - message: string - } -} - -export function updateConfigOrProfile( - props: Props, - fields: { [index: string]: FormItemField } -): void { - if (!fields) { - return - } - - const path = Object.keys(fields)[0] - if (!path) { - if (process.env.DEV_BUILD) { - console.error('empty field', fields) - } - return - } - - const field = fields[path] - - if (!field || field.dirty || field.validating || field.errors) { - return - } - - const key = (path.match(/^(config|profile)#/) || ['', ''])[1] - if (!key) { - if (process.env.DEV_BUILD) { - console.error('invalid field', fields) - } - return - } - - if (process.env.DEV_BUILD) { - const p = path.replace(/#/g, '.') - console.log(p, field.value) - const err = {} - if (get(props, p, err) === err) { - console.error('field not exist', fields) - } - } - - // antd form will swallow '.' path, use '#' instead - set(props, path.replace(/#/g, '.'), field.value) - - const delay = typeof field.value === 'number' ? 2000 : 1000 - - switch (key) { - case 'config': - clearTimeout(updateConfigTimeout) - updateConfigTimeout = setTimeout(() => { - updateConfig(props.config).catch(() => - message.error(props.t('msg_update_error')) - ) - }, delay) - break - case 'profile': - clearTimeout(updateProfileTimeout) - updateProfileTimeout = setTimeout(() => { - updateProfile(props.profile).catch(() => - message.error(props.t('msg_update_error')) - ) - }, delay) - break - default: - break - } -} - -/** - * Changes the contents of an array by moving an element to a different position - */ -export function arrayMove<T extends any[]>( - arr: T, - from: number, - to: number -): T { - arr.splice(to < 0 ? arr.length + to : to, 0, arr.splice(from, 1)[0]) - return arr -} diff --git a/src/options/components/options/typings.ts b/src/options/components/options/typings.ts deleted file mode 100644 index cbf7832f1..000000000 --- a/src/options/components/options/typings.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { AppConfig } from '@/app-config' -import { Profile } from '@/app-config/profiles' -import { i18n, TFunction } from 'i18next' - -export interface Props { - config: AppConfig - profile: Profile - t: TFunction - i18n: i18n -}
refactor
remove old entries
b0c35ea1e961730903e6a042edb9dc0e5f84bab3
2018-02-25 20:01:27
greenkeeper[bot]
chore(package): update fork-ts-checker-webpack-plugin to version 0.4.0
false
diff --git a/package.json b/package.json index d9d95b397..0be23803b 100644 --- a/package.json +++ b/package.json @@ -76,7 +76,7 @@ "dotenv": "5.0.0", "extract-text-webpack-plugin": "3.0.2", "file-loader": "1.1.9", - "fork-ts-checker-webpack-plugin": "^0.3.0", + "fork-ts-checker-webpack-plugin": "^0.4.0", "fs-extra": "^5.0.0", "generate-json-webpack-plugin": "^0.2.2", "html-webpack-plugin": "2.30.1",
chore
update fork-ts-checker-webpack-plugin to version 0.4.0
d5328e8955257cfe9d20a8d15189a702cfa39cab
2019-01-23 15:57:40
CRIMX
refactor(configs): new context menus configs
false
diff --git a/src/_locales/common/messages.json b/src/_locales/common/messages.json index 3a596d639..cda886a90 100644 --- a/src/_locales/common/messages.json +++ b/src/_locales/common/messages.json @@ -29,6 +29,11 @@ "zh_CN": "删除", "zh_TW": "删除" }, + "delete_confirm": { + "en": "Deleted item completely?", + "zh_CN": "确定完全删除该条目?", + "zh_TW": "確定完全刪除該條目?" + }, "edit": { "en": "Edit", "zh_CN": "编辑", @@ -69,6 +74,11 @@ "zh_CN": "最小", "zh_TW": "最小" }, + "name": { + "en": "Name", + "zh_CN": "名称", + "zh_TW": "名稱" + }, "none": { "en": "None", "zh_CN": "无", diff --git a/src/_locales/options/messages.json b/src/_locales/options/messages.json index ec5164c9f..5b55c2d61 100644 --- a/src/_locales/options/messages.json +++ b/src/_locales/options/messages.json @@ -234,6 +234,11 @@ "zh_CN": "英文自动发音", "zh_TW": "英文自動發音" }, + "opt_context_menus_add_rules": { + "en": "URL with %s in place of query.", + "zh_CN": "链接中的 %s 会被替换为选词。", + "zh_TW": "連結中的 %s 會被替換為選詞。" + }, "opt_dict_panel_font_size": { "en": "Font size for search reasults", "zh_CN": "词典内容字体大小", diff --git a/src/app-config/context-menus.ts b/src/app-config/context-menus.ts index 295f127b8..8d24eed13 100644 --- a/src/app-config/context-menus.ts +++ b/src/app-config/context-menus.ts @@ -1,3 +1,10 @@ +export interface CustomContextItem { + name: string + url: string +} + +export type ContextItem = string | CustomContextItem + export function getAllContextMenus () { const allContextMenus = { baidu_page_translate: 'x', @@ -31,5 +38,5 @@ export function getAllContextMenus () { // tslint:disable-next-line:no-unused-expression allContextMenus as { [id: string]: string } - return allContextMenus + return allContextMenus as typeof allContextMenus & { [index: string]: ContextItem } } diff --git a/src/app-config/index.ts b/src/app-config/index.ts index cb25cf156..5f021f063 100644 --- a/src/app-config/index.ts +++ b/src/app-config/index.ts @@ -17,8 +17,6 @@ export type DictConfigs = DeepReadonly<DictConfigsMutable> export type DictID = keyof DictConfigsMutable export type MtaAutoUnfold = _MtaAutoUnfold -export type ContextMenuDictID = keyof ReturnType<typeof getAllContextMenus> - export const enum TCDirection { center, top, @@ -251,7 +249,7 @@ function _getDefaultConfig () { 'google_search', 'google_page_translate', 'youdao_page_translate' - ] as ContextMenuDictID[], + ], all: getAllContextMenus() } } diff --git a/src/app-config/merge-config.ts b/src/app-config/merge-config.ts index fed92ed5d..5cd241825 100644 --- a/src/app-config/merge-config.ts +++ b/src/app-config/merge-config.ts @@ -113,8 +113,17 @@ export function mergeConfig (oldConfig: AppConfig, baseConfig?: AppConfig): AppC mergeSelectedContextMenus('contextMenus') - forEach(base.contextMenus.all, (dict, id) => { - mergeString(`contextMenus.all.${id}`) + forEach(oldConfig.contextMenus.all, (dict, id) => { + if (typeof dict === 'string') { + // default menus + if (base.contextMenus.all[id]) { + mergeString(`contextMenus.all.${id}`) + } + } else { + // custom menus + mergeString(`contextMenus.all.${id}.name`) + mergeString(`contextMenus.all.${id}.url`) + } }) // post-merge patch start diff --git a/src/background/context-menus.ts b/src/background/context-menus.ts index 838aefe11..499bb8015 100644 --- a/src/background/context-menus.ts +++ b/src/background/context-menus.ts @@ -1,6 +1,6 @@ import { message, openURL } from '@/_helpers/browser-api' import { MsgType } from '@/typings/message' -import { AppConfig, ContextMenuDictID } from '@/app-config' +import { AppConfig } from '@/app-config' import i18nLoader from '@/_helpers/i18n' import { TranslationFunction } from 'i18next' import contextLocles from '@/_locales/context' @@ -76,9 +76,12 @@ browser.contextMenus.onClicked.addListener(info => { default: getConfig() .then(config => { - const url = config.contextMenus.all[menuItemId] - if (url) { - openURL(url.replace('%s', selectionText)) + const item = config.contextMenus.all[menuItemId] + if (item) { + const url = typeof item === 'string' ? item : item.url + if (url) { + openURL(url.replace('%s', selectionText)) + } } }) } @@ -242,7 +245,7 @@ async function setContextMenus ( const containerCtx = new Set<browser.contextMenus.ContextType>(['selection']) const optionList: CreateMenuOptions[] = [] - let browserActionItems: ContextMenuDictID[] = [] + let browserActionItems: string[] = [] for (const id of contextMenus.selected) { let contexts: browser.contextMenus.ContextType[] switch (id) { @@ -267,7 +270,7 @@ async function setContextMenus ( } optionList.push({ id, - title: t(id), + title: getTitle(id), contexts }) } @@ -309,7 +312,7 @@ async function setContextMenus ( await createContextMenu({ id: id + '_ba', parentId: 'saladict_ba_container', - title: t(id), + title: getTitle(id), contexts: ['browser_action', 'page_action'] }) } @@ -317,7 +320,7 @@ async function setContextMenus ( for (const id of browserActionItems) { await createContextMenu({ id: id + '_ba', - title: t(id), + title: getTitle(id), contexts: ['browser_action', 'page_action'] }) } @@ -354,6 +357,11 @@ async function setContextMenus ( title: t('notebook_title'), contexts: ['browser_action'] }) + + function getTitle (id: string): string { + const item = contextMenus.all[id] + return !item || typeof item === 'string' ? t(id) : item.name + } } function createContextMenu (createProperties: CreateMenuOptions): Promise<void> {
refactor
new context menus configs
6582938c814a92b5ab36a8ae20b4ebdf6a77cc98
2020-05-01 09:05:34
crimx
test: update check-update
false
diff --git a/test/specs/_helpers/check-update.spec.ts b/test/specs/_helpers/check-update.spec.ts index 4e81ada46..1e7c31ca1 100644 --- a/test/specs/_helpers/check-update.spec.ts +++ b/test/specs/_helpers/check-update.spec.ts @@ -1,97 +1,49 @@ -import checkUpdate from '@/_helpers/check-update' +import { checkUpdate } from '@/_helpers/check-update' import _fetchMock, { FetchMock } from 'jest-fetch-mock' -import { browser } from '../../helper' +import getDefaultConfig from '@/app-config' const fetchMock = _fetchMock as FetchMock describe('Check Update', () => { beforeAll(() => { window.fetch = fetchMock - browser.runtime.getManifest.returns({ - version: '1.1.1' - }) }) + beforeEach(() => { fetchMock.resetMocks() + window.appConfig = getDefaultConfig() }) - it('Server Got Same Version (Not Available)', () => { - const responseObj = { tag_name: 'v1.1.1' } - const resolveSpy = jest.fn() - const rejectSpy = jest.fn() - const catchSpy = jest.fn() - - fetchMock.mockResponseOnce(JSON.stringify(responseObj)) - - const p = checkUpdate() - .then(resolveSpy, rejectSpy) - .catch(catchSpy) - .then(() => { - expect(resolveSpy).toHaveBeenCalledTimes(1) - expect(rejectSpy).toHaveBeenCalledTimes(0) - expect(catchSpy).toHaveBeenCalledTimes(0) - expect(resolveSpy).toBeCalledWith( - expect.objectContaining({ - isAvailable: false - }) - ) - }) - expect(fetchMock).toHaveBeenCalledTimes(1) - return p - }) - ;[ - ['Patch', 'v1.1.2', 'v1.1.0'], - ['Minor', 'v1.2.1', 'v1.0.1'], - ['Major', 'v2.1.1', 'v0.1.1'] - ].forEach(([title, newerVersion, olderVersion]) => { - describe(title, () => { - it('New Version Available', () => { - const responseObj = { tag_name: newerVersion } - const resolveSpy = jest.fn() - const rejectSpy = jest.fn() - const catchSpy = jest.fn() - - fetchMock.mockResponseOnce(JSON.stringify(responseObj)) - - const p = checkUpdate() - .then(resolveSpy, rejectSpy) - .catch(catchSpy) - .then(() => { - expect(resolveSpy).toHaveBeenCalledTimes(1) - expect(rejectSpy).toHaveBeenCalledTimes(0) - expect(catchSpy).toHaveBeenCalledTimes(0) - expect(resolveSpy).toBeCalledWith({ - isAvailable: true, - info: responseObj - }) - }) - expect(fetchMock).toHaveBeenCalledTimes(1) - return p - }) - - it('Server Got Older Version (Not Available)', () => { - const responseObj = { tag_name: olderVersion } - const resolveSpy = jest.fn() - const rejectSpy = jest.fn() - const catchSpy = jest.fn() - - fetchMock.mockResponseOnce(JSON.stringify(responseObj)) - - const p = checkUpdate() - .then(resolveSpy, rejectSpy) - .catch(catchSpy) - .then(() => { - expect(resolveSpy).toHaveBeenCalledTimes(1) - expect(rejectSpy).toHaveBeenCalledTimes(0) - expect(catchSpy).toHaveBeenCalledTimes(0) - expect(resolveSpy).toBeCalledWith( - expect.objectContaining({ - isAvailable: false - }) - ) - }) - expect(fetchMock).toHaveBeenCalledTimes(1) - return p + const tests = [ + ['Same', 'v1.1.1', 'v1.1.1', 0], + ['Newer Patch', 'v1.1.2', 'v1.1.0', 1], + ['Newer Minor', 'v1.2.1', 'v1.0.1', 2], + ['Newer Major', 'v2.1.1', 'v0.1.1', 3], + ['Older Patch', 'v1.1.0', 'v1.1.2', -1], + ['Older Minor', 'v1.0.1', 'v1.2.1', -2], + ['Older Major', 'v0.1.1', 'v2.1.1', -3] + ] as const + + tests.forEach(([title, newerVersion, olderVersion, diff]) => { + it(title, async () => { + const responseObj = { version: newerVersion } + const resolveSpy = jest.fn() + const rejectSpy = jest.fn() + const catchSpy = jest.fn() + + fetchMock.mockResponseOnce(JSON.stringify(responseObj)) + + await checkUpdate(olderVersion.slice(1)) + .then(resolveSpy, rejectSpy) + .catch(catchSpy) + + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(resolveSpy).toHaveBeenCalledTimes(1) + expect(rejectSpy).toHaveBeenCalledTimes(0) + expect(catchSpy).toHaveBeenCalledTimes(0) + expect(resolveSpy).toBeCalledWith({ + diff, + data: responseObj }) }) })
test
update check-update
9dfd9064be803a261544315a027282d3f456609d
2019-08-15 17:39:54
crimx
fix(components): add appear styles for shadow portal
false
diff --git a/src/components/ShadowPortal/ShadowPortal.scss b/src/components/ShadowPortal/ShadowPortal.scss index 752b62da7..bb2da464a 100644 --- a/src/components/ShadowPortal/ShadowPortal.scss +++ b/src/components/ShadowPortal/ShadowPortal.scss @@ -1,6 +1,8 @@ +.shadowPortal-appear, .shadowPortal-enter { opacity: 0; } +.shadowPortal-appear-active, .shadowPortal-enter-active { opacity: 1; transition: opacity 0.4s;
fix
add appear styles for shadow portal
70cb3819d4352a3b1e69f15fba40a0ccd21ad479
2020-07-11 11:42:52
crimx
refactor: import sass global in webpack
false
diff --git a/.neutrinorc.js b/.neutrinorc.js index 481b9f0f2..5dbb66df0 100644 --- a/.neutrinorc.js +++ b/.neutrinorc.js @@ -120,6 +120,19 @@ module.exports = { { loader: 'sass-loader', useId: 'scss' + }, + { + loader: 'sass-resources-loader', + useId: 'sass-resources', + options: { + sourceMap: process.env.NODE_ENV !== 'production', + resources: [ + path.resolve(__dirname, 'src/_sass_shared/_global/_interfaces.scss'), + path.resolve(__dirname, 'src/_sass_shared/_global/_z-indices.scss'), + path.resolve(__dirname, 'src/_sass_shared/_global/_variables.scss'), + path.resolve(__dirname, 'src/_sass_shared/_global/_mixins.scss'), + ] + } } ] }, diff --git a/package.json b/package.json index e0b3b3c7e..1e13c3721 100644 --- a/package.json +++ b/package.json @@ -167,6 +167,7 @@ "raw-loader": "^3.1.0", "react-docgen-typescript-loader": "^3.1.0", "sass-loader": "^7.1.0", + "sass-resources-loader": "^2.0.3", "socks-proxy-agent": "^5.0.0", "standard-version": "^6.0.1", "storybook-addon-jsx": "7.1.15", diff --git a/src/_helpers/storybook.tsx b/src/_helpers/storybook.tsx index 3ca4f5518..7f9620436 100644 --- a/src/_helpers/storybook.tsx +++ b/src/_helpers/storybook.tsx @@ -117,8 +117,8 @@ export function withSaladictPanel(options: WithSaladictPanelOptions) { return ( <root.div style={{ width, margin: '10px auto' }}> - <style>{require('@/_sass_global/_reset.scss').toString()}</style> - <style>{require('@/_sass_global/_theme.scss').toString()}</style> + <style>{require('@/_sass_shared/_reset.scss').toString()}</style> + <style>{require('@/_sass_shared/_theme.scss').toString()}</style> <div className={classNames('dictPanel-Root', 'saladict-theme', { isAnimate: withAnimation, diff --git a/src/_sass_global/_fancy-scrollbar.scss b/src/_sass_shared/_fancy-scrollbar.scss similarity index 100% rename from src/_sass_global/_fancy-scrollbar.scss rename to src/_sass_shared/_fancy-scrollbar.scss diff --git a/src/_sass_global/_interfaces.scss b/src/_sass_shared/_global/_interfaces.scss similarity index 100% rename from src/_sass_global/_interfaces.scss rename to src/_sass_shared/_global/_interfaces.scss diff --git a/src/_sass_global/_variables.scss b/src/_sass_shared/_global/_variables.scss similarity index 100% rename from src/_sass_global/_variables.scss rename to src/_sass_shared/_global/_variables.scss diff --git a/src/_sass_global/_z-indices.scss b/src/_sass_shared/_global/_z-indices.scss similarity index 100% rename from src/_sass_global/_z-indices.scss rename to src/_sass_shared/_global/_z-indices.scss diff --git a/src/_sass_global/_reset.scss b/src/_sass_shared/_reset.scss similarity index 100% rename from src/_sass_global/_reset.scss rename to src/_sass_shared/_reset.scss diff --git a/src/_sass_global/_theme.scss b/src/_sass_shared/_theme.scss similarity index 100% rename from src/_sass_global/_theme.scss rename to src/_sass_shared/_theme.scss diff --git a/src/audio-control/audio-control.scss b/src/audio-control/audio-control.scss index c4b59db1b..96c92df83 100644 --- a/src/audio-control/audio-control.scss +++ b/src/audio-control/audio-control.scss @@ -6,5 +6,5 @@ body { padding: 0; } -@import '@/_sass_global/_theme.scss'; +@import '@/_sass_shared/_theme.scss'; @import '@/components/Waveform/Waveform.scss'; diff --git a/src/components/HoverBox/HoverBox.scss b/src/components/HoverBox/HoverBox.scss index a3c204dd3..eb8dd6308 100644 --- a/src/components/HoverBox/HoverBox.scss +++ b/src/components/HoverBox/HoverBox.scss @@ -1,4 +1,3 @@ -@import '@/_sass_global/_z-indices.scss'; @import '@/components/FloatBox/FloatBox.scss'; .hoverBox-Container { diff --git a/src/components/dictionaries/naver/_style.shadow.scss b/src/components/dictionaries/naver/_style.shadow.scss index 8c693acbe..b347dd404 100644 --- a/src/components/dictionaries/naver/_style.shadow.scss +++ b/src/components/dictionaries/naver/_style.shadow.scss @@ -1,4 +1,4 @@ -@import '@/_sass_global/_reset.scss'; +@import '@/_sass_shared/_reset.scss'; .dictNaver-Entry-zh { .info_box { diff --git a/src/components/dictionaries/weblio/_style.shadow.scss b/src/components/dictionaries/weblio/_style.shadow.scss index e10cc5c85..be794a348 100644 --- a/src/components/dictionaries/weblio/_style.shadow.scss +++ b/src/components/dictionaries/weblio/_style.shadow.scss @@ -1,4 +1,4 @@ -@import '@/_sass_global/_reset.scss'; +@import '@/_sass_shared/_reset.scss'; @import '@/components/EntryBox/EntryBox.scss'; .dictWeblio-Entry > .entryBox { diff --git a/src/components/dictionaries/wikipedia/_style.shadow.scss b/src/components/dictionaries/wikipedia/_style.shadow.scss index b8436fd23..4882cf55e 100644 --- a/src/components/dictionaries/wikipedia/_style.shadow.scss +++ b/src/components/dictionaries/wikipedia/_style.shadow.scss @@ -1,4 +1,4 @@ -@import '@/_sass_global/_reset.scss'; +@import '@/_sass_shared/_reset.scss'; .dictWikipedia-LangSelectorBtn { margin: 0.2em 0 1em; diff --git a/src/content/components/DictItem/DictItemContent.shadow.scss b/src/content/components/DictItem/DictItemContent.shadow.scss index ddb6595de..d606b5049 100644 --- a/src/content/components/DictItem/DictItemContent.shadow.scss +++ b/src/content/components/DictItem/DictItemContent.shadow.scss @@ -1,4 +1,4 @@ -@import '@/_sass_global/_reset.scss'; +@import '@/_sass_shared/_reset.scss'; @import '@/components/Speaker/Speaker.scss'; @import '@/components/EntryBox/EntryBox.scss'; diff --git a/src/content/components/DictPanel/DictPanel.scss b/src/content/components/DictPanel/DictPanel.scss index f3674f089..afd85e1b9 100644 --- a/src/content/components/DictPanel/DictPanel.scss +++ b/src/content/components/DictPanel/DictPanel.scss @@ -1,5 +1,4 @@ -@import '@/_sass_global/_z-indices.scss'; -@import '@/_sass_global/_theme.scss'; +@import '@/_sass_shared/_theme.scss'; .dictPanel-FloatBox-Container { position: relative; @@ -32,7 +31,7 @@ -webkit-overflow-scrolling: touch; } -@import '@/_sass_global/_fancy-scrollbar.scss'; +@import '@/_sass_shared/_fancy-scrollbar.scss'; @import '../MenuBar/MenuBar.scss'; @import '../MtaBox/MtaBox.scss'; diff --git a/src/content/components/DictPanel/DictPanel.shadow.scss b/src/content/components/DictPanel/DictPanel.shadow.scss index 5917f90f4..537c4cb4b 100644 --- a/src/content/components/DictPanel/DictPanel.shadow.scss +++ b/src/content/components/DictPanel/DictPanel.shadow.scss @@ -1,4 +1,3 @@ -@import '@/_sass_global/_z-indices.scss'; @import '@/components/ShadowPortal/ShadowPortal.scss'; @import './DictPanel.scss'; diff --git a/src/content/components/SaladBowl/SaladBowl.shadow.scss b/src/content/components/SaladBowl/SaladBowl.shadow.scss index 947861bee..3231fd2ba 100644 --- a/src/content/components/SaladBowl/SaladBowl.shadow.scss +++ b/src/content/components/SaladBowl/SaladBowl.shadow.scss @@ -1,4 +1,3 @@ -@import '../../../_sass_global/z-indices'; $bowl-width: 30px; .saladbowl { diff --git a/src/content/components/WordEditor/WordEditor.scss b/src/content/components/WordEditor/WordEditor.scss index a0e6a080c..ead47262e 100644 --- a/src/content/components/WordEditor/WordEditor.scss +++ b/src/content/components/WordEditor/WordEditor.scss @@ -1,10 +1,7 @@ /*-----------------------------------------------*\ Variables \*-----------------------------------------------*/ -@import '@/_sass_global/_variables.scss'; -@import '@/_sass_global/_z-indices.scss'; -@import '@/_sass_global/_interfaces.scss'; -@import '@/_sass_global/_theme.scss'; +@import '@/_sass_shared/_theme.scss'; /*-----------------------------------------------*\ Libs diff --git a/src/content/components/WordEditor/WordEditorPanel.scss b/src/content/components/WordEditor/WordEditorPanel.scss index 42cfac374..23e73df4b 100644 --- a/src/content/components/WordEditor/WordEditorPanel.scss +++ b/src/content/components/WordEditor/WordEditorPanel.scss @@ -1,5 +1,4 @@ -@import '../../../_sass_global/z-indices'; -@import '@/_sass_global/_fancy-scrollbar.scss'; +@import '@/_sass_shared/_fancy-scrollbar.scss'; .wordEditorPanel-Background { position: fixed; diff --git a/src/content/components/WordEditor/WordEditorPanel.stories.tsx b/src/content/components/WordEditor/WordEditorPanel.stories.tsx index 76098d7df..da0c94569 100644 --- a/src/content/components/WordEditor/WordEditorPanel.stories.tsx +++ b/src/content/components/WordEditor/WordEditorPanel.stories.tsx @@ -75,7 +75,7 @@ storiesOf('Content Scripts|WordEditor', module) { decorators: [ withLocalStyle(require('./WordEditorPanel.scss')), - withLocalStyle(require('@/_sass_global/_theme.scss')) + withLocalStyle(require('@/_sass_shared/_theme.scss')) ], jsx: { skip: 1 } } diff --git a/src/options/components/EntrySideBar/_style.scss b/src/options/components/EntrySideBar/_style.scss index 9336b972b..c15e080f1 100644 --- a/src/options/components/EntrySideBar/_style.scss +++ b/src/options/components/EntrySideBar/_style.scss @@ -1,4 +1,4 @@ -@import '@/_sass_global/_fancy-scrollbar.scss'; +@import '@/_sass_shared/_fancy-scrollbar.scss'; .entry-sidebar { height: 100vh; diff --git a/src/options/components/Header/HeadInfo/_style.scss b/src/options/components/Header/HeadInfo/_style.scss index d1e55c3e8..473aedf84 100644 --- a/src/options/components/Header/HeadInfo/_style.scss +++ b/src/options/components/Header/HeadInfo/_style.scss @@ -1,5 +1,3 @@ -@import '@/_sass_global/_z-indices.scss'; - .head-info { align-self: flex-end; display: flex; diff --git a/src/popup/_style.scss b/src/popup/_style.scss index 08f435972..a87f32bfe 100644 --- a/src/popup/_style.scss +++ b/src/popup/_style.scss @@ -1,5 +1,4 @@ -@import '@/_sass_global/_z-indices.scss'; -@import '@/_sass_global/_theme.scss'; +@import '@/_sass_shared/_theme.scss'; /*------------------------------------*\ Base diff --git a/yarn.lock b/yarn.lock index 48dbc762f..34d551838 100644 --- a/yarn.lock +++ b/yarn.lock @@ -41,6 +41,22 @@ lodash "^4.17.15" resize-observer-polyfill "^1.5.0" +"@babel/cli@^7.4.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/cli/-/cli-7.10.4.tgz#ba38ad6d0b4b772a67b106934b7c33d656031896" + integrity sha512-xX99K4V1BzGJdQANK5cwK+EpF1vP9gvqhn+iWvG+TubCjecplW7RSQimJ2jcCvu6fnK5pY6mZMdu6EWTj32QVA== + dependencies: + commander "^4.0.1" + convert-source-map "^1.1.0" + fs-readdir-recursive "^1.1.0" + glob "^7.0.0" + lodash "^4.17.13" + make-dir "^2.1.0" + slash "^2.0.0" + source-map "^0.5.0" + optionalDependencies: + chokidar "^2.1.8" + "@babel/[email protected]": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" @@ -337,7 +353,7 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/parser@^7.1.0", "@babel/parser@^7.10.4", "@babel/parser@^7.4.3", "@babel/parser@^7.9.0": +"@babel/parser@^7.1.0", "@babel/parser@^7.10.4", "@babel/parser@^7.4.3", "@babel/parser@^7.7.0", "@babel/parser@^7.9.0": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.4.tgz#9eedf27e1998d87739fb5028a5120557c06a1a64" integrity sha512-8jHII4hf+YVDsskTF6WuMB3X4Eh+PsUkC2ljq22so5rHvH+T8BzyL94VOdyFLNR8tBSVXOTbNHOKpR4TfRxVtA== @@ -1161,7 +1177,7 @@ "@babel/parser" "^7.10.4" "@babel/types" "^7.10.4" -"@babel/traverse@^7.1.0", "@babel/traverse@^7.10.4", "@babel/traverse@^7.4.3", "@babel/traverse@^7.9.0": +"@babel/traverse@^7.1.0", "@babel/traverse@^7.10.4", "@babel/traverse@^7.4.3", "@babel/traverse@^7.7.0", "@babel/traverse@^7.9.0": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.10.4.tgz#e642e5395a3b09cc95c8e74a27432b484b697818" integrity sha512-aSy7p5THgSYm4YyxNGz6jZpXf+Ok40QF3aA2LyIONkDHpAcJzDUqlCKXv6peqYUs2gmic849C/t2HKw2a2K20Q== @@ -1176,7 +1192,7 @@ globals "^11.1.0" lodash "^4.17.13" -"@babel/types@^7.0.0", "@babel/types@^7.10.4", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.9.0": +"@babel/types@^7.0.0", "@babel/types@^7.10.4", "@babel/types@^7.3.0", "@babel/types@^7.3.3", "@babel/types@^7.4.0", "@babel/types@^7.4.4", "@babel/types@^7.7.0", "@babel/types@^7.9.0": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.10.4.tgz#369517188352e18219981efd156bfdb199fff1ee" integrity sha512-UTCFOxC3FsFHb7lkRMVvgLzaRVamXuAs2Tz4wajva4WxtVY82eZeaUBtC2Zt95FU9TiznuC0Zk35tsim8jeVpg== @@ -3596,6 +3612,11 @@ async@^2.1.4, async@^2.6.2, async@^2.6.3: dependencies: lodash "^4.17.14" +async@^3.0.1: + version "3.2.0" + resolved "https://registry.yarnpkg.com/async/-/async-3.2.0.tgz#b3a2685c5ebb641d3de02d161002c60fc9f85720" + integrity sha512-TR2mEZFVOj2pLStYxLht7TyfuRzaydfpxr3k9RpHIzMgw7A64dzsdqCxH1WJyQdoe8T10nDXd9wnEigmiuHIZw== + asynckit@^0.4.0: version "0.4.0" resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" @@ -3672,6 +3693,18 @@ babel-core@^7.0.0-bridge.0: resolved "https://registry.yarnpkg.com/babel-core/-/babel-core-7.0.0-bridge.0.tgz#95a492ddd90f9b4e9a4a1da14eb335b87b634ece" integrity sha512-poPX9mZH/5CSanm50Q+1toVci6pv5KSRv/5TWCwtzQS5XEwn40BcCrgIeMFWP9CKKIniKXNxoIOnOq4VVlGXhg== +babel-eslint@^10.0.2: + version "10.1.0" + resolved "https://registry.yarnpkg.com/babel-eslint/-/babel-eslint-10.1.0.tgz#6968e568a910b78fb3779cdd8b6ac2f479943232" + integrity sha512-ifWaTHQ0ce+448CYop8AdrQiBsGrnC+bMgfyKFdi6EsPLTAWG+QfyDeM6OH+FmWnKvEq5NnBMLvlBUPKQZoDSg== + dependencies: + "@babel/code-frame" "^7.0.0" + "@babel/parser" "^7.7.0" + "@babel/traverse" "^7.7.0" + "@babel/types" "^7.7.0" + eslint-visitor-keys "^1.0.0" + resolve "^1.12.0" + babel-helper-evaluate-path@^0.5.0: version "0.5.0" resolved "https://registry.yarnpkg.com/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz#a62fa9c4e64ff7ea5cea9353174ef023a900a67c" @@ -4961,7 +4994,7 @@ commander@^2.18.0, commander@^2.19.0, commander@^2.20.0: resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== -commander@^4.1.1: +commander@^4.0.1, commander@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068" integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA== @@ -5320,7 +5353,7 @@ [email protected]: meow "^4.0.0" q "^1.5.1" -convert-source-map@^1.4.0, convert-source-map@^1.5.0, convert-source-map@^1.5.1, convert-source-map@^1.7.0: +convert-source-map@^1.1.0, convert-source-map@^1.4.0, convert-source-map@^1.5.0, convert-source-map@^1.5.1, convert-source-map@^1.7.0: version "1.7.0" resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== @@ -6645,7 +6678,7 @@ eslint-utils@^2.0.0: dependencies: eslint-visitor-keys "^1.1.0" -eslint-visitor-keys@^1.1.0: +eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== @@ -7407,6 +7440,11 @@ fs-extra@^9.0.0: jsonfile "^6.0.1" universalify "^1.0.0" +fs-readdir-recursive@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz#e32fc030a2ccee44a6b5371308da54be0b397d27" + integrity sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA== + fs-write-stream-atomic@^1.0.8: version "1.0.10" resolved "https://registry.yarnpkg.com/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz#b47df53493ef911df75731e70a9ded0189db40c9" @@ -9782,7 +9820,7 @@ [email protected]: emojis-list "^2.0.0" json5 "^1.0.1" -loader-utils@^1.0.0, loader-utils@^1.0.1, loader-utils@^1.0.2, loader-utils@^1.1.0, loader-utils@^1.2.3, loader-utils@^1.4.0: +loader-utils@^1.0.0, loader-utils@^1.0.1, loader-utils@^1.0.2, loader-utils@^1.0.4, loader-utils@^1.1.0, loader-utils@^1.2.3, loader-utils@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.0.tgz#c579b5e34cb34b1a74edc6c1fb36bfa371d5a613" integrity sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA== @@ -13396,6 +13434,19 @@ sass-loader@^7.1.0: pify "^4.0.1" semver "^6.3.0" +sass-resources-loader@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/sass-resources-loader/-/sass-resources-loader-2.0.3.tgz#585636b357d9c27d02fa359c175fafe3e3d66ce4" + integrity sha512-kYujKXFPZvh5QUT+0DO35P93G6GeIRMP4c941Ilbvey5lo+iICFs2H4hP2CFHl68Llg7h2iXqe0RQpDoUzjUSw== + dependencies: + "@babel/cli" "^7.4.4" + "@babel/preset-env" "^7.4.5" + async "^3.0.1" + babel-eslint "^10.0.2" + chalk "^2.4.2" + glob "^7.1.1" + loader-utils "^1.0.4" + sax@^1.2.4, sax@~1.2.4: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"
refactor
import sass global in webpack
1970556656c3b2fa919cea2efa0ec6ab72806c71
2019-05-30 13:48:41
CRIMX
fix: ignore esc key on standalone panel
false
diff --git a/src/content/redux/modules/widget.ts b/src/content/redux/modules/widget.ts index 055aba0a7..ab5c367bf 100644 --- a/src/content/redux/modules/widget.ts +++ b/src/content/redux/modules/widget.ts @@ -559,7 +559,7 @@ export function mouseOnBowl (payload: boolean): DispatcherThunk { export function closePanel (): DispatcherThunk { return (dispatch, getState) => { - if (!isSaladictOptionsPage) { + if (!isSaladictOptionsPage && !isStandalonePage) { dispatch(restoreWidget()) dispatch(restoreDicts()) }
fix
ignore esc key on standalone panel
3b877a1356fa80936f227d1621855f2de1ea7683
2020-04-07 20:14:10
crimx
refactor(options): add panel preview
false
diff --git a/src/options/components/BtnPreview/_style.scss b/src/options/components/BtnPreview/_style.scss index af568c62d..95230f904 100644 --- a/src/options/components/BtnPreview/_style.scss +++ b/src/options/components/BtnPreview/_style.scss @@ -8,3 +8,19 @@ box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05); } + +.btn-preview-fade-enter { + opacity: 0; + transition: opacity 0.5s; +} + +.btn-preview-fade-enter-active, +.btn-preview-fade-exit { + opacity: 1; + transition: opacity 0.5s; +} + +.btn-preview-fade-exit-active { + opacity: 0; + transition: opacity 0.5s; +} diff --git a/src/options/components/BtnPreview/index.tsx b/src/options/components/BtnPreview/index.tsx index a75bf96bf..2d53ba52e 100644 --- a/src/options/components/BtnPreview/index.tsx +++ b/src/options/components/BtnPreview/index.tsx @@ -1,27 +1,64 @@ import React, { FC } from 'react' +import { useSelector } from 'react-redux' +import { CSSTransition } from 'react-transition-group' import { Button } from 'antd' import { useTranslate } from '@/_helpers/i18n' +import { message } from '@/_helpers/browser-api' +import { newWord } from '@/_helpers/record-manager' +import { getWordOfTheDay } from '@/_helpers/wordoftheday' +import { StoreState } from '@/content/redux/modules' import { PreviewIcon } from './PreviewIcon' import './_style.scss' -export interface BtnPreviewProps { - show: boolean - onClick: () => void -} - -export const BtnPreview: FC<BtnPreviewProps> = () => { +export const BtnPreview: FC = () => { const { t } = useTranslate('options') + const show = !useSelector(pickIsShowDictPanel) return ( - <Button - className="btn-preview" - title={t('previewPanel')} - shape="circle" - size="large" - icon={<PreviewIcon />} - /> + <CSSTransition + classNames="btn-preview-fade" + mountOnEnter + unmountOnExit + appear + in={show} + timeout={500} + > + <div> + <Button + className="btn-preview" + title={t('previewPanel')} + shape="circle" + size="large" + icon={<PreviewIcon />} + onClick={openDictPanel} + /> + </div> + </CSSTransition> ) } export const BtnPreviewMemo = React.memo(BtnPreview) + +function pickIsShowDictPanel(state: StoreState): boolean { + return state.isShowDictPanel +} + +async function openDictPanel(e: React.MouseEvent<HTMLButtonElement>) { + const { x, width } = e.currentTarget.getBoundingClientRect() + message.self.send({ + type: 'SELECTION', + payload: { + word: newWord({ text: await getWordOfTheDay() }), + self: true, // selection inside dict panel is always avaliable + instant: true, + mouseX: x + width, + mouseY: 80, + dbClick: true, + shiftKey: true, + ctrlKey: true, + metaKey: true, + force: true + } + }) +} diff --git a/src/options/components/MainEntry.tsx b/src/options/components/MainEntry.tsx index 60da435c2..e83ec01a2 100644 --- a/src/options/components/MainEntry.tsx +++ b/src/options/components/MainEntry.tsx @@ -10,9 +10,6 @@ import { import { reportGA } from '@/_helpers/analytics' import { ErrorBoundary } from '@/components/ErrorBoundary' import { useTranslate } from '@/_helpers/i18n' -import { message } from '@/_helpers/browser-api' -import { newWord } from '@/_helpers/record-manager' -import { getWordOfTheDay } from '@/_helpers/wordoftheday' import { EntrySideBarMemo } from './EntrySideBar' import { HeaderMemo } from './Header' import { EntryError } from './EntryError' @@ -82,7 +79,7 @@ export const MainEntry: FC = () => { </Layout> </Col> </Row> - <BtnPreviewMemo show={true} onClick={openDictPanel} /> + <BtnPreviewMemo /> </Layout> ) } @@ -90,21 +87,3 @@ export const MainEntry: FC = () => { function getEntry(): string { return new URL(document.URL).searchParams.get('menuselected') || 'General' } - -async function openDictPanel() { - message.self.send({ - type: 'SELECTION', - payload: { - word: newWord({ text: await getWordOfTheDay() }), - self: true, // selection inside dict panel is always avaliable - instant: true, - mouseX: window.innerWidth - 250, - mouseY: 80, - dbClick: true, - shiftKey: true, - ctrlKey: true, - metaKey: true, - force: true - } - }) -}
refactor
add panel preview
5c3c7dd6dbb54fd1655e20b680ed73131a11d564
2018-10-11 16:40:48
CRIMX
refactor(options): update wording
false
diff --git a/src/_locales/options/messages.json b/src/_locales/options/messages.json index 41806d652..d3dc19bb1 100644 --- a/src/_locales/options/messages.json +++ b/src/_locales/options/messages.json @@ -360,9 +360,9 @@ "zh_TW": "按住Ctrl/⌘" }, "mode_description": { - "en": "When a text selection is made: <ul><li><strong>'Show Icon'</strong>, a cute little icon pops up nearby the cursor; </li><li><strong>'Directly Search'</strong>, the dictionary panel shows up directly; </li><li><strong>'Double Click'</strong>, dictionary panel shows up after double click selection; </li><li><strong>'Hold Ctrl/⌘'</strong>, the <kbd>Ctrl</kbd> or <kbd>Command ⌘</kbd> key must be pressed when the selection is made; </li><li><strong>'Instant Capture'</strong>, selection is automatically made near by the cursor. </li></ul>", - "zh_CN": "当用鼠标在网页上选择了一段文本:<ul><li><strong>“显示图标”</strong>会先在鼠标附近显示一个图标,鼠标移上去后才显示词典面板;</li><li><strong>“直接搜索”</strong>则不显示图标,直接显示词典面板;</li><li><strong>“双击搜索”</strong>双击选择文本之后直接显示词典面板;</li><li><strong>“按住 Ctrl/⌘”</strong>在选择文本时需同时按住<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>键才显示词典面板;</li><li><strong>“鼠标悬浮取词”</strong>会自动选取鼠标下发的单词,可配合快捷键开启关闭。</li></ul>", - "zh_TW": "當使用滑鼠在網頁上選擇一段句子或單字:<ul><li><strong>「顯示圖案」</strong>會先在滑鼠附近顯示一個圖案,滑鼠移動到圖案,會顯示出字典的視窗介面;</li><li><strong>「直接搜尋」</strong>則不會顯示圖案,直接顯示字典視窗介面;</li><li><strong>「滑鼠雙點擊」</strong>滑鼠雙點擊所選擇的句子或單字後,會直接顯示字典視窗介面;</li><li><strong>「按住 Ctrl/⌘」</strong>在選擇句子或單字時,需同時按住<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>鍵,才顯示字典視窗介面;</li><li><strong>「滑鼠懸浮取詞」</strong>會自動選取滑鼠下方的單字,可配合快捷鍵啓用與關閉。</li></ul>" + "en": "When a text selection is made:", + "zh_CN": "当用鼠标在网页上选择了一段文本:", + "zh_TW": "當使用滑鼠在網頁上選擇一段句子或單字:" }, "mode_direct": { "en": "Direct Search", @@ -379,6 +379,11 @@ "zh_CN": "双击间隔", "zh_TW": "滑鼠雙點擊間隔" }, + "mode_explain": { + "en": "<ul><li><strong>'Show Icon'</strong>, a cute little icon pops up nearby the cursor; </li><li><strong>'Directly Search'</strong>, the dictionary panel shows up directly; </li><li><strong>'Double Click'</strong>, dictionary panel shows up after double click selection; </li><li><strong>'Hold Ctrl/⌘'</strong>, the <kbd>Ctrl</kbd> or <kbd>Command ⌘</kbd> key must be pressed when the selection is made; </li><li><strong>'Instant Capture'</strong>, selection is automatically made near by the cursor. </li></ul>", + "zh_CN": "<ul><li><strong>“显示图标”</strong>会先在鼠标附近显示一个图标,鼠标移上去后才显示词典面板;</li><li><strong>“直接搜索”</strong>则不显示图标,直接显示词典面板;</li><li><strong>“双击搜索”</strong>双击选择文本之后直接显示词典面板;</li><li><strong>“按住 Ctrl/⌘”</strong>在选择文本时需同时按住<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>键才显示词典面板;</li><li><strong>“鼠标悬浮取词”</strong>会自动选取鼠标下发的单词,可配合快捷键开启关闭。</li></ul>", + "zh_TW": "<ul><li><strong>「顯示圖案」</strong>會先在滑鼠附近顯示一個圖案,滑鼠移動到圖案,會顯示出字典的視窗介面;</li><li><strong>「直接搜尋」</strong>則不會顯示圖案,直接顯示字典視窗介面;</li><li><strong>「滑鼠雙點擊」</strong>滑鼠雙點擊所選擇的句子或單字後,會直接顯示字典視窗介面;</li><li><strong>「按住 Ctrl/⌘」</strong>在選擇句子或單字時,需同時按住<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>鍵,才顯示字典視窗介面;</li><li><strong>「滑鼠懸浮取詞」</strong>會自動選取滑鼠下方的單字,可配合快捷鍵啓用與關閉。</li></ul>" + }, "mode_icon": { "en": "Show Icon", "zh_CN": "显示图标", @@ -470,9 +475,9 @@ "zh_TW": "添加生字" }, "panelmode_description": { - "en": "Inside dict panel. See 'Search Mode' above.", - "zh_CN": "查词面板内部的查词模式。参见上方“查词模式”。", - "zh_TW": "字典視窗內部的查字模式。參見上方「查字模式」。" + "en": "Inside dict panel.", + "zh_CN": "查词面板内部的查词模式。", + "zh_TW": "字典視窗內部的查字模式。" }, "panelmode_title": { "en": "Panel Mode", @@ -485,9 +490,9 @@ "zh_TW": "使用本應用程式瀏覽 PDF" }, "pinmode_description": { - "en": "When Dictionary Panel is pinned. See 'Search Mode' above.", - "zh_CN": "当面板被钉住时的查词模式。参见上方“查词模式”。", - "zh_TW": "當視窗被釘住時的查字模式。參見上方「查字模式」。" + "en": "When Dictionary Panel is pinned.", + "zh_CN": "当面板被钉住时的查词模式。", + "zh_TW": "當視窗被釘住時的查字模式。" }, "pinmode_title": { "en": "Pinned Mode", @@ -590,9 +595,9 @@ "zh_TW": "開啟" }, "triple_ctrl_description": { - "en": "Press <kbd>Ctrl</kbd> or <kbd>Command ⌘</kbd> key three times to summon the dictionary panel. Preloaded content will be inserted into input box. Enable auto search to search as soon as the panel shows up.", - "zh_CN": "连续按三次<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>键将弹出词典界面。选择预先加载内容会显示在输入框里。启动自动查词将在面板出现之后自动开始查词。", - "zh_TW": "連續按三次<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>鍵,將會彈出字典視窗介面。選擇預先下載的內容,會顯示在輸入框裡。啟動自動查字功能,字典視窗介面會出現,此時,會自動開始查尋單字。" + "en": "Press <kbd>Ctrl</kbd> or <kbd>Command ⌘</kbd> key three times (or with browser shortkey) to summon the dictionary panel. <br>Preloaded content will be inserted into input box. Enable auto search to search as soon as the panel shows up.", + "zh_CN": "连续按三次<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>键(或设置浏览器快捷键)将弹出词典界面。<br>选择预先加载内容会显示在输入框里。启动自动查词将在面板出现之后自动开始查词。<br>若打开为新窗口可额外设置划词模式,或不对主页面划词响应(做单独词典窗口用)。", + "zh_TW": "連續按三次<kbd>Ctrl</kbd>或者<kbd>Command ⌘</kbd>鍵(或設定瀏覽器快捷鍵),將會彈出字典視窗介面。<br>選擇預先下載的內容,會顯示在輸入框裡。啟動自動查字功能,字典視窗介面會出現,此時,會自動開始查尋單字。<br>若開啟為新視窗可額外設定劃詞模式,或不對主頁面劃詞響應(做單獨字典視窗用)。" }, "triple_ctrl_height": { "en": "Window Height", diff --git a/src/options/OptMode.vue b/src/options/OptMode.vue index 5252c1a20..915084032 100644 --- a/src/options/OptMode.vue +++ b/src/options/OptMode.vue @@ -43,7 +43,7 @@ </div> </div> <div class="opt-item__description-wrap"> - <p class="opt-item__description" v-html="$t('opt:mode_description')"></p> + <p class="opt-item__description" v-html="$t('opt:mode_description') + $t('opt:mode_explain')"></p> </div> </div><!-- 查词模式--> </template> diff --git a/src/options/OptPanelMode.vue b/src/options/OptPanelMode.vue index fa7f517a8..078c6e9db 100644 --- a/src/options/OptPanelMode.vue +++ b/src/options/OptPanelMode.vue @@ -40,7 +40,7 @@ </div> </div> <div class="opt-item__description-wrap"> - <p class="opt-item__description" v-html="$t('opt:panelmode_description')"></p> + <p class="opt-item__description" v-html="$t('opt:panelmode_description') + $t('opt:mode_explain')"></p> </div> </div><!-- 面板查词--> </template> diff --git a/src/options/OptPinMode.vue b/src/options/OptPinMode.vue index 38966e55e..4bff628ca 100644 --- a/src/options/OptPinMode.vue +++ b/src/options/OptPinMode.vue @@ -40,7 +40,7 @@ </div> </div> <div class="opt-item__description-wrap"> - <p class="opt-item__description" v-html="$t('opt:pinmode_description')"></p> + <p class="opt-item__description" v-html="$t('opt:pinmode_description') + $t('opt:mode_explain')"></p> </div> </div><!-- 钉住查词--> </template> diff --git a/src/options/OptTripleCtrl.vue b/src/options/OptTripleCtrl.vue index cc2337a0f..a2a07a811 100644 --- a/src/options/OptTripleCtrl.vue +++ b/src/options/OptTripleCtrl.vue @@ -85,7 +85,7 @@ </transition> </div> <div class="opt-item__description-wrap"> - <p class="opt-item__description" v-html="$t('opt:triple_ctrl_description')"></p> + <p class="opt-item__description" v-html="$t('opt:triple_ctrl_description') + $t('opt:mode_explain')"></p> </div> </div><!-- 快捷查词 --> </template>
refactor
update wording
96722c551928bf279cb8de315957cf1a15a13017
2019-01-22 22:28:35
CRIMX
refactor: update url
false
diff --git a/.github/issue_template.md b/.github/issue_template.md index d70a73121..c1d261c6f 100644 --- a/.github/issue_template.md +++ b/.github/issue_template.md @@ -1,6 +1,6 @@ <details><summary>反馈说明</summary> -使用相关的问题请阅读 《使用方式》 <https://github.com/crimx/crx-saladict/wiki#wiki-content> 。 +使用相关的问题请阅读 《使用方式》 <https://github.com/crimx/ext-saladict/wiki#wiki-content> 。 常见问题: diff --git a/CHANGELOG.md b/CHANGELOG.md index 03e4ccc6f..f84bdfadd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1354,28 +1354,28 @@ All notable changes to this project will be documented in this file. See [standa - 搜索图标右击可以变成翻译搜索 - 修复了几处错误并加速了结果显示 -[Unreleased]: https://github.com/crimx/crx-saladict/compare/v5.31.7...HEAD -[5.31.7]: https://github.com/crimx/crx-saladict/compare/v5.30.0...v5.31.7 -[5.30.0]: https://github.com/crimx/crx-saladict/compare/v5.28.3...v5.30.0 -[5.29.3]: https://github.com/crimx/crx-saladict/compare/v5.28.1...v5.29.3 -[5.28.1]: https://github.com/crimx/crx-saladict/compare/v5.27.3...v5.28.1 -[5.27.3]: https://github.com/crimx/crx-saladict/compare/v5.19.1...v5.27.3 -[5.19.1]: https://github.com/crimx/crx-saladict/compare/v5.18.5...v5.19.1 -[5.18.5]: https://github.com/crimx/crx-saladict/compare/v5.16.1...v5.18.5 -[5.16.1]: https://github.com/crimx/crx-saladict/compare/v5.15.21...v5.16.1 -[5.15.21]: https://github.com/crimx/crx-saladict/compare/v5.15.19...v5.15.21 -[5.15.19]: https://github.com/crimx/crx-saladict/compare/v5.15.14...v5.15.19 -[5.15.14]: https://github.com/crimx/crx-saladict/compare/v5.15.12...v5.15.14 -[5.15.12]: https://github.com/crimx/crx-saladict/compare/v5.15.9...v5.15.12 -[5.15.9]: https://github.com/crimx/crx-saladict/compare/v5.15.4...v5.15.9 -[5.15.4]: https://github.com/crimx/crx-saladict/compare/v5.15.2...v5.15.4 -[5.15.2]: https://github.com/crimx/crx-saladict/compare/v5.12.8...v5.15.2 -[5.12.8]: https://github.com/crimx/crx-saladict/compare/v5.11.23...v5.12.8 -[5.11.23]: https://github.com/crimx/crx-saladict/compare/v5.7.20...v5.11.23 -[5.7.20]: https://github.com/crimx/crx-saladict/compare/v5.5.14...v5.7.20 -[5.5.14]: https://github.com/crimx/crx-saladict/compare/v5.5.12...v5.5.14 -[5.5.12]: https://github.com/crimx/crx-saladict/compare/v5.3.9...v5.5.12 -[5.3.9]: https://github.com/crimx/crx-saladict/compare/v5.1.6...v5.3.9 -[5.1.6]: https://github.com/crimx/crx-saladict/compare/v5.0.0...v5.1.6 -[5.0.0]: https://github.com/crimx/crx-saladict/compare/v4.1.1...v5.0.0 -[4.1.1]: https://github.com/crimx/crx-saladict/tree/v4.1.1 +[Unreleased]: https://github.com/crimx/ext-saladict/compare/v5.31.7...HEAD +[5.31.7]: https://github.com/crimx/ext-saladict/compare/v5.30.0...v5.31.7 +[5.30.0]: https://github.com/crimx/ext-saladict/compare/v5.28.3...v5.30.0 +[5.29.3]: https://github.com/crimx/ext-saladict/compare/v5.28.1...v5.29.3 +[5.28.1]: https://github.com/crimx/ext-saladict/compare/v5.27.3...v5.28.1 +[5.27.3]: https://github.com/crimx/ext-saladict/compare/v5.19.1...v5.27.3 +[5.19.1]: https://github.com/crimx/ext-saladict/compare/v5.18.5...v5.19.1 +[5.18.5]: https://github.com/crimx/ext-saladict/compare/v5.16.1...v5.18.5 +[5.16.1]: https://github.com/crimx/ext-saladict/compare/v5.15.21...v5.16.1 +[5.15.21]: https://github.com/crimx/ext-saladict/compare/v5.15.19...v5.15.21 +[5.15.19]: https://github.com/crimx/ext-saladict/compare/v5.15.14...v5.15.19 +[5.15.14]: https://github.com/crimx/ext-saladict/compare/v5.15.12...v5.15.14 +[5.15.12]: https://github.com/crimx/ext-saladict/compare/v5.15.9...v5.15.12 +[5.15.9]: https://github.com/crimx/ext-saladict/compare/v5.15.4...v5.15.9 +[5.15.4]: https://github.com/crimx/ext-saladict/compare/v5.15.2...v5.15.4 +[5.15.2]: https://github.com/crimx/ext-saladict/compare/v5.12.8...v5.15.2 +[5.12.8]: https://github.com/crimx/ext-saladict/compare/v5.11.23...v5.12.8 +[5.11.23]: https://github.com/crimx/ext-saladict/compare/v5.7.20...v5.11.23 +[5.7.20]: https://github.com/crimx/ext-saladict/compare/v5.5.14...v5.7.20 +[5.5.14]: https://github.com/crimx/ext-saladict/compare/v5.5.12...v5.5.14 +[5.5.12]: https://github.com/crimx/ext-saladict/compare/v5.3.9...v5.5.12 +[5.3.9]: https://github.com/crimx/ext-saladict/compare/v5.1.6...v5.3.9 +[5.1.6]: https://github.com/crimx/ext-saladict/compare/v5.0.0...v5.1.6 +[5.0.0]: https://github.com/crimx/ext-saladict/compare/v4.1.1...v5.0.0 +[4.1.1]: https://github.com/crimx/ext-saladict/tree/v4.1.1 diff --git a/README.md b/README.md index 25b5995c5..9b5f20352 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Chrome/Firefox WebExtension. Feature-rich inline translator with PDF support. Vi [【中文】](https://www.crimx.com/ext-saladict/)Chrome/Firefox 浏览器插件,网页划词翻译。 <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://raw.githubusercontent.com/wiki/crimx/ext-saladict/images/notebook.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://raw.githubusercontent.com/wiki/crimx/ext-saladict/images/notebook.gif" /></a> </p> ## Downloads @@ -37,13 +37,13 @@ Saladict 6 is a complete rewrite in React Typescript for both Chrome & Firefox. ## More screenshots: <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/youdao-page.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/youdao-page.gif" /></a> </p> <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/screen-notebook.png" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/screen-notebook.png" /></a> </p> <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/pin.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/pin.gif" /></a> </p> diff --git a/docs/index.md b/docs/index.md index c51a869f9..520ae4478 100644 --- a/docs/index.md +++ b/docs/index.md @@ -15,7 +15,7 @@ Chrome/Firefox 浏览器插件,网页划词翻译。 <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://raw.githubusercontent.com/wiki/crimx/ext-saladict/images/notebook.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://raw.githubusercontent.com/wiki/crimx/ext-saladict/images/notebook.gif" /></a> </p> # 下载 @@ -24,31 +24,31 @@ Chrome/Firefox 浏览器插件,网页划词翻译。 功能一览: - 词典丰富 - - [精选大量词典,手工打磨排版,涵盖几乎所有领域](https://github.com/crimx/crx-saladict/wiki#dicts) - - [自动发音,可选不同词典、英美音](https://github.com/crimx/crx-saladict/wiki#autopron) - - [各个词典支持个性化调整](https://github.com/crimx/crx-saladict/wiki#dict-settings) - - [支持整个网页翻译,谷歌和有道分级网页翻译](https://github.com/crimx/crx-saladict/wiki#page-trans) - - [右键支持更多词典页面直达](https://github.com/crimx/crx-saladict/wiki#context-menus) + - [精选大量词典,手工打磨排版,涵盖几乎所有领域](https://github.com/crimx/ext-saladict/wiki#dicts) + - [自动发音,可选不同词典、英美音](https://github.com/crimx/ext-saladict/wiki#autopron) + - [各个词典支持个性化调整](https://github.com/crimx/ext-saladict/wiki#dict-settings) + - [支持整个网页翻译,谷歌和有道分级网页翻译](https://github.com/crimx/ext-saladict/wiki#page-trans) + - [右键支持更多词典页面直达](https://github.com/crimx/ext-saladict/wiki#context-menus) - 划词方式组合变幻无穷 - - [支持四种划词方式,支持鼠标悬浮取词](https://github.com/crimx/crx-saladict/wiki#mode) - - [查词面板可钉住可拖动可输入](https://github.com/crimx/crx-saladict/wiki#pin) - - [钉住可以配置不同划词方式](https://github.com/crimx/crx-saladict/wiki#mode) + - [支持四种划词方式,支持鼠标悬浮取词](https://github.com/crimx/ext-saladict/wiki#mode) + - [查词面板可钉住可拖动可输入](https://github.com/crimx/ext-saladict/wiki#pin) + - [钉住可以配置不同划词方式](https://github.com/crimx/ext-saladict/wiki#mode) - 情境模式快速切换词典组合 - - [每个情境模式下设置相互独立,快速切换](https://github.com/crimx/crx-saladict/wiki#profile) + - [每个情境模式下设置相互独立,快速切换](https://github.com/crimx/ext-saladict/wiki#profile) - 全键盘操作亦可 - - [支持设置浏览器快捷键](https://github.com/crimx/crx-saladict/wiki#shortcuts) - - [兼容 Vimium 全键盘操作](https://github.com/crimx/crx-saladict/wiki#vimium) - - [三按 ctrl 打开快捷查词](https://github.com/crimx/crx-saladict/wiki#triple-ctrl) - - [点击地址栏图标快速查词(可设置快捷键)](https://github.com/crimx/crx-saladict/wiki#popup-icon) + - [支持设置浏览器快捷键](https://github.com/crimx/ext-saladict/wiki#shortcuts) + - [兼容 Vimium 全键盘操作](https://github.com/crimx/ext-saladict/wiki#vimium) + - [三按 ctrl 打开快捷查词](https://github.com/crimx/ext-saladict/wiki#triple-ctrl) + - [点击地址栏图标快速查词(可设置快捷键)](https://github.com/crimx/ext-saladict/wiki#popup-icon) - 单词管理 - - [保存上下文以及翻译,准确理解单词](https://github.com/crimx/crx-saladict/wiki#search-history) - - [支持添加生词](https://github.com/crimx/crx-saladict/wiki#search-history) - - [可保存查词历史](https://github.com/crimx/crx-saladict/wiki#search-history) -- [支持黑白名单](https://github.com/crimx/crx-saladict/wiki#black-white-list) -- [支持 PDF 划词](https://github.com/crimx/crx-saladict/wiki#pdf) - - [支持 PDF 黑白名单](https://github.com/crimx/crx-saladict/wiki#black-white-list) -- [可显示当前页面二维码](https://github.com/crimx/crx-saladict/wiki#qrcode) -- [支持本项目](https://github.com/crimx/crx-saladict/wiki#reward) + - [保存上下文以及翻译,准确理解单词](https://github.com/crimx/ext-saladict/wiki#search-history) + - [支持添加生词](https://github.com/crimx/ext-saladict/wiki#search-history) + - [可保存查词历史](https://github.com/crimx/ext-saladict/wiki#search-history) +- [支持黑白名单](https://github.com/crimx/ext-saladict/wiki#black-white-list) +- [支持 PDF 划词](https://github.com/crimx/ext-saladict/wiki#pdf) + - [支持 PDF 黑白名单](https://github.com/crimx/ext-saladict/wiki#black-white-list) +- [可显示当前页面二维码](https://github.com/crimx/ext-saladict/wiki#qrcode) +- [支持本项目](https://github.com/crimx/ext-saladict/wiki#reward) # 用户评价 @@ -71,15 +71,15 @@ Chrome/Firefox 浏览器插件,网页划词翻译。 更多截图: <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/youdao-page.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/youdao-page.gif" /></a> </p> <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/screen-notebook.png" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/screen-notebook.png" /></a> </p> <p align="center"> - <a href="https://github.com/crimx/crx-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/pin.gif" /></a> + <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/pin.gif" /></a> </p> 为什么需要这些权限: @@ -93,7 +93,7 @@ Chrome/Firefox 浏览器插件,网页划词翻译。 查看[本次更新](https://github.com/crimx/ext-saladict/releases)。 -查看[更新历史](https://github.com/crimx/crx-saladict/blob/dev/CHANGELOG.md)。 +查看[更新历史](https://github.com/crimx/ext-saladict/blob/dev/CHANGELOG.md)。 # 支持开发 @@ -102,7 +102,7 @@ Chrome/Firefox 浏览器插件,网页划词翻译。 觉得好用的话欢迎帮助更多朋友发现本扩展。请按上方的 <kbd>★Star</kbd> 以及在[谷歌商店](https://chrome.google.com/webstore/detail/cdonnmffkdaoajfknoeeecmchibpmkmg/reviews?hl=en)或[火狐商店](https://addons.mozilla.org/firefox/addon/ext-saladict/)留好评。设计与开发本扩展均由作者一人花费大量私人时间与精力完成,并承诺一直开源免费无广告。欢迎随喜打赏咖啡以支持继续开发,多少不重要,看到大家喜爱的留言便是莫大的鼓励!(山里人最近才发现支付宝红包,欢迎扫码或搜索 `514220641` 一起薅羊毛,拿到的红包亦可用于打赏) <div align="center"> - <img height="200" src="https://github.com/crimx/crx-saladict/wiki/images/wechat.png"> - <img height="200" src="https://github.com/crimx/crx-saladict/wiki/images/alipay.png"> - <img height="300" src="https://github.com/crimx/crx-saladict/wiki/images/pocket-money.png"> + <img height="200" src="https://github.com/crimx/ext-saladict/wiki/images/wechat.png"> + <img height="200" src="https://github.com/crimx/ext-saladict/wiki/images/alipay.png"> + <img height="300" src="https://github.com/crimx/ext-saladict/wiki/images/pocket-money.png"> </div> diff --git a/src/_helpers/check-update.ts b/src/_helpers/check-update.ts index 177ea090b..0752829c1 100644 --- a/src/_helpers/check-update.ts +++ b/src/_helpers/check-update.ts @@ -5,7 +5,7 @@ type UpdateInfo = { export default function checkUpdate (): Promise<UpdateInfo> { // check new version - return fetch('https://api.github.com/repos/crimx/crx-saladict/releases/latest') + return fetch('https://api.github.com/repos/crimx/ext-saladict/releases/latest') .then(r => r.json()) .then(data => { if (data && data.tag_name) { diff --git a/src/background/initialization.ts b/src/background/initialization.ts index 829e301c7..875dabae4 100644 --- a/src/background/initialization.ts +++ b/src/background/initialization.ts @@ -18,10 +18,14 @@ startSyncServiceInterval() browser.runtime.onInstalled.addListener(onInstalled) browser.runtime.onStartup.addListener(onStartup) -browser.notifications.onClicked.addListener(genClickListener('https://github.com/crimx/crx-saladict/releases')) +browser.notifications.onClicked.addListener( + genClickListener('https://github.com/crimx/ext-saladict/releases') +) if (browser.notifications.onButtonClicked) { // Firefox doesn't support - browser.notifications.onButtonClicked.addListener(genClickListener('https://github.com/crimx/crx-saladict/releases')) + browser.notifications.onButtonClicked.addListener( + genClickListener('https://github.com/crimx/ext-saladict/releases') + ) } browser.commands.onCommand.addListener(command => { @@ -78,7 +82,7 @@ async function onInstalled ({ reason, previousVersion }: { reason: string, previ if (reason === 'install') { if (!(await storage.sync.get('hasInstructionsShown')).hasInstructionsShown) { - openURL('https://github.com/crimx/crx-saladict/wiki/Instructions#wiki-content') + openURL('https://github.com/crimx/ext-saladict/wiki/Instructions#wiki-content') storage.sync.set({ hasInstructionsShown: true }) } (await browser.tabs.query({})).forEach(tab => { @@ -91,7 +95,7 @@ async function onInstalled ({ reason, previousVersion }: { reason: string, previ let data if (!process.env.DEV_BUILD) { try { - const response = await fetch('https://api.github.com/repos/crimx/crx-saladict/releases/latest') + const response = await fetch('https://api.github.com/repos/crimx/ext-saladict/releases/latest') data = await response.json() } catch (e) {/* */} } diff --git a/src/options/components/HeadInfo/index.tsx b/src/options/components/HeadInfo/index.tsx index e540b7805..38187a32e 100644 --- a/src/options/components/HeadInfo/index.tsx +++ b/src/options/components/HeadInfo/index.tsx @@ -42,7 +42,7 @@ export class OptMenu extends React.PureComponent<{ t: TranslationFunction }> { <ul className='head-info'> <li className='head-info-acknowledgement-wrap'> <a - href='https://github.com/crimx/crx-saladict/wiki#acknowledgement' + href='https://github.com/crimx/ext-saladict/wiki#acknowledgement' onMouseEnter={this.showAcknowledgement} onMouseLeave={this.hideAcknowledgement} onClick={this.preventDefault}>{t('opt:head_info_acknowledgement')}</a> @@ -79,7 +79,7 @@ export class OptMenu extends React.PureComponent<{ t: TranslationFunction }> { </li> <li> <a - href='https://github.com/crimx/crx-saladict/wiki#wiki-content' + href='https://github.com/crimx/ext-saladict/wiki#wiki-content' target='_blank' rel='noopener'>{t('opt:head_info_instructions')}</a> </li> @@ -107,7 +107,7 @@ export class OptMenu extends React.PureComponent<{ t: TranslationFunction }> { </li> <li> <a - href='https://github.com/crimx/crx-saladict/issues' + href='https://github.com/crimx/ext-saladict/issues' target='_blank' rel='noopener' >{t('opt:head_info_report_issue')}</a>
refactor
update url
685cd02e09adb11bf508ef9ae3033d4d4591763c
2020-04-02 17:30:19
crimx
fix(sync-services): ignore word addition from sync services
false
diff --git a/src/background/database.ts b/src/background/database.ts index 83965352a..4a367babf 100644 --- a/src/background/database.ts +++ b/src/background/database.ts @@ -1,5 +1,4 @@ import Dexie from 'dexie' -import { storage } from '@/_helpers/browser-api' import { isContainChinese, isContainEnglish } from '@/_helpers/lang-check' import { Word, DBArea } from '@/_helpers/record-manager' import { syncServiceUpload } from './sync-manager' @@ -68,8 +67,12 @@ export function isInNotebook(word: Message<'IS_IN_NOTEBOOK'>['payload']) { .then(count => count > 0) } -export function saveWord({ area, word }: Message<'SAVE_WORD'>['payload']) { - if (area === 'notebook') { +export function saveWord({ + area, + word, + fromSync +}: Message<'SAVE_WORD'>['payload']) { + if (!fromSync && area === 'notebook') { syncServiceUpload({ op: 'ADD', words: [word] @@ -78,13 +81,21 @@ export function saveWord({ area, word }: Message<'SAVE_WORD'>['payload']) { return db[area].put(word) } -export function saveWords({ area, words }: { area: DBArea; words: Word[] }) { +export function saveWords({ + area, + words, + fromSync +}: { + area: DBArea + words: Word[] + fromSync?: boolean // sync services +}) { if (process.env.DEV_BUILD) { if (words.length !== new Set(words.map(w => w.date)).size) { console.error('save Words: duplicate records') } } - if (area === 'notebook') { + if (!fromSync && area === 'notebook') { syncServiceUpload({ op: 'ADD', words @@ -174,60 +185,4 @@ export async function getWords({ return { total, words } } -/* ----------------------------------------------- *\ - Init -\* ----------------------------------------------- */ - -// Populate data from old non-indexed db version -db.on('ready', () => { - return db.notebook.count(async count => { - if (count > 0) { - return - } - - const { notebookCat } = await storage.local.get('notebookCat') - if (!notebookCat || !Array.isArray(notebookCat.data)) { - return - } - const sliceIDs = notebookCat.data - - const dbSlices = await storage.local.get(sliceIDs) - const words: Word[] = [] - - sliceIDs.forEach(sliceID => { - const slice = dbSlices[sliceID] - if (!slice || !Array.isArray(slice.data)) { - return - } - slice.data.forEach(wordsGroupByDate => { - const { date, data } = wordsGroupByDate - const dateNum = new Date( - `${date.slice(0, 2)}/${date.slice(2, 4)}/${date.slice(4)}` - ).getTime() - const oldWords = data.map((oldWord, i) => ({ - date: dateNum + i, - text: oldWord.text || '', - context: oldWord.context || '', - title: oldWord.title || '', - favicon: oldWord.favicon - ? oldWord.favicon.startsWith('chrome') - ? 'https://saladict.crimx.com/favicon.ico' - : oldWord.favicon - : '', - url: oldWord.url || '', - trans: oldWord.trans || '', - note: oldWord.note || '' - })) - words.push(...oldWords) - }) - }) - - browser.storage.local.clear() - - return db.transaction('rw', db.notebook, () => { - return db.notebook.bulkAdd(words) - }) - }) -}) - db.open() diff --git a/src/background/sync-manager/helpers.ts b/src/background/sync-manager/helpers.ts index 7ce075c1c..f49dd8ba0 100644 --- a/src/background/sync-manager/helpers.ts +++ b/src/background/sync-manager/helpers.ts @@ -93,8 +93,11 @@ export async function deleteMeta(serviceID: string): Promise<void> { await deleteSyncMeta(serviceID) } -export async function setNotebook(words: Word[]): Promise<void> { - await saveWords({ area: 'notebook', words }) +export async function setNotebook( + words: Word[], + fromSync?: boolean +): Promise<void> { + await saveWords({ area: 'notebook', words, fromSync }) } export async function getNotebook(): Promise<Word[]> { diff --git a/src/background/sync-manager/services/shanbay.ts b/src/background/sync-manager/services/shanbay.ts index 1dc1dbea4..2f38f2547 100644 --- a/src/background/sync-manager/services/shanbay.ts +++ b/src/background/sync-manager/services/shanbay.ts @@ -28,11 +28,6 @@ const locales = { "Unable to add to Shanbay notebook. This word is not in Shanbay's vocabulary database.", 'zh-CN': '无法添加到扇贝生词本,扇贝单词库没有收录此单词。', 'zh-TW': '無法新增到扇貝生字本,扇貝單字庫沒有收錄此單字。' - }, - errLearning: { - en: 'Unable to add to Shanbay notebook.', - 'zh-CN': '无法添加到扇贝生词本。', - 'zh-TW': '無法新增到扇貝生字本。' } } @@ -145,7 +140,7 @@ export class Service extends SyncService<SyncConfig> { } if (!resLearning || resLearning.status_code !== 0) { - this.notifyError('errLearning', text) + this.notifyError('errWord', text) return Promise.reject('learning') } } diff --git a/src/background/sync-manager/services/webdav.ts b/src/background/sync-manager/services/webdav.ts index 39ee41e1d..ac7b25ba2 100644 --- a/src/background/sync-manager/services/webdav.ts +++ b/src/background/sync-manager/services/webdav.ts @@ -264,7 +264,7 @@ export class Service extends SyncService<SyncConfig, SyncMeta> { return } - const headers = { + const headers: { [name: string]: string } = { Authorization: 'Basic ' + window.btoa(`${config.user}:${config.passwd}`) } if (!testConfig && !noCache && this.meta.etag != null) { @@ -297,55 +297,55 @@ export class Service extends SyncService<SyncConfig, SyncMeta> { try { var json: NotebookFile = await response.json() } catch (e) { - if (process.env.NODE_ENV !== 'test') { + if (process.env.DEV_BUILD) { console.error('Fetch webdav notebook.json error', response) } return Promise.reject('parse') } + if (process.env.DEV_BUILD) { + if (!response.headers.get('ETag')) { + console.warn('webdav notebook.json no etag', response) + } + } + if (!Array.isArray(json.words) || json.words.some(w => !w.date)) { - if (process.env.NODE_ENV !== 'test') { + if (process.env.DEV_BUILD) { console.error('Parse webdav notebook.json error: incorrect words', json) } return Promise.reject('format') } - if (!noCache && this.meta.timestamp) { - if (!json.timestamp) { - if (process.env.NODE_ENV !== 'test') { - console.error('webdav notebook.json no timestamp', json) - } - return Promise.reject('timestamp') - } - - if (!testConfig) { - if (json.timestamp === this.meta.timestamp && !this.meta.etag) { - await this.setMeta({ - timestamp: json.timestamp, - etag: response.headers.get('ETag') || '' - }) - } - } - - if (json.timestamp <= this.meta.timestamp!) { - // older file - return + if (!json.timestamp) { + if (process.env.DEV_BUILD) { + console.error('webdav notebook.json no timestamp', json) } + return Promise.reject('timestamp') } - if (process.env.DEV_BUILD) { - if (!response.headers.get('ETag')) { - console.warn('webdav notebook.json no etag', response) - } + if (testConfig) { + // connectivity is ok + return } - if (!testConfig) { + const oldMeta = this.meta + + if (!oldMeta.timestamp || json.timestamp >= oldMeta.timestamp) { await this.setMeta({ timestamp: json.timestamp, - etag: response.headers.get('ETag') || '' + etag: response.headers.get('ETag') || oldMeta.etag || '' }) + } - await setNotebook(json.words) + if (!noCache && oldMeta.timestamp && json.timestamp <= oldMeta.timestamp) { + // older file + return + } + + await setNotebook(json.words, true) + + if (process.env.DEV_BUILD) { + console.log('Webdav download', json) } } diff --git a/src/typings/message.ts b/src/typings/message.ts index 7cabf934a..52b23041a 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -101,6 +101,8 @@ export type MessageConfig = MessageConfigType<{ payload: { area: DBArea word: Word + /** From sync services */ + fromSync?: boolean } } diff --git a/test/specs/background/sync-manager/services/webdav.spec.ts b/test/specs/background/sync-manager/services/webdav.spec.ts index f937355b5..be33c9c6d 100644 --- a/test/specs/background/sync-manager/services/webdav.spec.ts +++ b/test/specs/background/sync-manager/services/webdav.spec.ts @@ -174,7 +174,7 @@ describe('Sync service WebDAV', () => { await service.download({}) - expect(helpers.setNotebook).lastCalledWith(words) + expect(helpers.setNotebook).lastCalledWith(words, true) expect(helpers.setMeta).lastCalledWith('webdav', { timestamp, etag }) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith(...fetchArgs.download(config)) @@ -219,7 +219,7 @@ describe('Sync service WebDAV', () => { await service.download({}) - expect(helpers.setNotebook).lastCalledWith(words) + expect(helpers.setNotebook).lastCalledWith(words, true) expect(helpers.setMeta).lastCalledWith('webdav', { timestamp, etag }) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( @@ -315,7 +315,7 @@ describe('Sync service WebDAV', () => { await service.download({}) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) - expect(helpers.setMeta).toHaveBeenCalledTimes(0) + expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, { @@ -369,7 +369,7 @@ describe('Sync service WebDAV', () => { await service.download({}) expect(helpers.setNotebook).toHaveBeenCalledTimes(0) - expect(helpers.setMeta).toHaveBeenCalledTimes(0) + expect(helpers.setMeta).toHaveBeenCalledTimes(1) expect(fetchInit.download).toHaveBeenCalledTimes(1) expect(fetchInit.download).lastCalledWith( ...fetchArgs.download(config, {
fix
ignore word addition from sync services
b9a1a3e211a405595724a9e466ffc8d9a2c7ec1d
2020-02-20 11:54:39
crimx
fix(wordpage): keyword matching
false
diff --git a/src/components/WordPage/ExportModal.tsx b/src/components/WordPage/ExportModal.tsx index 6594d1c62..7c1efdda1 100644 --- a/src/components/WordPage/ExportModal.tsx +++ b/src/components/WordPage/ExportModal.tsx @@ -30,6 +30,8 @@ interface TemplateData { contentR: string } +const keywordMatchStr = `%(${Object.keys(newWord()).join('|')})%` + export class ExportModalBody extends React.Component< ExportModalInnerProps, ExportModalState @@ -145,11 +147,11 @@ export class ExportModalBody extends React.Component< } processWords = (): string => { - const keys = Object.keys(newWord()) return this.props.rawWords .map(word => - this.state.template.replace(/%(\S+)%/g, (match, k) => { - if (keys.includes(k)) { + this.state.template.replace( + new RegExp(keywordMatchStr, 'g'), + (match, k) => { switch (k) { case 'date': return new Date(word.date).toLocaleDateString(this.props.locale) @@ -179,8 +181,7 @@ export class ExportModalBody extends React.Component< return word[k] || '' } } - return match - }) + ) ) .join('\n') }
fix
keyword matching
51b60d586f98261a9d705b073241320d0a5916d9
2019-03-12 17:59:23
CRIMX
fix(panel): max z-index for dict panel
false
diff --git a/src/_sass_global/_z-indices.scss b/src/_sass_global/_z-indices.scss index e5ed8e92f..d2abac72b 100644 --- a/src/_sass_global/_z-indices.scss +++ b/src/_sass_global/_z-indices.scss @@ -11,7 +11,7 @@ $global-zindex-popover: 2147483646 !default; $global-zindex-tooltip: 2147483647 !default; -$global-zindex-dicteditor: 2147483644; -$global-zindex-dictpanel-dragbg: 2147483645; -$global-zindex-dictpanel: 2147483646; +$global-zindex-dicteditor: 2147483645; +$global-zindex-dictpanel-dragbg: 2147483646; +$global-zindex-dictpanel: 2147483647; $global-zindex-bowl: 2147483647;
fix
max z-index for dict panel
3fbdc47f50a4dc21fc4b9f4a69ca8d73a99c764e
2019-07-12 20:02:19
CRIMX
chore(storybook): add background addon
false
diff --git a/.storybook/addons.ts b/.storybook/addons.ts index 026e8a92e..0321dc407 100644 --- a/.storybook/addons.ts +++ b/.storybook/addons.ts @@ -1,6 +1,7 @@ import '@storybook/addon-knobs/register' import '@storybook/addon-contexts/register' import '@storybook/addon-actions/register' +import '@storybook/addon-backgrounds/register' import addons from '@storybook/addons' import { STORY_RENDERED } from '@storybook/core-events' diff --git a/package.json b/package.json index 21c27d5a9..58fac804d 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,7 @@ "@neutrinojs/copy": "^9.0.0-rc.3", "@neutrinojs/react": "^9.0.0-rc.3", "@storybook/addon-actions": "^5.1.9", + "@storybook/addon-backgrounds": "^5.1.9", "@storybook/addon-contexts": "^5.1.9", "@storybook/addon-info": "^5.1.9", "@storybook/addon-knobs": "^5.1.9", diff --git a/yarn.lock b/yarn.lock index 85b546116..4979e217f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1610,6 +1610,22 @@ react-inspector "^3.0.2" uuid "^3.3.2" +"@storybook/addon-backgrounds@^5.1.9": + version "5.1.9" + resolved "https://registry.yarnpkg.com/@storybook/addon-backgrounds/-/addon-backgrounds-5.1.9.tgz#bb02aaaf9246624b06630a40f008cf81496b5199" + integrity sha512-3UmDt+WJApHx3YaY0N7XU/r/LaQ/X10ORP6AX0gpIlHqU1h1OeHXjIsFHewk+x/6wRCkAe3Zf3ue9M4/X9hs3A== + dependencies: + "@storybook/addons" "5.1.9" + "@storybook/api" "5.1.9" + "@storybook/client-logger" "5.1.9" + "@storybook/components" "5.1.9" + "@storybook/core-events" "5.1.9" + "@storybook/theming" "5.1.9" + core-js "^3.0.1" + memoizerific "^1.11.3" + react "^16.8.3" + util-deprecate "^1.0.2" + "@storybook/addon-contexts@^5.1.9": version "5.1.9" resolved "https://registry.yarnpkg.com/@storybook/addon-contexts/-/addon-contexts-5.1.9.tgz#fe8336f62dbd2aa181c529198c9156139c4bf8a8"
chore
add background addon
1eae8e86a4f2b1f6b9c056f8329ddb7415af48b9
2021-09-11 16:58:05
yipanhuasheng
feat: (dicts) add merriam webster's dict (#1476)
false
diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index 555cbe64..88641e8b 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -30,6 +30,7 @@ import urban from '@/components/dictionaries/urban/config' import vocabulary from '@/components/dictionaries/vocabulary/config' import weblio from '@/components/dictionaries/weblio/config' import weblioejje from '@/components/dictionaries/weblioejje/config' +import merriamwebster from '@/components/dictionaries/merriamwebster/config' import websterlearner from '@/components/dictionaries/websterlearner/config' import wikipedia from '@/components/dictionaries/wikipedia/config' import youdao from '@/components/dictionaries/youdao/config' @@ -69,6 +70,7 @@ export const defaultAllDicts = { vocabulary: vocabulary(), weblio: weblio(), weblioejje: weblioejje(), + merriamwebster: merriamwebster(), websterlearner: websterlearner(), wikipedia: wikipedia(), youdao: youdao(), diff --git a/src/components/dictionaries/merriamwebster/View.tsx b/src/components/dictionaries/merriamwebster/View.tsx new file mode 100644 index 00000000..f90a7904 --- /dev/null +++ b/src/components/dictionaries/merriamwebster/View.tsx @@ -0,0 +1,58 @@ +import React, { FC } from 'react' +import Speaker from '@/components/Speaker' +import { MerriamWebsterResult } from './engine' +import { ViewPorps } from '@/components/dictionaries/helpers' + +export const DictMerriamWebster: FC<ViewPorps<MerriamWebsterResult>> = ({ + result +}) => ( + <ul className="dictMerriamWebster-List"> + {result.map((def, defI) => ( + <li key={def.meaning} className="dictMerriamWebster-Item"> + <div className="dictMerriamWebster-TitleBox"> + <sup className="dictMerriamWebster-Sup">{defI + 1}</sup> + <span className="dictMerriamWebster-Title">{def.title}</span> + <span className="dictMerriamWebster-Pos">{def.pos}</span> + <Speaker src={def.pron} /> + </div> + + <div className="dictMerriamWebster-PronBox"> + {def.syllables && ( + <> + <span className="dictMerriamWebster-Syllables"> + {def.syllables} + </span> + <span className="dictMerriamWebster-Break">|</span> + </> + )} + {def.pr && <span>\{def.pr}\</span>} + + {def.headword && ( + <div> + <p + className="dictMerriamWebster-Headword" + dangerouslySetInnerHTML={{ __html: def.headword }} + /> + </div> + )} + </div> + + {def.meaning && ( + <p + className="dictMerriamWebster-Meaning" + dangerouslySetInnerHTML={{ __html: def.meaning }} + /> + )} + + {def.definition && ( + <p + className="dictMerriamWebster-Definition" + dangerouslySetInnerHTML={{ __html: def.definition }} + /> + )} + </li> + ))} + </ul> +) + +export default DictMerriamWebster diff --git a/src/components/dictionaries/merriamwebster/_locales.json b/src/components/dictionaries/merriamwebster/_locales.json new file mode 100644 index 00000000..e81ec2fe --- /dev/null +++ b/src/components/dictionaries/merriamwebster/_locales.json @@ -0,0 +1,19 @@ +{ + "name": { + "en": "Merriam-Webster's Dictionary", + "zh-CN": "韦氏词典", + "zh-TW": "韋氏字典" + }, + "options": { + "resultnum": { + "en": "Show", + "zh-CN": "结果数量", + "zh-TW": "結果數量" + }, + "resultnum_unit": { + "en": "results", + "zh-CN": "个", + "zh-TW": "個" + } + } +} diff --git a/src/components/dictionaries/merriamwebster/_style.shadow.scss b/src/components/dictionaries/merriamwebster/_style.shadow.scss new file mode 100644 index 00000000..09b1bc8b --- /dev/null +++ b/src/components/dictionaries/merriamwebster/_style.shadow.scss @@ -0,0 +1,202 @@ +.dictMerriamWebster-TitleBox { + .dictMerriamWebster-Sup { + font-weight: 700; + margin-right: 2px; + } + + .dictMerriamWebster-Title { + font-size: 1.5em; + font-weight: 700; + margin-right: 4px; + } + + .dictMerriamWebster-Pos { + color: #4a7d95; + font-weight: 700; + } +} + +.dictMerriamWebster-PronBox { + .dictMerriamWebster-Break { + padding: 0 6px; + } +} + +.dictMerriamWebster-Headword { + .if { + font-weight: 700; + } + + .first-slash { + padding-left: 3px; + } + + .last-slash { + padding-right: 3px; + } + + .l { + font-style: italic; + } +} + +.dictMerriamWebster-Meaning { + background-image: linear-gradient(180deg, #f5f9fa, #e7f0f4); + border-left: 4px solid #97bece; + padding: 4px; + + .hword2 { + font-weight: 700; + font-size: 1.2em; + color: #265667; + margin: 2px; + } + + .vg-header { + display: none; + } + + .vg { + .sb { + margin-bottom: 8px; + position: relative; + + &.has-num { + padding-left: 11px; + } + + &.has-subnum, + &.has-let { + padding-left: 33px; + } + } + + .t { + display: block; + padding-top: 2px; + color: #225f73; + + &::before { + content: '//'; + font-weight: 700; + padding: 0 4px 0 0; + color: #4a7d95; + } + } + + .dt { + .show-vis, + .hide-vis { + display: none; + } + } + + .num { + left: 0; + position: absolute; + top: 0; + font-weight: 700; + } + } +} + +.dictMerriamWebster-Definition { + .vg-header { + display: none; + } + + .dro { + padding-left: 18px; + + .drp { + font-weight: 700; + } + } + + .vg { + .sb { + margin-bottom: 12px; + position: relative; + + &.has-num { + padding-left: 18px; + } + + &.has-subnum, + &.has-let { + padding-left: 36px; + } + + .sense.has-subnum { + display: block; + padding: 0 0 6px 11px; + + .sub-num { + position: absolute; + left: 26px; + font-weight: 700; + } + } + + .sdsense { + display: block; + padding-top: 4px; + } + + &.letter-only span[class^='sb-'] > .has-sn { + padding-left: 18px; + + .letter { + left: 0; + position: absolute; + } + } + } + + span { + font-size: 14px; + letter-spacing: 0.2px; + line-height: 14px; + + &[class^='sb-'] { + display: block; + margin-top: 6px; + } + } + .auth, + .source { + color: #525a5b; + font-size: 12px; + } + + .sb-0 { + margin-top: 4px; + } + + .num { + left: 0; + position: absolute; + top: 0; + font-weight: 700; + } + + .letter { + left: 16px; + position: absolute; + font-weight: 700; + } + + .t { + display: block; + padding-top: 4px; + color: #225f73; + + &::before { + content: '//'; + font-weight: 700; + padding: 0 4px 0 0; + color: #4a7d95; + } + } + } +} diff --git a/src/components/dictionaries/merriamwebster/config.ts b/src/components/dictionaries/merriamwebster/config.ts new file mode 100644 index 00000000..4692cd39 --- /dev/null +++ b/src/components/dictionaries/merriamwebster/config.ts @@ -0,0 +1,39 @@ +import { DictItem } from '@/app-config/dicts' + +export type MerriamWebsterConfig = DictItem<{ + resultnum: number +}> + +export default (): MerriamWebsterConfig => ({ + lang: '10000000', + selectionLang: { + english: true, + chinese: false, + japanese: false, + korean: false, + french: false, + spanish: false, + deutsch: false, + others: false, + matchAll: false + }, + defaultUnfold: { + english: true, + chinese: true, + japanese: true, + korean: true, + french: true, + spanish: true, + deutsch: true, + others: true, + matchAll: false + }, + preferredHeight: 180, + selectionWC: { + min: 1, + max: 5 + }, + options: { + resultnum: 4 + } +}) diff --git a/src/components/dictionaries/merriamwebster/engine.ts b/src/components/dictionaries/merriamwebster/engine.ts new file mode 100644 index 00000000..355826ab --- /dev/null +++ b/src/components/dictionaries/merriamwebster/engine.ts @@ -0,0 +1,157 @@ +import { fetchDirtyDOM } from '@/_helpers/fetch-dom' +import { + HTMLString, + getText, + getInnerHTML, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, + DictSearchResult +} from '../helpers' + +export const getSrcPage: GetSrcPageFunction = text => { + return `https://www.merriam-webster.com/dictionary/${text}` +} + +const HOST = 'https://www.merriam-webster.com' + +interface MerriamWebsterResultItem { + /** keyword */ + title?: string + pos?: string + syllables?: string + pr?: string + /** pronunciation */ + pron?: string + meaning?: HTMLString + definition?: HTMLString + headword?: HTMLString +} + +export type MerriamWebsterResult = MerriamWebsterResultItem[] + +type MerriamWebsterSearchResult = DictSearchResult<MerriamWebsterResult> + +export const search: SearchFunction<MerriamWebsterResult> = ( + text, + config, + profile, + payload +) => { + const options = profile.dicts.all.merriamwebster.options + + return fetchDirtyDOM( + 'https://www.merriam-webster.com/dictionary/' + + encodeURIComponent(text.replace(/\s+/g, ' ')) + ) + .catch(handleNetWorkError) + .then(doc => handleDOM(doc, options)) +} + +/** + * get link of pronunciation from href attribute + */ +function getPronLink(href: string | null): string { + if (!href) { + return '' + } + const params = href.split('?')[1].split('&') + let lang + let dir + let file + params.map(url => { + if (url.includes('lang')) { + lang = url.substr(5) + const langs = lang.split('_') + + // eg: en_us + if (langs.length > 1) { + lang = langs.join('/') + } + } + if (url.includes('dir')) { + dir = url.substr(4) + } + if (url.includes('file')) { + file = `${url.substr(5)}.mp3` + } + }) + return lang && dir && file + ? `https://media.merriam-webster.com/audio/prons/${lang}/mp3/${dir}/${file}` + : '' +} + +function handleDOM( + doc: Document, + { resultnum }: { resultnum: number } +): MerriamWebsterSearchResult | Promise<MerriamWebsterSearchResult> { + const result: MerriamWebsterResult = [] + + const $content = doc.querySelector('#left-content') as HTMLElement + + if (!$content || !$content.querySelector('div[id^=dictionary-entry]')) { + return handleNoResult() + } + + const children: Element[] = Array.from($content.children) + + let resultItem + + for (let i = 0; i < children.length && result.length < resultnum; i++) { + const $el = children[i] + if ($el.className.includes('anchor-name')) { + resultItem && result.push(resultItem) + resultItem = {} + } + + if ($el.className.includes('entry-header')) { + resultItem.title = getText($el, '.hword') + resultItem.pos = getText($el, '.important-blue-link') + } + + if ($el.className.includes('entry-attr')) { + resultItem.syllables = getText($el, '.word-syllables') + resultItem.pr = getText($el, '.pr') + + const $pron = $el.querySelector('.play-pron') as HTMLElement + resultItem.pron = $pron ? getPronLink($pron.getAttribute('href')) : '' + } + + if ($el.className.includes('headword-row')) { + resultItem.headword = getInnerHTML(HOST, $el).replace( + /<\/?a.+[^>]*>/g, + '' + ) + + if (!resultItem.pron) { + const $pron = $el.querySelector('.play-pron') as HTMLElement + resultItem.pron = $pron ? getPronLink($pron.getAttribute('href')) : '' + } + } + + if ($el.className.includes('learners-essential-meaning')) { + resultItem.meaning = getInnerHTML(HOST, $el).replace(/<a.+<\/a>/g, '') + } + + if ($el.id.includes('dictionary-entry')) { + // ignore img tag + resultItem.definition = getInnerHTML(HOST, $el).replace( + /<\/?img.+[^>]*>/g, + '' + ) + } + + // the main content is before the first script tag + if ($el.nodeName === 'SCRIPT') { + result.push(resultItem) + break + } + } + + if (result.length > 0) { + return { result } + } else { + return handleNoResult() + } +} diff --git a/src/components/dictionaries/merriamwebster/favicon.png b/src/components/dictionaries/merriamwebster/favicon.png new file mode 100644 index 00000000..e3f79cf2 Binary files /dev/null and b/src/components/dictionaries/merriamwebster/favicon.png differ diff --git a/test/specs/components/dictionaries/merriamwebster/fixtures.js b/test/specs/components/dictionaries/merriamwebster/fixtures.js new file mode 100644 index 00000000..eab0bc77 --- /dev/null +++ b/test/specs/components/dictionaries/merriamwebster/fixtures.js @@ -0,0 +1,7 @@ +module.exports = { + files: [ + ['love.html', 'https://www.merriam-webster.com/dictionary/love'], + ['text.html', 'https://www.merriam-webster.com/dictionary/text'], + ['salad.html', 'https://www.merriam-webster.com/dictionary/salad'] + ] +} diff --git a/test/specs/components/dictionaries/merriamwebster/requests.mock.ts b/test/specs/components/dictionaries/merriamwebster/requests.mock.ts new file mode 100644 index 00000000..208373af --- /dev/null +++ b/test/specs/components/dictionaries/merriamwebster/requests.mock.ts @@ -0,0 +1,17 @@ +import { MockRequest } from '@/components/dictionaries/helpers' + +export const mockSearchTexts = ['love', 'text', 'salad'] + +export const mockRequest: MockRequest = mock => { + mock + .onGet(/merriam-webster.+love$/) + .reply(200, require(`raw-loader!./response/love.html`).default) + + mock + .onGet(/merriam-webster.+text$/) + .reply(200, require(`raw-loader!./response/text.html`).default) + + mock + .onGet(/merriam-webster.+salad$/) + .reply(200, require(`raw-loader!./response/salad.html`).default) +}
feat
(dicts) add merriam webster's dict (#1476)
f829a232499841b69493eb4f91f9a61f36fe059d
2020-01-16 19:48:31
crimx
refactor: add title for word pages
false
diff --git a/src/history/index.tsx b/src/history/index.tsx index 709befcee..a89d0a298 100644 --- a/src/history/index.tsx +++ b/src/history/index.tsx @@ -5,4 +5,6 @@ import React from 'react' import ReactDOM from 'react-dom' import WordPage from '@/components/WordPage' +document.title = 'Saladict History' + ReactDOM.render(<WordPage area="history" />, document.getElementById('root')) diff --git a/src/notebook/index.tsx b/src/notebook/index.tsx index b1fdfa481..943ff7d17 100644 --- a/src/notebook/index.tsx +++ b/src/notebook/index.tsx @@ -5,4 +5,6 @@ import React from 'react' import ReactDOM from 'react-dom' import WordPage from '@/components/WordPage' +document.title = 'Saladict Notebook' + ReactDOM.render(<WordPage area="notebook" />, document.getElementById('root'))
refactor
add title for word pages
1738627649f5a9cd4492781ae5769ccae1a40e42
2018-02-04 17:44:13
CRIMX
refactor(background): rewrite server
false
diff --git a/src/background/server.ts b/src/background/server.ts index f1527dfb3..f8148d55d 100644 --- a/src/background/server.ts +++ b/src/background/server.ts @@ -1,72 +1,84 @@ -import {storage, message, openURL} from 'src/helpers/chrome-api' -import {promiseTimer} from 'src/helpers/promise-more' -import AudioManager from './audio-manager' -import chsToChz from 'src/helpers/chs-to-chz' -const AUDIO = new AudioManager() +import { DictID, AppConfig } from '../app-config' +import { storage, message, openURL, Message } from '../_helpers/browser-api' +import { play } from './audio-manager' +import { chsToChz } from '../_helpers/chs-to-chz' -message.server() +interface MessageOpenUrlWithEscape { + type: 'OPEN_URL' + url: string + escape: true + text: string +} + +interface MessageOpenUrlWithoutEscape { + type: 'OPEN_URL' + url: string + escape?: false +} + +type MessageOpenUrl = MessageOpenUrlWithoutEscape | MessageOpenUrlWithEscape + +interface MessageAudioPlay { + type: 'AUDIO_PLAY' + src: string +} + +interface MessageFetchDictResult { + type: 'FETCH_DICT_RESULT' + dict: DictID + text: string +} + +message.self.initServer() // background script as transfer station -message.listen((data, sender, sendResponse) => { - switch (data.msg) { +message.addListener((data, sender: browser.runtime.MessageSender): Promise<void> | undefined => { + switch (data.type) { case 'OPEN_URL': - return createTab(data, sender, sendResponse) + return createTab(data) case 'AUDIO_PLAY': - return playAudio(data, sender, sendResponse) + return playAudio(data) case 'FETCH_DICT_RESULT': - return fetchDictResult(data, sender, sendResponse) + return fetchDictResult(data) case 'PRELOAD_SELECTION': - return preloadSelection(data, sender, sendResponse) + return preloadSelection() } }) -function createTab (data, sender, sendResponse) { - openURL( +function createTab (data: MessageOpenUrl): Promise<void> { + return openURL( data.escape ? data.url .replace(/%s/g, data.text) .replace(/%z/g, chsToChz(data.text)) : data.url ) - sendResponse() } -function playAudio (data, sender, sendResponse) { - AUDIO.load(data.src) - Promise.race([ - promiseTimer(4000), - new Promise(resolve => AUDIO.listen('ended', resolve)) - ]).then(sendResponse) - AUDIO.play() - return true +function playAudio (data: MessageAudioPlay): Promise<void> { + return play(data.src) } -function fetchDictResult (data, sender, sendResponse) { - const search = require('src/dictionaries/' + data.dict + '/engine.js').default - if (!search) { - sendResponse({error: 'Missing Dictionary!'}) - return - } +function fetchDictResult (data: MessageFetchDictResult): Promise<void> { + let search - storage.sync.get('config', ({config}) => { - search(data.text, config, {AUDIO}) - .then(result => sendResponse({result, dict: data.dict})) - .catch(error => sendResponse({error, dict: data.dict})) - }) + try { + search = require('../components/dictionaries/' + data.dict + '/engine.js') + } catch (err) { + return Promise.reject(err) + } - // keep the channel alive - return true + return search(data.text) + .then(result => ({ result, dict: data.dict })) } -function preloadSelection (data, sender, sendResponse) { - chrome.tabs.query({active: true, currentWindow: true}, tabs => { - if (tabs.length > 0) { - message.send(tabs[0].id, {msg: '__PRELOAD_SELECTION__'}, text => { - sendResponse(text || '') - }) - } else { - sendResponse('') - } - }) - return true +function preloadSelection (): Promise<void> { + return browser.tabs.query({ active: true, currentWindow: true }) + .then(tabs => { + if (tabs.length > 0 && tabs[0].id != null) { + return message.send(tabs[0].id as number, { type: '__PRELOAD_SELECTION__' }) + } + }) + .then(text => text || '') + .catch(() => '') } diff --git a/test/unit/background/server.spec.ts b/test/unit/background/server.spec.ts new file mode 100644 index 000000000..b8ef06579 --- /dev/null +++ b/test/unit/background/server.spec.ts @@ -0,0 +1,141 @@ +import { appConfigFactory, AppConfig } from '../../../src/app-config' +import * as browserWrap from '../../../src/_helpers/browser-api' +import sinon from 'sinon' + +describe('Server', () => { + const chsToChz = jest.fn() + const play = jest.fn() + const initServer = jest.fn() + const openURL = jest.fn() + const bingSearch = jest.fn() + browserWrap.message.self.initServer = initServer + // @ts-ignore + browserWrap.openURL = openURL + + beforeAll(() => { + jest.doMock('../../../src/_helpers/chs-to-chz', () => { + return { chsToChz } + }) + jest.doMock('../../../src/background/audio-manager', () => { + return { play } + }) + jest.doMock('../../../src/_helpers/browser-api', () => { + return browserWrap + }) + jest.doMock('../../../src/components/dictionaries/bing/engine.js', () => { + return bingSearch + }) + }) + + afterAll(() => { + browser.flush() + jest.dontMock('../../../src/_helpers/chs-to-chz') + jest.dontMock('../../../src/background/audio-manager') + jest.dontMock('../../../src/_helpers/browser-api') + jest.dontMock('../../../src/components/dictionaries/bing/engine.js') + }) + + beforeEach(() => { + browser.flush() + chsToChz.mockReset() + chsToChz.mockImplementation(t => t) + play.mockReset() + play.mockImplementation(() => Promise.resolve()) + initServer.mockReset() + openURL.mockReset() + bingSearch.mockReset() + bingSearch.mockImplementation(() => Promise.resolve()) + jest.resetModules() + require('../../../src/background/server') + }) + + it('should properly init', () => { + expect(initServer).toHaveBeenCalledTimes(1) + expect(browser.runtime.onMessage.addListener.calledOnce).toBeTruthy() + }) + + describe('Create Tab', () => { + it('called with escape', () => { + browser.runtime.onMessage.dispatch({ + type: 'OPEN_URL', + url: 'https://test.com/%s%z', + escape: true, + text: 'test', + }) + expect(chsToChz).toHaveBeenCalledTimes(1) + expect(chsToChz).toHaveBeenCalledWith('test') + expect(openURL).toHaveBeenCalledTimes(1) + expect(openURL).toHaveBeenCalledWith('https://test.com/testtest') + }) + + it('called without escape', () => { + browser.runtime.onMessage.dispatch({ + type: 'OPEN_URL', + url: 'https://test.com/', + text: 'test', + }) + expect(chsToChz).toHaveBeenCalledTimes(0) + expect(openURL).toHaveBeenCalledTimes(1) + expect(openURL).toHaveBeenCalledWith('https://test.com/') + }) + }) + + it('Audio Play', () => { + browser.runtime.onMessage.dispatch({ + type: 'AUDIO_PLAY', + src: 'https://test.com/a.mp3', + }) + expect(play).toHaveBeenCalledTimes(1) + expect(play).toHaveBeenCalledWith('https://test.com/a.mp3') + }) + + describe('Fetch Dict Result', () => { + it('should reject when missing dict id', done => { + const resolveStub = jest.fn() + const rejectStub = jest.fn() + browser.runtime.onMessage['_listeners'].forEach(f => + f({ + type: 'FETCH_DICT_RESULT', + text: 'test', + }) + .then(resolveStub, rejectStub) + ) + setTimeout(() => { + expect(bingSearch).toHaveBeenCalledTimes(0) + expect(resolveStub).toHaveBeenCalledTimes(0) + expect(rejectStub).toHaveBeenCalledTimes(1) + done() + }, 0) + }) + + it('should search text', () => { + browser.runtime.onMessage.dispatch({ + type: 'FETCH_DICT_RESULT', + dict: 'bing', + text: 'test', + }) + expect(bingSearch).toHaveBeenCalledTimes(1) + expect(bingSearch).toHaveBeenCalledWith('test') + }) + }) + + it('Preload Selection', done => { + const resolveStub = jest.fn() + const rejectStub = jest.fn() + const queryStub = jest.fn(() => Promise.resolve([{ id: 100 }])) + browser.tabs.query.callsFake(queryStub) + browser.tabs.sendMessage.callsFake(() => 'test') + browser.runtime.onMessage.dispatch({ type: 'PRELOAD_SELECTION' }) + browser.runtime.onMessage['_listeners'].forEach(f => + f({ type: 'PRELOAD_SELECTION' }) + .then(resolveStub, rejectStub) + ) + setTimeout(() => { + expect(resolveStub).toHaveBeenCalledTimes(1) + expect(resolveStub).toHaveBeenCalledWith('test') + expect(rejectStub).toHaveBeenCalledTimes(0) + expect(browser.tabs.sendMessage.calledWith(100, { type: '__PRELOAD_SELECTION__' })).toBeTruthy() + done() + }, 0) + }) +})
refactor
rewrite server
c5aeca2708026e466c8e11fe90b81e5b841a08ea
2018-09-01 14:37:32
CRIMX
fix(dicts): fix etymonline
false
diff --git a/config/fake-env/fake-ajax.js b/config/fake-env/fake-ajax.js index 3b480d740..6cc17df27 100644 --- a/config/fake-env/fake-ajax.js +++ b/config/fake-env/fake-ajax.js @@ -28,12 +28,21 @@ const fakeFetchData = [ { test: { method: /.*/, - url: /\.etymonline\.com/, + url: /\.etymonline\.com\/search/, }, response: { text: () => require('raw-loader!../../test/specs/components/dictionaries/etymonline/response/love.html'), }, }, + { + test: { + method: /.*/, + url: /\.etymonline\.com\/word/, + }, + response: { + text: () => require('raw-loader!../../test/specs/components/dictionaries/etymonline/response/love-word.html'), + }, + }, { test: { method: /.*/, diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index 3e3b5a0c4..6b6bed4c5 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -178,7 +178,8 @@ export function getALlDicts () { * For string, add additional `options_sel` field to list out choices. */ options: { - resultnum: 4 + resultnum: 4, + chart: true, } }, eudic: { diff --git a/src/components/__fake__/index.tsx b/src/components/__fake__/index.tsx index d7befd1c2..9932e3df1 100644 --- a/src/components/__fake__/index.tsx +++ b/src/components/__fake__/index.tsx @@ -5,9 +5,9 @@ import setupEnv from './devDict' setupEnv({ - dict: 'longman', + dict: 'etymonline', style: true, - text: 'common', + text: 'love', }) /*-----------------------------------------------*\ diff --git a/src/components/dictionaries/etymonline/View.tsx b/src/components/dictionaries/etymonline/View.tsx index 6e95f6285..7d0c721fa 100644 --- a/src/components/dictionaries/etymonline/View.tsx +++ b/src/components/dictionaries/etymonline/View.tsx @@ -8,9 +8,16 @@ export default class DictEtymonline extends React.PureComponent<{ result: Etymon {this.props.result.map(item => ( <li key={item.title} className='dictEtymonline-Item'> <h2 className='dictEtymonline-Title'> - <a href={item.href} target='_blank' rel='nofollow'>{item.title}</a> + {item.href + ? <a href={item.href} target='_blank' rel='nofollow'>{item.title}</a> + : item.title + } </h2> <p className='dictEtymonline-Def' dangerouslySetInnerHTML={{ __html: item.def }} /> + {item.chart + ? <img src={item.chart} alt={'Origin of ' + item.title} /> + : null + } </li> ))} </ul> diff --git a/src/components/dictionaries/etymonline/_locales.json b/src/components/dictionaries/etymonline/_locales.json index 91d36e579..14ed803d0 100644 --- a/src/components/dictionaries/etymonline/_locales.json +++ b/src/components/dictionaries/etymonline/_locales.json @@ -14,6 +14,11 @@ "en": "results", "zh_CN": "个", "zh_TW": "個" + }, + "chart": { + "en": "Show Chart", + "zh_CN": "显示图表", + "zh_TW": "顯示圖表" } } -} \ No newline at end of file +} diff --git a/src/components/dictionaries/etymonline/engine.ts b/src/components/dictionaries/etymonline/engine.ts index 6186e2ce1..0ba96a4f2 100644 --- a/src/components/dictionaries/etymonline/engine.ts +++ b/src/components/dictionaries/etymonline/engine.ts @@ -7,8 +7,9 @@ const getInnerHTML = getInnerHTMLThunk() type EtymonlineResultItem = { title: string - href: string def: HTMLString + href?: string + chart?: string } export type EtymonlineResult = EtymonlineResultItem[] @@ -23,34 +24,31 @@ export default function search ( text = encodeURIComponent(text) // http to bypass the referer checking - return fetchDirtyDOM('http://www.etymonline.com/search?q=' + text) + return fetchDirtyDOM('https://www.etymonline.com/word/' + text) .then(doc => handleDOM(doc, options)) - .catch(() => fetchDirtyDOM('https://www.etymonline.com/search?q=' + text) - .then(doc => handleDOM(doc, options)) - ) + // .catch(() => fetchDirtyDOM('http://www.etymonline.com/search?q=' + text) + // .then(doc => handleDOM(doc, options)) + // ) + // .catch(() => fetchDirtyDOM('https://www.etymonline.com/search?q=' + text) + // .then(doc => handleDOM(doc, options)) + // ) } function handleDOM ( doc: Document, - { resultnum }: { resultnum: number }, + options: AppConfig['dicts']['all']['etymonline']['options'], ): EtymonlineSearchResult | Promise<EtymonlineSearchResult> { const result: EtymonlineResult = [] - const $items = Array.from(doc.querySelectorAll('[class^="word--"]')) + const $items = Array.from(doc.querySelectorAll('[class*="word--"]')) - for (let i = 0; i < $items.length && result.length < resultnum; i++) { + for (let i = 0; i < $items.length && result.length < options.resultnum; i++) { const $item = $items[i] - let href = $item.getAttribute('href') || '' - if (href[0] === '/') { - href = 'https://www.etymonline.com' + href - } - if (!href) { continue } - - const title = getText($item, '[class^="word__name--"]') + const title = getText($item, '[class*="word__name--"]') if (!title) { continue } let def = '' - const $def = $item.querySelector('[class^="word__defination--"]>object') + const $def = $item.querySelector('[class*="word__defination--"]>*') if ($def) { $def.querySelectorAll('.crossreference').forEach($cf => { let word = ($cf.textContent || '').trim() @@ -60,7 +58,18 @@ function handleDOM ( } if (!def) { continue } - result.push({ href, title, def }) + let href = ($item.getAttribute('href') || '') + .replace(/^\/(?!\/)/, 'https://www.etymonline.com/') + + let chart = '' + if (options.chart) { + const $chart = $item.querySelector<HTMLImageElement>('[class*="chart--"] img') + if ($chart) { + chart = $chart.src.replace(/^\/(?!\/)/, 'https://www.etymonline.com/') + } + } + + result.push({ href, title, def, chart }) } if (result.length > 0) { diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index f8075a162..c34852bac 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -46,7 +46,7 @@ export function getOuterHTMLThunk (host?: string) { if (!child) { return '' } const content = DOMPurify.sanitize(child['outerHTML'] || '') return host - ? content.replace(/href="\//g, 'href="' + host) + ? content.replace(/href="\/(?!\/)/g, 'href="' + host) : content } } diff --git a/test/specs/components/dictionaries/etymonline/response/love-word.html b/test/specs/components/dictionaries/etymonline/response/love-word.html new file mode 100644 index 000000000..6dbe0b2f9 --- /dev/null +++ b/test/specs/components/dictionaries/etymonline/response/love-word.html @@ -0,0 +1,32 @@ + + + <!DOCTYPE html> + <html lang="en"> + <head> + <title data-react-helmet="true" property="og:title">love | Origin and meaning of love by Online Etymology Dictionary</title> + <meta data-react-helmet="true" charset="UTF-8" content="text/html;charset=utf-8;"/><meta data-react-helmet="true" http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta data-react-helmet="true" name="viewport" content="width=device-width, initial-scale=1"/><meta data-react-helmet="true" name="theme-color" content="#83001d"/><meta data-react-helmet="true" name="msapplication-TileColor" content="#83001d"/><meta data-react-helmet="true" name="msapplication-TileImage" content="/ms-icon-144x144.png"/><meta data-react-helmet="true" name="keywords" content="love, online etymology dictionary, English dictionary, love meaning, love definition, define love, definition of love, love origin, love history, prefix, suffix, 词源, 前缀, 后缀, 語源, etymologie, этимология, 어원, etimoloji, etimologia, etymologi"/><meta data-react-helmet="true" name="description" property="og:description" content="Meaning: &quot;feeling of love; romantic sexual attraction; affection; friendliness; the love of God; Love as an abstraction or… See more definitions."/><meta data-react-helmet="true" property="og:image" content="https://www.etymonline.com/graphics/header.jpg"/><meta data-react-helmet="true" name="twitter:card" content="summary"/> + <link data-react-helmet="true" rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/giehjnnlopapngdjbjjgddpaagoimmgl"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="57x57" href="/static/favicon/apple-icon-57x57.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="60x60" href="/static/favicon/apple-icon-60x60.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="72x72" href="/static/favicon/apple-icon-72x72.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="76x76" href="/static/favicon/apple-icon-76x76.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="114x114" href="/static/favicon/apple-icon-114x114.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="120x120" href="/static/favicon/apple-icon-120x120.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="144x144" href="/static/favicon/apple-icon-144x144.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="152x152" href="/static/favicon/apple-icon-152x152.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="180x180" href="/static/favicon/apple-icon-180x180.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="192x192" href="/static/favicon/android-icon-192x192.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="32x32" href="/static/favicon/favicon-32x32.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="96x96" href="/static/favicon/favicon-96x96.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="16x16" href="/static/favicon/favicon-16x16.png"/><link data-react-helmet="true" rel="manifest" href="/manifest.json"/><link data-react-helmet="true" href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/><link data-react-helmet="true" type="text/css" rel="stylesheet" href="https://cdn.etymonline.com/projects/etymonline-main-v3/style.34c9a337d8faeb4ef5982c3822c5bb59.css"/><link data-react-helmet="true" rel="canonical" href="https://www.etymonline.com/word/love"/> + </head> + <body> + <div id="root"><div><div class="container--1mazc"><div class="header header--1Mejf header__vanila--2dqaM"><div class="header__vanila__container--CElq1"><div class="ant-row"><div class="ant-col-sm-17"><div class="inner--7ZeMs" data-role="header-inner"><div class="header__logo--12Lje" data-role="header-logo"><a href="/" title="Index"><div title="Online Etymology Dictionary Homepage" class="header__logo__image--2avl2 header__logo__image_modern--DysTU" data-role="header-logo-image"></div></a></div><div class="header__searchbar--3yKr5" data-role="header-searchbar"><div class="searchform"><form class="searchbar--3dK8Z" action="/search"><div class="searchbar__container--2VZd7"><input type="text" value="love" autocomplete="off" role="combobox" aria-autocomplete="list" aria-owns="react-autowhatever-1" aria-expanded="false" aria-haspopup="false" class="searchbar__input--3L4IY" placeholder="Search" name="q" required="" autocapitalize="off" autocorrect="off" title="Type a word to search."/><div id="react-autowhatever-1"></div></div><i class="fa fa-times-circle search-clear"></i><input type="submit" title="Search" value="" class="searchbar__button--3luO1"/></form></div></div></div></div><div class="ant-col-sm-6 ant-col-sm-offset-1"></div></div></div></div><div class="bannerAd--3BIq1"><div class="bannerAd_container--2Uhkn bait"><span class="bannerad" style="display:none;"></span></div></div><div class="main main--10rAd" data-role="content-main"><div class="wordDetail--1sAHq"><div class="ant-row-flex ant-row-flex-space-around"><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-17"><div class="adContainer-left"><span class="adLabel">Advertisement</span><ins class="adsbygoogle desktop" style="display:inline-block;width:728px;height:90px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="7157382713"></ins></div><div class="word--C9UPa"><div><h1 id="etymonline_v_14556" class="notranslate word__name--TTbAA" title="Origin and meaning of love">love (n.)</h1><section class="word__defination--2q7ZH"><div><p></p><p>Old English <span class="foreign notranslate">lufu</span> &quot;feeling of love; romantic sexual attraction; affection; friendliness; the love of God; Love as an abstraction or personification,&quot; from Proto-Germanic <span class="foreign notranslate">*lubo</span> (source also of Old High German <span class="foreign notranslate">liubi</span> &quot;joy,&quot; German <span class="foreign notranslate">Liebe</span> &quot;love;&quot; Old Norse, Old Frisian, Dutch <span class="foreign notranslate">lof</span>; German <span class="foreign notranslate">Lob</span> &quot;praise;&quot; Old Saxon <span class="foreign notranslate">liof</span>, Old Frisian <span class="foreign notranslate">liaf</span>, Dutch <span class="foreign notranslate">lief</span>, Old High German <span class="foreign notranslate">liob</span>, German <span class="foreign notranslate">lieb</span>, Gothic <span class="foreign notranslate">liufs</span> &quot;dear, beloved&quot;). The Germanic words are from PIE root <a href="/word/*leubh-?ref=etymonline_crossreference" class="crossreference notranslate">*leubh-</a> &quot;to care, desire, love.&quot; +</p><p></p><p></p><p> +</p><p>The weakened sense &quot;liking, fondness&quot; was in Old English. Meaning &quot;a beloved person&quot; is from early 13c. The sense &quot;no score&quot; (in tennis, etc.) is 1742, from the notion of <span class="foreign notranslate">playing for love</span> (1670s), that is, for no stakes. Phrase <span class="foreign notranslate">for love or money</span> &quot;for anything&quot; is attested from 1580s. The phrase <span class="foreign notranslate">no love lost</span> (between two people) is ambiguous and was used 17c. in reference to two who love each other well (c. 1640) as well as two who have no liking for each other (1620s, the usual modern sense). +</p><p></p><p></p><p> +</p><p>To <span class="foreign notranslate">fall in love</span> is attested from early 15c.; to be <span class="foreign notranslate">in love with</span> (someone) is from c. 1500. To <span class="foreign notranslate">make love</span> is from 1570s in the sense &quot;pay amorous attention to;&quot; as a euphemism for &quot;have sex,&quot; it is attested from c. 1950. <span class="foreign notranslate">Love scene</span> is from 1630s. <span class="foreign notranslate">Love affair</span> &quot;a particular experience of love&quot; is from 1590s. <span class="foreign notranslate">Love life</span> &quot;one&#x27;s collective amorous activities&quot; is from 1919, originally a term in psychological jargon. <span class="foreign notranslate">Love beads</span> is from 1968. <span class="foreign notranslate">Love bug</span>, imaginary insect, is from 1937. <span class="foreign notranslate">Love-handles</span> is from 1960s. +</p><p></p><ins class="adsbygoogle mobile" style="display:inline-block;width:300px;height:250px;" data-ad-slot="4000736339" data-ad-client="ca-pub-7093273770345366"></ins><blockquote> +<p></p><p>&quot;Even now,&quot; she thought, &quot;almost no one remembers Esteban and Pepita but myself. Camilla alone remembers her Uncle Pio and her son; this woman, her mother. But soon we shall die and all memory of those five will have left the earth, and we ourselves shall be loved for a while and forgotten. But the love will have been enough; all those impulses of love return the love that made them. Even memory is not necessary for love. There is a land of the living and a land of the dead and the bridge is love, the only survival, the only meaning.&quot; [Thornton Wilder, &quot;Bridge of San Luis Rey,&quot; 1927] +</p><p></p></blockquote><p></p><p></p></div></section><div class="chart--2x1ib"><div class="chart"><img src="https://cdn.etymonline.com/chart/etymology-love-14556p.jpg?t=1535599699000" alt="Origin and meaning of love" data-chart-id="etymology-love-14556"/></div></div></div></div><div class="word--C9UPa"><div><p id="etymonline_v_14557" class="notranslate word__name--TTbAA" title="Origin and meaning of love">love (v.)</p><section class="word__defination--2q7ZH"><div><p></p><p>Old English <span class="foreign notranslate">lufian</span> &quot;to feel love for, cherish, show love to; delight in, approve,&quot; from Proto-Germanic <span class="foreign notranslate">*lubojanan</span> (source also of Old High German <span class="foreign notranslate">lubon</span>, German <span class="foreign notranslate">lieben</span>), a verb from the root of <a href="/word/love?ref=etymonline_crossreference#etymonline_v_14556" class="crossreference notranslate">love</a> (n.). Weakened sense of &quot;like&quot; attested by c. 1200. Intransitive sense &quot;be in love, have a passionate attachment&quot; is from mid-13c. To <span class="foreign notranslate">love (someone) up</span> &quot;make out with&quot; is from 1921. To <span class="foreign notranslate">love and leave</span> is from 1885.</p><p></p><p></p><ins class="adsbygoogle mobile" style="display:inline-block;width:300px;height:250px;" data-ad-slot="4000736339" data-ad-client="ca-pub-7093273770345366"></ins></div></section><div class="chart--2x1ib"><div class="chart"><img src="https://cdn.etymonline.com/chart/etymology-love-14557p.jpg?t=1535599699000" alt="Origin and meaning of love" data-chart-id="etymology-love-14557"/></div></div></div></div><div class="related--32LCi"><h3 class="h3_title notranslate" title="words related to love">Related Entries</h3><ul class="related__container--22iKI"><a target="_self" title="Origin and meaning of *leubh-" href="/word/*leubh-"><li class="notranslate related__word--3Si0N">*leubh-</li></a><a target="_self" title="Origin and meaning of beloved" href="/word/beloved"><li class="notranslate related__word--3Si0N">beloved</li></a><a target="_self" title="Origin and meaning of lady-love" href="/word/lady-love"><li class="notranslate related__word--3Si0N">lady-love</li></a><a target="_self" title="Origin and meaning of libido" href="/word/libido"><li class="notranslate related__word--3Si0N">libido</li></a><a target="_self" title="Origin and meaning of lovable" href="/word/lovable"><li class="notranslate related__word--3Si0N">lovable</li></a><a target="_self" title="Origin and meaning of love-child" href="/word/love-child"><li class="notranslate related__word--3Si0N">love-child</li></a><a target="_self" title="Origin and meaning of loved" href="/word/loved"><li class="notranslate related__word--3Si0N">loved</li></a><a target="_self" title="Origin and meaning of love-hate" href="/word/love-hate"><li class="notranslate related__word--3Si0N">love-hate</li></a><a target="_self" title="Origin and meaning of love-knot" href="/word/love-knot"><li class="notranslate related__word--3Si0N">love-knot</li></a><a target="_self" title="Origin and meaning of loveless" href="/word/loveless"><li class="notranslate related__word--3Si0N">loveless</li></a><a target="_self" title="Origin and meaning of love-letter" href="/word/love-letter"><li class="notranslate related__word--3Si0N">love-letter</li></a><a target="_self" title="Origin and meaning of love-longing" href="/word/love-longing"><li class="notranslate related__word--3Si0N">love-longing</li></a><a target="_self" title="Origin and meaning of love-lorn" href="/word/love-lorn"><li class="notranslate related__word--3Si0N">love-lorn</li></a><a target="_self" title="Origin and meaning of lovely" href="/word/lovely"><li class="notranslate related__word--3Si0N">lovely</li></a><a target="_self" title="Origin and meaning of love-making" href="/word/love-making"><li class="notranslate related__word--3Si0N">love-making</li></a><a target="_self" title="Origin and meaning of lover" href="/word/lover"><li class="notranslate related__word--3Si0N">lover</li></a><a target="_self" title="Origin and meaning of love-seat" href="/word/love-seat"><li class="notranslate related__word--3Si0N">love-seat</li></a><a target="_self" title="Origin and meaning of lovesick" href="/word/lovesick"><li class="notranslate related__word--3Si0N">lovesick</li></a><a target="_self" title="Origin and meaning of lovesome" href="/word/lovesome"><li class="notranslate related__word--3Si0N">lovesome</li></a><a target="_self" title="Origin and meaning of love-song" href="/word/love-song"><li class="notranslate related__word--3Si0N">love-song</li></a></ul><a href="/word/love/scrabble" class="related__more--1gm0U related__word--3Si0N">See all related words (28)</a></div><div class="share-tool notranslate socialShare--223YS"><h3 title="Share love to social networks" class="socialShare__title--34iP2">Share</h3><a title="Share on Facebook" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.etymonline.com%2Fword%2Flove" data-social-target="Facebook" target="blank" class="fa share socialShare__icon--3FJac socialShare__icon__facebook--2fm3U fa-facebook"></a><a title="Share on Twitter" href="https://twitter.com/share?url=https%3A%2F%2Fwww.etymonline.com%2Fword%2Flove&amp;text=love%20%7C%20Origin%20and%20meaning%20of%20love%20by%20Online%20Etymology%20Dictionary" data-social-target="Twitter" target="blank" class="fa share socialShare__icon--3FJac socialShare__icon__twitter--1iFxf fa-twitter"></a><a title="Share on Reddit" href="https://www.reddit.com/submit?url=https%3A%2F%2Fwww.etymonline.com%2Fword%2Flove&amp;title=love%20%7C%20Origin%20and%20meaning%20of%20love%20by%20Online%20Etymology%20Dictionary" data-social-target="Reddit" target="blank" class="fa share socialShare__icon--3FJac socialShare__icon__reddit--30bBu fa-reddit"></a><a title="Share on Email" href="mailto:?subject=love%20%7C%20Origin%20and%20meaning%20of%20love%20by%20Online%20Etymology%20Dictionary&amp;body=Meaning%3A%20%22feeling%20of%20love%3B%20romantic%20sexual%20attraction%3B%20affection%3B%20friendliness%3B%20the%20love%20of%20God%3B%20Love%20as%20an%20abstraction%20or%E2%80%A6%20See%20more%20definitions.%0Afrom%20https%3A%2F%2Fwww.etymonline.com%2Fword%2Flove%20Find%20out%20more%20at%20etymonline.com" data-social-target="Email" target="blank" class="fa share socialShare__icon--3FJac socialShare__icon__email--3hVBm fa-email"></a></div><a class="ad extension link--3mrBs link_banner--11FDz" target="_blank"><div class="wordDetail__extensionBanner--2Qrhv"></div></a></div><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-6"><div class="adContainer-top"><span class="adLabel">Advertisement</span><ins class="adsbygoogle desktop bypass" style="display:inline-block;width:300px;height:250px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="3516331235"></ins></div><a class="ad peigencihui-ad link--3mrBs link_square--3tXhH" target="_blank" rel="nofollow" href="http://blog.dancite.com/peigen-app-wechat/?ref=etymonline_ad"><div class="imageBlock--2hygR"></div></a><div class="alphabetical--2oTZG"><h3 title="words in alphabetical order" class="h3_title notranslate">Alphabetical list</h3><a title="Origin and meaning of lousy" target="" href="/word/lousy"><p class="notranslate alphabetical__word--3UeP2">lousy</p></a><a title="Origin and meaning of lout" target="" href="/word/lout"><p class="notranslate alphabetical__word--3UeP2">lout</p></a><a title="Origin and meaning of loutish" target="" href="/word/loutish"><p class="notranslate alphabetical__word--3UeP2">loutish</p></a><a title="Origin and meaning of louver" target="" href="/word/louver"><p class="notranslate alphabetical__word--3UeP2">louver</p></a><a title="Origin and meaning of lovable" target="" href="/word/lovable"><p class="notranslate alphabetical__word--3UeP2">lovable</p></a><p class="notranslate alphabetical__word--3UeP2 alphabetical__active--FCYcm">love</p><a title="Origin and meaning of love-apple" target="" href="/word/love-apple"><p class="notranslate alphabetical__word--3UeP2">love-apple</p></a><a title="Origin and meaning of love-bird" target="" href="/word/love-bird"><p class="notranslate alphabetical__word--3UeP2">love-bird</p></a><a title="Origin and meaning of love-child" target="" href="/word/love-child"><p class="notranslate alphabetical__word--3UeP2">love-child</p></a><a title="Origin and meaning of loved" target="" href="/word/loved"><p class="notranslate alphabetical__word--3UeP2">loved</p></a><a title="Origin and meaning of love-hate" target="" href="/word/love-hate"><p class="notranslate alphabetical__word--3UeP2">love-hate</p></a></div><div id="google_translate_element"></div></div></div></div></div><div class="alphabet--3sMXd"><ul class="alphabet__inner--2NEtM"><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter A"><a href="/search?q=a">A</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter B"><a href="/search?q=b">B</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter C"><a href="/search?q=c">C</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter D"><a href="/search?q=d">D</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter E"><a href="/search?q=e">E</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter F"><a href="/search?q=f">F</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter G"><a href="/search?q=g">G</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter H"><a href="/search?q=h">H</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter I"><a href="/search?q=i">I</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter J"><a href="/search?q=j">J</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter K"><a href="/search?q=k">K</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter L"><a href="/search?q=l">L</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter M"><a href="/search?q=m">M</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter N"><a href="/search?q=n">N</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter O"><a href="/search?q=o">O</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter P"><a href="/search?q=p">P</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Q"><a href="/search?q=q">Q</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter R"><a href="/search?q=r">R</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter S"><a href="/search?q=s">S</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter T"><a href="/search?q=t">T</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter U"><a href="/search?q=u">U</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter V"><a href="/search?q=v">V</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter W"><a href="/search?q=w">W</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter X"><a href="/search?q=x">X</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Y"><a href="/search?q=y">Y</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Z"><a href="/search?q=z">Z</a></li></ul></div><div class="footer--zLQrv"><div class="footer__info--3VNMU"><div class="footer__info_inner--1aVeV"><div><p class="footer__info_title--3LoBd">links</p><a href="/classic?ref=etymonline_footer" class="footer__info_node--3T-ZQ classicbait">Classic Version</a><a href="/columns/post/sources?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Sources</a><a href="/columns/post/links?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Links</a></div><div><p class="footer__info_title--3LoBd">more</p><a href="https://chrome.google.com/webstore/detail/etymonline/giehjnnlopapngdjbjjgddpaagoimmgl?ref=link_footer" class="footer__info_node--3T-ZQ">Chrome Extension</a><a href="https://itunes.apple.com/app/apple-store/id813629612?pt=33423801&amp;ct=etymonline_footer&amp;mt=8" class="footer__info_node--3T-ZQ">词根词源词典 App</a><a href="http://blog.dancite.com/peigen-app-wechat/?ref=etymonline_footer" class="footer__info_node--3T-ZQ">培根词汇微信公众号</a></div><div><p class="footer__info_title--3LoBd">about etymonline</p><a href="/columns/post/abbr?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Introduction</a><a href="/columns/post/bio?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Who did this</a><a href="https://www.facebook.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Follow on Facebook</a></div><div><p class="footer__info_title--3LoBd">support us</p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;[email protected]&amp;lc=US&amp;item_name=Donation+to +Help+Keep+Etymonline+Free+and+Open&amp;no_note=0&amp;cn=&amp;curency_code=USD&amp;bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted" class="footer__info_node--3T-ZQ">Donate with PayPal</a><a href="http://www.cafepress.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Ye Olde Swag Shoppe</a><a href="https://www.patreon.com/etymonline?ref=etymonline.com" class="footer__info_node--3T-ZQ">Support on Patreon</a></div></div></div><div class="footer__link--1RSEJ"><div class="footer__link_inner--KP2Wz"><p>Web design and development by MaoningTech.</p><a href="mailto:[email protected]" title="Douglas Harper. All rights reserved.">© 2001-2018 Douglas Harper. All rights reserved.</a></div></div></div><div class="backtop"><div class="backtop-content"><i class="fa fa-arrow-up"></i></div></div></div></div></div> + <script async src="https://www.googletagmanager.com/gtag/js?id=UA-26425972-1"></script> + <script> + window.dataLayer = window.dataLayer || []; + function gtag(){dataLayer.push(arguments);} + gtag('js', new Date()); + gtag('config', 'UA-26425972-1'); + </script> + <script + type="text/javascript" + src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" + ></script> + <script data-react-helmet="true" src="https://cdn.etymonline.com/projects/etymonline-main-v3/jquery-3.2.1.min.js"></script><script data-react-helmet="true" src="https://cdn.etymonline.com/projects/etymonline-main-v3/plugins.8c4c86fb3a77e30e5214.js" async="true"></script><script data-react-helmet="true" async="true" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> + </body> + </html> diff --git a/test/specs/components/dictionaries/etymonline/response/love.html b/test/specs/components/dictionaries/etymonline/response/love.html index 2f83058aa..d1ff9e0a9 100644 --- a/test/specs/components/dictionaries/etymonline/response/love.html +++ b/test/specs/components/dictionaries/etymonline/response/love.html @@ -5,13 +5,15 @@ <head> <title data-react-helmet="true" name="twitter:title">love | Search Online Etymology Dictionary</title> <meta data-react-helmet="true" charset="UTF-8" content="text/html;charset=utf-8;"/><meta data-react-helmet="true" http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta data-react-helmet="true" name="viewport" content="width=device-width, initial-scale=1"/><meta data-react-helmet="true" name="theme-color" content="#83001d"/><meta data-react-helmet="true" name="keywords" content="online etymology dictionary, English dictionary, 英语词源在线词典, 語源, etymologie, этимология, 어원, etimoloji, etimologia, etymologi, ετυμολογία, origin, history, prefix, suffix, thesaurus, glossary, translation, language, define, definition, meaning, spelling, terminology, medical, computer, education, science, biology, trending words, reference, free dictionary"/><meta data-react-helmet="true" name="description" property="og:description" content="The online etymology dictionary is the internet&#x27;s go-to source for quick and reliable accounts of the origin and history of English words, phrases, and idioms. It is professional enough to satisfy academic standards, but accessible enough to be used by anyone. The site has become a favorite resource of teachers of reading, spelling, and English as a second language."/><meta data-react-helmet="true" name="msapplication-TileColor" content="#83001d"/><meta data-react-helmet="true" name="msapplication-TileImage" content="/ms-icon-144x144.png"/><meta data-react-helmet="true" property="og:image" name="twitter:image" content="https://www.etymonline.com/graphics/header.jpg"/><meta data-react-helmet="true" name="twitter:card" content="summary_large_image"/> - <link data-react-helmet="true" rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/giehjnnlopapngdjbjjgddpaagoimmgl"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="57x57" href="/static/favicon/apple-icon-57x57.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="60x60" href="/static/favicon/apple-icon-60x60.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="72x72" href="/static/favicon/apple-icon-72x72.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="76x76" href="/static/favicon/apple-icon-76x76.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="114x114" href="/static/favicon/apple-icon-114x114.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="120x120" href="/static/favicon/apple-icon-120x120.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="144x144" href="/static/favicon/apple-icon-144x144.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="152x152" href="/static/favicon/apple-icon-152x152.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="180x180" href="/static/favicon/apple-icon-180x180.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="192x192" href="/static/favicon/android-icon-192x192.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="32x32" href="/static/favicon/favicon-32x32.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="96x96" href="/static/favicon/favicon-96x96.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="16x16" href="/static/favicon/favicon-16x16.png"/><link data-react-helmet="true" rel="manifest" href="/manifest.json"/><link data-react-helmet="true" href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/><link data-react-helmet="true" rel="stylesheet" href="/static/style.9cd46109e08869d7ffe7257cb22e7d04.css"/> + <link data-react-helmet="true" rel="chrome-webstore-item" href="https://chrome.google.com/webstore/detail/giehjnnlopapngdjbjjgddpaagoimmgl"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="57x57" href="/static/favicon/apple-icon-57x57.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="60x60" href="/static/favicon/apple-icon-60x60.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="72x72" href="/static/favicon/apple-icon-72x72.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="76x76" href="/static/favicon/apple-icon-76x76.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="114x114" href="/static/favicon/apple-icon-114x114.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="120x120" href="/static/favicon/apple-icon-120x120.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="144x144" href="/static/favicon/apple-icon-144x144.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="152x152" href="/static/favicon/apple-icon-152x152.png"/><link data-react-helmet="true" rel="apple-touch-icon" sizes="180x180" href="/static/favicon/apple-icon-180x180.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="192x192" href="/static/favicon/android-icon-192x192.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="32x32" href="/static/favicon/favicon-32x32.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="96x96" href="/static/favicon/favicon-96x96.png"/><link data-react-helmet="true" rel="icon" type="image/png" sizes="16x16" href="/static/favicon/favicon-16x16.png"/><link data-react-helmet="true" rel="manifest" href="/manifest.json"/><link data-react-helmet="true" href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/><link data-react-helmet="true" type="text/css" rel="stylesheet" href="https://cdn.etymonline.com/projects/etymonline-main-v3/style.34c9a337d8faeb4ef5982c3822c5bb59.css"/> </head> <body> - <div id="root"><div><div class="container--1mazc"><div class="header header--1Mejf header__vanila--2dqaM"><div class="header__vanila__container--CElq1"><div class="ant-row"><div class="ant-col-sm-17"><div class="inner--7ZeMs" data-role="header-inner"><div class="header__logo--12Lje" data-role="header-logo"><a href="/" title="Index"><div title="Online Etymology Dictionary Homepage" class="header__logo__image--2avl2 header__logo__image_modern--DysTU" data-role="header-logo-image"></div></a></div><div class="header__searchbar--3yKr5" data-role="header-searchbar"><div class="searchform"><form class="searchbar--3dK8Z" action="/search"><div class="searchbar__container--2VZd7"><input type="text" value="love" autocomplete="off" role="combobox" aria-autocomplete="list" aria-owns="react-autowhatever-1" aria-expanded="false" aria-haspopup="false" class="searchbar__input--3L4IY" placeholder="Search" name="q" required="" autocapitalize="off" autocorrect="off" title="Type a word to search."/><div id="react-autowhatever-1"></div></div><i class="fa fa-times-circle search-clear"></i><input type="submit" title="Search" value="" class="searchbar__button--3luO1"/></form></div></div></div></div><div class="ant-col-sm-6 ant-col-sm-offset-1"></div></div></div></div><div class="bannerAd--3BIq1"><div class="bannerAd_container--2Uhkn bait"><span class="bannerad" style="display:none;"></span></div></div><div class="main main--10rAd" data-role="content-main"><div class="searchList--2GaBs"><div class="ant-row-flex ant-row-flex-space-around"><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-17"><div><div class="adContainer-left"><span class="adLabel">Advertisement</span><ins class="adsbygoogle desktop" style="display:inline-block;width:728px;height:90px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="8941237679"></ins></div><div class="searchList__pageCount--2jQdB">267 entries found</div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love">love (v.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>Old English <span class="foreign">lufian</span> &quot;to feel <em>love</em> for, cherish, show <em>love</em> to; delight in, approve,&quot; from Proto-Germanic <span class="foreign">*lubojan</span> (source also of Old High … German <span class="foreign">lubon</span>, German <span class="foreign">lieben</span>), a verb from the root of <span class="crossreference"><em>love</em></span> (n.). Weakened sense of &quot;like&quot; attested by c. 1200 … Intransitive sense &quot;be in <em>love</em>, have a passionate attachment&quot; is from mid-13c. To <span class="foreign"><em>love</em> (someone) up</span> &quot;make out with&quot; is from 1921. To <span class="foreign"><em>love</em> and leave</span> is from 1885.</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love">love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>Old English <span class="foreign">lufu</span> &quot;feeling of <em>love</em>; romantic sexual attraction; affection; friendliness; the <em>love</em> of God; <em>Love</em> as an abstraction or personification,&quot; from Proto-Germanic … <span class="foreign">*lubo</span> (source also of Old High German <span class="foreign">liubi</span> &quot;joy,&quot; German <span class="foreign">Liebe</span> &quot;<em>love</em>;&quot; Old Norse, Old Frisian, Dutch … <span class="crossreference">*leubh-</span> &quot;to care, desire, <em>love</em>.&quot; + <div id="root"><div><div class="container--1mazc"><div class="header header--1Mejf header__vanila--2dqaM"><div class="header__vanila__container--CElq1"><div class="ant-row"><div class="ant-col-sm-17"><div class="inner--7ZeMs" data-role="header-inner"><div class="header__logo--12Lje" data-role="header-logo"><a href="/" title="Index"><div title="Online Etymology Dictionary Homepage" class="header__logo__image--2avl2 header__logo__image_modern--DysTU" data-role="header-logo-image"></div></a></div><div class="header__searchbar--3yKr5" data-role="header-searchbar"><div class="searchform"><form class="searchbar--3dK8Z" action="/search"><div class="searchbar__container--2VZd7"><input type="text" value="love" autocomplete="off" role="combobox" aria-autocomplete="list" aria-owns="react-autowhatever-1" aria-expanded="false" aria-haspopup="false" class="searchbar__input--3L4IY" placeholder="Search" name="q" required="" autocapitalize="off" autocorrect="off" title="Type a word to search."/><div id="react-autowhatever-1"></div></div><i class="fa fa-times-circle search-clear"></i><input type="submit" title="Search" value="" class="searchbar__button--3luO1"/></form></div></div></div></div><div class="ant-col-sm-6 ant-col-sm-offset-1"></div></div></div></div><div class="bannerAd--3BIq1"><div class="bannerAd_container--2Uhkn bait"><span class="bannerad" style="display:none;"></span></div></div><div class="main main--10rAd" data-role="content-main"><div class="searchList--2GaBs"><div class="ant-row-flex ant-row-flex-space-around"><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-17"><div><div class="adContainer-left"><span class="adLabel">Advertisement</span><ins class="adsbygoogle desktop" style="display:inline-block;width:728px;height:90px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="8941237679"></ins></div><div class="searchList__pageCount--2jQdB">274 entries found</div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love#etymonline_v_14557"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love">love (v.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div><p>Old English <span class="foreign">lufian</span> &quot;to feel <em>love</em> for, cherish, show <em>love</em> to; delight in, approve,&quot; from Proto-Germanic <span class="foreign">*lubojanan</span> (source also of Old High … German <span class="foreign">lubon</span>, German <span class="foreign">lieben</span>), a verb from the root of <span class="crossreference"><em>love</em></span> (n.). Weakened sense of &quot;like&quot; attested by c … 1200. Intransitive sense &quot;be in <em>love</em>, have a passionate attachment&quot; is from mid-13c. To <span class="foreign"><em>love</em> (someone) up</span> &quot;make out with&quot; is from 1921. To <span class="foreign"><em>love</em> and leave</span> is from 1885.</p> …</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love#etymonline_v_14556"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love">love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>Old English <span class="foreign">lufu</span> &quot;feeling of <em>love</em>; romantic sexual attraction; affection; friendliness; the <em>love</em> of God; <em>Love</em> as an abstraction or personification,&quot; from Proto-Germanic … <span class="foreign">*lubo</span> (source also of Old High German <span class="foreign">liubi</span> &quot;joy,&quot; German <span class="foreign">Liebe</span> &quot;<em>love</em>;&quot; Old Norse, Old Frisian, Dutch … <span class="crossreference">*leubh-</span> &quot;to care, desire, <em>love</em>.&quot; -The weakened sense &quot;liking, fondness&quot; was in Old English. Meaning &quot;a beloved person&quot; is from early 13c. The sense &quot;no score …</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-letter"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-letter">love-letter (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>mid-13c., from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">letter</span> (n.).</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-seat"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-seat">love-seat (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>1904, from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">seat</span> (n.).</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-song"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-song">love-song (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>early 14c., from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">song</span> (n.). - …</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/self-love"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of self-love">self-love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>also <span class="foreign">self <em>love</em></span>, 1560s, from <span class="crossreference">self-</span> + <span class="crossreference"><em>love</em></span> (n.).</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-tap"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-tap">love-tap (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>&quot;gentle blow given affectionately,&quot; 1848, from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">tap</span> (n.2).</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-hate"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-hate">love-hate (adj.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>expressing ambivalent and strong feelings toward someone or something, 1935, originally in the jargon of psychology, from <span class="crossreference"><em>love</em></span> + <span class="crossreference">hate</span>.</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/lady-love"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of lady-love">lady-love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>&quot;woman who is the object of one&#x27;s affections,&quot; 1733; see <span class="crossreference">lady</span> + <span class="crossreference"><em>love</em></span> (n.).</object></section></div></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-knot"><div><p class="word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-knot">love-knot (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><object>bow or ribbon tied in a particular way, as a <em>love</em> token, late 14c., from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">knot</span> (n.).</object></section></div></a></div><div><div class="pagination_simple--1ilDd"><span></span><a href="/search?page=2&amp;q=love">Next</a><a title="next" class="pagination_simple_next--3KB2t" href="/search?page=2&amp;q=love"><i class="fa fa-2x fa-angle-right" aria-hidden="true"></i></a></div><ul class="ant-pagination pagination--1DEpf" unselectable="unselectable"><li title="Previous Page" tabindex="0" class="ant-pagination-disabled ant-pagination-prev" aria-disabled="true"><a href="/search?page=0&amp;q=love">Prev</a></li><li title="1" class="ant-pagination-item ant-pagination-item-1 ant-pagination-item-active" tabindex="0"><a href="/search?page=1&amp;q=love">1</a></li><li title="2" class="ant-pagination-item ant-pagination-item-2" tabindex="0"><a href="/search?page=2&amp;q=love">2</a></li><li title="3" class="ant-pagination-item ant-pagination-item-3" tabindex="0"><a href="/search?page=3&amp;q=love">3</a></li><li title="4" class="ant-pagination-item ant-pagination-item-4" tabindex="0"><a href="/search?page=4&amp;q=love">4</a></li><li title="5" class="ant-pagination-item ant-pagination-item-5 ant-pagination-item-before-jump-next" tabindex="0"><a href="/search?page=5&amp;q=love">5</a></li><li title="Next 5 Pages" tabindex="0" class="ant-pagination-jump-next"><a class="ant-pagination-item-link"></a></li><li title="27" class="ant-pagination-item ant-pagination-item-27" tabindex="0"><a href="/search?page=27&amp;q=love">27</a></li><li title="Next Page" tabindex="0" class=" ant-pagination-next" aria-disabled="false"><a href="/search?page=2&amp;q=love">Next</a></li></ul></div></div></div><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-6"><div class="adContainer-top"><span class="adLabel">Advertisement</span><ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="6781721037"></ins></div><div class="trending__normal--2eWJF"><div><h3 class="h3_title">Trending Words</h3><ul><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of catholic" href="/word/catholic?ref=trending_srp">1. catholic</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of good-bye" href="/word/good-bye?ref=trending_srp">2. good-bye</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of bear" href="/word/bear?ref=trending_srp">3. bear</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of deadline" href="/word/deadline?ref=trending_srp">4. deadline</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of faith" href="/word/faith?ref=trending_srp">5. faith</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of hysterical" href="/word/hysterical?ref=trending_srp">6. hysterical</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of medicine" href="/word/medicine?ref=trending_srp">7. medicine</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of rover" href="/word/rover?ref=trending_srp">8. rover</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of language" href="/word/language?ref=trending_srp">9. language</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of egypt" href="/word/egypt?ref=trending_srp">10. egypt</a></li></ul></div></div></div></div></div></div><div class="alphabet--3sMXd"><ul class="alphabet__inner--2NEtM"><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter A"><a href="/search?q=a">A</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter B"><a href="/search?q=b">B</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter C"><a href="/search?q=c">C</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter D"><a href="/search?q=d">D</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter E"><a href="/search?q=e">E</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter F"><a href="/search?q=f">F</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter G"><a href="/search?q=g">G</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter H"><a href="/search?q=h">H</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter I"><a href="/search?q=i">I</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter J"><a href="/search?q=j">J</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter K"><a href="/search?q=k">K</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter L"><a href="/search?q=l">L</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter M"><a href="/search?q=m">M</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter N"><a href="/search?q=n">N</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter O"><a href="/search?q=o">O</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter P"><a href="/search?q=p">P</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Q"><a href="/search?q=q">Q</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter R"><a href="/search?q=r">R</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter S"><a href="/search?q=s">S</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter T"><a href="/search?q=t">T</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter U"><a href="/search?q=u">U</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter V"><a href="/search?q=v">V</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter W"><a href="/search?q=w">W</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter X"><a href="/search?q=x">X</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Y"><a href="/search?q=y">Y</a></li><li class="alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Z"><a href="/search?q=z">Z</a></li></ul></div><div class="footer--zLQrv"><div class="footer__info--3VNMU"><div class="footer__info_inner--1aVeV"><div><p class="footer__info_title--3LoBd">links</p><a href="/classic?ref=etymonline_footer" class="footer__info_node--3T-ZQ classicbait">Classic Version</a><a href="/columns/post/sources?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Sources</a><a href="/columns/post/links?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Links</a></div><div><p class="footer__info_title--3LoBd">more</p><a href="https://chrome.google.com/webstore/detail/etymonline/giehjnnlopapngdjbjjgddpaagoimmgl?ref=link_footer" class="footer__info_node--3T-ZQ">Chrome Extension</a><a href="https://itunes.apple.com/app/apple-store/id813629612?pt=33423801&amp;ct=etymonline_footer&amp;mt=8" class="footer__info_node--3T-ZQ">词根词源词典 App</a><a href="http://blog.dancite.com/peigen-app-wechat/?ref=etymonline_footer" class="footer__info_node--3T-ZQ">培根词汇微信公众号</a></div><div><p class="footer__info_title--3LoBd">about etymonline</p><a href="/columns/post/abbr?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Introduction</a><a href="/columns/post/bio?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Who did this</a><a href="https://www.facebook.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Follow on Facebook</a></div><div><p class="footer__info_title--3LoBd">support us</p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;[email protected]&amp;lc=US&amp;item_name=Donation+to +Help+Keep+Etymonline+Free+and+Open&amp;no_note=0&amp;cn=&amp;curency_code=USD&amp;bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted" class="footer__info_node--3T-ZQ">Donate with PayPal</a><a href="http://www.cafepress.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Ye Olde Swag Shoppe</a><a href="https://www.patreon.com/etymonline?ref=etymonline.com" class="footer__info_node--3T-ZQ">Support on Patreon</a></div></div></div><div class="footer__link--1RSEJ"><div class="footer__link_inner--KP2Wz"><p>Web design and development by MaoningTech.</p><a href="mailto:[email protected]" title="Douglas Harper. All rights reserved.">© 2001-2018 Douglas Harper. All rights reserved.</a></div></div></div><div class="backtop"><div class="backtop-content"><i class="fa fa-arrow-up"></i></div></div></div></div></div> +The weakened sense &quot;liking, fondness&quot; was in Old English. Meaning &quot;a beloved person&quot; is from early 13c. The sense &quot;no score …</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-letter#etymonline_v_52025"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-letter">love-letter (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>mid-13c., from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">letter</span> (n.).</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-seat#etymonline_v_52024"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-seat">love-seat (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>1904, from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">seat</span> (n.).</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-song#etymonline_v_52026"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-song">love-song (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>early 14c., from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">song</span> (n.). + …</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/self-love#etymonline_v_48450"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of self-love">self-love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>also <span class="foreign">self <em>love</em></span>, 1560s, from <span class="crossreference">self-</span> + <span class="crossreference"><em>love</em></span> (n.).</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-tap#etymonline_v_52027"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-tap">love-tap (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>&quot;gentle blow given affectionately,&quot; 1848, from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">tap</span> (n.2).</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-hate#etymonline_v_52023"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-hate">love-hate (adj.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>expressing ambivalent and strong feelings toward someone or something, 1935, originally in the jargon of psychology, from <span class="crossreference"><em>love</em></span> + <span class="crossreference">hate</span>.</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/lady-love#etymonline_v_51757"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of lady-love">lady-love (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>&quot;woman who is the object of one&#x27;s affections,&quot; 1733; see <span class="crossreference">lady</span> + <span class="crossreference"><em>love</em></span> (n.).</div></section></div></object></a></div><div><a class="word--C9UPa word_thumbnail--2DBNk" href="/word/love-longing#etymonline_v_25785"><object><div><p class="notranslate word__name--TTbAA word_thumbnail__name--1khEg" title="Origin and meaning of love-longing">love-longing (n.)</p><section class="word__defination--2q7ZH word__defination_thumbnail--HCtyA"><div>c. 1300, <span class="foreign">luue langing</span>, from <span class="crossreference"><em>love</em></span> (n.) + <span class="crossreference">longing</span> (n.). + + …</div></section></div></object></a></div><div><div class="pagination_simple--1ilDd"><span></span><a href="/search?page=2&amp;q=love">Next</a><a title="next" class="pagination_simple_next--3KB2t" href="/search?page=2&amp;q=love"><i class="fa fa-2x fa-angle-right" aria-hidden="true"></i></a></div><ul class="ant-pagination pagination--1DEpf" unselectable="unselectable"><li title="Previous Page" tabindex="0" class="ant-pagination-disabled ant-pagination-prev" aria-disabled="true"><a href="/search?page=0&amp;q=love">Prev</a></li><li title="1" class="ant-pagination-item ant-pagination-item-1 ant-pagination-item-active" tabindex="0"><a href="/search?page=1&amp;q=love">1</a></li><li title="2" class="ant-pagination-item ant-pagination-item-2" tabindex="0"><a href="/search?page=2&amp;q=love">2</a></li><li title="3" class="ant-pagination-item ant-pagination-item-3" tabindex="0"><a href="/search?page=3&amp;q=love">3</a></li><li title="4" class="ant-pagination-item ant-pagination-item-4" tabindex="0"><a href="/search?page=4&amp;q=love">4</a></li><li title="5" class="ant-pagination-item ant-pagination-item-5 ant-pagination-item-before-jump-next" tabindex="0"><a href="/search?page=5&amp;q=love">5</a></li><li title="Next 5 Pages" tabindex="0" class="ant-pagination-jump-next"><a class="ant-pagination-item-link"></a></li><li title="28" class="ant-pagination-item ant-pagination-item-28" tabindex="0"><a href="/search?page=28&amp;q=love">28</a></li><li title="Next Page" tabindex="0" class=" ant-pagination-next" aria-disabled="false"><a href="/search?page=2&amp;q=love">Next</a></li></ul></div></div></div><div class="ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-lg-6"><div class="adContainer-top"><span class="adLabel">Advertisement</span><ins class="adsbygoogle" style="display:inline-block;width:300px;height:250px;" data-ad-client="ca-pub-7093273770345366" data-ad-slot="6781721037"></ins></div><div class="trending__normal--2eWJF"><div><h3 class="h3_title">Trending Words</h3><ul><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of kamikaze" href="/word/kamikaze?ref=trending_srp">1. kamikaze</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of fascist" href="/word/fascist?ref=trending_srp">2. fascist</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of value" href="/word/value?ref=trending_srp">3. value</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of digest" href="/word/digest?ref=trending_srp">4. digest</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of pharmacy" href="/word/pharmacy?ref=trending_srp">5. pharmacy</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of extravagant" href="/word/extravagant?ref=trending_srp">6. extravagant</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of technology" href="/word/technology?ref=trending_srp">7. technology</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of leg" href="/word/leg?ref=trending_srp">8. leg</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of mnemonic" href="/word/mnemonic?ref=trending_srp">9. mnemonic</a></li><li class="trending__normal__word--1Qvnq"><a title="Origin and meaning of sinister" href="/word/sinister?ref=trending_srp">10. sinister</a></li></ul></div></div></div></div></div></div><div class="alphabet--3sMXd"><ul class="alphabet__inner--2NEtM"><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter A"><a href="/search?q=a">A</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter B"><a href="/search?q=b">B</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter C"><a href="/search?q=c">C</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter D"><a href="/search?q=d">D</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter E"><a href="/search?q=e">E</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter F"><a href="/search?q=f">F</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter G"><a href="/search?q=g">G</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter H"><a href="/search?q=h">H</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter I"><a href="/search?q=i">I</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter J"><a href="/search?q=j">J</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter K"><a href="/search?q=k">K</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter L"><a href="/search?q=l">L</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter M"><a href="/search?q=m">M</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter N"><a href="/search?q=n">N</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter O"><a href="/search?q=o">O</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter P"><a href="/search?q=p">P</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Q"><a href="/search?q=q">Q</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter R"><a href="/search?q=r">R</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter S"><a href="/search?q=s">S</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter T"><a href="/search?q=t">T</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter U"><a href="/search?q=u">U</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter V"><a href="/search?q=v">V</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter W"><a href="/search?q=w">W</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter X"><a href="/search?q=x">X</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Y"><a href="/search?q=y">Y</a></li><li class="notranslate alphabet__node--huwT8" title="Prefix, suffix and words starting with the letter Z"><a href="/search?q=z">Z</a></li></ul></div><div class="footer--zLQrv"><div class="footer__info--3VNMU"><div class="footer__info_inner--1aVeV"><div><p class="footer__info_title--3LoBd">links</p><a href="/classic?ref=etymonline_footer" class="footer__info_node--3T-ZQ classicbait">Classic Version</a><a href="/columns/post/sources?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Sources</a><a href="/columns/post/links?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Links</a></div><div><p class="footer__info_title--3LoBd">more</p><a href="https://chrome.google.com/webstore/detail/etymonline/giehjnnlopapngdjbjjgddpaagoimmgl?ref=link_footer" class="footer__info_node--3T-ZQ">Chrome Extension</a><a href="https://itunes.apple.com/app/apple-store/id813629612?pt=33423801&amp;ct=etymonline_footer&amp;mt=8" class="footer__info_node--3T-ZQ">词根词源词典 App</a><a href="http://blog.dancite.com/peigen-app-wechat/?ref=etymonline_footer" class="footer__info_node--3T-ZQ">培根词汇微信公众号</a></div><div><p class="footer__info_title--3LoBd">about etymonline</p><a href="/columns/post/abbr?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Introduction</a><a href="/columns/post/bio?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Who did this</a><a href="https://www.facebook.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Follow on Facebook</a></div><div><p class="footer__info_title--3LoBd">support us</p><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;[email protected]&amp;lc=US&amp;item_name=Donation+to +Help+Keep+Etymonline+Free+and+Open&amp;no_note=0&amp;cn=&amp;curency_code=USD&amp;bn=PP-DonationsBF:btn_donateCC_LG.gif:NonHosted" class="footer__info_node--3T-ZQ">Donate with PayPal</a><a href="http://www.cafepress.com/etymonline?ref=etymonline_footer" class="footer__info_node--3T-ZQ">Ye Olde Swag Shoppe</a><a href="https://www.patreon.com/etymonline?ref=etymonline.com" class="footer__info_node--3T-ZQ">Support on Patreon</a></div></div></div><div class="footer__link--1RSEJ"><div class="footer__link_inner--KP2Wz"><p>Web design and development by MaoningTech.</p><a href="mailto:[email protected]" title="Douglas Harper. All rights reserved.">© 2001-2018 Douglas Harper. All rights reserved.</a></div></div></div><div class="backtop"><div class="backtop-content"><i class="fa fa-arrow-up"></i></div></div></div></div></div> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-26425972-1"></script> <script> window.dataLayer = window.dataLayer || []; @@ -19,7 +21,10 @@ gtag('js', new Date()); gtag('config', 'UA-26425972-1'); </script> - <script data-react-helmet="true" src="/static/jquery-3.2.1.min.js"></script><script data-react-helmet="true" src="/static/plugins.8b94d9a1afab4fce8a48.js" async="true"></script> + <script + type="text/javascript" + src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" + ></script> + <script data-react-helmet="true" src="https://cdn.etymonline.com/projects/etymonline-main-v3/jquery-3.2.1.min.js"></script><script data-react-helmet="true" src="https://cdn.etymonline.com/projects/etymonline-main-v3/plugins.8c4c86fb3a77e30e5214.js" async="true"></script> </body> </html> - \ No newline at end of file
fix
fix etymonline
d40cf2a762609b9f57851617bdd150244e186f02
2018-07-26 21:36:14
CRIMX
feat(panel): open links in new tabs
false
diff --git a/src/content/components/DictItem/index.tsx b/src/content/components/DictItem/index.tsx index 2c9767c6b..70299f2b1 100644 --- a/src/content/components/DictItem/index.tsx +++ b/src/content/components/DictItem/index.tsx @@ -140,6 +140,8 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati } handleDictItemClick = (e: React.MouseEvent<HTMLElement>) => { + if (e.ctrlKey || e.metaKey || e.altKey) { return } + // use background script to open new page const $target = e.target as HTMLElement if (!$target.tagName || !$target.parentElement) { return }
feat
open links in new tabs
e13b1fc3c255f42a95b098d929c6721e3a51de25
2020-07-12 11:45:10
crimx
chore(release): 7.14.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index f15796e49..f4a96317f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +### [7.14.1](https://github.com/crimx/ext-saladict/compare/v7.14.0...v7.14.1) (2020-07-12) + + +### Bug Fixes + +* **options:** update antd typings ([2879c4f](https://github.com/crimx/ext-saladict/commit/2879c4fe9e1ef6a5397ac807ce94a2d188d61d30)) +* fixed incorrect options merging ([8e062dc](https://github.com/crimx/ext-saladict/commit/8e062dc7dc87642da282bcceeabbaf86d58770f4)) +* switch default slInitial back to collapse ([524223c](https://github.com/crimx/ext-saladict/commit/524223c4a2cfafd5a0a8d0a2eb6fa494926e5099)) + + +### Build System + +* add sass globals to storybook ([f44ce5a](https://github.com/crimx/ext-saladict/commit/f44ce5a6bd54b2f3346d63934151db6aa76789d0)) + ## [7.14.0](https://github.com/crimx/ext-saladict/compare/v7.13.4...v7.14.0) (2020-07-10) diff --git a/package.json b/package.json index a4b208a0c..5e4a285cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "7.14.0", + "version": "7.14.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
7.14.1
053934520ca9cdeb90707e49d1be0496edfa4b43
2020-07-07 15:12:37
crimx
refactor: add typing cloze to anki
false
diff --git a/src/background/sync-manager/services/ankiconnect/index.ts b/src/background/sync-manager/services/ankiconnect/index.ts index f0a8ef6c0..65f9f8221 100644 --- a/src/background/sync-manager/services/ankiconnect/index.ts +++ b/src/background/sync-manager/services/ankiconnect/index.ts @@ -150,16 +150,16 @@ export class Service extends SyncService<SyncConfig> { async addNoteType() { this.noteFileds = [ - 'Date.', - 'Text.', - 'Translation.', - 'Context.', - 'ContextCloze.', - 'Note.', - 'Title.', - 'Url.', - 'Favicon.', - 'Audio.' + 'Date', + 'Text', + 'Translation', + 'Context', + 'ContextCloze', + 'Note', + 'Title', + 'Url', + 'Favicon', + 'Audio' ] await this.request('createModel', { @@ -223,24 +223,35 @@ export class Service extends SyncService<SyncConfig> { this.noteFileds = await this.getNotefields() } return { + // Date [this.noteFileds[0]]: `${word.date}`, + // Text [this.noteFileds[1]]: word.text || '', + // Translation [this.noteFileds[2]]: this.parseTrans( word.trans, this.config.escapeTrans ), + // Context [this.noteFileds[3]]: this.multiline( word.context, this.config.escapeContext ), - [this.noteFileds[4]]: this.multiline( - word.context.split(word.text).join(`{{c1::${word.text}}}`), - this.config.escapeContext - ), + // ContextCloze + [this.noteFileds[4]]: + this.multiline( + word.context.split(word.text).join(`{{c1::${word.text}}}`), + this.config.escapeContext + ) || `{{c1::${word.text}}}`, + // Note [this.noteFileds[5]]: this.multiline(word.note, this.config.escapeNote), + // Title [this.noteFileds[6]]: word.title || '', + // Url [this.noteFileds[7]]: word.url || '', + // Favicon [this.noteFileds[8]]: word.favicon || '', + // Audio [this.noteFileds[9]]: '' // @TODO } } @@ -251,18 +262,18 @@ export class Service extends SyncService<SyncConfig> { }) // Anki connect bug - return nf?.includes('Date') + return nf?.includes('Date.') ? [ - 'Date', - 'Text', - 'Translation', - 'Context', - 'ContextCloze', - 'Note', - 'Title', - 'Url', - 'Favicon', - 'Audio' + 'Date.', + 'Text.', + 'Translation.', + 'Context.', + 'ContextCloze.', + 'Note.', + 'Title.', + 'Url.', + 'Favicon.', + 'Audio.' ] : nf?.includes('日期') ? [ @@ -278,16 +289,16 @@ export class Service extends SyncService<SyncConfig> { 'Audio' ] : [ - 'Date.', - 'Text.', - 'Translation.', - 'Context.', - 'ContextCloze.', - 'Note.', - 'Title.', - 'Url.', - 'Favicon.', - 'Audio.' + 'Date', + 'Text', + 'Translation', + 'Context', + 'ContextCloze', + 'Note', + 'Title', + 'Url', + 'Favicon', + 'Audio' ] } @@ -353,6 +364,7 @@ export class Service extends SyncService<SyncConfig> { function cardText(front: boolean, nf: string[]) { return `{{#${nf[4]}}} <section>{{cloze:${nf[4]}}}</section> +<section>{{{{type:cloze:${nf[4]}}}</section> {{#${nf[2]}}} <section>{{${nf[2]}}}</section> {{/${nf[2]}}}
refactor
add typing cloze to anki
fc7849b7651681b0a25ac901d5abbc3ade89863e
2019-09-14 20:42:41
crimx
refactor(panel): delay bowl hovering
false
diff --git a/src/content/components/SaladBowl/SaladBowl.tsx b/src/content/components/SaladBowl/SaladBowl.tsx index 654070ce3..ed1248a82 100644 --- a/src/content/components/SaladBowl/SaladBowl.tsx +++ b/src/content/components/SaladBowl/SaladBowl.tsx @@ -1,6 +1,6 @@ import React, { FC } from 'react' import { useSubscription, useObservableCallback } from 'observable-hooks' -import { hover } from '@/_helpers/observables' +import { hoverWithDelay } from '@/_helpers/observables' import { SALADICT_EXTERNAL } from '@/_helpers/saladict' export interface SaladBowlProps { @@ -24,7 +24,7 @@ export const SaladBowl: FC<SaladBowlProps> = props => { const [onMouseOverOut, mouseOverOut$] = useObservableCallback< boolean, React.MouseEvent<HTMLDivElement> - >(hover) + >(hoverWithDelay) useSubscription(mouseOverOut$, active => { props.onHover(active)
refactor
delay bowl hovering
979ff7d4e9a928a272a41d179a4e984f6a00fd9d
2018-11-01 13:03:11
CRIMX
refactor(helpers): update typings
false
diff --git a/src/_helpers/browser-api.ts b/src/_helpers/browser-api.ts index e43465ce0..30f0e49b9 100644 --- a/src/_helpers/browser-api.ts +++ b/src/_helpers/browser-api.ts @@ -154,6 +154,7 @@ export default { type StorageThisTwo = typeof storage.sync | typeof storage.local type StorageThisThree = StorageThisTwo | typeof storage +function storageClear (): Promise<void> function storageClear (this: StorageThisThree): Promise<void> { return this.__storageArea__ === 'all' ? Promise.all([ @@ -163,6 +164,7 @@ function storageClear (this: StorageThisThree): Promise<void> { : browser.storage[this.__storageArea__].clear() } +function storageRemove (keys: string | string[]): Promise<void> function storageRemove (this: StorageThisTwo, keys: string | string[]): Promise<void> { return browser.storage[this.__storageArea__].remove(keys) } @@ -173,6 +175,7 @@ function storageGet<T = any> (this: StorageThisTwo, ...args): Promise<T> { return browser.storage[this.__storageArea__].get(...args) } +function storageSet (keys: any): Promise<void> function storageSet (this: StorageThisTwo, keys: any): Promise<void> { return browser.storage[this.__storageArea__].set(keys) }
refactor
update typings
7d54aa013653e0e35b25e9dd7338fd54e126e5ef
2018-09-02 12:09:27
CRIMX
fix(configs): fix config not updating on init
false
diff --git a/src/_helpers/config-manager.ts b/src/_helpers/config-manager.ts index b878746d7..12d5767bb 100644 --- a/src/_helpers/config-manager.ts +++ b/src/_helpers/config-manager.ts @@ -52,10 +52,7 @@ export async function initConfig (): Promise<AppConfig> { // beware of quota bytes per item exceeds for (let i = 0; i < modes.length; i++) { - const id = modes[i].id - if (!obj[id]) { - await storage.sync.set({ [id]: modes[i] }) - } + await storage.sync.set({ [modes[i].id]: modes[i] }) } await storage.sync.remove(
fix
fix config not updating on init
763c3e31a24d66ea6f61b111d9bc93479d3188ff
2019-08-27 22:00:57
crimx
refactor(selection): intergration fix
false
diff --git a/src/content/redux/modules/epics/newSelection.epic.ts b/src/content/redux/modules/epics/newSelection.epic.ts index c669b19ec..5df078d42 100644 --- a/src/content/redux/modules/epics/newSelection.epic.ts +++ b/src/content/redux/modules/epics/newSelection.epic.ts @@ -35,6 +35,7 @@ export const newSelectionEpic: Epic = (action$, state$) => if ( isShowDictPanel && + selection.word && selection.word.text && (!isPinned || pinMode.direct || @@ -63,6 +64,7 @@ function selectionInsideDictPanel( // inside dict panel const { direct, double, holding } = config.panelMode if ( + selection.word && selection.word.text && (selection.instant || direct || @@ -93,6 +95,7 @@ function selectionToQSPanel( // standalone panel takes control const { direct, double, holding } = config.qsPanelMode if ( + selection.word && selection.word.text && (selection.instant || direct || diff --git a/src/content/redux/modules/reducer/new-selection.handler.ts b/src/content/redux/modules/reducer/new-selection.handler.ts index 35aef497e..38ae9dee6 100644 --- a/src/content/redux/modules/reducer/new-selection.handler.ts +++ b/src/content/redux/modules/reducer/new-selection.handler.ts @@ -1,16 +1,30 @@ import { StoreActionHandler } from '..' import { isStandalonePage, isOptionsPage } from '@/_helpers/saladict' +import { Mutable } from '@/typings/helpers' export const newSelection: StoreActionHandler<'NEW_SELECTION'> = ( state, - { payload } + { payload: selection } ) => { - const { selection, config } = state + const { config, selection: lastSelection } = state - const newState = { + const newState: Mutable<typeof state> = { ...state, - selection: payload, - dictPanelCord: { + selection: selection.word + ? selection + : { + ...selection, + // keep in same position so that + // hide animation won't float around + mouseX: lastSelection.mouseX, + mouseY: lastSelection.mouseY + } + } + + if (selection.word) { + newState.text = selection.word.text + + newState.dictPanelCord = { mouseX: selection.mouseX, mouseY: selection.mouseY } @@ -32,6 +46,7 @@ export const newSelection: StoreActionHandler<'NEW_SELECTION'> = ( newState.isShowDictPanel = Boolean( state.isPinned || (isActive && + selection.word && selection.word.text && (state.isShowDictPanel || direct || @@ -45,6 +60,7 @@ export const newSelection: StoreActionHandler<'NEW_SELECTION'> = ( newState.isShowBowl = Boolean( isActive && + selection.word && selection.word.text && icon && !newState.isShowDictPanel && diff --git a/src/content/redux/modules/state.ts b/src/content/redux/modules/state.ts index 1008cb99d..00ff418ea 100644 --- a/src/content/redux/modules/state.ts +++ b/src/content/redux/modules/state.ts @@ -12,7 +12,7 @@ export const initState = () => ({ profiles: [] as ProfileIDList, activeProfile: getDefaultProfile(), selection: { - word: newWord(), + word: newWord() as Word | null, mouseX: 0, mouseY: 0, self: false, diff --git a/src/selection/select-text.ts b/src/selection/select-text.ts index 13c2e0665..7e46d430c 100644 --- a/src/selection/select-text.ts +++ b/src/selection/select-text.ts @@ -1,16 +1,9 @@ import { Observable, empty, of } from 'rxjs' -import { - withLatestFrom, - filter, - map, - distinctUntilChanged, - mergeMap -} from 'rxjs/operators' +import { withLatestFrom, distinctUntilChanged, mergeMap } from 'rxjs/operators' import { AppConfig } from '@/app-config' import { createValidMouseupStream, - createClickPeriodCountStream, - createMousedownStream + createClickPeriodCountStream } from './mouse-events' import { isTypeField } from './helper' import { isInDictPanel, isStandalonePage } from '@/_helpers/saladict'
refactor
intergration fix
63987e372c2ae4ad3954cc98b0066958a4d69525
2019-12-10 17:50:42
crimx
ci: move to travis.com
false
diff --git a/.travis.yml b/.travis.yml index 3f6c608b3..d56185eef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,6 @@ language: node_js node_js: - - "12" -before_install: - - curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.16.0 - - export PATH=$HOME/.yarn/bin:$PATH -cache: - yarn: true - directories: - - node_modules + - 'stable' script: - - yarn test - yarn build + - yarn test diff --git a/README.md b/README.md index 6338e849b..af45ff0e3 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![Mozilla Add-on](https://img.shields.io/amo/users/ext-saladict.svg?label=Firefoxe%20users)](https://addons.mozilla.org/firefox/addon/ext-saladict/) [![Mozilla Add-on](https://img.shields.io/amo/stars/ext-saladict.svg?label=Firefoxe%20stars)](https://addons.mozilla.org/firefox/addon/ext-saladict/) -[![Build Status](https://travis-ci.org/crimx/ext-saladict.svg)](https://travis-ci.org/crimx/ext-saladict) +[![Build Status](https://travis-ci.com/crimx/ext-saladict.svg)](https://travis-ci.com/crimx/ext-saladict) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg?maxAge=2592000)](http://commitizen.github.io/cz-cli/) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-brightgreen.svg?maxAge=2592000)](https://conventionalcommits.org) [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?maxAge=2592000)](https://standardjs.com/)
ci
move to travis.com
3cda99251ec181cd58bc436854c7947fe62b414a
2018-04-20 23:06:08
CRIMX
style(content): change wording
false
diff --git a/src/content/components/DictItem/index.tsx b/src/content/components/DictItem/index.tsx index 7baba7e7d..b96d6b426 100644 --- a/src/content/components/DictItem/index.tsx +++ b/src/content/components/DictItem/index.tsx @@ -22,19 +22,19 @@ export type DictItemProps = { export type DictItemState = { copySearchStatus: SearchStatus | null - bodyHeight: number - displayHeight: number + offsetHeight: number + visibleHeight: number isUnfold: boolean } export class DictItem extends React.PureComponent<DictItemProps & { t: TranslationFunction }, DictItemState> { bodyRef = React.createRef<HTMLElement>() - prevItemHeight = 0 + prevItemHeight = 30 state = { copySearchStatus: null, - bodyHeight: 10, - displayHeight: 10, + offsetHeight: 10, + visibleHeight: 10, isUnfold: false, } @@ -53,7 +53,7 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati switch (nextProps.searchStatus) { case SearchStatus.Searching: newState.isUnfold = false - newState.bodyHeight = 0 + newState.offsetHeight = 0 break case SearchStatus.Finished: newState.isUnfold = true @@ -69,9 +69,9 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati calcBodyHeight (force?: boolean): Partial<DictItemState> | null { if (this.bodyRef.current) { - const bodyHeight = Math.max(this.bodyRef.current.offsetHeight, 10) || 10 - if (force || this.state.bodyHeight !== bodyHeight) { - return { bodyHeight, displayHeight: Math.min(bodyHeight, this.props.preferredHeight) } + const offsetHeight = Math.max(this.bodyRef.current.offsetHeight, 10) || 10 + if (force || this.state.offsetHeight !== offsetHeight) { + return { offsetHeight, visibleHeight: Math.min(offsetHeight, this.props.preferredHeight) } } } return null @@ -100,7 +100,7 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati } showFull = e => { - this.setState(state => ({ displayHeight: state.bodyHeight })) + this.setState(state => ({ visibleHeight: state.offsetHeight })) e.currentTarget.blur() } @@ -131,15 +131,15 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati } = this.props const { - bodyHeight, - displayHeight, + offsetHeight, + visibleHeight, isUnfold, } = this.state - const finalBodyHeight = isUnfold ? displayHeight : 10 + const displayHeight = isUnfold ? visibleHeight : 10 // plus header - const itemHeight = finalBodyHeight + 20 + const itemHeight = displayHeight + 20 if (itemHeight !== this.prevItemHeight) { this.prevItemHeight = itemHeight updateItemHeight({ id, height: itemHeight }) @@ -168,7 +168,7 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati </button> </header> <Motion defaultStyle={{ height: 10, opacity: 0 }} - style={{ height: spring(finalBodyHeight), opacity: spring(isUnfold ? 1 : 0) }} + style={{ height: spring(displayHeight), opacity: spring(isUnfold ? 1 : 0) }} > {({ height, opacity }) => ( <div className='panel-DictItem_Body' @@ -176,7 +176,7 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati > <article ref={this.bodyRef} style={{ opacity }}> {React.createElement(require('@/components/dictionaries/' + id + '/View.tsx').default, { result: searchResult })} - <button className={`panel-DictItem_FoldMask ${displayHeight < bodyHeight ? 'isActive' : ''}`} onClick={this.showFull}> + <button className={`panel-DictItem_FoldMask ${visibleHeight < offsetHeight ? 'isActive' : ''}`} onClick={this.showFull}> <svg className='panel-DictItem_FoldMaskArrow' width='15' height='15' viewBox='0 0 59.414 59.414' xmlns='http://www.w3.org/2000/svg'> <path d='M58 14.146L29.707 42.44 1.414 14.145 0 15.56 29.707 45.27 59.414 15.56' /> </svg>
style
change wording
da7318da42d91cecb6f328fd401e3d0705f5abd4
2018-04-20 23:05:26
CRIMX
style(content): fix styles
false
diff --git a/src/content/components/MenuBar/_style.scss b/src/content/components/MenuBar/_style.scss index 6eaaedcca..4a8125c3b 100644 --- a/src/content/components/MenuBar/_style.scss +++ b/src/content/components/MenuBar/_style.scss @@ -51,7 +51,7 @@ stroke: #fff; stroke-width: 2; - &.is-Active { + &.isActive { fill: #dd4b39; stroke-width: 0; } @@ -69,7 +69,7 @@ @extend %panel-MenuBar_Icon; transition: transform 400ms; - &.is-Active { + &.isActive { transform: rotate(45deg); } }
style
fix styles
dd3019e943f8a9630123b3c995cba30f46c570a1
2020-05-26 01:47:53
crimx
refactor(sync-services): refactor shanbay
false
diff --git a/src/_locales/en/options.ts b/src/_locales/en/options.ts index c287213b8..400f3dd5b 100644 --- a/src/_locales/en/options.ts +++ b/src/_locales/en/options.ts @@ -244,7 +244,8 @@ export const locale: typeof _locale = { syncService: { description: 'Sync settings.', - start: 'Syncing started in background', + start: 'Syncing. Do not close this page until finished.', + finished: 'Syncing finished', success: 'Syncing success', failed: 'Syncing failed', close_confirm: 'Settings not saved. Close?', diff --git a/src/_locales/zh-CN/options.ts b/src/_locales/zh-CN/options.ts index 26594ed15..a99bb7ad5 100644 --- a/src/_locales/zh-CN/options.ts +++ b/src/_locales/zh-CN/options.ts @@ -233,7 +233,8 @@ export const locale = { syncService: { description: '数据同步设置。', - start: '同步已在后台开始', + start: '同步进行中,结束前请勿关闭此页面。', + finished: '同步结束', success: '同步成功', failed: '同步失败', close_confirm: '设置未保存,关闭?', diff --git a/src/_locales/zh-TW/options.ts b/src/_locales/zh-TW/options.ts index 78747c4a1..dc8d55f09 100644 --- a/src/_locales/zh-TW/options.ts +++ b/src/_locales/zh-TW/options.ts @@ -237,7 +237,8 @@ export const locale: typeof _locale = { syncService: { description: '資料同步設定。', - start: '同步已在背景開始', + start: '同步進行中,結束前請勿關閉此頁面。', + finished: '同步結束', success: '同步成功', failed: '同步失敗', close_confirm: '設定未儲存,關閉?', diff --git a/src/background/sync-manager/index.ts b/src/background/sync-manager/index.ts index b4a8893e8..b9c23bbda 100644 --- a/src/background/sync-manager/index.ts +++ b/src/background/sync-manager/index.ts @@ -87,7 +87,7 @@ export async function syncServiceUpload( id, error, options.action === 'ADD' && options.words?.[0] - ? `「${options.words?.[0]}」` + ? `「${options.words?.[0].text}」` : '' ) } diff --git a/src/background/sync-manager/services/shanbay/_locales/en.ts b/src/background/sync-manager/services/shanbay/_locales/en.ts index 9bd3c3ba6..97d80a0e0 100644 --- a/src/background/sync-manager/services/shanbay/_locales/en.ts +++ b/src/background/sync-manager/services/shanbay/_locales/en.ts @@ -1,6 +1,13 @@ import { locale as _locale } from './zh-CN' export const locale: typeof _locale = { - title: 'Shanbay', - error: {} + title: 'Shanbay Word Syncing', + open: 'Open', + error: { + login: 'Shanbay login failed. Click to open shanbay.com.', + network: + 'Unable to access shanbay.com. Please check your network connection.', + word: + "Unable to add to Shanbay notebook. This word is not in Shanbay's vocabulary database." + } } diff --git a/src/background/sync-manager/services/shanbay/_locales/zh-CN.ts b/src/background/sync-manager/services/shanbay/_locales/zh-CN.ts index 24a847f94..6fa4ee16e 100644 --- a/src/background/sync-manager/services/shanbay/_locales/zh-CN.ts +++ b/src/background/sync-manager/services/shanbay/_locales/zh-CN.ts @@ -1,4 +1,9 @@ export const locale = { - title: '扇贝', - error: {} + title: '扇贝单词同步', + open: '打开', + error: { + login: '扇贝登录已失效,请点击打开官网重新登录。', + network: '无法访问扇贝生词本,请检查网络。', + word: '无法添加到扇贝生词本,扇贝单词库没有收录此单词。' + } } diff --git a/src/background/sync-manager/services/shanbay/_locales/zh-TW.ts b/src/background/sync-manager/services/shanbay/_locales/zh-TW.ts index 014d6817e..ae92d4be4 100644 --- a/src/background/sync-manager/services/shanbay/_locales/zh-TW.ts +++ b/src/background/sync-manager/services/shanbay/_locales/zh-TW.ts @@ -1,6 +1,11 @@ import { locale as _locale } from './zh-CN' export const locale: typeof _locale = { - title: '扇贝', - error: {} + title: '扇貝單字同步', + open: '開啟', + error: { + login: '扇貝登入已失效,請點選開啟官網重新登入。', + network: '無法訪問扇貝生字本,請檢查網路。', + word: '無法新增到扇貝生字本,扇貝單字庫沒有收錄此單字。' + } } diff --git a/src/background/sync-manager/services/shanbay/index.ts b/src/background/sync-manager/services/shanbay/index.ts index c25eaac3e..25a9a665d 100644 --- a/src/background/sync-manager/services/shanbay/index.ts +++ b/src/background/sync-manager/services/shanbay/index.ts @@ -1,42 +1,17 @@ import { AddConfig, SyncService } from '../../interface' -import { getNotebook, getSyncConfig, setSyncConfig } from '../../helpers' +import { getNotebook, setSyncConfig, notifyError } from '../../helpers' import { openURL } from '@/_helpers/browser-api' import { timer } from '@/_helpers/promise-more' import { isFirefox } from '@/_helpers/saladict' +import { I18nManager } from '@/background/i18n-manager' export interface SyncConfig { enable: boolean } -const locales = { - open: { - en: 'Open', - 'zh-CN': '打开', - 'zh-TW': '開啟' - }, - loginCheckFailed: { - en: 'Shanbay login failed. Click to open shanbay.com.', - 'zh-CN': '扇贝登录已失效,请点击打开官网重新登录。', - 'zh-TW': '扇貝登入已失效,請點選開啟官網重新登入。' - }, - errNetwork: { - en: 'Unable to access shanbay.com. Please check your network connection.', - 'zh-CN': '无法访问扇贝生词本,请检查网络。', - 'zh-TW': '無法訪問扇貝生字本,請檢查網路。' - }, - errWord: { - en: - "Unable to add to Shanbay notebook. This word is not in Shanbay's vocabulary database.", - 'zh-CN': '无法添加到扇贝生词本,扇贝单词库没有收录此单词。', - 'zh-TW': '無法新增到扇貝生字本,扇貝單字庫沒有收錄此單字。' - } -} - export class Service extends SyncService<SyncConfig> { static readonly id = 'shanbay' - config = Service.getDefaultConfig() - static getDefaultConfig(): SyncConfig { return { enable: false @@ -48,10 +23,7 @@ export class Service extends SyncService<SyncConfig> { } async startInterval() { - const config = await getSyncConfig<SyncConfig>(Service.id) - if (config) { - this.config = config - } + if (!this.config?.enable) return browser.notifications.onClicked.addListener(this.handleLoginNotification) if (browser.notifications.onButtonClicked) { @@ -61,23 +33,36 @@ export class Service extends SyncService<SyncConfig> { } } + async destroy() { + browser.notifications.onClicked.removeListener(this.handleLoginNotification) + browser.notifications.onButtonClicked.removeListener( + this.handleLoginNotification + ) + } + async init() { if (!(await this.isLogin())) { return Promise.reject('login') } - this.config.enable = true await setSyncConfig<SyncConfig>(Service.id, this.config) } - async add({ words, force }: AddConfig) { + async add(config: AddConfig) { + await this.addInternal(config) + } + + /** + * @returns failed words + */ + async addInternal({ words, force }: AddConfig): Promise<number> { if (!this.config.enable) { - return + return 0 } if (!(await this.isLogin())) { this.notifyLogin() - return + return 0 } if (force) { @@ -85,21 +70,30 @@ export class Service extends SyncService<SyncConfig> { } if (!words || words.length <= 0) { - return + return 0 } + let errorCount = 0 + for (let i = 0; i < words.length; i++) { try { await this.addWord(words[i].text) - } catch (e) { - break + } catch (error) { + if (error !== 'word') { + throw error + } + errorCount += 1 + notifyError(Service.id, 'word', `「${words[i].text}」`) } + if ((i + 1) % 50 === 0) { await timer(15 * 60000) } else { await timer(500) } } + + return errorCount } async addWord(text: string) { @@ -109,12 +103,10 @@ export class Service extends SyncService<SyncConfig> { encodeURIComponent(text) var resSearch = await fetch(url).then(r => r.json()) } catch (e) { - this.notifyError('errNetwork', text) return Promise.reject('network') } if (!resSearch || !resSearch.data) { - this.notifyError('errWord', text) return Promise.reject('word') } @@ -130,13 +122,11 @@ export class Service extends SyncService<SyncConfig> { } ).then(r => r.json()) } catch (e) { - this.notifyError('errNetwork', text) return Promise.reject('network') } if (!resLearning || resLearning.status_code !== 0) { - this.notifyError('errWord', text) - return Promise.reject('learning') + return Promise.reject('word') } } @@ -155,33 +145,21 @@ export class Service extends SyncService<SyncConfig> { } } - notifyError(locale: keyof typeof locales, text: string) { - const { langCode } = window.appConfig - - browser.notifications.create({ - type: 'basic', - iconUrl: browser.runtime.getURL(`assets/icon-128.png`), - title: `Saladict Sync Service ${Service.title[langCode]}`, - message: `「${text}」${locales[locale][langCode]}`, - eventTime: Date.now() + 20000, - priority: 2 - }) - } - - notifyLogin() { - const { langCode } = window.appConfig + async notifyLogin() { + const { i18n } = await I18nManager.getInstance() + await i18n.loadNamespaces('sync') const options: browser.notifications.CreateNotificationOptions = { type: 'basic', iconUrl: browser.runtime.getURL(`assets/icon-128.png`), - title: `Saladict Sync Service ${Service.title[langCode]}`, - message: locales.loginCheckFailed[langCode], + title: `Saladict ${i18n.t(`sync:shanbay.title`)}`, + message: i18n.t('shanbay.error.login'), eventTime: Date.now() + 10000, priority: 2 } if (!isFirefox) { - options.buttons = [{ title: locales.open[langCode] }] + options.buttons = [{ title: i18n.t('shanbay.open') }] } browser.notifications.create('shanbay-login', options) diff --git a/src/background/sync-manager/services/webdav/_locales/en.ts b/src/background/sync-manager/services/webdav/_locales/en.ts index 3f441bc98..baf04cf30 100644 --- a/src/background/sync-manager/services/webdav/_locales/en.ts +++ b/src/background/sync-manager/services/webdav/_locales/en.ts @@ -1,7 +1,7 @@ import { locale as _locale } from './zh-CN' export const locale: typeof _locale = { - title: 'WebDAV', + title: 'WebDAV Word Syncing', error: { download: 'Download failed. Unable to connect WebDAV Server.', internal: 'Unable to save settings.', diff --git a/src/background/sync-manager/services/webdav/_locales/zh-CN.ts b/src/background/sync-manager/services/webdav/_locales/zh-CN.ts index 827483e5d..e809f1b44 100644 --- a/src/background/sync-manager/services/webdav/_locales/zh-CN.ts +++ b/src/background/sync-manager/services/webdav/_locales/zh-CN.ts @@ -1,5 +1,5 @@ export const locale = { - title: 'WebDAV', + title: 'WebDAV 单词同步', error: { download: '下载失败。无法访问 WebDAV 服务器。', internal: '无法保存。', diff --git a/src/background/sync-manager/services/webdav/_locales/zh-TW.ts b/src/background/sync-manager/services/webdav/_locales/zh-TW.ts index fe01d9fb8..7db56e10b 100644 --- a/src/background/sync-manager/services/webdav/_locales/zh-TW.ts +++ b/src/background/sync-manager/services/webdav/_locales/zh-TW.ts @@ -1,7 +1,7 @@ import { locale as _locale } from './zh-CN' export const locale: typeof _locale = { - title: 'WebDAV', + title: 'WebDAV 單字同步', error: { download: '下載失敗。無法訪問 WebDAV 伺服器。', internal: '無法儲存。', diff --git a/src/background/sync-manager/services/webdav/index.ts b/src/background/sync-manager/services/webdav/index.ts index 85c1a7a3a..4f3c544dc 100644 --- a/src/background/sync-manager/services/webdav/index.ts +++ b/src/background/sync-manager/services/webdav/index.ts @@ -178,7 +178,7 @@ export class Service extends SyncService<SyncConfig, SyncMeta> { } } - await setSyncConfig(Service.id, this.config) + await setSyncConfig<SyncConfig>(Service.id, this.config) await this.setMeta({}) if (dir) { diff --git a/src/options/components/Entries/Notebook/ShanbayModal.tsx b/src/options/components/Entries/Notebook/ShanbayModal.tsx index 7f7a0a949..d691a5777 100644 --- a/src/options/components/Entries/Notebook/ShanbayModal.tsx +++ b/src/options/components/Entries/Notebook/ShanbayModal.tsx @@ -1,9 +1,8 @@ -import React, { FC, useState } from 'react' +import React, { FC, useState, useEffect } from 'react' import { Modal, Button, Switch, message as AntdMsg, notification } from 'antd' import { Service, SyncConfig } from '@/background/sync-manager/services/shanbay' import { setSyncConfig as uploadSyncConfig } from '@/background/sync-manager/helpers' -import { message } from '@/_helpers/browser-api' -import { getWords } from '@/_helpers/record-manager' +import { getWords, Word } from '@/_helpers/record-manager' import { useTranslate } from '@/_helpers/i18n' export interface WebdavModalProps { @@ -13,10 +12,15 @@ export interface WebdavModalProps { } export const ShanbayModal: FC<WebdavModalProps> = props => { - const { t } = useTranslate(['options', 'common']) + const { t, i18n } = useTranslate(['options', 'common', 'sync']) const [syncConfig, setSyncConfig] = useState<SyncConfig>( - props.syncConfig || { enable: false } + () => props.syncConfig || Service.getDefaultConfig() ) + useEffect(() => { + if (props.syncConfig) { + setSyncConfig(props.syncConfig) + } + }, [props.syncConfig]) return ( <Modal @@ -50,14 +54,10 @@ export const ShanbayModal: FC<WebdavModalProps> = props => { enable } if (enable) { + const service = new Service(newConfig) + try { - await message.send<'SYNC_SERVICE_INIT', SyncConfig>({ - type: 'SYNC_SERVICE_INIT', - payload: { - serviceID: Service.id, - config: newConfig - } - }) + await service.init() } catch (e) { Modal.confirm({ title: t('syncService.shanbay.login'), @@ -77,7 +77,7 @@ export const ShanbayModal: FC<WebdavModalProps> = props => { } catch (e) { notification.error({ message: t('config.opt.upload_error'), - description: e?.message + description: `${e}` }) } } @@ -91,25 +91,7 @@ export const ShanbayModal: FC<WebdavModalProps> = props => { return } - AntdMsg.destroy() - AntdMsg.success(t('sync.start')) - - try { - await message.send<'SYNC_SERVICE_UPLOAD'>({ - type: 'SYNC_SERVICE_UPLOAD', - payload: { - op: 'ADD', - serviceID: Service.id, - force: true - } - }) - AntdMsg.success(t('sync.success')) - } catch (e) { - notification.error({ - message: t('sync.failed'), - description: e?.message - }) - } + await syncWords() } async function onSyncLast() { @@ -121,24 +103,29 @@ export const ShanbayModal: FC<WebdavModalProps> = props => { return } + await syncWords(words) + } + + async function syncWords(words?: Word[]) { AntdMsg.destroy() - AntdMsg.success(t('sync.start')) + AntdMsg.success(t('syncService.start'), 0) + + const service = new Service(syncConfig) try { - await message.send({ - type: 'SYNC_SERVICE_UPLOAD', - payload: { - op: 'ADD', - serviceID: Service.id, - force: true, - words - } - }) - AntdMsg.success(t('sync.success')) - } catch (e) { + const errorCount = await service.addInternal({ words, force: true }) + AntdMsg.destroy() + if (errorCount > 0) { + AntdMsg.info(t('syncService.finished')) + } else { + AntdMsg.success(t('syncService.success')) + } + } catch (error) { + if (error === 'words') return + const msgPath = `sync:shanbay.error.${error}` notification.error({ - message: t('sync.failed'), - description: e?.message + message: t('syncService.failed'), + description: i18n.exists(msgPath) ? t(msgPath) : `${error}` }) } } diff --git a/src/options/components/Entries/Notebook/WebdavModal.tsx b/src/options/components/Entries/Notebook/WebdavModal.tsx index 62ba1ce72..f34b3e456 100644 --- a/src/options/components/Entries/Notebook/WebdavModal.tsx +++ b/src/options/components/Entries/Notebook/WebdavModal.tsx @@ -64,7 +64,7 @@ export const WebdavModal: FC<WebdavModalProps> = props => { > <Form ref={formRef} - initialValues={props.syncConfig || { duration: 15 }} + initialValues={props.syncConfig || Service.getDefaultConfig()} labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} onFinish={saveService}
refactor
refactor shanbay
587a2e6a64909d7146561192892bec9d8091ec83
2018-04-21 10:58:57
CRIMX
refactor(content): change props
false
diff --git a/src/content/components/MenuBar/index.tsx b/src/content/components/MenuBar/index.tsx index 794dd55ab..1a3cc9f74 100644 --- a/src/content/components/MenuBar/index.tsx +++ b/src/content/components/MenuBar/index.tsx @@ -2,26 +2,29 @@ import './_style.scss' import React, { KeyboardEvent, MouseEvent } from 'react' import { translate } from 'react-i18next' import { TranslationFunction } from 'i18next' +import { SelectionInfo } from '@/_helpers/selection' +import { openURL } from '@/_helpers/browser-api' export type MenuBarProps = { - t: TranslationFunction isFav: boolean isPinned: boolean updateDragArea: ({ left, width }: { left: number, width: number }) => any searchText: (text: string) => any - openSettings: () => any addToNotebook: () => any - openNotebook: () => any - openHistory: () => any + removeFromNotebook: () => any shareImg: () => any pinPanel: () => any closePanel: () => any } -export class MenuBar extends React.PureComponent<MenuBarProps> { +export class MenuBar extends React.PureComponent<MenuBarProps & { t: TranslationFunction }> { dragAreaRef = React.createRef<HTMLDivElement>() text = '' + openSettings () { openURL('options.html', true) } + + openHistory () { openURL('history.html', true) } + updateDragArea = () => { const el = this.dragAreaRef.current if (el) { @@ -48,10 +51,14 @@ export class MenuBar extends React.PureComponent<MenuBarProps> { handleIconFavClick = (e: MouseEvent<SVGElement>) => { switch (e.button) { case 0: // main button - this.props.addToNotebook() + if (this.props.isFav) { + this.props.removeFromNotebook() + } else { + this.props.addToNotebook() + } break case 2: // secondary button - this.props.openNotebook() + openURL('notebook.html', true) break } } @@ -61,8 +68,6 @@ export class MenuBar extends React.PureComponent<MenuBarProps> { t, isFav, isPinned, - openSettings, - openHistory, shareImg, pinPanel, closePanel, @@ -91,7 +96,7 @@ export class MenuBar extends React.PureComponent<MenuBarProps> { <svg className='panel-MenuBar_IconSettings' width='30' height='30' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 612 612' - onClick={openSettings} + onClick={this.openSettings} > <title>{t('tipOpenSettings')}</title> <path d='M0 97.92v24.48h612V97.92H0zm0 220.32h612v-24.48H0v24.48zm0 195.84h612V489.6H0v24.48z'/> @@ -109,7 +114,7 @@ export class MenuBar extends React.PureComponent<MenuBarProps> { <svg className='panel-MenuBar_IconHistory' width='30' height='30' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' - onClick={openHistory} + onClick={this.openHistory} > <title>{t('tipOpenHistory')}</title> <path d='M34.688 3.315c-15.887 0-28.812 12.924-28.81 28.73-.012.25-.157 4.434 1.034 8.94l-3.88-2.262c-.965-.56-2.193-.235-2.76.727-.557.96-.233 2.195.728 2.755l9.095 5.302c.02.01.038.013.056.022.1.05.2.09.31.12.07.02.14.05.21.07.09.02.176.02.265.03.06.003.124.022.186.022.036 0 .07-.01.105-.015.034 0 .063.007.097.004.05-.003.097-.024.146-.032.097-.017.19-.038.28-.068.08-.028.157-.06.23-.095.086-.04.165-.085.24-.137.074-.046.14-.096.206-.15.07-.06.135-.125.198-.195.06-.067.11-.135.16-.207.026-.04.062-.07.086-.11.017-.03.017-.067.032-.1.03-.053.07-.1.096-.16l3.62-8.96c.417-1.03-.08-2.205-1.112-2.622-1.033-.413-2.207.083-2.624 1.115l-1.86 4.6c-1.24-4.145-1.1-8.406-1.093-8.523C9.92 18.455 21.04 7.34 34.7 7.34c13.663 0 24.78 11.116 24.78 24.78S48.357 56.9 34.694 56.9c-1.114 0-2.016.902-2.016 2.015s.9 2.02 2.012 2.02c15.89 0 28.81-12.925 28.81-28.81 0-15.89-12.923-28.814-28.81-28.814z'/> diff --git a/test/specs/components/content/MenuBar.spec.tsx b/test/specs/components/content/MenuBar.spec.tsx index 20d2c37b0..c23d0125e 100644 --- a/test/specs/components/content/MenuBar.spec.tsx +++ b/test/specs/components/content/MenuBar.spec.tsx @@ -12,10 +12,8 @@ describe('Component/content/MenuBar', () => { isPinned: false, updateDragArea: noop, searchText: noop, - openSettings: noop, addToNotebook: noop, - openNotebook: noop, - openHistory: noop, + removeFromNotebook: noop, shareImg: noop, pinPanel: noop, closePanel: noop, @@ -31,10 +29,8 @@ describe('Component/content/MenuBar', () => { isPinned: true, updateDragArea: noop, searchText: noop, - openSettings: noop, addToNotebook: noop, - openNotebook: noop, - openHistory: noop, + removeFromNotebook: noop, shareImg: noop, pinPanel: noop, closePanel: noop,
refactor
change props
7e3ac952bad2f031061a53e9f1549499d314a26d
2018-05-10 04:49:22
CRIMX
refactor(dicts): rename engines to ts
false
diff --git a/src/components/dictionaries/guoyu/engine.js b/src/components/dictionaries/guoyu/engine.ts similarity index 100% rename from src/components/dictionaries/guoyu/engine.js rename to src/components/dictionaries/guoyu/engine.ts diff --git a/src/components/dictionaries/liangan/engine.js b/src/components/dictionaries/liangan/engine.ts similarity index 100% rename from src/components/dictionaries/liangan/engine.js rename to src/components/dictionaries/liangan/engine.ts
refactor
rename engines to ts
8de62aa288e2498bec3d49d9b97c4db794c8d027
2018-02-04 21:55:58
CRIMX
build(typescript): make ts-loader work with babel-loader
false
diff --git a/config/fake-env/webextension-page.js b/config/fake-env/webextension-page.js index 39604f63a..ea3beb65d 100644 --- a/config/fake-env/webextension-page.js +++ b/config/fake-env/webextension-page.js @@ -4,6 +4,7 @@ * I faked a subset of common apis by hand to mimic the behaviours. */ import _ from 'lodash' +import locales from '../../src/_locales/messages.json' const platform = navigator.userAgent.indexOf('Chrome') !== -1 ? 'chrome' : 'firefox' @@ -19,8 +20,17 @@ window.browser = { getBadgeText (x, cb) { cb(Date.now().toString()) }, setBadgeBackgroundColor () {}, }, + contextMenus: { + onClicked: { + addListener () {}, + hasListener () {}, + removeListener () {}, + }, + removeAll () { return Promise.resolve() }, + create () { return Promise.resolve() }, + }, i18n: { - getMessage () { return 'xxx' } + getMessage (k) { return locales[k] && locales[k].message.zh_CN } }, notifications: { create: _.partial(console.log, 'create notifications:'), @@ -39,12 +49,26 @@ window.browser = { // ... add other info accordingly }) }, + query () { return Promise.resolve([]) }, + highlight () { return Promise.resolve() }, // No other tab to receive anyway sendMessage () { return Promise.resolve() } }, + webRequest: { + onBeforeRequest: { + addListener () {}, + hasListener () {}, + removeListener () {}, + }, + onHeadersReceived: { + addListener () {}, + hasListener () {}, + removeListener () {}, + }, + }, runtime: { id: 'mdidnbkkjainbfbcenphabdajogedcnx', - getURL (name) { return '/' + name }, + getURL (name) { return 'x' }, getManifest () { return _.assign( {}, @@ -57,7 +81,7 @@ window.browser = { addListener (listener) { if (!_.isFunction(listener)) { throw new TypeError('Wrong argument type') } // delay startup calls - settimeout(listener, 0) + setTimeout(listener, 0) } }, onInstalled: { diff --git a/config/webpack.config.dev.js b/config/webpack.config.dev.js index e2f7cd175..a592e5f1d 100644 --- a/config/webpack.config.dev.js +++ b/config/webpack.config.dev.js @@ -168,7 +168,17 @@ module.exports = { { test: /\.tsx?$/, include: paths.appSrc, - loader: require.resolve('ts-loader'), + use: [ + { + loader: require.resolve('babel-loader'), + options: { + cacheDirectory: true, + }, + }, + { + loader: require.resolve('ts-loader'), + } + ], }, // Process JS with Babel. { diff --git a/tsconfig.json b/tsconfig.json index cfa0a7dc4..a9f0f8e13 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,14 +1,14 @@ { "compilerOptions": { - "strict": true, - "outDir": "./dist/", - "sourceMap": true, - "noImplicitAny": false, - "module": "commonjs", - "target": "es6", "allowSyntheticDefaultImports": true, "jsx": "react", "lib": ["es6", "dom"], + "moduleResolution": "node", + "noImplicitAny": false, + "outDir": "./dist/", + "sourceMap": true, + "strict": true, + "target": "es6", "typeRoots": ["node_modules/@types", "node_modules/web-ext-types"] }, "include": [
build
make ts-loader work with babel-loader
fbb69b6aaf901853a1b85fc74592b7fec1e9526c
2019-02-12 17:15:42
CRIMX
test(dicts): add real requests for dicts
false
diff --git a/config/jest/setupTests.js b/config/jest/setupTests.js index c6107f085..f8d91c7c4 100644 --- a/config/jest/setupTests.js +++ b/config/jest/setupTests.js @@ -2,11 +2,18 @@ import browser from 'sinon-chrome/extensions' import Enzyme from 'enzyme' import Adapter from 'enzyme-adapter-react-16' import raf from 'raf' -import { Request, Response } from 'node-fetch' +import fetch from 'node-fetch' window.browser = browser -window.Request = Request -window.Response = Response +window.Request = fetch.Request +window.Response = fetch.Response + +if (process.env.CI) { + window.FormData = require('form-data') + window.fetch = fetch + + jest.setTimeout(30000) +} Enzyme.configure({ adapter: new Adapter() }) diff --git a/package.json b/package.json index 2d361398d..755e54a9e 100644 --- a/package.json +++ b/package.json @@ -100,6 +100,7 @@ "extract-text-webpack-plugin": "3.0.2", "file-loader": "1.1.11", "fork-ts-checker-webpack-plugin": "^0.4.0", + "form-data": "^2.3.3", "fs-extra": "^5.0.0", "generate-json-webpack-plugin": "^0.2.2", "html-webpack-plugin": "3.0.6", @@ -139,8 +140,7 @@ "webpack": "3.11.0", "webpack-bundle-analyzer": "^2.11.1", "webpack-dev-server": "2.11.1", - "wrapper-webpack-plugin": "^1.0.0", - "xmlhttprequest": "^1.8.0" + "wrapper-webpack-plugin": "^1.0.0" }, "jest": { "globals": { diff --git a/src/components/dictionaries/cambridge/engine.ts b/src/components/dictionaries/cambridge/engine.ts index 9f7ccbaca..a95e7aa7b 100644 --- a/src/components/dictionaries/cambridge/engine.ts +++ b/src/components/dictionaries/cambridge/engine.ts @@ -45,7 +45,7 @@ export const search: SearchFunction<CambridgeSearchResult> = ( ? 'https://dictionary.cambridge.org/zht/搜索/英語-漢語-繁體/direct/?q=' : 'https://dictionary.cambridge.org/search/english/direct/?q=' - return fetchDirtyDOM(url + text.toLocaleLowerCase().replace(/[^A-Za-z0-9]+/g, '-')) + return fetchDirtyDOM(encodeURI(url) + text.toLocaleLowerCase().replace(/[^A-Za-z0-9]+/g, '-')) .catch(handleNetWorkError) .then(handleDOM) } diff --git a/test/specs/components/dictionaries/baidu/engine.spec.ts b/test/specs/components/dictionaries/baidu/engine.spec.ts index 42c22b49b..ebb2553c3 100644 --- a/test/specs/components/dictionaries/baidu/engine.spec.ts +++ b/test/specs/components/dictionaries/baidu/engine.spec.ts @@ -4,12 +4,6 @@ import { getDefaultProfile } from '@/app-config/profiles' import { isContainChinese, isContainEnglish, isContainJapanese } from '@/_helpers/lang-check' describe('Dict/Baidu/engine', () => { - beforeAll(() => { - if (process.env.CI) { - window.fetch = require('node-fetch') - } - }) - it('should parse result correctly', () => { if (process.env.CI) { return search('我爱你', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) diff --git a/test/specs/components/dictionaries/bing/engine.spec.ts b/test/specs/components/dictionaries/bing/engine.spec.ts index 4beaab9a1..a1c1dcb04 100644 --- a/test/specs/components/dictionaries/bing/engine.spec.ts +++ b/test/specs/components/dictionaries/bing/engine.spec.ts @@ -7,9 +7,7 @@ import { URL } from 'url' describe('Dict/Bing/engine', () => { beforeAll(() => { - if (process.env.CI) { - window.fetch = require('node-fetch') - } else { + if (!process.env.CI) { const response = { love: fs.readFileSync(path.join(__dirname, 'response/lex.html'), 'utf8'), machine: fs.readFileSync(path.join(__dirname, 'response/machine.html'), 'utf8'), diff --git a/test/specs/components/dictionaries/cambridge/engine.spec.ts b/test/specs/components/dictionaries/cambridge/engine.spec.ts index 5fc5de51b..63cf34da8 100644 --- a/test/specs/components/dictionaries/cambridge/engine.spec.ts +++ b/test/specs/components/dictionaries/cambridge/engine.spec.ts @@ -1,5 +1,5 @@ import { search } from '@/components/dictionaries/cambridge/engine' -import { getDefaultConfig } from '@/app-config' +import { getDefaultConfig, AppConfigMutable } from '@/app-config' import getDefaultProfile from '@/app-config/profiles' import fs from 'fs' import path from 'path' @@ -8,22 +8,24 @@ const fetchbak = window.fetch describe('Dict/Cambridge/engine', () => { beforeAll(() => { - const response = { - love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), - house: fs.readFileSync(path.join(__dirname, 'response/house-zhs.html'), 'utf8'), - catch: fs.readFileSync(path.join(__dirname, 'response/catch-zht.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), + house: fs.readFileSync(path.join(__dirname, 'response/house-zhs.html'), 'utf8'), + catch: fs.readFileSync(path.join(__dirname, 'response/catch-zht.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) afterAll(() => { @@ -36,7 +38,7 @@ describe('Dict/Cambridge/engine', () => { expect(audio && typeof audio.uk).toBe('string') expect(audio && typeof audio.us).toBe('string') - expect(result).toHaveLength(4) + expect(result.length).toBeGreaterThanOrEqual(1) result.forEach(r => { expect(typeof r.title).toBe('string') @@ -62,7 +64,7 @@ describe('Dict/Cambridge/engine', () => { expect(audio && typeof audio.uk).toBe('string') expect(audio && typeof audio.us).toBe('string') - expect(result).toHaveLength(2) + expect(result.length).toBeGreaterThanOrEqual(1) result.forEach(r => { expect(typeof r.title).toBe('string') @@ -81,12 +83,14 @@ describe('Dict/Cambridge/engine', () => { }) it('should parse result (zht) correctly', () => { - return search('catch', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + const config = getDefaultConfig() as AppConfigMutable + config.langCode = 'zh-TW' + return search('catch', config, getDefaultProfile(), { isPDF: false }) .then(({ result, audio }) => { expect(audio && typeof audio.uk).toBe('string') expect(audio && typeof audio.us).toBe('string') - expect(result).toHaveLength(2) + expect(result.length).toBeGreaterThanOrEqual(1) result.forEach(r => { expect(typeof r.title).toBe('string') diff --git a/test/specs/components/dictionaries/cobuild/engine.spec.ts b/test/specs/components/dictionaries/cobuild/engine.spec.ts index 648ad5498..9e93d6141 100644 --- a/test/specs/components/dictionaries/cobuild/engine.spec.ts +++ b/test/specs/components/dictionaries/cobuild/engine.spec.ts @@ -1,16 +1,18 @@ import { search } from '@/components/dictionaries/cobuild/engine' -import { getDefaultConfig, AppConfigMutable } from '@/app-config' +import { getDefaultConfig } from '@/app-config' import { getDefaultProfile, ProfileMutable } from '@/app-config/profiles' import fs from 'fs' import path from 'path' describe('Dict/COBUILD/engine', () => { beforeAll(() => { - const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => response - })) + if (!process.env.CI) { + const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => response + })) + } }) it('should parse result correctly', () => { @@ -18,7 +20,7 @@ describe('Dict/COBUILD/engine', () => { profile.dicts.all.cobuild.options = { sentence: 4 } - return search('any', getDefaultConfig(), profile, { isPDF: false }) + return search('love', getDefaultConfig(), profile, { isPDF: false }) .then(searchResult => { expect(searchResult.audio).toHaveProperty('us', expect.stringContaining('mp3')) expect(searchResult.audio).toHaveProperty('uk', expect.stringContaining('mp3')) @@ -26,7 +28,8 @@ describe('Dict/COBUILD/engine', () => { const result = searchResult.result expect(typeof result.title).toBe('string') expect(typeof result.level).toBe('string') - expect(typeof result.star).toBe('number') + // rating has been removed + // expect(typeof result.star).toBe('number') expect(result.defs).toHaveLength(4) expect(result.prons).toHaveLength(2) }) diff --git a/test/specs/components/dictionaries/etymonline/engine.spec.ts b/test/specs/components/dictionaries/etymonline/engine.spec.ts index 16746f261..313a1153b 100644 --- a/test/specs/components/dictionaries/etymonline/engine.spec.ts +++ b/test/specs/components/dictionaries/etymonline/engine.spec.ts @@ -6,11 +6,13 @@ import path from 'path' describe('Dict/Etymonline/engine', () => { beforeAll(() => { - const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => response - })) + if (!process.env.CI) { + const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => response + })) + } }) it('should parse result correctly', () => { @@ -19,7 +21,7 @@ describe('Dict/Etymonline/engine', () => { chart: true, resultnum: 4 } - return search('any', getDefaultConfig(), profile, { isPDF: false }) + return search('love', getDefaultConfig(), profile, { isPDF: false }) .then(searchResult => { expect(searchResult.audio).toBeUndefined() diff --git a/test/specs/components/dictionaries/eudic/engine.spec.ts b/test/specs/components/dictionaries/eudic/engine.spec.ts index 74c7dd27b..b7103b2f1 100644 --- a/test/specs/components/dictionaries/eudic/engine.spec.ts +++ b/test/specs/components/dictionaries/eudic/engine.spec.ts @@ -6,15 +6,17 @@ import path from 'path' describe('Dict/Eudic/engine', () => { beforeAll(() => { - const entry = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') - const data = fs.readFileSync(path.join(__dirname, 'response/sentences.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => url.indexOf('tab-detail') === -1 ? entry : data - })) + if (!process.env.CI) { + const entry = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') + const data = fs.readFileSync(path.join(__dirname, 'response/sentences.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => url.indexOf('tab-detail') === -1 ? entry : data + })) + } }) - it('should parse result correctly', () => { + it('should parse result correctly', async () => { return search('love', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { expect(searchResult.audio && typeof searchResult.audio.us).toBe('string') diff --git a/test/specs/components/dictionaries/google/engine.spec.ts b/test/specs/components/dictionaries/google/engine.spec.ts index f377e995b..8bbca7cdc 100644 --- a/test/specs/components/dictionaries/google/engine.spec.ts +++ b/test/specs/components/dictionaries/google/engine.spec.ts @@ -1,45 +1,50 @@ import { search } from '@/components/dictionaries/google/engine' import { getDefaultConfig } from '@/app-config' import { getDefaultProfile } from '@/app-config/profiles' +import { isContainEnglish, isContainJapanese, isContainChinese } from '@/_helpers/lang-check' import fs from 'fs' import path from 'path' -const homepage = fs.readFileSync(path.join(__dirname, 'response/homepage.html'), 'utf8') -const translation = fs.readFileSync(path.join(__dirname, 'response/f.txt'), 'utf8') - -const fetchbak = window.fetch - describe('Dict/Google/engine', () => { beforeAll(() => { - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => /translate_a|googleapis\.com/.test(url) ? translation : homepage - })) - }) + if (!process.env.CI) { + const homepage = fs.readFileSync(path.join(__dirname, 'response/homepage.html'), 'utf8') + const translation = fs.readFileSync(path.join(__dirname, 'response/f.txt'), 'utf8') - afterAll(() => { - window.fetch = fetchbak + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => /translate_a|googleapis\.com/.test(url) ? translation : homepage + })) + } }) it('should parse result correctly', () => { - return search('any', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + return search('我爱你', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { + if (process.env.CI) { + expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() + } else { + expect(searchResult.result.trans.text).toBe('“当你不需要的时候,这就是你所读到的东西,当你无法帮助它时,它将决定你将会是什么。”\n - 奥斯卡·王尔德\n 成功一夜成名需要很长时间。') + } expect(searchResult.audio).toBeUndefined() - expect(searchResult.result.trans.text).toBe('“当你不需要的时候,这就是你所读到的东西,当你无法帮助它时,它将决定你将会是什么。”\n - 奥斯卡·王尔德\n 成功一夜成名需要很长时间。') expect(searchResult.result.id).toBe('google') expect(searchResult.result.sl).toBe('auto') expect(searchResult.result.tl).toBe('en') + expect(isContainChinese(searchResult.result.searchText.text)).toBeTruthy() expect(typeof searchResult.result.trans.audio).toBe('string') - expect(typeof searchResult.result.searchText.text).toBe('string') expect(typeof searchResult.result.searchText.audio).toBe('string') }) }) it('should parse result correctly with payload', () => { - return search('any', getDefaultConfig(), getDefaultProfile(), { sl: 'en', tl: 'jp', isPDF: false }) + return search('I love you', getDefaultConfig(), getDefaultProfile(), { sl: 'en', tl: 'ja', isPDF: false }) .then(searchResult => { expect(searchResult.result.sl).toBe('en') - expect(searchResult.result.tl).toBe('jp') + expect(searchResult.result.tl).toBe('ja') + if (process.env.CI) { + expect(isContainJapanese(searchResult.result.trans.text)).toBeTruthy() + expect(isContainEnglish(searchResult.result.searchText.text)).toBeTruthy() + } }) }) }) diff --git a/test/specs/components/dictionaries/googledict/engine.spec.ts b/test/specs/components/dictionaries/googledict/engine.spec.ts new file mode 100644 index 000000000..821481c5a --- /dev/null +++ b/test/specs/components/dictionaries/googledict/engine.spec.ts @@ -0,0 +1,14 @@ +import { search } from '@/components/dictionaries/googledict/engine' +import { getDefaultConfig } from '@/app-config' +import { getDefaultProfile } from '@/app-config/profiles' + +describe('Dict/GoogleDict/engine', () => { + it('should parse result correctly', () => { + if (process.env.CI) { + return search('love', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + .then(searchResult => { + expect(typeof searchResult.result.entry).toBe('string') + }) + } + }) +}) diff --git a/test/specs/components/dictionaries/guoyu/engine.spec.ts b/test/specs/components/dictionaries/guoyu/engine.spec.ts index 72224a789..3ad7483fb 100644 --- a/test/specs/components/dictionaries/guoyu/engine.spec.ts +++ b/test/specs/components/dictionaries/guoyu/engine.spec.ts @@ -4,14 +4,16 @@ import { getDefaultProfile } from '@/app-config/profiles' describe('Dict/GuoYu/engine', () => { beforeAll(() => { - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - json: () => require('./response/愛.json') - })) + if (!process.env.CI) { + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + json: () => require('./response/愛.json') + })) + } }) it('should parse result correctly', () => { - return search('any', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + return search('愛', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { expect(searchResult.audio && typeof searchResult.audio.py).toBe('string') expect(typeof searchResult.result.t).toBe('string') diff --git a/test/specs/components/dictionaries/longman/engine.spec.ts b/test/specs/components/dictionaries/longman/engine.spec.ts index 26273db10..65441ac2a 100644 --- a/test/specs/components/dictionaries/longman/engine.spec.ts +++ b/test/specs/components/dictionaries/longman/engine.spec.ts @@ -1,27 +1,29 @@ import { search, LongmanResultLex, LongmanResultRelated } from '@/components/dictionaries/longman/engine' -import { getDefaultConfig, AppConfigMutable } from '@/app-config' +import { getDefaultConfig } from '@/app-config' import { getDefaultProfile, ProfileMutable } from '@/app-config/profiles' import fs from 'fs' import path from 'path' describe('Dict/Longman/engine', () => { beforeAll(() => { - const response = { - love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), - profit: fs.readFileSync(path.join(__dirname, 'response/profit.html'), 'utf8'), - jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), + profit: fs.readFileSync(path.join(__dirname, 'response/profit.html'), 'utf8'), + jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) it('should parse lex result (love) correctly', () => { diff --git a/test/specs/components/dictionaries/macmillan/engine.spec.ts b/test/specs/components/dictionaries/macmillan/engine.spec.ts index 1e676d682..084461610 100644 --- a/test/specs/components/dictionaries/macmillan/engine.spec.ts +++ b/test/specs/components/dictionaries/macmillan/engine.spec.ts @@ -6,22 +6,24 @@ import path from 'path' describe('Dict/Macmillan/engine', () => { beforeAll(() => { - const response = { - love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), - love_2: fs.readFileSync(path.join(__dirname, 'response/love_2.html'), 'utf8'), - jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), + love_2: fs.readFileSync(path.join(__dirname, 'response/love_2.html'), 'utf8'), + jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) it('should parse lex result correctly', () => { diff --git a/test/specs/components/dictionaries/oald/engine.spec.ts b/test/specs/components/dictionaries/oald/engine.spec.ts index b8d411074..f2acf92fe 100644 --- a/test/specs/components/dictionaries/oald/engine.spec.ts +++ b/test/specs/components/dictionaries/oald/engine.spec.ts @@ -6,22 +6,24 @@ import path from 'path' describe('Dict/OALD/engine', () => { beforeAll(() => { - const response = { - love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), - love_2: fs.readFileSync(path.join(__dirname, 'response/love_2.html'), 'utf8'), - jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), + love_2: fs.readFileSync(path.join(__dirname, 'response/love_2.html'), 'utf8'), + jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) it('should parse lex result correctly', () => { diff --git a/test/specs/components/dictionaries/sogou/engine.spec.ts b/test/specs/components/dictionaries/sogou/engine.spec.ts new file mode 100644 index 000000000..6e70e9731 --- /dev/null +++ b/test/specs/components/dictionaries/sogou/engine.spec.ts @@ -0,0 +1,36 @@ +import { search } from '@/components/dictionaries/sogou/engine' +import { getDefaultConfig } from '@/app-config' +import { getDefaultProfile } from '@/app-config/profiles' +import { isContainEnglish, isContainJapanese, isContainChinese } from '@/_helpers/lang-check' + +describe('Dict/Sogou/engine', () => { + it('should parse result correctly', () => { + if (process.env.CI) { + return search('我爱你', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + .then(searchResult => { + expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() + expect(searchResult.audio).toBeUndefined() + expect(searchResult.result.id).toBe('sogou') + expect(searchResult.result.sl).toBe('auto') + expect(searchResult.result.tl).toBe('en') + expect(isContainChinese(searchResult.result.searchText.text)).toBeTruthy() + expect(typeof searchResult.result.trans.audio).toBe('string') + expect(typeof searchResult.result.searchText.audio).toBe('string') + }) + } + }) + + it('should parse result correctly with payload', () => { + if (process.env.CI) { + return search('I love you', getDefaultConfig(), getDefaultProfile(), { sl: 'en', tl: 'ja', isPDF: false }) + .then(searchResult => { + expect(searchResult.result.sl).toBe('en') + expect(searchResult.result.tl).toBe('ja') + if (process.env.CI) { + expect(isContainJapanese(searchResult.result.trans.text)).toBeTruthy() + expect(isContainEnglish(searchResult.result.searchText.text)).toBeTruthy() + } + }) + } + }) +}) diff --git a/test/specs/components/dictionaries/urban/engine.spec.ts b/test/specs/components/dictionaries/urban/engine.spec.ts index 4b813c288..b87f980df 100644 --- a/test/specs/components/dictionaries/urban/engine.spec.ts +++ b/test/specs/components/dictionaries/urban/engine.spec.ts @@ -6,15 +6,17 @@ import path from 'path' describe('Dict/Urban/engine', () => { beforeAll(() => { - const response = fs.readFileSync(path.join(__dirname, 'response/test.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => response - })) + if (!process.env.CI) { + const response = fs.readFileSync(path.join(__dirname, 'response/test.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => response + })) + } }) it('should parse result correctly', () => { - return search('any', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + return search('love', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { expect(searchResult.audio && typeof searchResult.audio.us).toBe('string') expect(searchResult.result).toHaveLength(4) diff --git a/test/specs/components/dictionaries/vocabulary/engine.spec.ts b/test/specs/components/dictionaries/vocabulary/engine.spec.ts index 09b232552..1c67807fa 100644 --- a/test/specs/components/dictionaries/vocabulary/engine.spec.ts +++ b/test/specs/components/dictionaries/vocabulary/engine.spec.ts @@ -6,15 +6,17 @@ import path from 'path' describe('Dict/Vocabulary/engine', () => { beforeAll(() => { - const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => response - })) + if (!process.env.CI) { + const response = fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => response + })) + } }) it('should parse result correctly', () => { - return search('any', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + return search('love', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(({ result, audio }) => { expect(audio).toBeUndefined() expect(typeof result.long).toBe('string') diff --git a/test/specs/components/dictionaries/weblio/engine.spec.ts b/test/specs/components/dictionaries/weblio/engine.spec.ts new file mode 100644 index 000000000..a52069ba2 --- /dev/null +++ b/test/specs/components/dictionaries/weblio/engine.spec.ts @@ -0,0 +1,18 @@ +import { search } from '@/components/dictionaries/weblio/engine' +import { getDefaultConfig } from '@/app-config' +import { getDefaultProfile } from '@/app-config/profiles' + +describe('Dict/Weblio/engine', () => { + ['love', '吐く', '当たる'].forEach(text => { + it(`should parse result ${text} correctly`, () => { + if (process.env.CI) { + return search(text, getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + .then(({ result }) => { + expect(result.length).toBeGreaterThanOrEqual(1) + expect(typeof result[0].title).toBe('string') + expect(typeof result[0].def).toBe('string') + }) + } + }) + }) +}) diff --git a/test/specs/components/dictionaries/websterlearner/engine.spec.ts b/test/specs/components/dictionaries/websterlearner/engine.spec.ts index 9666b5f6a..71532ac26 100644 --- a/test/specs/components/dictionaries/websterlearner/engine.spec.ts +++ b/test/specs/components/dictionaries/websterlearner/engine.spec.ts @@ -6,22 +6,24 @@ import path from 'path' describe('Dict/WebsterLearner/engine', () => { beforeAll(() => { - const response = { - house: fs.readFileSync(path.join(__dirname, 'response/house.html'), 'utf8'), - door: fs.readFileSync(path.join(__dirname, 'response/door.html'), 'utf8'), - jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + house: fs.readFileSync(path.join(__dirname, 'response/house.html'), 'utf8'), + door: fs.readFileSync(path.join(__dirname, 'response/door.html'), 'utf8'), + jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) it('should parse lex result correctly', () => { @@ -83,15 +85,4 @@ describe('Dict/WebsterLearner/engine', () => { expect(result.items[1].derived).toBeFalsy() }) }) - - it('should parse related result correctly', () => { - return search('jumblish', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) - .then(searchResult => { - expect(searchResult.audio).toBeUndefined() - - const result = searchResult.result as WebsterLearnerResultRelated - expect(result.type).toBe('related') - expect(typeof result.list).toBe('string') - }) - }) }) diff --git a/test/specs/components/dictionaries/wikipedia/engine.spec.ts b/test/specs/components/dictionaries/wikipedia/engine.spec.ts new file mode 100644 index 000000000..d798939ba --- /dev/null +++ b/test/specs/components/dictionaries/wikipedia/engine.spec.ts @@ -0,0 +1,15 @@ +import { search } from '@/components/dictionaries/wikipedia/engine' +import { getDefaultConfig } from '@/app-config' +import { getDefaultProfile } from '@/app-config/profiles' + +describe('Dict/Wikipedia/engine', () => { + it('should parse result correctly', () => { + if (process.env.CI) { + return search('数字', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + .then(({ result }) => { + expect(typeof result.title).toBe('string') + expect(typeof result.content).toBe('string') + }) + } + }) +}) diff --git a/test/specs/components/dictionaries/youdao/engine.spec.ts b/test/specs/components/dictionaries/youdao/engine.spec.ts index 35a6e163d..3e0566f2a 100644 --- a/test/specs/components/dictionaries/youdao/engine.spec.ts +++ b/test/specs/components/dictionaries/youdao/engine.spec.ts @@ -6,22 +6,24 @@ import path from 'path' describe('Dict/Youdao/engine', () => { beforeAll(() => { - const response = { - love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), - jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), - translation: fs.readFileSync(path.join(__dirname, 'response/translation.html'), 'utf8'), - } - - window.fetch = jest.fn((url: string) => { - const key = Object.keys(response).find(keyword => url.endsWith(keyword)) - if (key) { - return Promise.resolve({ - ok: true, - text: () => response[key] - }) + if (!process.env.CI) { + const response = { + love: fs.readFileSync(path.join(__dirname, 'response/love.html'), 'utf8'), + jumblish: fs.readFileSync(path.join(__dirname, 'response/jumblish.html'), 'utf8'), + translation: fs.readFileSync(path.join(__dirname, 'response/translation.html'), 'utf8'), } - return Promise.reject(new Error(`Missing Response file for ${url}`)) - }) + + window.fetch = jest.fn((url: string) => { + const key = Object.keys(response).find(keyword => url.endsWith(keyword)) + if (key) { + return Promise.resolve({ + ok: true, + text: () => response[key] + }) + } + return Promise.reject(new Error(`Missing Response file for ${url}`)) + }) + } }) it('should parse lex result correctly', () => { @@ -86,7 +88,10 @@ describe('Dict/Youdao/engine', () => { }) it('should parse translation result correctly', () => { - return search('translation', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + const text = process.env.CI + ? 'She walks in beauty, like the night Of cloudless climes and starry skies.' + : 'translation' + return search(text, getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { expect(!searchResult.audio || !searchResult.audio.uk).toBeTruthy() expect(!searchResult.audio || !searchResult.audio.us).toBeTruthy() diff --git a/test/specs/components/dictionaries/zdic/engine.spec.ts b/test/specs/components/dictionaries/zdic/engine.spec.ts index 0e5ab66bc..8211b73bc 100644 --- a/test/specs/components/dictionaries/zdic/engine.spec.ts +++ b/test/specs/components/dictionaries/zdic/engine.spec.ts @@ -6,12 +6,14 @@ import path from 'path' describe('Dict/Zdic/engine', () => { beforeAll(() => { - const word = fs.readFileSync(path.join(__dirname, 'response/爱.html'), 'utf8') - const phrase = fs.readFileSync(path.join(__dirname, 'response/沙拉.html'), 'utf8') - window.fetch = jest.fn((url: string) => Promise.resolve({ - ok: true, - text: () => url.indexOf('爱') !== -1 ? word : phrase - })) + if (!process.env.CI) { + const word = fs.readFileSync(path.join(__dirname, 'response/爱.html'), 'utf8') + const phrase = fs.readFileSync(path.join(__dirname, 'response/沙拉.html'), 'utf8') + window.fetch = jest.fn((url: string) => Promise.resolve({ + ok: true, + text: () => url.indexOf('爱') !== -1 ? word : phrase + })) + } }) it('should parse word result correctly', () => { diff --git a/yarn.lock b/yarn.lock index e18680fe0..d3a7a4a04 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2036,6 +2036,13 @@ [email protected], combined-stream@^1.0.5, combined-stream@~1.0.5: dependencies: delayed-stream "~1.0.0" +combined-stream@^1.0.6: + version "1.0.7" + resolved "http://registry.npm.taobao.org/combined-stream/download/combined-stream-1.0.7.tgz#2d1d24317afb8abe95d6d2c0b07b57813539d828" + integrity sha1-LR0kMXr7ir6V1tLAsHtXgTU52Cg= + dependencies: + delayed-stream "~1.0.0" + [email protected], commander@^2.12.1, commander@^2.13.0, commander@^2.9.0, commander@~2.15.0: version "2.15.1" resolved "http://registry.npm.taobao.org/commander/download/commander-2.15.1.tgz#df46e867d0fc2aec66a34662b406a9ccafff5b0f" @@ -3784,6 +3791,15 @@ fork-ts-checker-webpack-plugin@^0.4.0: tapable "^1.0.0" vue-parser "^1.1.5" +form-data@^2.3.3: + version "2.3.3" + resolved "http://registry.npm.taobao.org/form-data/download/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6" + integrity sha1-3M5SwF9kTymManq5Nr1yTO/786Y= + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.6" + mime-types "^2.1.12" + form-data@~2.1.1: version "2.1.4" resolved "http://registry.npm.taobao.org/form-data/download/form-data-2.1.4.tgz#33c183acf193276ecaa98143a69e94bfee1750d1" @@ -10168,11 +10184,6 @@ xml-name-validator@^3.0.0: version "3.0.0" resolved "http://registry.npm.taobao.org/xml-name-validator/download/xml-name-validator-3.0.0.tgz#6ae73e06de4d8c6e47f9fb181f78d648ad457c6a" -xmlhttprequest@^1.8.0: - version "1.8.0" - resolved "http://registry.npm.taobao.org/xmlhttprequest/download/xmlhttprequest-1.8.0.tgz#67fe075c5c24fef39f9d65f5f7b7fe75171968fc" - integrity sha1-Z/4HXFwk/vOfnWX197f+dRcZaPw= - [email protected]: version "4.0.0" resolved "http://registry.npm.taobao.org/xregexp/download/xregexp-4.0.0.tgz#e698189de49dd2a18cc5687b05e17c8e43943020"
test
add real requests for dicts
77e40b623bc964ac941c9b72e6368dae8a8c6317
2021-07-25 07:40:36
crimx
chore(release): 7.19.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 72676cfd..91b316ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +### [7.19.1](https://github.com/crimx/ext-saladict/compare/v7.19.0...v7.19.1) (2021-07-25) + + +### Bug Fixes + +* **no-typefield:** add support for content editable ([#1334](https://github.com/crimx/ext-saladict/issues/1334)) ([7984991](https://github.com/crimx/ext-saladict/commit/7984991e0e7adfb0b5fa16d604ffa3da6be65a40)) +* **pdf:** update pdf dir ([a8df19f](https://github.com/crimx/ext-saladict/commit/a8df19f12bcc5000eedaf40f6c0d3e0438386371)) + ## [7.19.0](https://github.com/crimx/ext-saladict/compare/v7.18.2...v7.19.0) (2021-05-23) diff --git a/package.json b/package.json index 81c4c13f..9c3e7ebf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "7.19.0", + "version": "7.19.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
7.19.1
fd25764c0303d448bccf7421fc4d4b46967a3647
2018-02-11 19:09:36
greenkeeperio-bot
chore(package): update lockfile
false
diff --git a/yarn.lock b/yarn.lock index 804d06681..2c187d6dd 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1537,6 +1537,14 @@ [email protected], chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0: escape-string-regexp "^1.0.5" supports-color "^4.0.0" [email protected]: + version "2.3.1" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.1.tgz#523fe2678aec7b04e8041909292fe8b17059b796" + dependencies: + ansi-styles "^3.2.0" + escape-string-regexp "^1.0.5" + supports-color "^5.2.0" + chardet@^0.4.0: version "0.4.2" resolved "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2" @@ -3665,6 +3673,10 @@ has-flag@^2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz#e8207af1cc7b30d446cc70b734b5e8be18f88d51" +has-flag@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" + has-unicode@^2.0.0: version "2.0.1" resolved "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" @@ -7623,6 +7635,12 @@ supports-color@^5.1.0: dependencies: has-flag "^2.0.0" +supports-color@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.2.0.tgz#b0d5333b1184dd3666cbe5aa0b45c5ac7ac17a4a" + dependencies: + has-flag "^3.0.0" + svgo@^0.7.0: version "0.7.2" resolved "https://registry.npmjs.org/svgo/-/svgo-0.7.2.tgz#9f5772413952135c6fefbf40afe6a4faa88b4bb5"
chore
update lockfile
f3592056958aef56d19e4e999ad6e4036a4d262c
2018-06-12 18:23:57
CRIMX
fix(panel): reset dict height
false
diff --git a/src/content/components/DictPanelPortal/_style.scss b/src/content/components/DictPanelPortal/_style.scss index d24bd7585..003cea9bd 100644 --- a/src/content/components/DictPanelPortal/_style.scss +++ b/src/content/components/DictPanelPortal/_style.scss @@ -47,6 +47,15 @@ transition: opacity 0.4s, width 0.4s, height 0.4s !important; } + &.saladict-DictPanel-entering { + will-change: opacity, width, height, left, top !important; + transition: opacity 0.2s, + width 0.4s, height 0.4s, + top 0.4s cubic-bezier(0.55, 0.82, 0.63, 0.95), + left 0.4s cubic-bezier(0.4, 0.9, 0.71, 1.02) + !important; + } + &.saladict-DictPanel-exit { will-change: opacity, width, height; transition: opacity 0.1s, width 0.4s, height 0.4s !important; diff --git a/src/content/redux/modules/widget.ts b/src/content/redux/modules/widget.ts index e84186dff..0d0073b45 100644 --- a/src/content/redux/modules/widget.ts +++ b/src/content/redux/modules/widget.ts @@ -598,14 +598,13 @@ function listenNewSelection ( } if (!isPinned && (shouldPanelShow || !lastShouldPanelShow)) { + dictHeights = {} // don't calculate on hiding to prevent moving animation newWidgetPartial.panelRect = _getPanelRectFromEvent( mouseX, mouseY, lastPanelRect.width, - shouldPanelShow - ? 30 + state.dictionaries.active.length * 30 - : isSaladictPopupPage ? 400 : 30, + isSaladictPopupPage ? 400 : 30, ) }
fix
reset dict height
a449119ae1643b2cb19b23e68aa1a998382c6cb9
2020-09-17 10:51:31
crimx
fix(dicts): sogou access token is required Closes #1011
false
diff --git a/src/_locales/en/content.ts b/src/_locales/en/content.ts index fec955152..9c9c9c4f0 100644 --- a/src/_locales/en/content.ts +++ b/src/_locales/en/content.ts @@ -39,7 +39,9 @@ export const locale: typeof _locale = { stext: 'Original', showSl: 'Show Source', copySrc: 'Copy Source', - copyTrans: 'Copy Translation' + copyTrans: 'Copy Translation', + login: 'Please provide {access token}.', + dictAccount: 'access token' }, updateAnki: { title: 'Update to Anki', diff --git a/src/_locales/zh-CN/content.ts b/src/_locales/zh-CN/content.ts index 6a5278489..9929a0e49 100644 --- a/src/_locales/zh-CN/content.ts +++ b/src/_locales/zh-CN/content.ts @@ -37,7 +37,9 @@ export const locale = { stext: '原文', showSl: '显示原文', copySrc: '复制原文', - copyTrans: '复制译文' + copyTrans: '复制译文', + login: '请登录{词典帐号}以使用。', + dictAccount: '词典帐号' }, updateAnki: { title: '更新到 Anki', diff --git a/src/_locales/zh-TW/content.ts b/src/_locales/zh-TW/content.ts index e4fbfb413..8efd50016 100644 --- a/src/_locales/zh-TW/content.ts +++ b/src/_locales/zh-TW/content.ts @@ -39,7 +39,9 @@ export const locale: typeof _locale = { stext: '原文', showSl: '顯示原文', copySrc: '複製原文', - copyTrans: '複製譯文' + copyTrans: '複製譯文', + login: '請登入{詞典帳號}以使用。', + dictAccount: '詞典帳號' }, updateAnki: { title: '更新到 Anki', diff --git a/src/components/MachineTrans/MachineTrans.tsx b/src/components/MachineTrans/MachineTrans.tsx index 84c214837..754c3108c 100644 --- a/src/components/MachineTrans/MachineTrans.tsx +++ b/src/components/MachineTrans/MachineTrans.tsx @@ -11,6 +11,7 @@ import { ViewPorps } from '@/components/dictionaries/helpers' import { DictID } from '@/app-config' import { message } from '@/_helpers/browser-api' import { MachineTranslateResult } from './engine' +import { Trans, useTranslate } from '@/_helpers/i18n' type TTextSource = | MachineTranslateResult<DictID>['searchText'] @@ -133,6 +134,10 @@ export const MachineTrans: FC<MachineTransProps> = props => { } }) + if (props.result.requireCredential) { + return renderCredential() + } + return ( <div className={ @@ -152,3 +157,18 @@ export const MachineTrans: FC<MachineTransProps> = props => { </div> ) } + +function renderCredential() { + const { t } = useTranslate('content') + return ( + <Trans message={t('machineTrans.login')}> + <a + href={browser.runtime.getURL('options.html?menuselected=DictAuths')} + target="_blank" + rel="nofollow noopener noreferrer" + > + {t('machineTrans.dictAccount')} + </a> + </Trans> + ) +} diff --git a/src/components/MachineTrans/engine.ts b/src/components/MachineTrans/engine.ts index 77bd66023..b314a47e5 100644 --- a/src/components/MachineTrans/engine.ts +++ b/src/components/MachineTrans/engine.ts @@ -25,6 +25,7 @@ export interface MachineTranslateResult<ID extends DictID> { paragraphs: string[] tts?: string } + requireCredential?: boolean } type DefaultMachineOptions<Lang extends Language> = { diff --git a/src/components/dictionaries/sogou/engine.ts b/src/components/dictionaries/sogou/engine.ts index b7f581420..8456bbe17 100644 --- a/src/components/dictionaries/sogou/engine.ts +++ b/src/components/dictionaries/sogou/engine.ts @@ -42,6 +42,23 @@ export const search: SearchFunction< SogouResult, MachineTranslatePayload<SogouLanguage> > = async (rawText, config, profile, payload) => { + if (!config.dictAuth.sogou.pid) { + return machineResult( + { + result: { + requireCredential: true, + id: 'sogou', + sl: 'auto', + tl: 'auto', + slInitial: 'hide', + searchText: { paragraphs: [''] }, + trans: { paragraphs: [''] } + } + }, + [] + ) + } + const translator = getTranslator() const { sl, tl, text } = await getMTArgs( @@ -52,9 +69,10 @@ export const search: SearchFunction< payload ) - const pid = config.dictAuth.sogou.pid - const key = config.dictAuth.sogou.key - const translatorConfig = pid || key ? { pid, key } : undefined + const translatorConfig = { + pid: config.dictAuth.sogou.pid, + key: config.dictAuth.sogou.key + } try { const result = await translator.translate(text, sl, tl, translatorConfig) @@ -64,6 +82,7 @@ export const search: SearchFunction< id: 'sogou', sl: result.from, tl: result.to, + slInitial: profile.dicts.all.sogou.options.slInitial, searchText: result.origin, trans: result.trans }, @@ -81,6 +100,7 @@ export const search: SearchFunction< id: 'sogou', sl, tl, + slInitial: 'hide', searchText: { paragraphs: [''] }, trans: { paragraphs: [''] } }
fix
sogou access token is required Closes #1011
f8da4be56efb06a8509f6aa365dfa057af028f1f
2018-07-18 16:41:23
CRIMX
feat(selection): add selection inside dict panel #165
false
diff --git a/src/_helpers/selection.ts b/src/_helpers/selection.ts index 227d6697b..dec5a2b76 100644 --- a/src/_helpers/selection.ts +++ b/src/_helpers/selection.ts @@ -124,16 +124,22 @@ export function isSameSelection (a: SelectionInfo, b: SelectionInfo) { return a && b && a.text === b.text && a.context === b.context } -export function getSelectionInfo (): SelectionInfo { +export function getSelectionInfo (config: Partial<SelectionInfo> = {}): SelectionInfo { return { - text: getSelectionText(), - context: getSelectionSentence(), - title: window.pageTitle || document.title, - url: window.pageURL || document.URL, + text: config.text != null ? config.text : getSelectionText(), + context: config.context != null ? config.context : getSelectionSentence(), + title: config.title != null + ? config.title + : window.pageTitle || document.title || '', + url: config.url != null + ? config.url + : window.pageURL || document.URL || '', // set by chrome-api helper - favicon: window.faviconURL || '', - trans: '', - note: '', + favicon: config.favicon != null + ? config.favicon + : window.faviconURL || '', + trans: config.trans || '', + note: config.note || '', } } diff --git a/src/_locales/options/messages.json b/src/_locales/options/messages.json index 6b137cbd5..976e4920b 100644 --- a/src/_locales/options/messages.json +++ b/src/_locales/options/messages.json @@ -389,6 +389,16 @@ "zh_CN": "添加生词", "zh_TW": "添加生字" }, + "panelmode_description": { + "en": "Inside dict panel. See 'Search Mode' above. <p class=\"hl\">Note that it won't affect the dict panel on this page.</p>", + "zh_CN": "查词面板内部的查词模式。参见上方“查词模式”。<p class=\"hl\">注意在本页面的查词面板上没有效果。</p>", + "zh_TW": "字典視窗內部的查字模式。參見上方「查字模式」。<p class=\"hl\">注意在本窗口的字典視窗介面中沒有效果。</p>" + }, + "panelmode_title": { + "en": "Panel Mode", + "zh_CN": "面板查词", + "zh_TW": "內部滑選" + }, "pdf_sniff": { "en": "Enable PDF Viewer", "zh_CN": "默认用本扩展浏览 PDF", diff --git a/src/app-config/index.ts b/src/app-config/index.ts index 7be95a0f8..ec78b0a46 100644 --- a/src/app-config/index.ts +++ b/src/app-config/index.ts @@ -56,14 +56,6 @@ export interface AppConfigMutable { /** panel font-size */ fontSize: number - /** - * panel double click search - * empty means no double click search - * 'double' means double click - * 'ctrl' means double click + ctrl/command pressed - */ - panelDbSearch: '' | 'double' | 'ctrl' - /** sniff pdf request */ pdfSniff: boolean @@ -112,6 +104,22 @@ export interface AppConfigMutable { } }, + /** when and how to search text inside dict panel */ + panelMode: { + /** direct: on mouseup */ + direct: boolean + /** double: double click */ + double: boolean + /** ctrl: search when double click ctrl + selection not empty */ + ctrl: boolean + /** cursor instant capture */ + instant: { + enable: boolean + key: 'direct' | 'ctrl' | 'alt' + delay: number + } + }, + /** instant capture delay, in ms */ insCapDelay: number @@ -178,7 +186,7 @@ export default appConfigFactory export function appConfigFactory (): AppConfig { return { - version: 7, + version: 8, active: true, @@ -194,8 +202,6 @@ export function appConfigFactory (): AppConfig { fontSize: 13, - panelDbSearch: '', - pdfSniff: true, searhHistory: false, @@ -228,6 +234,17 @@ export function appConfigFactory (): AppConfig { }, }, + panelMode: { + direct: false, + double: false, + ctrl: false, + instant: { + enable: false, + key: 'alt', + delay: 600, + }, + }, + insCapDelay: 600, doubleClickDelay: 450, diff --git a/src/app-config/merge-config.ts b/src/app-config/merge-config.ts index e1a8d125f..e1b6634d2 100644 --- a/src/app-config/merge-config.ts +++ b/src/app-config/merge-config.ts @@ -30,7 +30,6 @@ function mergeHistorical (config: AppConfig, baseConfig?: AppConfig): AppConfig mergeNumber('panelWidth') mergeNumber('panelMaxHeightRatio') mergeNumber('fontSize') - merge('panelDbSearch', val => val === '' || val === 'double' || val === 'ctrl') mergeBoolean('pdfSniff') mergeBoolean('searhHistory') mergeBoolean('searhHistoryInco') @@ -52,6 +51,13 @@ function mergeHistorical (config: AppConfig, baseConfig?: AppConfig): AppConfig merge('pinMode.instant.key', val => val === 'direct' || val === 'ctrl' || val === 'alt') mergeNumber('pinMode.instant.delay') + mergeBoolean('panelMode.direct') + mergeBoolean('panelMode.double') + mergeBoolean('panelMode.ctrl') + mergeBoolean('panelMode.instant.enable') + merge('panelMode.instant.key', val => val === 'direct' || val === 'ctrl' || val === 'alt') + mergeNumber('panelMode.instant.delay') + mergeNumber('doubleClickDelay') mergeBoolean('tripleCtrl') @@ -99,9 +105,20 @@ function mergeHistorical (config: AppConfig, baseConfig?: AppConfig): AppConfig }) // patch - if (config.version === 6) { - base.dicts.all.google.selectionWC.max = 999999999999999 - base.dicts.all.youdao.selectionWC.max = 999999999999999 + switch (config.version) { + case 6: + base.dicts.all.google.selectionWC.max = 999999999999999 + base.dicts.all.youdao.selectionWC.max = 999999999999999 + break + case 7: + if (config['panelDbSearch'] === 'double') { + base.panelMode.double = true + } else if (config['panelDbSearch'] === 'ctrl') { + base.panelMode.ctrl = true + } + break + default: + break } return base diff --git a/src/content/__fake__/envContent.tsx b/src/content/__fake__/envContent.tsx index 7b7328f34..a45b90a9b 100644 --- a/src/content/__fake__/envContent.tsx +++ b/src/content/__fake__/envContent.tsx @@ -14,6 +14,9 @@ config.dicts.selected = ['bing', 'google', 'guoyu', 'cobuild', 'liangan'] config.mode.double = true // config.mode.icon = false // config.animation = false +config.panelMode.double = true +config.panelMode.ctrl = true +config.panelMode.instant.enable = true config.tripleCtrlAuto = true config.tripleCtrlLocation = TCDirection.right config.tripleCtrlPreload = 'selection' diff --git a/src/content/components/DictItem/index.tsx b/src/content/components/DictItem/index.tsx index 7d0e6bec3..db334ccd6 100644 --- a/src/content/components/DictItem/index.tsx +++ b/src/content/components/DictItem/index.tsx @@ -23,7 +23,6 @@ export interface DictItemProps extends DictItemDispatchers { readonly searchResult: any readonly fontSize: number - readonly panelDbSearch: '' | 'double' | 'ctrl' readonly panelWidth: number } @@ -171,25 +170,6 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati } } - handleDictItemDbClick = (e: React.MouseEvent<HTMLElement>) => { - const { t, id, searchText, panelDbSearch } = this.props - if (!panelDbSearch || (panelDbSearch === 'ctrl' && !(e.ctrlKey || e.metaKey))) { - return - } - const win = e.currentTarget.ownerDocument.defaultView - const text = getSelectionText(win) - if (text) { - searchText({ - info: getDefaultSelectionInfo({ - text, - context: getSelectionSentence(win), - title: `${t('fromSaladict')}: ${t(`dict:${id}`)}`, - favicon: `https://raw.githubusercontent.com/crimx/ext-saladict/dev/src/components/dictionaries/${id}/favicon.png` - }), - }) - } - } - handleDictURLClick = (e: React.MouseEvent<HTMLElement>) => { e.stopPropagation() e.preventDefault() @@ -252,7 +232,6 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati id, dictURL, fontSize, - panelDbSearch, searchStatus, searchResult, } = this.props @@ -267,7 +246,6 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati return ( <section className='panel-DictItem' onClick={this.handleDictItemClick} - onDoubleClick={panelDbSearch ? this.handleDictItemDbClick : undefined} > <header className='panel-DictItem_Header' onClick={this.toggleFolding}> <img className='panel-DictItem_Logo' src={require('@/components/dictionaries/' + id + '/favicon.png')} alt='dict logo' /> diff --git a/src/content/components/DictPanel/index.tsx b/src/content/components/DictPanel/index.tsx index e673a2332..4c5cd80b6 100644 --- a/src/content/components/DictPanel/index.tsx +++ b/src/content/components/DictPanel/index.tsx @@ -53,7 +53,6 @@ export default class DictPanel extends React.Component<DictPanelProps> { allDictsConfig, panelWidth, fontSize, - panelDbSearch, updateItemHeight, } = this.props @@ -90,7 +89,6 @@ export default class DictPanel extends React.Component<DictPanelProps> { text: (dictionaries.searchHistory[0] || selection.selectionInfo).text, dictURL, fontSize, - panelDbSearch, preferredHeight: allDictsConfig[id].preferredHeight, panelWidth, searchStatus: (dictsInfo[id] as any).searchStatus, diff --git a/src/content/components/DictPanelPortal/index.tsx b/src/content/components/DictPanelPortal/index.tsx index 1da6430f9..5101084fe 100644 --- a/src/content/components/DictPanelPortal/index.tsx +++ b/src/content/components/DictPanelPortal/index.tsx @@ -249,7 +249,7 @@ export default class DictPanelPortal extends React.Component<DictPanelPortalProp <PortalFrame className={frameClassName} bodyClassName={isAnimation ? 'isAnimate' : undefined} - name='saladict-frame' + name='saladict-dictpanel' frameBorder='0' head={this.frameHead} frameDidMount={this.frameDidMount} diff --git a/src/content/components/WordEditorPortal/index.tsx b/src/content/components/WordEditorPortal/index.tsx index 4baa4ecae..ed247c3ee 100644 --- a/src/content/components/WordEditorPortal/index.tsx +++ b/src/content/components/WordEditorPortal/index.tsx @@ -73,7 +73,7 @@ export default class WordEditorPortal extends React.Component<WordEditorPortalPr return ( <PortalFrame className={'saladict-WordEditor' + (isAnimation ? ' isAnimate' : '')} - name='saladict-frame' + name='saladict-wordeditor' frameBorder='0' head={this.frameHead} > diff --git a/src/content/containers/DictPanelContainer.tsx b/src/content/containers/DictPanelContainer.tsx index 933ef1299..3ebb38e68 100644 --- a/src/content/containers/DictPanelContainer.tsx +++ b/src/content/containers/DictPanelContainer.tsx @@ -20,7 +20,6 @@ export const mapStateToProps = ({ isAnimation: config.animation, allDictsConfig: config.dicts.all, fontSize: config.fontSize, - panelDbSearch: config.panelDbSearch, langCode: config.langCode, selection, diff --git a/src/content/redux/modules/widget.ts b/src/content/redux/modules/widget.ts index 16eb26c96..6166f557f 100644 --- a/src/content/redux/modules/widget.ts +++ b/src/content/redux/modules/widget.ts @@ -5,7 +5,7 @@ import { message } from '@/_helpers/browser-api' import { createAppConfigStream } from '@/_helpers/config-manager' import { MsgSelection, MsgType, MsgTempDisabledState, MsgEditWord, MsgOpenUrl } from '@/typings/message' import { searchText, restoreDicts } from '@/content/redux/modules/dictionaries' -import { SelectionInfo } from '@/_helpers/selection' +import { SelectionInfo, getDefaultSelectionInfo } from '@/_helpers/selection' import { Mutable } from '@/typings/helpers' const isSaladictOptionsPage = !!window.__SALADICT_OPTIONS_PAGE__ @@ -555,13 +555,36 @@ function listenNewSelection ( ) { message.self.addListener<MsgSelection>(MsgType.Selection, message => { const state = getState() + const { selectionInfo, dbClick, ctrlKey, instant, mouseX, mouseY, self } = message + + if (self) { + // inside dict panel + const { direct, double, ctrl } = state.config.panelMode + const { text, context } = selectionInfo + if (text && ( + instant || + direct || + (double && dbClick) || + (ctrl && ctrlKey) + ) + ) { + dispatch(searchText({ + info: getDefaultSelectionInfo({ + text, + context, + title: 'Saladict Panel', + favicon: 'https://raw.githubusercontent.com/crimx/ext-saladict/dev/public/static/icon-16.png', + }) + })) + } + return + } - if (isSaladictPopupPage) { return } + if (isSaladictPopupPage || isSaladictOptionsPage) { return } const isActive = state.config.active && !state.widget.isTempDisabled const { direct, ctrl, double, icon } = state.config.mode - const { selectionInfo, dbClick, ctrlKey, instant, mouseX, mouseY } = message const { isPinned, shouldPanelShow: lastShouldPanelShow, @@ -578,7 +601,6 @@ function listenNewSelection ( (ctrl && ctrlKey) || instant )) || - isSaladictOptionsPage || isSaladictPopupPage ) @@ -591,7 +613,6 @@ function listenNewSelection ( !(double && dbClick) && !(ctrl && ctrlKey) && !instant && - !isSaladictOptionsPage && !isSaladictPopupPage ) @@ -620,14 +641,12 @@ function listenNewSelection ( // should search text? const { pinMode } = state.config - if ((shouldPanelShow && selectionInfo.text && ( - !isPinned || - pinMode.direct || - (pinMode.double && dbClick) || - (pinMode.ctrl && ctrlKey) - ) - ) || - isSaladictOptionsPage + if (shouldPanelShow && selectionInfo.text && ( + !isPinned || + pinMode.direct || + (pinMode.double && dbClick) || + (pinMode.ctrl && ctrlKey) + ) ) { dispatch(searchText({ info: selectionInfo })) } else if (!shouldPanelShow && lastShouldPanelShow) { diff --git a/src/options/OptDictPanel.vue b/src/options/OptDictPanel.vue index b6babd023..b4e009918 100644 --- a/src/options/OptDictPanel.vue +++ b/src/options/OptDictPanel.vue @@ -4,16 +4,6 @@ <strong>{{ $t('opt:dict_panel_title') }}</strong> </div> <div class="opt-item__body"> - <div class="select-box-container"> - <label class="select-box"> - <span class="select-label">{{ $t('opt:dict_panel_db_search') }}</span> - <select class="form-control" v-model="panelDbSearch"> - <option value="">{{ $t('opt:dict_panel_db_search_none') }}</option> - <option value="double">{{ $t('opt:dict_panel_db_search_double') }}</option> - <option value="ctrl">{{ $t('opt:dict_panel_db_search_ctrl') }}</option> - </select> - </label> - </div> <div class="input-group"> <div class="input-group-addon">{{ $t('opt:dict_panel_height_ratio') }}</div> <input type="number" step="1" min="10" max="90" class="form-control" @@ -51,7 +41,6 @@ export default { panelWidth: 'config.panelWidth', panelMaxHeightRatio: 'config.panelMaxHeightRatio', fontSize: 'config.fontSize', - panelDbSearch: 'config.panelDbSearch', searchText: 'searchText', }, watch: { diff --git a/src/options/OptPanelMode.vue b/src/options/OptPanelMode.vue new file mode 100644 index 000000000..65ce3bfd7 --- /dev/null +++ b/src/options/OptPanelMode.vue @@ -0,0 +1,55 @@ +<template> + <div class="opt-item"><!-- 面板查词--> + <div class="opt-item__header"> + <strong>{{ $t('opt:panelmode_title') }}</strong> + </div> + <div class="opt-item__body"> + <div class="checkbox"> + <label class="checkbox-inline"> + <input type="checkbox" v-model="panelMode.direct"> {{ $t('opt:mode_direct') }} + </label> + <label class="checkbox-inline"> + <input type="checkbox" v-model="panelMode.double"> {{ $t('opt:mode_double') }} + </label> + <label class="checkbox-inline"> + <input type="checkbox" v-model="panelMode.ctrl"> {{ $t('opt:mode_ctrl') }} + </label> + <label class="checkbox-inline"> + <input type="checkbox" v-model="panelMode.instant.enable"> {{ $t('opt:mode_instant') }} + </label> + </div> + <div class="input-group" v-if="panelMode.double"> + <div class="input-group-addon">{{ $t('opt:mode_double_click_delay') }}</div> + <input type="number" min="1" class="form-control" v-model.number="doubleClickDelay"> + <div class="input-group-addon">{{ $t('opt:unit_ms') }}</div> + </div> + <div class="instant-capture-container" v-if="panelMode.instant.enable"> + <label class="select-box"> + <span class="select-label">{{ $t('opt:mode_instant_key') }}</span> + <select class="form-control" v-model="panelMode.instant.key"> + <option value="alt">{{ $t('opt:mode_instant_alt') }}</option> + <option value="ctrl">{{ $t('opt:mode_instant_ctrl') }}</option> + <option value="direct">{{ $t('opt:mode_instant_direct') }}</option> + </select> + </label> + <div class="input-group instant-capture-delay"> + <div class="input-group-addon">{{ $t('opt:mode_instant_delay') }}</div> + <input type="number" min="1" class="form-control" v-model.number="panelMode.instant.delay"> + <div class="input-group-addon">{{ $t('opt:unit_ms') }}</div> + </div> + </div> + </div> + <div class="opt-item__description-wrap"> + <p class="opt-item__description" v-html="$t('opt:panelmode_description')"></p> + </div> + </div><!-- 面板查词--> +</template> + +<script> +export default { + store: { + panelMode: 'config.panelMode', + doubleClickDelay: 'config.doubleClickDelay', + } +} +</script> diff --git a/src/options/Options.vue b/src/options/Options.vue index 763dbd523..88a432acf 100644 --- a/src/options/Options.vue +++ b/src/options/Options.vue @@ -69,6 +69,7 @@ const _optNames = [ 'OptDictPanel', 'OptMode', 'OptPinMode', + 'OptPanelMode', 'OptPopup', 'OptTripleCtrl', 'OptAutopron', @@ -450,6 +451,13 @@ kbd { padding-left: 15px; line-height: 1.8; color: #666; + + .hl { + padding: 0 5px; + color: white; + border-radius: 5px; + background: red; + } } .frame-container { diff --git a/src/options/index.ts b/src/options/index.ts index 4025b742f..08a530296 100644 --- a/src/options/index.ts +++ b/src/options/index.ts @@ -53,6 +53,7 @@ storage.sync.get('config') selectionInfo: getDefaultSelectionInfo({ text: window.__SALADICT_LAST_SEARCH__ || 'salad' }), + self: true, mouseX: window.innerWidth - this.$store.config.panelWidth - 110, mouseY: window.innerHeight * (1 - this.$store.config.panelMaxHeightRatio) / 2 + 50, dbClick: false, diff --git a/src/selection/index.ts b/src/selection/index.ts index bfebebe79..9056591a7 100644 --- a/src/selection/index.ts +++ b/src/selection/index.ts @@ -28,6 +28,8 @@ import { startWith } from 'rxjs/operators/startWith' import { pluck } from 'rxjs/operators/pluck' import { combineLatest } from 'rxjs/observable/combineLatest' +const isDictPanel = window.name === 'saladict-dictpanel' + let config = appConfigFactory() createAppConfigStream().subscribe(newConfig => config = newConfig) @@ -55,15 +57,8 @@ message.addListener(msg => { mouseX: clientX, mouseY: clientY, instant: true, - selectionInfo: { - text, - context: selection.getSelectionSentence(), - title: window.pageTitle || document.title, - url: window.pageURL || document.URL, - favicon: window.faviconURL || '', - trans: '', - note: '' - }, + self: isDictPanel, + selectionInfo: selection.getSelectionInfo({ text }), }) } } @@ -89,7 +84,7 @@ window.addEventListener('message', ({ data, source }: { data: PostMsgSelection, sendMessage(msg) }) -if (window.name !== 'saladict-frame') { +if (!window.name.startsWith('saladict-')) { /** * Pressing ctrl/command key more than three times within 500ms * trigers TripleCtrl @@ -129,7 +124,7 @@ const validMouseup$$ = merge( ), ).pipe( filter(({ target }) => { - if (window.name === 'saladict-frame') { + if (window.name === 'saladict-wordeditor') { return false } @@ -201,6 +196,7 @@ validMouseup$$.subscribe(event => { mouseY: event.clientY, dbClick: clickPeriodCount >= 2, ctrlKey: Boolean(event['metaKey'] || event['ctrlKey']), + self: isDictPanel, selectionInfo: { text: selection.getSelectionText(), context, @@ -230,15 +226,18 @@ combineLatest( ), ).pipe( map(([config, isPinned]) => { - const { instant } = config[isPinned ? 'pinMode' : 'mode'] + const { instant } = config[isDictPanel ? 'panelMode' : isPinned ? 'pinMode' : 'mode'] return [ instant.enable ? instant.key : '', instant.delay - ] as ['' | AppConfig['mode']['instant']['key'] | AppConfig['pinMode']['instant']['key'], number] + ] as [ + '' | AppConfig['mode']['instant']['key'] | AppConfig['pinMode']['instant']['key'] | AppConfig['panelMode']['instant']['key'], + number + ] }), distinctUntilChanged((oldVal, newVal) => oldVal[0] === newVal[0] && oldVal[1] === newVal[1]), switchMap(([instant, insCapDelay]) => { - if (!instant || window.name === 'saladict-frame') { return of(undefined) } + if (!instant || window.name === 'saladict-wordeditor') { return of(undefined) } return merge( validMouseup$$.pipe(mapTo(undefined)), fromEvent<MouseEvent>(window, 'mouseout', { capture: true }).pipe(mapTo(undefined)), @@ -272,15 +271,8 @@ combineLatest( mouseX: event.clientX, mouseY: event.clientY, instant: true, - selectionInfo: { - text, - context, - title: window.pageTitle || document.title, - url: window.pageURL || document.URL, - favicon: window.faviconURL || '', - trans: '', - note: '' - }, + self: isDictPanel, + selectionInfo: selection.getSelectionInfo({ text, context }), }) } }) @@ -294,6 +286,7 @@ function sendMessage ( selectionInfo: selection.SelectionInfo mouseX: number mouseY: number + self: boolean dbClick?: boolean ctrlKey?: boolean instant?: boolean @@ -322,16 +315,8 @@ function sendEmptyMessage () { // empty message const msg: MsgSelection = { type: MsgType.Selection, - selectionInfo: { - text: '', - context: '', - title: window.pageTitle || document.title, - url: window.pageURL || document.URL, - // set by browser-api helper - favicon: window.faviconURL || '', - trans: '', - note: '' - }, + selectionInfo: selection.getDefaultSelectionInfo(), + self: isDictPanel, mouseX: 0, mouseY: 0, dbClick: false, diff --git a/src/typings/message.ts b/src/typings/message.ts index b9e6f463f..d98e31a61 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -72,6 +72,8 @@ export interface MsgSelection { readonly selectionInfo: SelectionInfo readonly mouseX: number readonly mouseY: number + /** inside panel? */ + readonly self: boolean readonly dbClick?: boolean readonly ctrlKey?: boolean /** skip salad bowl and show panel directly */
feat
add selection inside dict panel #165
fb3c7329b3fb8732f154fd78bac91da7cadb3611
2019-03-17 13:50:37
CRIMX
chore(release): 6.27.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4620141ee..414d73cd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.27.1"></a> +## [6.27.1](https://github.com/crimx/ext-saladict/compare/v6.27.0...v6.27.1) (2019-03-17) + + +### Bug Fixes + +* **manifest:** firefox incognito mode ([58b946f](https://github.com/crimx/ext-saladict/commit/58b946f)) + + + <a name="6.27.0"></a> # [6.27.0](https://github.com/crimx/ext-saladict/compare/v6.26.0...v6.27.0) (2019-03-17) diff --git a/package.json b/package.json index fa132d7fb..bb1269053 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.27.0", + "version": "6.27.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.27.1
508f44344c55cf9f38f246d80b60f334a793d5e9
2019-09-13 02:52:11
crimx
chore(release): 6.33.6
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index a1e49ae77..d0aa9a3e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.33.6"></a> +## [6.33.6](https://github.com/crimx/ext-saladict/compare/v6.33.5...v6.33.6) (2019-09-12) + + +### Bug Fixes + +* update dicts ([4492cd0](https://github.com/crimx/ext-saladict/commit/4492cd0)) + + + <a name="6.33.5"></a> ## [6.33.5](https://github.com/crimx/ext-saladict/compare/v6.33.4...v6.33.5) (2019-08-11) diff --git a/package.json b/package.json index a205a453b..14b3a73c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.33.5", + "version": "6.33.6", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.33.6
1226f4ae4a0a7d0c2d097ddb2772bebc372ed79c
2019-09-28 15:04:17
crimx
chore(dicts): compress favicon
false
diff --git a/src/components/dictionaries/weblioejje/favicon.png b/src/components/dictionaries/weblioejje/favicon.png index 7c07c3604..e0ee06ae9 100644 Binary files a/src/components/dictionaries/weblioejje/favicon.png and b/src/components/dictionaries/weblioejje/favicon.png differ
chore
compress favicon
dc7ede1438fffbd23b2a92f94ece343ed34e19ef
2019-02-13 09:32:32
CRIMX
chore(release): 6.24.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index af20db12b..fd440220f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.24.1"></a> +## [6.24.1](https://github.com/crimx/ext-saladict/compare/v6.24.0...v6.24.1) (2019-02-13) + + +### Bug Fixes + +* **background:** proper init ([9babdef](https://github.com/crimx/ext-saladict/commit/9babdef)) + + + <a name="6.24.0"></a> # [6.24.0](https://github.com/crimx/ext-saladict/compare/v6.23.1...v6.24.0) (2019-02-12) diff --git a/package.json b/package.json index 1a51c74f0..d56751c9f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.24.0", + "version": "6.24.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.24.1
31c3132e14a7051e6b043722ff19555d132e6cb5
2020-07-07 14:39:04
crimx
refactor(components): add title to catalog select
false
diff --git a/src/components/FloatBox/index.tsx b/src/components/FloatBox/index.tsx index 0f8d11921..8cef3dcaa 100644 --- a/src/components/FloatBox/index.tsx +++ b/src/components/FloatBox/index.tsx @@ -18,6 +18,7 @@ export type FloatBoxItem = value: string label: string }> + title?: string } export interface FloatBoxProps { @@ -104,6 +105,7 @@ export const FloatBox: FC<FloatBoxProps> = React.forwardRef( onBlur={props.onBlur} onChange={onSelectItemChange} > + {item.title && <option disabled>{item.title}</option>} {item.options.map(opt => ( <option key={opt.value} value={opt.value}> {opt.label} diff --git a/src/components/MachineTrans/engine.ts b/src/components/MachineTrans/engine.ts index 20c4e1a28..a4aed1f9c 100644 --- a/src/components/MachineTrans/engine.ts +++ b/src/components/MachineTrans/engine.ts @@ -222,11 +222,13 @@ export function machineResult<ID extends DictID>( { key: 'sl', value: data.result.sl, + title: '%t(content:machineTrans.sl)', options: langCodesOptions }, { key: 'tl', value: data.result.tl, + title: '%t(content:machineTrans.tl)', options: langCodesOptions }, { diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index 9ca9a5418..5f4dd8055 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -44,6 +44,7 @@ export interface DictSearchResult<Result> { value: string label: string }> + title?: string } > } diff --git a/src/content/components/DictItem/DictItemHead.tsx b/src/content/components/DictItem/DictItemHead.tsx index 174d0d64e..a10fa1d99 100644 --- a/src/content/components/DictItem/DictItemHead.tsx +++ b/src/content/components/DictItem/DictItemHead.tsx @@ -27,6 +27,7 @@ export interface DictItemHeadProps { value: string label: string }> + title?: string } > } @@ -65,6 +66,7 @@ export const DictItemHead: FC<DictItemHeadProps> = props => { menuItems.push({ key: item.key, value: item.value, + title: item.title && localedLabel(item.title), options: item.options.map(opt => ({ value: opt.value, label: localedLabel(opt.label)
refactor
add title to catalog select
82a4c4d3c93fe0e6c99cf99874f80042e754c077
2019-08-20 17:00:37
crimx
refactor(content): redux init
false
diff --git a/src/content/redux/modules/action-catalog.ts b/src/content/redux/modules/action-catalog.ts index 5f2b90bbb..be1afdfed 100644 --- a/src/content/redux/modules/action-catalog.ts +++ b/src/content/redux/modules/action-catalog.ts @@ -7,20 +7,34 @@ export type ActionCatalog = { NEW_CONFIG: { payload: AppConfig } + NEW_PROFILE: { payload: Profile } + NEW_SELECTION: { payload: Message<'SELECTION'>['payload'] } + + /** Is App temporary disabled */ + TEMP_DISABLED_STATE: { + payload: boolean + } + /** Click or hover on salad bowl */ BOWL_ACTIVATED: {} - SEARCH_END: { - payload: { - id: DictID - result: any - } + + /* ------------------------------------------------ *\ + Dict Panel + \* ------------------------------------------------ */ + + CLOSE_PANEL: {} + + /** Is current word in Notebook */ + WORD_IN_NOTEBOOK: { + payload: boolean } + SEARCH_START: { payload?: { /** Search with specific dict */ @@ -31,8 +45,26 @@ export type ActionCatalog = { payload?: any } } - /** Is current word in Notebook */ - WORD_IN_NOTEBOOK: { + + SEARCH_END: { + payload: { + id: DictID + result: any + } + } + + /* ------------------------------------------------ *\ + Quick Search Dict Panel + \* ------------------------------------------------ */ + + SUMMONED_PANEL_INIT: { + /** search text */ + payload: string + } + + QS_PANEL_CHANGED: { payload: boolean } + + OPEN_QS_PANEL: {} } diff --git a/src/content/redux/modules/init.ts b/src/content/redux/modules/init.ts index fe719f04e..9abd70f41 100644 --- a/src/content/redux/modules/init.ts +++ b/src/content/redux/modules/init.ts @@ -1,9 +1,16 @@ import { Init } from '../utils/types' import { addConfigListener } from '@/_helpers/config-manager' import { addActiveProfileListener } from '@/_helpers/profile-manager' -import { isPopupPage, isQuickSearchPage } from '@/_helpers/saladict' -import { StoreActionCatalog, StoreState } from '.' +import { + isPopupPage, + isQuickSearchPage, + isOptionsPage +} from '@/_helpers/saladict' +import { StoreActionCatalog, StoreAction, StoreState } from '.' import { message } from '@/_helpers/browser-api' +import { PreloadSource } from '@/app-config' +import { Dispatch } from 'redux' +import { Word, newWord } from '@/_helpers/record-manager' export const init: Init<StoreActionCatalog, StoreState> = ( dispatch, @@ -17,15 +24,147 @@ export const init: Init<StoreActionCatalog, StoreState> = ( dispatch({ type: 'NEW_PROFILE', payload: newProfile }) }) + message.addListener(msg => { + switch (msg.type) { + case 'TEMP_DISABLED_STATE': + if (msg.payload.op === 'set') { + dispatch({ type: 'TEMP_DISABLED_STATE', payload: msg.payload.value }) + return Promise.resolve(true) + } else { + return Promise.resolve(getState().isTempDisabled) + } + + case 'QS_PANEL_SEARCH_TEXT': + if (isQuickSearchPage()) { + // request searching text, from other tabs + dispatch({ type: 'SEARCH_START', payload: { word: msg.payload } }) + // focus standalone panel + message.send({ type: 'OPEN_QS_PANEL' }) + } + return Promise.resolve() + + case 'QS_PANEL_CHANGED': + if (!isQuickSearchPage()) { + dispatch({ type: 'QS_PANEL_CHANGED', payload: msg.payload }) + } + return Promise.resolve() + } + }) + + message.self.addListener(msg => { + switch (msg.type) { + case 'ESCAPE_KEY': + dispatch({ type: 'CLOSE_PANEL' }) + return Promise.resolve() + + case 'SEARCH_TEXT': + dispatch({ type: 'SEARCH_START', payload: { word: msg.payload } }) + return Promise.resolve() + + case 'TRIPLE_CTRL': + if (!isPopupPage() && !isOptionsPage()) { + const { isShowDictPanel, config, selection } = getState() + if (config.tripleCtrl) { + if (config.tripleCtrlStandalone) { + // focus if the standalone panel is already opened + message.send({ type: 'OPEN_QS_PANEL' }) + } else if (!isShowDictPanel) { + dispatch({ type: 'OPEN_QS_PANEL' }) + summonedPanelInit( + dispatch, + selection.word, + config.tripleCtrlPreload, + config.tripleCtrlAuto, + '' + ) + } + } + } + return Promise.resolve() + } + }) + if (isPopupPage()) { - const { baPreload, baAuto } = getState().config - dispatch(summonedPanelInit(baPreload, baAuto, 'popup')) - } else if (isQuickSearchPage()) { - /** From other tabs */ - message.addListener('QS_PANEL_SEARCH_TEXT', ({ payload }) => { - dispatch({ type: 'SEARCH_START', payload: { word: payload } }) - // focus standalone panel - message.send({ type: 'OPEN_QS_PANEL' }) - }) + const { config, selection } = getState() + summonedPanelInit( + dispatch, + selection.word, + config.baPreload, + config.baAuto, + 'popup' + ) + } + + if (isQuickSearchPage()) { + const { config, selection } = getState() + summonedPanelInit( + dispatch, + selection.word, + config.tripleCtrlPreload, + config.tripleCtrlAuto, + 'quick-search' + ) + } else { + message + .send<'QUERY_QS_PANEL'>({ type: 'QUERY_QS_PANEL' }) + .then(response => + dispatch({ type: 'QS_PANEL_CHANGED', payload: response }) + ) + } +} + +/** Dict Panel show that is triggered by anything other than selection */ +async function summonedPanelInit( + dispatch: Dispatch<StoreAction>, + word: Word | null, + preload: PreloadSource, + autoSearch: boolean, + // quick-search could be turned off so this argument is needed + standalone: '' | 'popup' | 'quick-search' +) { + if (!preload) { + return + } + + try { + if (preload === 'selection') { + if (standalone === 'popup') { + const tab = (await browser.tabs.query({ + active: true, + currentWindow: true + }))[0] + if (tab && tab.id != null) { + word = await message.send<'PRELOAD_SELECTION'>(tab.id, { + type: 'PRELOAD_SELECTION' + }) + } + } else if (standalone === 'quick-search') { + const infoText = new URL(document.URL).searchParams.get('info') + if (infoText) { + try { + word = JSON.parse(decodeURIComponent(infoText)) + } catch (err) { + word = null + } + } + } + } /* preload === clipboard */ else { + const text = await message.send<'GET_CLIPBOARD'>({ + type: 'GET_CLIPBOARD' + }) + word = newWord({ text, title: 'From Clipboard' }) + } + } catch (e) { + if (process.env.NODE_ENV !== 'production') { + console.warn(e) + } + } + + if (word) { + if (autoSearch && word.text) { + dispatch({ type: 'SEARCH_START', payload: { word } }) + } else { + dispatch({ type: 'SUMMONED_PANEL_INIT', payload: word.text }) + } } } diff --git a/src/content/redux/modules/reducer/index.ts b/src/content/redux/modules/reducer/index.ts index 1de6cbcf8..53f669abb 100644 --- a/src/content/redux/modules/reducer/index.ts +++ b/src/content/redux/modules/reducer/index.ts @@ -1,8 +1,10 @@ +import { isOptionsPage, isStandalonePage } from '@/_helpers/saladict' import { createReducer } from '../../utils/createReducer' import { initState } from '../state' import { ActionCatalog } from '../action-catalog' import { searchStart } from './search-start.handler' import { newSelection } from './new-selection.handler' +import { openQSPanel } from './open-qs-panel.handler' export const reducer = createReducer<typeof initState, ActionCatalog>( initState, @@ -17,6 +19,7 @@ export const reducer = createReducer<typeof initState, ActionCatalog>( payload.whitelist.every(([r]) => !new RegExp(r).test(url)) } }, + NEW_PROFILE: (state, { payload }) => ({ ...state, activeProfile: payload, @@ -24,12 +27,46 @@ export const reducer = createReducer<typeof initState, ActionCatalog>( payload.dicts.selected.includes(id) ) }), + NEW_SELECTION: newSelection, + + TEMP_DISABLED_STATE: (state, { payload }) => + payload + ? { + ...state, + isTempDisabled: true, + isPinned: false, + shouldPanelShow: false, + shouldBowlShow: false + } + : { + ...state, + isTempDisabled: false + }, + BOWL_ACTIVATED: state => ({ ...state, isShowBowl: false, isShowDictPanel: true }), + + CLOSE_PANEL: state => + isOptionsPage() || isStandalonePage() + ? state + : { + ...state, + isPinned: false, + isShowBowl: false, + isShowDictPanel: false + }, + + WORD_IN_NOTEBOOK: (state, { payload }) => ({ + ...state, + isFav: payload + }), + + SEARCH_START: searchStart, + SEARCH_END: (state, { payload }) => { if (state.renderedDicts.every(({ id }) => id !== payload.id)) { // this dict is for auto-pronunciation only @@ -49,11 +86,36 @@ export const reducer = createReducer<typeof initState, ActionCatalog>( ) } }, - SEARCH_START: searchStart, - WORD_IN_NOTEBOOK: (state, { payload }) => ({ + + SUMMONED_PANEL_INIT: (state, { payload }) => ({ ...state, - isFav: payload - }) + text: payload, + historyIndex: 0, + isShowDictPanel: true, + isShowBowl: false + }), + + QS_PANEL_CHANGED: (state, { payload }) => { + if (state.withQSPanel === payload) { + return state + } + + // hide panel on otehr pages and leave just quick search panel + return payload + ? { + ...state, + withQSPanel: payload, + isPinned: false, + shouldPanelShow: false, + shouldBowlShow: false + } + : { + ...state, + withQSPanel: payload + } + }, + + OPEN_QS_PANEL: openQSPanel } ) diff --git a/src/content/redux/modules/reducer/open-qs-panel.handler.ts b/src/content/redux/modules/reducer/open-qs-panel.handler.ts new file mode 100644 index 000000000..41e936cdd --- /dev/null +++ b/src/content/redux/modules/reducer/open-qs-panel.handler.ts @@ -0,0 +1,63 @@ +import { StoreActionHandler } from '..' + +export const openQSPanel: StoreActionHandler<'OPEN_QS_PANEL'> = state => { + const { panelWidth, tripleCtrl, tripleCtrlLocation } = state.config + + if (!tripleCtrl || state.isShowDictPanel) { + return state + } + + let x = 10 + let y = 10 + + switch (tripleCtrlLocation) { + case 'CENTER': + x = (window.innerWidth - panelWidth) / 2 + y = window.innerHeight * 0.3 + break + case 'TOP': + x = (window.innerWidth - panelWidth) / 2 + y = 10 + break + case 'RIGHT': + x = window.innerWidth - panelWidth - 30 + y = window.innerHeight * 0.3 + break + case 'BOTTOM': + x = (window.innerWidth - panelWidth) / 2 + y = window.innerHeight - 10 + break + case 'LEFT': + x = 10 + y = window.innerHeight * 0.3 + break + case 'TOP_LEFT': + x = 10 + y = 10 + break + case 'TOP_RIGHT': + x = window.innerWidth - panelWidth - 30 + y = 10 + break + case 'BOTTOM_LEFT': + x = 10 + y = window.innerHeight - 10 + break + case 'BOTTOM_RIGHT': + x = window.innerWidth - panelWidth - 30 + y = window.innerHeight - 10 + break + } + + return { + ...state, + isShowDictPanel: true, + // skip reconciliation with negative values + dictPanelCord: { + mouseX: -x, + mouseY: -y + } + } +} + +export default openQSPanel diff --git a/src/content/redux/modules/state.ts b/src/content/redux/modules/state.ts index 9e2b68568..0c1e9f868 100644 --- a/src/content/redux/modules/state.ts +++ b/src/content/redux/modules/state.ts @@ -26,10 +26,10 @@ export const initState = { withQSPanel: false, /** Is current word in Notebook */ isFav: false, - /** -1 is for panel show triggered by anything other than selection */ + /** Pass negative value to skip the reconciliation */ dictPanelCord: { - mouseX: -1, - mouseY: -1 + mouseX: 0, + mouseY: 0 }, /** Dicts that will be rendered to dict panel */ renderedDicts: [] as { @@ -37,6 +37,8 @@ export const initState = { readonly searchStatus: 'IDLE' | 'SEARCHING' | 'FINISH' readonly searchResult: any }[], + /** Search text */ + text: '', /** 0 is the oldest */ searchHistory: [] as Word[], /** User can view back search history */ diff --git a/src/typings/message.ts b/src/typings/message.ts index 50d3c3336..3eb3fc7ec 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -27,6 +27,11 @@ export type MessageConfig = { } } + /** Get clipboard content */ + GET_CLIPBOARD: { + response: string + } + /** Request backend for page info */ PAGE_INFO: { response: { @@ -162,6 +167,16 @@ export type MessageConfig = { } } + /** send to the current active tab for selection */ + PRELOAD_SELECTION: { + response: Word + } + + ESCAPE_KEY: {} + + /** Ctrl/Command has been hit 3 times */ + TRIPLE_CTRL: {} + /* ------------------------------------------------ *\ Dict Panel \* ------------------------------------------------ */ @@ -177,6 +192,23 @@ export type MessageConfig = { payload?: string } + /** request searching */ + SEARCH_TEXT: { + payload: Word + } + + TEMP_DISABLED_STATE: { + payload: + | { + op: 'get' + } + | { + op: 'set' + value: boolean + } + response: boolean + } + /* ------------------------------------------------ *\ Quick Search Dict Panel \* ------------------------------------------------ */ @@ -189,6 +221,16 @@ export type MessageConfig = { /** Open or update Quick Search Panel */ OPEN_QS_PANEL: {} + /** query backend for standalone panel appearance */ + QUERY_QS_PANEL: { + response: boolean + } + + /** Fired from backend when standalone panel show or hide */ + QS_PANEL_CHANGED: { + payload: boolean + } + /* ------------------------------------------------ *\ Sync services \* ------------------------------------------------ */ @@ -251,38 +293,17 @@ export type MessageResponse<T extends MsgType> = Readonly< // /** Default */ // Default, -// /** is a standalone panel running? */ -// QSPanelIDChanged, - -// /** query background for standalone panel appearance */ -// QueryQSPanel, - // CloseQSPanel, -// /** Ctrl/Command has been hit 3 times */ -// TripleCtrl, - -// /** Escape key is pressed */ -// EscapeKey, - // /** Response the pageInfo of a page */ // PageInfo, // /** Background to a dict panel on one page */ // PlayWaveform, // /** Request background proxy for current selection */ -// PreloadSelection, -// /** Get clipboard content */ -// GetClipboard, // RequestCSS, -// /** Popup page */ -// TempDisabledState, - -// /** Word page */ -// EditWord, - // /** Query panel state */ // QueryPanelState, @@ -417,22 +438,6 @@ export type MessageResponse<T extends MsgType> = Readonly< // readonly words: Word[] // } -// export type MsgTempDisabledState = -// | { -// readonly type: MsgType.TempDisabledState -// readonly op: 'get' -// } -// | { -// readonly type: MsgType.TempDisabledState -// readonly op: 'set' -// readonly value: boolean -// } - -// export interface MsgEditWord { -// readonly type: MsgType.EditWord -// readonly word: Word -// } - // export interface MsgIsPinned { // readonly type: MsgType.IsPinned // readonly isPinned: boolean
refactor
redux init
c81e06362c2b9f17595f6de69a079f93822a1225
2018-09-01 19:55:52
CRIMX
refactor(options): show error when import failed
false
diff --git a/src/options/Options.vue b/src/options/Options.vue index 04ee114b1..df5fc6244 100644 --- a/src/options/Options.vue +++ b/src/options/Options.vue @@ -1,8 +1,8 @@ <template> <div> <transition name="dropdown"> - <div class="config-updated" v-if="isShowConfigUpdated"> - {{ $t('opt:storage_updated') }} + <div :class="`config-updated ${configUpdateStatus}`" v-if="configUpdateStatus"> + {{ configUpdateMsg }} </div> </transition> <div class="opt-container"> @@ -93,20 +93,29 @@ export default { store: ['activeConfigID', 'configProfileIDs', 'configProfiles', 'config', 'newVersionAvailable', 'searchText'], data () { return { - isShowConfigUpdated: false, + configUpdateStatus: '', + configUpdateMsg: '', isShowSocial: false, isShowAcknowledgement: false, optNames: _optNames, } }, methods: { - showSavedBar () { - this.isShowConfigUpdated = true + showConfigUpdateBar (msg, status) { + this.configUpdateMsg = msg + this.configUpdateStatus = status clearTimeout(this.showConfigUpdatedTimeout) this.showConfigUpdatedTimeout = setTimeout(() => { - this.isShowConfigUpdated = false + this.configUpdateStatus = '' + this.configUpdateMsg = '' }, 1500) }, + showSavedBar () { + this.showConfigUpdateBar(this.$t('opt:storage_updated'), 'alert-success') + }, + showImportErrorBar () { + this.showConfigUpdateBar(this.$t('opt:storage_import_error'), 'alert-danger') + }, showSocialMedia (flag) { clearTimeout(this.__showSocialMediaTimeout) if (flag) { @@ -138,6 +147,8 @@ export default { if (process.env.NODE_ENV !== 'production' || process.env.DEV_BUILD) { console.warn(err) } + this.showImportErrorBar() + return } const { @@ -156,6 +167,7 @@ export default { if (process.env.DEV_BUILD) { console.error('Wrong import file') } + this.showImportErrorBar() return }
refactor
show error when import failed
b19dab8be49f333cd267307526a441eeff78d5b6
2018-05-11 13:49:08
CRIMX
fix(dicts): remove logging
false
diff --git a/src/components/dictionaries/cobuild/engine.ts b/src/components/dictionaries/cobuild/engine.ts index 55c5d616f..9230e5398 100644 --- a/src/components/dictionaries/cobuild/engine.ts +++ b/src/components/dictionaries/cobuild/engine.ts @@ -79,8 +79,6 @@ function handleDom ( .map(d => DOMPurify.sanitize(d.outerHTML)) } - console.log(doc) - if (result.title && result.defs && result.defs.length > 0) { return { result, audio } as COBUILDSearchResult }
fix
remove logging
da7033cd94e07325ddaf900a4f124e7943cb3265
2019-09-23 20:22:55
crimx
fix(background): show unsupported badge on internal tabs
false
diff --git a/src/background/badge.ts b/src/background/badge.ts index c54aa0928..de597fa04 100644 --- a/src/background/badge.ts +++ b/src/background/badge.ts @@ -17,30 +17,29 @@ export function initBadge() { }) browser.tabs.onActivated.addListener(async ({ tabId }) => { - if (tabId) { - currentTabInfo.tabId = tabId + if (!tabId) { + currentTabInfo.tempDisable = false + currentTabInfo.unsupported = false + updateBadge() + return + } - try { - const response = await message.send<'GET_TAB_BADGE_INFO'>(tabId, { - type: 'GET_TAB_BADGE_INFO' - }) + currentTabInfo.tabId = tabId - // response is empty if tab is just created - if (response) { - currentTabInfo.tempDisable = response.tempDisable - currentTabInfo.unsupported = response.unsupported - updateBadge() - } + const response = await message + .send<'GET_TAB_BADGE_INFO'>(tabId, { + type: 'GET_TAB_BADGE_INFO' + }) + .catch(console.warn) - return - } catch (e) { - console.warn(e) - } + if (response) { + currentTabInfo.tempDisable = response.tempDisable + currentTabInfo.unsupported = response.unsupported + } else { + currentTabInfo.tempDisable = false + currentTabInfo.unsupported = true } - currentTabInfo.tabId = null - currentTabInfo.tempDisable = false - currentTabInfo.unsupported = false updateBadge() }) }
fix
show unsupported badge on internal tabs
1f4b91b9d73e01ec9d8d53a50748fc9b6fe649f0
2018-04-05 20:17:19
CRIMX
style(message): tweak message typings
false
diff --git a/src/_helpers/browser-api.ts b/src/_helpers/browser-api.ts index a06a78fde..c03368b66 100644 --- a/src/_helpers/browser-api.ts +++ b/src/_helpers/browser-api.ts @@ -28,7 +28,7 @@ export type StorageListenerCb = ( ) => void export interface Message { - type: number + type: MsgType [propName: string]: any } @@ -420,7 +420,7 @@ function initServer (): void { const selfMsg = selfMsgTester.exec(message.type) if (selfMsg) { - message.type = Number(selfMsg[1]) + message.type = Number(selfMsg[1]) as MsgType if (sender.tab && sender.tab.id) { return messageSend(sender.tab.id, message) } else { diff --git a/src/selection/index.ts b/src/selection/index.ts index 2f387f7e8..a816504f3 100644 --- a/src/selection/index.ts +++ b/src/selection/index.ts @@ -3,7 +3,7 @@ import { message, storage } from '@/_helpers/browser-api' import { isContainChinese, isContainEnglish } from '@/_helpers/lang-check' import { createAppConfigStream } from '@/_helpers/config-manager' import * as selection from '@/_helpers/selection' -import { MsgType, MsgSALADICT_SELECTION, MsgSELECTION } from '@/typings/message' +import { MsgType, MsgSaladictSelection, MsgSelection } from '@/typings/message' import { Observable } from 'rxjs/Observable' import { of } from 'rxjs/observable/of' @@ -16,7 +16,7 @@ message.addListener(MsgType.__PreloadSelection__, (data, sender, sendResponse) = sendResponse(selection.getSelectionInfo()) }) -window.addEventListener('message', ({ data, source }: { data: MsgSALADICT_SELECTION, source: Window }) => { +window.addEventListener('message', ({ data, source }: { data: MsgSaladictSelection, source: Window }) => { if (data.type !== MsgType.SaladictSelection) { return } // get the souce iframe @@ -120,7 +120,7 @@ function sendMessage ( mouseX: clientX, mouseY: clientY, ctrlKey: isCtrlPressed, - } as MsgSELECTION) + } as MsgSelection) } else { // post to upper frames/window window.parent.postMessage({ @@ -129,7 +129,7 @@ function sendMessage ( mouseX: clientX, mouseY: clientY, ctrlKey: isCtrlPressed, - } as MsgSALADICT_SELECTION, '*') + } as MsgSaladictSelection, '*') } } @@ -147,7 +147,7 @@ function sendEmptyMessage () { trans: '', note: '' } - } as MsgSELECTION) + } as MsgSelection) } /** diff --git a/src/typings/message.ts b/src/typings/message.ts index bbd09e7ff..c2ab319ce 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -1,7 +1,5 @@ import { SelectionInfo } from '@/_helpers/selection' -/* tslint:disable:class-name */ - export enum MsgType { /** Nothing */ Null, @@ -35,7 +33,7 @@ export enum MsgType { __PreloadSelection__, } -export interface MsgSELECTION { +export interface MsgSelection { type: MsgType.Selection selectionInfo: SelectionInfo mouseX?: number @@ -43,7 +41,7 @@ export interface MsgSELECTION { ctrlKey?: boolean } -export interface MsgSALADICT_SELECTION { +export interface MsgSaladictSelection { type: MsgType.SaladictSelection selectionInfo: SelectionInfo mouseX: number
style
tweak message typings
5b215080846d2e1bfed313a183fbf60aacb9402a
2018-05-11 13:54:27
CRIMX
refactor(panel): handle link clicking on panel
false
diff --git a/src/content/components/DictItem/index.tsx b/src/content/components/DictItem/index.tsx index ff24b5772..607d5b1a7 100644 --- a/src/content/components/DictItem/index.tsx +++ b/src/content/components/DictItem/index.tsx @@ -3,17 +3,20 @@ import { DictID } from '@/app-config' import { translate } from 'react-i18next' import { TranslationFunction } from 'i18next' import { Spring } from 'react-spring' -import { openURL } from '@/_helpers/browser-api' +import { message } from '@/_helpers/browser-api' +import { MsgType, MsgOpenUrl } from '@/typings/message' import { SearchStatus } from '@/content/redux/modules/dictionaries' +import { SelectionInfo, getDefaultSelectionInfo } from '@/_helpers/selection' export interface DictItemDispatchers { - readonly searchText: ({ id: DictID }) => any + readonly searchText: (arg: { id: DictID } | { info: SelectionInfo }) => any readonly updateItemHeight: ({ id, height }: { id: DictID, height: number }) => any } export interface DictItemProps extends DictItemDispatchers { readonly id: DictID + readonly text: string readonly dictURL: string readonly fontSize: number readonly preferredHeight: number @@ -126,10 +129,29 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati e.currentTarget.blur() } - openDictURL = e => { - openURL(this.props.dictURL) - e.preventDefault() + handleDictItemClick = (e: React.MouseEvent<HTMLElement>) => { + // use background script to open new page + if (e.target['tagName'] === 'A') { + e.preventDefault() + this.props.searchText({ + info: getDefaultSelectionInfo({ + text: e.target['textContent'] || '', + title: this.props.t('fromSaladict'), + favicon: 'https://raw.githubusercontent.com/crimx/ext-saladict/dev/public/static/icon-16.png' + }), + }) + } + } + + handleDictURLClick = (e: React.MouseEvent<HTMLElement>) => { e.stopPropagation() + e.preventDefault() + message.send<MsgOpenUrl>({ + type: MsgType.OpenURL, + url: this.props.dictURL, + placeholder: true, + text: this.props.text, + }) } componentDidUpdate (prevProps: DictItemProps) { @@ -170,11 +192,11 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati } = this.state return ( - <section className='panel-DictItem'> + <section className='panel-DictItem' onClick={this.handleDictItemClick}> <header className='panel-DictItem_Header' onClick={this.toggleFolding}> <img className='panel-DictItem_Logo' src={require('@/components/dictionaries/' + id + '/favicon.png')} alt='dict logo' /> <h1 className='panel-DictItem_Title'> - <a href={dictURL} onClick={this.openDictURL}>{t(`dict:${id}`)}</a> + <a href={dictURL} onClick={this.handleDictURLClick}>{t(`dict:${id}`)}</a> </h1> { searchStatus === SearchStatus.Searching && <div className='panel-DictItem_Loader'> @@ -198,18 +220,18 @@ export class DictItem extends React.PureComponent<DictItemProps & { t: Translati style={{ fontSize, height }} > <article ref={this.bodyRef} className='panel-DictItem_BodyMesure' style={{ opacity }}> - {searchResult && React.createElement(require('@/components/dictionaries/' + id + '/View.tsx').default, { result: searchResult })} + {searchResult && React.createElement(require('@/components/dictionaries/' + id + '/View.tsx').default, { result: searchResult })} </article> {isUnfold && searchResult && visibleHeight < offsetHeight && - <button + <button className={'panel-DictItem_FoldMask'} - onClick={this.showFull} - > - <svg className='panel-DictItem_FoldMaskArrow' width='15' height='15' viewBox='0 0 59.414 59.414' xmlns='http://www.w3.org/2000/svg'> - <path d='M58 14.146L29.707 42.44 1.414 14.145 0 15.56 29.707 45.27 59.414 15.56' /> - </svg> - </button> - } + onClick={this.showFull} + > + <svg className='panel-DictItem_FoldMaskArrow' width='15' height='15' viewBox='0 0 59.414 59.414' xmlns='http://www.w3.org/2000/svg'> + <path d='M58 14.146L29.707 42.44 1.414 14.145 0 15.56 29.707 45.27 59.414 15.56' /> + </svg> + </button> + } </div> )} </Spring> diff --git a/src/content/components/DictPanel/index.tsx b/src/content/components/DictPanel/index.tsx index 6674dca61..ab5e6c310 100644 --- a/src/content/components/DictPanel/index.tsx +++ b/src/content/components/DictPanel/index.tsx @@ -97,6 +97,7 @@ export default class DictPanel extends React.Component<DictPanelProps> { {config.dicts.selected.map(id => React.createElement(DictItem, { key: id, id, + text: (dictionaries.searchHistory[0] || selection.selectionInfo).text, dictURL: allDictsConfig[id].page, fontSize: config.fontSize, preferredHeight: allDictsConfig[id].preferredHeight,
refactor
handle link clicking on panel
c0cf11e46ee96615e8f7536ff0032dd4b1fd5b02
2018-10-01 18:57:50
CRIMX
feat(dicts): chs to chz
false
diff --git a/src/_helpers/chs-to-chz.ts b/src/_helpers/chs-to-chz.ts index dc32e62e1..ab4017e6e 100644 --- a/src/_helpers/chs-to-chz.ts +++ b/src/_helpers/chs-to-chz.ts @@ -2639,9 +2639,7 @@ const charMap = { } export function chsToChz (text: string): string { - return text.split('') - .map(c => charMap[c] || c) - .join('') + return text.replace(/[\u4e00-\u9fa5]/g, m => charMap[m] || m) } export default chsToChz diff --git a/src/components/__fake__/devDict.tsx b/src/components/__fake__/devDict.tsx index be3a39625..f6bba66cb 100644 --- a/src/components/__fake__/devDict.tsx +++ b/src/components/__fake__/devDict.tsx @@ -3,7 +3,7 @@ */ import React from 'react' import ReactDOM from 'react-dom' -import { appConfigFactory, DictID } from '@/app-config' +import { appConfigFactory, DictID, AppConfigMutable } from '@/app-config' import { I18nextProvider as ProviderI18next, translate } from 'react-i18next' import i18nLoader from '@/_helpers/i18n' @@ -50,7 +50,11 @@ export default function setupEnv ({ dict, style = true, text = 'salad' }: EnvCon require('../dictionaries/' + dict + '/_style.scss') } - search(text, appConfigFactory()) + const config = appConfigFactory() as AppConfigMutable + // config.langCode = 'zh-TW' + const payload = {} + + search(text, config, payload) .then(result => { ReactDOM.render( <ProviderI18next i18n={i18n}> diff --git a/src/components/__fake__/index.tsx b/src/components/__fake__/index.tsx index 21069f9f7..74209a7fd 100644 --- a/src/components/__fake__/index.tsx +++ b/src/components/__fake__/index.tsx @@ -5,9 +5,9 @@ import setupEnv from './devDict' setupEnv({ - dict: 'google', - style: false, - text: 'love', // 当たる 吐く + dict: 'zdic', + style: true, + text: '爱', // 当たる 吐く }) /*-----------------------------------------------*\ diff --git a/src/components/dictionaries/bing/engine.ts b/src/components/dictionaries/bing/engine.ts index a0fe29fd2..4fd6bda7c 100644 --- a/src/components/dictionaries/bing/engine.ts +++ b/src/components/dictionaries/bing/engine.ts @@ -73,17 +73,19 @@ export default function search ( return fetchDirtyDOM(DICT_LINK + encodeURIComponent(text.replace(/\s+/g, ' '))) .catch(handleNetWorkError) .then(doc => { + const isChz = config.langCode === 'zh-TW' + if (doc.querySelector('.client_def_hd_hd')) { - return handleLexResult(doc, bingConfig.options) + return handleLexResult(doc, bingConfig.options, isChz) } if (doc.querySelector('.client_trans_head')) { - return handleMachineResult(doc) + return handleMachineResult(doc, isChz) } if (bingConfig.options.related) { if (doc.querySelector('.client_do_you_mean_title_bar')) { - return handleRelatedResult(doc, bingConfig) + return handleRelatedResult(doc, bingConfig, isChz) } } @@ -94,11 +96,12 @@ export default function search ( function handleLexResult ( doc: Document, options: BingConfig['options'], + isChz: boolean, ): BingSearchResultLex | Promise<BingSearchResultLex> { let searchResult: DictSearchResult<BingResultLex> = { result: { type: 'lex', - title: getText(doc, '.client_def_hd_hd') + title: getText(doc, '.client_def_hd_hd', isChz) } } @@ -136,8 +139,8 @@ function handleLexResult ( let $defs = Array.from($container.querySelectorAll('.client_def_bar')) if ($defs.length > 0) { searchResult.result.cdef = $defs.map(el => ({ - 'pos': getText(el, '.client_def_title_bar'), - 'def': getText(el, '.client_def_list') + 'pos': getText(el, '.client_def_title_bar', isChz), + 'def': getText(el, '.client_def_list', isChz) })) } } @@ -152,33 +155,32 @@ function handleLexResult ( } if (options.sentence > 0) { - let $sens = Array.from(doc.querySelectorAll('.client_sentence_list')) - if ($sens.length > 0) { - searchResult.result.sentences = $sens - .map(el => { - let mp3 = '' - const $audio = el.querySelector('.client_aud_o') - if ($audio) { - mp3 = (($audio.getAttribute('onclick') || '').match(/https.*\.mp3/) || [''])[0] - } - el.querySelectorAll('.client_sen_en_word').forEach($word => { - $word.outerHTML = getText($word) - }) - el.querySelectorAll('.client_sen_cn_word').forEach($word => { - $word.outerHTML = getText($word) - }) - el.querySelectorAll('.client_sentence_search').forEach($word => { - $word.outerHTML = `<span class="dictBing-SentenceItem_HL">${getText($word)}</span>` - }) - return { - en: getInnerHTML(el, '.client_sen_en'), - chs: getInnerHTML(el, '.client_sen_cn'), - source: getText(el, '.client_sentence_list_link'), - mp3 - } - }) - .slice(0, options.sentence) + let $sens = doc.querySelectorAll('.client_sentence_list') + const sentences: typeof searchResult.result.sentences = [] + for (let i = 0; i < $sens.length && sentences.length < options.sentence; i++) { + const el = $sens[i] + let mp3 = '' + const $audio = el.querySelector('.client_aud_o') + if ($audio) { + mp3 = (($audio.getAttribute('onclick') || '').match(/https.*\.mp3/) || [''])[0] + } + el.querySelectorAll('.client_sen_en_word').forEach($word => { + $word.outerHTML = getText($word) + }) + el.querySelectorAll('.client_sen_cn_word').forEach($word => { + $word.outerHTML = getText($word, isChz) + }) + el.querySelectorAll('.client_sentence_search').forEach($word => { + $word.outerHTML = `<span class="dictBing-SentenceItem_HL">${getText($word)}</span>` + }) + sentences.push({ + en: getInnerHTML(el, '.client_sen_en'), + chs: getInnerHTML(el, '.client_sen_cn', isChz), + source: getText(el, '.client_sentence_list_link'), + mp3 + }) } + searchResult.result.sentences = sentences } if (Object.keys(searchResult.result).length > 2) { @@ -189,8 +191,9 @@ function handleLexResult ( function handleMachineResult ( doc: Document, + isChz: boolean, ): BingSearchResultMachine | Promise<BingSearchResultMachine> { - const mt = getText(doc, '.client_sen_cn') + const mt = getText(doc, '.client_sen_cn', isChz) if (mt) { return { @@ -207,11 +210,12 @@ function handleMachineResult ( function handleRelatedResult ( doc: Document, config: BingConfig, + isChz: boolean, ): BingSearchResultRelated | Promise<BingSearchResultRelated> { const searchResult: DictSearchResult<BingResultRelated> = { result: { type: 'related', - title: getText(doc, '.client_do_you_mean_title_bar'), + title: getText(doc, '.client_do_you_mean_title_bar', isChz), defs: [] } } @@ -220,13 +224,13 @@ function handleRelatedResult ( const $defsList = $area.querySelectorAll('.client_do_you_mean_list') if ($defsList.length > 0) { searchResult.result.defs.push({ - title: getText($area, '.client_do_you_mean_title'), + title: getText($area, '.client_do_you_mean_title', isChz), meanings: Array.from($defsList).map($list => { - const word = getText($list, '.client_do_you_mean_list_word') + const word = getText($list, '.client_do_you_mean_list_word', isChz) return { href: config.page.replace('%s', word), word, - def: getText($list, '.client_do_you_mean_list_def') + def: getText($list, '.client_do_you_mean_list_def', isChz) } }) }) diff --git a/src/components/dictionaries/cobuild/engine.ts b/src/components/dictionaries/cobuild/engine.ts index b55f203eb..1c868895e 100644 --- a/src/components/dictionaries/cobuild/engine.ts +++ b/src/components/dictionaries/cobuild/engine.ts @@ -23,23 +23,25 @@ export default function search ( config: AppConfig ): Promise<COBUILDSearchResult> { text = encodeURIComponent(text.replace(/\s+/g, ' ')) + const isChz = config.langCode === 'zh-TW' return fetchDirtyDOM('https://www.iciba.com/' + text) - .then(doc => handleDOM(doc, config.dicts.all.cobuild.options)) + .then(doc => handleDOM(doc, config.dicts.all.cobuild.options, isChz)) .catch(() => { return fetchDirtyDOM('http://www.iciba.com/' + text) .catch(handleNetWorkError) - .then(doc => handleDOM(doc, config.dicts.all.cobuild.options)) + .then(doc => handleDOM(doc, config.dicts.all.cobuild.options, isChz)) }) } function handleDOM ( doc: Document, - options: DictConfigs['cobuild']['options'] + options: DictConfigs['cobuild']['options'], + isChz: boolean, ): COBUILDSearchResult | Promise<COBUILDSearchResult> { const result: Partial<COBUILDResult> = {} const audio: { uk?: string, us?: string } = {} - result.title = getText(doc, '.keyword') + result.title = getText(doc, '.keyword', isChz) if (!result.title) { return handleNoResult() } result.level = getText(doc, '.base-level') @@ -74,7 +76,7 @@ function handleDOM ( if ($article) { result.defs = Array.from($article.querySelectorAll('.prep-order')) .slice(0, options.sentence) - .map(d => getInnerHTML(d)) + .map(d => getInnerHTML(d, isChz)) } if (result.defs && result.defs.length > 0) { diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index 3fa7c1648..b0c012d23 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -2,6 +2,7 @@ import DOMPurify from 'dompurify' import { TranslationFunction } from 'i18next' import { DictID } from '@/app-config' import { SelectionInfo } from '@/_helpers/selection' +import { chsToChz } from '@/_helpers/chs-to-chz' export type HTMLString = string @@ -43,16 +44,40 @@ export interface MachineTranslateResult { } } -export function getText (parent: ParentNode, selector?: string): string { +/** + * Get the textContent of a node or its child. + */ +export function getText (parent: ParentNode, selector?: string, toChz?: boolean): string +export function getText (parent: ParentNode, toChz?: boolean, selector?: string): string +export function getText (parent: ParentNode, ...args): string { + let selector = '' + let toChz = false + for (let i = args.length; i >= 0; i--) { + if (typeof args[i] === 'string') { + selector = args[i] + } else if (typeof args[i] === 'boolean') { + toChz = args[i] + } + } + const child = selector ? parent.querySelector(selector) : parent if (!child) { return '' } - return child['textContent'] || '' + const textContent = child['textContent'] || '' + return toChz ? chsToChz(textContent) : textContent +} + +interface GetHTML { + (parent: ParentNode, selector?: string, toChz?: boolean): HTMLString + (parent: ParentNode, toChz?: boolean, selector?: string): HTMLString } -export function getInnerHTMLThunk ( - host?: string, - DOMPurifyConfig?: DOMPurify.Config, -): (parent: ParentNode, selector?: string) => HTMLString +/** + * Return a function that can get inner HTML from a node or its child. + * + * @param host - repleace the relative href + * @param DOMPurifyConfig - config for DOM Purify + */ +export function getInnerHTMLThunk (host?: string, DOMPurifyConfig?: DOMPurify.Config): GetHTML export function getInnerHTMLThunk (...args) { let host: string = typeof args[0] === 'string' ? args.shift() : '' let DOMPurifyConfig: DOMPurify.Config = Object(args[0]) === args[0] ? args.shift() : { @@ -63,24 +88,44 @@ export function getInnerHTMLThunk (...args) { if (host && !host.endsWith('/')) { host = host + '/' } - return function getInnerHTML (parent: ParentNode, selector?: string): HTMLString { + + const getInnerHTML: GetHTML = (parent: ParentNode, ...args): HTMLString => { + let selector = '' + let toChz = false + for (let i = args.length; i >= 0; i--) { + if (typeof args[i] === 'string') { + selector = args[i] + } else if (typeof args[i] === 'boolean') { + toChz = args[i] + } + } + const child = selector ? parent.querySelector(selector) : parent if (!child) { return '' } - let purifyResult = DOMPurify.sanitize(child['outerHTML'] || '', DOMPurifyConfig) - const content = typeof purifyResult === 'string' + let purifyResult = DOMPurify.sanitize(child['innerHTML'] || '', DOMPurifyConfig) + let content = typeof purifyResult === 'string' ? purifyResult : purifyResult['outerHTML'] ? purifyResult['outerHTML'] : purifyResult.firstElementChild ? purifyResult.firstElementChild.outerHTML : '' - return host + content = host ? content.replace(/href="\/[^/]/g, 'href="' + host) : content + return toChz ? chsToChz(content) : content } + + return getInnerHTML } -export function getOuterHTMLThunk (host?: string, DOMPurifyConfig?: DOMPurify.Config) +/** + * Return a function that can get outer HTML from a node or its child. + * + * @param host - repleace the relative href + * @param DOMPurifyConfig - config for DOM Purify + */ +export function getOuterHTMLThunk (host?: string, DOMPurifyConfig?: DOMPurify.Config): GetHTML export function getOuterHTMLThunk (...args) { let host: string = typeof args[0] === 'string' ? args.shift() : '' let DOMPurifyConfig: DOMPurify.Config = Object(args[0]) === args[0] ? args.shift() : { @@ -91,35 +136,58 @@ export function getOuterHTMLThunk (...args) { if (host && !host.endsWith('/')) { host = host + '/' } - return function getOuterHTML (parent: ParentNode, selector?: string): HTMLString { + + const getOuterHTML: GetHTML = (parent: ParentNode, ...args): HTMLString => { + let selector = '' + let toChz = false + for (let i = args.length; i >= 0; i--) { + if (typeof args[i] === 'string') { + selector = args[i] + } else if (typeof args[i] === 'boolean') { + toChz = args[i] + } + } + const child = selector ? parent.querySelector(selector) : parent if (!child) { return '' } - let purifyResult = DOMPurify.sanitize(child['innerHTML'] || '', DOMPurifyConfig) - const content = typeof purifyResult === 'string' + let purifyResult = DOMPurify.sanitize(child['outerHTML'] || '', DOMPurifyConfig) + let content = typeof purifyResult === 'string' ? purifyResult : purifyResult['outerHTML'] ? purifyResult['outerHTML'] : purifyResult.firstElementChild ? purifyResult.firstElementChild.outerHTML : '' - return host + content = host ? content.replace(/href="\/[^/]/g, 'href="' + host) : content + return toChz ? chsToChz(content) : content } -} -export function decodeHEX (text: string): string { - return text.replace( - /\\x([0-9A-Fa-f]{2})/g, - (m, p1) => String.fromCharCode(parseInt(p1, 16)), - ) + return getOuterHTML } +/** + * Remove a child node from a parent node + */ export function removeChild (parent: ParentNode, selector: string) { const child = parent.querySelector(selector) if (child) { child.remove() } } +/** + * Remove all the matching child nodes from a parent node + */ export function removeChildren (parent: ParentNode, selector: string) { parent.querySelectorAll(selector).forEach(el => el.remove()) } + +/** + * HEX string to normal string + */ +export function decodeHEX (text: string): string { + return text.replace( + /\\x([0-9A-Fa-f]{2})/g, + (m, p1) => String.fromCharCode(parseInt(p1, 16)), + ) +} diff --git a/src/components/dictionaries/youdao/engine.ts b/src/components/dictionaries/youdao/engine.ts index 8b1e90f2d..9f0b4ef99 100644 --- a/src/components/dictionaries/youdao/engine.ts +++ b/src/components/dictionaries/youdao/engine.ts @@ -36,24 +36,26 @@ export default function search ( config: AppConfig, ): Promise<YoudaoSearchResult> { const options = config.dicts.all.youdao.options + const isChz = config.langCode === 'zh-TW' return fetchDirtyDOM('http://www.youdao.com/w/' + encodeURIComponent(text.replace(/\s+/g, ' '))) .catch(handleNetWorkError) - .then(doc => checkResult(doc, options)) + .then(doc => checkResult(doc, options, isChz)) } function checkResult ( doc: Document, options: DictConfigs['youdao']['options'], + isChz: boolean, ): YoudaoSearchResult | Promise<YoudaoSearchResult> { const $typo = doc.querySelector('.error-typo') if (!$typo) { - return handleDOM(doc, options) + return handleDOM(doc, options, isChz) } else if (options.related) { return { result: { type: 'related', - list: getInnerHTML($typo) + list: getInnerHTML($typo, isChz) } } } @@ -63,13 +65,14 @@ function checkResult ( function handleDOM ( doc: Document, options: DictConfigs['youdao']['options'], + isChz: boolean, ): YoudaoSearchResult | Promise<YoudaoSearchResult> { const result: YoudaoResult = { type: 'lex', - title: getText(doc, '.keyword'), + title: getText(doc, '.keyword', isChz), stars: 0, rank: getText(doc, '.rank'), - pattern: getText(doc, '.pattern'), + pattern: getText(doc, '.pattern', isChz), prons: [], } @@ -97,23 +100,23 @@ function handleDOM ( }) if (options.basic) { - result.basic = getInnerHTML(doc, '#phrsListTab .trans-container') + result.basic = getInnerHTML(doc, '#phrsListTab .trans-container', isChz) } if (options.collins) { - result.collins = getInnerHTML(doc, '#collinsResult .ol') + result.collins = getInnerHTML(doc, '#collinsResult .ol', isChz) } if (options.discrimination) { - result.discrimination = getInnerHTML(doc, '#discriminate') + result.discrimination = getInnerHTML(doc, '#discriminate', isChz) } if (options.sentence) { - result.sentence = getInnerHTML(doc, '#authority .ol') + result.sentence = getInnerHTML(doc, '#authority .ol', isChz) } if (options.translation) { - result.translation = getInnerHTML(doc, '#fanyiToggle .trans-container') + result.translation = getInnerHTML(doc, '#fanyiToggle .trans-container', isChz) } if (result.title || result.translation) {
feat
chs to chz
5dc29cd61fc181929804dcf4d1cd4337289a062b
2021-08-09 21:46:12
九庄-庄城祥
fix(hot-words): remove daily hot words of urban dict (#1428)
false
diff --git a/src/components/dictionaries/urban/engine.ts b/src/components/dictionaries/urban/engine.ts index 26eacf75f..b448948b0 100644 --- a/src/components/dictionaries/urban/engine.ts +++ b/src/components/dictionaries/urban/engine.ts @@ -70,6 +70,11 @@ function handleDOM( } for (let i = 0; i < defPanels.length && result.length < resultnum; i++) { + // Remove daily hot words of urban dict. It's fixed in second place at list of defPanels. + if (i === 1) { + continue + } + const $panel = defPanels[i] const resultItem: UrbanResultItem = { title: '' }
fix
remove daily hot words of urban dict (#1428)
c9a8bf7de0c8480407cc72b9ae0ff3f6bcd7783d
2018-10-08 08:50:34
CRIMX
fix(panel): only load on top frame
false
diff --git a/src/content/index.tsx b/src/content/index.tsx index 42eb40221..6329c4c40 100644 --- a/src/content/index.tsx +++ b/src/content/index.tsx @@ -13,34 +13,30 @@ import contentLocles from '@/_locales/content' import profileLocles from '@/_locales/config-profiles' import langcodeLocles from '@/_locales/langcode' -import { message } from '@/_helpers/browser-api' -import { MsgType } from '@/typings/message' - import './content.scss' -// Chrome fails to inject css via manifest if the page is loaded -// as "last opened tabs" when browser opens. -setTimeout(() => message.send({ type: MsgType.RequestCSS }), 1000) - -const i18n = i18nLoader({ - content: contentLocles, - dict: dictsLocles, - profile: profileLocles, - langcode: langcodeLocles, -}, 'content') - -const store = createStore() - -const App = () => ( - <ProviderRedux store={store}> - <ProviderI18next i18n={i18n}> - <div> - <SaladBowlContainer /> - <DictPanelContainer /> - <WordEditorContainer /> - </div> - </ProviderI18next> - </ProviderRedux> -) - -ReactDOM.render(<App />, document.createElement('div')) +// Only load on top frame +if (window.parent === window) { + const i18n = i18nLoader({ + content: contentLocles, + dict: dictsLocles, + profile: profileLocles, + langcode: langcodeLocles, + }, 'content') + + const store = createStore() + + const App = () => ( + <ProviderRedux store={store}> + <ProviderI18next i18n={i18n}> + <div> + <SaladBowlContainer /> + <DictPanelContainer /> + <WordEditorContainer /> + </div> + </ProviderI18next> + </ProviderRedux> + ) + + ReactDOM.render(<App />, document.createElement('div')) +}
fix
only load on top frame
a81a2c562e3c49f83416528d2c106d4ad137ad14
2018-05-19 17:17:36
CRIMX
test(helpers): log useful info
false
diff --git a/src/_helpers/browser-api.ts b/src/_helpers/browser-api.ts index cf148c8bb..b1023e396 100644 --- a/src/_helpers/browser-api.ts +++ b/src/_helpers/browser-api.ts @@ -271,7 +271,7 @@ function messageSend (...args): Promise<any> { : browser.tabs.sendMessage(args[0], args[1]) ).catch(err => { if (process.env.DEV_BUILD) { - console.warn(err) + console.warn(err, ...args) } else if (process.env.NODE_ENV !== 'production') { return Promise.reject(err) as any } @@ -287,7 +287,7 @@ function messageSendSelf<T extends Message, U = any> (message: T): Promise<U> { type: `[[${message.type}]]` })).catch(err => { if (process.env.DEV_BUILD) { - console.warn(err) + console.warn(err, message) } else if (process.env.NODE_ENV !== 'production') { return Promise.reject(err) as any }
test
log useful info
8a6fa290b5fec5830d09670f7f154e505dc4604c
2019-05-25 19:30:55
CRIMX
chore(release): 6.31.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index d8490413d..cfce7c8de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.31.1"></a> +## [6.31.1](https://github.com/crimx/ext-saladict/compare/v6.31.0...v6.31.1) (2019-05-25) + + +### Bug Fixes + +* **dicts:** multiline result ([b17e915](https://github.com/crimx/ext-saladict/commit/b17e915)) + + + <a name="6.31.0"></a> # [6.31.0](https://github.com/crimx/ext-saladict/compare/v6.30.0...v6.31.0) (2019-05-24) diff --git a/package.json b/package.json index 35be1d0ab..b19cac874 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.31.0", + "version": "6.31.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.31.1
f0d203c84f107762d7b753593851d4ffb417c310
2020-06-01 21:35:04
crimx
fix: remove unused
false
diff --git a/src/background/sync-manager/services/shanbay/index.ts b/src/background/sync-manager/services/shanbay/index.ts index 38cf7591a..8fd2eb3b4 100644 --- a/src/background/sync-manager/services/shanbay/index.ts +++ b/src/background/sync-manager/services/shanbay/index.ts @@ -1,5 +1,5 @@ import { AddConfig, SyncService } from '../../interface' -import { getNotebook, setSyncConfig, notifyError } from '../../helpers' +import { getNotebook, notifyError } from '../../helpers' import { openURL } from '@/_helpers/browser-api' import { timer } from '@/_helpers/promise-more' import { isFirefox } from '@/_helpers/saladict'
fix
remove unused
22b0fca606c432c3442cbba7027ee5bb33acce73
2019-05-31 09:49:12
CRIMX
test: update browser-api test
false
diff --git a/test/specs/_helpers/browser-api.spec.ts b/test/specs/_helpers/browser-api.spec.ts index 0457dc91e..49ee48f5c 100644 --- a/test/specs/_helpers/browser-api.spec.ts +++ b/test/specs/_helpers/browser-api.spec.ts @@ -10,8 +10,8 @@ describe('Browser API Wapper', () => { delete window.faviconURL delete window.pageTitle delete window.pageURL - browser.runtime.sendMessage.callsFake(() => Promise.resolve()) - browser.tabs.sendMessage.callsFake(() => Promise.resolve()) + browser.runtime.sendMessage.callsFake(() => Promise.resolve({})) + browser.tabs.sendMessage.callsFake(() => Promise.resolve({})) }) describe('Storage', () => { @@ -310,8 +310,8 @@ describe('Browser API Wapper', () => { browser.runtime.sendMessage.flush() browser.tabs.sendMessage.flush() - browser.runtime.sendMessage.callsFake(() => Promise.resolve()) - browser.tabs.sendMessage.callsFake(() => Promise.resolve()) + browser.runtime.sendMessage.callsFake(() => Promise.resolve({})) + browser.tabs.sendMessage.callsFake(() => Promise.resolve({})) message.send(tabId, msg) expect(browser.tabs.sendMessage.calledWith(tabId, msg)).toBeTruthy() @@ -471,7 +471,8 @@ describe('Browser API Wapper', () => { expect(browser.runtime.onMessage.addListener.calledOnce).toBeTruthy() browser.runtime.onMessage.dispatch({ type: '[[1]]', __pageId__: 1 }, {}) - expect(browser.runtime.sendMessage.calledWith({ type: 1, __pageId__: 1 })).toBeFalsy() + expect(browser.runtime.sendMessage.calledWith({ type: 1, __pageId__: 1 })).toBeTruthy() + browser.runtime.sendMessage.resetHistory() browser.runtime.onMessage.dispatch({ type: '[[1]]', __pageId__: 1 }, { tab }) expect(browser.tabs.sendMessage.calledWith(tab.id, { type: 1, __pageId__: 1 })).toBeTruthy() diff --git a/test/specs/background/initialization.spec.ts b/test/specs/background/initialization.spec.ts index 6e1b8d7f5..d04c4cf91 100644 --- a/test/specs/background/initialization.spec.ts +++ b/test/specs/background/initialization.spec.ts @@ -63,6 +63,11 @@ describe('Initialization', () => { let mergeConfig: jest.Mock let mergeProfile: jest.Mock + beforeAll(() => { + browser.runtime.sendMessage.callsFake(() => Promise.resolve({})) + browser.tabs.sendMessage.callsFake(() => Promise.resolve({})) + }) + beforeEach(() => { browser.flush() jest.resetModules() diff --git a/test/specs/background/server.spec.ts b/test/specs/background/server.spec.ts index 29b935f27..333958269 100644 --- a/test/specs/background/server.spec.ts +++ b/test/specs/background/server.spec.ts @@ -21,6 +21,9 @@ describe('Server', () => { browserWrap.openURL = openURL beforeAll(() => { + browser.runtime.sendMessage.callsFake(() => Promise.resolve({})) + browser.tabs.sendMessage.callsFake(() => Promise.resolve({})) + jest.doMock('@/background/sync-manager', () => {}) jest.doMock('@/_helpers/chs-to-chz', () => { diff --git a/test/specs/components/dictionaries/baidu/engine.spec.ts b/test/specs/components/dictionaries/baidu/engine.spec.ts index 8715067e5..85084b258 100644 --- a/test/specs/components/dictionaries/baidu/engine.spec.ts +++ b/test/specs/components/dictionaries/baidu/engine.spec.ts @@ -10,7 +10,6 @@ describe('Dict/Baidu/engine', () => { return retry(() => search('我爱你', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(searchResult => { - expect(searchResult.audio).toBeUndefined() expect(isContainChinese(searchResult.result.searchText.text)).toBeTruthy() expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() expect(searchResult.result.trans.text).toMatch(/love/) diff --git a/test/specs/components/dictionaries/caiyun/engine.spec.ts b/test/specs/components/dictionaries/caiyun/engine.spec.ts index 93af885f6..24d387a13 100644 --- a/test/specs/components/dictionaries/caiyun/engine.spec.ts +++ b/test/specs/components/dictionaries/caiyun/engine.spec.ts @@ -17,7 +17,6 @@ describe('Dict/Caiyun/engine', () => { .then(searchResult => { expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() expect(searchResult.result.trans.text).toMatch(/love/i) - expect(searchResult.audio).toBeUndefined() expect(searchResult.result.id).toBe('caiyun') expect(searchResult.result.sl).toBe('zh') expect(searchResult.result.tl).toBe('en') diff --git a/test/specs/components/dictionaries/google/engine.spec.ts b/test/specs/components/dictionaries/google/engine.spec.ts index 4b3f9a5de..dd5b8e4cf 100644 --- a/test/specs/components/dictionaries/google/engine.spec.ts +++ b/test/specs/components/dictionaries/google/engine.spec.ts @@ -29,7 +29,6 @@ describe('Dict/Google/engine', () => { } else { expect(searchResult.result.trans.text).toBe('“当你不需要的时候,这就是你所读到的东西,当你无法帮助它时,它将决定你将会是什么。”\n - 奥斯卡·王尔德\n 成功一夜成名需要很长时间。') } - expect(searchResult.audio).toBeUndefined() expect(searchResult.result.id).toBe('google') expect(searchResult.result.sl).toBe('auto') expect(searchResult.result.tl).toBe('en') diff --git a/test/specs/components/dictionaries/sogou/engine.spec.ts b/test/specs/components/dictionaries/sogou/engine.spec.ts index 25f1b47f2..fa8fa4998 100644 --- a/test/specs/components/dictionaries/sogou/engine.spec.ts +++ b/test/specs/components/dictionaries/sogou/engine.spec.ts @@ -17,7 +17,6 @@ describe('Dict/Sogou/engine', () => { .then(searchResult => { expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() expect(searchResult.result.trans.text).toMatch(/love/) - expect(searchResult.audio).toBeUndefined() expect(searchResult.result.id).toBe('sogou') expect(searchResult.result.sl).toBe('auto') expect(searchResult.result.tl).toBe('en') diff --git a/test/specs/components/dictionaries/tencent/engine.spec.ts b/test/specs/components/dictionaries/tencent/engine.spec.ts index 98cc65a3c..a3ba15742 100644 --- a/test/specs/components/dictionaries/tencent/engine.spec.ts +++ b/test/specs/components/dictionaries/tencent/engine.spec.ts @@ -29,7 +29,6 @@ describe('Dict/Tencent/engine', () => { .then(searchResult => { expect(isContainEnglish(searchResult.result.trans.text)).toBeTruthy() expect(searchResult.result.trans.text).toMatch(/love/i) - expect(searchResult.audio).toBeUndefined() expect(searchResult.result.id).toBe('tencent') expect(searchResult.result.sl).toBe('zh') expect(searchResult.result.tl).toBe('en') diff --git a/test/specs/components/dictionaries/zdic/engine.spec.ts b/test/specs/components/dictionaries/zdic/engine.spec.ts index 95a453a23..ced506b6d 100644 --- a/test/specs/components/dictionaries/zdic/engine.spec.ts +++ b/test/specs/components/dictionaries/zdic/engine.spec.ts @@ -1,7 +1,7 @@ import { retry } from '../helpers' import { search } from '@/components/dictionaries/zdic/engine' import { getDefaultConfig } from '@/app-config' -import getDefaultProfile from '@/app-config/profiles' +import getDefaultProfile, { ProfileMutable } from '@/app-config/profiles' import fs from 'fs' import path from 'path' @@ -22,15 +22,17 @@ describe('Dict/Zdic/engine', () => { return retry(() => search('爱', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) .then(({ result, audio }) => { - expect(audio && typeof audio.py).toBe('string') + expect(audio && typeof audio.py).toBeUndefined() expect(result.length).toBeGreaterThan(0) }) ) }) it('should parse phrase result correctly', () => { + const profile = getDefaultProfile() as ProfileMutable + profile.dicts.all.zdic.options.audio = true return retry(() => - search('沙拉', getDefaultConfig(), getDefaultProfile(), { isPDF: false }) + search('沙拉', getDefaultConfig(), profile, { isPDF: false }) .then(({ result, audio }) => { expect(audio && typeof audio.py).toBe('string') expect(result.length).toBeGreaterThan(0)
test
update browser-api test
3825d74ab2aee0888d0d74621ad71204c761de87
2018-08-30 22:05:13
CRIMX
feat(options): add config profile settings
false
diff --git a/src/_locales/options/messages.json b/src/_locales/options/messages.json index 7501db8e7..dd32c789e 100644 --- a/src/_locales/options/messages.json +++ b/src/_locales/options/messages.json @@ -84,6 +84,21 @@ "zh_CN": "修改未保存。确认关闭?", "zh_TW": "修改未保存。確定關閉?" }, + "config_profile": { + "en": "Current Profile", + "zh_CN": "当前模式", + "zh_TW": "当前模式" + }, + "config_profile_description": { + "en": "Settings within different Profiles are independent. You can have different settings for different Profiles.", + "zh_CN": "每个模式下的设置都是独立的,互不干扰。", + "zh_TW": "每個模式下的设置都是獨立的,互不干擾。" + }, + "config_profile_title": { + "en": "Config Profile", + "zh_CN": "情景模式", + "zh_TW": "情景模式" + }, "contact_author": { "en": "Contact Author", "zh_CN": "联系作者", diff --git a/src/options/OptConfigProfile.vue b/src/options/OptConfigProfile.vue new file mode 100644 index 000000000..2994e24f9 --- /dev/null +++ b/src/options/OptConfigProfile.vue @@ -0,0 +1,52 @@ +<template> + <div class="opt-item"><!-- 情景模式 --> + <div class="opt-item__header"> + <strong>{{ $t('opt:config_profile_title') }}</strong> + </div> + <div class="opt-item__body opt-config-profile-body"> + <div class="select-box-container"> + <label class="select-box"> + <select class="form-control" v-model="activeConfigID"> + <option + v-for="id in configProfileIDs" + :value="id" + :selected="id === activeConfigID" + >{{ profileText(id) }}</option> + </select> + </label> + </div> + </div> + <div class="opt-item__description-wrap"> + <p class="opt-item__description" v-html="$t('opt:config_profile_description')"></p> + </div> + </div><!-- 情景模式 --> +</template> + +<script> +export default { + store: ['configProfileIDs', 'configProfiles', 'activeConfigID'], + methods: { + profileText (id) { + const name = this.configProfiles[id].name + + // default names + const match = /^%%_(\S+)_%%$/.exec(name) + if (match) { + return this.$t(`profile:${match[1]}`) || name + } + + return name + } + }, +} +</script> + +<style> +.opt-config-profile-body { + display: flex; + justify-content: center; + border: 1px solid #FDE3A7; + background: #fffec8; +} +</style> + diff --git a/src/options/Options.vue b/src/options/Options.vue index 67218b6f6..34b950ce0 100644 --- a/src/options/Options.vue +++ b/src/options/Options.vue @@ -60,10 +60,11 @@ import { mergeConfig } from '@/app-config/merge-config' import Coffee from './Coffee' import SocialMedia from './SocialMedia' import AlertModal from '@/components/AlertModal' -import { updateActiveConfig } from '@/_helpers/config-manager'; +import { updateActiveConfig, updateActiveConfigID, updateConfigIDList } from '@/_helpers/config-manager' // Auto import option section components const _optNames = [ + 'OptConfigProfile', 'OptAppActive', 'OptPreference', 'OptPrivacy', @@ -89,7 +90,7 @@ const _optComps = _optNames.reduce((o, name) => { export default { name: 'options', - store: ['config', 'newVersionAvailable', 'searchText'], + store: ['activeConfigID', 'configProfileIDs', 'configProfiles', 'config', 'newVersionAvailable', 'searchText'], data () { return { isShowConfigUpdated: false, @@ -99,6 +100,13 @@ export default { } }, methods: { + showSavedBar () { + this.isShowConfigUpdated = true + clearTimeout(this.showConfigUpdatedTimeout) + this.showConfigUpdatedTimeout = setTimeout(() => { + this.isShowConfigUpdated = false + }, 1500) + }, showSocialMedia (flag) { clearTimeout(this.__showSocialMediaTimeout) if (flag) { @@ -123,10 +131,34 @@ export default { const fr = new FileReader() fr.onload= () => { try { - const content = JSON.parse(fr.result) - if (content.version) { - this.$store.config = mergeConfig(content, this.$store.config) + const newStore = JSON.parse(fr.result) + const { + activeConfigID, + configProfileIDs, + configProfiles + } = newStore + + if (!activeConfigID || + typeof activeConfigID !== 'string' || + !Array.isArray(configProfileIDs) || + !configProfileIDs.includes(activeConfigID) || + !configProfiles || + configProfileIDs.some(id => !configProfiles[id] || !configProfiles[id].id) + ) { + if (process.env.DEV_BUILD) { + console.error('Wrong import file') + } + return } + + configProfileIDs.forEach(id => { + configProfiles[id] = mergeConfig(configProfiles[id], appConfigFactory(configProfiles[id].id)) + }) + + this.configProfiles = configProfiles + this.configProfileIDs = configProfileIDs + this.activeConfigID = activeConfigID + this.config = configProfiles[activeConfigID] } catch (err) { if (process.env.NODE_ENV !== 'production' || process.env.DEV_BUILD) { console.warn(err) @@ -138,7 +170,15 @@ export default { handleExport () { browser.runtime.getPlatformInfo() .then(({ os }) => { - let config = JSON.stringify(this.$store.config, null, ' ') + let config = JSON.stringify( + { + activeConfigID: this.activeConfigID, + configProfileIDs: this.configProfileIDs, + configProfiles: this.configProfiles, + }, + null, + ' ' + ) if (os === 'win') { config = config.replace(/\r\n|\n/g, '\r\n') } @@ -160,6 +200,18 @@ export default { } }, watch: { + async activeConfigID (newID) { + await updateActiveConfigID(newID) + this.config = this.configProfiles[newID] + }, + configProfileIDs: { + deep: true, + async handler () { + await updateConfigIDList(this.configProfileIDs) + this.configProfiles = await storage.sync.get(this.configProfileIDs) + this.showSavedBar() + } + }, config: { deep: true, handler () { @@ -186,13 +238,7 @@ export default { config.contextMenus.all.sogou = `https://fanyi.sogou.com/#auto/${sogouLang}/%s` updateActiveConfig(config) - .then(() => { - this.isShowConfigUpdated = true - clearTimeout(this.showConfigUpdatedTimeout) - this.showConfigUpdatedTimeout = setTimeout(() => { - this.isShowConfigUpdated = false - }, 1500) - }) + .then(() => this.showSavedBar()) } }, }, @@ -203,9 +249,11 @@ export default { AlertModal }, mounted () { - Promise.all([getWordOfTheDay(), timer(1000)]) - .then(([word]) => this.searchText(word)) - .catch(() => this.searchText('salad')) + if (process.env.NODE_ENV !== 'development') { + Promise.all([getWordOfTheDay(), timer(1000)]) + .then(([word]) => this.searchText(word)) + .catch(() => this.searchText('salad')) + } } } </script> diff --git a/src/options/index.ts b/src/options/index.ts index 16f1eab8d..7b1140362 100644 --- a/src/options/index.ts +++ b/src/options/index.ts @@ -5,7 +5,6 @@ import App from './Options.vue' import { message, storage } from '@/_helpers/browser-api' import checkUpdate from '@/_helpers/check-update' import { getDefaultSelectionInfo } from '@/_helpers/selection' -import { appConfigFactory, AppConfigMutable } from '@/app-config' import { injectSaladictInternal } from '@/_helpers/injectSaladictInternal' import i18nLoader from '@/_helpers/i18n' @@ -13,14 +12,17 @@ import commonLocles from '@/_locales/common' import dictsLocles from '@/_locales/dicts' import optionsLocles from '@/_locales/options' import contextLocles from '@/_locales/context' +import profileLocles from '@/_locales/config-modes' import { MsgType, MsgSelection } from '@/typings/message' -import { getActiveConfig } from '@/_helpers/config-manager' +import { getActiveConfigID, getConfigIDList, initConfig } from '@/_helpers/config-manager' window.__SALADICT_INTERNAL_PAGE__ = true window.__SALADICT_OPTIONS_PAGE__ = true window.__SALADICT_LAST_SEARCH__ = '' -injectSaladictInternal() +if (process.env.NODE_ENV !== 'development') { + injectSaladictInternal() +} Vue.use(VueStash) Vue.use(VueI18Next) @@ -32,10 +34,12 @@ const i18n = new VueI18Next(i18nLoader({ opt: optionsLocles, dict: dictsLocles, ctx: contextLocles, + profile: profileLocles, }, 'common')) -getActiveConfig() - .then(config => { +Promise.all([getActiveConfigID(), getConfigIDList()]) + .then(async ([activeConfigID, configProfileIDs]) => { + const configProfiles = await storage.sync.get(configProfileIDs) // tslint:disable new Vue({ el: '#app', @@ -43,7 +47,10 @@ getActiveConfig() render: h => h(App), data: { store: { - config: (config || appConfigFactory()) as AppConfigMutable, + config: configProfiles[activeConfigID], + activeConfigID, + configProfileIDs, + configProfiles, unlock: false, newVersionAvailable: false, searchText (text?: string) { @@ -68,17 +75,19 @@ getActiveConfig() } }, created () { - storage.sync.get('unlock') - .then(({ unlock }) => { - this.store.unlock = Boolean(unlock) - storage.sync.addListener('unlock', changes => { - this.store.unlock = changes.unlock.newValue + if (process.env.NODE_ENV !== 'development') { + storage.sync.get('unlock') + .then(({ unlock }) => { + this.store.unlock = Boolean(unlock) + storage.sync.addListener('unlock', changes => { + this.store.unlock = changes.unlock.newValue + }) }) - }) - checkUpdate().then(({ isAvailable }) => { - this.store.newVersionAvailable = isAvailable - }) + checkUpdate().then(({ isAvailable }) => { + this.store.newVersionAvailable = isAvailable + }) + } }, }) })
feat
add config profile settings
f4d812765e73c4671c62f74682d5fe9bf7119572
2019-09-07 23:28:24
crimx
refactor(panel): disable dynamic chunks
false
diff --git a/src/content/components/DictItem/DictItemBody.tsx b/src/content/components/DictItem/DictItemBody.tsx index b9d6d4026..6031733d4 100644 --- a/src/content/components/DictItem/DictItemBody.tsx +++ b/src/content/components/DictItem/DictItemBody.tsx @@ -26,10 +26,13 @@ export const DictItemBody: FC<DictItemBodyProps> = props => { const Dict = useMemo( () => React.lazy<ComponentType<ViewPorps<any>>>(() => + // due to browser extension limitation + // jsonp needs a little hack to work + // disable dynamic chunks for now import( /* webpackInclude: /View\.tsx$/ */ /* webpackChunkName: "dicts/[request]" */ - /* webpackMode: "lazy" */ + /* webpackMode: "eager" */ /* webpackPrefetch: true */ /* webpackPreload: true */ `@/components/dictionaries/${props.dictID}/View.tsx`
refactor
disable dynamic chunks
26e5638b6e6e7a565aa37a355c3e0b9435c87993
2018-05-31 01:28:10
CRIMX
chore(release): 6.0.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index e4bf4d793..0fa91d1c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,221 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +<a name="6.0.0"></a> +# [6.0.0](https://github.com/crimx/ext-saladict/compare/v5.31.7...v6.0.0) (2018-05-30) + + +### Bug Fixes + +* **assets:** assets to static ([8dc5092](https://github.com/crimx/ext-saladict/commit/8dc5092)) +* **background:** content script cannot catch rejections from bg ([29667a5](https://github.com/crimx/ext-saladict/commit/29667a5)) +* **background:** context menus i18n init event ([25dbeef](https://github.com/crimx/ext-saladict/commit/25dbeef)) +* **background:** fix typo ([6d7e25c](https://github.com/crimx/ext-saladict/commit/6d7e25c)) +* **browser:** fix diffrenent removeListener api ([40c4721](https://github.com/crimx/ext-saladict/commit/40c4721)) +* **browser:** fix webext polyfills ([ce11f10](https://github.com/crimx/ext-saladict/commit/ce11f10)) +* **build:** fix fake env ([a1bf3ae](https://github.com/crimx/ext-saladict/commit/a1bf3ae)) +* **components:** better keys for star rates ([6b50750](https://github.com/crimx/ext-saladict/commit/6b50750)) +* **components:** fix Speaker svg dimension ([7d48654](https://github.com/crimx/ext-saladict/commit/7d48654)) +* **components:** fix StarRates style ([1f65959](https://github.com/crimx/ext-saladict/commit/1f65959)) +* **components:** stop setState when unmounted ([0d86b56](https://github.com/crimx/ext-saladict/commit/0d86b56)) +* **config:** more test friendly ([a8e194f](https://github.com/crimx/ext-saladict/commit/a8e194f)) +* **config:** replace the empty sting ([56937a9](https://github.com/crimx/ext-saladict/commit/56937a9)) +* **config:** update config ([635608b](https://github.com/crimx/ext-saladict/commit/635608b)) +* **content:** close on save & filter self ([e92a2f6](https://github.com/crimx/ext-saladict/commit/e92a2f6)) +* **content:** delay injecting css ([a12e070](https://github.com/crimx/ext-saladict/commit/a12e070)) +* **content:** fix close panel when pinned ([4771637](https://github.com/crimx/ext-saladict/commit/4771637)) +* **content:** fix dict item height restore on search ([d5fbc78](https://github.com/crimx/ext-saladict/commit/d5fbc78)) +* **content:** fix firefox !important bug ([73c162a](https://github.com/crimx/ext-saladict/commit/73c162a)) +* **content:** fix firefox svg animation ([76f17cb](https://github.com/crimx/ext-saladict/commit/76f17cb)) +* **content:** fix iframe flickering in Chrome ([9bab2af](https://github.com/crimx/ext-saladict/commit/9bab2af)) +* **content:** fix init position since now use translate ([9ffb1ef](https://github.com/crimx/ext-saladict/commit/9ffb1ef)) +* **content:** fix inject css ([4a82878](https://github.com/crimx/ext-saladict/commit/4a82878)) +* **content:** fix long press ctrl ([e2613fc](https://github.com/crimx/ext-saladict/commit/e2613fc)) +* **content:** fix mask button disabled on fold ([35769e9](https://github.com/crimx/ext-saladict/commit/35769e9)) +* **content:** fix new config refresh bug ([3f44afc](https://github.com/crimx/ext-saladict/commit/3f44afc)) +* **content:** get the first config before listening ([2a6fdf6](https://github.com/crimx/ext-saladict/commit/2a6fdf6)) +* **database:** ignore case ([72f6abe](https://github.com/crimx/ext-saladict/commit/72f6abe)) +* **dicts:** add space after basic ([8bbfb08](https://github.com/crimx/ext-saladict/commit/8bbfb08)) +* **dicts:** bypass etymonline referer checking ([a105eec](https://github.com/crimx/ext-saladict/commit/a105eec)) +* **dicts:** change url ([4772fa9](https://github.com/crimx/ext-saladict/commit/4772fa9)) +* **dicts:** fix bing audio ([b0b641f](https://github.com/crimx/ext-saladict/commit/b0b641f)) +* **dicts:** fix bing audio language detection ([ad577c3](https://github.com/crimx/ext-saladict/commit/ad577c3)) +* **dicts:** fix bing phsym key ([d248a6d](https://github.com/crimx/ext-saladict/commit/d248a6d)) +* **dicts:** fix cambridge link ([68b0a4d](https://github.com/crimx/ext-saladict/commit/68b0a4d)) +* **dicts:** fix COBUILD page link ([7a6f45e](https://github.com/crimx/ext-saladict/commit/7a6f45e)) +* **dicts:** fix img style ([130158a](https://github.com/crimx/ext-saladict/commit/130158a)) +* **dicts:** fix lang code ([b6532cd](https://github.com/crimx/ext-saladict/commit/b6532cd)) +* **dicts:** fix locales ([c39151e](https://github.com/crimx/ext-saladict/commit/c39151e)) +* **dicts:** fix macmillan style ([64aee9b](https://github.com/crimx/ext-saladict/commit/64aee9b)) +* **dicts:** fix p margin ([1561888](https://github.com/crimx/ext-saladict/commit/1561888)) +* **dicts:** get correct href ([cd887e1](https://github.com/crimx/ext-saladict/commit/cd887e1)) +* **dicts:** remove logging ([b19dab8](https://github.com/crimx/ext-saladict/commit/b19dab8)) +* **dicts:** use innerHTML ([dee2afd](https://github.com/crimx/ext-saladict/commit/dee2afd)) +* **dicts:** use lower case ([f66e99a](https://github.com/crimx/ext-saladict/commit/f66e99a)) +* **helper:** rxjs6 fromEventPattern inconsistency ([7c1594d](https://github.com/crimx/ext-saladict/commit/7c1594d)) +* **helpers:** always merge config ([49e01ff](https://github.com/crimx/ext-saladict/commit/49e01ff)) +* **helpers:** fix wrong deletion ([a55c46d](https://github.com/crimx/ext-saladict/commit/a55c46d)) +* **helpers:** get first config ([d8bb3fa](https://github.com/crimx/ext-saladict/commit/d8bb3fa)) +* **helpers:** get initial config ([a221bc7](https://github.com/crimx/ext-saladict/commit/a221bc7)) +* **helpers:** handle annoying msg errors from webext polyfill ([272f1eb](https://github.com/crimx/ext-saladict/commit/272f1eb)) +* **helpers:** props added to window should be optional ([1f12b26](https://github.com/crimx/ext-saladict/commit/1f12b26)) +* **locales:** add from Saladict ([b3b215e](https://github.com/crimx/ext-saladict/commit/b3b215e)) +* **locales:** add missing locales ([fc500ab](https://github.com/crimx/ext-saladict/commit/fc500ab)) +* **locales:** fix browser ui locale naming ([e57e61c](https://github.com/crimx/ext-saladict/commit/e57e61c)) +* **locales:** fix wording ([2d7486e](https://github.com/crimx/ext-saladict/commit/2d7486e)) +* **locales:** use standard lang code ([7a901ec](https://github.com/crimx/ext-saladict/commit/7a901ec)) +* **manifest:** declare wordeditor as web accessible resources ([f9984f5](https://github.com/crimx/ext-saladict/commit/f9984f5)) +* **manifest:** fix manifest ([685ded1](https://github.com/crimx/ext-saladict/commit/685ded1)) +* **menus:** fix rxjs path ([07fc3a9](https://github.com/crimx/ext-saladict/commit/07fc3a9)) +* **options:** add key for v-for ([becfe1d](https://github.com/crimx/ext-saladict/commit/becfe1d)) +* **options:** add max width ([45a1532](https://github.com/crimx/ext-saladict/commit/45a1532)) +* **options:** fix auto search ([cd87b86](https://github.com/crimx/ext-saladict/commit/cd87b86)) +* **options:** fix decimal bug ([835e1ca](https://github.com/crimx/ext-saladict/commit/835e1ca)) +* **options:** fix language code ([d86b5c0](https://github.com/crimx/ext-saladict/commit/d86b5c0)) +* **options:** fix modal scroll bar flickering ([9294de4](https://github.com/crimx/ext-saladict/commit/9294de4)) +* **options:** fix style ([2417ec4](https://github.com/crimx/ext-saladict/commit/2417ec4)) +* **options:** search text when options page is opened ([c359b70](https://github.com/crimx/ext-saladict/commit/c359b70)) +* **package:** update normalize.css to version 8.0.0 ([1dbc42f](https://github.com/crimx/ext-saladict/commit/1dbc42f)) +* **panel:** blur input on drag start ([1759053](https://github.com/crimx/ext-saladict/commit/1759053)) +* **panel:** calculate margin height ([33d1a0a](https://github.com/crimx/ext-saladict/commit/33d1a0a)) +* **panel:** can't unfold a dict when the panel fisrt popup ([41e9498](https://github.com/crimx/ext-saladict/commit/41e9498)) +* **panel:** close panel and word editer on esc ([d133d6e](https://github.com/crimx/ext-saladict/commit/d133d6e)) +* **panel:** debounce animation end ([0cd7e32](https://github.com/crimx/ext-saladict/commit/0cd7e32)) +* **panel:** fix data inconsistency ([1b956aa](https://github.com/crimx/ext-saladict/commit/1b956aa)) +* **panel:** fix firame flickering ([81aebc7](https://github.com/crimx/ext-saladict/commit/81aebc7)) +* **panel:** fix icon bleeds ([9ce942a](https://github.com/crimx/ext-saladict/commit/9ce942a)) +* **panel:** fix panel init height ([799cc4c](https://github.com/crimx/ext-saladict/commit/799cc4c)) +* **panel:** fix panel init on options page ([be4815d](https://github.com/crimx/ext-saladict/commit/be4815d)) +* **panel:** fix preload text ([79732b8](https://github.com/crimx/ext-saladict/commit/79732b8)) +* **panel:** fix search box should follow history ([5cca229](https://github.com/crimx/ext-saladict/commit/5cca229)) +* **panel:** fix styles ([557fdff](https://github.com/crimx/ext-saladict/commit/557fdff)) +* **panel:** height recalculation on show full ([6f0077e](https://github.com/crimx/ext-saladict/commit/6f0077e)) +* **panel:** hide dicts when the selection lang does not match ([b099b5f](https://github.com/crimx/ext-saladict/commit/b099b5f)) +* **panel:** keep dict height unchanged when there is nothing ([47ef11b](https://github.com/crimx/ext-saladict/commit/47ef11b)) +* **panel:** only set immediate to x and y when dragging ([ce0e252](https://github.com/crimx/ext-saladict/commit/ce0e252)) +* **panel:** panel should listen to config on options page ([c751d44](https://github.com/crimx/ext-saladict/commit/c751d44)) +* **panel:** recalc body height when expanding menus ([b6a5714](https://github.com/crimx/ext-saladict/commit/b6a5714)) +* **panel:** record search text on options page ([86eec63](https://github.com/crimx/ext-saladict/commit/86eec63)) +* **panel:** remove animation on popup page ([d298201](https://github.com/crimx/ext-saladict/commit/d298201)) +* **panel:** replace same selection ([5270b8e](https://github.com/crimx/ext-saladict/commit/5270b8e)) +* **panel:** stop following cursor when pinned ([c1d04c1](https://github.com/crimx/ext-saladict/commit/c1d04c1)) +* **panel:** stop searching when selection lang doesn't match ([e506edd](https://github.com/crimx/ext-saladict/commit/e506edd)) +* **panel:** try whatever I can to stop iframe flickering ([949d03e](https://github.com/crimx/ext-saladict/commit/949d03e)) +* **panel:** tweak styles ([14437ef](https://github.com/crimx/ext-saladict/commit/14437ef)) +* **popup:** add to notebook on popup page ([f27dc2f](https://github.com/crimx/ext-saladict/commit/f27dc2f)) +* **popup:** remove white spaces ([c1f22e2](https://github.com/crimx/ext-saladict/commit/c1f22e2)) +* **sass:** add global ([73aaffa](https://github.com/crimx/ext-saladict/commit/73aaffa)) +* **selection:** compress whitespaces in selection ([d43eaa1](https://github.com/crimx/ext-saladict/commit/d43eaa1)) +* **selection:** fix className breaking on svg elements ([f932de3](https://github.com/crimx/ext-saladict/commit/f932de3)) +* **selection:** fix editor detection ([5d5c11a](https://github.com/crimx/ext-saladict/commit/5d5c11a)) +* **selection:** fix ignoring same selection rule for double click ([a587c22](https://github.com/crimx/ext-saladict/commit/a587c22)) +* **selection:** fix undefined detection ([2ad9269](https://github.com/crimx/ext-saladict/commit/2ad9269)) +* **selection:** get target on mousedown ([248578d](https://github.com/crimx/ext-saladict/commit/248578d)) +* **selection:** track same selection ([bbdbcbf](https://github.com/crimx/ext-saladict/commit/bbdbcbf)) +* **static:** fix [#99](https://github.com/crimx/ext-saladict/issues/99) fanyi.youdao bypass http request ([fe84550](https://github.com/crimx/ext-saladict/commit/fe84550)) +* **static:** use browser instead of chrome ([3709e3f](https://github.com/crimx/ext-saladict/commit/3709e3f)) +* **types:** fix typings ([f242fd3](https://github.com/crimx/ext-saladict/commit/f242fd3)) + + +### Features + +* **background:** add auto pronounce ([20a8a33](https://github.com/crimx/ext-saladict/commit/20a8a33)) +* **background:** add search result typing ([76dc07b](https://github.com/crimx/ext-saladict/commit/76dc07b)) +* **background:** context menus with i18n ([9e66f55](https://github.com/crimx/ext-saladict/commit/9e66f55)) +* **background:** timeout searching ([d2bd4d4](https://github.com/crimx/ext-saladict/commit/d2bd4d4)) +* **build:** add devbuild flag ([a5f2af0](https://github.com/crimx/ext-saladict/commit/a5f2af0)) +* **component:** add PortalFrame ([cbe2ddd](https://github.com/crimx/ext-saladict/commit/cbe2ddd)) +* **components:** add word-phrase filter for WordPage ([29cf96a](https://github.com/crimx/ext-saladict/commit/29cf96a)), closes [#103](https://github.com/crimx/ext-saladict/issues/103) +* **components:** add WordPage ([0727db1](https://github.com/crimx/ext-saladict/commit/0727db1)) +* **components:** add wordpage search text ([f4a61fd](https://github.com/crimx/ext-saladict/commit/f4a61fd)) +* **components:** change Speaker to render nothing when no src ([5a50165](https://github.com/crimx/ext-saladict/commit/5a50165)) +* **content:** add animation switch ([8c2939e](https://github.com/crimx/ext-saladict/commit/8c2939e)) +* **content:** add component DictItem ([c600671](https://github.com/crimx/ext-saladict/commit/c600671)) +* **content:** add component SaladBowl ([4200c19](https://github.com/crimx/ext-saladict/commit/4200c19)) +* **content:** add content script entry ([a07519d](https://github.com/crimx/ext-saladict/commit/a07519d)) +* **content:** add dict panel ([9a68f2c](https://github.com/crimx/ext-saladict/commit/9a68f2c)) +* **content:** add i18n for menu bar ([b1a8c9e](https://github.com/crimx/ext-saladict/commit/b1a8c9e)) +* **content:** add menu bar ([bf6b74f](https://github.com/crimx/ext-saladict/commit/bf6b74f)) +* **content:** add menu bar search history ([5f33191](https://github.com/crimx/ext-saladict/commit/5f33191)) +* **content:** add mouseevent on bowl ([44a37bd](https://github.com/crimx/ext-saladict/commit/44a37bd)) +* **content:** add notebook ui logic ([dfd18ac](https://github.com/crimx/ext-saladict/commit/dfd18ac)) +* **content:** add onhold ([6b0844e](https://github.com/crimx/ext-saladict/commit/6b0844e)) +* **content:** add panel closing ([8a20f74](https://github.com/crimx/ext-saladict/commit/8a20f74)) +* **content:** add panel dragging ([9682afc](https://github.com/crimx/ext-saladict/commit/9682afc)) +* **content:** add redux store ([956d2af](https://github.com/crimx/ext-saladict/commit/956d2af)) +* **content:** add related words ([25c6cf7](https://github.com/crimx/ext-saladict/commit/25c6cf7)) +* **content:** add relationships between bowl and panel ([bd24060](https://github.com/crimx/ext-saladict/commit/bd24060)) +* **content:** add saladbow redux container ([6699707](https://github.com/crimx/ext-saladict/commit/6699707)) +* **content:** add search box text update ([2dc6bbc](https://github.com/crimx/ext-saladict/commit/2dc6bbc)) +* **content:** add store dictionaries ([56ce6dc](https://github.com/crimx/ext-saladict/commit/56ce6dc)) +* **content:** add store search text ([ff5c751](https://github.com/crimx/ext-saladict/commit/ff5c751)) +* **content:** add triple ctrl ([69ae1c4](https://github.com/crimx/ext-saladict/commit/69ae1c4)) +* **content:** add word editor ([9415cf0](https://github.com/crimx/ext-saladict/commit/9415cf0)) +* **content:** connect word editor to main component ([38a566c](https://github.com/crimx/ext-saladict/commit/38a566c)) +* **content:** delay mouse on bowl ([0aa1b90](https://github.com/crimx/ext-saladict/commit/0aa1b90)) +* **content:** finish word editor feature ([c77978c](https://github.com/crimx/ext-saladict/commit/c77978c)) +* **content:** intergrate content script into options page ([5c946f1](https://github.com/crimx/ext-saladict/commit/5c946f1)) +* **content:** listen to edit word event ([9188f21](https://github.com/crimx/ext-saladict/commit/9188f21)) +* **content:** move search logic together ([f7a1294](https://github.com/crimx/ext-saladict/commit/f7a1294)) +* **content:** notify parents of hight changing ([1d90c45](https://github.com/crimx/ext-saladict/commit/1d90c45)) +* **content:** setup files ([90c41c3](https://github.com/crimx/ext-saladict/commit/90c41c3)) +* **content:** support important styling ([d150e45](https://github.com/crimx/ext-saladict/commit/d150e45)) +* **content:** supprot max height ([deecdcc](https://github.com/crimx/ext-saladict/commit/deecdcc)) +* **content:** sync panel height with dict item height ([a0d215a](https://github.com/crimx/ext-saladict/commit/a0d215a)) +* **context-menus:** add youglish ([cd39f22](https://github.com/crimx/ext-saladict/commit/cd39f22)) +* **dicts:** add %h hyphen joining ([311ae79](https://github.com/crimx/ext-saladict/commit/311ae79)) +* **dicts:** add cambridge ([be329bd](https://github.com/crimx/ext-saladict/commit/be329bd)) +* **dicts:** add helper ([09f929f](https://github.com/crimx/ext-saladict/commit/09f929f)) +* **dicts:** add helpers ([999362c](https://github.com/crimx/ext-saladict/commit/999362c)) +* **dicts:** add helpers ([428cd08](https://github.com/crimx/ext-saladict/commit/428cd08)) +* **dicts:** add Longman ([90688b6](https://github.com/crimx/ext-saladict/commit/90688b6)) +* **dicts:** add oald ([65b7327](https://github.com/crimx/ext-saladict/commit/65b7327)) +* **dicts:** add webster learners dict ([6e0f1ee](https://github.com/crimx/ext-saladict/commit/6e0f1ee)) +* **dicts:** add youdao ([57ec2b3](https://github.com/crimx/ext-saladict/commit/57ec2b3)) +* **dicts:** fix longman style ([95f172e](https://github.com/crimx/ext-saladict/commit/95f172e)) +* **dicts:** more robust google engine ([701d1d4](https://github.com/crimx/ext-saladict/commit/701d1d4)) +* **helpers:** let openURL support ext based url ([e89eb54](https://github.com/crimx/ext-saladict/commit/e89eb54)) +* **history:** add history entry ([750a51a](https://github.com/crimx/ext-saladict/commit/750a51a)) +* **i18n:** loader accepts callback ([c9077b8](https://github.com/crimx/ext-saladict/commit/c9077b8)) +* **locale:** add back and next ([97d7094](https://github.com/crimx/ext-saladict/commit/97d7094)) +* **locales:** add locales ([10e9a2e](https://github.com/crimx/ext-saladict/commit/10e9a2e)) +* **locales:** update options locales ([5fbc0d1](https://github.com/crimx/ext-saladict/commit/5fbc0d1)) +* **manifest:** support dynamically generated iframes ([94ff5d4](https://github.com/crimx/ext-saladict/commit/94ff5d4)), closes [#106](https://github.com/crimx/ext-saladict/issues/106) +* **notebook:** add notebook entry ([b24c7db](https://github.com/crimx/ext-saladict/commit/b24c7db)) +* **options:** add Acknowledgement ([578891a](https://github.com/crimx/ext-saladict/commit/578891a)) +* **options:** add animation option ([4da7b31](https://github.com/crimx/ext-saladict/commit/4da7b31)) +* **options:** add config import and export ([21d32d1](https://github.com/crimx/ext-saladict/commit/21d32d1)) +* **options:** add displaying supported languages ([6bb345e](https://github.com/crimx/ext-saladict/commit/6bb345e)) +* **options:** smart searching ([451860f](https://github.com/crimx/ext-saladict/commit/451860f)) +* **options:** update options ([817a314](https://github.com/crimx/ext-saladict/commit/817a314)) +* **options:** update options to the latest config ([6901f84](https://github.com/crimx/ext-saladict/commit/6901f84)) +* **panel:** add error boundary for dict ([56e957d](https://github.com/crimx/ext-saladict/commit/56e957d)) +* **panel:** add touch support ([2e856b4](https://github.com/crimx/ext-saladict/commit/2e856b4)) +* **panel:** disable buttons in popup page ([2b80ea4](https://github.com/crimx/ext-saladict/commit/2b80ea4)) +* **panel:** get all dict styles ([a80d0ac](https://github.com/crimx/ext-saladict/commit/a80d0ac)) +* **panel:** integrate panel with popup page ([fddbc38](https://github.com/crimx/ext-saladict/commit/fddbc38)) +* **panel:** open exteranl link ([9aaf70d](https://github.com/crimx/ext-saladict/commit/9aaf70d)) +* **panel:** open url base on lang code ([efb5187](https://github.com/crimx/ext-saladict/commit/efb5187)) +* **panel:** sticky header! pure css! ([e9490ac](https://github.com/crimx/ext-saladict/commit/e9490ac)) +* **popup:** add temporary disabling dict panel ([7710e3c](https://github.com/crimx/ext-saladict/commit/7710e3c)) +* **scss:** add scss globals ([af6e6df](https://github.com/crimx/ext-saladict/commit/af6e6df)) +* **selection:** add double click detection ([1299bec](https://github.com/crimx/ext-saladict/commit/1299bec)) +* **selection:** add get empty selection info ([9d01d9c](https://github.com/crimx/ext-saladict/commit/9d01d9c)) +* **selection:** add noTypeField ([f395f8c](https://github.com/crimx/ext-saladict/commit/f395f8c)) +* **selection:** detect esc key in all frames ([1e6ecc5](https://github.com/crimx/ext-saladict/commit/1e6ecc5)) +* **test:** add snapshot testing ([0be395c](https://github.com/crimx/ext-saladict/commit/0be395c)) +* **wordbook:** add database for words ([46c4327](https://github.com/crimx/ext-saladict/commit/46c4327)) + + +### Performance Improvements + +* **config:** refactor to get ride of cloneDeep ([d986b53](https://github.com/crimx/ext-saladict/commit/d986b53)) +* **helpers:** use DOMParser which is 6 time faster ([157a929](https://github.com/crimx/ext-saladict/commit/157a929)) +* **message:** change message type to typescript enum ([7682a1d](https://github.com/crimx/ext-saladict/commit/7682a1d)) + + + # Changelog [Unreleased]
chore
6.0.0
edb8dc1d432fc21013a35c508e4fbb4e00855334
2020-10-19 22:40:08
crimx
refactor: open dict site on the background if ctrlkey is pressed
false
diff --git a/src/background/server.ts b/src/background/server.ts index 9615acf20..e4398d93c 100644 --- a/src/background/server.ts +++ b/src/background/server.ts @@ -170,12 +170,18 @@ export class BackgroundServer { async openSrcPage({ id, - text + text, + active }: Message<'OPEN_DICT_SRC_PAGE'>['payload']): Promise<void> { const engine = await BackgroundServer.getDictEngine(id) - return openUrl( - await engine.getSrcPage(text, window.appConfig, window.activeProfile) - ) + return openUrl({ + url: await engine.getSrcPage( + text, + window.appConfig, + window.activeProfile + ), + active + }) } async fetchDictResult( diff --git a/src/content/components/DictItem/DictItemHead.tsx b/src/content/components/DictItem/DictItemHead.tsx index a10fa1d99..55f39e316 100644 --- a/src/content/components/DictItem/DictItemHead.tsx +++ b/src/content/components/DictItem/DictItemHead.tsx @@ -9,7 +9,7 @@ export interface DictItemHeadProps { dictID: DictID isSearching: boolean toggleFold: () => void - openDictSrcPage: (id: DictID) => void + openDictSrcPage: (id: DictID, ctrlKey: boolean) => void onCatalogSelect: (item: { key: string; value: string }) => void catalog?: Array< | { @@ -104,7 +104,7 @@ export const DictItemHead: FC<DictItemHeadProps> = props => { onClick={(e: React.MouseEvent<HTMLElement>) => { e.stopPropagation() e.preventDefault() - props.openDictSrcPage(props.dictID) + props.openDictSrcPage(props.dictID, e.ctrlKey) }} > {t(`${props.dictID}.name`)} diff --git a/src/content/components/DictList/DictList.container.tsx b/src/content/components/DictList/DictList.container.tsx index 7660a7fa9..92d59c2e6 100644 --- a/src/content/components/DictList/DictList.container.tsx +++ b/src/content/components/DictList/DictList.container.tsx @@ -57,7 +57,7 @@ const mapDispatchToProps: MapDispatchToPropsFunction< searchText: payload => { dispatch({ type: 'SEARCH_START', payload }) }, - openDictSrcPage: id => { + openDictSrcPage: (id, ctrlKey) => { dispatch((dispatch, getState) => { const { searchHistory } = getState() const word = searchHistory[searchHistory.length - 1] @@ -65,7 +65,8 @@ const mapDispatchToProps: MapDispatchToPropsFunction< type: 'OPEN_DICT_SRC_PAGE', payload: { id, - text: word && word.text ? word.text : '' + text: word && word.text ? word.text : '', + active: !ctrlKey } }) }) diff --git a/src/typings/message.ts b/src/typings/message.ts index bd1c9af24..4bf4e3e0b 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -24,6 +24,8 @@ export type MessageConfig = MessageConfigType<{ payload: { id: DictID text: string + /** Focus on the new page? */ + active?: boolean } }
refactor
open dict site on the background if ctrlkey is pressed
5108b2b1db2bf94ea41c1a02f2ee451404cbf1e7
2019-05-11 16:29:02
CRIMX
docs: see dict typings
false
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index df7e9e9b9..a5f9a4967 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,7 +47,7 @@ Run `yarn zip` to pack zibballs to `./dist/`. ## How to add a dictionary -1. Register the dictionary in [app config](./src/app-config/dicts.ts) so that TypeScript generates the correct typings. Dict ID **MUST** follow alphabetical order. +1. Register the dictionary in [app config](./src/app-config/dicts.ts) so that TypeScript generates the correct typings. Dict ID **MUST** follow alphabetical order. See the top of the file for typings and explanations on each filed. 1. Create a directory at [`src/components/dictionaries/`](./src/components/dictionaries/), with the name of the dict ID. 1. Use any existing dictionary as guidance, e.g. [Bing](./src/components/dictionaries/bing). Copy files to the new directory. 1. Replace the favicon with a new LOGO.
docs
see dict typings
556cc38cb9a090e3fa8436c8732621ae67aef366
2018-03-10 03:20:44
greenkeeper[bot]
chore(package): update webpack-dev-server to version 3.1.1
false
diff --git a/package.json b/package.json index 40024c08d..986ef04a6 100644 --- a/package.json +++ b/package.json @@ -112,7 +112,7 @@ "vue-style-loader": "^4.0.0", "vue-template-compiler": "^2.5.13", "webpack": "4.1.1", - "webpack-dev-server": "3.1.0" + "webpack-dev-server": "3.1.1" }, "jest": { "globals": {
chore
update webpack-dev-server to version 3.1.1
645877d97fb0b3aacb155bad351cd6af74c3c237
2020-05-20 16:08:18
crimx
docs: remove legacy
false
diff --git a/docs/_config.yml b/docs/_config.yml deleted file mode 100644 index c4192631f..000000000 --- a/docs/_config.yml +++ /dev/null @@ -1 +0,0 @@ -theme: jekyll-theme-cayman \ No newline at end of file diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html deleted file mode 100644 index 63f6402ab..000000000 --- a/docs/_layouts/default.html +++ /dev/null @@ -1,11 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <meta charset="UTF-8"> - <title> Saladict 沙拉查词 </title> - <meta http-equiv="refresh" content="0; url=//saladict.crimx.com"> - <link rel="canonical" href="//saladict.crimx.com" /> -</head> -<body> -</body> -</html> diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index f3a90cf61..000000000 --- a/docs/index.md +++ /dev/null @@ -1,107 +0,0 @@ -# Saladict 沙拉查词 6 - -[![Version](https://img.shields.io/github/release/crimx/ext-saladict.svg?label=version)](https://github.com/crimx/ext-saladict/releases) -[![Chrome Web Store](https://img.shields.io/chrome-web-store/users/cdonnmffkdaoajfknoeeecmchibpmkmg.svg?label=Chrome%20users)](https://chrome.google.com/webstore/detail/cdonnmffkdaoajfknoeeecmchibpmkmg?hl=en) -[![Chrome Web Store](https://img.shields.io/chrome-web-store/stars/cdonnmffkdaoajfknoeeecmchibpmkmg.svg?label=Chrome%20stars)](https://chrome.google.com/webstore/detail/cdonnmffkdaoajfknoeeecmchibpmkmg?hl=en) -[![Mozilla Add-on](https://img.shields.io/amo/users/ext-saladict.svg?label=Firefoxe%20users)](https://addons.mozilla.org/firefox/addon/ext-saladict/) -[![Mozilla Add-on](https://img.shields.io/amo/stars/ext-saladict.svg?label=Firefoxe%20stars)](https://addons.mozilla.org/firefox/addon/ext-saladict/) - -[![Build Status](https://travis-ci.org/crimx/ext-saladict.svg)](https://travis-ci.org/crimx/ext-saladict) -[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg?maxAge=2592000)](http://commitizen.github.io/cz-cli/) -[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-brightgreen.svg?maxAge=2592000)](https://conventionalcommits.org) -[![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?maxAge=2592000)](https://standardjs.com/) -[![License](https://img.shields.io/github/license/crimx/ext-saladict.svg?colorB=44cc11?maxAge=2592000)](https://github.com/crimx/ext-saladict/blob/dev/LICENSE) - -Chrome/Firefox 浏览器插件,网页划词翻译。 - -<p align="center"> - <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://raw.githubusercontent.com/wiki/crimx/ext-saladict/images/notebook.gif" /></a> -</p> - -# 下载 - -见[最新发布版本](https://github.com/crimx/ext-saladict/releases)。 -功能一览: - -- 词典丰富 - - [精选大量词典,手工打磨排版,涵盖几乎所有领域](https://github.com/crimx/ext-saladict/wiki#dicts) - - [自动发音,可选不同词典、英美音](https://github.com/crimx/ext-saladict/wiki#autopron) - - [各个词典支持个性化调整](https://github.com/crimx/ext-saladict/wiki#dict-settings) - - [支持整个网页翻译,谷歌和有道分级网页翻译](https://github.com/crimx/ext-saladict/wiki#page-trans) - - [右键支持更多词典页面直达](https://github.com/crimx/ext-saladict/wiki#context-menus) -- 划词方式组合变幻无穷 - - [支持四种划词方式,支持鼠标悬浮取词](https://github.com/crimx/ext-saladict/wiki#mode) - - [查词面板可钉住可拖动可输入](https://github.com/crimx/ext-saladict/wiki#pin) - - [钉住可以配置不同划词方式](https://github.com/crimx/ext-saladict/wiki#mode) -- 情境模式快速切换词典组合 - - [每个情境模式下设置相互独立,快速切换](https://github.com/crimx/ext-saladict/wiki#profile) -- 全键盘操作亦可 - - [支持设置浏览器快捷键](https://github.com/crimx/ext-saladict/wiki#shortcuts) - - [三按 ctrl 打开快捷查词](https://github.com/crimx/ext-saladict/wiki#triple-ctrl) - - [点击地址栏图标快速查词(可设置快捷键)](https://github.com/crimx/ext-saladict/wiki#popup-icon) -- 单词管理 - - [保存上下文以及翻译,准确理解单词](https://github.com/crimx/ext-saladict/wiki#search-history) - - [支持添加生词](https://github.com/crimx/ext-saladict/wiki#search-history) - - [可保存查词历史](https://github.com/crimx/ext-saladict/wiki#search-history) -- [支持黑白名单](https://github.com/crimx/ext-saladict/wiki#black-white-list) -- [支持 PDF 划词](https://github.com/crimx/ext-saladict/wiki#pdf) - - [支持 PDF 黑白名单](https://github.com/crimx/ext-saladict/wiki#black-white-list) -- [可显示当前页面二维码](https://github.com/crimx/ext-saladict/wiki#qrcode) -- [支持本项目](https://github.com/crimx/ext-saladict/wiki#reward) - -# 用户评价 - -> “我用过的最好的查词插件,UI 美观大方,查词功能也很强,还有多词源对照,真的很棒!身边同学已经全被我安利换成这个插件了。就目前来说还是有些难以找到比这款优秀的查词插件。” - -> “非常好用,支持快速查词和划词查询,而且可以添加多个翻译工具。” - -> “查词很快,重要的是多个词典对照,还有 urban dictionary~ 赞” - -> “好喜欢这个软件,界面设计的美观,查询源也丰富” - -> “很满意,速度非常快,该有的都有,简洁全面!” - -> “非常棒啊,就是这种不用别的操作的词典” - -> “哎哟,不错哦!小巧,方便,够用!” - -> “只有一个棒字可以形容!!!” - -更多截图: - -<p align="center"> - <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/youdao-page.gif" /></a> -</p> - -<p align="center"> - <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/screen-notebook.png" /></a> -</p> - -<p align="center"> - <a href="https://github.com/crimx/ext-saladict/releases/" target="_blank"><img src="https://github.com/crimx/ext-saladict/wiki/images/pin.gif" /></a> -</p> - -为什么需要这些权限: - -- 划词需要访问网页数据 -- 快速查词会直接搜索剪贴板文字 - -另外本扩展依赖 Google Analytics 服务作设计改进的参考,可在设置中关闭。 - -# 更新 - -查看[本次更新](https://github.com/crimx/ext-saladict/releases)。 - -查看[更新历史](https://github.com/crimx/ext-saladict/blob/dev/CHANGELOG.md)。 - -# 支持开发 - -## 支持本项目 - -觉得好用的话欢迎帮助更多朋友发现本扩展。请按上方的 <kbd>★Star</kbd> 以及在[谷歌商店](https://chrome.google.com/webstore/detail/cdonnmffkdaoajfknoeeecmchibpmkmg/reviews?hl=en)或[火狐商店](https://addons.mozilla.org/firefox/addon/ext-saladict/)留好评。设计与开发本扩展均由作者一人花费大量私人时间与精力完成,并承诺一直开源免费无广告。欢迎随喜打赏咖啡以支持继续开发,多少不重要,看到大家喜爱的留言便是莫大的鼓励!(山里人最近才发现支付宝红包,欢迎扫码或搜索 `514220641` 一起薅羊毛,拿到的红包亦可用于打赏) - -<div align="center"> - <img height="200" src="https://github.com/crimx/ext-saladict/wiki/images/wechat.png"> - <img height="200" src="https://github.com/crimx/ext-saladict/wiki/images/alipay.png"> - <img height="300" src="https://github.com/crimx/ext-saladict/wiki/images/pocket-money.png"> -</div>
docs
remove legacy
a58dca9319c2020f74b4da39a859efa5b6bb3ecf
2019-08-04 16:32:52
crimx
refactor: always load dict options locales
false
diff --git a/src/_helpers/i18n.ts b/src/_helpers/i18n.ts index 6847e043e..32711a26e 100644 --- a/src/_helpers/i18n.ts +++ b/src/_helpers/i18n.ts @@ -45,6 +45,8 @@ export function i18nLoader() { i18n .use({ type: 'backend', + init: () => {}, + create: () => {}, read: (lang: LangCode, ns: Namespace, cb: Function) => { if (ns === 'dicts') { cb(null, extractDictLocales(lang)) @@ -53,7 +55,7 @@ export function i18nLoader() { cb(null, require(`@/_locales/${lang}/${ns}.ts`).locale) } }) - .use(initReactI18next) + .use(initReactI18next as any) .init({ lng: (/^(en|zh-CN|zh-TW)$/.exec(browser.i18n.getUILanguage()) || [ 'en' @@ -113,16 +115,11 @@ function extractDictLocales(lang: LangCode) { o[dictId] = { name: json.name[lang] } - if (window.__SALADICT_OPTIONS_PAGE__) { - if (json.options) { - o[dictId].options = mapValues( - json.options, - rawLocale => rawLocale[lang] - ) - } - if (json.helps) { - o[dictId].helps = mapValues(json.helps, rawLocale => rawLocale[lang]) - } + if (json.options) { + o[dictId].options = mapValues(json.options, rawLocale => rawLocale[lang]) + } + if (json.helps) { + o[dictId].helps = mapValues(json.helps, rawLocale => rawLocale[lang]) } return o }, {}) diff --git a/src/components/dictionaries/hjdict/View.tsx b/src/components/dictionaries/hjdict/View.tsx index e01a28a8d..20c36eef9 100644 --- a/src/components/dictionaries/hjdict/View.tsx +++ b/src/components/dictionaries/hjdict/View.tsx @@ -1,7 +1,6 @@ import React, { FC } from 'react' import { HjdictResult, HjdictResultLex, HjdictResultRelated } from './engine' import { ViewPorps } from '@/components/dictionaries/helpers' -import { HjdictConfig } from './config' import { useTranslate } from '@/_helpers/i18n' import { StaticSpeakerContainer } from '@/components/Speaker' @@ -52,8 +51,7 @@ const langSelectList = ['w', 'jp/cj', 'jp/jc', 'kr', 'fr', 'de', 'es'] function LangSelect(props: ViewPorps<HjdictResult>) { const { langCode } = props.result - const locales: HjdictConfig = require('./_locales.json') - const { i18n } = useTranslate() + const { t } = useTranslate('dicts') return ( <select @@ -67,7 +65,7 @@ function LangSelect(props: ViewPorps<HjdictResult>) { > {langSelectList.map(lang => ( <option key={lang} value={lang} selected={lang === langCode}> - {locales.options[`chsas-${lang}`][i18n.language]} + {t(`hjdict.options.chsas-${lang}`)} </option> ))} </select>
refactor
always load dict options locales
786b8e5ede0d9e22bf513656f6b8ecd09bc15820
2019-08-03 18:03:49
crimx
refactor: let static speaker container accept div props
false
diff --git a/src/components/Speaker/index.tsx b/src/components/Speaker/index.tsx index 7e4668fac..0d4716a4c 100644 --- a/src/components/Speaker/index.tsx +++ b/src/components/Speaker/index.tsx @@ -1,4 +1,4 @@ -import React, { FC } from 'react' +import React, { FC, ComponentProps } from 'react' import { message } from '@/_helpers/browser-api' import { useObservableCallback, @@ -73,7 +73,9 @@ export default React.memo(Speaker) /** * Listens to HTML injected Speakers in childern */ -export const StaticSpeakerContainer: FC = props => { +export const StaticSpeakerContainer: FC< + Omit<ComponentProps<'div'>, 'onClick'> +> = props => { const [onClick, clickEvent$] = useObservableCallback< any, React.MouseEvent<HTMLDivElement> @@ -111,7 +113,11 @@ export const StaticSpeakerContainer: FC = props => { useSubscription(clickEvent$) - return <div onClick={onClick}>{props.children}</div> + return ( + <div onClick={onClick} {...props}> + {props.children} + </div> + ) } /** @@ -119,7 +125,7 @@ export const StaticSpeakerContainer: FC = props => { */ export const getStaticSpeaker = (src?: string | null) => { if (!src) { - return null + return '' } const $a = document.createElement('a')
refactor
let static speaker container accept div props
60b10da2dbb890270965de7b24a6672ced4ce579
2020-03-10 11:07:17
crimx
fix(dicts): add fallback language for machine translate
false
diff --git a/src/_helpers/i18n.ts b/src/_helpers/i18n.ts index 317373c33..48307b609 100644 --- a/src/_helpers/i18n.ts +++ b/src/_helpers/i18n.ts @@ -107,11 +107,12 @@ function extractDictLocales(lang: LangCode) { const req = require.context( '@/components/dictionaries', true, - /_locales\.json$/ + /_locales\.(json|ts)$/ ) return req.keys().reduce<{ [id: string]: DictLocales }>((o, filename) => { - const json: RawDictLocales = req(filename) - const dictId = /([^/]+)\/_locales\.json$/.exec(filename)![1] + const localeModule = req(filename) + const json: RawDictLocales = localeModule.locales || localeModule + const dictId = /([^/]+)\/_locales\.(json|ts)$/.exec(filename)![1] o[dictId] = { name: json.name[lang] } diff --git a/src/components/dictionaries/baidu/_locales.json b/src/components/dictionaries/baidu/_locales.json deleted file mode 100644 index 3c3c31b1b..000000000 --- a/src/components/dictionaries/baidu/_locales.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": { - "en": "Baidu Translate", - "zh-CN": "百度翻译", - "zh-TW": "百度翻譯" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - } -} diff --git a/src/components/dictionaries/baidu/_locales.ts b/src/components/dictionaries/baidu/_locales.ts new file mode 100644 index 000000000..48498d166 --- /dev/null +++ b/src/components/dictionaries/baidu/_locales.ts @@ -0,0 +1,7 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales({ + en: 'Baidu Translate', + 'zh-CN': '百度翻译', + 'zh-TW': '百度翻譯' +}) diff --git a/src/components/dictionaries/baidu/config.ts b/src/components/dictionaries/baidu/config.ts index e7269770c..f6cd9aa01 100644 --- a/src/components/dictionaries/baidu/config.ts +++ b/src/components/dictionaries/baidu/config.ts @@ -12,6 +12,7 @@ export type BaiduLanguage = Subunion< export type BaiduConfig = DictItem<{ pdfNewline: boolean tl: 'default' | BaiduLanguage + tl2: 'default' | BaiduLanguage }> export default (): BaiduConfig => ({ @@ -46,7 +47,8 @@ export default (): BaiduConfig => ({ options: { /** Keep linebreaks on PDF */ pdfNewline: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { tl: [ @@ -61,6 +63,19 @@ export default (): BaiduConfig => ({ 'es', 'ru', 'nl' + ], + tl2: [ + 'default', + 'zh-CN', + 'zh-TW', + 'en', + 'ja', + 'ko', + 'fr', + 'de', + 'es', + 'ru', + 'nl' ] } }) diff --git a/src/components/dictionaries/caiyun/_locales.json b/src/components/dictionaries/caiyun/_locales.json deleted file mode 100644 index 0a7a5dc2d..000000000 --- a/src/components/dictionaries/caiyun/_locales.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": { - "en": "LingoCloud", - "zh-CN": "彩云小译", - "zh-TW": "彩雲小譯" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - } -} diff --git a/src/components/dictionaries/caiyun/_locales.ts b/src/components/dictionaries/caiyun/_locales.ts new file mode 100644 index 000000000..dfb41c4ae --- /dev/null +++ b/src/components/dictionaries/caiyun/_locales.ts @@ -0,0 +1,7 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales({ + en: 'LingoCloud', + 'zh-CN': '彩云小译', + 'zh-TW': '彩雲小譯' +}) diff --git a/src/components/dictionaries/caiyun/config.ts b/src/components/dictionaries/caiyun/config.ts index 950172ac5..96ae7328e 100644 --- a/src/components/dictionaries/caiyun/config.ts +++ b/src/components/dictionaries/caiyun/config.ts @@ -7,6 +7,7 @@ export type CaiyunLanguage = Subunion<Language, 'zh-CN' | 'en' | 'ja'> export type CaiyunConfig = DictItem<{ pdfNewline: boolean tl: 'default' | CaiyunLanguage + tl2: 'default' | CaiyunLanguage }> export default (): CaiyunConfig => ({ @@ -41,9 +42,11 @@ export default (): CaiyunConfig => ({ options: { /** Keep linebreaks on PDF */ pdfNewline: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { - tl: ['default', 'zh-CN', 'en', 'ja'] + tl: ['default', 'zh-CN', 'en', 'ja'], + tl2: ['default', 'zh-CN', 'en', 'ja'] } }) diff --git a/src/components/dictionaries/dictionaries.stories.tsx b/src/components/dictionaries/dictionaries.stories.tsx index 8d1a7d082..46e45d572 100644 --- a/src/components/dictionaries/dictionaries.stories.tsx +++ b/src/components/dictionaries/dictionaries.stories.tsx @@ -93,9 +93,11 @@ function Dict(props: { mockRequest: MockRequest } - const locales = require('@/components/dictionaries/' + + const localesModule = require('@/components/dictionaries/' + props.dictID + - '/_locales.json') + '/_locales') + + const locales = localesModule.locales || localesModule const { search } = require('@/components/dictionaries/' + props.dictID + diff --git a/src/components/dictionaries/google/_locales.json b/src/components/dictionaries/google/_locales.json deleted file mode 100644 index 2c743c648..000000000 --- a/src/components/dictionaries/google/_locales.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": { - "en": "Google Translation", - "zh-CN": "谷歌翻译", - "zh-TW": "谷歌翻譯" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "cnfirst": { - "en": "Use google.cn first", - "zh-CN": "优先使用 google.cn", - "zh-TW": "優先使用 google.cn" - }, - "concurrent": { - "en": "Search concurrently", - "zh-CN": "并行查询", - "zh-TW": "並行查詢" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - }, - "helps": { - "concurrent": { - "en": "Search .com and .cn concurrently", - "zh-CN": "同时搜索 .com 和 .cn 取最先返回的结果", - "zh-TW": "同時搜尋 .com 和 .cn 取最先返回的結果" - } - } -} diff --git a/src/components/dictionaries/google/_locales.ts b/src/components/dictionaries/google/_locales.ts new file mode 100644 index 000000000..b31e5c9f6 --- /dev/null +++ b/src/components/dictionaries/google/_locales.ts @@ -0,0 +1,28 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales( + { + en: 'Google Translation', + 'zh-CN': '谷歌翻译', + 'zh-TW': '谷歌翻譯' + }, + { + cnfirst: { + en: 'Use google.cn first', + 'zh-CN': '优先使用 google.cn', + 'zh-TW': '優先使用 google.cn' + }, + concurrent: { + en: 'Search concurrently', + 'zh-CN': '并行查询', + 'zh-TW': '並行查詢' + } + }, + { + concurrent: { + en: 'Search .com and .cn concurrently', + 'zh-CN': '同时搜索 .com 和 .cn 取最先返回的结果', + 'zh-TW': '同時搜尋 .com 和 .cn 取最先返回的結果' + } + } +) diff --git a/src/components/dictionaries/google/config.ts b/src/components/dictionaries/google/config.ts index b678f5ae1..6b1d6abe4 100644 --- a/src/components/dictionaries/google/config.ts +++ b/src/components/dictionaries/google/config.ts @@ -12,6 +12,7 @@ export type GoogleConfig = DictItem<{ cnfirst: boolean concurrent: boolean tl: 'default' | GoogleLanguage + tl2: 'default' | GoogleLanguage }> export default (): GoogleConfig => ({ @@ -48,7 +49,8 @@ export default (): GoogleConfig => ({ pdfNewline: false, cnfirst: true, concurrent: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { tl: [ @@ -63,6 +65,19 @@ export default (): GoogleConfig => ({ 'es', 'ru', 'nl' + ], + tl2: [ + 'default', + 'zh-CN', + 'zh-TW', + 'en', + 'ja', + 'ko', + 'fr', + 'de', + 'es', + 'ru', + 'nl' ] } }) diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index a7a47080c..5d57b8811 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -100,8 +100,15 @@ export async function getMTArgs( options, options_sel }: { - options: { tl: 'default' | Language; pdfNewline?: boolean } - options_sel: { tl: ReadonlyArray<'default' | Language> } + options: { + tl: 'default' | Language + tl2: 'default' | Language + pdfNewline?: boolean + } + options_sel: { + tl: ReadonlyArray<'default' | Language> + tl2: ReadonlyArray<'default' | Language> + } }, config: AppConfig, payload: { @@ -133,8 +140,25 @@ export async function getMTArgs( 'en' } - if (sl === tl && !payload.sl) { - sl = 'auto' + if (sl === tl) { + if (!payload.tl) { + if (options.tl2 === 'default') { + if (tl !== config.langCode) { + tl = config.langCode + } else if (tl !== 'en') { + tl = 'en' + } else { + tl = + options_sel.tl.find( + (lang): lang is Language => lang !== 'default' && lang !== tl + ) || 'en' + } + } else { + tl = options.tl2 + } + } else if (!payload.sl) { + sl = 'auto' + } } return { sl, tl, text } diff --git a/src/components/dictionaries/locales.ts b/src/components/dictionaries/locales.ts new file mode 100644 index 000000000..3a643eed0 --- /dev/null +++ b/src/components/dictionaries/locales.ts @@ -0,0 +1,50 @@ +interface LocaleItem { + en: string + 'zh-CN': string + 'zh-TW': string +} + +interface LocaleObject { + [name: string]: LocaleItem +} + +export function getMachineLocales( + name: LocaleItem, + options: LocaleObject = {}, + helps: LocaleObject = {} +): { + name: LocaleItem + options: LocaleObject + helps: LocaleObject +} { + return { + name, + options: { + pdfNewline: { + en: 'Keep linebreaks on PDF', + 'zh-CN': 'PDF 保持换行', + 'zh-TW': 'PDF 保持換行' + }, + tl: { + en: 'Target language', + 'zh-CN': '目标语言', + 'zh-TW': '目標語言' + }, + tl2: { + en: 'Fallback target language', + 'zh-CN': '第二目标语言', + 'zh-TW': '第二目標語言' + }, + ...options + }, + helps: { + tl2: { + en: + 'Fallback when detected languange and target language are identical', + 'zh-CN': '如果检测的源语言与目标语言相同将自动切换第二目标语言', + 'zh-TW': '如果檢測的源語言與目標語言相同將自動切換第二目標語言' + }, + ...helps + } + } +} diff --git a/src/components/dictionaries/sogou/_locales.json b/src/components/dictionaries/sogou/_locales.json deleted file mode 100644 index 947fae27f..000000000 --- a/src/components/dictionaries/sogou/_locales.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": { - "en": "Sogou Translation", - "zh-CN": "搜狗翻译", - "zh-TW": "搜狗翻譯" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - } -} diff --git a/src/components/dictionaries/sogou/_locales.ts b/src/components/dictionaries/sogou/_locales.ts new file mode 100644 index 000000000..546dd7b2f --- /dev/null +++ b/src/components/dictionaries/sogou/_locales.ts @@ -0,0 +1,7 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales({ + en: 'Sogou Translation', + 'zh-CN': '搜狗翻译', + 'zh-TW': '搜狗翻譯' +}) diff --git a/src/components/dictionaries/sogou/config.ts b/src/components/dictionaries/sogou/config.ts index 651534c6f..eb18f52e7 100644 --- a/src/components/dictionaries/sogou/config.ts +++ b/src/components/dictionaries/sogou/config.ts @@ -10,6 +10,7 @@ export type SogouLanguage = Subunion< export type SogouConfig = DictItem<{ pdfNewline: boolean tl: 'default' | SogouLanguage + tl2: 'default' | SogouLanguage }> export default (): SogouConfig => ({ @@ -44,9 +45,11 @@ export default (): SogouConfig => ({ options: { /** Keep linebreaks on PDF */ pdfNewline: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { - tl: ['default', 'zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'] + tl: ['default', 'zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'], + tl2: ['default', 'zh-CN', 'zh-TW', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'] } }) diff --git a/src/components/dictionaries/tencent/_locales.json b/src/components/dictionaries/tencent/_locales.json deleted file mode 100644 index ed47d04d4..000000000 --- a/src/components/dictionaries/tencent/_locales.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": { - "en": "Tencent Translate", - "zh-CN": "腾讯翻译君", - "zh-TW": "騰訊翻譯君" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - } -} diff --git a/src/components/dictionaries/tencent/_locales.ts b/src/components/dictionaries/tencent/_locales.ts new file mode 100644 index 000000000..d1ee25c91 --- /dev/null +++ b/src/components/dictionaries/tencent/_locales.ts @@ -0,0 +1,7 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales({ + en: 'Tencent Translate', + 'zh-CN': '腾讯翻译君', + 'zh-TW': '騰訊翻譯君' +}) diff --git a/src/components/dictionaries/tencent/config.ts b/src/components/dictionaries/tencent/config.ts index 946df9100..c10ddaf84 100644 --- a/src/components/dictionaries/tencent/config.ts +++ b/src/components/dictionaries/tencent/config.ts @@ -10,6 +10,7 @@ export type TencentLanguage = Subunion< export type TencentConfig = DictItem<{ pdfNewline: boolean tl: 'default' | TencentLanguage + tl2: 'default' | TencentLanguage }> export default (): TencentConfig => ({ @@ -44,9 +45,11 @@ export default (): TencentConfig => ({ options: { /** Keep linebreaks on PDF */ pdfNewline: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { - tl: ['default', 'zh-CN', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'] + tl: ['default', 'zh-CN', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'], + tl2: ['default', 'zh-CN', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru'] } }) diff --git a/src/components/dictionaries/youdaotrans/_locales.json b/src/components/dictionaries/youdaotrans/_locales.json deleted file mode 100644 index 20bc83f3e..000000000 --- a/src/components/dictionaries/youdaotrans/_locales.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": { - "en": "Youdao Translate", - "zh-CN": "有道翻译", - "zh-TW": "有道翻譯" - }, - "options": { - "pdfNewline": { - "en": "Keep linebreaks on PDF", - "zh-CN": "PDF 保持换行", - "zh-TW": "PDF 保持換行" - }, - "tl": { - "en": "Target language", - "zh-CN": "目标语言", - "zh-TW": "目標語言" - } - } -} diff --git a/src/components/dictionaries/youdaotrans/_locales.ts b/src/components/dictionaries/youdaotrans/_locales.ts new file mode 100644 index 000000000..0abe1462d --- /dev/null +++ b/src/components/dictionaries/youdaotrans/_locales.ts @@ -0,0 +1,7 @@ +import { getMachineLocales } from '../locales' + +export const locales = getMachineLocales({ + en: 'Youdao Translate', + 'zh-CN': '有道翻译', + 'zh-TW': '有道翻譯' +}) diff --git a/src/components/dictionaries/youdaotrans/config.ts b/src/components/dictionaries/youdaotrans/config.ts index 64a47199f..1d073c400 100644 --- a/src/components/dictionaries/youdaotrans/config.ts +++ b/src/components/dictionaries/youdaotrans/config.ts @@ -10,6 +10,7 @@ export type YoudaotransLanguage = Subunion< export type YoudaotransConfig = DictItem<{ pdfNewline: boolean tl: 'default' | YoudaotransLanguage + tl2: 'default' | YoudaotransLanguage }> export default (): YoudaotransConfig => ({ @@ -44,9 +45,11 @@ export default (): YoudaotransConfig => ({ options: { /** Keep linebreaks on PDF */ pdfNewline: false, - tl: 'default' + tl: 'default', + tl2: 'default' }, options_sel: { - tl: ['default', 'zh-CN', 'en', 'pt', 'es', 'ja', 'ko', 'fr', 'ru'] + tl: ['default', 'zh-CN', 'en', 'pt', 'es', 'ja', 'ko', 'fr', 'ru'], + tl2: ['default', 'zh-CN', 'en', 'pt', 'es', 'ja', 'ko', 'fr', 'ru'] } }) diff --git a/src/options/components/options/Dictionaries/EditDictModal.tsx b/src/options/components/options/Dictionaries/EditDictModal.tsx index 00a12f3c7..b15accfa1 100644 --- a/src/options/components/options/Dictionaries/EditDictModal.tsx +++ b/src/options/components/options/Dictionaries/EditDictModal.tsx @@ -41,8 +41,8 @@ export class EditDictModal extends React.Component<EditDictModalProps> { key={optKey} label={t(`dicts:${dictID}.options.${optKey}`)} help={ - i18n.exists(`dicts:${dictID}.helpers.${optKey}`) - ? t(`dicts:${dictID}.helpers.${optKey}`) + i18n.exists(`dicts:${dictID}.helps.${optKey}`) + ? t(`dicts:${dictID}.helps.${optKey}`) : null } > @@ -63,8 +63,8 @@ export class EditDictModal extends React.Component<EditDictModalProps> { key={optKey} label={t(`dicts:${dictID}.options.${optKey}`)} help={ - i18n.exists(`dicts:${dictID}.helpers.${optKey}`) - ? t(`dicts:${dictID}.helpers.${optKey}`) + i18n.exists(`dicts:${dictID}.helps.${optKey}`) + ? t(`dicts:${dictID}.helps.${optKey}`) : null } > @@ -81,8 +81,8 @@ export class EditDictModal extends React.Component<EditDictModalProps> { key={optKey} label={t(`dicts:${dictID}.options.${optKey}`)} help={ - i18n.exists(`dicts:${dictID}.helpers.${optKey}`) - ? t(`dicts:${dictID}.helpers.${optKey}`) + i18n.exists(`dicts:${dictID}.helps.${optKey}`) + ? t(`dicts:${dictID}.helps.${optKey}`) : null } style={{ marginBottom: 0 }} @@ -93,7 +93,7 @@ export class EditDictModal extends React.Component<EditDictModalProps> { <Radio.Group> {dict['options_sel'][optKey].map(option => ( <Radio value={option} key={option}> - {optKey === 'tl' + {optKey === 'tl' || optKey === 'tl2' ? t(`langcode:${option}`) : t(`dicts:${dictID}.options.${optKey}-${option}`)} </Radio>
fix
add fallback language for machine translate
8b72b69b73d52d5483f0152945e6a39abe21183b
2018-11-03 16:28:35
CRIMX
feat(dicts): add options to remove linebreaks on PDF
false
diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index a7748a70a..1a4d25d4a 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -269,7 +269,9 @@ export function getALlDicts () { * For string, add additional `options_sel` field to list out choices. */ options: { - cnfirst: false, + /** Keep linebreaks on PDF */ + pdfNewline: false, + cnfirst: true, tl: 'default' as 'default' | 'zh-CN' | 'zh-TW' | 'en', }, options_sel: { @@ -580,6 +582,8 @@ export function getALlDicts () { * For string, add additional `options_sel` field to list out choices. */ options: { + /** Keep linebreaks on PDF */ + pdfNewline: false, tl: 'default' as 'default' | 'zh-CHS' | 'zh-CHT' | 'en', }, options_sel: { diff --git a/src/components/dictionaries/google/_locales.json b/src/components/dictionaries/google/_locales.json index a6d7a3a23..3de7ad7a9 100644 --- a/src/components/dictionaries/google/_locales.json +++ b/src/components/dictionaries/google/_locales.json @@ -5,6 +5,11 @@ "zh_TW": "谷歌翻譯" }, "options": { + "pdfNewline": { + "en": "Keep linebreaks on PDF", + "zh_CN": "PDF 保持换行", + "zh_TW": "PDF 保持換行" + }, "cnfirst": { "en": "Use google.cn first", "zh_CN": "优先使用 google.cn", diff --git a/src/components/dictionaries/google/engine.ts b/src/components/dictionaries/google/engine.ts index 78f73a5ac..795464742 100644 --- a/src/components/dictionaries/google/engine.ts +++ b/src/components/dictionaries/google/engine.ts @@ -44,12 +44,17 @@ export const search: SearchFunction<GoogleSearchResult, MachineTranslatePayload> : options.tl ) + const isNoLinebreak = payload.isPDF && !options.pdfNewline + if (isNoLinebreak) { + text = text.replace(/\n/g, ' ') + } + return first([ fetchWithToken('https://translate.google.com', sl, tl, text), fetchWithToken('https://translate.google.cn', sl, tl, text), ]) .catch(() => fetchWithoutToken(sl, tl, text)) - .then(handleText) + .then(r => handleText(r, isNoLinebreak)) } function fetchWithToken (base: string, sl: string, tl: string, text: string): Promise<GoogleRawResult> { @@ -98,7 +103,8 @@ function fetchWithoutToken (sl: string, tl: string, text: string): Promise<Googl } function handleText ( - { json, base, sl, tl, tk1, tk2, text }: GoogleRawResult + { json, base, sl, tl, tk1, tk2, text }: GoogleRawResult, + isNoLinebreak: boolean, ): GoogleSearchResult | Promise<GoogleSearchResult> { const data = JSON.parse(json.replace(/,+/g, ',')) @@ -109,7 +115,7 @@ function handleText ( const transText: string = data[0] .map(item => item[0] && item[0].trim()) .filter(Boolean) - .join('\n') + .join(isNoLinebreak ? ' ' : '\n') if (transText.length > 0) { return { diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index bb15b16a3..df9f32e67 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -5,7 +5,7 @@ import { SelectionInfo } from '@/_helpers/selection' import { chsToChz } from '@/_helpers/chs-to-chz' export interface SearchFunction<Result, Payload = {}> { - (text: string, config: AppConfig, payload: Payload): Promise<Result> + (text: string, config: AppConfig, payload: Readonly<Payload & { isPDF: boolean }>): Promise<Result> } export type HTMLString = string diff --git a/src/components/dictionaries/sogou/_locales.json b/src/components/dictionaries/sogou/_locales.json index e6fd17ac7..fa826c7ab 100644 --- a/src/components/dictionaries/sogou/_locales.json +++ b/src/components/dictionaries/sogou/_locales.json @@ -5,6 +5,11 @@ "zh_TW": "搜狗翻譯" }, "options": { + "pdfNewline": { + "en": "Keep linebreaks on PDF", + "zh_CN": "PDF 保持换行", + "zh_TW": "PDF 保持換行" + }, "tl": { "en": "Target language", "zh_CN": "目标语言", diff --git a/src/components/dictionaries/sogou/engine.ts b/src/components/dictionaries/sogou/engine.ts index 860670e44..c52e370f7 100644 --- a/src/components/dictionaries/sogou/engine.ts +++ b/src/components/dictionaries/sogou/engine.ts @@ -31,6 +31,10 @@ export const search: SearchFunction<SogouSearchResult, MachineTranslatePayload> : options.tl ) + if (payload.isPDF && !options.pdfNewline) { + text = text.replace(/\n/g, ' ') + } + return fetch('https://fanyi.sogou.com/reventondc/translate', { method: 'POST', headers: { diff --git a/src/content/redux/modules/dictionaries.ts b/src/content/redux/modules/dictionaries.ts index f517199ce..c5569727f 100644 --- a/src/content/redux/modules/dictionaries.ts +++ b/src/content/redux/modules/dictionaries.ts @@ -12,6 +12,7 @@ const isSaladictOptionsPage = !!window.__SALADICT_OPTIONS_PAGE__ const isSaladictInternalPage = !!window.__SALADICT_INTERNAL_PAGE__ const isSaladictPopupPage = !!window.__SALADICT_POPUP_PAGE__ const isSaladictQuickSearchPage = !!window.__SALADICT_QUICK_SEARCH_PAGE__ +const isSaladictPDFPage = !!window.__SALADICT_PDF_PAGE__ const isStandalonePage = isSaladictPopupPage || isSaladictQuickSearchPage const isNoSearchHistoryPage = isSaladictInternalPage && !isStandalonePage @@ -376,7 +377,9 @@ export function searchText ( type: MsgType.FetchDictResult, id, text: info.text, - payload: arg && arg.payload, + payload: arg && arg.payload + ? { isPDF: isSaladictPDFPage, ...arg.payload } + : { isPDF: isSaladictPDFPage }, }) } diff --git a/src/content/redux/modules/widget.ts b/src/content/redux/modules/widget.ts index 09d016531..930bf1888 100644 --- a/src/content/redux/modules/widget.ts +++ b/src/content/redux/modules/widget.ts @@ -637,10 +637,12 @@ export function requestFavWord (): DispatcherThunk { if (word.context) { const dicts = ['Google', 'Sogou'] const ids = ['google', 'sogou'] as ['google', 'sogou'] + const payload = { isPDF: isSaladictPDFPage } reflect<MachineTranslateResult>(ids.map(id => message.send<MsgFetchDictResult>({ type: MsgType.FetchDictResult, id, text: word.context, + payload, }))) .then(results => { const trans = results diff --git a/src/typings/global.d.ts b/src/typings/global.d.ts index f287553b6..a40d6fb0c 100644 --- a/src/typings/global.d.ts +++ b/src/typings/global.d.ts @@ -11,6 +11,7 @@ interface Window { __SALADICT_OPTIONS_PAGE__?: boolean __SALADICT_POPUP_PAGE__?: boolean __SALADICT_QUICK_SEARCH_PAGE__?: boolean + __SALADICT_PDF_PAGE__?: boolean // Options page __SALADICT_LAST_SEARCH__?: string
feat
add options to remove linebreaks on PDF
2e83bcf65a4a7b46ab1590dca3d87e29cbd7af31
2018-10-07 14:04:30
CRIMX
refactor(config): update default heights for google and sogou
false
diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index 6d59b557e..a7748a70a 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -252,7 +252,7 @@ export function getALlDicts () { * the preferred height is used and a mask with a view-more button is shown. * Otherwise the content height is used. */ - preferredHeight: 210, + preferredHeight: 320, /** Word count to start searching */ selectionWC: { min: 1, @@ -563,7 +563,7 @@ export function getALlDicts () { * the preferred height is used and a mask with a view-more button is shown. * Otherwise the content height is used. */ - preferredHeight: 210, + preferredHeight: 320, /** Word count to start searching */ selectionWC: { min: 1,
refactor
update default heights for google and sogou
075aef764d8327f78288e0d6d183ae51f9f82f48
2020-06-29 07:40:32
crimx
fix(options): update sortable list on store changes
false
diff --git a/src/options/components/Entries/ContextMenus/index.tsx b/src/options/components/Entries/ContextMenus/index.tsx index f85afb521..ceabd4a0e 100644 --- a/src/options/components/Entries/ContextMenus/index.tsx +++ b/src/options/components/Entries/ContextMenus/index.tsx @@ -1,4 +1,4 @@ -import React, { FC, useState } from 'react' +import React, { FC, useState, useLayoutEffect } from 'react' import { Row, Col } from 'antd' import { isFirefox } from '@/_helpers/saladict' import { useTranslate } from '@/_helpers/i18n' @@ -12,6 +12,7 @@ import { EditModal } from './EditeModal' export const ContextMenus: FC = () => { const { t } = useTranslate(['options', 'common', 'menus']) + const upload = useUpload() const [showAddModal, setShowAddModal] = useState(false) const [editingMenu, setEditingMenu] = useState<string | null>(null) const listLayout = useListLayout() @@ -20,7 +21,9 @@ export const ContextMenus: FC = () => { const [selectedMenus, setSelectedMenus] = useState<ReadonlyArray<string>>( contextMenus.selected ) - const upload = useUpload() + useLayoutEffect(() => { + setSelectedMenus(contextMenus.selected) + }, [contextMenus.selected]) return ( <Row> diff --git a/src/options/components/Entries/Dictionaries/index.tsx b/src/options/components/Entries/Dictionaries/index.tsx index a157161d5..236b157e9 100644 --- a/src/options/components/Entries/Dictionaries/index.tsx +++ b/src/options/components/Entries/Dictionaries/index.tsx @@ -1,4 +1,4 @@ -import React, { FC, useState } from 'react' +import React, { FC, useState, useLayoutEffect } from 'react' import { Tooltip, Row, Col } from 'antd' import { BlockOutlined } from '@ant-design/icons' import { DictID } from '@/app-config' @@ -27,6 +27,9 @@ export const Dictionaries: FC = () => { const [selectedDicts, setSelectedDicts] = useState<ReadonlyArray<DictID>>( dicts.selected ) + useLayoutEffect(() => { + setSelectedDicts(dicts.selected) + }, [dicts.selected]) return ( <Row> diff --git a/src/options/components/Entries/Profiles/index.tsx b/src/options/components/Entries/Profiles/index.tsx index f3e8ba512..eafa5f32d 100644 --- a/src/options/components/Entries/Profiles/index.tsx +++ b/src/options/components/Entries/Profiles/index.tsx @@ -1,4 +1,4 @@ -import React, { FC, useState } from 'react' +import React, { FC, useState, useLayoutEffect } from 'react' import { Row, Col, Modal, notification, message as antdMsg } from 'antd' import { BlockOutlined } from '@ant-design/icons' import { useTranslate, Trans } from '@/_helpers/i18n' @@ -31,10 +31,14 @@ export const Profiles: FC = () => { ) const listLayout = useListLayout() + const storeProfileIDList = useSelector(state => state.profiles) // make a local copy to avoid flickering on drag end const [profileIDList, setProfileIDList] = useState<ProfileIDList>( - useSelector(state => state.profiles) + storeProfileIDList ) + useLayoutEffect(() => { + setProfileIDList(storeProfileIDList) + }, [storeProfileIDList]) const tryTo = async (action: () => any): Promise<void> => { try {
fix
update sortable list on store changes
0b261fd23d9ea9512ffc59d3adafdd14967b69c7
2020-04-23 16:26:56
crimx
fix(panel): mta font size
false
diff --git a/src/content/components/MtaBox/MtaBox.container.tsx b/src/content/components/MtaBox/MtaBox.container.tsx index 15797b227..1bea1d23d 100644 --- a/src/content/components/MtaBox/MtaBox.container.tsx +++ b/src/content/components/MtaBox/MtaBox.container.tsx @@ -22,6 +22,7 @@ const mapStateToProps: MapStateToProps< expand: state.isExpandMtaBox, maxHeight: state.panelMaxHeight, text: state.text, + fontSize: state.config.fontSize, shouldFocus: !state.activeProfile.mtaAutoUnfold || state.isQSPanel || isStandalonePage() }) diff --git a/src/content/components/MtaBox/MtaBox.tsx b/src/content/components/MtaBox/MtaBox.tsx index 7b44df167..542b28004 100644 --- a/src/content/components/MtaBox/MtaBox.tsx +++ b/src/content/components/MtaBox/MtaBox.tsx @@ -9,6 +9,7 @@ export interface MtaBoxProps { expand: boolean maxHeight: number text: string + fontSize: number shouldFocus: boolean searchText: (text: string) => any onInput: (text: string) => void @@ -79,7 +80,7 @@ export const MtaBox: FC<MtaBoxProps> = props => { autoFocus inputRef={textareaRef} className="mtaBox-TextArea" - style={{ maxHeight: props.maxHeight }} + style={{ maxHeight: props.maxHeight, fontSize: props.fontSize }} value={props.text} onChange={e => { isTypedRef.current = true
fix
mta font size
7c1594db261e70d8a929f5bd9129d9f0fba107b5
2018-04-27 12:27:59
CRIMX
fix(helper): rxjs6 fromEventPattern inconsistency
false
diff --git a/src/_helpers/browser-api.ts b/src/_helpers/browser-api.ts index 17917ddf4..8c9a4f87f 100644 --- a/src/_helpers/browser-api.ts +++ b/src/_helpers/browser-api.ts @@ -264,7 +264,7 @@ function storageCreateStream (this: StorageThisThree, key: string) { handler => this.addListener(key, handler as StorageListenerCb), handler => this.removeListener(key, handler as StorageListenerCb), ).pipe( - map(change => change[key]) + map(args => Array.isArray(args) ? args[0][key] : args[key]) ) } @@ -350,17 +350,17 @@ function messageRemoveListener (this: MessageThis, ...args): void { function messageCreateStream<T = any> (messageType?: Message['type']): Observable<T> function messageCreateStream (this: MessageThis, messageType = MsgType.Null) { - if (messageType !== MsgType.Null) { - return fromEventPattern( + const pattern$ = messageType !== MsgType.Null + ? fromEventPattern( handler => this.addListener(messageType, handler as onMessageEvent), handler => this.removeListener(messageType, handler as onMessageEvent), ) - } else { - return fromEventPattern( + : fromEventPattern( handler => this.addListener(handler as onMessageEvent), handler => this.removeListener(handler as onMessageEvent), ) - } + + return pattern$.pipe(map(args => Array.isArray(args) ? args[0] : args)) } /** diff --git a/test/specs/_helpers/browser-api.spec.ts b/test/specs/_helpers/browser-api.spec.ts index 873d1bbbb..374484f6c 100644 --- a/test/specs/_helpers/browser-api.spec.ts +++ b/test/specs/_helpers/browser-api.spec.ts @@ -570,7 +570,7 @@ describe('Browser API Wapper', () => { expect(nextStub).toHaveBeenCalledTimes(1) expect(errorStub).toHaveBeenCalledTimes(0) expect(completeStub).toHaveBeenCalledTimes(1) - expect(nextStub).toBeCalledWith({ type: 1, __pageId__: window.pageId }) + expect(nextStub.mock.calls[0][0]).toEqual({ type: 1, __pageId__: window.pageId }) }) }) })
fix
rxjs6 fromEventPattern inconsistency
5f887c7bc700b1d4a9ef7f734d1245292597c85b
2020-04-19 21:01:05
crimx
refactor(options): responsive form and list layout
false
diff --git a/src/options/components/BtnPreview/index.tsx b/src/options/components/BtnPreview/index.tsx index cc17fceb6..5b3583b6a 100644 --- a/src/options/components/BtnPreview/index.tsx +++ b/src/options/components/BtnPreview/index.tsx @@ -1,19 +1,20 @@ import React, { FC } from 'react' import { Dispatch } from 'redux' -import { useSelector, useDispatch } from 'react-redux' +import { useDispatch } from 'react-redux' import { CSSTransition } from 'react-transition-group' import { Button } from 'antd' +import { StoreAction } from '@/content/redux/modules' import { useTranslate } from '@/_helpers/i18n' import { newWord } from '@/_helpers/record-manager' import { getWordOfTheDay } from '@/_helpers/wordoftheday' -import { StoreState, StoreAction } from '@/content/redux/modules' +import { useIsShowDictPanel } from '@/options/helpers/panel-store' import { PreviewIcon } from './PreviewIcon' import './_style.scss' export const BtnPreview: FC = () => { const { t } = useTranslate('options') - const show = !useSelector(pickIsShowDictPanel) + const show = !useIsShowDictPanel() const dispatch = useDispatch<Dispatch<StoreAction>>() return ( @@ -51,7 +52,3 @@ export const BtnPreview: FC = () => { } export const BtnPreviewMemo = React.memo(BtnPreview) - -function pickIsShowDictPanel(state: StoreState): boolean { - return state.isShowDictPanel -} diff --git a/src/options/components/Entries/ContextMenus/index.tsx b/src/options/components/Entries/ContextMenus/index.tsx index cec5e7737..817c3f664 100644 --- a/src/options/components/Entries/ContextMenus/index.tsx +++ b/src/options/components/Entries/ContextMenus/index.tsx @@ -7,6 +7,7 @@ import { GlobalsContext, config$$ } from '@/options/data' import { SortableList, arrayMove } from '@/options/components/SortableList' import { getConfigPath } from '@/options/helpers/path-joiner' import { upload } from '@/options/helpers/upload' +import { useListLayout } from '@/options/helpers/layout' import { AddModal } from './AddModal' import { EditModal } from './EditeModal' @@ -15,6 +16,7 @@ export const ContextMenus: FC = () => { const globals = useContext(GlobalsContext) const [showAddModal, setShowAddModal] = useState(false) const [editingMenu, setEditingMenu] = useState<string | null>(null) + const listLayout = useListLayout() // make a local copy to avoid flickering on drag end const [selectedMenus, setSelectedMenus] = useState<ReadonlyArray<string>>([]) @@ -24,7 +26,7 @@ export const ContextMenus: FC = () => { return ( <Row> - <Col span={14}> + <Col {...listLayout}> <SortableList title={t('nav.ContextMenus')} description={<p>{t('config.opt.contextMenus_description')}</p>} diff --git a/src/options/components/Entries/Dictionaries/index.tsx b/src/options/components/Entries/Dictionaries/index.tsx index 1cee172b0..1789aa79d 100644 --- a/src/options/components/Entries/Dictionaries/index.tsx +++ b/src/options/components/Entries/Dictionaries/index.tsx @@ -9,6 +9,7 @@ import { SortableList, arrayMove } from '@/options/components/SortableList' import { SaladictModalForm } from '@/options/components/SaladictModalForm' import { getProfilePath } from '@/options/helpers/path-joiner' import { upload } from '@/options/helpers/upload' +import { useListLayout } from '@/options/helpers/layout' import { DictTitleMemo } from './DictTitle' import { EditModal } from './EditModal' import { AllDicts } from './AllDicts' @@ -18,6 +19,7 @@ export const Dictionaries: FC = () => { const globals = useContext(GlobalsContext) const [editingDict, setEditingDict] = useState<DictID | null>(null) const [showAddModal, setShowAddModal] = useState(false) + const listLayout = useListLayout() // make a local copy to avoid flickering on drag end const [selectedDicts, setSelectedDicts] = useState<ReadonlyArray<DictID>>([]) @@ -27,7 +29,7 @@ export const Dictionaries: FC = () => { return ( <Row> - <Col span={14}> + <Col {...listLayout}> <SortableList title={ <Tooltip diff --git a/src/options/components/Entries/Profiles/index.tsx b/src/options/components/Entries/Profiles/index.tsx index b326c5188..4caa90cb4 100644 --- a/src/options/components/Entries/Profiles/index.tsx +++ b/src/options/components/Entries/Profiles/index.tsx @@ -1,9 +1,13 @@ import React, { FC, useState } from 'react' import { Row, Col, Modal, notification, message as antdMsg } from 'antd' -import { SortableList, arrayMove } from '../../SortableList' -import { useTranslate, Trans } from '@/_helpers/i18n' +import { BlockOutlined } from '@ant-design/icons' import { useObservableGetState, useSubscription } from 'observable-hooks' -import { profile$$, profileIDList$$ } from '@/options/data' +import { useTranslate, Trans } from '@/_helpers/i18n' +import { + ProfileID, + ProfileIDList, + getDefaultProfileID +} from '@/app-config/profiles' import { getProfileName, updateActiveProfileID, @@ -11,14 +15,11 @@ import { updateProfileIDList, addProfile } from '@/_helpers/profile-manager' -import { - ProfileID, - ProfileIDList, - getDefaultProfileID -} from '@/app-config/profiles' import { useFixedCallback } from '@/_helpers/hooks' +import { SortableList, arrayMove } from '@/options/components/SortableList' +import { profile$$, profileIDList$$ } from '@/options/data' +import { useListLayout } from '@/options/helpers/layout' import { EditNameModal } from './EditNameModal' -import { BlockOutlined } from '@ant-design/icons' export const Profiles: FC = () => { const { t } = useTranslate('options') @@ -28,6 +29,7 @@ export const Profiles: FC = () => { const [editingProfileID, setEditingProfileID] = useState<ProfileID | null>( null ) + const listLayout = useListLayout() // make a local copy to avoid flickering on drag end const [profileIDList, setProfileIDList] = useState<ProfileIDList>([]) @@ -66,7 +68,7 @@ export const Profiles: FC = () => { return ( <Row> - <Col span={12}> + <Col {...listLayout}> <SortableList title={t('nav.Profiles')} description={ diff --git a/src/options/components/SaladictForm/index.tsx b/src/options/components/SaladictForm/index.tsx index 1ef8dd32f..cd5d915c6 100644 --- a/src/options/components/SaladictForm/index.tsx +++ b/src/options/components/SaladictForm/index.tsx @@ -12,7 +12,10 @@ import { useTranslate } from '@/_helpers/i18n' import { isFirefox } from '@/_helpers/saladict' import { openURL } from '@/_helpers/browser-api' import { GlobalsContext } from '@/options/data' -import { formItemLayout, formItemFooterLayout } from '@/options/helpers/layout' +import { + useFormItemLayout, + formItemFooterLayout +} from '@/options/helpers/layout' import { uploadResult$$, upload } from '@/options/helpers/upload' import shallowEqual from 'shallowequal' @@ -53,6 +56,7 @@ export const SaladictForm = React.forwardRef( const { loading: uploading } = useObservableState(uploadResult$$, { loading: false }) + const formItemLayout = useFormItemLayout() function extractInitial( items: SaladictFormItem[], diff --git a/src/options/helpers/layout.ts b/src/options/helpers/layout.ts index a34d212da..a83db3fe7 100644 --- a/src/options/helpers/layout.ts +++ b/src/options/helpers/layout.ts @@ -1,4 +1,15 @@ -export const formItemLayout = { +import { useIsShowDictPanel } from './panel-store' + +export const formItemFooterLayout = { + wrapperCol: { offset: 6, span: 18 } +} as const + +export const formItemModalLayout = { + labelCol: { span: 6 }, + wrapperCol: { span: 18 } +} as const + +const formItemLayoutWithDictPanel = { labelCol: { xs: { span: 9 }, sm: { span: 9 }, @@ -11,16 +22,35 @@ export const formItemLayout = { } } as const -export const formItemFooterLayout = { - wrapperCol: { offset: 6, span: 18 } +const formItemLayoutWithoutDictPanel = { + labelCol: { + xs: { span: 9 }, + sm: { span: 9 }, + lg: { span: 7 } + }, + wrapperCol: { + xs: { span: 15 }, + sm: { span: 15 }, + lg: { span: 9 } + } } as const -export const formSubItemLayout = { - labelCol: { span: 7 }, - wrapperCol: { span: 17 } +export const useFormItemLayout = () => + useIsShowDictPanel() + ? formItemLayoutWithDictPanel + : formItemLayoutWithoutDictPanel + +const listLayoutWithPanel = { + xs: { span: 24 }, + sm: { span: 24 }, + lg: { span: 12 } } as const -export const formItemModalLayout = { - labelCol: { span: 6 }, - wrapperCol: { span: 18 } +const listLayoutWithoutPanel = { + xs: { span: 24 }, + sm: { span: 24 }, + lg: { span: 14, offset: 2 } } as const + +export const useListLayout = () => + useIsShowDictPanel() ? listLayoutWithPanel : listLayoutWithoutPanel diff --git a/src/options/helpers/panel-store.ts b/src/options/helpers/panel-store.ts new file mode 100644 index 000000000..ad1ed3012 --- /dev/null +++ b/src/options/helpers/panel-store.ts @@ -0,0 +1,7 @@ +import { useSelector } from 'react-redux' +import { StoreState } from '@/content/redux/modules' + +const pickIsShowDictPanel = (state: StoreState): boolean => + state.isShowDictPanel + +export const useIsShowDictPanel = () => useSelector(pickIsShowDictPanel)
refactor
responsive form and list layout
16e78d59d17af7eea537c8f33c2ac3f130add02a
2021-05-27 20:40:21
crimx
refactor: clean code
false
diff --git a/src/selection/helper.ts b/src/selection/helper.ts index dbff13dd..1f5c2157 100644 --- a/src/selection/helper.ts +++ b/src/selection/helper.ts @@ -44,12 +44,8 @@ export function isTypeField(element: Node | EventTarget | null): boolean { return false } - for (let el: Element | null = element as Element; el; el = el.parentElement) { - if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') { - return true - } - - if (el instanceof HTMLElement && el.isContentEditable) { + for (let el: HTMLElement | null = element as HTMLElement; el; el = el.parentElement) { + if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable) { return true }
refactor
clean code
de42e3bfa102059203cf8581b038d9fc7916709f
2018-10-29 16:47:12
CRIMX
refactor: update typings
false
diff --git a/src/_helpers/selection.ts b/src/_helpers/selection.ts index ef208cae7..a3abc6d65 100644 --- a/src/_helpers/selection.ts +++ b/src/_helpers/selection.ts @@ -21,9 +21,11 @@ export function getSelectionText (win = window): string { // Firefox fix const activeElement = win.document.activeElement - if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') { - const el = activeElement as HTMLInputElement | HTMLTextAreaElement - return el.value.slice(el.selectionStart || 0, el.selectionEnd || 0) + if (activeElement) { + if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') { + const el = activeElement as HTMLInputElement | HTMLTextAreaElement + return el.value.slice(el.selectionStart || 0, el.selectionEnd || 0) + } } return '' diff --git a/src/typings/message.ts b/src/typings/message.ts index 3f2b668d9..94b3ba426 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -160,7 +160,7 @@ export interface MsgGetWords { readonly area: DBArea readonly itemsPerPage?: number readonly pageNum?: number - readonly filters: { [field: string]: string[] | undefined } + readonly filters?: { [field: string]: string[] | undefined } readonly sortField?: string readonly sortOrder?: 'ascend' | 'descend' | false readonly searchText?: string
refactor
update typings
f1bd672159b643721b8a74ed11338336e93bbfcd
2018-06-07 08:04:44
CRIMX
fix(dicts): hide sharing
false
diff --git a/src/components/dictionaries/cambridge/_style.scss b/src/components/dictionaries/cambridge/_style.scss index ccfc227df..44f0011a9 100644 --- a/src/components/dictionaries/cambridge/_style.scss +++ b/src/components/dictionaries/cambridge/_style.scss @@ -387,12 +387,6 @@ color: #292929; } - .di .share { - position: absolute; - top: -10px; - right: -1em; - } - .di .pos-head .pos-info { margin: 0 0 20px; } @@ -1363,7 +1357,7 @@ border-bottom: 0; } - .circle.bg--more.open .fcdo-minus,.circle.bg--more .fcdo-plus,.share .bg--gp,.share .bg--di,.share .bg--su,.share .bg--tu,.share .bg--re,.share .bg--def,.translator_layout .share .circle,.share .bg--more { + .circle.bg--more.open .fcdo-minus,.circle.bg--more .bg--more { display: inline-block; } @@ -2208,4 +2202,8 @@ color: inherit; } } + + .share { + display: none !important; + } }
fix
hide sharing
8a5a3f49206036c2e01f46d4eafa641c4c744e81
2018-06-05 18:28:48
CRIMX
refactor(content): change link color
false
diff --git a/src/content/components/WordEditor/_style.scss b/src/content/components/WordEditor/_style.scss index 6ecdab277..f30615c8d 100644 --- a/src/content/components/WordEditor/_style.scss +++ b/src/content/components/WordEditor/_style.scss @@ -121,7 +121,7 @@ textarea { a { text-decoration: none; - color: #999; + color: #1890ff; } }
refactor
change link color
5d5c11a108b1101e06c9c71c2f998a552031499b
2018-05-24 19:27:12
CRIMX
fix(selection): fix editor detection
false
diff --git a/src/selection/index.ts b/src/selection/index.ts index 25eaab8b0..bde7c5ead 100644 --- a/src/selection/index.ts +++ b/src/selection/index.ts @@ -244,12 +244,13 @@ function isTypeField (traget: EventTarget | null): boolean { return true } - if (traget['classList'] && traget['parentElement']) { - // Popular code editors CodeMirror and ACE - for (let el = traget as Element | null; el; el = el.parentElement) { - if (el.classList.contains('CodeMirror') || el.classList.contains('ace_editor')) { - return true - } + const editorTester = /CodeMirror|ace_editor/ + // Popular code editors CodeMirror and ACE + for (let el = traget as Element | null; el; el = el.parentElement) { + // With CodeMirror the `pre.CodeMirror-line` somehow got detached when the event + // triggerd. So el will never reach the root `.CodeMirror`. + if (editorTester.test(el.className)) { + return true } } }
fix
fix editor detection
57bb6e7a1694134782511667d4566f577450fe95
2018-06-28 19:10:36
CRIMX
chore(release): 6.4.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dd460c39..2bcdfd188 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.4.1"></a> +## [6.4.1](https://github.com/crimx/ext-saladict/compare/v6.4.0...v6.4.1) (2018-06-28) + + +### Bug Fixes + +* **content:** fix dynamic document.body [#150](https://github.com/crimx/ext-saladict/issues/150) ([27f2787](https://github.com/crimx/ext-saladict/commit/27f2787)) +* **manifest:** fix browser global conflict [#148](https://github.com/crimx/ext-saladict/issues/148) ([ca0d8a1](https://github.com/crimx/ext-saladict/commit/ca0d8a1)) + + + <a name="6.4.0"></a> # [6.4.0](https://github.com/crimx/ext-saladict/compare/v6.3.2...v6.4.0) (2018-06-17) diff --git a/package.json b/package.json index 107eab23d..24205fec7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.4.0", + "version": "6.4.1", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.4.1
ba377e77f84f8a7c610017fdc3b000c96645b0b6
2018-11-24 18:46:56
CRIMX
refactor: let engine handle dict source url generation
false
diff --git a/src/app-config/dicts.ts b/src/app-config/dicts.ts index 1a4d25d4a..b215239d4 100644 --- a/src/app-config/dicts.ts +++ b/src/app-config/dicts.ts @@ -6,13 +6,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1100', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-".. - */ - page: 'https://cn.bing.com/dict/search?q=%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -55,17 +48,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1110', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-".. - */ - page: { - en: 'https://dictionary.cambridge.org/search/english/direct/?q=%h', - 'zh-CN': 'https://dictionary.cambridge.org/zhs/搜索/英语-汉语-简体/direct/?q=%s', - 'zh-TW': 'https://dictionary.cambridge.org/zht/搜索/英語-漢語-繁體/direct/?q=%z', - }, /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -97,13 +79,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.collinsdictionary.com/dictionary/english/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -142,13 +117,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.etymonline.com/search?q=%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -188,13 +156,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1100', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-".. - */ - page: 'https://dict.eudic.net/dicts/en/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -233,13 +194,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1111', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://translate.google.com/#auto/zh-CN/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -284,13 +238,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1111', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.google.com.hk/search?q=define+%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -329,13 +276,6 @@ export function getALlDicts () { * `1` for supported */ lang: '0010', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.moedict.tw/%z', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -367,13 +307,6 @@ export function getALlDicts () { * `1` for supported */ lang: '0010', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.moedict.tw/~%z', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -405,13 +338,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.ldoceonline.com/dictionary/%h', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -456,13 +382,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.macmillandictionary.com/dictionary/british/%h', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -501,13 +420,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.oxfordlearnersdictionaries.com/definition/english/%h', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -546,13 +458,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1111', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://fanyi.sogou.com/#auto/zh-CHS/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -596,13 +501,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.urbandictionary.com/define.php?term=%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -641,13 +539,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.vocabulary.com/dictionary/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -673,19 +564,12 @@ export function getALlDicts () { minor: false, } }, - websterlearner: { + weblio: { /** * Supported language: en, zh-CN, zh-TW, ja * `1` for supported */ - lang: '1000', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.learnersdictionary.com/definition/%h', + lang: '0001', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -702,39 +586,21 @@ export function getALlDicts () { /** Word count to start searching */ selectionWC: { min: 1, - max: 5, + max: 20, }, /** Only start searching if the selection contains the language. */ selectionLang: { eng: true, - chs: false, - minor: false, - }, - /** - * Optional dict custom options. Can only be boolean, number or string. - * For string, add additional `options_sel` field to list out choices. - */ - options: { - defs: true, - phrase: true, - derived: true, - arts: true, - related: true, + chs: true, + minor: true, }, }, - weblio: { + websterlearner: { /** * Supported language: en, zh-CN, zh-TW, ja * `1` for supported */ - lang: '0001', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'https://www.weblio.jp/content/%s', + lang: '1000', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -751,13 +617,24 @@ export function getALlDicts () { /** Word count to start searching */ selectionWC: { min: 1, - max: 20, + max: 5, }, /** Only start searching if the selection contains the language. */ selectionLang: { eng: true, - chs: true, - minor: true, + chs: false, + minor: false, + }, + /** + * Optional dict custom options. Can only be boolean, number or string. + * For string, add additional `options_sel` field to list out choices. + */ + options: { + defs: true, + phrase: true, + derived: true, + arts: true, + related: true, }, }, youdao: { @@ -766,13 +643,6 @@ export function getALlDicts () { * `1` for supported */ lang: '1100', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.youdao.com/w/eng/%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -816,13 +686,6 @@ export function getALlDicts () { * `1` for supported */ lang: '0100', - /** - * Full content page to jump to when user clicks the title. - * %s will be replaced with the current word. - * %z will be replaced with the traditional Chinese version of the current word. - * %h will be replaced with the current word joining with hyphen "-". - */ - page: 'http://www.zdic.net/search/?c=1&q=%s', /** * If set to true, the dict start searching automatically. * Otherwise it'll only start seaching when user clicks the unfold button. @@ -855,11 +718,6 @@ export function getALlDicts () { allDicts as { [id: string]: { lang: string - page: string | { - en: string - 'zh-CN'?: string - 'zh-TW'?: string - } defaultUnfold: boolean selectionWC: { min: number, diff --git a/src/background/server.ts b/src/background/server.ts index 83b24731f..da36bf265 100644 --- a/src/background/server.ts +++ b/src/background/server.ts @@ -1,17 +1,16 @@ import { appConfigFactory, TCDirection } from '@/app-config' import { message, openURL } from '@/_helpers/browser-api' -import { chsToChz } from '@/_helpers/chs-to-chz' import { timeout, timer } from '@/_helpers/promise-more' import { createActiveConfigStream } from '@/_helpers/config-manager' import { getSuggests } from '@/_helpers/getSuggests' import { DictSearchResult } from '@/typings/server' -import { SearchErrorType, SearchFunction } from '@/components/dictionaries/helpers' +import { SearchErrorType, SearchFunction, GetSrcPageFunction } from '@/components/dictionaries/helpers' import { syncServiceInit, syncServiceDownload, syncServiceUpload } from './sync-manager' import { isInNotebook, saveWord, deleteWords, getWordsByText, getWords } from './database' import { play } from './audio-manager' import { MsgType, - MsgOpenUrl, + MsgOpenSrcPage, MsgAudioPlay, MsgFetchDictResult, MsgIsInNotebook, @@ -42,8 +41,10 @@ let qsPanelID: number | false = false // background script as transfer station message.addListener((data, sender: browser.runtime.MessageSender) => { switch (data.type) { + case MsgType.OpenSrcPage: + return openSrcPage(data as MsgOpenSrcPage) case MsgType.OpenURL: - return createTab(data as MsgOpenUrl) + return openURL(data.url, data.self) case MsgType.PlayAudio: return playAudio(data as MsgAudioPlay) case MsgType.FetchDictResult: @@ -189,16 +190,14 @@ export async function openQSPanel (): Promise<void> { } } -function createTab (data: MsgOpenUrl): Promise<void> { - return openURL( - data.placeholder - ? data.url - .replace(/%s/g, data.text) - .replace(/%z/g, chsToChz(data.text)) - .replace(/%h/g, data.text.trim().split(/\s+/).join('-')) - : data.url, - data.self - ) +function openSrcPage (data: MsgOpenSrcPage): Promise<void> { + let getSrcPage: GetSrcPageFunction + try { + getSrcPage = require('@/components/dictionaries/' + data.id + '/engine').getSrcPage + } catch (err) { + return Promise.reject(err) + } + return openURL(getSrcPage(data.text, config)) } function playAudio (data: MsgAudioPlay): Promise<void> { diff --git a/src/components/dictionaries/bing/engine.ts b/src/components/dictionaries/bing/engine.ts index 3a4c56cf6..4ff7cab48 100644 --- a/src/components/dictionaries/bing/engine.ts +++ b/src/components/dictionaries/bing/engine.ts @@ -1,8 +1,19 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { handleNoResult, handleNetWorkError, getText, getInnerHTMLBuilder, SearchFunction } from '../helpers' +import { + handleNoResult, + handleNetWorkError, + getText, + getInnerHTMLBuilder, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://cn.bing.com/dict/search?q=${text}` +} + const getInnerHTML = getInnerHTMLBuilder('https://cn.bing.com/') const DICT_LINK = 'https://cn.bing.com/dict/clientsearch?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=' @@ -227,7 +238,7 @@ function handleRelatedResult ( meanings: Array.from($defsList).map($list => { const word = getText($list, '.client_do_you_mean_list_word', isChz) return { - href: config.page.replace('%s', word), + href: `https://cn.bing.com/dict/search?q=${word}`, word, def: getText($list, '.client_do_you_mean_list_def', isChz) } diff --git a/src/components/dictionaries/cambridge/engine.ts b/src/components/dictionaries/cambridge/engine.ts index bab6076fe..fa33ff183 100644 --- a/src/components/dictionaries/cambridge/engine.ts +++ b/src/components/dictionaries/cambridge/engine.ts @@ -1,3 +1,4 @@ +import { chsToChz } from '@/_helpers/chs-to-chz' import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { HTMLString, @@ -7,9 +8,18 @@ import { removeChild, handleNetWorkError, SearchFunction, + GetSrcPageFunction, } from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text, config) => { + switch (config.langCode) { + case 'en': return `https://dictionary.cambridge.org/search/english/direct/?q=${text.trim().split(/\s+/).join('-')}` + case 'zh-CN': return `https://dictionary.cambridge.org/zhs/搜索/英语-汉语-简体/direct/?q=${text}` + case 'zh-TW': return `https://dictionary.cambridge.org/zht/搜索/英語-漢語-繁體/direct/?q=${chsToChz(text)}` + } +} + const getInnerHTML = getInnerHTMLBuilder('https://dictionary.cambridge.org/') interface CambridgeResultItem { diff --git a/src/components/dictionaries/cobuild/engine.ts b/src/components/dictionaries/cobuild/engine.ts index 02d5a3566..e8f23917a 100644 --- a/src/components/dictionaries/cobuild/engine.ts +++ b/src/components/dictionaries/cobuild/engine.ts @@ -1,8 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getText, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getText, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.collinsdictionary.com/dictionary/english/${text}` +} + const getInnerHTML = getInnerHTMLBuilder() export interface COBUILDResult { diff --git a/src/components/dictionaries/etymonline/engine.ts b/src/components/dictionaries/etymonline/engine.ts index 28f9fb6d5..c03df65e2 100644 --- a/src/components/dictionaries/etymonline/engine.ts +++ b/src/components/dictionaries/etymonline/engine.ts @@ -1,8 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { DictConfigs } from '@/app-config' -import { getText, getInnerHTMLBuilder, handleNoResult, HTMLString, handleNetWorkError, SearchFunction } from '../helpers' +import { + getText, + getInnerHTMLBuilder, + handleNoResult, + HTMLString, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `http://www.etymonline.com/search?q=${text}` +} + const getInnerHTML = getInnerHTMLBuilder() type EtymonlineResultItem = { diff --git a/src/components/dictionaries/eudic/engine.ts b/src/components/dictionaries/eudic/engine.ts index 5daa52200..0a27f2694 100644 --- a/src/components/dictionaries/eudic/engine.ts +++ b/src/components/dictionaries/eudic/engine.ts @@ -1,7 +1,17 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { getText, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + getText, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://dict.eudic.net/dicts/en/${text}` +} + interface EudicResultItem { chs: string eng: string diff --git a/src/components/dictionaries/google/engine.ts b/src/components/dictionaries/google/engine.ts index 685133cd9..ef7c7bea3 100644 --- a/src/components/dictionaries/google/engine.ts +++ b/src/components/dictionaries/google/engine.ts @@ -1,8 +1,24 @@ -import { handleNoResult, MachineTranslateResult, handleNetWorkError, SearchFunction, MachineTranslatePayload } from '../helpers' +import { + handleNoResult, + MachineTranslateResult, + handleNetWorkError, + SearchFunction, + MachineTranslatePayload, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' import { isContainChinese, isContainJapanese, isContainKorean } from '@/_helpers/lang-check' import { first } from '@/_helpers/promise-more' +export const getSrcPage: GetSrcPageFunction = (text, config) => { + const domain = config.dicts.all.google.options.cnfirst ? 'cn' : 'com' + const lang = config.dicts.all.google.options.tl === 'default' + ? config.langCode + : config.dicts.all.google.options.tl + + return `https://translate.google.${domain}/#auto/${lang}/${text}` +} + export type GoogleResult = MachineTranslateResult interface GoogleRawResult { diff --git a/src/components/dictionaries/googledict/engine.ts b/src/components/dictionaries/googledict/engine.ts index 172cf06d9..10ff31eb5 100644 --- a/src/components/dictionaries/googledict/engine.ts +++ b/src/components/dictionaries/googledict/engine.ts @@ -1,6 +1,20 @@ -import { HTMLString, handleNoResult, getInnerHTMLBuilder, removeChild, decodeHEX, removeChildren, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + handleNoResult, + getInnerHTMLBuilder, + removeChild, + decodeHEX, + removeChildren, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.google.com.hk/search?q=define+${text}` +} + export interface GoogleDictResult { entry: HTMLString } diff --git a/src/components/dictionaries/guoyu/engine.ts b/src/components/dictionaries/guoyu/engine.ts index bf755418b..6aeae8933 100644 --- a/src/components/dictionaries/guoyu/engine.ts +++ b/src/components/dictionaries/guoyu/engine.ts @@ -1,8 +1,12 @@ -import { handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { handleNoResult, handleNetWorkError, SearchFunction, GetSrcPageFunction } from '../helpers' import chsToChz from '@/_helpers/chs-to-chz' import { AppConfig } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.moedict.tw/${chsToChz(text)}` +} + /** @see https://github.com/audreyt/moedict-webkit#4-國語-a */ export interface GuoYuResult { n: number diff --git a/src/components/dictionaries/helpers.ts b/src/components/dictionaries/helpers.ts index df9f32e67..bfe7ec01a 100644 --- a/src/components/dictionaries/helpers.ts +++ b/src/components/dictionaries/helpers.ts @@ -4,10 +4,16 @@ import { DictID, AppConfig } from '@/app-config' import { SelectionInfo } from '@/_helpers/selection' import { chsToChz } from '@/_helpers/chs-to-chz' +/** Fetch and parse dictionary search result */ export interface SearchFunction<Result, Payload = {}> { (text: string, config: AppConfig, payload: Readonly<Payload & { isPDF: boolean }>): Promise<Result> } +/** Return a dictionary source page url for the dictionary header */ +export interface GetSrcPageFunction { + (text: string, config: AppConfig): string +} + export type HTMLString = string export interface ViewPorps<T> { diff --git a/src/components/dictionaries/liangan/engine.ts b/src/components/dictionaries/liangan/engine.ts index 2d775e33e..5770f1d52 100644 --- a/src/components/dictionaries/liangan/engine.ts +++ b/src/components/dictionaries/liangan/engine.ts @@ -1,7 +1,12 @@ -import { SearchFunction } from '../helpers' +import { SearchFunction, GetSrcPageFunction } from '../helpers' +import chsToChz from '@/_helpers/chs-to-chz' import { DictSearchResult } from '@/typings/server' import { moedictSearch, GuoYuResult } from '../guoyu/engine' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.moedict.tw/~${chsToChz(text)}` +} + export type LiangAnResult = GuoYuResult export const search: SearchFunction<DictSearchResult<LiangAnResult>> = ( diff --git a/src/components/dictionaries/longman/engine.ts b/src/components/dictionaries/longman/engine.ts index cf259be35..b33a330ac 100644 --- a/src/components/dictionaries/longman/engine.ts +++ b/src/components/dictionaries/longman/engine.ts @@ -1,8 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getText, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getText, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.ldoceonline.com/dictionary/${text.trim().split(/\s+/).join('-')}` +} + const getInnerHTML = getInnerHTMLBuilder('https://www.ldoceonline.com/') export interface LongmanResultEntry { diff --git a/src/components/dictionaries/macmillan/engine.ts b/src/components/dictionaries/macmillan/engine.ts index 99e15b814..183812d12 100644 --- a/src/components/dictionaries/macmillan/engine.ts +++ b/src/components/dictionaries/macmillan/engine.ts @@ -1,9 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { reflect } from '@/_helpers/promise-more' -import { HTMLString, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `http://www.macmillandictionary.com/dictionary/british/${text.trim().split(/\s+/).join('-')}` +} + const getInnerHTML = getInnerHTMLBuilder('http://www.macmillandictionary.com/') interface MacmillanResultItem { diff --git a/src/components/dictionaries/oald/engine.ts b/src/components/dictionaries/oald/engine.ts index 4af102f6d..ecc4c4210 100644 --- a/src/components/dictionaries/oald/engine.ts +++ b/src/components/dictionaries/oald/engine.ts @@ -1,9 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { reflect } from '@/_helpers/promise-more' -import { HTMLString, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.oxfordlearnersdictionaries.com/definition/english/${text.trim().split(/\s+/).join('-')}` +} + const getInnerHTML = getInnerHTMLBuilder('https://www.oxfordlearnersdictionaries.com/') interface OALDResultItem { diff --git a/src/components/dictionaries/sogou/engine.ts b/src/components/dictionaries/sogou/engine.ts index fc5b7a455..2b482716d 100644 --- a/src/components/dictionaries/sogou/engine.ts +++ b/src/components/dictionaries/sogou/engine.ts @@ -1,8 +1,27 @@ -import { handleNoResult, MachineTranslatePayload, MachineTranslateResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + handleNoResult, + MachineTranslatePayload, + MachineTranslateResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' import { isContainChinese, isContainJapanese, isContainKorean } from '@/_helpers/lang-check' import md5 from 'md5' +export const getSrcPage: GetSrcPageFunction = (text, config) => { + const lang = config.dicts.all.sogou.options.tl === 'default' + ? config.langCode === 'zh-CN' + ? 'zh-CHS' + : config.langCode === 'zh-TW' + ? 'zh-CHT' + : 'en' + : config.dicts.all.sogou.options.tl + + return `https://fanyi.sogou.com/#auto/${lang}/${text}` +} + export type SogouResult = MachineTranslateResult type SogouSearchResult = DictSearchResult<SogouResult> diff --git a/src/components/dictionaries/urban/engine.ts b/src/components/dictionaries/urban/engine.ts index af789033a..d2340f22e 100644 --- a/src/components/dictionaries/urban/engine.ts +++ b/src/components/dictionaries/urban/engine.ts @@ -1,7 +1,19 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getText, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getText, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `http://www.urbandictionary.com/define.php?term=${text}` +} + const getInnerHTML = getInnerHTMLBuilder('https://www.urbandictionary.com/') interface UrbanResultItem { diff --git a/src/components/dictionaries/vocabulary/engine.ts b/src/components/dictionaries/vocabulary/engine.ts index f22f5d438..7c8d699c6 100644 --- a/src/components/dictionaries/vocabulary/engine.ts +++ b/src/components/dictionaries/vocabulary/engine.ts @@ -1,7 +1,17 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { getText, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + getText, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.vocabulary.com/dictionary/${text}` +} + export interface VocabularyResult { short: string long: string diff --git a/src/components/dictionaries/weblio/engine.ts b/src/components/dictionaries/weblio/engine.ts index 2442d7c09..867a1a44b 100644 --- a/src/components/dictionaries/weblio/engine.ts +++ b/src/components/dictionaries/weblio/engine.ts @@ -1,7 +1,19 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, getOuterHTMLBuilder, SearchFunction } from '../helpers' +import { + HTMLString, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + getOuterHTMLBuilder, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://www.weblio.jp/content/${text}` +} + const getInnerHTML = getInnerHTMLBuilder('https://www.weblio.jp/', {}) // keep inline style const getOuterHTML = getOuterHTMLBuilder('https://www.weblio.jp/', {}) // keep inline style diff --git a/src/components/dictionaries/websterlearner/engine.ts b/src/components/dictionaries/websterlearner/engine.ts index 3ec2b0927..765e58584 100644 --- a/src/components/dictionaries/websterlearner/engine.ts +++ b/src/components/dictionaries/websterlearner/engine.ts @@ -1,8 +1,19 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `http://www.learnersdictionary.com/definition/${text.trim().split(/\s+/).join('-')}` +} + const getInnerHTML = getInnerHTMLBuilder('http://www.learnersdictionary.com/') interface WebsterLearnerResultItem { diff --git a/src/components/dictionaries/youdao/engine.ts b/src/components/dictionaries/youdao/engine.ts index e99508193..59bb4bdd3 100644 --- a/src/components/dictionaries/youdao/engine.ts +++ b/src/components/dictionaries/youdao/engine.ts @@ -1,8 +1,20 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { getText, getInnerHTMLBuilder, handleNoResult, HTMLString, handleNetWorkError, SearchFunction } from '../helpers' +import { + getText, + getInnerHTMLBuilder, + handleNoResult, + HTMLString, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictConfigs } from '@/app-config' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `https://dict.youdao.com/w/eng/${text}` +} + const getInnerHTML = getInnerHTMLBuilder('http://www.youdao.com/') export interface YoudaoResultLex { diff --git a/src/components/dictionaries/zdic/engine.ts b/src/components/dictionaries/zdic/engine.ts index ca788a73f..19074c99d 100644 --- a/src/components/dictionaries/zdic/engine.ts +++ b/src/components/dictionaries/zdic/engine.ts @@ -1,7 +1,18 @@ import { fetchDirtyDOM } from '@/_helpers/fetch-dom' -import { HTMLString, getInnerHTMLBuilder, handleNoResult, handleNetWorkError, SearchFunction } from '../helpers' +import { + HTMLString, + getInnerHTMLBuilder, + handleNoResult, + handleNetWorkError, + SearchFunction, + GetSrcPageFunction, +} from '../helpers' import { DictSearchResult } from '@/typings/server' +export const getSrcPage: GetSrcPageFunction = (text) => { + return `http://www.zdic.net/search/?c=1&q=${text}` +} + const getInnerHTML = getInnerHTMLBuilder('http://www.zdic.net/') export interface ZdicResult { diff --git a/src/content/components/DictItem/index.tsx b/src/content/components/DictItem/index.tsx index 0316a0e3a..fcbd08915 100644 --- a/src/content/components/DictItem/index.tsx +++ b/src/content/components/DictItem/index.tsx @@ -2,7 +2,7 @@ import React from 'react' import { DictID } from '@/app-config' import { TranslationFunction } from 'i18next' import { message } from '@/_helpers/browser-api' -import { MsgType, MsgOpenUrl } from '@/typings/message' +import { MsgType, MsgOpenUrl, MsgOpenSrcPage } from '@/typings/message' import { SearchStatus } from '@/content/redux/modules/dictionaries' import { SelectionInfo, getDefaultSelectionInfo } from '@/_helpers/selection' @@ -18,7 +18,6 @@ export interface DictItemProps extends DictItemDispatchers { readonly t: TranslationFunction readonly id: DictID readonly text: string - readonly dictURL: string readonly preferredHeight: number readonly searchStatus: SearchStatus readonly searchResult: any @@ -176,12 +175,11 @@ export default class DictItem extends React.PureComponent<DictItemProps, DictIte handleDictURLClick = (e: React.MouseEvent<HTMLElement>) => { e.stopPropagation() e.preventDefault() - message.send<MsgOpenUrl>({ - type: MsgType.OpenURL, - url: this.props.dictURL, - placeholder: true, + message.send<MsgOpenSrcPage>({ + type: MsgType.OpenSrcPage, text: this.props.text, - }) + id: this.props.id, + }).catch(e => {/* */}) } handleRecalcBodyHeight = () => { @@ -233,7 +231,6 @@ export default class DictItem extends React.PureComponent<DictItemProps, DictIte const { t, id, - dictURL, fontSize, searchStatus, searchResult, @@ -254,7 +251,7 @@ export default class DictItem extends React.PureComponent<DictItemProps, DictIte <header className='panel-DictItem_Header' onClick={this.toggleFolding}> <img className='panel-DictItem_Logo' src={require('@/components/dictionaries/' + id + '/favicon.png')} alt='dict logo' /> <h1 className='panel-DictItem_Title'> - <a href={dictURL} onClick={this.handleDictURLClick}>{t(`dict:${id}`)}</a> + <a href='#' onClick={this.handleDictURLClick}>{t(`dict:${id}`)}</a> </h1> {searchStatus === SearchStatus.Searching && !hasError && <svg className='panel-DictItem_Loader' width='120' height='10' viewBox='0 0 120 10' xmlns='http://www.w3.org/2000/svg'> diff --git a/src/content/components/DictPanel/index.tsx b/src/content/components/DictPanel/index.tsx index 2323fd300..52c8fe437 100644 --- a/src/content/components/DictPanel/index.tsx +++ b/src/content/components/DictPanel/index.tsx @@ -33,7 +33,6 @@ type ChildrenProps = 't' | 'id' | 'text' | - 'dictURL' | 'preferredHeight' | 'searchStatus' | 'searchResult' @@ -246,17 +245,12 @@ export class DictPanel extends React.Component<DictPanelProps & { t: Translation </svg> </button> {activeDicts.map(id => { - let dictURL = allDictsConfig[id].page - if (typeof dictURL !== 'string') { - dictURL = dictURL[langCode] || dictURL.en - } const dictInfo = dictsInfo[id] return React.createElement(DictItem, { t, key: id, id, text: (dictionaries.searchHistory[0] || selection.selectionInfo).text, - dictURL, fontSize, preferredHeight: allDictsConfig[id].preferredHeight, panelWidth, diff --git a/src/options/Options.vue b/src/options/Options.vue index 405136ab1..ffbc45216 100644 --- a/src/options/Options.vue +++ b/src/options/Options.vue @@ -280,7 +280,6 @@ export default { const googleLang = config.dicts.all.google.options.tl === 'default' ? config.langCode : config.dicts.all.google.options.tl - config.dicts.all.google.page = `https://translate.google.${googleLocation}/#auto/${googleLang}/%s` config.contextMenus.all.google_translate = `https://translate.google.${googleLocation}/#auto/${googleLang}/%s` const sogouLang = config.dicts.all.sogou.options.tl === 'default' @@ -290,7 +289,6 @@ export default { ? 'zh-CHT' : 'en' : config.dicts.all.sogou.options.tl - config.dicts.all.sogou.page = `https://fanyi.sogou.com/#auto/${sogouLang}/%s` config.contextMenus.all.sogou = `https://fanyi.sogou.com/#auto/${sogouLang}/%s` updateActiveConfig(config) diff --git a/src/typings/message.ts b/src/typings/message.ts index f47b7ef64..8714930bc 100644 --- a/src/typings/message.ts +++ b/src/typings/message.ts @@ -34,8 +34,10 @@ export const enum MsgType { /** Response the pageInfo of a page */ PageInfo, - /** Create a tab with the url */ + /** Create a tab with the url or highlight an existing one */ OpenURL, + /** open a dictionary source page */ + OpenSrcPage, /** Play a audio src */ PlayAudio, /** Search text with a dictionary and response the result */ @@ -103,17 +105,7 @@ export interface PostMsgSelection extends Omit<MsgSelection, 'type'> { readonly type: PostMsgType.Selection } -interface MsgOpenUrlWithPlaceholder { - readonly type: MsgType.OpenURL - readonly url: string - readonly placeholder: true - /** text to replace the placeholder */ - readonly text: string - /** use browser.runtime.getURL? */ - readonly self?: boolean -} - -interface MsgOpenUrlWithoutPlaceholder { +export interface MsgOpenUrl { readonly type: MsgType.OpenURL readonly url: string readonly placeholder?: false @@ -121,7 +113,11 @@ interface MsgOpenUrlWithoutPlaceholder { readonly self?: boolean } -export type MsgOpenUrl = MsgOpenUrlWithoutPlaceholder | MsgOpenUrlWithPlaceholder +export interface MsgOpenSrcPage { + readonly type: MsgType.OpenSrcPage + readonly text: string + readonly id: DictID +} export interface MsgAudioPlay { readonly type: MsgType.PlayAudio
refactor
let engine handle dict source url generation
369d27ec92f8bc6563ca22bd8b0652de5aad7e96
2019-01-17 18:34:55
CRIMX
chore: disable wiki opening
false
diff --git a/config/fake-env/webextension-page.js b/config/fake-env/webextension-page.js index 8d0cffb2d..c551a19c1 100644 --- a/config/fake-env/webextension-page.js +++ b/config/fake-env/webextension-page.js @@ -182,7 +182,7 @@ function sendMessage (extensionId, message) { function genStorageApis () { window['storageData'] = { local: genLocalStorageData(), - sync: {}, + sync: { hasInstructionsShown: true }, listeners: [], }
chore
disable wiki opening
4ffc59353ff98eb24d1f845084ec8e94b9f5902a
2018-04-25 16:42:17
CRIMX
refactor(content): change searchText api
false
diff --git a/src/content/redux/modules/dictionaries.ts b/src/content/redux/modules/dictionaries.ts index b4c7f0e3e..002319607 100644 --- a/src/content/redux/modules/dictionaries.ts +++ b/src/content/redux/modules/dictionaries.ts @@ -85,13 +85,19 @@ export default function reducer (state = initState, action): DictionariesState { } } case Actions.SEARCH_START: { - const { info }: { info: SelectionInfo } = action.payload + const { id, info }: { id?: DictID, info: SelectionInfo } = action.payload return { ...state, lastSearchInfo: info, dicts: mapValues<typeof state.dicts, DictState>( state.dicts, - dict => ({ ...dict, searchStatus: SearchStatus.Searching, searchResult: null }) as DictState + (dictInfo, dictID) => { + return ( + !id || dictID === id + ? { ...dictInfo, searchStatus: SearchStatus.Searching, searchResult: null } + : dictInfo + ) as DictState + } ), } } @@ -122,7 +128,8 @@ export function newItemHeight (payload: { id: DictID, height: number }): Action return ({ type: Actions.UPDATE_HEIGHT, payload }) } -export function searchStart (payload: { info: SelectionInfo }): Action { +/** Search all selected dicts if id is not provided */ +export function searchStart (payload: { id?: DictID, info: SelectionInfo }): Action { return ({ type: Actions.SEARCH_START, payload }) } @@ -139,18 +146,26 @@ type Dispatcher = ( getState: () => StoreState, ) => any -export function searchText (arg?: SelectionInfo | string): Dispatcher { +/** + * Search all selected dicts if id is not provided. + * Use last selection if info is not provided. + */ +export function searchText (arg?: { id?: DictID, info?: SelectionInfo | string }): Dispatcher { return (dispatch, getState) => { const state = getState() const info = arg - ? typeof arg === 'string' - ? getDefaultSelectionInfo({ text: arg }) - : arg + ? typeof arg.info === 'string' + ? getDefaultSelectionInfo({ text: arg.info }) + : arg.info || state.dictionaries.lastSearchInfo : state.dictionaries.lastSearchInfo - dispatch(searchStart({ info })) + const id = arg && arg.id + + dispatch(searchStart({ id, info })) + + const dicts = id ? [id] : state.config.dicts.selected - state.config.dicts.selected.forEach(id => { + dicts.forEach(id => { const msg: MsgFetchDictResult = { type: MsgType.FetchDictResult, id,
refactor
change searchText api
05e8e4f85ff691feee45327860ca06796a43b0cd
2018-07-27 11:11:37
CRIMX
chore(release): 6.8.3
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index acaaa92be..db0323994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.8.3"></a> +## [6.8.3](https://github.com/crimx/ext-saladict/compare/v6.8.2...v6.8.3) (2018-07-27) + + +### Bug Fixes + +* **dicts:** fix audio link ([8b7e140](https://github.com/crimx/ext-saladict/commit/8b7e140)), closes [#175](https://github.com/crimx/ext-saladict/issues/175) + + + <a name="6.8.2"></a> ## [6.8.2](https://github.com/crimx/ext-saladict/compare/v6.8.1...v6.8.2) (2018-07-26) diff --git a/package.json b/package.json index 1930fa8fd..7bb587602 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.8.2", + "version": "6.8.3", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.8.3
8707bcb8922e13b55e7d37f550b03863f5920bd4
2018-06-05 16:35:10
CRIMX
test(selection): fix testing
false
diff --git a/test/specs/selection/index.spec.ts b/test/specs/selection/index.spec.ts index d137f6369..231691589 100644 --- a/test/specs/selection/index.spec.ts +++ b/test/specs/selection/index.spec.ts @@ -161,6 +161,10 @@ describe('Message Selection', () => { }) it('should send empty message if the selection is made inside a input box', done => { + const config = mockAppConfigFactory() + config.noTypeField = true + dispatchAppConfigEvent(config) + const $input = document.createElement('input') document.body.appendChild($input)
test
fix testing
1e74644f2073549aa5682152df4384c16bf67080
2018-04-28 17:47:34
CRIMX
test(content): update snapshot
false
diff --git a/test/specs/components/content/__snapshots__/MenuBar.spec.tsx.snap b/test/specs/components/content/__snapshots__/MenuBar.spec.tsx.snap index faa8a28c0..a4818116f 100644 --- a/test/specs/components/content/__snapshots__/MenuBar.spec.tsx.snap +++ b/test/specs/components/content/__snapshots__/MenuBar.spec.tsx.snap @@ -5,7 +5,7 @@ exports[`Component/content/MenuBar should render correctly 1`] = ` className="panel-MenuBar" > <button - className="panel-MenuBar_Btn" + className="panel-MenuBar_Btn-dir" disabled={true} onClick={[Function]} > @@ -20,12 +20,12 @@ exports[`Component/content/MenuBar should render correctly 1`] = ` tipSearchHistoryBack </title> <path - d="M 5.191 15.999 L 19.643 1.548 C 19.998 1.192 19.998 0.622 19.643 0.267 C 19.288 -0.089 18.718 -0.089 18.362 0.267 L 3.267 15.362 C 2.911 15.718 2.911 16.288 3.267 16.643 L 18.362 31.732 C 18.537 31.906 18.771 32 18.999 32 C 19.227 32 19.462 31.913 19.636 31.732 C 19.992 31.377 19.992 30.807 19.636 30.451 L 5.191 15.999 Z" + d="M 7.191 15.999 L 21.643 1.548 C 21.998 1.192 21.998 0.622 21.643 0.267 C 21.288 -0.089 20.718 -0.089 20.362 0.267 L 5.267 15.362 C 4.911 15.718 4.911 16.288 5.267 16.643 L 20.362 31.732 C 20.537 31.906 20.771 32 20.999 32 C 21.227 32 21.462 31.913 21.636 31.732 C 21.992 31.377 21.992 30.807 21.636 30.451 L 7.191 15.999 Z" /> </svg> </button> <button - className="panel-MenuBar_Btn" + className="panel-MenuBar_Btn-dir" disabled={true} onClick={[Function]} > @@ -40,7 +40,7 @@ exports[`Component/content/MenuBar should render correctly 1`] = ` tipSearchHistoryNext </title> <path - d="M 26.643 15.362 L 11.547 0.267 C 11.192 -0.089 10.622 -0.089 10.267 0.267 C 9.911 0.622 9.911 1.192 10.267 1.547 L 24.718 15.999 L 10.267 30.451 C 9.911 30.806 9.911 31.376 10.267 31.732 C 10.441 31.906 10.676 32 10.904 32 C 11.132 32 11.366 31.913 11.541 31.732 L 26.636 16.636 C 26.992 16.288 26.992 15.711 26.643 15.362 Z" + d="M 25.643 15.362 L 10.547 0.267 C 10.192 -0.089 9.622 -0.089 9.267 0.267 C 8.911 0.622 8.911 1.192 9.267 1.547 L 23.718 15.999 L 9.267 30.451 C 8.911 30.806 8.911 31.376 9.267 31.732 C 9.441 31.906 9.676 32 9.904 32 C 10.132 32 10.366 31.913 10.541 31.732 L 25.636 16.636 C 25.992 16.288 25.992 15.711 25.643 15.362 Z" /> </svg> </button> @@ -202,7 +202,7 @@ exports[`Component/content/MenuBar should render correctly with fav and pin 1`] className="panel-MenuBar" > <button - className="panel-MenuBar_Btn" + className="panel-MenuBar_Btn-dir" disabled={true} onClick={[Function]} > @@ -217,12 +217,12 @@ exports[`Component/content/MenuBar should render correctly with fav and pin 1`] tipSearchHistoryBack </title> <path - d="M 5.191 15.999 L 19.643 1.548 C 19.998 1.192 19.998 0.622 19.643 0.267 C 19.288 -0.089 18.718 -0.089 18.362 0.267 L 3.267 15.362 C 2.911 15.718 2.911 16.288 3.267 16.643 L 18.362 31.732 C 18.537 31.906 18.771 32 18.999 32 C 19.227 32 19.462 31.913 19.636 31.732 C 19.992 31.377 19.992 30.807 19.636 30.451 L 5.191 15.999 Z" + d="M 7.191 15.999 L 21.643 1.548 C 21.998 1.192 21.998 0.622 21.643 0.267 C 21.288 -0.089 20.718 -0.089 20.362 0.267 L 5.267 15.362 C 4.911 15.718 4.911 16.288 5.267 16.643 L 20.362 31.732 C 20.537 31.906 20.771 32 20.999 32 C 21.227 32 21.462 31.913 21.636 31.732 C 21.992 31.377 21.992 30.807 21.636 30.451 L 7.191 15.999 Z" /> </svg> </button> <button - className="panel-MenuBar_Btn" + className="panel-MenuBar_Btn-dir" disabled={true} onClick={[Function]} > @@ -237,7 +237,7 @@ exports[`Component/content/MenuBar should render correctly with fav and pin 1`] tipSearchHistoryNext </title> <path - d="M 26.643 15.362 L 11.547 0.267 C 11.192 -0.089 10.622 -0.089 10.267 0.267 C 9.911 0.622 9.911 1.192 10.267 1.547 L 24.718 15.999 L 10.267 30.451 C 9.911 30.806 9.911 31.376 10.267 31.732 C 10.441 31.906 10.676 32 10.904 32 C 11.132 32 11.366 31.913 11.541 31.732 L 26.636 16.636 C 26.992 16.288 26.992 15.711 26.643 15.362 Z" + d="M 25.643 15.362 L 10.547 0.267 C 10.192 -0.089 9.622 -0.089 9.267 0.267 C 8.911 0.622 8.911 1.192 9.267 1.547 L 23.718 15.999 L 9.267 30.451 C 8.911 30.806 8.911 31.376 9.267 31.732 C 9.441 31.906 9.676 32 9.904 32 C 10.132 32 10.366 31.913 10.541 31.732 L 25.636 16.636 C 25.992 16.288 25.992 15.711 25.643 15.362 Z" /> </svg> </button>
test
update snapshot
5b6f60b176cc528664ff072a2a0e9dcb314270eb
2020-09-04 07:36:33
dependabot[bot]
build(deps): bump bl from 4.0.2 to 4.0.3 (#986)
false
diff --git a/yarn.lock b/yarn.lock index 5b5f36a6a..56859fd97 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4186,9 +4186,9 @@ bindings@^1.5.0: file-uri-to-path "1.0.0" bl@^4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/bl/-/bl-4.0.2.tgz#52b71e9088515d0606d9dd9cc7aa48dc1f98e73a" - integrity sha512-j4OH8f6Qg2bGuWfRiltT2HYGx0e1QcBTrK9KAHNMwMZdQnDZFk0ZSYIpADjYCB3U12nicC5tVJwSIhwOWjb4RQ== + version "4.0.3" + resolved "https://registry.yarnpkg.com/bl/-/bl-4.0.3.tgz#12d6287adc29080e22a705e5764b2a9522cdc489" + integrity sha512-fs4G6/Hu4/EE+F75J8DuN/0IpQqNjAdC7aEQv7Qt8MHGUH7Ckv2MwTEEeN9QehD0pfIDkMI1bkHYkKy7xHyKIg== dependencies: buffer "^5.5.0" inherits "^2.0.4"
build
bump bl from 4.0.2 to 4.0.3 (#986)
68ccbef3614b5e3bbe5e189bfef4b8688492af73
2020-04-11 21:41:05
crimx
refactor(options): update locales
false
diff --git a/src/_locales/en/options.ts b/src/_locales/en/options.ts index 3f542633d..05a406439 100644 --- a/src/_locales/en/options.ts +++ b/src/_locales/en/options.ts @@ -3,6 +3,46 @@ import { locale as _locale } from '../zh-CN/options' export const locale: typeof _locale = { title: 'Saladict Options', previewPanel: 'Preview Dict Panel', + + config: { + active: 'Enable Inline Translator', + active_help: + '"Quick Search" is still available even if Inline translation is turned off.', + animation: 'Animation transitions', + animation_help: 'Switch off animation transitions to reduce runtime cost.', + darkMode: 'Dark Mode', + langCode: 'App Language', + + opt: { + export: 'Export Configs', + help: 'Configs are synced automatically via browser.', + import: 'Import Configs', + import_error: 'Import Configs failed', + reset: 'Reset Configs', + reset_confirm: 'Reset to default settings. Confirm?', + upload_error: 'Unable to save settings.' + } + }, + + profiles: { + opt: { + add_name: 'Add Profile Name', + delete_confirm: 'Delete Profile "{{name}}". Confirm?', + edit_name: 'Change Profile Name', + help: + 'Each profile represents an independent set of settings. Some of the settings (with <span style="color:#f5222d">*</span> prefix) change according to profile. One may switch profiles by hovering on the menu icon on Dict Panel, or focus on the icon then hit <kbd>↓</kbd>.' + } + }, + + profile: { + opt: { + item_extra: 'This option may change base on "Profile".' + } + }, + + shortcuts: 'Set Shortcuts', + unsave_confirm: 'Settings not saved. Sure to leave?', + dict: { add: 'Add dicts', default_height: 'Default Panel Height', @@ -71,9 +111,6 @@ export const locale: typeof _locale = { analytics_help: 'Share anonymous device browser version information. Saladict author will offer prioritized support to popular devices and browsers.', animation: 'Animation transitions', - animation_help: 'Switch off animation transitions to reduce runtime cost.', - app_active_help: - '"Quick Search" is still available even if Inline translation is turned off.', autopron: { accent: 'Accent Preference', accent_uk: 'UK', @@ -165,7 +202,6 @@ export const locale: typeof _locale = { 'Search when selection contains words in the chosen languages.', sel_lang_warning: 'Note that Japanese and Korean also include Chinese. French, Deutsch and Spanish also include English. If Chinese or English is cancelled while others are selected, only the exclusive parts of those languages are tested. E.g. kana characters in Japanese.', - shortcuts: 'Set Shortcuts', searchMode: { direct: 'Direct Search', direct_help: 'Show dict panel directly.', @@ -231,14 +267,6 @@ export const locale: typeof _locale = { selection: 'Page Selection' }, - profiles: { - add_name: 'Add Profile Name', - delete_confirm: 'Delete Profile "{{name}}". Confirm?', - edit_name: 'Change Profile Name', - help: - 'Each profile represents an independent set of settings. Some of the settings (with <span style="color:#f5222d">*</span> prefix) change according to profile. One may switch profiles by hovering on the menu icon on Dict Panel, or focus on the icon then hit <kbd>↓</kbd>.' - }, - sync: { description: 'Sync settings.', start: 'Syncing started in background', diff --git a/src/_locales/zh-CN/options.ts b/src/_locales/zh-CN/options.ts index 483c227f0..5c7da382d 100644 --- a/src/_locales/zh-CN/options.ts +++ b/src/_locales/zh-CN/options.ts @@ -31,6 +31,12 @@ export const locale = { } }, + profile: { + opt: { + item_extra: '此选项会因「情景模式」而改变。' + } + }, + shortcuts: '设置快捷键', unsave_confirm: '修改尚未保存,确定放弃?', diff --git a/src/_locales/zh-TW/options.ts b/src/_locales/zh-TW/options.ts index 65a501a37..2f530b00e 100644 --- a/src/_locales/zh-TW/options.ts +++ b/src/_locales/zh-TW/options.ts @@ -3,6 +3,45 @@ import { locale as _locale } from '../zh-CN/options' export const locale: typeof _locale = { title: '沙拉查詞設定', previewPanel: '預覽字典介面', + + config: { + active: '啟用滑鼠選字翻譯', + active_help: '關閉後「迅速查字」功能依然可用。', + animation: '啟用轉換動畫', + animation_help: '在低效能裝置上關閉過渡動畫可減少渲染負擔。', + darkMode: '黑暗模式', + langCode: '介面語言', + + opt: { + export: '匯出設定', + help: '設定已通過瀏覽器自動同步,也可以手動匯入匯出。', + import: '匯入設定', + import_error: '匯入設定失敗', + reset: '重設設定', + reset_confirm: '所有設定將還原至預設值,確定?', + upload_error: '設定儲存失敗' + } + }, + + profiles: { + opt: { + add_name: '新增情景模式名稱', + delete_confirm: '「{{name}}」將被刪除,確認?', + edit_name: '變更情景模式名稱', + help: + '每個情景模式相當於一套獨立的設定,一些選項(帶有 <span style="color:#f5222d">*</span>)會隨著情景模式變化。滑鼠懸浮在字典介面的選單圖示上可快速切換,或者焦點選中選單圖示然後按<kbd>↓</kbd>。' + } + }, + + profile: { + opt: { + item_extra: '此選項會因「情景模式」而改變。' + } + }, + + shortcuts: '設定快速鍵', + unsave_confirm: '修改尚未儲存,確定放棄?', + dict: { add: '新增字典', default_height: '字典預設高度', @@ -69,8 +108,6 @@ export const locale: typeof _locale = { analytics_help: '提供匿名裝置瀏覽器版本資訊。沙拉查詞作者會優先支援使用者更多的裝置和瀏覽器。', animation: '啟用轉換動畫', - animation_help: '在低效能裝置上關閉過渡動畫可減少渲染負擔。', - app_active_help: '關閉後「迅速查字」功能依然可用。', autopron: { accent: '優先口音', accent_uk: '英式', @@ -155,7 +192,6 @@ export const locale: typeof _locale = { sel_lang_help: '當選取的文字包含相對應的語言時,才進行尋找。', sel_lang_warning: '注意日語與韓語也包含了漢字。法語、德語和西語也包含了英文。若取消了中文或英語而勾選了其它語言,則只翻譯那些語言獨有的部分,如日語只翻譯假名。', - shortcuts: '設定快速鍵', searchMode: { direct: '直接搜尋', direct_help: '直接顯示字典視窗介面。', @@ -223,14 +259,6 @@ export const locale: typeof _locale = { selection: '滑鼠選字' }, - profiles: { - add_name: '新增情景模式名稱', - delete_confirm: '「{{name}}」將被刪除,確認?', - edit_name: '變更情景模式名稱', - help: - '每個情景模式相當於一套獨立的設定,一些選項(帶有 <span style="color:#f5222d">*</span>)會隨著情景模式變化。滑鼠懸浮在字典介面的選單圖示上可快速切換,或者焦點選中選單圖示然後按<kbd>↓</kbd>。' - }, - sync: { description: '資料同步設定。', start: '同步已在背景開始',
refactor
update locales
052531fc0f95b40011783e0354e47db974e8b563
2019-03-17 13:06:31
CRIMX
chore(release): 6.27.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index cf4f206b3..4620141ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,39 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="6.27.0"></a> +# [6.27.0](https://github.com/crimx/ext-saladict/compare/v6.26.0...v6.27.0) (2019-03-17) + + +### Bug Fixes + +* compress data ([3795836](https://github.com/crimx/ext-saladict/commit/3795836)) +* **dicts:** fix shanbay typing warning ([99caa99](https://github.com/crimx/ext-saladict/commit/99caa99)) +* **dicts:** prevent in-panel search ([f88b960](https://github.com/crimx/ext-saladict/commit/f88b960)) +* **dicts:** remove float elements ([143b258](https://github.com/crimx/ext-saladict/commit/143b258)) +* **dicts:** typings ([bafe61c](https://github.com/crimx/ext-saladict/commit/bafe61c)) +* **manifest:** load pdf viewer under incognito mode ([5d57b25](https://github.com/crimx/ext-saladict/commit/5d57b25)) +* **menus:** prevent items being removed in incognito mode ([a380980](https://github.com/crimx/ext-saladict/commit/a380980)) +* **panel:** disable fav icon on options page ([c616149](https://github.com/crimx/ext-saladict/commit/c616149)) +* typings ([7f382a2](https://github.com/crimx/ext-saladict/commit/7f382a2)) +* **panel:** center panel vertically when word editor shows up ([c31b5fa](https://github.com/crimx/ext-saladict/commit/c31b5fa)), closes [#315](https://github.com/crimx/ext-saladict/issues/315) +* **panel:** max z-index for dict panel ([51b60d5](https://github.com/crimx/ext-saladict/commit/51b60d5)), closes [#316](https://github.com/crimx/ext-saladict/issues/316) +* **sync:** duration ([4785a71](https://github.com/crimx/ext-saladict/commit/4785a71)) + + +### Features + +* **dicts:** add shanbay dictionary ([95ee0d5](https://github.com/crimx/ext-saladict/commit/95ee0d5)) +* **panel:** add custom css ([4c58886](https://github.com/crimx/ext-saladict/commit/4c58886)) +* **sync:** add shanbay ([a7389d5](https://github.com/crimx/ext-saladict/commit/a7389d5)) + + +### Performance Improvements + +* cache lang checks ([5e3034e](https://github.com/crimx/ext-saladict/commit/5e3034e)) + + + <a name="6.26.0"></a> # [6.26.0](https://github.com/crimx/ext-saladict/compare/v6.25.1...v6.26.0) (2019-03-09) diff --git a/package.json b/package.json index 84200cb4c..fa132d7fb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "saladict", - "version": "6.26.0", + "version": "6.27.0", "description": "Chrome extension and Firefox WebExtension, inline translator powered by mutiple online dictionaries", "private": true, "scripts": {
chore
6.27.0
3d55b356b5410310d6adad1c8fb9f49740f7ea9a
2018-05-10 18:02:17
CRIMX
test(dicts): fix name
false
diff --git a/src/components/dictionaries/cobuild/engine.js b/src/components/dictionaries/cobuild/engine.ts similarity index 100% rename from src/components/dictionaries/cobuild/engine.js rename to src/components/dictionaries/cobuild/engine.ts diff --git a/test/specs/components/dictionaries/guoyu/engine.spec.ts b/test/specs/components/dictionaries/guoyu/engine.spec.ts index 005ae4007..449ccc81c 100644 --- a/test/specs/components/dictionaries/guoyu/engine.spec.ts +++ b/test/specs/components/dictionaries/guoyu/engine.spec.ts @@ -3,7 +3,7 @@ import { appConfigFactory } from '@/app-config' const fetchbak = window.fetch -describe('Dict/Google/engine', () => { +describe('Dict/GuoYu/engine', () => { beforeAll(() => { window.fetch = jest.fn((url: string) => Promise.resolve({ json: () => require('./response/愛.json')
test
fix name
b9d209b825f774d71b806a038473a6468b1fadc8
2020-01-06 16:08:32
crimx
fix(background): remove duplicated qs panel onclose response
false
diff --git a/src/background/server.ts b/src/background/server.ts index f868de762..05a0682c0 100644 --- a/src/background/server.ts +++ b/src/background/server.ts @@ -104,20 +104,6 @@ export class BackgroundServer { return this.youdaoTranslateAjax(msg.payload) } }) - - browser.windows.onRemoved.addListener(async winId => { - if (this.qsPanelManager.isQsPanel(winId)) { - this.qsPanelManager.destroy() - ;(await browser.tabs.query({})).forEach(tab => { - if (tab.id && tab.windowId !== winId) { - message.send(tab.id, { - type: 'QS_PANEL_CHANGED', - payload: false - }) - } - }) - } - }) } async openQSPanel(): Promise<void> { diff --git a/src/background/windows-manager.ts b/src/background/windows-manager.ts index 032eaf43c..a64dc81a7 100644 --- a/src/background/windows-manager.ts +++ b/src/background/windows-manager.ts @@ -174,6 +174,15 @@ export class QsPanelManager { } async destroy(): Promise<void> { + ;(await browser.tabs.query({})).forEach(tab => { + if (tab.id && tab.windowId !== this.qsPanelId) { + message.send(tab.id, { + type: 'QS_PANEL_CHANGED', + payload: false + }) + } + }) + this.qsPanelId = null this.isSidebar = false this.destroySnapshot()
fix
remove duplicated qs panel onclose response