Skip to content

Commit

Permalink
customize worker-dom
Browse files Browse the repository at this point in the history
  • Loading branch information
kazupon committed Mar 18, 2021
1 parent b7c11b3 commit 7c5596e
Show file tree
Hide file tree
Showing 17 changed files with 512 additions and 189 deletions.
1 change: 0 additions & 1 deletion CODE_OF_CONDUCT.md

This file was deleted.

27 changes: 0 additions & 27 deletions CONTRIBUTING.md

This file was deleted.

1 change: 0 additions & 1 deletion OWNERS.yaml

This file was deleted.

147 changes: 59 additions & 88 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,119 +1,90 @@
# WorkerDOM

An in-progress implementation of the DOM API intended to run within a Web Worker.
## What's difference from Original?

**Purpose**: Move complexity of intermediate work related to DOM mutations to a background thread, sending only the necessary manipulations to a foreground thread.
- Define the useful APIs from [@mizchi/worker-dom](https://github.com/mizchi/worker-dom)
- Can be modified the DOM with your Web Worker

**Use Cases**:
1. Embedded content from a third party living side by side with first party code.
2. Mitigation of expensive rendering for content not requiring synchronous updates to user actions.
3. Retaining main thread availablity for high priority updates by async updating elsewhere in a document.
### Installation

For more information, visit our [blog post](https://bit.ly/worker-dom-blog) announcing WorkerDOM or checkout the [slides](https://bit.ly/worker-dom-slides) from the announcement at JSConf US.

## Installation

```bash
npm install @ampproject/worker-dom
```sh
npm install @intlify/worker-dom --save
```

## Usage
### APIs
- `attachWorker(element: HTMLElement, worker: Worker): Promise<ExportedWoker>` on main-thread
- `ready` on worker to connect `attachWorker`.

WorkerDOM comes in two flavours, a global variant and a module variant. It is possible to include the WorkerDOM main thread code within your document directly or via a bundler. Here's how you might do so directly:
### Example for Vite

```html
<script src="path/to/workerdom/dist/main.mjs" type="module"></script>
<script src="path/to/workerdom/dist/main.js" nomodule defer></script>
```
```js
// worker.js
import { ready, exportFunction } from '@intlify/worker-dom/dist/lib/worker';

WorkerDOM allows us to upgrade a specific section of the document to be driven by a worker. For example, imagine a `div` node in the page like so:
// define your functions on worker
function add(a, b) {
const ret = a + b
const el = document.createElement('p')
el.textContent = ret.toString()
document.body.appendChild(el)
return ret
}

```html
<div src="hello-world.js" id="upgrade-me"></div>
```
// export worker functions
[add].map(fn => exportFunction(fn.name, fn))

To upgrade this node using the module version of the code, we can directly import `upgradeElement` and use it like this:
// wait for ready
await ready;

```html
<script type="module">
import {upgradeElement} from './dist/main.mjs';
upgradeElement(document.getElementById('upgrade-me'), './dist/worker/worker.mjs');
</script>
// should keep same content with main-thread on init.
document.body.firstChild.textContent = 'hello from worker mutate';
```

The nomodule format exposes the global `MainThread`, and could upgrade the `div` in the following way:

```html
<script nomodule async=false defer>
document.addEventListener('DOMContentLoaded', function() {
MainThread.upgradeElement(document.getElementById('upgrade-me'), './dist/worker/worker.js');
}, false);
</script>
```

### AMP Distribution for `amp-script`
```js
// main.js
import { attachWorker } from '@intlify/worker-dom/dist/lib/main';
import Worker from './woker?worker';

WorkerDOM has a special output variant that supplies additional hooks for safety features e.g. HTML sanitization. This variant is distributed under the amp folder for main and worker thread binaries:
// attach worker to dom
const worker = await attachWorker(document.querySelector('#root'), new Worker());

// call function that is exported from worker
const result = await woker.callFunction('add', 1, 1)
```
amp/main.mjs
amp/worker/worker.mjs
```

This output assumes the consumer will compile this distributed JavaScript to ensure it works with older `user-agent`s.

### Debug Distribution

WorkerDOM also has an output variant that includes additional debugging messages. This variant is distributed in the debug folder.
### Example for Webpack

```
debug/main.mjs
debug/main.js
debug/worker/worker.mjs
debug/worker/worker.js
```js
// webpack.config.js
const WorkerPlugin = require("worker-plugin");
module.exports = {
// ...
plugins: [new WorkerPlugin()]
}
```

## Running Demos Locally
```js
// worker.js
import { ready } from "@intlify/worker-dom/dist/lib/worker";

After cloning the repository, you can try out the debug demos with the following.

```bash
npm run demo
ready.then(() =>{
// should keep same content with main-thread on init.
document.body.firstChild.textContent = 'hello from worker mutate';
});
```

This script will build the current version of WorkerDOM and start up a local [webserver](http://localhost:3001).

## Which JavaScript APIs can I use?

Currently, most DOM elements and their properties are supported. DOM query APIs like `querySelector` have partial support. Browser APIs like History are not implemented yet. Please see the API support matrix [here](web_compat_table.md).
```js
// main.js
import { attachWorker } from "@intlify/worker-dom/dist/lib/main";

## Which Browsers are supported?
// Create worker by your own way
const worker = new Worker("./worker.js", { type: "module" });

In general we support the latest two versions of major browsers like Chrome, Firefox, Edge, Safari, Opera and UC Browser. We support desktop, phone, tablet and the web view version of these respective browsers.

Beyond that, we aim for very wide browser support and we accept fixes for all browsers with market share greater than 1 percent.

In particular, we try to maintain "it might not be perfect but isn't broken"-support for IE 11, iOS 8, the Android 4.0 system browser and Chrome 41.

## Local Development

Local development of WorkerDOM assumes the following:
1. Familiarity with `npm` or `yarn`
2. Latest LTS release of Node (10 at time of writing) available.
3. Comfort with TypeScript, the codebase and tests are entirely written in TypeScript.

## Release Log

Each release includes a log of changes with the newly released version. You can find the log here: https://github.com/ampproject/worker-dom/releases

## Security disclosures

The AMP Project accepts responsible security disclosures through the [Google Application Security program](https://www.google.com/about/appsecurity/).

## Code of conduct

The AMP Project strives for a positive and growing project community that provides a safe environment for everyone. All members, committers and volunteers in the community are required to act according to the [code of conduct](CODE_OF_CONDUCT.md).
// attach worker to dom
attachWorker(document.querySelector('#root'), worker);
```

## License
## LICENSE

worker-dom is licensed under the [Apache License, Version 2.0](LICENSE).
16 changes: 0 additions & 16 deletions RELEASING.md

This file was deleted.

8 changes: 7 additions & 1 deletion config/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
* limitations under the License.
*/

/**
* Modified by mizchi
* https://github.com/mizchi/worker-dom/blob/7f8b0295b757f1988e853c79858af682e850c312/config/rollup.config.js#L19-L21
*/

import MainThreadBuilds from './rollup.main-thread.js';
import WorkerThreadBuilds from './rollup.worker-thread.js';
import LibBuilds from './rollup.lib.js';

export default [...MainThreadBuilds, ...WorkerThreadBuilds];
export default [...MainThreadBuilds, ...WorkerThreadBuilds, ...LibBuilds];
80 changes: 80 additions & 0 deletions config/rollup.lib.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* Copyright 2021 The Intlify Project Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* This code is written by mizchi
* Modified by kazuya kawkaguchi
* https://github.com/mizchi/worker-dom/blob/main/config/rollup.lib.js
*/

import compiler from '@ampproject/rollup-plugin-closure-compiler';
import { terser } from 'rollup-plugin-terser';
import replace from '@rollup/plugin-replace';
import { babelPlugin } from './rollup.plugins.js';
import path from 'path';

// Compile plugins should always be added at the end of the plugin list.
const compilePlugins = [
compiler({
env: 'CUSTOM',
}),
terser(),
];

export default [
{
input: path.join(__dirname, '../output/main-thread/lib.js'),
output: {
file: 'dist/lib/main.mjs',
format: 'esm',
sourcemap: true,
},
plugins: [
replace({
values: {
WORKER_DOM_DEBUG: false,
},
preventAssignment: true,
}),
babelPlugin({
transpileToES5: false,
allowConsole: true,
}),
...compilePlugins,
],
},
{
input: path.join(__dirname, '../output/worker-thread/lib.js'),
output: {
file: 'dist/lib/worker.mjs',
format: 'esm',
sourcemap: true,
},
plugins: [
replace({
values: {
WORKER_DOM_DEBUG: false,
},
preventAssignment: true,
}),
babelPlugin({
transpileToES5: false,
allowConsole: true,
}),
...compilePlugins,
],
},
];
4 changes: 4 additions & 0 deletions demo/vite/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
.DS_Store
dist
*.local
15 changes: 15 additions & 0 deletions demo/vite/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app">
<h1>main</h1>
<button>click</button>
</div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
14 changes: 14 additions & 0 deletions demo/vite/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "vite",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"devDependencies": {
"typescript": "^4.2.3",
"vite": "^2.1.2"
}
}
14 changes: 14 additions & 0 deletions demo/vite/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { attachWorker } from '@intlify/worker-dom/dist/lib/main.mjs'
import Worker from './worker?worker'

;(async () => {
const el = document.getElementById('app')
const worker = new Worker()
const exportedWorker = await attachWorker(el, worker)

const button = document.querySelector('button')
button.onclick = async (ev) => {
const val = await exportedWorker.callFunction('addElement', 'hello wokrer-dom')
console.log('result', val)
}
})();
Loading

0 comments on commit 7c5596e

Please sign in to comment.