modern-monaco 0.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020-2024 Je Xia <i@jex.me>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,359 @@
1
+ > [!WARNING]
2
+ > **This project is currently under active development and is not ready for production use.**
3
+
4
+ # Modern Monaco
5
+
6
+ Meeting the modern version of [Monaco Editor](https://www.npmjs.com/package/monaco-editor):
7
+
8
+ - Easy to use, no `MonacoEnvironment` setup and web-worker/css loader
9
+ - Using [Shiki](https://shiki.style) for syntax highlighting with tons of grammars and themes.
10
+ - Lazy loading: pre-highlighting code with Shiki while loading `monaco-editor-core` in background.
11
+ - Support **server-side rendering(SSR)**.
12
+ - Workspace (edit history, file system provider, etc).
13
+ - Automatically loading `.d.ts` from [esm.sh](https://esm.sh) CDN for type checking.
14
+ - Using [import maps](https://github.com/WICG/import-maps) for resolving **bare specifier** imports in JavaScript/TypeScript.
15
+ - VSCode `window` APIs like `showInputBox`, `showQuickPick`, etc.
16
+ - Embedded languages(importmap/CSS/JavaScript) in HTML.
17
+ - Inline `html` and `css` in JavaScript/TypeScript.
18
+ - Auto-closing HTML/JSX tags.
19
+
20
+ Planned features:
21
+
22
+ - [ ] Show a loading indicator while loading the editor
23
+ - [ ] Quick open menu (only if a workspace is provided)
24
+ - [ ] Drag and drop file (only if a workspace is provided)
25
+ - [ ] Display non-code files, like images, videos, etc
26
+ - [ ] VSCode `winodow.show<XXX>Message` APIs
27
+ - [ ] Emmet
28
+ - [ ] Markdown language service
29
+ - [ ] [Volar](https://github.com/volarjs/volar.js) integration
30
+ - [ ] Support [Shiki JS RegExp Engine](https://shiki.style/guide/regex-engines#javascript-regexp-engine-experimental)
31
+
32
+ ## Installation
33
+
34
+ You can install the package from NPM in your node project with a bundler like [vite](http://vitejs.dev).
35
+
36
+ ```bash
37
+ npm i modern-monaco typescript
38
+ ```
39
+
40
+ > [!Note]
41
+ > The `typescript` package is required by JavaScript/TypeScript LSP worker. We recommend `typescript@5.5.x` or later.
42
+
43
+ or import it from [esm.sh](https://esm.sh/) in browser without build step:
44
+
45
+ ```js
46
+ import * from "https://esm.sh/modern-monaco"
47
+ ```
48
+
49
+ ## Usage
50
+
51
+ `modern-monaco` provides three modes to create a browser based code editor:
52
+
53
+ - **Lazy**: pre-hightlight code with Shiki while loading the `editor-core.js` in background.
54
+ - **SSR**: render the editor in server side, and hydrate it in client side.
55
+ - **Manual**: create a monaco editor instance manually.
56
+
57
+ ### Lazy Mode
58
+
59
+ [monaco-editor](https://www.npmjs.com/package/monaco-editor) is a large package with extra CSS/Worker dependencies, not mention the `MonacoEnvironment` setup. `modern-monaco` provides a lazy but smart way to load the editor on demand, and it pre-highlights code with Shiki while loading the `editor-core.js` in background.
60
+
61
+ ```html
62
+ <monaco-editor></monaco-editor>
63
+
64
+ <script type="module">
65
+ import { lazy, Workspace } from "modern-monaco";
66
+
67
+ // create a workspace with initial files
68
+ const workspace = new Workspace({
69
+ initialFiles: {
70
+ "index.html": `<html><head><title>Hello, world!</title></head><body><script src="main.js"></script></body></html>`,
71
+ "main.js": `console.log("Hello, world!")`
72
+ },
73
+ entryFile: "index.html",
74
+ });
75
+
76
+ // initialize the editor lazily
77
+ lazy({ workspace });
78
+ </script>
79
+ ```
80
+
81
+ ### SSR Mode
82
+
83
+ SSR mode returns a instant rendered editor in server side, and hydrate it in client side.
84
+
85
+ ```js
86
+ import { renderToWebComponent } from "modern-monaco/ssr";
87
+
88
+ export default {
89
+ fetch(req) => {
90
+ const ssrOut = renderToWebComponent({
91
+ filename: "main.js",
92
+ code: `console.log("Hello, world!")`,
93
+ userAgent: req.headers.get("user-agent"), // detecte default font for different platforms
94
+ theme: "theme-id",
95
+ });
96
+ return new Response(html`
97
+ ${ssrOut}
98
+ <script type="module">
99
+ import { hydrate } from "https://esm.sh/modern-monaco";
100
+ // hydrate the editor
101
+ hydrate();
102
+ </script>
103
+ `, { headers: { "Content-Type": "text/html" }});
104
+ }
105
+ }
106
+ ```
107
+
108
+ ### Manual Mode
109
+
110
+ You can also create a [monaco editor](https://microsoft.github.io/monaco-editor/docs.html) instance manually.
111
+
112
+ ```html
113
+ <div id="editor"></div>
114
+
115
+ <script type="module">
116
+ import { init } from "modern-monaco";
117
+
118
+ // load monaco-editor-core.js
119
+ const monaco = await init();
120
+
121
+ // create a monaco editor instance
122
+ const editor = monaco.editor.create(document.getElementById("editor"));
123
+
124
+ // create and attach a model to the editor
125
+ editor.setModel(monaco.editor.createModel(`console.log("Hello, world!")`, "javascript"));
126
+ </script>
127
+ ```
128
+
129
+ ## Using Workspace
130
+
131
+ `modern-monaco` provides vscode-like workspace features, like edit history, file system provider, etc.
132
+
133
+ ```js
134
+ import { lazy, Workspace } from "modern-monaco";
135
+
136
+ // 1. create a workspace with initial files
137
+ const workspace = new Workspace({
138
+ /** the name of the workspace, used for project isolation, default is "default". */
139
+ name: "project-name",
140
+ /** initial files in the workspace. */
141
+ initialFiles: {
142
+ "index.html": `<html><head><title>Hello, world!</title></head><body><script src="main.js"></script></body></html>`,
143
+ "main.js": `console.log("Hello, world!")`,
144
+ },
145
+ /** file to open when the editor is loaded at first time. */
146
+ entryFile: "index.html",
147
+ });
148
+
149
+ // 2. use the workspace in lazy mode
150
+ lazy({ workspace });
151
+
152
+ // 3. open a file in the workspace
153
+ workspace.openTextDocument("main.js")
154
+ ```
155
+
156
+ ### Adding `tsconfig.json`
157
+
158
+ You can also add a `tsconfig.json` file to configure the TypeScript compiler options for the TypeScript language service worker.
159
+
160
+ ```js
161
+ const tsconfig = {
162
+ "compilerOptions": {
163
+ "strict": true,
164
+ "noUnusedLocals": true,
165
+ "noUnusedParameters": true,
166
+ "noFallthroughCasesInSwitch": true,
167
+ },
168
+ };
169
+ const workspace = new Workspace({
170
+ initialFiles: {
171
+ "tsconfig.json": JSON.stringify(tsconfig, null, 2),
172
+ },
173
+ });
174
+ ```
175
+
176
+ ### Using Import Maps
177
+
178
+ `modern-monaco` uses [import maps](https://github.com/WICG/import-maps) to resolving **bare specifier** import in JavaScript/TypeScript.
179
+ By default, `modern-monaco` dedetects the `importmap` script of root `index.html`.
180
+
181
+ ```js
182
+ const indexHtml = html`<!DOCTYPE html>
183
+ <html>
184
+ <head>
185
+ <script type="importmap">
186
+ {
187
+ "imports": {
188
+ "@jsxRuntime": "https://esm.sh/react@18",
189
+ "react": "https://esm.sh/react@18"
190
+ }
191
+ }
192
+ </script>
193
+ </head>
194
+ <body>
195
+ <script type="module">
196
+ import React from "react";
197
+ </script>
198
+ </body>
199
+ </html>
200
+ `;
201
+ const workspace = new Workspace({
202
+ initialFiles: {
203
+ "index.html": indexHtml,
204
+ },
205
+ });
206
+ ```
207
+
208
+ > [!Note]
209
+ > By default, `modern-monaco` uses `react` or `preact` in the `importmap` script as the `jsxImportSource` option for typescript worker.
210
+ > To use a custom `jsxImportSource` option, add `@jsxRuntime` specifier in the `importmap` script. For example, [solid-js](https://esm.sh/solid-js/jsx-runtime).
211
+
212
+
213
+ ## Editor Theme & Language Grammars
214
+
215
+ `modern-monaco` uses [Shiki](https://shiki.style) for syntax highlighting with tons of grammars and themes. It loads themes and grammars from esm.sh on demand.
216
+
217
+ ### Setting the Editor Theme
218
+
219
+ To set the theme of the editor, you can add a `theme` attribute to the `<monaco-editor>` element.
220
+
221
+ ```html
222
+ <monaco-editor theme="theme-id"></monaco-editor>
223
+ ```
224
+
225
+ or set it in the `lazy`, `init`, or `hydrate` function.
226
+
227
+ ```js
228
+ lazy({
229
+ theme: "theme-id",
230
+ });
231
+ ```
232
+
233
+ > [!Note]
234
+ > The theme ID should be one of the [Shiki Themes](https://shiki.style/themes).
235
+
236
+ ### Pre-loading Language Grammars
237
+
238
+ By default, `modern-monaco` loads language grammars when a specific language mode is attached in the editor. You can also pre-load language grammars by adding the `langs` option to the `lazy`, `init`, or `hydrate` function.
239
+
240
+ ```js
241
+ lazy({
242
+ langs: ["javascript", "typescript", "css", "html", "json", "markdown"],
243
+ });
244
+ ```
245
+
246
+ ### Custom Language Grammars
247
+
248
+ You can also add custom language grammars to the editor.
249
+
250
+ ```js
251
+ lazy({
252
+ langs: [
253
+ // hand-crafted language grammar
254
+ {
255
+ name: "mylang",
256
+ scopeName: "source.mylang",
257
+ patterns: [/* ... */],
258
+ },
259
+ // or load a grammar from URL
260
+ "https://example.com/grammars/mylang.json",
261
+ ],
262
+ });
263
+ ```
264
+
265
+ ## Editor Options
266
+
267
+ You can set the editor options in the `<monaco-editor>` element as attributes. The editor options are the same as the [`editor.EditorOptions`](https://microsoft.github.io/monaco-editor/docs.html#variables/editor.EditorOptions.html).
268
+
269
+ ```html
270
+ <monaco-editor
271
+ theme="theme-id"
272
+ fontFamily="Geist Mono"
273
+ fontSize="16"
274
+ ></monaco-editor>
275
+ ```
276
+
277
+ For SSR mode, you can set the editor options in the `renderToWebComponent` function.
278
+
279
+ ```js
280
+ import { renderToWebComponent } from "modern-monaco/ssr";
281
+
282
+ const html = renderToWebComponent({
283
+ // render options
284
+ filename: "main.js",
285
+ code: `console.log("Hello, world!")`,
286
+ userAgent: req.headers.get("user-agent"), // font detection for different platforms
287
+ // ...
288
+
289
+ // editor options
290
+ theme: "theme-id",
291
+ fontFamily: "Geist Mono",
292
+ fontSize: 16,
293
+ // ...
294
+ });
295
+ ```
296
+
297
+ For manual mode, check [here](https://microsoft.github.io/monaco-editor/docs.html#functions/editor.create.html) for more details.
298
+
299
+ ## Language Server Protocol(LSP)
300
+
301
+ `modern-monaco` by default supports full LSP features for following languages:
302
+
303
+ - **HTML**
304
+ - **CSS/SCSS/LESS**
305
+ - **JavaScript/TypeScript**
306
+ - **JSON**
307
+
308
+ Plus, `modern-monaco` also supports features like:
309
+
310
+ - **File System Provider for import completions**
311
+ - **Embedded languages in HTML**
312
+ - **Auto-closing HTML/JSX tags**
313
+
314
+ > [!Note]
315
+ > You don't need to set the `MonacoEnvironment.getWorker` for LSP support.
316
+ > `modern-monaco` will automatically load required LSP workers.
317
+
318
+ ### LSP language configuration
319
+
320
+ You can configure builtin LSPs in the `lazy`, `init`, or `hydrate` function.
321
+
322
+ ```js
323
+ lazy({
324
+ // configure LSP for each language
325
+ lsp: {
326
+ html: {/* ... */},
327
+ json: {/* ... */},
328
+ typescript: {/* ... */},
329
+ },
330
+ });
331
+ ```
332
+
333
+ The `LSPLanguageConfig` interface is defined as:
334
+
335
+ ```ts
336
+ export interface LSPLanguageConfig {
337
+ html?: {
338
+ attributeDefaultValue?: "empty" | "singlequotes" | "doublequotes";
339
+ customTags?: ITagData[];
340
+ hideAutoCompleteProposals?: boolean;
341
+ };
342
+ css?: {};
343
+ json?: {
344
+ schemas?: JSONSchemaSource[];
345
+ };
346
+ typescript?: {
347
+ /** The compiler options. */
348
+ compilerOptions?: ts.CompilerOptions;
349
+ /** The global import map. */
350
+ importMap?: ImportMap;
351
+ /** The version of the typescript from CDN. Default: ">= 5.0.0" */
352
+ tsVersion?: string;
353
+ };
354
+ }
355
+ ```
356
+
357
+ ### Custom LSP
358
+
359
+ [TODO]
package/dist/cache.js ADDED
@@ -0,0 +1,94 @@
1
+ // src/cache.ts
2
+ import { defineProperty, openIDB, promisifyIDBRequest, toURL } from "./util.js";
3
+ var Cache = class {
4
+ _db = null;
5
+ constructor(name) {
6
+ if (globalThis.indexedDB) {
7
+ this._db = this._openDB(name);
8
+ }
9
+ }
10
+ _openDB(name) {
11
+ return openIDB(
12
+ name,
13
+ 1,
14
+ { name: "store", keyPath: "url" }
15
+ ).then((db) => {
16
+ db.onclose = () => {
17
+ this._db = this._openDB(name);
18
+ };
19
+ return this._db = db;
20
+ });
21
+ }
22
+ async fetch(url) {
23
+ url = toURL(url);
24
+ const storedRes = await this.query(url);
25
+ if (storedRes) {
26
+ return storedRes;
27
+ }
28
+ const res = await fetch(url);
29
+ if (res.ok && this._db) {
30
+ const db = await this._db;
31
+ const file = {
32
+ url: url.href,
33
+ content: null,
34
+ ctime: Date.now()
35
+ };
36
+ if (res.redirected) {
37
+ const tx = db.transaction("store", "readwrite").objectStore("store");
38
+ file.headers = [["location", res.url]];
39
+ await promisifyIDBRequest(tx.put(file));
40
+ }
41
+ const content = await res.arrayBuffer();
42
+ const headers = [...res.headers.entries()].filter(
43
+ ([k]) => ["cache-control", "content-type", "content-length", "x-typescript-types"].includes(k)
44
+ );
45
+ file.url = res.url;
46
+ file.headers = headers;
47
+ file.content = content;
48
+ await this.store(file);
49
+ const resp = new Response(content, { headers });
50
+ defineProperty(resp, "url", res.url);
51
+ defineProperty(resp, "redirected", res.redirected);
52
+ return resp;
53
+ }
54
+ return res;
55
+ }
56
+ async query(key) {
57
+ if (!this._db) {
58
+ return null;
59
+ }
60
+ const url = toURL(key).href;
61
+ const db = await this._db;
62
+ const tx = db.transaction("store", "readonly").objectStore("store");
63
+ const ret = await promisifyIDBRequest(tx.get(url));
64
+ if (ret && ret.headers) {
65
+ const headers = new Headers(ret.headers);
66
+ if (headers.has("location")) {
67
+ const redirectedUrl = headers.get("location");
68
+ const res2 = await this.query(redirectedUrl);
69
+ if (res2) {
70
+ defineProperty(res2, "redirected", true);
71
+ }
72
+ return res2;
73
+ }
74
+ const res = new Response(ret.content, { headers });
75
+ defineProperty(res, "url", url);
76
+ return res;
77
+ }
78
+ return null;
79
+ }
80
+ async store(file) {
81
+ if (!this._db) {
82
+ return;
83
+ }
84
+ const db = await this._db;
85
+ const tx = db.transaction("store", "readwrite").objectStore("store");
86
+ await promisifyIDBRequest(tx.put(file));
87
+ }
88
+ };
89
+ var cache = new Cache("monaco:cache");
90
+ var cache_default = cache;
91
+ export {
92
+ cache,
93
+ cache_default as default
94
+ };