Skip to content

Commit

Permalink
Example of an extra method (#59)
Browse files Browse the repository at this point in the history
- Refs #58
  • Loading branch information
tmcw authored Feb 12, 2025
1 parent f91a46e commit 4faf485
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 7 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,32 @@ Comlink.expose(worker);
> a web browser, ATA will not help you with your HTTP imports or prefixed
> imports. It narrowly targets the Node & NPM way of doing imports.
## Calling other methods in the worker

The provided `createWorker` method creates a standard object with methods
that the frontend code knows about and can call to power TypeScript support.
If you want to do something else with Worker, like transpiling or
running a code formatter, you can nest the result of createWorker. See
[the demo for an example](https://val-town.github.io/codemirror-ts/):
the gist is:

In your worker, nest the `worker` instead of directly exposing it.

```ts
Comlink.expose({
worker,
anotherMethod() {
return 'another-result';
}
})
```

In the front-end, reach in for the exposed worker:

```ts
tsFacet.of({ worker: worker.worker, path }),
```

## Conceptual notes: persisted code

There are a few different approaches to building CodeMirror + TypeScript
Expand Down
12 changes: 12 additions & 0 deletions demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ <h2>Demo with ATA</h2>
<div id="app" class='border'>
<div id="editor-worker-ata"></div>
</div>


<h2>Demo with transpiling</h2>
<p>
This demo adds another method in the typescript worker to transpile
the given code.
</p>
<div id="app" class='border'>
<div id="editor-worker-extra"></div>
<pre id='editor-worker-extra-output'></pre>
</div>

<h2>Currently supported</h2>
<ul>
<li>Autocomplete</li>
Expand Down
50 changes: 45 additions & 5 deletions demo/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
import { autocompletion } from "@codemirror/autocomplete";
import { javascript } from "@codemirror/lang-javascript";
import {
createDefaultMapFromCDN,
createSystem,
createVirtualTypeScriptEnvironment,
} from "@typescript/vfs";
import { EditorView, basicSetup } from "codemirror";
import * as Comlink from "comlink";
import type ts from "typescript";
Expand All @@ -18,6 +13,7 @@ import {
tsTwoslash,
} from "../src/index.js";
import type { WorkerShape } from "../src/worker.js";
import type { Exposed } from "./worker_extra_function.js";

function renderDisplayParts(dp: ts.SymbolDisplayPart[]) {
const div = document.createElement("div");
Expand Down Expand Up @@ -143,3 +139,47 @@ const minimumValue = min([1, 2, 3]);`,
parent: document.querySelector("#editor-worker-ata")!,
});
})().catch((e) => console.error(e));

(async () => {
const path = "index.ts";

// TODO: this is the one place where we can't use .js urls
const innerWorker = new Worker(
new URL("./worker_extra_function.ts", import.meta.url),
{
type: "module",
},
);
const w = Comlink.wrap(innerWorker) as Exposed;
const worker = w.worker as unknown as WorkerShape;
await worker.initialize();

const editor = new EditorView({
doc: `enum X { Y = 'Y' };
console.log(X.Y);`,
extensions: [
basicSetup,
javascript({
typescript: true,
jsx: true,
}),
tsFacet.of({ worker, path }),
tsSync(),
tsLinter(),
autocompletion({
override: [tsAutocomplete()],
}),
tsHover(),
tsGoto(),
tsTwoslash(),
EditorView.updateListener.of((_update) => {
w.getTranspiledFile(path).then((code) => {
(document.querySelector(
"#editor-worker-extra-output",
) as HTMLPreElement)!.innerText = code.outputText;
});
}),
],
parent: document.querySelector("#editor-worker-extra")!,
});
})().catch((e) => console.error(e));
43 changes: 43 additions & 0 deletions demo/worker_extra_function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
createDefaultMapFromCDN,
createSystem,
createVirtualTypeScriptEnvironment,
} from "@typescript/vfs";
import * as Comlink from "comlink";
import ts from "typescript";
import { createWorker } from "../src/worker/createWorker.js";
import type { Remote } from "comlink";

const _env = (async () => {
const fsMap = await createDefaultMapFromCDN(
{ target: ts.ScriptTarget.ES2022 },
ts.version,
false,
ts,
);
const system = createSystem(fsMap);
return createVirtualTypeScriptEnvironment(system, [], ts, {
lib: ["ES2022"],
});
})();

const exposed = {
async getTranspiledFile(path: string) {
const env = await _env;
const file = env.getSourceFile(path);
if (!file) throw new Error(`File not found for path ${path}`);
return ts.transpileModule(file.text, {
compilerOptions: {
target: ts.ScriptTarget.ES2015,
module: ts.ModuleKind.None,
},
});
},
worker: createWorker({
env: _env,
}),
};

export type Exposed = Remote<typeof exposed>;

Comlink.expose(exposed);
8 changes: 6 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
"rootDir": "./src",
"outDir": "./dist"
},
"include": ["./src"],
"exclude": ["./demo", "./src/**/*.test.ts"]
"include": [
"./src"
],
"exclude": [
"./src/**/*.test.ts"
]
}

0 comments on commit 4faf485

Please sign in to comment.