@kabmo-labs/kabmo 0.16.0 → 0.17.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.
Files changed (131) hide show
  1. package/README.md +2 -2
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +417 -417
  4. package/dist/client/static/js/index-3ve31rzx.css +1 -0
  5. package/dist/client/static/js/{index-cpydmygd.js → index-rerjq5th.js} +839 -837
  6. package/package.json +1 -1
  7. package/src/client/components/common/code-surface/bracket-guide.test.ts +2 -2
  8. package/src/client/components/common/code-surface/bracket-guide.ts +2 -2
  9. package/src/client/components/common/code-surface/conflict-markers.ts +5 -5
  10. package/src/client/components/common/code-surface/extensions.ts +7 -4
  11. package/src/client/components/common/code-surface/theme.ts +34 -9
  12. package/src/client/components/common/code-surface/whitespace.test.ts +223 -0
  13. package/src/client/components/common/code-surface/whitespace.ts +140 -0
  14. package/src/client/components/common/{server-switcher/index.tsx → server-control/Panel.tsx} +73 -35
  15. package/src/client/components/common/{server-switcher → server-control}/index.test.tsx +98 -37
  16. package/src/client/components/common/server-control/index.tsx +118 -0
  17. package/src/client/components/layout/desktop-layout/TopNavbar.tsx +8 -50
  18. package/src/client/components/mobile/mobile-main-view/Header.tsx +6 -12
  19. package/src/client/components/mobile/mobile-session-sidebar/Header.tsx +41 -13
  20. package/src/client/components/settings/Modal.tsx +9 -3
  21. package/src/client/components/settings/ProjectSelectorDropdown.tsx +19 -9
  22. package/src/client/components/settings/categories/AgentSettings.tsx +27 -6
  23. package/src/client/components/settings/categories/ProjectSettings.tsx +122 -156
  24. package/src/client/components/settings/categories/SkillCatalogSettings.tsx +220 -260
  25. package/src/client/components/settings/categories/SkillSettings.tsx +6 -3
  26. package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +5 -0
  27. package/src/client/components/settings/categories/project-settings/AccentPalette.test.tsx +189 -0
  28. package/src/client/components/settings/categories/project-settings/AccentPalette.tsx +156 -24
  29. package/src/client/components/settings/categories/project-settings/AddProjectModal.tsx +175 -0
  30. package/src/client/components/settings/categories/project-settings/DeleteProjectModal.tsx +107 -0
  31. package/src/client/components/settings/categories/project-settings/DetailsForm.tsx +40 -24
  32. package/src/client/components/settings/categories/project-settings/DetailsHeader.tsx +17 -7
  33. package/src/client/components/settings/categories/project-settings/IconGrid.tsx +164 -69
  34. package/src/client/components/settings/categories/project-settings/ModelDropdown.test.tsx +122 -0
  35. package/src/client/components/settings/categories/project-settings/ModelDropdown.tsx +124 -53
  36. package/src/client/components/settings/categories/project-settings/NameInput.tsx +57 -11
  37. package/src/client/components/settings/categories/project-settings/PathField.tsx +122 -0
  38. package/src/client/components/settings/categories/project-settings/SidebarList.tsx +100 -59
  39. package/src/client/components/settings/categories/skill-catalog/GitImportPanel.tsx +253 -0
  40. package/src/client/components/settings/categories/skill-catalog/SkillCard.tsx +89 -0
  41. package/src/client/components/settings/categories/skill-catalog/SourceRail.tsx +122 -0
  42. package/src/client/components/settings/categories/skill-catalog/catalog-ui.test.tsx +179 -0
  43. package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +208 -0
  44. package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +137 -232
  45. package/src/client/components/settings/categories/skill-settings/InstructionsEditor.tsx +84 -0
  46. package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +123 -87
  47. package/src/client/components/settings/categories/skill-settings/pane.test.tsx +179 -0
  48. package/src/client/components/settings/categories/skill-settings/row-meta.ts +58 -0
  49. package/src/client/components/workspace/chat-timeline/index.tsx +6 -1
  50. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.test.ts +46 -0
  51. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Proc.tsx +15 -6
  52. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.test.ts +29 -0
  53. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Wait.tsx +11 -3
  54. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.test.ts +24 -1
  55. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/card-header.ts +6 -2
  56. package/src/client/components/workspace/editor/viewers/SvgPreview.tsx +18 -2
  57. package/src/client/components/workspace/editor/viewers/viewers.test.ts +39 -0
  58. package/src/client/components/workspace/file-explorer/ContextMenu.tsx +18 -5
  59. package/src/client/components/workspace/file-explorer/Modals.tsx +15 -1
  60. package/src/client/components/workspace/file-explorer/RowLabel.tsx +68 -0
  61. package/src/client/components/workspace/file-explorer/TreeItem.tsx +47 -57
  62. package/src/client/components/workspace/file-explorer/collapsed-chain.test.ts +167 -0
  63. package/src/client/components/workspace/file-explorer/drag-props.ts +42 -0
  64. package/src/client/components/workspace/file-explorer/drag.test.ts +43 -0
  65. package/src/client/components/workspace/file-explorer/index.tsx +21 -20
  66. package/src/client/data/settings/omp-schema.json +91 -4
  67. package/src/client/data/settings/project.ts +9 -28
  68. package/src/client/data/settings/skill.ts +6 -32
  69. package/src/client/hooks/chat/timeline/pending-model.ts +28 -0
  70. package/src/client/hooks/settings/projects/index.ts +294 -0
  71. package/src/client/hooks/settings/projects.test.ts +237 -0
  72. package/src/client/hooks/settings/skill-catalog.ts +101 -9
  73. package/src/client/hooks/settings/skill-git-import.ts +153 -0
  74. package/src/client/hooks/shell/servers.test.ts +166 -0
  75. package/src/client/hooks/{desktop → shell}/servers.ts +17 -14
  76. package/src/client/hooks/ui/updates/shell-download.ts +1 -1
  77. package/src/client/hooks/ui/updates/shell-update.ts +2 -6
  78. package/src/client/hooks/workspace/file-row-drag.ts +41 -0
  79. package/src/client/hooks/workspace/file-tree-actions.ts +25 -1
  80. package/src/client/hooks/workspace/file-tree-edits.ts +23 -6
  81. package/src/client/hooks/workspace/root-drop-target.ts +77 -0
  82. package/src/client/hooks/workspace/unfolded-chains.ts +165 -0
  83. package/src/client/lib/desktop/dropped-paths.ts +1 -1
  84. package/src/client/lib/desktop/titlebar.test.ts +12 -3
  85. package/src/client/lib/desktop/titlebar.ts +1 -1
  86. package/src/client/lib/shell/desktop.ts +117 -0
  87. package/src/client/lib/shell/servers.ts +75 -0
  88. package/src/client/lib/shell/transport.ts +216 -0
  89. package/src/client/main.tsx +9 -0
  90. package/src/server/lib/fs/git-merge-conflict.test.ts +14 -1
  91. package/src/server/lib/omp/config/skill-sources.ts +49 -0
  92. package/src/server/lib/omp/config/skills-git-install.ts +155 -0
  93. package/src/server/lib/omp/config/skills-git-repo.ts +288 -0
  94. package/src/server/lib/omp/config/skills-git.test.ts +220 -0
  95. package/src/server/lib/workspace/project-model.server.test.ts +102 -0
  96. package/src/server/lib/workspace/project-model.server.ts +47 -0
  97. package/src/server/lib/workspace/project-patch.server.ts +156 -0
  98. package/src/server/routes/agent/new.ts +8 -1
  99. package/src/server/routes/settings/agents.ts +19 -7
  100. package/src/server/routes/settings/projects.ts +53 -19
  101. package/src/server/routes/settings/settings-projects-routes.test.ts +214 -0
  102. package/src/server/routes/settings/settings-store-routes.test.ts +5 -2
  103. package/src/server/routes/settings/skills-catalog-actions.ts +195 -0
  104. package/src/server/routes/settings/skills.test.ts +225 -0
  105. package/src/server/routes/settings/skills.ts +18 -15
  106. package/src/shared/lib/fs/folder-chain.test.ts +81 -1
  107. package/src/shared/lib/fs/folder-chain.ts +84 -0
  108. package/src/shared/lib/omp/config/schema.test.ts +35 -0
  109. package/src/shared/lib/omp/session/job-progress.test.ts +37 -1
  110. package/src/shared/lib/omp/session/job-progress.ts +31 -0
  111. package/src/shared/lib/omp/session/proc.ts +5 -0
  112. package/src/shared/lib/omp/session/wait.ts +5 -0
  113. package/src/shared/lib/ui/mobile-overlay.ts +61 -0
  114. package/src/shared/lib/ui/svg-scope.test.ts +97 -0
  115. package/src/shared/lib/ui/svg-scope.ts +134 -0
  116. package/src/shared/lib/workspace/project-accent.test.ts +69 -0
  117. package/src/shared/lib/workspace/project-accent.ts +63 -0
  118. package/src/shared/lib/workspace/project-icon.ts +40 -0
  119. package/src/shared/lib/workspace/project-model.test.ts +79 -0
  120. package/src/shared/lib/workspace/project-model.ts +64 -0
  121. package/src/shared/types/settings/skill.ts +53 -3
  122. package/src/test-support/file-explorer-disk.test-util.ts +25 -1
  123. package/src/test-support/file-explorer-drag.test-util.ts +88 -0
  124. package/src/test-support/file-explorer.test-util.ts +47 -47
  125. package/dist/client/static/js/index-fjnq2z2d.css +0 -1
  126. package/src/client/components/common/code-surface/indent-guide.ts +0 -104
  127. package/src/client/components/settings/categories/skill-catalog/AddSourceModal.tsx +0 -133
  128. package/src/client/hooks/desktop/servers.test.ts +0 -73
  129. package/src/client/lib/desktop/bridge.ts +0 -203
  130. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +0 -65
  131. package/src/shared/lib/code/editor/indent-guide-rule.ts +0 -47
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kabmo-labs/kabmo",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "Web console and diagnostic workbench for AI coding agents — Elysia + Preact on Bun.",
5
5
  "license": "MIT",
6
6
  "author": "Wijanarko Putra Rajeb <wijanarko.rajeb@gmail.com>",
@@ -9,8 +9,8 @@
9
9
  * Three failure modes are silent here and each is a test:
10
10
  *
11
11
  * - A guide drawn at the line's LEFT edge instead of under the opening brace
12
- * looks like an indent guide, which is a different feature. The column is a
13
- * decoration attribute, so the assertion is on the emitted style.
12
+ * points at the wrong column. The column is a decoration attribute, so the
13
+ * assertion is on the emitted style.
14
14
  * - A guide through a BLANK line makes a block read as if it continued across
15
15
  * the gap between two functions.
16
16
  * - A mode table entry that does not exist in `@codemirror/legacy-modes` fails
@@ -15,8 +15,8 @@
15
15
  * **The guide is driven by the CARET, not by every pair in the viewport.** A
16
16
  * viewport-wide version (VS Code's `bracketPairGuides`) draws a rule for every
17
17
  * brace on screen: on a 337-line component that is dozens of overlapping lines,
18
- * which is the same noise as a permanently-on indent guide and hides the one
19
- * pair the reader is looking at. This shows the pair the caret is IN.
18
+ * which is noise that hides the one pair the reader is looking at. This shows
19
+ * the pair the caret is IN.
20
20
  *
21
21
  * **It reads `matchBrackets`, the same call `bracketMatching()` makes.** A second
22
22
  * pairing rule would eventually disagree with the highlight, and a guide that
@@ -29,8 +29,8 @@
29
29
  * still held their text, i.e. the line's content was swallowed by a decoration
30
30
  * that should not have covered it.
31
31
  *
32
- * The walk below is the shape `indent-guide.ts` uses: visible lines only,
33
- * rebuilt on scroll and on edit, so a 20 MB file costs the viewport.
32
+ * The walk below visits the VISIBLE lines only and is rebuilt on scroll and on
33
+ * edit, so a 20 MB file costs the viewport.
34
34
  */
35
35
 
36
36
  import type { Range } from '@codemirror/state';
@@ -84,9 +84,9 @@ function buildMarkers(view: EditorView): DecorationSet {
84
84
  /**
85
85
  * The marker bands, as a view plugin.
86
86
  *
87
- * A plugin rather than a state field for the same reason `indentGuides` is: the
88
- * bands are derived from what is RENDERED, so a scroll has to rebuild them, and
89
- * a field would hold a decoration set the document does not own.
87
+ * A plugin rather than a state field because the bands are derived from what is
88
+ * RENDERED: a scroll has to rebuild them, and a field would hold a decoration
89
+ * set the document does not own.
90
90
  */
91
91
  export function conflictMarkers() {
92
92
  return ViewPlugin.fromClass(
@@ -57,7 +57,7 @@ import { indentDataExtension, indentExtensions } from '@/client/components/commo
57
57
  import { typingExtensions, type EditorTypingOptions } from '@/client/components/common/code-surface/typing';
58
58
  import { indentFoldService } from '@/client/components/common/code-surface/fold';
59
59
  import { foldPlaceholderDom } from '@/client/components/common/code-surface/fold-placeholder';
60
- import { indentGuides } from '@/client/components/common/code-surface/indent-guide';
60
+ import { whitespaceMarks } from '@/client/components/common/code-surface/whitespace';
61
61
  import { findMarksField } from '@/client/components/common/code-surface/marks';
62
62
  import { surfaceKeymap } from '@/client/components/common/code-surface/keymap';
63
63
  import { shikiHighlight, type ShikiThemeNames } from '@/client/components/common/code-surface/shiki';
@@ -228,9 +228,12 @@ export function surfaceExtensions({
228
228
  // Control characters drawn as their glyph instead of nothing: a stray NUL or a
229
229
  // zero-width space is invisible, which makes a corrupted file look fine.
230
230
  highlightSpecialChars(),
231
- // A rule at every nesting level, from indentation (there is no tree). Deliberately
232
- // dimmer than `bracketGuide`, which draws ONE line between a brace and its pair.
233
- indentGuides,
231
+ // A space drawn as a dot and a tab as an arrow, on the SELECTION only — VS Code's
232
+ // `renderWhitespace: 'selection'`, its default. The package's own
233
+ // `highlightWhitespace()` marks every space in the viewport, which is a permanent
234
+ // dotted layer over the code; these marks appear when a reader drags over a
235
+ // block, which is the moment they are asking about the bytes.
236
+ whitespaceMarks,
234
237
  history(),
235
238
  drawSelection(),
236
239
  dropCursor(),
@@ -214,15 +214,40 @@ export function surfaceTheme(): Extension {
214
214
  backgroundColor: 'var(--editor-active-line, color-mix(in srgb, var(--theme-ink) 4%, transparent))',
215
215
  color: 'var(--editor-fg, var(--theme-ink))',
216
216
  },
217
- // An indent guide: one rule per nesting level, at the level's column. It must be
218
- // VISUALLY distinct from the bracket pair guide (which sits under the opening
219
- // brace), so this is a dim border at the column boundary rather than a band.
220
- '.cm-indent-guide': {
221
- backgroundImage:
222
- 'linear-gradient(to right, var(--editor-indent-guide, color-mix(in srgb, var(--theme-ink) 12%, transparent)) 0 1px, transparent 1px)',
223
- backgroundRepeat: 'no-repeat',
224
- backgroundSize: '1px 100%',
225
- backgroundPosition: 'calc(var(--indent-guide-col, 2ch) - 1px) 0',
217
+ // Whitespace marks (`whitespace.ts`): a dot per space and an arrow per tab,
218
+ // drawn only for characters the reader has SELECTED — VS Code's
219
+ // `renderWhitespace: 'selection'`. Nothing is painted for a bare caret.
220
+ //
221
+ // The ink is read from `--editor-fg`, NOT from `currentColor`: a mark that lands
222
+ // inside a Shiki token inherits that token's colour, so the dots in one line
223
+ // would come out in as many colours as the highlighting uses.
224
+ //
225
+ // The dot geometry is the package's own (`.4em`, centred at 55%): a dot wide
226
+ // enough to read at 8px would touch its neighbours at 24px. The tab draws an
227
+ // ARROW rather than a second dot, because one tab and a run of spaces are the
228
+ // same width and must not look alike. The arrow is a MASK, not a background
229
+ // image: an SVG in `url()` is its own document, so `currentColor` inside it
230
+ // resolves to black and the arrow would vanish in a dark theme.
231
+ '.cm-whitespace-space': {
232
+ background:
233
+ 'radial-gradient(circle at 50% 55%, var(--editor-fg, var(--theme-ink)) 20%, transparent 0) no-repeat',
234
+ backgroundSize: '.4em',
235
+ backgroundPosition: 'calc(min(50%, 0px)) center',
236
+ opacity: '0.45',
237
+ },
238
+ '.cm-whitespace-tab': {
239
+ backgroundColor: 'var(--editor-fg, var(--theme-ink))',
240
+ maskImage:
241
+ "url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"20\"><path stroke=\"%23000\" stroke-width=\"1\" fill=\"none\" d=\"M1 10H196L190 5M190 15L196 10M197 4L197 16\"/></svg>')",
242
+ WebkitMaskImage:
243
+ "url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"20\"><path stroke=\"%23000\" stroke-width=\"1\" fill=\"none\" d=\"M1 10H196L190 5M190 15L196 10M197 4L197 16\"/></svg>')",
244
+ maskSize: 'auto 100%',
245
+ WebkitMaskSize: 'auto 100%',
246
+ maskPosition: 'right 90%',
247
+ WebkitMaskPosition: 'right 90%',
248
+ maskRepeat: 'no-repeat',
249
+ WebkitMaskRepeat: 'no-repeat',
250
+ opacity: '0.45',
226
251
  },
227
252
  // The line-blame label at the end of a run's first line.
228
253
  //
@@ -0,0 +1,223 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Whitespace marks, through the REAL surface stack.
8
+ *
9
+ * Pins what makes this feature different from both alternatives, and each case
10
+ * is one a naive version gets wrong:
11
+ *
12
+ * - **A bare caret paints nothing.** The package's `highlightWhitespace()` marks
13
+ * every space in the viewport and a leading-run version marks every block's
14
+ * indentation; both look identical to this one as soon as text is selected,
15
+ * so the CARET case is the only one that tells them apart.
16
+ * - **Only the selected characters are marked**, so a selection that stops
17
+ * mid-line marks the part it covers and nothing past it.
18
+ * - **Collapsing the selection clears the marks.** They are a function of the
19
+ * selection, so a missing rebuild leaves the last painted set on screen.
20
+ *
21
+ * The marks exist only once a view mounts (a `ViewPlugin`), which is why every
22
+ * case here mounts one; `whitespaceDecorations` is also driven directly, so the
23
+ * rules are asserted without depending on the DOM.
24
+ */
25
+
26
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
27
+ import { Window } from 'happy-dom';
28
+ import { Compartment, EditorState } from '@codemirror/state';
29
+ import { EditorView } from '@codemirror/view';
30
+
31
+ import { surfaceExtensions } from '@/client/components/common/code-surface/extensions';
32
+ import { whitespaceDecorations } from '@/client/components/common/code-surface/whitespace';
33
+ import { SHIKI_THEMES } from '@/shared/lib/code/shiki-themes';
34
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
35
+
36
+ const EXTRA_GLOBALS = ['MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame'] as const;
37
+ const native: Partial<Record<(typeof EXTRA_GLOBALS)[number], unknown>> = {};
38
+
39
+ let host: HTMLElement;
40
+
41
+ beforeAll(() => {
42
+ const win = new Window({ url: 'http://localhost' });
43
+ installDomGlobals(win);
44
+ const target = globalThis as unknown as Record<string, unknown>;
45
+ for (const key of EXTRA_GLOBALS) {
46
+ native[key] = target[key];
47
+ target[key] = (win as unknown as Record<string, unknown>)[key];
48
+ }
49
+ host = document.body.appendChild(document.createElement('div'));
50
+ });
51
+
52
+ afterAll(() => {
53
+ const target = globalThis as unknown as Record<string, unknown>;
54
+ for (const key of EXTRA_GLOBALS) {
55
+ if (native[key] === undefined) delete target[key];
56
+ else target[key] = native[key];
57
+ }
58
+ restoreDomGlobals();
59
+ });
60
+
61
+ /** The component's own stack, mounted at `selection` (offsets into `doc`). */
62
+ function mount(doc: string, selection?: { anchor: number; head: number }): EditorView {
63
+ return new EditorView({
64
+ parent: host,
65
+ state: EditorState.create({
66
+ doc,
67
+ selection,
68
+ extensions: surfaceExtensions({
69
+ language: 'typescript',
70
+ wordWrapCompartment: new Compartment(),
71
+ readOnlyCompartment: new Compartment(),
72
+ themeCompartment: new Compartment(),
73
+ languageCompartment: new Compartment(),
74
+ indentCompartment: new Compartment(),
75
+ typingCompartment: new Compartment(),
76
+ blameCompartment: new Compartment(),
77
+ blame: null,
78
+ indentUnitText: ' ',
79
+ typing: { autoCloseBrackets: false, autocomplete: false },
80
+ wordWrap: false,
81
+ readOnly: false,
82
+ themes: SHIKI_THEMES,
83
+ onDocChange: () => {},
84
+ onState: () => {},
85
+ }),
86
+ }),
87
+ });
88
+ }
89
+
90
+ /** The mark classes on each rendered line, in document order. */
91
+ function marksByLine(view: EditorView): Array<{ text: string; marks: string[] }> {
92
+ return Array.from(view.contentDOM.querySelectorAll('.cm-line')).map((line) => ({
93
+ text: line.textContent ?? '',
94
+ marks: Array.from(line.querySelectorAll('.cm-whitespace-space, .cm-whitespace-tab')).map((mark) => mark.className),
95
+ }));
96
+ }
97
+
98
+ /** Every marked range of a document, without mounting a view. */
99
+ function ranges(doc: string, selection?: { anchor: number; head: number }): Array<[number, number]> {
100
+ const state = EditorState.create({ doc, selection });
101
+ const out: Array<[number, number]> = [];
102
+ whitespaceDecorations(state).between(0, state.doc.length, (from, to) => {
103
+ out.push([from, to]);
104
+ });
105
+ return out;
106
+ }
107
+
108
+ describe('whitespace marks', () => {
109
+ test('a caret paints nothing, however much whitespace the file holds', () => {
110
+ const doc = 'function f() {\n const a = 1;\n}\n';
111
+ const view = mount(doc, { anchor: 0, head: 0 });
112
+ expect(marksByLine(view).flatMap((line) => line.marks)).toEqual([]);
113
+ // And the rule agrees without a view.
114
+ expect(ranges(doc)).toEqual([]);
115
+ view.destroy();
116
+ });
117
+
118
+ test('a selection marks every space it covers, indent and between tokens alike', () => {
119
+ const doc = 'function f() {\n const a = 1;\n}\n';
120
+ const lineFrom = doc.indexOf(' const');
121
+ const view = mount(doc, { anchor: lineFrom, head: lineFrom + ' const a = 1;'.length });
122
+ const block = marksByLine(view).find((line) => line.text === ' const a = 1;');
123
+ view.destroy();
124
+
125
+ // Four of indent plus the three between `const`, `a`, `=` and `1`: inside a
126
+ // selection, EVERY space is the point — that is what the reader is counting.
127
+ expect(block?.marks).toEqual(Array(7).fill('cm-whitespace-space'));
128
+ });
129
+
130
+ test('a selection that stops mid-line marks only the part it covers', () => {
131
+ expect(ranges(' x\n', { anchor: 0, head: 2 })).toEqual([
132
+ [0, 1],
133
+ [1, 2],
134
+ ]);
135
+ expect(ranges(' x\n', { anchor: 1, head: 3 })).toEqual([
136
+ [1, 2],
137
+ [2, 3],
138
+ ]);
139
+ });
140
+
141
+ test('a tab in the selection is one arrow, not the columns it measures', () => {
142
+ const view = mount('\tif (a) {\n', { anchor: 0, head: 6 });
143
+ expect(marksByLine(view)[0].marks).toEqual(['cm-whitespace-tab', 'cm-whitespace-space']);
144
+ view.destroy();
145
+ });
146
+
147
+ test('a selection spanning several lines marks each covered line', () => {
148
+ const doc = ' a\n b\nc\n';
149
+ expect(ranges(doc, { anchor: 0, head: doc.length })).toEqual([
150
+ [0, 1],
151
+ [1, 2],
152
+ [4, 5],
153
+ [5, 6],
154
+ [6, 7],
155
+ [7, 8],
156
+ ]);
157
+ });
158
+
159
+ test('a selection ending in a line break does not reach the next line', () => {
160
+ // ` b` is fully covered; `c` starts at offset 9 and must not be touched.
161
+ const doc = ' a\n b\nc\n';
162
+ expect(ranges(doc, { anchor: 4, head: 9 })).toEqual([
163
+ [4, 5],
164
+ [5, 6],
165
+ [6, 7],
166
+ [7, 8],
167
+ ]);
168
+ });
169
+
170
+ test('collapsing the selection clears the marks instead of leaving them painted', () => {
171
+ const doc = ' a\n b\n';
172
+ const view = mount(doc, { anchor: 0, head: doc.length });
173
+ expect(marksByLine(view).flatMap((line) => line.marks).length).toBe(6);
174
+
175
+ view.dispatch({ selection: { anchor: 3, head: 3 } });
176
+ expect(marksByLine(view).flatMap((line) => line.marks)).toEqual([]);
177
+ view.destroy();
178
+ });
179
+
180
+ test('the mark holds the character it replaces, so a copy keeps its whitespace', () => {
181
+ const view = mount(' x\n', { anchor: 0, head: 4 });
182
+ const mark = view.contentDOM.querySelector('.cm-whitespace-space');
183
+ expect(mark?.textContent).toBe(' ');
184
+ expect(view.contentDOM.querySelector('.cm-line')?.textContent).toBe(' x');
185
+ view.destroy();
186
+ });
187
+
188
+ test('the window bounds the walk, so a whole-document selection is still cheap', () => {
189
+ // The window is the viewport in the plugin; here it stands in for one, and the
190
+ // answer must be the selection INTERSECTED with it — not the whole document.
191
+ const doc = ' a\n b\n c\n';
192
+ const state = EditorState.create({ doc, selection: { anchor: 0, head: doc.length } });
193
+ const out: Array<[number, number]> = [];
194
+ whitespaceDecorations(state, state.selection.ranges, { from: 4, to: 8 }).between(0, state.doc.length, (from, to) => {
195
+ out.push([from, to]);
196
+ });
197
+ // Line 2's two spaces; the newline at 7 and line 3 (from offset 8) are outside
198
+ // the window, so they cost nothing.
199
+ expect(out).toEqual([
200
+ [4, 5],
201
+ [5, 6],
202
+ ]);
203
+ });
204
+ });
205
+
206
+ describe('whitespace theme', () => {
207
+ test('both marks paint from the surface ink, and no indent guide survives', () => {
208
+ const view = mount(' a\n', { anchor: 0, head: 3 });
209
+ const css = Array.from(document.head.querySelectorAll('style'))
210
+ .map((node) => node.textContent ?? '')
211
+ .join('\n');
212
+ view.destroy();
213
+
214
+ // The package's own `#aaa`/`#888` are chroma the palette does not own, and
215
+ // they disappear against a dark editor theme, so both marks restate the ink.
216
+ expect(css).toMatch(/\.cm-whitespace-space \{[^}]*var\(--editor-fg, var\(--theme-ink\)\)/);
217
+ expect(css).toMatch(/\.cm-whitespace-tab \{[^}]*var\(--editor-fg, var\(--theme-ink\)\)/);
218
+ // One dot per character box, which is what `.4em` with `no-repeat` gives.
219
+ expect(css).toMatch(/\.cm-whitespace-space \{[^}]*background-size: \.4em/);
220
+ // The per-level vertical rule is gone; the marks replaced it.
221
+ expect(css).not.toContain('.cm-indent-guide');
222
+ });
223
+ });
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Whitespace marks, drawn only where the text is SELECTED — VS Code's
8
+ * `editor.renderWhitespace: 'selection'`, its default.
9
+ *
10
+ * ## Why the selection, and not the document
11
+ *
12
+ * An always-on mark is a permanent dotted layer over every block in a file: it
13
+ * competes with the code it was meant to explain, and it answers a question
14
+ * nobody asked until they started caring about the bytes. Painting the marks on
15
+ * the selection answers it at the moment it is asked — a drag across a block, or
16
+ * `⇧⌘→` over a line — and leaves the rest of the document as code. The package's
17
+ * own `highlightWhitespace()` marks every space in the viewport; a leading-run
18
+ * version marks every block's indentation. Both were tried and both are noise.
19
+ *
20
+ * ## Two bounds keep it cheap
21
+ *
22
+ * - Only SELECTED characters are considered, so a caret (`empty` range) paints
23
+ * nothing — which is also what makes thousands of `⌘D` cursors free.
24
+ * - Only the selection's intersection with the VIEWPORT is walked, so `⌘A` on a
25
+ * 20 MB file costs the lines on screen rather than the document.
26
+ *
27
+ * ## It is NOT an indent guide
28
+ *
29
+ * Nothing here draws a vertical rule per nesting level — that feature was
30
+ * removed, because a column of rules read as structure the file does not have.
31
+ */
32
+
33
+ import type { EditorState, SelectionRange } from '@codemirror/state';
34
+ import { RangeSetBuilder } from '@codemirror/state';
35
+ import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from '@codemirror/view';
36
+
37
+ /** The two characters a mark is drawn for; a line break is not one of them. */
38
+ const KINDS = {
39
+ ' ': Decoration.mark({ class: 'cm-whitespace-space' }),
40
+ '\t': Decoration.mark({ class: 'cm-whitespace-tab' }),
41
+ } as const;
42
+
43
+ type WhitespaceChar = keyof typeof KINDS;
44
+
45
+ /**
46
+ * Marks every space and tab in `[from, to)`.
47
+ *
48
+ * One mark per CHARACTER, not per run: a mark's box is what the CSS paints, and
49
+ * a single span over four spaces can hold only one dot (`no-repeat` at `.4em`).
50
+ * Per-character ranges are what make four spaces draw four dots.
51
+ */
52
+ function addSlice(state: EditorState, from: number, to: number, builder: RangeSetBuilder<Decoration>): void {
53
+ let line = state.doc.lineAt(from);
54
+ for (;;) {
55
+ const start = Math.max(from, line.from);
56
+ const end = Math.min(to, line.to);
57
+ for (let offset = start; offset < end; offset++) {
58
+ const kind = line.text[offset - line.from] as WhitespaceChar;
59
+ // Anything else — a newline, or the file's content — is not a mark.
60
+ if (kind === ' ' || kind === '\t') builder.add(offset, offset + 1, KINDS[kind]);
61
+ }
62
+ if (line.to >= to || line.to >= state.doc.length) break;
63
+ line = state.doc.lineAt(line.to + 1);
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The marks for one selection range, clipped to the window `[windowFrom, windowTo)`.
69
+ *
70
+ * The clip is the viewport, which is the bound that makes a whole-document
71
+ * selection cheap: a mark outside the rendered lines could not be seen.
72
+ */
73
+ function addRange(
74
+ state: EditorState,
75
+ range: SelectionRange,
76
+ windowFrom: number,
77
+ windowTo: number,
78
+ builder: RangeSetBuilder<Decoration>,
79
+ ): void {
80
+ const from = Math.max(range.from, windowFrom);
81
+ const to = Math.min(range.to, windowTo);
82
+ // A caret, or a selection entirely outside the window: nothing to paint.
83
+ if (from >= to) return;
84
+ addSlice(state, from, to, builder);
85
+ }
86
+
87
+ /**
88
+ * The whitespace marks for `ranges`, in document order.
89
+ *
90
+ * `window` defaults to the whole document, which is what a caller that has no
91
+ * view (a test) wants; the plugin passes its viewport, because that is the only
92
+ * part of a selection that can be seen.
93
+ */
94
+ export function whitespaceDecorations(
95
+ state: EditorState,
96
+ ranges: readonly SelectionRange[] = state.selection.ranges,
97
+ window: { from: number; to: number } = { from: 0, to: state.doc.length },
98
+ ): DecorationSet {
99
+ const builder = new RangeSetBuilder<Decoration>();
100
+ for (const range of ranges) {
101
+ // CodeMirror keeps selection ranges ascending, and the window is one span,
102
+ // so appending as we go yields a sorted set.
103
+ addRange(state, range, window.from, window.to, builder);
104
+ }
105
+ return builder.finish();
106
+ }
107
+
108
+ /**
109
+ * The whitespace marks, as a view plugin.
110
+ *
111
+ * Rebuilt on a SELECTION change as well as on an edit or a scroll: the marks are
112
+ * a function of the selection AND of what is rendered, so collapsing the
113
+ * selection is what removes them and scrolling is what produces them elsewhere.
114
+ */
115
+ export const whitespaceMarks = ViewPlugin.fromClass(
116
+ class {
117
+ decorations: DecorationSet;
118
+
119
+ constructor(view: EditorView) {
120
+ this.decorations = this.build(view);
121
+ }
122
+
123
+ update(update: ViewUpdate) {
124
+ if (update.docChanged || update.selectionSet || update.viewportChanged) {
125
+ this.decorations = this.build(update.view);
126
+ }
127
+ }
128
+
129
+ private build(view: EditorView): DecorationSet {
130
+ const builder = new RangeSetBuilder<Decoration>();
131
+ for (const { from, to } of view.visibleRanges) {
132
+ for (const range of view.state.selection.ranges) {
133
+ if (!range.empty) addRange(view.state, range, from, to, builder);
134
+ }
135
+ }
136
+ return builder.finish();
137
+ }
138
+ },
139
+ { decorations: (plugin) => plugin.decorations },
140
+ );