@ruckc/truss-code 1.34.0 → 1.36.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
@@ -22,9 +22,11 @@ npm install monaco-editor # only if you use the editors
22
22
  </script>
23
23
 
24
24
  <CodeEditor bind:value={sql} language="sql" height={240} />
25
- <CodeBlock code={sql} language="sql" />
25
+ <CodeBlock code={sql} language="sql" copy />
26
26
  ```
27
27
 
28
+ `CodeBlock` colours with the small built-in highlighter and only uses Monaco's tokenizers when something else (an editor on the page) has already loaded Monaco, so a read-only block never downloads it. Set `highlighter="monaco"` on a block, or `configureCodeEditor({ highlighter: 'monaco' })` for every read-only view, to always load Monaco for colouring, or `'lite'` to never use it. `copy` adds a Copy button; to render Markdown fences with it, pass `{#snippet code({ lang, text })}<CodeBlock code={text} language={lang} copy />{/snippet}` to `@ruckc/truss-markdown`'s `Markdown`. That package does not depend on this one.
29
+
28
30
  ## License
29
31
 
30
32
  MIT
@@ -1,7 +1,10 @@
1
1
  <script lang="ts">
2
- import { onMount } from 'svelte';
2
+ import { onMount, onDestroy } from 'svelte';
3
+ import { Button, Tooltip } from '@ruckc/truss-ui';
3
4
  import type { ClassValue } from 'svelte/elements';
4
- import { highlightText } from './syntax.js';
5
+ import { highlightText, effectiveHighlighter } from './syntax.js';
6
+ import { isMonacoLoaded, onMonacoLoaded } from './monaco.js';
7
+ import type { Highlighter } from './editor-defaults.svelte.js';
5
8
  import { segmentLine, splitLines, paletteVars, type Seg } from './highlight.js';
6
9
  import { resolveLanguage, modelLanguage, type SqlDialect } from './lang.js';
7
10
  import { readTheme, watchTheme, type Theme } from './theme.js';
@@ -18,6 +21,8 @@
18
21
  maxLines,
19
22
  height,
20
23
  follow = $bindable(false),
24
+ copy = false,
25
+ highlighter,
21
26
  class: klass,
22
27
  style: userStyle,
23
28
  ...rest
@@ -45,6 +50,13 @@
45
50
  * It turns `false` when the reader scrolls up and `true` again at the bottom, so setting it to `true` jumps to the end. Bindable.
46
51
  */
47
52
  follow?: boolean;
53
+ /** Show a Copy button in the corner that puts `code` on the clipboard; "Copied" or "Copy failed" is announced politely. */
54
+ copy?: boolean;
55
+ /**
56
+ * Which tokenizer colours the code: `lite` is the small built-in one, `monaco` loads Monaco through the registered loader, and `auto` (the default,
57
+ * unless `configureCodeEditor({ highlighter })` says otherwise) uses Monaco only when something else has already loaded it, so a read-only block never downloads it.
58
+ */
59
+ highlighter?: Highlighter;
48
60
  class?: ClassValue;
49
61
  style?: string;
50
62
  [attr: string]: unknown;
@@ -95,18 +107,57 @@
95
107
  return watchTheme(el, () => (theme = readTheme(el)));
96
108
  });
97
109
 
110
+ // `auto` colours with the built-in tokenizer, then again with Monaco if an editor loads it later
111
+ let monacoSeen = $state(isMonacoLoaded());
112
+ $effect(() => {
113
+ const text = code, language = lang, mode = effectiveHighlighter(highlighter, 'auto');
114
+ if (mode === 'auto' && !monacoSeen) return onMonacoLoaded(() => (monacoSeen = true));
115
+ });
98
116
  $effect(() => {
99
- const text = code, language = lang;
117
+ const text = code, language = lang, mode = effectiveHighlighter(highlighter, 'auto');
118
+ void monacoSeen;
100
119
  let stale = false;
101
- highlightText(text, language).then((segs) => { if (!stale) tokens = { code: text, lang: language, segs }; });
120
+ highlightText(text, language, mode).then((segs) => { if (!stale) tokens = { code: text, lang: language, segs }; });
102
121
  return () => { stale = true; };
103
122
  });
123
+
124
+ let status = $state('');
125
+ let timer: ReturnType<typeof setTimeout>;
126
+ onDestroy(() => clearTimeout(timer));
127
+ async function copyCode() {
128
+ try {
129
+ await navigator.clipboard.writeText(code);
130
+ status = 'Copied';
131
+ } catch {
132
+ status = 'Copy failed';
133
+ }
134
+ clearTimeout(timer);
135
+ timer = setTimeout(() => (status = ''), 2000);
136
+ }
104
137
  </script>
105
138
 
139
+ {#snippet block()}
106
140
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
107
141
  <pre {...rest} bind:this={el} role="region" class={['cb', klass]} class:wrap class:nums={lineNumbers} {style} {onscroll} tabindex="0" aria-label={label}><code>{#each lines as segs, i (i)}<span class="ln">{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="tx">{#each segs as s}<span class={s.role ? `s-${s.role}` : undefined}>{s.text}</span>{/each}{'\n'}</span></span>{/each}</code></pre>
142
+ {/snippet}
143
+
144
+ {#if copy}
145
+ <div class="box">
146
+ {@render block()}
147
+ <span class="copy">
148
+ <Tooltip text="Copy code">
149
+ <Button variant="minimal" size="sm" icon={status === 'Copied' ? 'tick' : 'copy'} aria-label="Copy code" tooltip={false} onclick={copyCode} />
150
+ </Tooltip>
151
+ </span>
152
+ <span class="tr-visually-hidden" role="status" aria-live="polite">{status}</span>
153
+ </div>
154
+ {:else}
155
+ {@render block()}
156
+ {/if}
108
157
 
109
158
  <style>
159
+ .box { position: relative; }
160
+ .copy { position: absolute; top: var(--tr-space-1); inset-inline-end: var(--tr-space-1); }
110
161
  .cb {
111
162
  margin: 0; padding: var(--tr-space-3) var(--tr-space-4); overflow: auto; border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md);
112
163
  background: var(--code-bg, var(--tr-surface)); color: var(--code-fg, var(--tr-on-surface)); font-family: var(--tr-font-mono); font-size: var(--tr-text-md); line-height: 1.5; tab-size: 4;
@@ -1,4 +1,5 @@
1
1
  import type { ClassValue } from 'svelte/elements';
2
+ import type { Highlighter } from './editor-defaults.svelte.js';
2
3
  import { type SqlDialect } from './lang.js';
3
4
  type $$ComponentProps = {
4
5
  /** The text to show. */
@@ -24,6 +25,13 @@ type $$ComponentProps = {
24
25
  * It turns `false` when the reader scrolls up and `true` again at the bottom, so setting it to `true` jumps to the end. Bindable.
25
26
  */
26
27
  follow?: boolean;
28
+ /** Show a Copy button in the corner that puts `code` on the clipboard; "Copied" or "Copy failed" is announced politely. */
29
+ copy?: boolean;
30
+ /**
31
+ * Which tokenizer colours the code: `lite` is the small built-in one, `monaco` loads Monaco through the registered loader, and `auto` (the default,
32
+ * unless `configureCodeEditor({ highlighter })` says otherwise) uses Monaco only when something else has already loaded it, so a read-only block never downloads it.
33
+ */
34
+ highlighter?: Highlighter;
27
35
  class?: ClassValue;
28
36
  style?: string;
29
37
  [attr: string]: unknown;
@@ -1,4 +1,10 @@
1
1
  import type * as Monaco from 'monaco-editor';
2
+ /**
3
+ * Which tokenizer the read-only views (`CodeBlock`, `DiffView`, `MergeView`) colour with: `monaco` loads Monaco through the registered loader,
4
+ * `auto` uses Monaco only when it is already loaded (an editor is on the page) and otherwise the small built-in highlighter, and `lite`
5
+ * always uses the built-in highlighter.
6
+ */
7
+ export type Highlighter = 'auto' | 'monaco' | 'lite';
2
8
  /** Editor options that `configureCodeEditor` can set for every `CodeEditor`. Each is the prop of the same name. */
3
9
  export interface CodeEditorDefaults {
4
10
  minimap?: boolean;
@@ -8,6 +14,8 @@ export interface CodeEditorDefaults {
8
14
  autoSurround?: 'languageDefined' | 'quotes' | 'brackets' | 'never';
9
15
  autoClosingBrackets?: 'always' | 'languageDefined' | 'beforeWhitespace' | 'never';
10
16
  autoClosingQuotes?: 'always' | 'languageDefined' | 'beforeWhitespace' | 'never';
17
+ /** The tokenizer for the read-only views, app-wide; a `CodeBlock`'s own `highlighter` prop wins. Unset, `CodeBlock` uses `auto` and the diff and merge views use `monaco`. */
18
+ highlighter?: Highlighter;
11
19
  /** Monaco options applied to every editor beneath each editor's own `options` (the two are merged key by key). */
12
20
  options?: Monaco.editor.IStandaloneEditorConstructionOptions;
13
21
  }
package/dist/lite.d.ts CHANGED
@@ -4,7 +4,7 @@ export { default as DiffView } from './DiffView.svelte';
4
4
  export { default as DiffFiles } from './DiffFiles.svelte';
5
5
  export { default as MergeView } from './MergeView.svelte';
6
6
  export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
7
- export { setMonacoLoader, loadMonaco } from './monaco.js';
7
+ export { setMonacoLoader, loadMonaco, isMonacoLoaded } from './monaco.js';
8
8
  export { fallbackHighlight } from './fallback.js';
9
9
  export { markLines } from './patch-text.js';
10
10
  export { configureCodeEditor } from './editor-defaults.svelte.js';
@@ -14,7 +14,7 @@ export { detectMoves } from './moves.js';
14
14
  export { parsePatch, patchLines, layoutPatch, unquotePath, filePath } from './patch.js';
15
15
  export { entriesFromPatch, buildTree } from './files.js';
16
16
  export { diff3, render as renderMerge, mergeText, chosenLines, customResolution } from './merge.js';
17
- export type { CodeEditorDefaults } from './editor-defaults.svelte.js';
17
+ export type { CodeEditorDefaults, Highlighter } from './editor-defaults.svelte.js';
18
18
  export type { MonacoApi, MonacoLoader } from './monaco.js';
19
19
  export type { SqlDialect } from './lang.js';
20
20
  export type { CodeMarker, MarkerSeverity, CompletionItem, CompletionKind, CompletionContext, DiffAnnotation } from './types.js';
package/dist/lite.js CHANGED
@@ -7,7 +7,7 @@ export { default as DiffView } from './DiffView.svelte';
7
7
  export { default as DiffFiles } from './DiffFiles.svelte';
8
8
  export { default as MergeView } from './MergeView.svelte';
9
9
  export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
10
- export { setMonacoLoader, loadMonaco } from './monaco.js';
10
+ export { setMonacoLoader, loadMonaco, isMonacoLoaded } from './monaco.js';
11
11
  export { fallbackHighlight } from './fallback.js';
12
12
  export { markLines } from './patch-text.js';
13
13
  // app-wide editor defaults: config only (its Monaco import is type-only), so calling it at startup pulls no editor code into the entry chunk
package/dist/monaco.d.ts CHANGED
@@ -13,6 +13,10 @@ export type LanguageSetup = (monaco: MonacoApi) => Promise<void>;
13
13
  * fallback highlighter. The most recent loader wins. Pass `undefined` to forget it.
14
14
  */
15
15
  export declare function setMonacoLoader(next: MonacoLoader | undefined): void;
16
+ /** Whether Monaco has finished loading (an editor mounted, or something called `loadMonaco`). The read-only views use it to highlight with Monaco only when that costs nothing. */
17
+ export declare const isMonacoLoaded: () => boolean;
18
+ /** Calls `fn` once Monaco has loaded (immediately never: check `isMonacoLoaded` first). Returns the function that cancels it. */
19
+ export declare function onMonacoLoaded(fn: () => void): () => void;
16
20
  /** Monaco's worker label to the kind of worker that serves it. */
17
21
  export declare const workerKind: (label: string) => string;
18
22
  /** Whether a loader has been registered (`CodeEditor` and `DiffEditor` register the built-in one when they are bundled). */
package/dist/monaco.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { readTheme, monacoTheme } from './theme.js';
2
2
  let loader;
3
3
  let pending;
4
+ let loaded = false;
5
+ const loadedListeners = new Set();
4
6
  const languageSetups = new Map();
5
7
  /**
6
8
  * Tells the package where Monaco comes from, so that this module never names `monaco-editor` itself and a bundler sees no import of it.
@@ -10,6 +12,14 @@ const languageSetups = new Map();
10
12
  export function setMonacoLoader(next) {
11
13
  loader = next;
12
14
  pending = undefined;
15
+ loaded = false;
16
+ }
17
+ /** Whether Monaco has finished loading (an editor mounted, or something called `loadMonaco`). The read-only views use it to highlight with Monaco only when that costs nothing. */
18
+ export const isMonacoLoaded = () => loaded;
19
+ /** Calls `fn` once Monaco has loaded (immediately never: check `isMonacoLoaded` first). Returns the function that cancels it. */
20
+ export function onMonacoLoaded(fn) {
21
+ loadedListeners.add(fn);
22
+ return () => void loadedListeners.delete(fn);
13
23
  }
14
24
  /** Monaco's worker label to the kind of worker that serves it. */
15
25
  export const workerKind = (label) => label === 'json' ? 'json' : ['css', 'scss', 'less'].includes(label) ? 'css' : ['html', 'handlebars', 'razor'].includes(label) ? 'html' : ['typescript', 'javascript'].includes(label) ? 'typescript' : 'editor';
@@ -32,7 +42,14 @@ export function loadMonaco() {
32
42
  return Promise.reject(new Error('@ruckc/truss-code: Monaco is not configured. Call setMonacoLoader(() => import("monaco-editor")) or useMonaco() from "@ruckc/truss-code/monaco".'));
33
43
  if (!pending) {
34
44
  const mine = (pending = loader());
35
- mine.catch(() => { if (pending === mine)
45
+ mine.then(() => {
46
+ if (pending !== mine)
47
+ return;
48
+ loaded = true;
49
+ for (const fn of [...loadedListeners])
50
+ fn();
51
+ loadedListeners.clear();
52
+ }, () => { if (pending === mine)
36
53
  pending = undefined; }); // a failed load (offline, blocked chunk) can be retried by the next mount
37
54
  }
38
55
  return pending;
package/dist/syntax.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { type Seg } from './highlight.js';
2
+ import { type Highlighter } from './editor-defaults.svelte.js';
3
+ /** The highlighter in effect: the view's own, else the app-wide one, else `fallback` (each view's default). */
4
+ export declare const effectiveHighlighter: (own: Highlighter | undefined, fallback: Highlighter) => Highlighter;
2
5
  /**
3
6
  * Colours `text` for the read-only views: with Monaco's tokenizers when a loader is registered and loads, and with the small built-in
4
- * tokenizer otherwise (no loader, a failed load, or Monaco failing on this input).
7
+ * tokenizer otherwise (no loader, a failed load, or Monaco failing on this input). `lite` never touches Monaco, and `auto` uses it only when
8
+ * it is already loaded.
5
9
  */
6
- export declare function highlightText(text: string, language: string): Promise<Seg[][]>;
10
+ export declare function highlightText(text: string, language: string, mode?: Highlighter): Promise<Seg[][]>;
package/dist/syntax.js CHANGED
@@ -1,11 +1,17 @@
1
1
  import { highlight } from './highlight.js';
2
2
  import { fallbackHighlight } from './fallback.js';
3
- import { loadMonaco, ensureLanguage } from './monaco.js';
3
+ import { loadMonaco, ensureLanguage, isMonacoLoaded } from './monaco.js';
4
+ import { codeEditorDefaults } from './editor-defaults.svelte.js';
5
+ /** The highlighter in effect: the view's own, else the app-wide one, else `fallback` (each view's default). */
6
+ export const effectiveHighlighter = (own, fallback) => own ?? codeEditorDefaults().highlighter ?? fallback;
4
7
  /**
5
8
  * Colours `text` for the read-only views: with Monaco's tokenizers when a loader is registered and loads, and with the small built-in
6
- * tokenizer otherwise (no loader, a failed load, or Monaco failing on this input).
9
+ * tokenizer otherwise (no loader, a failed load, or Monaco failing on this input). `lite` never touches Monaco, and `auto` uses it only when
10
+ * it is already loaded.
7
11
  */
8
- export async function highlightText(text, language) {
12
+ export async function highlightText(text, language, mode = effectiveHighlighter(undefined, 'monaco')) {
13
+ if (mode === 'lite' || (mode === 'auto' && !isMonacoLoaded()))
14
+ return fallbackHighlight(text, language);
9
15
  try {
10
16
  const m = await loadMonaco();
11
17
  await ensureLanguage(m, language);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-code",
3
- "version": "1.34.0",
3
+ "version": "1.36.0",
4
4
  "description": "Read-only code blocks, diff and merge views, plus an optional Monaco code editor, styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",