Skip to content

Commit

Permalink
code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ttop32 committed Nov 3, 2023
1 parent 60220fe commit 227676e
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 105 deletions.
38 changes: 19 additions & 19 deletions .github/workflows/releases.yml
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
name: Releases

on:
on:
push:
tags:
- '*'
- "*"

jobs:

build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x]
matrix:
node-version: [18.x]
permissions:
contents: write
steps:
- uses: actions/checkout@v3

- uses: actions/checkout@v3

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build-zip-en

- name: Write package version json
run: cat <<< $(jq '.version=${{github.ref_name}}' package.json ) > package.json
- name: Write manifest version json
run: cat <<< $(jq '.version=${{github.ref_name}}' public/manifest.json ) > public/manifest.json

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build-zip-en

- uses: ncipollo/release-action@v1
with:
artifacts: "mouse_tooltip_translator_*.zip"
body: "[Change Log](https://github.com/ttop32/MouseTooltipTranslator/blob/main/doc/description.md#change-log)"

- uses: ncipollo/release-action@v1
with:
artifacts: "mouse_tooltip_translator_*.zip"
body: "[Change Log](https://github.com/ttop32/MouseTooltipTranslator/blob/main/doc/description.md#change-log)"
9 changes: 1 addition & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ download from [chrome web store](https://chrome.google.com/webstore/detail/mouse
[<img alt="chrome web store" width="128px" src="doc/google.png" />](https://chrome.google.com/webstore/detail/mouse-tooltip-translator/hmigninkgibhdckiaphhmbgcghochdjc?hl=en)
[<img alt="microsoft store" width="128px" src="doc/microsoft.png" />](https://microsoftedge.microsoft.com/addons/detail/mouse-tooltip-translator/nnodgmifnfgkolmakhcfkkbbjjcobhbl)
[<img alt="softpedia" width="128px" src="doc/softpedia.png" />](https://www.softpedia.com/get/Internet/Internet-Applications-Addons/Chrome-Extensions/Mouse-Tooltip-Translator-for-Chrome.shtml)

# Result

![Alt Text](doc/result_0.gif)
Expand Down Expand Up @@ -64,13 +64,6 @@ download from [chrome web store](https://chrome.google.com/webstore/detail/mouse
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/michael-nhat">
<img src="https://avatars.githubusercontent.com/u/66666570?v=4" width="100;" alt="michael-nhat"/>
<br />
<sub><b>Hoang Van Nhat</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/netanel123123">
<img src="https://avatars.githubusercontent.com/u/81083157?v=4" width="100;" alt="netanel123123"/>
Expand Down
2 changes: 2 additions & 0 deletions doc/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ English, Russian, Japanese, Chinese and so on

# Change Log

- 0.1.89
- add pdf shortcut for note & draw (contributed by michael-nhat)
- 0.1.89
- fix youtube embed conflict (request by BH J)
- 0.1.88
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

66 changes: 23 additions & 43 deletions src/contentScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@

import $ from "jquery";
import "bootstrap/js/dist/tooltip";
import {
enableSelectionEndEvent,
triggerSelectionEnd,
} from "/src/event/selection";
import {
enableMouseoverTextEvent,
triggerMouseoverText,
} from "/src/event/mouseover";
import { enableSelectionEndEvent } from "/src/event/selection";
import { enableMouseoverTextEvent } from "/src/event/mouseover";
import { encode } from "he";
import matchUrl from "match-url-wildcard";
import * as util from "/src/util";
Expand Down Expand Up @@ -74,8 +68,8 @@ function startMouseoverDetector() {
!selectedText &&
setting["translateWhen"].includes("mouseover")
) {
var word = getTextFromRange(event.range, event.isIframe);
await processWord(word, "mouseover");
var mouseoverText = event.mouseoverText[getDetectType()];
await processWord(mouseoverText, "mouseover");
}
});
}
Expand All @@ -98,7 +92,7 @@ async function processWord(word, actionType) {
if (checkMouseTargetIsTooltip()) {
return;
}
word = util.filterWord(word); //filter out one that is url,over 1000length,no normal char
word = util.filterWord(word); //filter out one that is url,no normal char

//hide tooltip, if activated word exist and current word is none
//do nothing, if no new word or no word change
Expand Down Expand Up @@ -163,12 +157,7 @@ function restartWordProcess() {
}
}

function getTextFromRange(range, isIframe) {
if (!range) {
return "";
}

//expand char to get word,sentence based on setting
function getDetectType() {
//if swap key pressed, swap detect type
//if mouse target is special web block, handle as block
var detectType = setting["detectType"];
Expand All @@ -177,27 +166,9 @@ function getTextFromRange(range, isIframe) {
? "sentence"
: "word"
: detectType;
detectType = checkMouseTargetIsSpecialWebBlock() ? "container" : detectType;
expandRange(range, detectType);

if (!isIframe && !util.checkXYInElement(range, clientX, clientY)) {
return "";
}
return range.toString();
}

function expandRange(range, type) {
try {
if (type == "container") {
range.setStartBefore(range.startContainer);
range.setEndAfter(range.startContainer);
range.setStart(range.startContainer, 0);
} else {
range.expand(type); // "word" or "sentence"
}
} catch (error) {
console.log(error);
}
detectType = checkMouseTargetIsSpecialWebBlock() ? "container" : detectType;
return detectType;
}

function checkMouseTargetIsSpecialWebBlock() {
Expand Down Expand Up @@ -569,17 +540,17 @@ function applyStyleSetting() {
visibility: visible !important;
pointer-events: none !important;
}
.bootstrapiso .bs-tooltip-top {
.bootstrapiso .bs-tooltip-top {
margin-bottom: ${setting["tooltipDistance"]}px !important;
}
.bootstrapiso .bs-tooltip-bottom {
.bootstrapiso .bs-tooltip-bottom {
margin-top: ${setting["tooltipDistance"]}px !important;
}
.bootstrapiso .tooltip-inner {
font-size: ${setting["tooltipFontSize"]}px !important;
max-width: ${setting["tooltipWidth"]}px !important;
text-align: ${setting["tooltipTextAlign"]} !important;
backdrop-filter: blur(${setting["tooltipBackgroundBlur"]}px) !important;
backdrop-filter: blur(${setting["tooltipBackgroundBlur"]}px) !important;
background-color: ${setting["tooltipBackgroundColor"]} !important;
color: ${setting["tooltipFontColor"]} !important;
pointer-events: auto;
Expand Down Expand Up @@ -692,10 +663,19 @@ async function checkYoutube() {
async function addCaptionButtonListener() {
await delay(2000);
$(".ytp-subtitles-button").on("click", (e) => {
var captionOnStatusByUser = e.target.getAttribute("aria-pressed");
setting["captionOnStatusByUser"] = captionOnStatusByUser;
setting.save();
handleCaptionOnOff();
});
$(document).on("keydown", (e) => {
if (e.code == "KeyC") {
handleCaptionOnOff();
}
});
}

function handleCaptionOnOff() {
var captionOnStatusByUser = $(".ytp-subtitles-button").attr("aria-pressed");
setting["captionOnStatusByUser"] = captionOnStatusByUser;
setting.save();
}

function pausePlayer() {
Expand Down
13 changes: 7 additions & 6 deletions src/ebook/ebookEventInject.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import * as util from "/src/util/index.js";
import { enableSelectionEndEvent } from "/src/event/selection";
import { enableMouseoverTextEvent } from "/src/event/mouseover";
import { waitUntil, WAIT_FOREVER } from "async-wait-until";

var iframeSrc = "";

Expand All @@ -21,24 +19,27 @@ function getIframe() {
}

function bindIFrameEvent(iframe) {
//bind text selection
enableSelectionEndEvent(iframe.contentWindow);
enableMouseoverTextEvent(iframe.contentWindow, true);

// bind mouse event
["mousemove", "keydown", "keyup", "mouseup"].forEach((eventName) => {
// bind mouse for mouse over event
["mousemove"].forEach((eventName) => {
iframe.contentWindow.addEventListener(eventName, (e) => {
var evt = new CustomEvent(eventName, {
bubbles: true,
cancelable: false,
});
var clRect = iframe.getBoundingClientRect();

evt.ebookWindow = iframe.contentWindow;
evt.key = e?.key;
evt.code = e?.code;
evt.ctrlKey = e?.ctrlKey;
evt.clientX = e?.clientX ? e.clientX + clRect.left : "";
evt.clientY = e?.clientY ? e.clientY + clRect.top : "";

evt.iframeX = e?.clientX;
evt.iframeY = e?.clientY;

window.dispatchEvent(evt);
});
});
Expand Down
93 changes: 66 additions & 27 deletions src/event/mouseover.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,91 @@
/**
* Selection related functions
*/
// get mouse over text using range
// 1. get mouse xy
// 2. get range from overlapped xy element
// 3. expand range for char -> string
// 4. range to text

import { throttle } from "throttle-debounce";
import * as util from "/src/util";

var clientX = 0;
var clientY = 0;
var mouseTarget;
var _win;
var _isIframe;
var _isIframe = false;

export function enableMouseoverTextEvent(_window = window, isIframe) {
export function enableMouseoverTextEvent(_window = window) {
_win = _window;
_isIframe = isIframe;

// Listen mouse move and scroll events
["scroll", "wheel", "keydown", "mousemove"].forEach((eventType) => {
_win.document.addEventListener(eventType, (e) => {
triggerMouseoverText(getMouseoverRange(clientX, clientY));
});
});
setInterval(() => {
triggerMouseoverText(getMouseoverText(clientX, clientY));
}, 700);

_win.document.addEventListener("mousemove", (e) => {
setMouseStatus(e);
window.addEventListener("mousemove", (e) => {
//if is ebook viewer event, take ebook window
if (e.ebookWindow) {
_win = e.ebookWindow;
_isIframe = true;
clientX = e.iframeX;
clientY = e.iframeY;
}
if (_isIframe == true) {
return;
}
//else record mouse xy
clientX = e.clientX;
clientY = e.clientY;
});
}

export const triggerMouseoverText = throttle(700, (range) => {
export const triggerMouseoverText = (mouseoverText) => {
var evt = new CustomEvent("mouseoverText", {
bubbles: true,
cancelable: false,
});
evt.range = range;
evt.isIframe = _isIframe;
evt.mouseoverText = mouseoverText;
document.dispatchEvent(evt);
});

function setMouseStatus(e) {
clientX = e.clientX;
clientY = e.clientY;
mouseTarget = e.target;
}
};

function getMouseoverRange(x, y) {
function getMouseoverText(x, y) {
//get range
var range =
util.caretRangeFromPoint(x, y, _win.document) ||
util.caretRangeFromPointOnShadowDom(x, y);

return range;
//get text from range
var mouseoverText = getTextFromRange(range);
return mouseoverText;
}

function getTextFromRange(range) {
var output = {};

["word", "sentence", "container"].forEach((detectType) => {
if (range) {
//expand range
expandRange(range, detectType);

//check mouse xy overlap the range element
if (util.checkXYInElement(range, clientX, clientY)) {
output[detectType] = range.toString();
}
}

output[detectType] = output[detectType] || ""; //if no text, give empty ""
});

return output;
}

function expandRange(range, type) {
try {
if (type == "container") {
range.setStartBefore(range.startContainer);
range.setEndAfter(range.startContainer);
range.setStart(range.startContainer, 0);
} else {
range.expand(type); // "word" or "sentence"
}
} catch (error) {
console.log(error);
}
}
1 change: 1 addition & 0 deletions src/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ export function filterWord(word) {
// filter one that only include num,space and special char(include currency sign) as combination
word = word.replace(/\s+/g, " "); //replace whitespace as single space
word = word.trim(); // remove whitespaces from begin and end of word
// word=word.slice(0,1000);
if (
word.length > 1000 || //filter out text that has over 1000length
isUrl(word) || //if it is url
Expand Down

0 comments on commit 227676e

Please sign in to comment.