@coldsmirk/inkstone-monaco 0.10.1 → 0.12.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/README.md CHANGED
@@ -11,7 +11,11 @@ Part of [inkstone](https://github.com/coldsmirk/inkstone). For a drop-in React c
11
11
  - **`monacoLanguages`** — the sorted catalog of every built-in language id the installed Monaco registers (with the `MonacoBuiltInLanguage` union type behind it), held to the installed `monaco-editor` by an upgrade-tripwire test. These are *ids*, not display names (`proto`, `sol`, `aes`); an unknown id silently falls back to `plaintext`.
12
12
  - **`disabledKeybindings` / `installDisabledKeybindings`** — swallow the find/replace chords and the command palette's F1 for editors that opt in. Monaco's standalone keybinding service is page-global and its rules are permanent, so the install registers each chord once per monaco module's service (duplicate copies of this package share the ledger; independent monaco bundles register their own) and scopes it with a per-capability context key created on the opted-in editor; the chord table is held to the installed `monaco-editor` by an upgrade-tripwire test.
13
13
  - **Embedded-editor fix** — works around [microsoft/monaco-editor#5177](https://github.com/microsoft/monaco-editor/issues/5177) (find-widget button tooltips landing on top of the buttons they describe) with a `width: max-content` hover-layer style tagged `data-inkstone="monaco-hover-geometry"`; deleted the moment upstream fixes it. The tooltip layer positions against the editor's container — give that container `position: relative`.
14
- - **`StreamingEditorController`** — stream generated text into an editor without routing every token through app state: `begin()` / `append(chunk)` / `end()` / `discard()`, `attach(editor)` / `detach(editor)` with buffered replay for late-mounting editors (and for a model swapped onto the attached editor mid-stream, including after the final chunk), `isStreaming()` for the onChange guard, and `replace(old, new, all)` for exact edits that preserve undo/cursor/folds. The stream locks every editor it touches read-only and `end()` / `discard()` restore each one's own setting — by handle, so an editor detached mid-stream is restored too; `discard()` puts every displaced document back into the model it came from, and `end()` does the same for every model except the one keeping the streamed text. Full-buffer writes and restorations preserve each model's UTF-8 BOM. Editors and models the app disposed mid-stream are skipped, never touched — teardown can race the stream without wedging it.
14
+ - **`StreamingEditorController`** — stream generated text into an editor without routing every token through app state: `begin()` / `append(chunk)` / `end()` / `discard()`, `attach(editor)` / `detach(editor)` with buffered replay for late-mounting editors (and for a model swapped onto the attached editor mid-stream, including after the final chunk), and `isStreaming()` for the onChange guard. The stream locks every editor it touches read-only and `end()` / `discard()` restore each one's own setting — by handle, so an editor detached mid-stream is restored too; `discard()` puts every displaced document back into the model it came from, and `end()` does the same for every model except the one keeping the streamed text. Full-buffer writes and restorations preserve each model's UTF-8 BOM. Editors and models the app disposed mid-stream are skipped, never touched — teardown can race the stream without wedging it.
15
+ - **`replaceInEditor(editor, old, new, all)`** — exact find-and-replace on an editor handle via `executeEdits`, preserving undo/cursor/folds; returns whether the edit landed (`false` = no editor / empty search / no match / a read-only editor refused it — e.g. one locked by a stream in progress), so a tool-call handler knows to fall back to a state write.
16
+ - **`registerShikiHighlighting(monaco, highlighter)`** — wire `@coldsmirk/inkstone-core`'s shared Shiki highlighter onto a monaco module, once per distinct module: registers the canonical grammar names as Monaco languages, applies `@shikijs/monaco`'s tokenizer/themes, and repairs its `setTheme` patch so non-Shiki theme ids (vs/vs-dark, caller-defined) keep Monaco's original path. A failed registration is restored and retried on the next call.
17
+ - **`DEFAULT_MONACO_OPTIONS`** — the inkstone construction-option baseline (no minimap, 14px/1.6 type on the shared `--inkstone-font-family-code` token, embedded-friendly find widget, tuned completion, thin scrollbars). Spread it to extend: `{ ...DEFAULT_MONACO_OPTIONS, wordWrap: "on" }`.
18
+ - **`reconcileModelValue` / `modelValueMatches`** — the controlled-value reconcile: diff an external value against a live model (normalized to the model's EOL) and apply one minimal `applyEdits` replace that never lands on the undo stack or moves a caret outside the changed region.
15
19
 
16
20
  ## Install
17
21
 
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { HighlighterCore } from "@coldsmirk/inkstone-core";
1
2
  import * as monacoEditor from "monaco-editor";
2
3
  import { editor } from "monaco-editor";
3
4
 
@@ -31,6 +32,24 @@ interface MonacoHostOptions {
31
32
  * The monaco module namespace, as resolved by {@link ensureMonacoHost}.
32
33
  */
33
34
  type MonacoModule = typeof monacoEditor;
35
+ /**
36
+ * Bring up the shared Monaco host: UI locale, then the monaco module, then worker routing —
37
+ * fully offline, no CDN, workers bundled by the consumer's bundler.
38
+ *
39
+ * Idempotent and async-safe: every caller shares one promise, and the first call wins the
40
+ * configuration (`globalThis.MonacoEnvironment` is a single global — per-editor configuration
41
+ * would clobber whichever editor mounted first).
42
+ *
43
+ * The locale catalog must be evaluated **before** the monaco module: monaco resolves
44
+ * `localize()` calls against `globalThis._VSCODE_NLS_MESSAGES` as its modules evaluate.
45
+ * Owning both dynamic imports here turns that ordering footgun into a guarantee. The
46
+ * corollary: never `import "monaco-editor"` statically in app code — take the instance
47
+ * from this promise (type-only imports are fine, they erase).
48
+ *
49
+ * A failed bring-up is not cached: the slot resets so a later call retries the imports
50
+ * (both are idempotent), instead of replaying one transient failure — a chunk 404 after a
51
+ * redeploy, a flaky network — for the rest of the session.
52
+ */
34
53
  declare function ensureMonacoHost(options?: MonacoHostOptions): Promise<MonacoModule>;
35
54
  //#endregion
36
55
  //#region src/keybindings.d.ts
@@ -99,6 +118,46 @@ declare const monacoLanguages: readonly MonacoBuiltInLanguage[];
99
118
  */
100
119
  type MonacoLanguage = MonacoBuiltInLanguage | (string & Record<never, never>);
101
120
  //#endregion
121
+ //#region src/options.d.ts
122
+ /**
123
+ * Baseline construction options shared by every inkstone Monaco editor: no minimap, compact
124
+ * code type, in-place layout tracking, widgets floated above clipping containers, completion
125
+ * tuned for API-assisted editing, thin scrollbars, and an embedded-friendly find widget.
126
+ * Spread these to extend rather than replace: `options={{ ...DEFAULT_MONACO_OPTIONS, wordWrap: "on" }}`.
127
+ */
128
+ declare const DEFAULT_MONACO_OPTIONS: editor.IStandaloneEditorConstructionOptions;
129
+ //#endregion
130
+ //#region src/reconcile.d.ts
131
+ /**
132
+ * Reconcile `externalValue` into `model` as one minimal replace, or do nothing when the
133
+ * documents already match. Fires the model's content-change event synchronously when it
134
+ * edits — callers that must not re-enter their change callback silence it around this call.
135
+ */
136
+ declare function reconcileModelValue(model: editor.ITextModel, externalValue: string): void;
137
+ /**
138
+ * Whether an external value already matches the model after applying its EOL convention.
139
+ */
140
+ declare function modelValueMatches(model: editor.ITextModel, externalValue: string): boolean;
141
+ //#endregion
142
+ //#region src/replace.d.ts
143
+ /**
144
+ * Exact find-and-replace on a Monaco editor, located by character offset and applied via
145
+ * `executeEdits` — preserving the undo stack, cursor, and fold state. Returns whether it was
146
+ * applied (`false` = no editor / empty search / no match, or an editor that refused the edit
147
+ * because it is read-only — e.g. locked by a stream in progress; the caller falls back to a
148
+ * state write).
149
+ */
150
+ declare function replaceInEditor(target: editor.ICodeEditor | null, search: string, replaceWith: string, all: boolean): boolean;
151
+ //#endregion
152
+ //#region src/shiki-bridge.d.ts
153
+ /**
154
+ * Register the shared Shiki highlighter's languages, themes, and tokenizer on a monaco module —
155
+ * once per distinct module, whichever caller gets there first. Language services are
156
+ * unaffected: Shiki replaces syntax highlighting only. The module is recorded only after every
157
+ * registration succeeds, so a transient failure can retry on a later call.
158
+ */
159
+ declare function registerShikiHighlighting(monaco: MonacoModule, highlighter: HighlighterCore): void;
160
+ //#endregion
102
161
  //#region src/streaming.d.ts
103
162
  /**
104
163
  * The editor surface the controller drives — satisfied by any Monaco code editor
@@ -219,14 +278,6 @@ declare class StreamingEditorController {
219
278
  * where flushing the partial stream into the now-current document would corrupt it.
220
279
  */
221
280
  discard(): void;
222
- /**
223
- * Exact find-and-replace on the attached editor, located by character offset and applied
224
- * via `executeEdits` — preserving the undo stack, cursor, and fold state. Returns whether
225
- * it was applied (`false` = no editor / empty search / no match, or an editor that refused
226
- * the edit because it is read-only — a stream in progress; the caller falls back to a state
227
- * write).
228
- */
229
- replace(search: string, replaceWith: string, all: boolean): boolean;
230
281
  }
231
282
  //#endregion
232
- export { type KeybindingTargetEditor, type MonacoBuiltInLanguage, type MonacoHostOptions, type MonacoLanguage, type MonacoModule, type MonacoUiLocale, type StreamTargetEditor, StreamingEditorController, type SwallowedKeybindings, disabledKeybindings, ensureMonacoHost, installDisabledKeybindings, monacoLanguages };
283
+ export { DEFAULT_MONACO_OPTIONS, type KeybindingTargetEditor, type MonacoBuiltInLanguage, type MonacoHostOptions, type MonacoLanguage, type MonacoModule, type MonacoUiLocale, type StreamTargetEditor, StreamingEditorController, type SwallowedKeybindings, disabledKeybindings, ensureMonacoHost, installDisabledKeybindings, modelValueMatches, monacoLanguages, reconcileModelValue, registerShikiHighlighting, replaceInEditor };
package/dist/index.js CHANGED
@@ -1,3 +1,23 @@
1
+ import { CODE_FONT_FAMILY } from "@coldsmirk/inkstone-core";
2
+ import { shikiToMonaco } from "@shikijs/monaco";
3
+ //#region src/geometry-fixes.ts
4
+ const HOVER_GEOMETRY_STYLE_SELECTOR = "style[data-inkstone=\"monaco-hover-geometry\"]";
5
+ function installHoverGeometryFix() {
6
+ if (document.querySelector(HOVER_GEOMETRY_STYLE_SELECTOR)) return;
7
+ const style = document.createElement("style");
8
+ style.dataset.inkstone = "monaco-hover-geometry";
9
+ style.textContent = ".context-view:has(> .workbench-hover-container) { width: max-content !important; }";
10
+ document.head.append(style);
11
+ }
12
+ const SUGGEST_GEOMETRY_STYLE_SELECTOR = "style[data-inkstone=\"monaco-suggest-geometry\"]";
13
+ function installSuggestGeometryFix() {
14
+ if (document.querySelector(SUGGEST_GEOMETRY_STYLE_SELECTOR)) return;
15
+ const style = document.createElement("style");
16
+ style.dataset.inkstone = "monaco-suggest-geometry";
17
+ style.textContent = ".monaco-editor .suggest-widget .monaco-list .monaco-list-row > .contents > .main > .right > span.readMore.codicon.codicon-suggest-more-info::before { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }";
18
+ document.head.append(style);
19
+ }
20
+ //#endregion
1
21
  //#region src/host.ts
2
22
  const HOST_PROMISE_KEY = Symbol.for("coldsmirk.inkstone.monaco.hostPromise");
3
23
  const NLS_REGISTRY_KEY = Symbol.for("coldsmirk.inkstone.monaco.nlsRegistry");
@@ -55,22 +75,6 @@ function builtinGetWorker(label) {
55
75
  const factory = WORKER_BY_LABEL[WORKER_ALIASES[label] ?? label];
56
76
  return factory ? factory() : editorWorker();
57
77
  }
58
- const HOVER_GEOMETRY_STYLE_SELECTOR = "style[data-inkstone=\"monaco-hover-geometry\"]";
59
- function installHoverGeometryFix() {
60
- if (document.querySelector(HOVER_GEOMETRY_STYLE_SELECTOR)) return;
61
- const style = document.createElement("style");
62
- style.dataset.inkstone = "monaco-hover-geometry";
63
- style.textContent = ".context-view:has(> .workbench-hover-container) { width: max-content !important; }";
64
- document.head.append(style);
65
- }
66
- const SUGGEST_GEOMETRY_STYLE_SELECTOR = "style[data-inkstone=\"monaco-suggest-geometry\"]";
67
- function installSuggestGeometryFix() {
68
- if (document.querySelector(SUGGEST_GEOMETRY_STYLE_SELECTOR)) return;
69
- const style = document.createElement("style");
70
- style.dataset.inkstone = "monaco-suggest-geometry";
71
- style.textContent = ".monaco-editor .suggest-widget .monaco-list .monaco-list-row > .contents > .main > .right > span.readMore.codicon.codicon-suggest-more-info::before { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }";
72
- document.head.append(style);
73
- }
74
78
  function ensureMonacoHost(options = {}) {
75
79
  const registry = globalThis;
76
80
  const existing = registry[HOST_PROMISE_KEY];
@@ -234,6 +238,134 @@ const monacoLanguages = [
234
238
  "yaml"
235
239
  ].toSorted();
236
240
  //#endregion
241
+ //#region src/options.ts
242
+ const DEFAULT_MONACO_OPTIONS = {
243
+ find: { addExtraSpaceOnTop: false },
244
+ minimap: { enabled: false },
245
+ fontSize: 14,
246
+ lineHeight: 1.6,
247
+ fontFamily: CODE_FONT_FAMILY,
248
+ scrollBeyondLastLine: false,
249
+ automaticLayout: true,
250
+ renderLineHighlight: "line",
251
+ smoothScrolling: true,
252
+ padding: {
253
+ top: 12,
254
+ bottom: 12
255
+ },
256
+ fixedOverflowWidgets: true,
257
+ quickSuggestions: {
258
+ other: true,
259
+ comments: false,
260
+ strings: true
261
+ },
262
+ wordBasedSuggestions: "off",
263
+ tabCompletion: "on",
264
+ scrollbar: {
265
+ alwaysConsumeMouseWheel: false,
266
+ verticalScrollbarSize: 8,
267
+ horizontalScrollbarSize: 8
268
+ }
269
+ };
270
+ //#endregion
271
+ //#region src/reconcile.ts
272
+ function reconcileModelValue(model, externalValue) {
273
+ const value = normalizeModelValue(model, externalValue);
274
+ const current = model.getValue();
275
+ if (value === current) return;
276
+ const shorter = Math.min(current.length, value.length);
277
+ let from = 0;
278
+ while (from < shorter && current.codePointAt(from) === value.codePointAt(from)) from += 1;
279
+ let currentEnd = current.length;
280
+ let valueEnd = value.length;
281
+ while (currentEnd > from && valueEnd > from && current.codePointAt(currentEnd - 1) === value.codePointAt(valueEnd - 1)) {
282
+ currentEnd -= 1;
283
+ valueEnd -= 1;
284
+ }
285
+ const start = model.getPositionAt(from);
286
+ const end = model.getPositionAt(currentEnd);
287
+ model.applyEdits([{
288
+ range: {
289
+ startLineNumber: start.lineNumber,
290
+ startColumn: start.column,
291
+ endLineNumber: end.lineNumber,
292
+ endColumn: end.column
293
+ },
294
+ text: value.slice(from, valueEnd)
295
+ }]);
296
+ }
297
+ function modelValueMatches(model, externalValue) {
298
+ return model.getValue() === normalizeModelValue(model, externalValue);
299
+ }
300
+ function normalizeModelValue(model, externalValue) {
301
+ return externalValue.split(/\r\n|\r|\n/).join(model.getEOL());
302
+ }
303
+ //#endregion
304
+ //#region src/replace.ts
305
+ function replaceInEditor(target, search, replaceWith, all) {
306
+ const model = target?.getModel();
307
+ if (search === "" || !target || !model) return false;
308
+ const source = model.getValue();
309
+ const offsets = [];
310
+ let from = 0;
311
+ for (;;) {
312
+ const index = source.indexOf(search, from);
313
+ if (index === -1) break;
314
+ offsets.push(index);
315
+ if (!all) break;
316
+ from = index + search.length;
317
+ }
318
+ if (offsets.length === 0) return false;
319
+ const edits = offsets.map((offset) => {
320
+ const start = model.getPositionAt(offset);
321
+ const end = model.getPositionAt(offset + search.length);
322
+ return {
323
+ range: {
324
+ startLineNumber: start.lineNumber,
325
+ startColumn: start.column,
326
+ endLineNumber: end.lineNumber,
327
+ endColumn: end.column
328
+ },
329
+ text: replaceWith
330
+ };
331
+ });
332
+ return target.executeEdits("inkstone-replace", edits);
333
+ }
334
+ //#endregion
335
+ //#region src/shiki-bridge.ts
336
+ const SHIKI_REGISTRY_KEY = Symbol.for("coldsmirk.inkstone.monaco.shikiRegistry");
337
+ function registeredModules() {
338
+ const host = globalThis;
339
+ const existing = host[SHIKI_REGISTRY_KEY];
340
+ if (existing) return existing;
341
+ const created = /* @__PURE__ */ new WeakSet();
342
+ host[SHIKI_REGISTRY_KEY] = created;
343
+ return created;
344
+ }
345
+ function registerShikiHighlighting(monaco, highlighter) {
346
+ const registry = registeredModules();
347
+ if (registry.has(monaco)) return;
348
+ const canonical = new Set(highlighter.getLoadedLanguages().map((id) => highlighter.getLanguage(id).name));
349
+ const registered = new Set(monaco.languages.getLanguages().map((registeredLanguage) => registeredLanguage.id));
350
+ for (const lang of canonical) if (!registered.has(lang)) monaco.languages.register({ id: lang });
351
+ const shikiThemes = new Set(highlighter.getLoadedThemes());
352
+ const originalCreate = monaco.editor.create;
353
+ const originalSetTheme = monaco.editor.setTheme;
354
+ try {
355
+ shikiToMonaco(highlighter, monaco);
356
+ const setShikiTheme = monaco.editor.setTheme;
357
+ monaco.editor.setTheme = (themeName) => {
358
+ if (shikiThemes.has(themeName)) setShikiTheme.call(monaco.editor, themeName);
359
+ else originalSetTheme.call(monaco.editor, themeName);
360
+ };
361
+ } catch (error) {
362
+ monaco.editor.create = originalCreate;
363
+ monaco.editor.setTheme = originalSetTheme;
364
+ throw error;
365
+ }
366
+ registry.add(monaco);
367
+ }
368
+ //#endregion
237
369
  //#region src/streaming.ts
238
370
  const UTF8_BOM = "";
239
371
  var StreamingEditorController = class {
@@ -341,35 +473,6 @@ var StreamingEditorController = class {
341
473
  this.releaseAll();
342
474
  }
343
475
  }
344
- replace(search, replaceWith, all) {
345
- const model = this.editor?.getModel();
346
- if (search === "" || !this.editor || !model) return false;
347
- const source = model.getValue();
348
- const offsets = [];
349
- let from = 0;
350
- for (;;) {
351
- const index = source.indexOf(search, from);
352
- if (index === -1) break;
353
- offsets.push(index);
354
- if (!all) break;
355
- from = index + search.length;
356
- }
357
- if (offsets.length === 0) return false;
358
- const edits = offsets.map((offset) => {
359
- const start = model.getPositionAt(offset);
360
- const end = model.getPositionAt(offset + search.length);
361
- return {
362
- range: {
363
- startLineNumber: start.lineNumber,
364
- startColumn: start.column,
365
- endLineNumber: end.lineNumber,
366
- endColumn: end.column
367
- },
368
- text: replaceWith
369
- };
370
- });
371
- return this.editor.executeEdits("inkstone-stream-replace", edits);
372
- }
373
476
  };
374
477
  //#endregion
375
- export { StreamingEditorController, disabledKeybindings, ensureMonacoHost, installDisabledKeybindings, monacoLanguages };
478
+ export { DEFAULT_MONACO_OPTIONS, StreamingEditorController, disabledKeybindings, ensureMonacoHost, installDisabledKeybindings, modelValueMatches, monacoLanguages, reconcileModelValue, registerShikiHighlighting, replaceInEditor };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@coldsmirk/inkstone-monaco",
3
- "version": "0.10.1",
4
- "description": "Framework-agnostic Monaco assembly: lazy offline host (all language workers bundled, no CDN), opt-in Simplified-Chinese UI via monaco's official NLS catalog, and a streaming editor controller for AI-typed content.",
3
+ "version": "0.12.0",
4
+ "description": "Framework-agnostic Monaco assembly: lazy offline host (all language workers bundled, no CDN), opt-in Simplified-Chinese UI via monaco's official NLS catalog, a streaming editor controller for AI-typed content, and the shared Shiki highlighting bridge.",
5
5
  "keywords": [
6
6
  "monaco",
7
7
  "monaco-editor",
@@ -34,6 +34,10 @@
34
34
  "files": [
35
35
  "dist"
36
36
  ],
37
+ "dependencies": {
38
+ "@shikijs/monaco": "^4.3.1",
39
+ "@coldsmirk/inkstone-core": "^0.12.0"
40
+ },
37
41
  "devDependencies": {
38
42
  "monaco-editor": "^0.55.1"
39
43
  },