Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issues with isoworker #107

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12,677 changes: 12,677 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
- Buble Sort ( complex calculation )
- External Scripts ( `removeDependencies` option example )
- Transferable ( `transferable` option example )
<!-- - LocalDeps ( `localDependencies` option example ) -->
- LocalDeps ( `localDependencies` option example )
2 changes: 1 addition & 1 deletion packages/examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "1.0.0",
"private": true,
"dependencies": {
"@koale/useworker": "workspace:^3.3.0",
"@koale/useworker": "workspace:^4.0.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
Expand Down
3 changes: 2 additions & 1 deletion packages/useWorker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"background"
],
"dependencies": {
"dequal": "^1.0.0"
"dequal": "^1.0.0",
"isoworker": "^0.2.4"
}
}
60 changes: 60 additions & 0 deletions packages/useWorker/src/lib/createWorker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { createContext, dataPlaceholder, DepList } from 'isoworker';
import { TRANSFERABLE_TYPE } from 'src/useWorker'
import jobRunner from './jobRunner'
import remoteDepsParser from './remoteDepsParser'

/**
* Converts the "fn" function into a worker that takes parameters from messages and returns via messages
*
* @param {Function} fn the function to run with web worker
* @param {Array.<String>} deps array of strings, imported into the worker through "importScripts"
*
* @returns {Worker} a worker created via a blob url containing the code of "fn" as a string
*
* @example
* createWorker((a,b) => a+b, [])
* // return "onmessage=return Promise.resolve((a,b) => a + b)
* .then(postMessage(['SUCCESS', result]))
* .catch(postMessage(['ERROR', error])"
*/
const createWorker = (
fn: Function,
deps: string[],
transferable: TRANSFERABLE_TYPE,
localDeps: DepList,
) => {
const [context, runtimeCode, transferables] = createContext(localDeps)
const initMessage: unknown[] = []
let onInitMessage = ''
for (let part of runtimeCode) {
if (typeof part != 'string') {
const partIndex = initMessage.push(part[1]) - 1
part = part[0].replace(dataPlaceholder, `event.data[${partIndex}]`)
}
onInitMessage += part
}
const blobCode = `
${remoteDepsParser(deps)};
${context}
onmessage = function(event) {
${onInitMessage}
onmessage = (${jobRunner})({
fn: (${fn}),
transferable: '${transferable}'
})
}
`
const blob = new Blob([blobCode], { type: 'text/javascript' })
const url = URL.createObjectURL(blob)
const worker: Worker & { _url?: string } = new Worker(url)
worker._url = url
worker.postMessage(
initMessage,
transferable == TRANSFERABLE_TYPE.AUTO
? transferables as Transferable[]
: []
)
return worker
}

export default createWorker
36 changes: 0 additions & 36 deletions packages/useWorker/src/lib/createWorkerBlobUrl.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/useWorker/src/lib/remoteDepsParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
const remoteDepsParser = (deps: string[]) => {
if (deps.length === 0) return ''

const depsString = (deps.map(dep => `${dep}`)).toString()
return `importScripts('${depsString}')`
const depsString = (deps.map(dep => `'${dep}'`)).toString()
return `importScripts(${depsString})`
}

export default remoteDepsParser
13 changes: 6 additions & 7 deletions packages/useWorker/src/useWorker.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from 'react'
import createWorkerBlobUrl from './lib/createWorkerBlobUrl'
import createWorker from './lib/createWorker'
import WORKER_STATUS from './lib/status'
import { useDeepCallback } from './hook/useDeepCallback'
import { DepList } from 'isoworker'

type WorkerController = {
status: WORKER_STATUS;
Expand All @@ -18,7 +19,7 @@ type Options = {
remoteDependencies?: string[];
autoTerminate?: boolean;
transferable?: TRANSFERABLE_TYPE;
// localDependencies?: () => unknown[];
localDependencies?: DepList;
}

const PROMISE_RESOLVE = 'resolve'
Expand All @@ -28,7 +29,7 @@ const DEFAULT_OPTIONS: Options = {
remoteDependencies: [],
autoTerminate: true,
transferable: TRANSFERABLE_TYPE.AUTO,
// localDependencies: () => [],
localDependencies: () => [],
}


Expand Down Expand Up @@ -80,12 +81,10 @@ export const useWorker = <T extends (...fnArgs: any[]) => any>(
remoteDependencies = DEFAULT_OPTIONS.remoteDependencies,
timeout = DEFAULT_OPTIONS.timeout,
transferable = DEFAULT_OPTIONS.transferable,
// localDependencies = DEFAULT_OPTIONS.localDependencies,
localDependencies = DEFAULT_OPTIONS.localDependencies,
} = options

const blobUrl = createWorkerBlobUrl(fn, remoteDependencies!, transferable! /*, localDependencies!*/)
const newWorker: Worker & { _url?: string } = new Worker(blobUrl)
newWorker._url = blobUrl
const newWorker = createWorker(fn, remoteDependencies!, transferable!, localDependencies!)

newWorker.onmessage = (e: MessageEvent) => {
const [status, result] = e.data as [WORKER_STATUS, ReturnType<T>]
Expand Down
7 changes: 3 additions & 4 deletions packages/useWorker/test/localDeps.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import { renderHook } from "@testing-library/react-hooks";

const adder = (a, b) => a + b;

it("localDependencies", async () => {
/* const sum = (a, b) => adder(a, b);
it("Return", async () => {
const sum = (a, b) => adder(a, b);
const { result } = renderHook(() =>
useWorker(sum, { localDependencies: () => [adder] })
);
const [sumWorker] = result.current;
const res = await sumWorker(1, 2);
assert.equal(res, 3); */
assert.equal(1, 1);
assert.equal(res, 3);
});
14 changes: 14 additions & 0 deletions packages/useWorker/test/localDepsImport.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React from "react";
import { useWorker } from "../dist/index";
import { renderHook } from "@testing-library/react-hooks";
import { adder } from "./utils";

it("Return", async () => {
const sum = (a, b) => adder(a, b);
const { result } = renderHook(() =>
useWorker(sum, { localDependencies: () => [adder] })
);
const [sumWorker] = result.current;
const res = await sumWorker(1, 2);
assert.equal(res, 3);
});
4 changes: 1 addition & 3 deletions packages/website/docs/useworker.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ to view the values of `WORKER_STATUS` click here: [Status API](./workerstatus.md
| ------------------ | --------------- | --------- | ------------------------------------------------------------------------- |
| timeout | Number | undefined | The number of milliseconds before killing the worker |
| remoteDependencies | Array of String | [] | An array that contains the remote dependencies needed to run the worker |
<!-- | localDependencies | Function of Array of String | () => [] | A function that returns an array that contains the local dependencies needed to run the worker | -->
| localDependencies | Function of Array of String | () => [] | A function that returns an array that contains the local dependencies needed to run the worker |
| autoTerminate | Boolean | true | Kill the worker once it's done (success or error) |
| transferable | String | 'auto' | Enable [Transferable Objects](https://developer.mozilla.org/en-US/docs/Web/API/Transferable), to disable it set transferable: 'none' |

Expand All @@ -61,7 +61,6 @@ const [workerFn, {status: workerStatus, kill: workerTerminate }] = useWorker(fn,
],
});
```
<!--
## Local Dependencies Example

```javascript
Expand All @@ -75,7 +74,6 @@ const [workerFn, {status: workerStatus, kill: workerTerminate }] = useWorker(fn,
localDependencies: () => [expensiveAdder] // we pass the local function to the worker
});
```
-->

:::tip
To see an example click here: [ExternalScripts](https://github.com/alewin/useWorker/blob/develop/example/src/pages/ExternalScripts/index.js)
Expand Down
11 changes: 8 additions & 3 deletions pnpm-lock.yaml

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