@ruckc/truss-code 1.18.3 → 1.20.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.
@@ -1,7 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { onMount } from 'svelte';
3
- import { loadMonaco, ensureLanguage } from './monaco.js';
4
- import { highlight, segmentLine, splitLines, paletteVars, type Seg } from './highlight.js';
3
+ import { highlightText } from './syntax.js';
4
+ import { segmentLine, splitLines, paletteVars, type Seg } from './highlight.js';
5
5
  import { resolveLanguage, modelLanguage, type SqlDialect } from './lang.js';
6
6
  import { readTheme, watchTheme, type Theme } from './theme.js';
7
7
 
@@ -47,10 +47,7 @@
47
47
  $effect(() => {
48
48
  const text = code, language = lang;
49
49
  let stale = false;
50
- loadMonaco().then(
51
- (m) => ensureLanguage(m, language).then(() => highlight(m, text, language)).then((segs) => { if (!stale) tokens = { code: text, lang: language, segs }; }),
52
- () => {} // without Monaco the block stays plain text
53
- );
50
+ highlightText(text, language).then((segs) => { if (!stale) tokens = { code: text, lang: language, segs }; });
54
51
  return () => { stale = true; };
55
52
  });
56
53
  </script>
@@ -1,3 +1,9 @@
1
+ <script module lang="ts">
2
+ import { useMonacoByDefault } from './monaco-default.js';
3
+ // bundling an editor is what opts the app into Monaco: unless the app registered its own loader, use the built-in one
4
+ useMonacoByDefault();
5
+ </script>
6
+
1
7
  <script lang="ts">
2
8
  import { onMount } from 'svelte';
3
9
  import type { HTMLAttributes } from 'svelte/elements';
@@ -8,6 +14,7 @@
8
14
  import { watchTheme, fontMetrics, type Metrics } from './theme.js';
9
15
  import { toMonacoMarker, toMonacoCompletion, completionProvider, type CompletionsOption } from './editor-util.js';
10
16
  import type { CodeMarker } from './types.js';
17
+ import { codeEditorDefaults } from './editor-defaults.svelte.js';
11
18
 
12
19
  let {
13
20
  value = $bindable(''),
@@ -18,17 +25,17 @@
18
25
  typescript,
19
26
  path,
20
27
  readonly = false,
21
- minimap = false,
22
- lineNumbers = true,
23
- wordWrap = false,
28
+ minimap,
29
+ lineNumbers,
30
+ wordWrap,
24
31
  height = 320,
25
- screenReader = 'auto',
32
+ screenReader,
26
33
  label = 'Code editor',
27
34
  markers = [],
28
35
  completions,
29
- autoSurround = 'languageDefined',
30
- autoClosingBrackets = 'languageDefined',
31
- autoClosingQuotes = 'languageDefined',
36
+ autoSurround,
37
+ autoClosingBrackets,
38
+ autoClosingQuotes,
32
39
  options,
33
40
  onchange,
34
41
  onsave,
@@ -213,24 +220,26 @@
213
220
  synced = text;
214
221
  });
215
222
 
216
- // options: props first, then the passthrough, then the theme's type metrics
223
+ // options: props first (else the `configureCodeEditor` defaults, else Monaco's), then the passthrough, then the theme's type metrics
217
224
  $effect(() => {
218
225
  if (!editor) return;
226
+ const dflt = codeEditorDefaults();
219
227
  editor.updateOptions({
220
228
  readOnly: readonly,
221
- minimap: { enabled: minimap },
222
- lineNumbers: lineNumbers ? 'on' : 'off',
223
- wordWrap: wordWrap ? 'on' : 'off',
224
- accessibilitySupport: screenReader,
229
+ minimap: { enabled: minimap ?? dflt.minimap ?? false },
230
+ lineNumbers: (lineNumbers ?? dflt.lineNumbers ?? true) ? 'on' : 'off',
231
+ wordWrap: (wordWrap ?? dflt.wordWrap ?? false) ? 'on' : 'off',
232
+ accessibilitySupport: screenReader ?? dflt.screenReader ?? 'auto',
225
233
  ariaLabel: label,
226
- autoSurround,
227
- autoClosingBrackets,
228
- autoClosingQuotes,
234
+ autoSurround: autoSurround ?? dflt.autoSurround ?? 'languageDefined',
235
+ autoClosingBrackets: autoClosingBrackets ?? dflt.autoClosingBrackets ?? 'languageDefined',
236
+ autoClosingQuotes: autoClosingQuotes ?? dflt.autoClosingQuotes ?? 'languageDefined',
229
237
  // Monaco's quick-fix bulb is a listbox without an accessible name; keep it off unless you opt in through `options`
230
238
  lightbulb: { enabled: 'off' as Monaco.editor.ShowLightbulbIconMode },
231
239
  fontSize: metrics.fontSize,
232
240
  lineHeight: metrics.lineHeight,
233
241
  fontFamily: metrics.fontFamily,
242
+ ...dflt.options,
234
243
  ...options
235
244
  });
236
245
  });
@@ -1,3 +1,9 @@
1
+ <script module lang="ts">
2
+ import { useMonacoByDefault } from './monaco-default.js';
3
+ // bundling an editor is what opts the app into Monaco: unless the app registered its own loader, use the built-in one
4
+ useMonacoByDefault();
5
+ </script>
6
+
1
7
  <script lang="ts">
2
8
  import { onMount } from 'svelte';
3
9
  import { Skeleton } from '@ruckc/truss-ui';
@@ -44,6 +44,6 @@ type $$ComponentProps = {
44
44
  load?: LoadText;
45
45
  class?: string;
46
46
  } & Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class' | 'role' | 'onkeydown'>;
47
- declare const DiffFiles: import("svelte").Component<$$ComponentProps, {}, "collapsed" | "selected" | "layout" | "viewed">;
47
+ declare const DiffFiles: import("svelte").Component<$$ComponentProps, {}, "selected" | "collapsed" | "layout" | "viewed">;
48
48
  type DiffFiles = ReturnType<typeof DiffFiles>;
49
49
  export default DiffFiles;
@@ -11,8 +11,8 @@
11
11
  import { offsets, rulerRuns, windowOf, type Lane } from './virtual.js';
12
12
  import { layoutPatch, parsePatch } from './patch.js';
13
13
  import { cachedLoader, type LoadText } from './load.js';
14
- import { highlight, overlay, paletteVars, segmentLine, type Seg } from './highlight.js';
15
- import { loadMonaco } from './monaco.js';
14
+ import { overlay, paletteVars, segmentLine, type Seg } from './highlight.js';
15
+ import { highlightText } from './syntax.js';
16
16
  import { resolveLanguage } from './lang.js';
17
17
  import { readTheme, watchTheme, type Theme } from './theme.js';
18
18
  import type { PatchFile } from './patch.js';
@@ -81,7 +81,7 @@
81
81
  granularity?: 'line' | 'word' | 'char';
82
82
  ignoreWhitespace?: boolean;
83
83
  ignoreCase?: boolean;
84
- /** Colour the code with Monaco's tokenizers (loaded on demand; only when the language is known and the diff is under 20000 lines). */
84
+ /** Colour the code (only when the language is known and the diff is under 20000 lines): with Monaco's tokenizers when a Monaco loader is registered, else with the small built-in highlighter. */
85
85
  highlight?: boolean;
86
86
  /** Above this many lines in `old` plus `new`, a placeholder with a "Show anyway" button replaces the diff. Rendering is virtual, so the default is high. */
87
87
  maxLines?: number;
@@ -306,13 +306,9 @@
306
306
  const d = docs, language = lang, ls = lines;
307
307
  if (!syntax || language === 'plaintext' || !ls.length || ls.length > HIGHLIGHT_MAX) return;
308
308
  let stale = false;
309
- loadMonaco().then(
310
- async (m) => {
311
- const [o, n] = await Promise.all([highlight(m, d.old, language), highlight(m, d.new, language)]);
312
- if (!stale) hl = { lines: ls, lang: language, old: o, new: n };
313
- },
314
- () => {} // without Monaco the diff stays uncoloured
315
- );
309
+ Promise.all([highlightText(d.old, language), highlightText(d.new, language)]).then(([o, n]) => {
310
+ if (!stale) hl = { lines: ls, lang: language, old: o, new: n };
311
+ });
316
312
  return () => { stale = true; };
317
313
  });
318
314
 
@@ -683,10 +679,10 @@
683
679
  <span class="note">{e.f.count ? `${e.f.count} unchanged ${e.f.count === 1 ? 'line' : 'lines'} not in this patch` : 'Lines not in this patch'}</span>
684
680
  {:else}
685
681
  {#if !e.f.fixed && e.f.count > EXPAND}
686
- <Button size="sm" variant="minimal" intent="neutral" aria-label="Show {EXPAND} more lines from above" onclick={() => grow(e.f, 'top')}>&darr; {EXPAND}</Button>
687
- <Button size="sm" variant="minimal" intent="neutral" aria-label="Show {EXPAND} more lines from below" onclick={() => grow(e.f, 'bottom')}>&uarr; {EXPAND}</Button>
682
+ <Button size="sm" variant="minimal" intent="neutral" aria-label="Show {EXPAND} more lines from above" data-testid="diff-expand-above" data-fold={e.f.key} onclick={() => grow(e.f, 'top')}>&darr; {EXPAND}</Button>
683
+ <Button size="sm" variant="minimal" intent="neutral" aria-label="Show {EXPAND} more lines from below" data-testid="diff-expand-below" data-fold={e.f.key} onclick={() => grow(e.f, 'bottom')}>&uarr; {EXPAND}</Button>
688
684
  {/if}
689
- <Button size="sm" variant="minimal" intent="neutral" loading={busy === e.f.key} onclick={() => (e.f.fixed ? fill(e.f) : grow(e.f, 'all'))}>{failed?.key === e.f.key ? 'Retry' : `Expand ${e.f.count === 1 ? '1 line' : `${e.f.count} lines`}`}</Button>
685
+ <Button size="sm" variant="minimal" intent="neutral" data-testid="diff-expand" data-fold={e.f.key} data-lines={e.f.count} loading={busy === e.f.key} onclick={() => (e.f.fixed ? fill(e.f) : grow(e.f, 'all'))}>{failed?.key === e.f.key ? 'Retry' : `Expand ${e.f.count === 1 ? '1 line' : `${e.f.count} lines`}`}</Button>
690
686
  {#if failed?.key === e.f.key}<span class="note err" role="alert">Could not load the file: {failed.message}</span>{/if}
691
687
  {/if}
692
688
  </td></tr>
@@ -30,7 +30,7 @@ type $$ComponentProps = {
30
30
  granularity?: 'line' | 'word' | 'char';
31
31
  ignoreWhitespace?: boolean;
32
32
  ignoreCase?: boolean;
33
- /** Colour the code with Monaco's tokenizers (loaded on demand; only when the language is known and the diff is under 20000 lines). */
33
+ /** Colour the code (only when the language is known and the diff is under 20000 lines): with Monaco's tokenizers when a Monaco loader is registered, else with the small built-in highlighter. */
34
34
  highlight?: boolean;
35
35
  /** Above this many lines in `old` plus `new`, a placeholder with a "Show anyway" button replaces the diff. Rendering is virtual, so the default is high. */
36
36
  maxLines?: number;
@@ -3,8 +3,8 @@
3
3
  import { Button, SegmentedControl, Textarea } from '@ruckc/truss-ui';
4
4
  import { diff3, render, chosenLines, customResolution, linesText, type Choice, type Merge, type MergeLabels, type Resolution } from './merge.js';
5
5
  import { splitDocument, type Line } from './diff.js';
6
- import { highlight, paletteVars, segmentLine, type Seg } from './highlight.js';
7
- import { loadMonaco } from './monaco.js';
6
+ import { paletteVars, segmentLine, type Seg } from './highlight.js';
7
+ import { highlightText } from './syntax.js';
8
8
  import { resolveLanguage } from './lang.js';
9
9
  import { readTheme, watchTheme, type Theme } from './theme.js';
10
10
 
@@ -24,9 +24,9 @@
24
24
  }
25
25
 
26
26
  let {
27
- base = '',
28
- ours = '',
29
- theirs = '',
27
+ base: baseProp,
28
+ ours: oursProp,
29
+ theirs: theirsProp,
30
30
  path,
31
31
  language,
32
32
  result = $bindable(''),
@@ -34,13 +34,14 @@
34
34
  labels,
35
35
  highlight: syntax = true,
36
36
  label = 'Merge',
37
+ load,
37
38
  onresolve
38
39
  }: {
39
- /** The common ancestor. */
40
+ /** The common ancestor. Omit it (with `load`) to have it fetched; without either it is empty. */
40
41
  base?: string;
41
- /** Our version (the left side of the merge). */
42
+ /** Our version (the left side of the merge). Omit it (with `load`) to have it fetched. */
42
43
  ours?: string;
43
- /** Their version (the side being merged in). */
44
+ /** Their version (the side being merged in). Omit it (with `load`) to have it fetched. */
44
45
  theirs?: string;
45
46
  /** File name: sets the language for syntax colours and the accessible name. */
46
47
  path?: string;
@@ -52,9 +53,16 @@
52
53
  conflicts?: number;
53
54
  /** Names for the three sides in the headings and the conflict markers. */
54
55
  labels?: MergeLabels;
55
- /** Colour the code with Monaco's tokenizers (loaded on demand; only when the language is known). */
56
+ /** Colour the code (only when the language is known): with Monaco's tokenizers when a Monaco loader is registered, else with the small built-in highlighter. */
56
57
  highlight?: boolean;
57
58
  label?: string;
59
+ /**
60
+ * Fetches the whole text of a side you did not pass as a prop, e.g. when the app only has conflict regions and assembles
61
+ * the files on demand (like `DiffFiles`' `load`). All missing sides are fetched together when the view mounts, and again when
62
+ * `load` or the set of missing sides changes. While they load the view shows "Loading..." and reports no merge;
63
+ * a rejection shows the error with a Retry button. A side passed as a prop is never fetched.
64
+ */
65
+ load?: (side: 'base' | 'ours' | 'theirs') => Promise<string>;
58
66
  /** Called whenever the merge changes: new inputs, or a conflict resolved, edited or reset. */
59
67
  onresolve?: (state: MergeState) => void;
60
68
  } = $props();
@@ -76,6 +84,35 @@
76
84
  let hlResult = $state.raw<{ lang: string; text: string; rows: Seg[][] }>();
77
85
 
78
86
  // ───── the merge, and what has been decided about its conflicts (kept per merge, so new inputs start afresh)
87
+ let loaded = $state.raw<Partial<Record<Col, string>>>({});
88
+ let loading = $state(false);
89
+ let loadError = $state<string>();
90
+ let attempt = $state(0);
91
+ const base = $derived(baseProp ?? loaded.base ?? '');
92
+ const ours = $derived(oursProp ?? loaded.ours ?? '');
93
+ const theirs = $derived(theirsProp ?? loaded.theirs ?? '');
94
+ $effect(() => {
95
+ const fetch = load;
96
+ void attempt;
97
+ const given = { base: baseProp, ours: oursProp, theirs: theirsProp };
98
+ const sides = COLS.filter((c) => given[c] === undefined);
99
+ untrack(() => { loading = !!fetch && sides.length > 0; loadError = undefined; });
100
+ if (!fetch || !sides.length) return;
101
+ let stale = false;
102
+ Promise.all(sides.map(async (side) => fetch(side))).then(
103
+ (texts) => {
104
+ if (stale) return;
105
+ loaded = { ...loaded, ...Object.fromEntries(sides.map((side, i) => [side, texts[i]])) };
106
+ loading = false;
107
+ },
108
+ (err) => {
109
+ if (stale) return;
110
+ loadError = err instanceof Error ? err.message : String(err);
111
+ loading = false;
112
+ }
113
+ );
114
+ return () => { stale = true; };
115
+ });
79
116
  const merge = $derived(diff3(base, ours, theirs));
80
117
  let decided = $state.raw<{ merge: Merge; list: (Resolution | undefined)[] }>();
81
118
  const resolutions = $derived(decided?.merge === merge ? decided.list : []);
@@ -88,11 +125,13 @@
88
125
  const name = $derived(path ?? '');
89
126
 
90
127
  $effect.pre(() => {
128
+ if (loading) return;
91
129
  result = out.text;
92
130
  conflicts = out.conflicts;
93
131
  });
94
132
  $effect(() => {
95
133
  const o = out;
134
+ if (untrack(() => loading)) return;
96
135
  untrack(() => onresolve?.({ result: o.text, resolved: o.resolved, conflicts: o.conflicts }));
97
136
  });
98
137
  $effect.pre(() => {
@@ -100,7 +139,7 @@
100
139
  untrack(() => { cur = -1; editing = null; announce = ''; });
101
140
  });
102
141
 
103
- const status = $derived(total ? `${out.resolved} of ${total} ${total === 1 ? 'conflict' : 'conflicts'} resolved` : 'No conflicts');
142
+ const status = $derived(loading ? 'Loading...' : total ? `${out.resolved} of ${total} ${total === 1 ? 'conflict' : 'conflicts'} resolved` : 'No conflicts');
104
143
 
105
144
  function decide(c: number, res: Resolution | undefined) {
106
145
  const list = [...resolutions];
@@ -161,26 +200,16 @@
161
200
  const t = texts, language = lang;
162
201
  if (!syntax || language === 'plaintext') return;
163
202
  let stale = false;
164
- loadMonaco().then(
165
- async (m) => {
166
- const [b, o, th] = await Promise.all([highlight(m, t.base, language), highlight(m, t.ours, language), highlight(m, t.theirs, language)]);
167
- if (!stale) hl = { lang: language, texts: t, rows: { base: b, ours: o, theirs: th } };
168
- },
169
- () => {} // without Monaco the panes stay uncoloured
170
- );
203
+ Promise.all([highlightText(t.base, language), highlightText(t.ours, language), highlightText(t.theirs, language)]).then(([b, o, th]) => {
204
+ if (!stale) hl = { lang: language, texts: t, rows: { base: b, ours: o, theirs: th } };
205
+ });
171
206
  return () => { stale = true; };
172
207
  });
173
208
  $effect(() => {
174
209
  const t = out.text, language = lang;
175
210
  if (!syntax || language === 'plaintext') return;
176
211
  let stale = false;
177
- loadMonaco().then(
178
- async (m) => {
179
- const rows = await highlight(m, t, language);
180
- if (!stale) hlResult = { lang: language, text: t, rows };
181
- },
182
- () => {}
183
- );
212
+ highlightText(t, language).then((rows) => { if (!stale) hlResult = { lang: language, text: t, rows }; });
184
213
  return () => { stale = true; };
185
214
  });
186
215
  const segs = (col: Col, n: number, line: Line): Seg[] => (hl && hl.lang === lang && hl.texts[col] === texts[col] ? hl.rows[col][n] : undefined) ?? segmentLine(line.text, []);
@@ -255,13 +284,16 @@
255
284
  </script>
256
285
 
257
286
  <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
258
- <div bind:this={root} class="mv" {style} role="group" aria-label={name ? `${label}: ${name}` : label} data-narrow={narrow} onkeydown={onkey} aria-describedby="{uid}-help">
287
+ <div bind:this={root} class="mv" {style} role="group" aria-label={name ? `${label}: ${name}` : label} data-narrow={narrow} aria-busy={loading || undefined} onkeydown={onkey} aria-describedby="{uid}-help">
259
288
  <div class="bar">
260
289
  <span class="sum" role="status" data-testid="status" data-done={total > 0 && out.resolved === total}>{status}</span>
261
290
  <span class="grow"></span>
262
291
  <Button variant="minimal" intent="neutral" size="sm" icon="chevron-up" aria-label="Previous conflict" shortcut="p" disabled={!total} onclick={prev} />
263
292
  <Button variant="minimal" intent="neutral" size="sm" icon="chevron-down" aria-label="Next conflict" shortcut="n" disabled={!total} onclick={next} />
264
293
  </div>
294
+ {#if loadError}
295
+ <div class="load-err" role="alert" data-testid="load-error"><span>Could not load the files: {loadError}</span> <Button size="sm" variant="minimal" intent="neutral" data-testid="load-retry" onclick={() => attempt++}>Retry</Button></div>
296
+ {/if}
265
297
  <div class="vh" id="{uid}-help">Three-way merge. Press n or F7 for the next conflict, p or Shift and F7 for the previous one. Each conflict has buttons to accept one side, both sides, the base, or to edit the result.</div>
266
298
  <div class="vh" role="status" aria-live="polite" data-testid="announce">{announce}</div>
267
299
  {#if narrow}
@@ -360,6 +392,7 @@
360
392
  {/snippet}
361
393
 
362
394
  <style>
395
+ .load-err { padding: 6px 10px; color: var(--tr-danger); font-size: 0.875rem; border-bottom: 1px solid var(--tr-outline-variant); display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
363
396
  .mv {
364
397
  --m-conflict: color-mix(in srgb, var(--tr-warning) 20%, var(--code-bg, var(--tr-surface)));
365
398
  --m-conflict-strong: var(--tr-warning);
@@ -9,11 +9,11 @@ export interface MergeState {
9
9
  conflicts: number;
10
10
  }
11
11
  type $$ComponentProps = {
12
- /** The common ancestor. */
12
+ /** The common ancestor. Omit it (with `load`) to have it fetched; without either it is empty. */
13
13
  base?: string;
14
- /** Our version (the left side of the merge). */
14
+ /** Our version (the left side of the merge). Omit it (with `load`) to have it fetched. */
15
15
  ours?: string;
16
- /** Their version (the side being merged in). */
16
+ /** Their version (the side being merged in). Omit it (with `load`) to have it fetched. */
17
17
  theirs?: string;
18
18
  /** File name: sets the language for syntax colours and the accessible name. */
19
19
  path?: string;
@@ -25,9 +25,16 @@ type $$ComponentProps = {
25
25
  conflicts?: number;
26
26
  /** Names for the three sides in the headings and the conflict markers. */
27
27
  labels?: MergeLabels;
28
- /** Colour the code with Monaco's tokenizers (loaded on demand; only when the language is known). */
28
+ /** Colour the code (only when the language is known): with Monaco's tokenizers when a Monaco loader is registered, else with the small built-in highlighter. */
29
29
  highlight?: boolean;
30
30
  label?: string;
31
+ /**
32
+ * Fetches the whole text of a side you did not pass as a prop, e.g. when the app only has conflict regions and assembles
33
+ * the files on demand (like `DiffFiles`' `load`). All missing sides are fetched together when the view mounts, and again when
34
+ * `load` or the set of missing sides changes. While they load the view shows "Loading..." and reports no merge;
35
+ * a rejection shows the error with a Retry button. A side passed as a prop is never fetched.
36
+ */
37
+ load?: (side: 'base' | 'ours' | 'theirs') => Promise<string>;
31
38
  /** Called whenever the merge changes: new inputs, or a conflict resolved, edited or reset. */
32
39
  onresolve?: (state: MergeState) => void;
33
40
  };
@@ -0,0 +1,53 @@
1
+ <script lang="ts">
2
+ import type { HTMLAttributes } from 'svelte/elements';
3
+ import { markLines, type MarkKind } from './patch-text.js';
4
+
5
+ let {
6
+ text,
7
+ label = 'Patch text',
8
+ maxHeight,
9
+ wrap = false,
10
+ lineNumbers = false,
11
+ ...rest
12
+ }: Omit<HTMLAttributes<HTMLPreElement>, 'children'> & {
13
+ /** Unified-diff-like text. It does not have to be a valid patch: lines starting with `+`, `-`, `@@` or `#` are coloured, any other line is plain. */
14
+ text: string;
15
+ /** Accessible name of the scrollable region. */
16
+ label?: string;
17
+ /** A CSS length; the view scrolls beyond it. */
18
+ maxHeight?: string | number;
19
+ /** Wrap long lines instead of scrolling sideways. */
20
+ wrap?: boolean;
21
+ lineNumbers?: boolean;
22
+ } = $props();
23
+
24
+ const MARK: Partial<Record<MarkKind, { sym: string; sr: string }>> = { add: { sym: '+', sr: 'added' }, del: { sym: '−', sr: 'removed' } };
25
+ const lines = $derived(markLines(text).map((l) => ({ ...l, mark: MARK[l.kind], body: MARK[l.kind] ? l.text.slice(1) : l.text })));
26
+ const style = $derived(maxHeight != null ? `max-height:${typeof maxHeight === 'number' ? maxHeight + 'px' : maxHeight}` : undefined);
27
+ </script>
28
+
29
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
30
+ <pre {...rest} role="region" class="pt" class:wrap class:nums={lineNumbers} {style} tabindex="0" aria-label={label}><code>{#each lines as l, i (i)}<span class={"ln " + l.kind} data-kind={l.kind}>{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="sym">{#if l.mark}<span aria-hidden="true">{l.mark.sym}</span><span class="vh">{l.mark.sr + ": "}</span>{/if}</span><span class="tx">{l.body + '\n'}</span></span>{/each}</code></pre>
31
+
32
+ <style>
33
+ .pt {
34
+ --add: var(--code-added, color-mix(in srgb, var(--tr-success) 15%, var(--tr-surface)));
35
+ --del: var(--code-removed, color-mix(in srgb, var(--tr-danger) 14%, var(--tr-surface)));
36
+ margin: 0; padding: var(--tr-space-3) 0; overflow: auto; border: 1px solid var(--tr-outline-variant); border-radius: var(--tr-radius-md);
37
+ 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;
38
+ }
39
+ .pt:focus-visible { outline: none; border-color: var(--tr-primary); box-shadow: var(--tr-focus-ring); }
40
+ code { font: inherit; }
41
+ .ln { display: grid; grid-template-columns: 2ch 1fr; padding: 0 var(--tr-space-4) 0 var(--tr-space-2); }
42
+ .nums .ln { grid-template-columns: 3ch 2ch 1fr; column-gap: var(--tr-space-2); }
43
+ .no { text-align: right; color: var(--tr-on-surface-variant); user-select: none; }
44
+ .sym { text-align: center; font-weight: 700; user-select: none; }
45
+ .tx { white-space: pre; }
46
+ .wrap .tx { white-space: pre-wrap; overflow-wrap: anywhere; }
47
+ .add { background: var(--add); } .add .sym { color: var(--tr-success); }
48
+ .del { background: var(--del); } .del .sym { color: var(--tr-danger); }
49
+ .hunk { background: var(--tr-surface-container); color: var(--tr-primary); }
50
+ .heading { font-weight: 700; }
51
+ .meta { color: var(--tr-on-surface-variant); }
52
+ .vh { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
53
+ </style>
@@ -0,0 +1,15 @@
1
+ import type { HTMLAttributes } from 'svelte/elements';
2
+ type $$ComponentProps = Omit<HTMLAttributes<HTMLPreElement>, 'children'> & {
3
+ /** Unified-diff-like text. It does not have to be a valid patch: lines starting with `+`, `-`, `@@` or `#` are coloured, any other line is plain. */
4
+ text: string;
5
+ /** Accessible name of the scrollable region. */
6
+ label?: string;
7
+ /** A CSS length; the view scrolls beyond it. */
8
+ maxHeight?: string | number;
9
+ /** Wrap long lines instead of scrolling sideways. */
10
+ wrap?: boolean;
11
+ lineNumbers?: boolean;
12
+ };
13
+ declare const PatchText: import("svelte").Component<$$ComponentProps, {}, "">;
14
+ type PatchText = ReturnType<typeof PatchText>;
15
+ export default PatchText;
@@ -0,0 +1,21 @@
1
+ import type * as Monaco from 'monaco-editor';
2
+ /** Editor options that `configureCodeEditor` can set for every `CodeEditor`. Each is the prop of the same name. */
3
+ export interface CodeEditorDefaults {
4
+ minimap?: boolean;
5
+ lineNumbers?: boolean;
6
+ wordWrap?: boolean;
7
+ screenReader?: 'auto' | 'on' | 'off';
8
+ autoSurround?: 'languageDefined' | 'quotes' | 'brackets' | 'never';
9
+ autoClosingBrackets?: 'always' | 'languageDefined' | 'beforeWhitespace' | 'never';
10
+ autoClosingQuotes?: 'always' | 'languageDefined' | 'beforeWhitespace' | 'never';
11
+ /** Monaco options applied to every editor beneath each editor's own `options` (the two are merged key by key). */
12
+ options?: Monaco.editor.IStandaloneEditorConstructionOptions;
13
+ }
14
+ /**
15
+ * Sets app-wide defaults for the `CodeEditor` props listed in `CodeEditorDefaults`, e.g. `configureCodeEditor({ autoSurround: 'never' })`.
16
+ * A prop passed to an editor still wins. The call replaces the previous defaults (`configureCodeEditor({})` clears them) and
17
+ * reaches editors that are already mounted. Call it once at startup.
18
+ */
19
+ export declare function configureCodeEditor(defaults: CodeEditorDefaults): void;
20
+ /** The defaults set by `configureCodeEditor` (reactive). */
21
+ export declare const codeEditorDefaults: () => CodeEditorDefaults;
@@ -0,0 +1,11 @@
1
+ let current = $state.raw({});
2
+ /**
3
+ * Sets app-wide defaults for the `CodeEditor` props listed in `CodeEditorDefaults`, e.g. `configureCodeEditor({ autoSurround: 'never' })`.
4
+ * A prop passed to an editor still wins. The call replaces the previous defaults (`configureCodeEditor({})` clears them) and
5
+ * reaches editors that are already mounted. Call it once at startup.
6
+ */
7
+ export function configureCodeEditor(defaults) {
8
+ current = { ...defaults };
9
+ }
10
+ /** The defaults set by `configureCodeEditor` (reactive). */
11
+ export const codeEditorDefaults = () => current;
@@ -0,0 +1,3 @@
1
+ import { type Seg } from './highlight.js';
2
+ /** Tokenizes `text` as `language`, one `Seg[]` per line (the same shape Monaco's tokenizers give `highlight`). */
3
+ export declare function fallbackHighlight(text: string, language: string): Seg[][];
@@ -0,0 +1,66 @@
1
+ import { segmentLine, splitLines } from './highlight.js';
2
+ const FAMILY = {
3
+ javascript: 'c', typescript: 'c', java: 'c', c: 'c', cpp: 'c', csharp: 'c', go: 'c', rust: 'c', kotlin: 'c', swift: 'c', scala: 'c', dart: 'c', php: 'c', css: 'c', scss: 'c', less: 'c',
4
+ python: 'hash', ruby: 'hash', shell: 'hash', yaml: 'hash', ini: 'hash', dockerfile: 'hash', perl: 'hash', r: 'hash', powershell: 'hash', toml: 'hash',
5
+ sql: 'sql', pgsql: 'sql', mysql: 'sql', 'truss-sqlite': 'sql',
6
+ json: 'json', jsonc: 'json',
7
+ html: 'markup', xml: 'markup', svelte: 'markup', vue: 'markup'
8
+ };
9
+ const words = (list) => new Set(list.split(' '));
10
+ const KEYWORDS = {
11
+ c: words('as async await break case catch class const continue default delete do else enum export extends finally for from function if implements import in instanceof interface let new of package private protected public return static super switch throw try type typeof var void while yield fn func impl mod pub struct trait use mut match self this true false null undefined nil None'),
12
+ hash: words('and as assert break class continue def del elif else except finally for from global if import in is lambda not or pass raise return try while with yield end do then fi done esac function local export true false null None True False'),
13
+ sql: words('select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full cross on group by order having limit offset union all distinct as case when then else end null is in like between exists primary key foreign references default unique check constraint with returning pragma begin commit rollback true false'),
14
+ json: words('true false null'),
15
+ markup: new Set()
16
+ };
17
+ const RULES = {
18
+ c: [['comment', /\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/y], ['string', /"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?|`(?:[^`\\]|\\[\s\S])*`?/y], ['number', /\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?\b|\b0[xX][\da-fA-F]+\b/y]],
19
+ hash: [['comment', /#[^\n]*/y], ['string', /"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?/y], ['number', /\b\d[\d_]*(?:\.\d+)?\b/y]],
20
+ sql: [['comment', /--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/y], ['string', /'(?:[^']|'')*'?/y], ['number', /\b\d+(?:\.\d+)?\b/y]],
21
+ json: [['attribute', /"(?:[^"\\\n]|\\.)*"(?=\s*:)/y], ['string', /"(?:[^"\\\n]|\\.)*"?/y], ['number', /-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/y]],
22
+ markup: [['comment', /<!--[\s\S]*?(?:-->|$)/y], ['tag', /<\/?[A-Za-z][\w:.-]*|\/?>/y], ['string', /"[^"\n]*"?|'[^'\n]*'?/y]]
23
+ };
24
+ const WORD = /[A-Za-z_][\w$]*/y;
25
+ /** Tokenizes `text` as `language`, one `Seg[]` per line (the same shape Monaco's tokenizers give `highlight`). */
26
+ export function fallbackHighlight(text, language) {
27
+ const family = FAMILY[language];
28
+ if (!family || !/\S/.test(text))
29
+ return splitLines(text).map((l) => segmentLine(l, []));
30
+ text = text.replace(/\r\n?/g, '\n');
31
+ const rules = RULES[family], keywords = KEYWORDS[family], ci = family === 'sql';
32
+ const out = [[]];
33
+ const push = (chunk, role) => {
34
+ chunk.split('\n').forEach((part, i) => {
35
+ if (i)
36
+ out.push([]);
37
+ if (!part)
38
+ return;
39
+ const row = out[out.length - 1], last = row[row.length - 1];
40
+ if (last && last.role === role)
41
+ last.text += part;
42
+ else
43
+ row.push({ text: part, role });
44
+ });
45
+ };
46
+ let i = 0;
47
+ while (i < text.length) {
48
+ let hit;
49
+ for (const [role, re] of rules) {
50
+ re.lastIndex = i;
51
+ const m = re.exec(text);
52
+ if (m && m[0]) {
53
+ hit = [role, m[0]];
54
+ break;
55
+ }
56
+ }
57
+ if (!hit) {
58
+ WORD.lastIndex = i;
59
+ const m = WORD.exec(text);
60
+ hit = m ? [keywords.has(ci ? m[0].toLowerCase() : m[0]) ? 'keyword' : undefined, m[0]] : [undefined, text[i]];
61
+ }
62
+ push(hit[1], hit[0]);
63
+ i += hit[1].length;
64
+ }
65
+ return out;
66
+ }
package/dist/index.d.ts CHANGED
@@ -1,26 +1,7 @@
1
+ export * from './lite.js';
1
2
  export { default as CodeEditor } from './CodeEditor.svelte';
2
- export { default as CodeBlock } from './CodeBlock.svelte';
3
- export { default as DiffView } from './DiffView.svelte';
4
- export { default as DiffFiles } from './DiffFiles.svelte';
5
3
  export { default as DiffEditor } from './DiffEditor.svelte';
6
- export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
7
- export { loadMonaco } from './monaco.js';
4
+ export { useMonaco } from './monaco-default.js';
8
5
  export type { TypeScriptSetup } from './monaco.js';
9
- export type { SqlDialect } from './lang.js';
10
6
  export type { CompletionsOption } from './editor-util.js';
11
- export { buildPalette, monacoTheme, ensureContrast, contrast, parseColor } from './theme.js';
12
- export { diffLines, diffSeq, intraline, annotateIntraline, pairLines, inlineWords, hunkSpans, toHunks, formatHunks, unifiedPatch, foldItems, expandFold, splitRows, splitDocument, changeStarts, diffStats } from './diff.js';
13
- export { detectMoves } from './moves.js';
14
- export { parsePatch, patchLines, layoutPatch, unquotePath, filePath } from './patch.js';
15
- export { entriesFromPatch, buildTree } from './files.js';
16
- export type { CodeMarker, MarkerSeverity, CompletionItem, CompletionKind, CompletionContext, DiffAnnotation } from './types.js';
17
- export type { Palette, Role, Mode } from './theme.js';
18
- export type { DiffLine, Hunk, DiffOptions, IntraSeg, Expansion, LineSelection, Side, WordPart } from './diff.js';
19
- export type { Move, MoveOptions } from './moves.js';
20
- export type { PatchFile, FileStatus } from './patch.js';
21
- export type { DiffFileInput, DiffStatus, FileEntry } from './files.js';
22
- export type { LoadText } from './load.js';
23
- export { default as MergeView } from './MergeView.svelte';
24
- export { diff3, render as renderMerge, mergeText, chosenLines, customResolution } from './merge.js';
25
- export type { MergeState } from './MergeView.svelte';
26
- export type { Merge, MergeRegion, RegionKind, Resolution, Choice, MergeLabels, Rendered as RenderedMerge } from './merge.js';
7
+ export { configureCodeEditor, type CodeEditorDefaults } from './editor-defaults.svelte.js';
package/dist/index.js CHANGED
@@ -1,15 +1,8 @@
1
+ // The full entry: everything in `lite` plus the Monaco editors. Importing CodeEditor or DiffEditor is what opts an app into Monaco; a
2
+ // bundle that imports only the read-only views from here still tree-shakes Monaco away (the package has no side effects), but a dev server
3
+ // and the type checker still see the editors, so apps without `monaco-editor` installed should import from `@ruckc/truss-code/lite`.
4
+ export * from './lite.js';
1
5
  export { default as CodeEditor } from './CodeEditor.svelte';
2
- export { default as CodeBlock } from './CodeBlock.svelte';
3
- export { default as DiffView } from './DiffView.svelte';
4
- export { default as DiffFiles } from './DiffFiles.svelte';
5
6
  export { default as DiffEditor } from './DiffEditor.svelte';
6
- export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
7
- export { loadMonaco } from './monaco.js';
8
- export { buildPalette, monacoTheme, ensureContrast, contrast, parseColor } from './theme.js';
9
- // pure diff and patch logic, usable without any component
10
- export { diffLines, diffSeq, intraline, annotateIntraline, pairLines, inlineWords, hunkSpans, toHunks, formatHunks, unifiedPatch, foldItems, expandFold, splitRows, splitDocument, changeStarts, diffStats } from './diff.js';
11
- export { detectMoves } from './moves.js';
12
- export { parsePatch, patchLines, layoutPatch, unquotePath, filePath } from './patch.js';
13
- export { entriesFromPatch, buildTree } from './files.js';
14
- export { default as MergeView } from './MergeView.svelte';
15
- export { diff3, render as renderMerge, mergeText, chosenLines, customResolution } from './merge.js';
7
+ export { useMonaco } from './monaco-default.js';
8
+ export { configureCodeEditor } from './editor-defaults.svelte.js';
package/dist/lite.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export { default as CodeBlock } from './CodeBlock.svelte';
2
+ export { default as PatchText } from './PatchText.svelte';
3
+ export { default as DiffView } from './DiffView.svelte';
4
+ export { default as DiffFiles } from './DiffFiles.svelte';
5
+ export { default as MergeView } from './MergeView.svelte';
6
+ export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
7
+ export { setMonacoLoader, loadMonaco } from './monaco.js';
8
+ export { fallbackHighlight } from './fallback.js';
9
+ export { markLines } from './patch-text.js';
10
+ export { buildPalette, monacoTheme, ensureContrast, contrast, parseColor } from './theme.js';
11
+ export { diffLines, diffSeq, intraline, annotateIntraline, pairLines, inlineWords, hunkSpans, toHunks, formatHunks, unifiedPatch, foldItems, expandFold, splitRows, splitDocument, changeStarts, diffStats } from './diff.js';
12
+ export { detectMoves } from './moves.js';
13
+ export { parsePatch, patchLines, layoutPatch, unquotePath, filePath } from './patch.js';
14
+ export { entriesFromPatch, buildTree } from './files.js';
15
+ export { diff3, render as renderMerge, mergeText, chosenLines, customResolution } from './merge.js';
16
+ export type { MonacoApi, MonacoLoader } from './monaco.js';
17
+ export type { SqlDialect } from './lang.js';
18
+ export type { CodeMarker, MarkerSeverity, CompletionItem, CompletionKind, CompletionContext, DiffAnnotation } from './types.js';
19
+ export type { Palette, Role, Mode } from './theme.js';
20
+ export type { Seg } from './highlight.js';
21
+ export type { MarkKind, MarkedLine } from './patch-text.js';
22
+ export type { DiffLine, Hunk, DiffOptions, IntraSeg, Expansion, LineSelection, Side, WordPart } from './diff.js';
23
+ export type { Move, MoveOptions } from './moves.js';
24
+ export type { PatchFile, FileStatus } from './patch.js';
25
+ export type { DiffFileInput, DiffStatus, FileEntry } from './files.js';
26
+ export type { LoadText } from './load.js';
27
+ export type { MergeState } from './MergeView.svelte';
28
+ export type { Merge, MergeRegion, RegionKind, Resolution, Choice, MergeLabels, Rendered as RenderedMerge } from './merge.js';
package/dist/lite.js ADDED
@@ -0,0 +1,19 @@
1
+ // The Monaco-free entry (`@ruckc/truss-code/lite`): every read-only view and every pure helper, and nothing that names `monaco-editor`.
2
+ // A bundler that follows this entry never resolves, bundles or needs Monaco. Highlighting uses the small built-in tokenizer unless the app
3
+ // registers Monaco with `setMonacoLoader` (or `useMonaco()` from `@ruckc/truss-code/monaco`).
4
+ export { default as CodeBlock } from './CodeBlock.svelte';
5
+ export { default as PatchText } from './PatchText.svelte';
6
+ export { default as DiffView } from './DiffView.svelte';
7
+ export { default as DiffFiles } from './DiffFiles.svelte';
8
+ export { default as MergeView } from './MergeView.svelte';
9
+ export { detectLanguage, resolveLanguage, modelLanguage } from './lang.js';
10
+ export { setMonacoLoader, loadMonaco } from './monaco.js';
11
+ export { fallbackHighlight } from './fallback.js';
12
+ export { markLines } from './patch-text.js';
13
+ export { buildPalette, monacoTheme, ensureContrast, contrast, parseColor } from './theme.js';
14
+ // pure diff and patch logic, usable without any component
15
+ export { diffLines, diffSeq, intraline, annotateIntraline, pairLines, inlineWords, hunkSpans, toHunks, formatHunks, unifiedPatch, foldItems, expandFold, splitRows, splitDocument, changeStarts, diffStats } from './diff.js';
16
+ export { detectMoves } from './moves.js';
17
+ export { parsePatch, patchLines, layoutPatch, unquotePath, filePath } from './patch.js';
18
+ export { entriesFromPatch, buildTree } from './files.js';
19
+ export { diff3, render as renderMerge, mergeText, chosenLines, customResolution } from './merge.js';
@@ -0,0 +1,10 @@
1
+ import { type MonacoLoader } from './monaco.js';
2
+ /**
3
+ * Loads Monaco and wires its workers through the bundler: every language service worker is its own lazy chunk, fetched only when that
4
+ * language is used. If the app already set `self.MonacoEnvironment`, it is left alone.
5
+ */
6
+ export declare const monacoLoader: MonacoLoader;
7
+ /** Makes this package load Monaco itself (with its workers wired for Vite) and registers the SQLite dialect. Call it once; nothing is loaded until a component needs it. */
8
+ export declare function useMonaco(): void;
9
+ /** `useMonaco()` unless the app already registered its own loader. The editors call this when their module is evaluated. */
10
+ export declare function useMonacoByDefault(): void;
@@ -0,0 +1,39 @@
1
+ import { setMonacoLoader, setLanguageSetup, hasMonacoLoader, workerKind } from './monaco.js';
2
+ import { SQLITE_ID, SQLITE_KEYWORDS } from './lang.js';
3
+ const workers = {
4
+ json: () => import('monaco-editor/language/json/json.worker.js?worker').then((m) => () => new m.default()),
5
+ css: () => import('monaco-editor/language/css/css.worker.js?worker').then((m) => () => new m.default()),
6
+ html: () => import('monaco-editor/language/html/html.worker.js?worker').then((m) => () => new m.default()),
7
+ typescript: () => import('monaco-editor/language/typescript/ts.worker.js?worker').then((m) => () => new m.default()),
8
+ editor: () => import('monaco-editor/editor/editor.worker.js?worker').then((m) => () => new m.default())
9
+ };
10
+ /**
11
+ * Loads Monaco and wires its workers through the bundler: every language service worker is its own lazy chunk, fetched only when that
12
+ * language is used. If the app already set `self.MonacoEnvironment`, it is left alone.
13
+ */
14
+ export const monacoLoader = async () => {
15
+ const g = globalThis;
16
+ if (!g.MonacoEnvironment) {
17
+ const cache = new Map();
18
+ await Promise.all(Object.entries(workers).map(async ([k, load]) => cache.set(k, await load())));
19
+ g.MonacoEnvironment = { getWorker: (_id, label) => cache.get(workerKind(label))() };
20
+ }
21
+ return (await import('monaco-editor'));
22
+ };
23
+ /** `truss-sqlite`: Monaco's generic SQL tokenizer with the SQLite keywords added. */
24
+ async function sqliteSetup(monaco) {
25
+ monaco.languages.register({ id: SQLITE_ID, aliases: ['SQLite'] });
26
+ const { conf, language } = await import('monaco-editor/languages/definitions/sql/sql.js');
27
+ monaco.languages.setLanguageConfiguration(SQLITE_ID, conf);
28
+ monaco.languages.setMonarchTokensProvider(SQLITE_ID, { ...language, tokenPostfix: '.sqlite', keywords: [...language.keywords, ...SQLITE_KEYWORDS] });
29
+ }
30
+ /** Makes this package load Monaco itself (with its workers wired for Vite) and registers the SQLite dialect. Call it once; nothing is loaded until a component needs it. */
31
+ export function useMonaco() {
32
+ setMonacoLoader(monacoLoader);
33
+ setLanguageSetup(SQLITE_ID, sqliteSetup);
34
+ }
35
+ /** `useMonaco()` unless the app already registered its own loader. The editors call this when their module is evaluated. */
36
+ export function useMonacoByDefault() {
37
+ if (!hasMonacoLoader())
38
+ useMonaco();
39
+ }
package/dist/monaco.d.ts CHANGED
@@ -3,20 +3,30 @@ import { type Theme } from './theme.js';
3
3
  export type MonacoApi = typeof Monaco;
4
4
  /** A worker constructor, as produced by Vite's `?worker` imports. */
5
5
  export type WorkerFactory = () => Worker;
6
+ /** Loads the Monaco module. Register one with `setMonacoLoader` (or `useMonaco()` from `@ruckc/truss-code/monaco`). */
7
+ export type MonacoLoader = () => Promise<MonacoApi>;
8
+ /** Prepares one language once Monaco is loaded (the built-in loader uses it to register `truss-sqlite`). */
9
+ export type LanguageSetup = (monaco: MonacoApi) => Promise<void>;
10
+ /**
11
+ * Tells the package where Monaco comes from, so that this module never names `monaco-editor` itself and a bundler sees no import of it.
12
+ * Apps that use only the diff, merge and code-block views never call this and never bundle Monaco; they keep working with the built-in
13
+ * fallback highlighter. The most recent loader wins. Pass `undefined` to forget it.
14
+ */
15
+ export declare function setMonacoLoader(next: MonacoLoader | undefined): void;
6
16
  /** Monaco's worker label to the kind of worker that serves it. */
7
17
  export declare const workerKind: (label: string) => string;
18
+ /** Whether a loader has been registered (`CodeEditor` and `DiffEditor` register the built-in one when they are bundled). */
19
+ export declare const hasMonacoLoader: () => boolean;
20
+ /** Registers the setup that `ensureLanguage` runs for language `id`. */
21
+ export declare function setLanguageSetup(id: string, setup: LanguageSetup | undefined): void;
8
22
  /**
9
- * Loads Monaco once (a separate chunk, never during SSR) and wires its workers through the bundler:
10
- * every language service worker is its own lazy chunk that is fetched only when that language is used.
11
- * If the app already set `self.MonacoEnvironment`, it is left alone.
23
+ * Loads Monaco once through the registered loader (never during SSR). It rejects when no loader was registered, which the highlighting
24
+ * callers treat as "use the fallback highlighter".
12
25
  */
13
26
  export declare function loadMonaco(): Promise<MonacoApi>;
14
27
  /** Defines and selects the Truss theme for the tokens in effect at `host`. Monaco themes are global, so the last editor to call this wins. */
15
28
  export declare function applyTheme(monaco: MonacoApi, host: Element): Theme;
16
- /**
17
- * Makes `id` a usable language. Monaco's own ids need nothing (they load on first use); `truss-sqlite` is registered here once, as Monaco's
18
- * generic SQL tokenizer with the SQLite keywords added.
19
- */
29
+ /** Makes `id` a usable language: runs its registered setup once (Monaco's own ids need nothing; they load on first use). */
20
30
  export declare function ensureLanguage(monaco: MonacoApi, id: string): Promise<void>;
21
31
  /**
22
32
  * Validates and completes one model against a JSON schema: an object, or the URL of one (fetched by the JSON worker, so it must allow CORS).
package/dist/monaco.js CHANGED
@@ -1,33 +1,39 @@
1
1
  import { readTheme, monacoTheme } from './theme.js';
2
- import { SQLITE_ID, SQLITE_KEYWORDS } from './lang.js';
2
+ let loader;
3
3
  let pending;
4
- const workers = {
5
- json: () => import('monaco-editor/language/json/json.worker.js?worker').then((m) => () => new m.default()),
6
- css: () => import('monaco-editor/language/css/css.worker.js?worker').then((m) => () => new m.default()),
7
- html: () => import('monaco-editor/language/html/html.worker.js?worker').then((m) => () => new m.default()),
8
- typescript: () => import('monaco-editor/language/typescript/ts.worker.js?worker').then((m) => () => new m.default()),
9
- editor: () => import('monaco-editor/editor/editor.worker.js?worker').then((m) => () => new m.default())
10
- };
4
+ const languageSetups = new Map();
5
+ /**
6
+ * Tells the package where Monaco comes from, so that this module never names `monaco-editor` itself and a bundler sees no import of it.
7
+ * Apps that use only the diff, merge and code-block views never call this and never bundle Monaco; they keep working with the built-in
8
+ * fallback highlighter. The most recent loader wins. Pass `undefined` to forget it.
9
+ */
10
+ export function setMonacoLoader(next) {
11
+ loader = next;
12
+ pending = undefined;
13
+ }
11
14
  /** Monaco's worker label to the kind of worker that serves it. */
12
15
  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';
16
+ /** Whether a loader has been registered (`CodeEditor` and `DiffEditor` register the built-in one when they are bundled). */
17
+ export const hasMonacoLoader = () => !!loader;
18
+ /** Registers the setup that `ensureLanguage` runs for language `id`. */
19
+ export function setLanguageSetup(id, setup) {
20
+ if (setup)
21
+ languageSetups.set(id, setup);
22
+ else
23
+ languageSetups.delete(id);
24
+ registered.delete(id);
25
+ }
13
26
  /**
14
- * Loads Monaco once (a separate chunk, never during SSR) and wires its workers through the bundler:
15
- * every language service worker is its own lazy chunk that is fetched only when that language is used.
16
- * If the app already set `self.MonacoEnvironment`, it is left alone.
27
+ * Loads Monaco once through the registered loader (never during SSR). It rejects when no loader was registered, which the highlighting
28
+ * callers treat as "use the fallback highlighter".
17
29
  */
18
30
  export function loadMonaco() {
31
+ if (!loader)
32
+ return Promise.reject(new Error('@ruckc/truss-code: Monaco is not configured. Call setMonacoLoader(() => import("monaco-editor")) or useMonaco() from "@ruckc/truss-code/monaco".'));
19
33
  if (!pending) {
20
- pending = (async () => {
21
- const g = globalThis;
22
- if (!g.MonacoEnvironment) {
23
- const cache = new Map();
24
- const ready = Promise.all(Object.entries(workers).map(async ([k, load]) => cache.set(k, await load())));
25
- await ready;
26
- g.MonacoEnvironment = { getWorker: (_id, label) => cache.get(workerKind(label))() };
27
- }
28
- return (await import('monaco-editor'));
29
- })();
30
- pending.catch(() => { pending = undefined; }); // a failed load (offline, blocked chunk) can be retried by the next mount
34
+ const mine = (pending = loader());
35
+ mine.catch(() => { if (pending === mine)
36
+ pending = undefined; }); // a failed load (offline, blocked chunk) can be retried by the next mount
31
37
  }
32
38
  return pending;
33
39
  }
@@ -41,21 +47,14 @@ export function applyTheme(monaco, host) {
41
47
  }
42
48
  // ───── SQL dialects
43
49
  const registered = new Map();
44
- /**
45
- * Makes `id` a usable language. Monaco's own ids need nothing (they load on first use); `truss-sqlite` is registered here once, as Monaco's
46
- * generic SQL tokenizer with the SQLite keywords added.
47
- */
50
+ /** Makes `id` a usable language: runs its registered setup once (Monaco's own ids need nothing; they load on first use). */
48
51
  export function ensureLanguage(monaco, id) {
49
- if (id !== SQLITE_ID)
52
+ const setup = languageSetups.get(id);
53
+ if (!setup)
50
54
  return Promise.resolve();
51
55
  let p = registered.get(id);
52
56
  if (!p) {
53
- p = (async () => {
54
- monaco.languages.register({ id, aliases: ['SQLite'] });
55
- const { conf, language } = await import('monaco-editor/languages/definitions/sql/sql.js');
56
- monaco.languages.setLanguageConfiguration(id, conf);
57
- monaco.languages.setMonarchTokensProvider(id, { ...language, tokenPostfix: '.sqlite', keywords: [...language.keywords, ...SQLITE_KEYWORDS] });
58
- })();
57
+ p = setup(monaco);
59
58
  registered.set(id, p);
60
59
  }
61
60
  return p;
@@ -0,0 +1,13 @@
1
+ /** What a line of loosely annotated unified text is, judged from its first characters alone. */
2
+ export type MarkKind = 'add' | 'del' | 'hunk' | 'heading' | 'meta' | 'ctx';
3
+ export interface MarkedLine {
4
+ text: string;
5
+ kind: MarkKind;
6
+ }
7
+ /**
8
+ * Classifies each line of `text` for colouring, tolerating anything that is not a strict git patch:
9
+ * `@@ ... @@` (any text between the markers, such as `@@ [modes.plan] @@`) is a hunk header, `# ...` a heading, `+` an addition, `-` a
10
+ * removal, git's `diff`/`index`/mode/rename lines are meta, and a `---` line directly followed by a `+++` line (and that `+++` line) are
11
+ * file headers rather than a removal and an addition. Everything else, free text included, is plain.
12
+ */
13
+ export declare function markLines(text: string): MarkedLine[];
@@ -0,0 +1,28 @@
1
+ const META = /^(diff |index [0-9a-f]|similarity index |rename (from|to) |copy (from|to) |new file mode|deleted file mode|old mode|new mode|Binary files )/;
2
+ /**
3
+ * Classifies each line of `text` for colouring, tolerating anything that is not a strict git patch:
4
+ * `@@ ... @@` (any text between the markers, such as `@@ [modes.plan] @@`) is a hunk header, `# ...` a heading, `+` an addition, `-` a
5
+ * removal, git's `diff`/`index`/mode/rename lines are meta, and a `---` line directly followed by a `+++` line (and that `+++` line) are
6
+ * file headers rather than a removal and an addition. Everything else, free text included, is plain.
7
+ */
8
+ export function markLines(text) {
9
+ const lines = text.split(/\r\n|\r|\n/);
10
+ if (lines.length > 1 && lines[lines.length - 1] === '')
11
+ lines.pop(); // a trailing newline does not start another line
12
+ return lines.map((l, i) => {
13
+ let kind = 'ctx';
14
+ if (l.startsWith('@@'))
15
+ kind = 'hunk';
16
+ else if (l.startsWith('#'))
17
+ kind = 'heading';
18
+ else if ((l.startsWith('--- ') && lines[i + 1]?.startsWith('+++ ')) || (l.startsWith('+++ ') && lines[i - 1]?.startsWith('--- ')))
19
+ kind = 'meta';
20
+ else if (l.startsWith('+'))
21
+ kind = 'add';
22
+ else if (l.startsWith('-'))
23
+ kind = 'del';
24
+ else if (META.test(l))
25
+ kind = 'meta';
26
+ return { text: l, kind };
27
+ });
28
+ }
@@ -0,0 +1,6 @@
1
+ import { type Seg } from './highlight.js';
2
+ /**
3
+ * 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).
5
+ */
6
+ export declare function highlightText(text: string, language: string): Promise<Seg[][]>;
package/dist/syntax.js ADDED
@@ -0,0 +1,17 @@
1
+ import { highlight } from './highlight.js';
2
+ import { fallbackHighlight } from './fallback.js';
3
+ import { loadMonaco, ensureLanguage } from './monaco.js';
4
+ /**
5
+ * 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).
7
+ */
8
+ export async function highlightText(text, language) {
9
+ try {
10
+ const m = await loadMonaco();
11
+ await ensureLanguage(m, language);
12
+ return await highlight(m, text, language);
13
+ }
14
+ catch {
15
+ return fallbackHighlight(text, language);
16
+ }
17
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ruckc/truss-code",
3
- "version": "1.18.3",
4
- "description": "Monaco code editor, read-only code blocks and diff views styled with Truss UI",
3
+ "version": "1.20.0",
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",
7
7
  "scripts": {
@@ -19,6 +19,15 @@
19
19
  ".": {
20
20
  "types": "./dist/index.d.ts",
21
21
  "svelte": "./dist/index.js"
22
+ },
23
+ "./lite": {
24
+ "types": "./dist/lite.d.ts",
25
+ "svelte": "./dist/lite.js"
26
+ },
27
+ "./monaco": {
28
+ "types": "./dist/monaco-default.d.ts",
29
+ "svelte": "./dist/monaco-default.js",
30
+ "default": "./dist/monaco-default.js"
22
31
  }
23
32
  },
24
33
  "peerDependencies": {
@@ -26,6 +35,11 @@
26
35
  "@ruckc/truss-ui": "^1.0.0",
27
36
  "monaco-editor": "^0.57.0"
28
37
  },
38
+ "peerDependenciesMeta": {
39
+ "monaco-editor": {
40
+ "optional": true
41
+ }
42
+ },
29
43
  "devDependencies": {
30
44
  "monaco-editor": "^0.57.0"
31
45
  },