Skip to content

Commit 7c5596e

Browse files
committed
customize worker-dom
1 parent b7c11b3 commit 7c5596e

17 files changed

+512
-189
lines changed

CODE_OF_CONDUCT.md

-1
This file was deleted.

CONTRIBUTING.md

-27
This file was deleted.

OWNERS.yaml

-1
This file was deleted.

README.md

+59-88
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,90 @@
11
# WorkerDOM
22

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

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

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

12-
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.
13-
14-
## Installation
15-
16-
```bash
17-
npm install @ampproject/worker-dom
10+
```sh
11+
npm install @intlify/worker-dom --save
1812
```
1913

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

22-
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:
18+
### Example for Vite
2319

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

29-
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:
24+
// define your functions on worker
25+
function add(a, b) {
26+
const ret = a + b
27+
const el = document.createElement('p')
28+
el.textContent = ret.toString()
29+
document.body.appendChild(el)
30+
return ret
31+
}
3032

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

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

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

44-
The nomodule format exposes the global `MainThread`, and could upgrade the `div` in the following way:
45-
46-
```html
47-
<script nomodule async=false defer>
48-
document.addEventListener('DOMContentLoaded', function() {
49-
MainThread.upgradeElement(document.getElementById('upgrade-me'), './dist/worker/worker.js');
50-
}, false);
51-
</script>
52-
```
53-
54-
### AMP Distribution for `amp-script`
43+
```js
44+
// main.js
45+
import { attachWorker } from '@intlify/worker-dom/dist/lib/main';
46+
import Worker from './woker?worker';
5547

56-
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:
48+
// attach worker to dom
49+
const worker = await attachWorker(document.querySelector('#root'), new Worker());
5750

51+
// call function that is exported from worker
52+
const result = await woker.callFunction('add', 1, 1)
5853
```
59-
amp/main.mjs
60-
amp/worker/worker.mjs
61-
```
62-
63-
This output assumes the consumer will compile this distributed JavaScript to ensure it works with older `user-agent`s.
6454

65-
### Debug Distribution
6655

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

69-
```
70-
debug/main.mjs
71-
debug/main.js
72-
debug/worker/worker.mjs
73-
debug/worker/worker.js
58+
```js
59+
// webpack.config.js
60+
const WorkerPlugin = require("worker-plugin");
61+
module.exports = {
62+
// ...
63+
plugins: [new WorkerPlugin()]
64+
}
7465
```
7566

76-
## Running Demos Locally
67+
```js
68+
// worker.js
69+
import { ready } from "@intlify/worker-dom/dist/lib/worker";
7770

78-
After cloning the repository, you can try out the debug demos with the following.
79-
80-
```bash
81-
npm run demo
71+
ready.then(() =>{
72+
// should keep same content with main-thread on init.
73+
document.body.firstChild.textContent = 'hello from worker mutate';
74+
});
8275
```
8376

84-
This script will build the current version of WorkerDOM and start up a local [webserver](http://localhost:3001).
85-
86-
## Which JavaScript APIs can I use?
87-
88-
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).
77+
```js
78+
// main.js
79+
import { attachWorker } from "@intlify/worker-dom/dist/lib/main";
8980

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

92-
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.
93-
94-
Beyond that, we aim for very wide browser support and we accept fixes for all browsers with market share greater than 1 percent.
95-
96-
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.
97-
98-
## Local Development
99-
100-
Local development of WorkerDOM assumes the following:
101-
1. Familiarity with `npm` or `yarn`
102-
2. Latest LTS release of Node (10 at time of writing) available.
103-
3. Comfort with TypeScript, the codebase and tests are entirely written in TypeScript.
104-
105-
## Release Log
106-
107-
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
108-
109-
## Security disclosures
110-
111-
The AMP Project accepts responsible security disclosures through the [Google Application Security program](https://www.google.com/about/appsecurity/).
112-
113-
## Code of conduct
114-
115-
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).
84+
// attach worker to dom
85+
attachWorker(document.querySelector('#root'), worker);
86+
```
11687

117-
## License
88+
## LICENSE
11889

11990
worker-dom is licensed under the [Apache License, Version 2.0](LICENSE).

RELEASING.md

-16
This file was deleted.

config/rollup.config.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,13 @@
1414
* limitations under the License.
1515
*/
1616

17+
/**
18+
* Modified by mizchi
19+
* https://github.com/mizchi/worker-dom/blob/7f8b0295b757f1988e853c79858af682e850c312/config/rollup.config.js#L19-L21
20+
*/
21+
1722
import MainThreadBuilds from './rollup.main-thread.js';
1823
import WorkerThreadBuilds from './rollup.worker-thread.js';
24+
import LibBuilds from './rollup.lib.js';
1925

20-
export default [...MainThreadBuilds, ...WorkerThreadBuilds];
26+
export default [...MainThreadBuilds, ...WorkerThreadBuilds, ...LibBuilds];

config/rollup.lib.js

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* Copyright 2021 The Intlify Project Authors. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS-IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
/**
18+
* This code is written by mizchi
19+
* Modified by kazuya kawkaguchi
20+
* https://github.com/mizchi/worker-dom/blob/main/config/rollup.lib.js
21+
*/
22+
23+
import compiler from '@ampproject/rollup-plugin-closure-compiler';
24+
import { terser } from 'rollup-plugin-terser';
25+
import replace from '@rollup/plugin-replace';
26+
import { babelPlugin } from './rollup.plugins.js';
27+
import path from 'path';
28+
29+
// Compile plugins should always be added at the end of the plugin list.
30+
const compilePlugins = [
31+
compiler({
32+
env: 'CUSTOM',
33+
}),
34+
terser(),
35+
];
36+
37+
export default [
38+
{
39+
input: path.join(__dirname, '../output/main-thread/lib.js'),
40+
output: {
41+
file: 'dist/lib/main.mjs',
42+
format: 'esm',
43+
sourcemap: true,
44+
},
45+
plugins: [
46+
replace({
47+
values: {
48+
WORKER_DOM_DEBUG: false,
49+
},
50+
preventAssignment: true,
51+
}),
52+
babelPlugin({
53+
transpileToES5: false,
54+
allowConsole: true,
55+
}),
56+
...compilePlugins,
57+
],
58+
},
59+
{
60+
input: path.join(__dirname, '../output/worker-thread/lib.js'),
61+
output: {
62+
file: 'dist/lib/worker.mjs',
63+
format: 'esm',
64+
sourcemap: true,
65+
},
66+
plugins: [
67+
replace({
68+
values: {
69+
WORKER_DOM_DEBUG: false,
70+
},
71+
preventAssignment: true,
72+
}),
73+
babelPlugin({
74+
transpileToES5: false,
75+
allowConsole: true,
76+
}),
77+
...compilePlugins,
78+
],
79+
},
80+
];

demo/vite/.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
node_modules
2+
.DS_Store
3+
dist
4+
*.local

demo/vite/index.html

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Vite App</title>
7+
</head>
8+
<body>
9+
<div id="app">
10+
<h1>main</h1>
11+
<button>click</button>
12+
</div>
13+
<script type="module" src="/src/main.ts"></script>
14+
</body>
15+
</html>

demo/vite/package.json

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "vite",
3+
"version": "0.0.0",
4+
"private": true,
5+
"scripts": {
6+
"dev": "vite",
7+
"build": "vite build",
8+
"serve": "vite preview"
9+
},
10+
"devDependencies": {
11+
"typescript": "^4.2.3",
12+
"vite": "^2.1.2"
13+
}
14+
}

demo/vite/src/main.ts

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { attachWorker } from '@intlify/worker-dom/dist/lib/main.mjs'
2+
import Worker from './worker?worker'
3+
4+
;(async () => {
5+
const el = document.getElementById('app')
6+
const worker = new Worker()
7+
const exportedWorker = await attachWorker(el, worker)
8+
9+
const button = document.querySelector('button')
10+
button.onclick = async (ev) => {
11+
const val = await exportedWorker.callFunction('addElement', 'hello wokrer-dom')
12+
console.log('result', val)
13+
}
14+
})();

0 commit comments

Comments
 (0)