Meta: Bundle dependencies with Parcel (#187)

This commit is contained in:
Federico 2021-02-02 19:21:41 -06:00 committed by GitHub
parent 953b36cfa1
commit dde68fcec0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 20273 additions and 239 deletions

View File

@ -1,5 +1,5 @@
env:
DIRECTORY: browser
DIRECTORY: distribution
# FILE GENERATED WITH: npx ghat fregante/ghatemplates/webext/release.yml
# SOURCE: https://github.com/fregante/ghatemplates

3
.parcelrc Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "@parcel/config-webextension"
}

View File

@ -1,9 +0,0 @@
The MIT License (MIT)
Copyright (c) Federico Brigante <me@fregante.com> (fregante.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because one or more lines are too long

View File

@ -1,2 +0,0 @@
/*! npm.im/one-event */
var oneEvent=function(){"use strict";function e(e,n,t,r){e.addEventListener(n,t,r),e.addEventListener(n,function i(){e.removeEventListener(n,t,r),e.removeEventListener(n,i,r)},r)}return e.promise=function(n,t,r){return new Promise(function(i){return e(n,t,i,r)})},e}();

View File

@ -1,134 +0,0 @@
// https://github.com/bfred-it/webext-options-sync
class OptionsSync {
constructor(storageName = 'options') {
this.storageName = storageName;
}
define(defs) {
defs = Object.assign({
defaults: {},
migrations: [],
}, defs);
if (chrome.runtime.onInstalled) { // In background script
chrome.runtime.onInstalled.addListener(() => this._applyDefinition(defs));
} else { // In content script, discouraged
this._applyDefinition(defs);
}
}
async _applyDefinition(defs) {
const options = await this.getAll();
console.info('Existing options:', options);
if (defs.migrations.length > 0) {
console.info('Running', defs.migrations.length, 'migrations');
defs.migrations.forEach(migrate => migrate(options, defs.defaults));
}
const newOptions = Object.assign(defs.defaults, options);
this.setAll(newOptions);
}
_parseNumbers(options) {
for (const name of Object.keys(options)) {
if (options[name] === String(Number(options[name]))) {
options[name] = Number(options[name]);
}
}
return options;
}
getAll() {
return new Promise(resolve => {
chrome.storage.sync.get(this.storageName,
keys => resolve(keys[this.storageName] || {})
);
}).then(this._parseNumbers);
}
setAll(newOptions) {
return new Promise(resolve => {
chrome.storage.sync.set({
[this.storageName]: newOptions,
}, resolve);
});
}
async set(newOptions) {
const options = await this.getAll();
this.setAll(Object.assign(options, newOptions));
}
syncForm(form) {
if (typeof form === 'string') {
form = document.querySelector(form);
}
this.getAll().then(options => OptionsSync._applyToForm(options, form));
form.addEventListener('input', e => this._handleFormUpdates(e));
form.addEventListener('change', e => this._handleFormUpdates(e));
}
static _applyToForm(options, form) {
for (const name of Object.keys(options)) {
const els = form.querySelectorAll(`[name="${name}"]`);
const [field] = els;
if (field) {
console.info('Set option', name, 'to', options[name]);
switch (field.type) {
case 'checkbox':
field.checked = options[name];
break;
case 'radio': {
const [selected] = [...els].filter(el => el.value === options[name]);
if (selected) {
selected.checked = true;
}
break;
}
default:
field.value = options[name];
break;
}
} else {
console.warn('Stored option {', name, ':', options[name], '} was not found on the page');
}
}
}
_handleFormUpdates({target: el}) {
const name = el.name;
let value = el.value;
if (!name || !el.validity.valid) {
return;
}
switch (el.type) {
case 'select-one':
value = el.options[el.selectedIndex].value;
break;
case 'checkbox':
value = el.checked;
break;
default: break;
}
console.info('Saving option', el.name, 'to', value);
this.set({
[name]: value,
});
}
}
OptionsSync.migrations = {
removeUnused(options, defaults) {
for (const key of Object.keys(options)) {
if (!(key in defaults)) {
delete options[key];
}
}
}
};
if (typeof module === 'object') {
module.exports = OptionsSync;
}

20271
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,36 @@
{
"private": true,
"scripts": {
"test": "xo"
"build": "parcel build source/manifest.json --dist-dir distribution --no-cache --detailed-report 0",
"lint": "xo",
"test": "xo && npm run build",
"watch": "parcel watch source/manifest.json --dist-dir distribution --no-cache --no-hmr"
},
"browserslist": [
"last 1 Chrome version",
"last 1 Firefox version"
],
"xo": {
"envs": [
"browser",
"webextensions"
],
"globals": [
"oneEvent"
],
"ignores": [
"browser/vendor/*"
"source/humane-ghosttext.js"
],
"rules": {
"no-alert": "off"
}
},
"dependencies": {
"one-event": "^3.0.0",
"webext-options-sync": "^2.0.1",
"webextension-polyfill": "^0.7.0"
},
"devDependencies": {
"@parcel/config-webextension": "^2.0.0-nightly.2186",
"@parcel/transformer-webextension": "^2.0.0-nightly.2186",
"parcel": "^2.0.0-nightly.562",
"xo": "^0.37.1"
}
}

View File

@ -15,7 +15,7 @@ Follow the [instructions on the main README.md](https://github.com/GhostText/Gho
### Setup
Run this in the project root (outside the folder `browser`):
Run this in the project root:
```sh
npm install
@ -30,11 +30,11 @@ npm run watch
2. Visit `chrome://extensions/` in Chrome
3. Enable the **Developer mode** in the upper-right corner
4. Use the "Load unpacked extension…" button on the left
5. Select the folder `browser` inside your newly cloned project
5. Select the folder `distribution` inside your newly cloned project
### On Firefox
1. Clone **GhostText** on your computer with `git clone https://github.com/GhostText/GhostText.git`
2. Visit `about:debugging#addons` in Firefox
3. Click on **Load Temporary Add-on**
4. Select the file `browser/manifest.json` inside your newly cloned project
4. Select the file `distribution/manifest.json` inside your newly cloned project

View File

@ -1,6 +1,8 @@
/* globals OptionsSync */
const optionsStorage = new OptionsSync();
optionsStorage.define({
import browser from 'webextension-polyfill';
import oneEvent from 'one-event';
import OptionsSync from 'webext-options-sync';
const optionsStorage = new OptionsSync({
defaults: {
serverPort: 4001
}
@ -35,13 +37,8 @@ async function handleAction({id}) {
try {
await Promise.all([
browser.tabs.insertCSS(id, {...defaults, file: '/scripts/ghost-text.css'}),
browser.tabs.insertCSS(id, {...defaults, file: '/vendor/humane-ghosttext.css'}),
browser.tabs.executeScript(id, {...defaults, file: '/vendor/webext-options-sync.js'}),
browser.tabs.executeScript(id, {...defaults, file: '/vendor/humane-ghosttext.js'}),
browser.tabs.executeScript(id, {...defaults, file: '/vendor/one-event.browser.js'}),
browser.tabs.executeScript(id, {...defaults, file: '/scripts/unsafe-messenger.js'}),
browser.tabs.executeScript(id, {...defaults, file: '/scripts/ghost-text.js'})
browser.tabs.insertCSS(id, {...defaults, file: '/ghost-text.css'}),
browser.tabs.executeScript(id, {...defaults, file: '/ghost-text.js'})
]);
} catch (error) {
console.error(error);
@ -77,8 +74,8 @@ chrome.runtime.onConnect.addListener(handlePortListenerErrors(async port => {
console.log('will open socket');
const socket = new WebSocket('ws://localhost:' + WebSocketPort);
const event = await Promise.race([
oneEvent.promise(socket, 'open'),
oneEvent.promise(socket, 'error')
oneEvent(socket, 'open'),
oneEvent(socket, 'error')
]);
console.log(event);

View File

@ -1,3 +1,5 @@
@import './humane-ghosttext.css';
[data-gt-field] {
transition: box-shadow 1s cubic-bezier(0.25, 2, 0.5, 1);
}

View File

@ -1,4 +1,5 @@
/* global GThumane */
import GThumane from './humane-ghosttext.js';
import unsafeMessenger from './unsafe-messenger.js';
const knownElements = new Map();
const activeFields = new Set();
@ -305,7 +306,7 @@ function stopGT() {
function init() {
const script = document.createElement('script');
script.textContent = '(' + window.unsafeMessenger.toString() + ')()';
script.textContent = '(' + unsafeMessenger.toString() + ')()';
document.head.append(script);
}

View File

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.7 KiB

View File

Before

Width:  |  Height:  |  Size: 803 B

After

Width:  |  Height:  |  Size: 803 B

View File

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -44,15 +44,12 @@
}
}
},
"content_scripts": [{
"matches": ["http://localhost:4001/*"],
"js": ["ghost-text.js"],
"css": ["ghost-text.css"]
}],
"background": {
"scripts": [
"vendor/webext-options-sync.js",
"vendor/browser-polyfill.min.js",
"vendor/one-event.browser.js",
"scripts/background.js"
]
},
"web_accessible_resources": [
"scripts/unsafe-messenger.js"
]
"scripts": ["background.js"]
}
}

View File

@ -42,5 +42,4 @@
Issues? Lets fix them on
<a href="https://github.com/GhostText/GhostText">GhostTexts GitHub repo</a>!
</footer>
<script src="vendor/webext-options-sync.js"></script>
<script src="scripts/options.js"></script>
<script src="options.js"></script>

View File

@ -1,2 +1,3 @@
/* globals OptionsSync */
import OptionsSync from 'webext-options-sync';
new OptionsSync().syncForm(document.querySelector('form'));

View File

@ -3,7 +3,7 @@
* as "unsafe" code, bridging the extension's sandbox and the website's libraries.
*/
window.unsafeMessenger = function () {
export default function unsafeMessenger() {
document.body.addEventListener('gt:get', listener);
function listener({target}) {
@ -73,7 +73,7 @@ window.unsafeMessenger = function () {
editor.blur();
});
}
};
}
// eslint-disable-next-line no-unused-expressions
undefined; // Avoids issues with tabs.injectScript