Skip to content

Commit

Permalink
Merge pull request #60 from GDG-Xian/bugfix/mass_popups
Browse files Browse the repository at this point in the history
解决偶尔跳出一大堆翻译结果的 BUG
  • Loading branch information
greatghoul committed May 26, 2016
2 parents dc7ef35 + 0c31b93 commit 82438a5
Show file tree
Hide file tree
Showing 15 changed files with 198 additions and 175 deletions.
3 changes: 3 additions & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"esversion": 6
}
22 changes: 12 additions & 10 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ module.exports = function(grunt) {

grunt.initConfig({
browserify: {
options: {
transform: [['babelify', { 'presets': ['es2015'] }]]
},
default: {
files: [{
expand: true,
Expand All @@ -14,6 +17,9 @@ module.exports = function(grunt) {
}
},
jshint: {
options: {
jshintrc: true
},
files: ['src/js/**/*.js']
},
uglify: {
Expand Down Expand Up @@ -67,16 +73,12 @@ module.exports = function(grunt) {
tasks: ['sass'],
},
static: {
files: {
expand: true,
cwd: 'src/',
src: [
'img/**/*',
'*.html',
'manifest.json'
]
},
tasks: ['copy']
files: [
'src/img/**/*',
'src/*.html',
'src/manifest.json'
],
tasks: ['copy'],
}
},
compress: {
Expand Down
15 changes: 14 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"name": "crx-transit",
"devDependencies": {
"babel-preset-es2015": "^6.9.0",
"babelify": "latest",
"grunt": "^0.4.5",
"grunt-browserify": "^5.0.0",
"grunt-contrib-compress": "^1.1.1",
Expand All @@ -15,8 +17,19 @@
"angular-elastic": "^2.3.5",
"jquery": "^2.1.4",
"sugar": "^1.4.1",
"underscore": "^1.8.3",
"vinyl-source-stream": "^1.1.0",
"blueimp-md5": "^1.1.1"
},
"browserify": {
"transform": [
[
"babelify",
{
"presets": [
"es2015"
]
}
]
]
}
}
1 change: 1 addition & 0 deletions src/css/contentstyle.scss
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
.transit-notify {
z-index: 2147483647;
max-width: 250px;
min-width: 150px;
line-height: 1.5;
font-size: 14px;
margin-bottom: 5px;
Expand Down
4 changes: 2 additions & 2 deletions src/js/config/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ app.setup({
app.showUpdateNotes = function() {
chrome.notifications.create("update_notes", {
type: "list",
title: "TransIt V1.5.1 更新记录",
title: "TransIt V1.5.3 更新记录",
message: "",
iconUrl: "img/icon48.png",
items: [
{
title: '',
message: '解决开启链接划词模式会破坏某些网页布局的问题'
message: '解决有时会冒出一大堆翻译结果的 bug'
}
]
}, function () {});
Expand Down
96 changes: 37 additions & 59 deletions src/js/contentscript.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,15 @@
* jshint strict: true
*/

var $ = require('jquery');
var app = require('./config/application');
var notify = require('./lib/notify');
import $ from 'jquery';
import app from './config/application';
import notify from './lib/notify';
import { getSelection } from './lib/utils';

var capslockEvents = [];
let capslockEvents = [];

function getPosition(evt, selection) {
var rect = selection.getRangeAt(0).getBoundingClientRect();

// 如果是在文本框中,这个坐标返回的会为 0,此时应该取鼠标位置
if (rect.left === 0 && rect.top === 0) {
rect = { left: evt.clientX, top: evt.clientY, height: 15 };
}

var left = rect.left + document.body.scrollLeft;
var top = rect.top + document.body.scrollTop;

var clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
if (clientHeight === 0) {
clientHeight = document.documentElement.clientHeight;
}
if (rect.top >= 150) {
var bottom = clientHeight - top;
return { left: left, bottom: bottom };
} else {
return { left: left, top: top + rect.height + 5 };
}
function isInFrameset() {
return !!window.top.document.querySelector('frameset');
}

function toggleLinkInspectMode(evt) {
Expand All @@ -49,45 +31,41 @@ function toggleLinkInspectMode(evt) {
}
}

function transIt(evt) {
$('body').removeClass('translt-link-inspect-mode');

var selection = window.getSelection();
var text = $.trim(selection.toString());

if (!text) return;

// 如果页面划词开启,并且选中的文本符合划词的 PATTERN 才进行翻译
var message = {
type: 'selection',
mode: app.options.notifyMode,
text: text
};
function toggleLinkInspectMode(flag) {
$('body').toggleClass('translt-link-inspect-mode', flag);
}

chrome.runtime.sendMessage(message, function() {
notify(text, {
mode: 'in-place',
position: getPosition(evt, selection),
timeout: app.options.notifyTimeout,
});
});
// Inspect translation works only on word
function canTranslate(text) {
return /^[a-z]+(\'|\'s)?$/i.test(text);
}

function selectionlateHandler(request) {
notify(request.text, {
mode: 'margin',
timeout: app.options.notifyTimeout,
});
function selectionHandler(evt) {
toggleLinkInspectMode(false);

const selection = getSelection(evt);

if (selection) {
chrome.runtime.sendMessage({ type: 'selection', text: selection.text });

if (app.options.pageInspect && canTranslate(selection.text)) {
if (app.options.notifyMode == 'in-place' || isInFrameset()) {
notify(selection.text, {
mode: 'in-place',
position: selection.position,
timeout: app.options.notifyTimeout
});
} else {
top.notify(selection.text, {
mode: 'margin',
timeout: app.options.notifyTimeout
});
}
}
}
}

app.initOptions(function(options) {
$(document).on('keyup keydown', toggleLinkInspectMode);
$(document).on('mouseup', transIt);

// 仅在顶层页面接受 margin 显示结果
if (window == top) {
app.registerMessageDispatcher({
selection: selectionlateHandler
});
}
$(document).on('mouseup', selectionHandler);
});
56 changes: 29 additions & 27 deletions src/js/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,48 @@
var translators = require('./translators');
var app = require('./config/application');

window.currentText = '';

function getTranslator() {
return translators[app.options.translator];
// Key name to store current text in local storage
const CURRENT_TEXT_KEY = 'transit_current_text';

// Setter / Getter for current text
//
// If text if passed, update `current_text` in local storage,
// otherwise, read from local storage.
function currentText(text) {
if (text) {
localStorage.setItem(CURRENT_TEXT_KEY, text);
return text;
} else {
return localStorage.getItem(CURRENT_TEXT_KEY);
}
}

// 执行翻译动作
function translateHanlder(request, sender, sendResponse) {
// 如果翻译已经缓存起来了,则直接取缓存中的结果,不再向服务器发请求
// TODO 为翻译缓存提供简单统计 @greatghoul
currentText = request.text;

// 如果词为空,则不再翻译
if (!currentText) return;

// log('Translating', currentText, 'from', service.name);
getTranslator().translate(currentText, sendResponse);
// Translate text and send result back
//
// TODO: Cache translated result to speed up querying.
function translateHanlder(message, sender, sendResponse) {
const translator = translators[app.options.translator];
translator.translate(message.text, sendResponse);
}

// 划词翻译只翻译单词
// Inspect translation works only on word
function canTranslate(text) {
return /^[a-z]+(\'|\'s)?$/i.test(text);
}

function selectionHandler(request, sender, sendResponse) {
currentText = request.text;
app.log('Selection from page:', request.text);
// Save current selection to localStorage
function selectionHandler(message, sender, sendResponse) {
currentText(message.text);
}

if (app.options.pageInspect && canTranslate(currentText)) {
if (request.mode == 'margin') {
app.talkToPage(null, request);
} else {
sendResponse();
}
}
function currentTextHandler(message, sender, sendResponse) {
sendResponse(currentText());
}

app.registerMessageDispatcher({
translate: translateHanlder,
selection: selectionHandler
selection: selectionHandler,
currentText: currentTextHandler
});

app.initOptions();
Expand Down
14 changes: 7 additions & 7 deletions src/js/lib/crxkit.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
* jshint strict: true
*/

require('sugar');
import sugar from 'sugar';

var options = {};
var name = 'crxkit';
let options = {};
let name = 'crxkit';

function noop() {}

function registerMessageDispatcher(dispatcher) {
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
var handler = dispatcher[request.type] || noop;
handler(request, sender, sendResponse);
function(message, sender, sendResponse) {
const handler = dispatcher[message.type] || noop;
handler(message, sender, sendResponse);

return true;
}
Expand All @@ -24,7 +24,7 @@ function registerMessageDispatcher(dispatcher) {

function talkToPage(tabId, message, callback) {
if (tabId) {
chrome.tabs.sendMessage(tabId, message, callback);
chrome.tabs.sendMessage(tabId, message, callback);
} else {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
talkToPage(tabs[0].id, message, callback);
Expand Down
25 changes: 16 additions & 9 deletions src/js/lib/notify.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
var $ = require('jquery');
var sugar = require('sugar');
var utils = require('./utils');
import $ from 'jquery';
import sugar from 'sugar';
import {
stopPropagation,
clearSelection,
renderTranslation
} from './utils';

var notifyList = [];
var tpls = {
Expand Down Expand Up @@ -56,7 +60,7 @@ Notify.prototype.request = function() {
var message = { type: 'translate', text: self.text };

chrome.extension.sendMessage(message, function(response) {
var result = utils.renderTranslation(self.text, response);
var result = renderTranslation(self.text, response);
self.$el.find('.transit-notify-content').html(result);
self.bind();
self.hide();
Expand Down Expand Up @@ -86,7 +90,7 @@ Notify.prototype.bind = function() {
$close.click($.proxy(this.close, this));

// Prevent trigger transit event.
$close.mouseup(utils.stopPropagation);
$close.mouseup(stopPropagation);
};

// Hide the notify after configured seconds.
Expand All @@ -97,7 +101,7 @@ Notify.prototype.hide = function() {

// Close the notify immediately
Notify.prototype.close = function(event) {
utils.clearSelection();
clearSelection();
this.$el.fadeOut($.proxy(this.destroy, this));
};

Expand All @@ -107,8 +111,11 @@ Notify.prototype.destroy = function() {
this.$el.remove();
};

module.exports = function(text, mode, handler) {
const notify = function(text, options) {
if (!notifyList.find({ text: text })) {
notifyList.push(new Notify(text, mode, handler));
notifyList.push(new Notify(text, options));
}
};
};

window.notify = notify;
export default notify;
Loading

0 comments on commit 82438a5

Please sign in to comment.