Skip to content

Commit

Permalink
feat(context): add context menus saladict search #152
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Jul 7, 2018
1 parent 1627eb1 commit 6125ca8
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 16 deletions.
5 changes: 5 additions & 0 deletions src/_locales/context/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,11 @@
"zh_CN": "牛津词典",
"zh_TW": "牛津字典"
},
"saladict": {
"en": "Saladict",
"zh_CN": "沙拉查词",
"zh_TW": "沙拉查詞"
},
"sogou": {
"en": "Sogou Translate",
"zh_CN": "搜狗翻译",
Expand Down
1 change: 1 addition & 0 deletions src/app-config/context-menus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export function getAllContextMenus () {
merriam_webster: 'http://www.merriam-webster.com/dictionary/%s',
microsoft_page_translate: 'x',
oxford: 'http://www.oxforddictionaries.com/us/definition/english/%s',
saladict: 'x',
sogou_page_translate: 'x',
sogou: 'https://fanyi.sogou.com/#auto/zh-CHS/%s',
youdao_page_translate: 'x',
Expand Down
15 changes: 14 additions & 1 deletion src/background/context-menus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { storage, openURL, StorageUpdate } from '@/_helpers/browser-api'
import { message, storage, openURL, StorageUpdate } from '@/_helpers/browser-api'
import { MsgType } from '@/typings/message'
import { AppConfig } from '@/app-config'
import i18nLoader from '@/_helpers/i18n'
import { TranslationFunction } from 'i18next'
Expand Down Expand Up @@ -64,6 +65,9 @@ browser.contextMenus.onClicked.addListener(info => {
case 'notebook':
openURL(browser.runtime.getURL('notebook.html'))
break
case 'saladict':
requestSelection()
break
default:
storage.sync.get('config')
.then(result => {
Expand Down Expand Up @@ -210,6 +214,15 @@ export function openMicrosoftPage () {
})
}

function requestSelection () {
browser.tabs.query({ active: true, currentWindow: true })
.then(tabs => {
if (tabs.length > 0 && tabs[0].id != null) {
message.send(tabs[0].id as number, { type: MsgType.EmitSelection })
}
})
}

function setContextMenus (
contextMenus: ContextMenusConfig,
t: TranslationFunction
Expand Down
66 changes: 51 additions & 15 deletions src/selection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,49 @@ import { startWith } from 'rxjs/operators/startWith'
import { pluck } from 'rxjs/operators/pluck'
import { combineLatest } from 'rxjs/observable/combineLatest'

message.addListener(MsgType.__PreloadSelection__, () => {
return Promise.resolve(selection.getSelectionInfo())
let config = appConfigFactory()
createAppConfigStream().subscribe(newConfig => config = newConfig)

let clickPeriodCount = 0
let lastMousedownEvent: MouseEvent | TouchEvent | null

/**
* Beware that this is run on every frame
*/
message.addListener(msg => {
switch (msg.type) {
case MsgType.PreloadSelection:
if (selection.getSelectionText()) {
return Promise.resolve(selection.getSelectionInfo())
}
break
case MsgType.EmitSelection:
if (lastMousedownEvent) {
const text = selection.getSelectionText()
if (text) {
const { clientX, clientY } = lastMousedownEvent instanceof MouseEvent
? lastMousedownEvent
: lastMousedownEvent.changedTouches[0]
sendMessage({
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: ''
},
})
}
}
break
default:
break
}
})

/** Pass through message from iframes */
Expand All @@ -48,12 +89,6 @@ window.addEventListener('message', ({ data, source }: { data: PostMsgSelection,
sendMessage(msg)
})

let config = appConfigFactory()
createAppConfigStream().subscribe(newConfig => config = newConfig)

let clickPeriodCount = 0
let lastMousedownTarget: EventTarget | null

/**
* Pressing ctrl/command key more than three times within 500ms
* trigers TripleCtrl
Expand All @@ -76,8 +111,8 @@ validCtrlPressed$$.pipe(
merge(
fromEvent<MouseEvent>(window, 'mousedown', { capture: true }),
fromEvent<TouchEvent>(window, 'touchstart', { capture: true }),
).subscribe(({ target }) => {
lastMousedownTarget = target
).subscribe(evt => {
lastMousedownEvent = evt
})

/**
Expand Down Expand Up @@ -137,7 +172,7 @@ isKeyPressed(isEscapeKey).subscribe(flag => {
let lastText: string
let lastContext: string
validMouseup$$.subscribe(event => {
if (config.noTypeField && isTypeField(lastMousedownTarget)) {
if (config.noTypeField && isTypeField(lastMousedownEvent)) {
sendEmptyMessage()
return
}
Expand Down Expand Up @@ -333,15 +368,16 @@ function isKeyPressed (keySelectior: (e: KeyboardEvent) => boolean): Observable<
)
}

function isTypeField (traget: EventTarget | null): boolean {
if (traget) {
if (traget['tagName'] === 'INPUT' || traget['tagName'] === 'TEXTAREA') {
function isTypeField (event: MouseEvent | TouchEvent | null): boolean {
if (event && event.target) {
const target = event.target
if (target['tagName'] === 'INPUT' || target['tagName'] === 'TEXTAREA') {
return true
}

const editorTester = /CodeMirror|ace_editor|monaco-editor/
// Popular code editors CodeMirror, ACE and Monaco
for (let el = traget as Element | null; el; el = el.parentElement) {
for (let el = target 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)) {
Expand Down
3 changes: 3 additions & 0 deletions src/typings/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ export const enum MsgType {
/** Query panel state */
QueryPanelState,

/** Manually emit selection event */
EmitSelection,

/**
* Background proxy sends back underlyingly
*/
Expand Down

0 comments on commit 6125ca8

Please sign in to comment.