Skip to content
This repository has been archived by the owner on Aug 16, 2022. It is now read-only.

Commit

Permalink
snap the selection to word
Browse files Browse the repository at this point in the history
  • Loading branch information
chunliu committed Jul 4, 2020
1 parent 26f4170 commit 48d2351
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 57 deletions.
49 changes: 41 additions & 8 deletions code/src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,42 @@
return success;
};

const sendMessageToCurrentTab = (message, data = null) => {
return new Promise((resolve, reject) => {
browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
browser.tabs.sendMessage(tabs[0].id, { message, data }, (response) => {
if (!response && browser.runtime.lastError) {
return reject(
new Error('Failed to connect to the specified tab.')
);
}
return resolve(response);
});
});
});
};

const injectScript = async () => {
try {
// If no error, the script has been injected.
await sendMessageToCurrentTab('is_ready');
} catch (err) {
await new Promise((resolve) => {
browser.tabs.insertCSS({ file: './content/msgbox.css' }, () => {
browser.tabs.executeScript({ file: './content/content.js' }, () => {
return resolve();
});
});
});
}
};

const getSelectedText = async () => {
await injectScript();
const response = await sendMessageToCurrentTab('get_selection');
return response.selection;
};

const quoteOnClick = async (info) => {
// Create the fragment link.
let directive = '#:~:text=';
Expand All @@ -36,7 +72,8 @@
directive = '&text=';
}

const fragmentLink = info.pageUrl + directive + await getFragment(info.selectionText);
const selectedText = await await getSelectedText();
const fragmentLink = info.pageUrl + directive + await getFragment(selectedText);

switch (info.menuItemId) {
case 'sttf_open': {
Expand All @@ -48,18 +85,14 @@
case 'sttf_copy': {
// Copy the link.
await copyToClipboard(fragmentLink);
browser.tabs.insertCSS({ file: './msgbox/msgbox.css' }, function () {
browser.tabs.executeScript({ file: './msgbox/msgbox.js' });
});
await sendMessageToCurrentTab('show_message');
break;
}
case 'sttf_copy_md': {
// Copy the selected text and the link as markdown.
const md = '[' + info.selectionText.trim() + '](' + fragmentLink + ')';
const md = '[' + selectedText + '](' + fragmentLink + ')';
await copyToClipboard(md);
browser.tabs.insertCSS({ file: './msgbox/msgbox.css' }, function () {
browser.tabs.executeScript({ file: './msgbox/msgbox.js' });
});
await sendMessageToCurrentTab('show_message');
break;
}
}
Expand Down
87 changes: 87 additions & 0 deletions code/src/content/content.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
((browser) => {
// Use fade in/out to display the message box
const fadeOut = (element) => {
var op = 1;
var timer = setInterval(function () {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
element.remove();
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ')';
op -= op * 0.1;
}, 10);
};

const fadeIn = (element) => {
var op = 0.1;
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ')';
op += op * 0.1;
}, 10);
};

const showMessageBox = () => {
let msgbox = document.querySelector('sttf-url-msg-box');
if (msgbox == null) {
// Create the message box element
const template = document.createElement('template');
template.innerHTML = '<div class="sttf-url-msg-box"><span class="helper"></span><div><p>The STTF link has been copied!</p></div></div>';

msgbox = template.content.firstChild;
document.body.append(msgbox);
}

fadeIn(msgbox);
setTimeout(fadeOut, 1000, msgbox);
};

// Based on: https://stackoverflow.com/a/7381574/6255000
const snapSelectionToWord = (sel) => {
if (!sel.isCollapsed) {
// Detect if selection is backwards
const range = document.createRange();
range.setStart(sel.anchorNode, sel.anchorOffset);
range.setEnd(sel.focusNode, sel.focusOffset);
const direction = range.collapsed ? ['backward', 'forward'] : ['forward', 'backward'];
range.detach();

// modify() works on the focus of the selection
const endNode = sel.focusNode;
const endOffset = sel.focusOffset;
sel.collapse(sel.anchorNode, sel.anchorOffset);
sel.modify('move', direction[0], 'character');
sel.modify('move', direction[1], 'word');
sel.extend(endNode, endOffset);
sel.modify('extend', direction[1], 'character');
sel.modify('extend', direction[0], 'word');
}
return sel.toString().trim();
};

browser.runtime.onMessage.addListener((request, _, sendResponse) => {
switch (request.message) {
case 'is_ready':
sendResponse('ready');
break;
case 'get_selection': {
const selection = window.getSelection();
const selectedText = snapSelectionToWord(selection);
sendResponse({ selection: selectedText });
break;
}
case 'show_message': {
showMessageBox();
sendResponse('shown');
break;
}
}
});
// eslint-disable-next-line no-undef
})(chrome || browser);
File renamed without changes.
2 changes: 1 addition & 1 deletion code/src/manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"manifest_version": 2,
"name": "STTF Url Generator",
"version": "1.1",
"version": "1.2",
"author": "Chun Liu",
"description": "Generate a url with text fragment and copy it to the clipboard or open it in a new tab.",
"permissions": [
Expand Down
46 changes: 0 additions & 46 deletions code/src/msgbox/msgbox.js

This file was deleted.

4 changes: 2 additions & 2 deletions code/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module.exports = {
context: path.resolve(__dirname, 'src'),
entry: {
background: './background.js',
'msgbox/msgbox': './msgbox/msgbox.js',
'content/content': './content/content.js',
'popup/popup': './popup/popup.js'
},
output: {
Expand All @@ -32,7 +32,7 @@ module.exports = {
new CopyWebpackPlugin({
patterns: [
{ from: './manifest.json', to: 'manifest.json' },
{ from: './msgbox/msgbox.css', to: 'msgbox/msgbox.css' },
{ from: './content/msgbox.css', to: 'content/msgbox.css' },
{ from: './popup/popup.html', to: 'popup/popup.html'},
{ from: './popup/popup.css', to: 'popup/popup.css'},
{ from: './images', to: 'images'}
Expand Down

0 comments on commit 48d2351

Please sign in to comment.