dsh-remote-vs 0.24.0 → 0.25.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 (61) hide show
  1. package/README.en.md +40 -10
  2. package/README.md +31 -9
  3. package/lib/client.js +2616 -542
  4. package/lib/index.js +186 -40
  5. package/lib/types/client/CodeEditor.d.ts +17 -0
  6. package/lib/types/client/EditorPane.d.ts +16 -5
  7. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  8. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  9. package/lib/types/client/RemoteRoot.d.ts +5 -5
  10. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  11. package/lib/types/client/TerminalView.d.ts +1 -1
  12. package/lib/types/client/XTerm.d.ts +33 -0
  13. package/lib/types/client/editor-capability.d.ts +27 -0
  14. package/lib/types/client/i18n.d.ts +1 -1
  15. package/lib/types/client/store.d.ts +59 -4
  16. package/lib/types/client/terminal-input.d.ts +23 -0
  17. package/lib/types/client/terminal-snippets.d.ts +86 -0
  18. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  19. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  20. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  21. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  22. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  23. package/lib/types/client/vsc/kit.d.ts +2 -0
  24. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  25. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  26. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  27. package/lib/types/client/vsc/terminal-theme.d.ts +22 -0
  28. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  29. package/lib/types/pool.d.ts +25 -0
  30. package/lib/types/terminal.d.ts +25 -1
  31. package/package.json +1 -1
  32. package/src/client/CodeEditor.tsx +54 -2
  33. package/src/client/EditorPane.tsx +485 -107
  34. package/src/client/FloatingPlaceholder.tsx +34 -5
  35. package/src/client/RemoteEditorView.tsx +14 -11
  36. package/src/client/RemoteRoot.tsx +20 -125
  37. package/src/client/TerminalSnippets.tsx +357 -0
  38. package/src/client/TerminalView.tsx +50 -1
  39. package/src/client/XTerm.tsx +228 -58
  40. package/src/client/auto-open-remote.ts +11 -9
  41. package/src/client/editor-capability.ts +42 -0
  42. package/src/client/i18n.ts +148 -6
  43. package/src/client/index.tsx +22 -6
  44. package/src/client/store.tsx +165 -13
  45. package/src/client/terminal-input.ts +44 -0
  46. package/src/client/terminal-snippets.ts +216 -0
  47. package/src/client/vsc/breadcrumb.tsx +251 -0
  48. package/src/client/vsc/editor-caret.ts +30 -0
  49. package/src/client/vsc/editor-langs.ts +20 -0
  50. package/src/client/vsc/editor-settings.ts +146 -0
  51. package/src/client/vsc/editor-theme.ts +4 -5
  52. package/src/client/vsc/image-preview.tsx +110 -0
  53. package/src/client/vsc/kit.tsx +20 -1
  54. package/src/client/vsc/terminal-clipboard.ts +19 -0
  55. package/src/client/vsc/terminal-line.ts +101 -0
  56. package/src/client/vsc/terminal-links.ts +166 -0
  57. package/src/client/vsc/terminal-theme.ts +71 -0
  58. package/src/client/vsc/terminal-writer.ts +112 -0
  59. package/src/client/vsc/vsc.css +687 -48
  60. package/src/pool.ts +99 -27
  61. package/src/terminal.ts +160 -6
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Common-command snippets: the little "常用指令" library above the terminal.
3
+ *
4
+ * A snippet is a NAME plus the COMMAND it stands for. Clicking one in the panel
5
+ * pastes the command into the active terminal's command line WITHOUT pressing
6
+ * Enter — the user reviews and runs it themselves, so a misclick cannot execute
7
+ * `rm -rf`.
8
+ *
9
+ * Storage is per browser (localStorage), like the port-forward rules and the
10
+ * editor preferences: this is a personal convenience list, not workspace state,
11
+ * and the host is told nothing about it. The pure half is exported so the gate
12
+ * can drive parsing / CRUD / ordering without a DOM, and the module-level store
13
+ * (snapshot + subscribe) is what makes the popover and the Ctrl+B shortcut share
14
+ * one list.
15
+ */
16
+
17
+ /** One saved command. */
18
+ export interface TerminalSnippet {
19
+ /** Stable identity (never reused, so drag/reorder cannot swap rows). */
20
+ id: string
21
+ /** Short label shown in the list. */
22
+ name: string
23
+ /** The command text pasted into the terminal (not executed). */
24
+ command: string
25
+ }
26
+
27
+ /** localStorage key (one JSON array, so the list cannot half-update). */
28
+ export const SNIPPETS_KEY = 'dsh-remote-vs.term.snippets'
29
+
30
+ /** Hard caps: a snippet list is a convenience, not a dataset. */
31
+ export const SNIPPETS_MAX = 200
32
+ export const SNIPPET_NAME_MAX = 80
33
+ export const SNIPPET_COMMAND_MAX = 4000
34
+
35
+ /** A fresh identity for one snippet. */
36
+ export function createSnippetId(): string {
37
+ return `s${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
38
+ }
39
+
40
+ /**
41
+ * Normalize one user-entered snippet; `undefined` when it is unusable.
42
+ *
43
+ * Both fields are required (an unnamed command is unfindable, an empty command
44
+ * does nothing) and both are trimmed — a leading/trailing newline in a pasted
45
+ * command would otherwise send an empty line and RUN the command, which is
46
+ * exactly what this feature promises not to do.
47
+ */
48
+ export function sanitizeSnippetInput(input: { name?: string; command?: string }): { name: string; command: string } | undefined {
49
+ const name = (input.name ?? '').trim().slice(0, SNIPPET_NAME_MAX)
50
+ const command = (input.command ?? '').trim().slice(0, SNIPPET_COMMAND_MAX)
51
+ if (name === '' || command === '') return undefined
52
+ return { name, command }
53
+ }
54
+
55
+ /** Parse the persisted JSON; anything malformed is dropped, never repaired silently. */
56
+ export function parseSnippets(raw: string | null | undefined): TerminalSnippet[] {
57
+ if (typeof raw !== 'string' || raw === '') return []
58
+ let parsed: unknown
59
+ try {
60
+ parsed = JSON.parse(raw) as unknown
61
+ } catch {
62
+ return []
63
+ }
64
+ if (!Array.isArray(parsed)) return []
65
+ const list: TerminalSnippet[] = []
66
+ const seen = new Set<string>()
67
+ for (const item of parsed) {
68
+ if (typeof item !== 'object' || item === null) continue
69
+ const record = item as Record<string, unknown>
70
+ const sanitized = sanitizeSnippetInput({
71
+ name: typeof record.name === 'string' ? record.name : '',
72
+ command: typeof record.command === 'string' ? record.command : '',
73
+ })
74
+ if (sanitized === undefined) continue
75
+ // A duplicated id would make two rows share a React key and a drag target.
76
+ let id = typeof record.id === 'string' && record.id !== '' ? record.id : createSnippetId()
77
+ if (seen.has(id)) id = createSnippetId()
78
+ seen.add(id)
79
+ list.push({ id, ...sanitized })
80
+ if (list.length >= SNIPPETS_MAX) break
81
+ }
82
+ return list
83
+ }
84
+
85
+ /** Serialize only the known fields. */
86
+ export function serializeSnippets(list: readonly TerminalSnippet[]): string {
87
+ return JSON.stringify(list.map(item => ({ id: item.id, name: item.name, command: item.command })))
88
+ }
89
+
90
+ /** Append one snippet (newest last); returns the SAME array when it is invalid. */
91
+ export function addSnippet(
92
+ list: readonly TerminalSnippet[],
93
+ input: { name?: string; command?: string },
94
+ id: string = createSnippetId(),
95
+ ): SnippetList {
96
+ const sanitized = sanitizeSnippetInput(input)
97
+ if (sanitized === undefined) return list
98
+ if (list.some(item => item.id === id)) id = createSnippetId()
99
+ const next = [...list, { id, ...sanitized }]
100
+ // The cap drops the OLDEST entry: the newest command is the one being used.
101
+ return next.length > SNIPPETS_MAX ? next.slice(next.length - SNIPPETS_MAX) : next
102
+ }
103
+
104
+ /** Replace one snippet's fields; an invalid edit leaves the list untouched. */
105
+ export function updateSnippet(
106
+ list: readonly TerminalSnippet[],
107
+ id: string,
108
+ input: { name?: string; command?: string },
109
+ ): SnippetList {
110
+ const index = list.findIndex(item => item.id === id)
111
+ if (index < 0) return list
112
+ const sanitized = sanitizeSnippetInput(input)
113
+ if (sanitized === undefined) return list
114
+ const current = list[index] as TerminalSnippet
115
+ if (current.name === sanitized.name && current.command === sanitized.command) return list
116
+ const next = [...list]
117
+ next[index] = { id, ...sanitized }
118
+ return next
119
+ }
120
+
121
+ /** Drop one snippet. */
122
+ export function removeSnippet(list: readonly TerminalSnippet[], id: string): SnippetList {
123
+ const next = list.filter(item => item.id !== id)
124
+ return next.length === list.length ? list : next
125
+ }
126
+
127
+ /**
128
+ * Move one snippet to another index (drag & drop), clamping both ends.
129
+ *
130
+ * Returning the SAME list for a no-op keeps the store's "did it change" test
131
+ * cheap and stops a drag that lands on its own row from re-rendering everything.
132
+ */
133
+ export function moveSnippet(list: readonly TerminalSnippet[], from: number, to: number): SnippetList {
134
+ if (list.length < 2) return list
135
+ const source = Math.max(0, Math.min(list.length - 1, from))
136
+ const target = Math.max(0, Math.min(list.length - 1, to))
137
+ if (source === target) return list
138
+ const next = [...list]
139
+ const [moved] = next.splice(source, 1)
140
+ if (moved === undefined) return list
141
+ next.splice(target, 0, moved)
142
+ return next
143
+ }
144
+
145
+ /** A list type that is either the caller's unchanged value or a new array. */
146
+ type SnippetList = readonly TerminalSnippet[]
147
+
148
+ // ----------------------------------------------------------------- store
149
+
150
+ const listeners = new Set<() => void>()
151
+ /** Lazy current list; undefined = localStorage not read yet. */
152
+ let current: readonly TerminalSnippet[] | undefined
153
+
154
+ function readFromStorage(): readonly TerminalSnippet[] {
155
+ try {
156
+ return parseSnippets(localStorage.getItem(SNIPPETS_KEY))
157
+ } catch {
158
+ // Private mode / storage disabled: the list works for this session only.
159
+ return []
160
+ }
161
+ }
162
+
163
+ function persist(list: readonly TerminalSnippet[]): void {
164
+ try {
165
+ localStorage.setItem(SNIPPETS_KEY, serializeSnippets(list))
166
+ } catch {
167
+ // Same as above: failing to persist does not affect this session.
168
+ }
169
+ }
170
+
171
+ function emit(): void {
172
+ for (const listener of [...listeners]) {
173
+ try {
174
+ listener()
175
+ } catch {
176
+ // One broken surface must not starve the others.
177
+ }
178
+ }
179
+ }
180
+
181
+ /** Current list (identity-stable while unchanged, safe for useSyncExternalStore). */
182
+ export function snippetsSnapshot(): readonly TerminalSnippet[] {
183
+ if (current === undefined) current = readFromStorage()
184
+ return current
185
+ }
186
+
187
+ /** Subscribe to snippet changes; returns the unsubscribe. */
188
+ export function subscribeSnippets(listener: () => void): () => void {
189
+ listeners.add(listener)
190
+ return () => {
191
+ listeners.delete(listener)
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Apply one pure transition and persist it when it really changed.
197
+ *
198
+ * The updater must be pure and return either the same array (no change → no
199
+ * notification, no write) or a new one; every CRUD helper above already does.
200
+ */
201
+ export function updateSnippets(
202
+ updater: (list: readonly TerminalSnippet[]) => readonly TerminalSnippet[],
203
+ ): void {
204
+ const before = snippetsSnapshot()
205
+ const next = updater(before)
206
+ if (next === before) return
207
+ current = next
208
+ persist(next)
209
+ emit()
210
+ }
211
+
212
+ /** Reset the module store (the gate drives it directly; production never calls it). */
213
+ export function resetSnippetsForTests(list?: readonly TerminalSnippet[]): void {
214
+ current = list ?? []
215
+ listeners.clear()
216
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Breadcrumb above the editor in the full-width (conversation view) variant.
3
+ *
4
+ * Every path segment is clickable and opens a VS Code-style sibling picker: a
5
+ * directory segment lists itself, the file segment lists its parent directory,
6
+ * so "open the file next to this one" costs one click instead of a trip to the
7
+ * tree (whose expansion state lives in another view and cannot be expressed in
8
+ * a URL).
9
+ *
10
+ * Read-only: it only calls `fileOp.list` on the remote. The remote path is the
11
+ * Host's own business — no second validation layer here.
12
+ */
13
+ import { useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'
14
+ import { api } from '../api.ts'
15
+ import type { RemoteFileEntry } from '../../protocol.ts'
16
+
17
+ /** One breadcrumb segment. */
18
+ interface Crumb {
19
+ /** Display text. */
20
+ label: string
21
+ /** Absolute remote path. */
22
+ path: string
23
+ }
24
+
25
+ /** Split an absolute POSIX path into segments (empty path = empty list). */
26
+ function pathSegments(path: string): string[] {
27
+ return path.replace(/\\/g, '/').split('/').filter(part => part !== '')
28
+ }
29
+
30
+ /** Root display name: the binding's name, else the last segment of the root. */
31
+ function rootLabel(root: string, rootName: string, fallback: string): string {
32
+ if (rootName !== '') return rootName
33
+ const parts = pathSegments(root)
34
+ return parts[parts.length - 1] ?? fallback
35
+ }
36
+
37
+ /** Open dropdown state. */
38
+ interface MenuState {
39
+ /** Absolute directory being listed. */
40
+ dir: string
41
+ /** Menu's left edge, relative to the breadcrumb container (px). */
42
+ left: number
43
+ }
44
+
45
+ /** Props of {@link Breadcrumb}. */
46
+ export interface BreadcrumbProps {
47
+ /** i18n lookup (falls back to inline copy when a key is missing). */
48
+ t: (key: string) => string
49
+ /** SSH host alias the workspace lives on (the file route's first argument). */
50
+ alias: string
51
+ /** Remote workspace root, absolute. */
52
+ root: string
53
+ /** Display name of the workspace root. */
54
+ rootName: string
55
+ /** Absolute path of the file on screen. */
56
+ path: string
57
+ /** Open one remote file in the editor. */
58
+ onOpen: (fullPath: string) => void
59
+ }
60
+
61
+ /** Translate one key, falling back to the inline copy when the dictionary lacks it. */
62
+ function tr(t: (key: string) => string, key: string, fallback: string): string {
63
+ const value = t(key)
64
+ return value === undefined || value === '' || value === key ? fallback : value
65
+ }
66
+
67
+ /** Breadcrumb: path segments + sibling dropdown. */
68
+ export function Breadcrumb(props: BreadcrumbProps): ReactNode {
69
+ const navRef = useRef<HTMLElement>(null)
70
+ const [menu, setMenu] = useState<MenuState | undefined>(undefined)
71
+ const [entries, setEntries] = useState<RemoteFileEntry[]>([])
72
+ const [loading, setLoading] = useState(false)
73
+ const [error, setError] = useState<string | undefined>(undefined)
74
+ /** Load token: two quick segment clicks must only let the last answer land. */
75
+ const loadSeq = useRef(0)
76
+
77
+ const t = props.t
78
+ const root = props.root.replace(/\/+$/, '')
79
+ /**
80
+ * A path OUTSIDE the workspace root (a repo sitting next to the binding, a
81
+ * diff path that left the tree) cannot be split into root-relative crumbs:
82
+ * doing it anyway would build `/root/home/...` and the sibling picker would
83
+ * list the wrong directory. Fall back to the plain path line.
84
+ */
85
+ const underRoot = root !== ''
86
+ && (props.path === root || props.path.startsWith(`${root}/`))
87
+ const segments = useMemo(() => {
88
+ const full = props.path.replace(/\/+$/, '')
89
+ if (root !== '' && full.startsWith(`${root}/`)) return pathSegments(full.slice(root.length + 1))
90
+ return pathSegments(full)
91
+ }, [props.path, root])
92
+ const crumbs = useMemo<Crumb[]>(() => {
93
+ const list: Crumb[] = [{ label: rootLabel(root, props.rootName, tr(t, 'editor.crumbRoot', '工作区')), path: root }]
94
+ for (const [index, segment] of segments.entries()) {
95
+ list.push({ label: segment, path: `${root}/${segments.slice(0, index + 1).join('/')}` })
96
+ }
97
+ return list
98
+ }, [root, props.rootName, segments, t])
99
+
100
+ /** List one directory and show the menu; `left` keeps the current position. */
101
+ const openMenu = (dir: string, left: number): void => {
102
+ setMenu({ dir, left })
103
+ setLoading(true)
104
+ setError(undefined)
105
+ loadSeq.current += 1
106
+ const token = loadSeq.current
107
+ void (async () => {
108
+ try {
109
+ const listed = await api.fileOp.list(props.alias, dir)
110
+ if (loadSeq.current !== token) return
111
+ // Directories first, then names: same order as the tree, faster to scan.
112
+ const sorted = [...listed].sort((a, b) => {
113
+ const aDir = a.isDir ? 0 : 1
114
+ const bDir = b.isDir ? 0 : 1
115
+ if (aDir !== bDir) return aDir - bDir
116
+ return a.name.localeCompare(b.name)
117
+ })
118
+ setEntries(sorted)
119
+ } catch (caught) {
120
+ if (loadSeq.current !== token) return
121
+ setEntries([])
122
+ setError(caught instanceof Error ? caught.message : String(caught))
123
+ } finally {
124
+ if (loadSeq.current === token) setLoading(false)
125
+ }
126
+ })()
127
+ }
128
+
129
+ // Close on an outside click / Esc. Capture phase: CodeMirror's own mousedown
130
+ // handling must not run first (it grabs focus back and the menu looks stuck).
131
+ useEffect(() => {
132
+ if (menu === undefined) return
133
+ const onMouseDown = (event: MouseEvent): void => {
134
+ const nav = navRef.current
135
+ if (nav !== null && event.target instanceof Node && nav.contains(event.target)) return
136
+ setMenu(undefined)
137
+ }
138
+ const onKeyDown = (event: KeyboardEvent): void => {
139
+ // During IME composition Esc cancels the candidate, not the menu.
140
+ if (event.isComposing) return
141
+ if (event.key === 'Escape') setMenu(undefined)
142
+ }
143
+ document.addEventListener('mousedown', onMouseDown, true)
144
+ document.addEventListener('keydown', onKeyDown, true)
145
+ return () => {
146
+ document.removeEventListener('mousedown', onMouseDown, true)
147
+ document.removeEventListener('keydown', onKeyDown, true)
148
+ }
149
+ }, [menu])
150
+
151
+ // Another file closes the menu: a stale dropdown over a new file is misaligned.
152
+ useEffect(() => {
153
+ setMenu(undefined)
154
+ }, [props.path])
155
+
156
+ if (!underRoot) {
157
+ return (
158
+ <nav className="rvs-breadcrumb" aria-label={tr(t, 'editor.crumbLabel', '文件路径')}>
159
+ <span className="rvs-einfo-path" title={props.path}>{props.path}</span>
160
+ </nav>
161
+ )
162
+ }
163
+
164
+ /** Click a segment: a directory lists itself; the file lists its parent. */
165
+ const clickCrumb = (crumb: Crumb, index: number, event: ReactMouseEvent<HTMLButtonElement>): void => {
166
+ const isFile = index === crumbs.length - 1
167
+ const dir = isFile ? crumb.path.slice(0, Math.max(0, crumb.path.lastIndexOf('/'))) : crumb.path
168
+ openMenu(dir === '' ? '/' : dir, Math.max(0, event.currentTarget.offsetLeft))
169
+ }
170
+
171
+ const parentDirOf = (dir: string): string | undefined => {
172
+ if (dir === '' || dir === root || dir === '/') return undefined
173
+ const parts = pathSegments(dir)
174
+ parts.pop()
175
+ return parts.length === 0 ? undefined : `/${parts.join('/')}`
176
+ }
177
+
178
+ return (
179
+ <nav className="rvs-breadcrumb" ref={navRef} aria-label={tr(t, 'editor.crumbLabel', '文件路径')}>
180
+ {crumbs.map((crumb, index) => {
181
+ const isFile = index === crumbs.length - 1
182
+ return (
183
+ <span className="rvs-crumb-wrap" key={`${crumb.path}:${index}`}>
184
+ {index > 0 && <span className="rvs-crumb-sep" aria-hidden="true">›</span>}
185
+ <button
186
+ type="button"
187
+ className={`rvs-crumb${isFile ? ' rvs-crumb-file' : ''}`}
188
+ // The last segment is the FILE (its menu lists siblings); a
189
+ // directory segment lists ITSELF, so the hint must not promise
190
+ // sibling files there.
191
+ title={isFile ? props.path : crumb.path}
192
+ aria-haspopup="menu"
193
+ onClick={event => clickCrumb(crumb, index, event)}
194
+ >
195
+ {crumb.label}
196
+ </button>
197
+ </span>
198
+ )
199
+ })}
200
+
201
+ {menu !== undefined && (
202
+ <div className="rvs-crumb-menu" role="menu" style={{ left: menu.left }}>
203
+ <div className="rvs-crumb-menu-head">
204
+ <button
205
+ type="button"
206
+ className="rvs-crumb-menu-up"
207
+ title={tr(t, 'editor.crumbUp', '上一级')}
208
+ disabled={parentDirOf(menu.dir) === undefined}
209
+ onClick={() => {
210
+ const parent = parentDirOf(menu.dir)
211
+ if (parent === undefined) return
212
+ openMenu(parent, menu.left)
213
+ }}
214
+ >
215
+ ↑
216
+ </button>
217
+ <span className="rvs-crumb-menu-path" title={menu.dir}>{menu.dir}</span>
218
+ </div>
219
+ <div className="rvs-crumb-menu-list">
220
+ {loading && <div className="rvs-crumb-menu-note">{tr(t, 'common.loading', '加载中…')}</div>}
221
+ {!loading && error !== undefined && <div className="rvs-crumb-menu-note rvs-status-error">{error}</div>}
222
+ {!loading && error === undefined && entries.length === 0 && (
223
+ <div className="rvs-crumb-menu-note">{tr(t, 'editor.crumbEmpty', '空目录')}</div>
224
+ )}
225
+ {!loading && error === undefined && entries.map(entry => (
226
+ <button
227
+ key={entry.path}
228
+ type="button"
229
+ role="menuitem"
230
+ className={`rvs-crumb-menu-item${entry.isDir ? ' rvs-dir' : ''}`}
231
+ title={entry.path}
232
+ onClick={() => {
233
+ if (entry.isDir) {
234
+ openMenu(entry.path, menu.left)
235
+ return
236
+ }
237
+ // Stay on the surface this breadcrumb belongs to: no sidebar jump.
238
+ props.onOpen(entry.path)
239
+ setMenu(undefined)
240
+ }}
241
+ >
242
+ <span className="rvs-crumb-menu-glyph" aria-hidden="true">{entry.isDir ? '▸' : '·'}</span>
243
+ <span className="rvs-crumb-menu-name">{entry.name}</span>
244
+ </button>
245
+ ))}
246
+ </div>
247
+ </div>
248
+ )}
249
+ </nav>
250
+ )
251
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Caret readout maths for the editor status bar (pure, no CodeMirror/DOM).
3
+ *
4
+ * Kept out of `CodeEditor.tsx` so the gate can assert the 1-based conversion and
5
+ * the "selected characters" count without mounting an editor.
6
+ */
7
+
8
+ /** Caret readout for the status bar (1-based, matching what the user sees). */
9
+ export interface CodeEditorCaret {
10
+ /** 1-based line of the caret (the selection's head). */
11
+ line: number
12
+ /** 1-based column of the caret. */
13
+ column: number
14
+ /** Number of selected characters (0 = empty selection). */
15
+ selected: number
16
+ }
17
+
18
+ /** The caret reading of one editor state. */
19
+ export function caretOf(state: {
20
+ doc: { lineAt(offset: number): { number: number; from: number; to: number } }
21
+ selection: { main: { head: number; from: number; to: number } }
22
+ }): CodeEditorCaret {
23
+ const main = state.selection.main
24
+ const line = state.doc.lineAt(main.head)
25
+ return {
26
+ line: line.number,
27
+ column: main.head - line.from + 1,
28
+ selected: Math.max(0, main.to - main.from),
29
+ }
30
+ }
@@ -135,3 +135,23 @@ export function langFor(path: string): Extension[] {
135
135
  return []
136
136
  }
137
137
  }
138
+
139
+ /**
140
+ * Guess the indentation style from the file body (status-bar hint only).
141
+ *
142
+ * Only the first stretch of lines that really starts with whitespace is
143
+ * inspected: the goal is a quick hint, not a formatter. `undefined` means "no
144
+ * indented line in the head", and the status bar then omits the item instead of
145
+ * inventing a default.
146
+ */
147
+ export function detectIndentLabel(text: string): string | undefined {
148
+ const lines = text.split('\n', 200)
149
+ for (const line of lines) {
150
+ if (line.trim() === '') continue
151
+ if (line.startsWith('\t')) return 'Tab'
152
+ const spaces = /^ +/.exec(line)
153
+ if (spaces === null) continue
154
+ return `Spaces: ${Math.min(8, spaces[0].length)}`
155
+ }
156
+ return undefined
157
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Editor view preferences (word wrap + font size), shared by every surface that
3
+ * shows the editor (the sidebar pane, the conversation-view tab, the floating
4
+ * window).
5
+ *
6
+ * Module-level, React/DOM-free on purpose: those three surfaces are three
7
+ * different React trees, so React state cannot carry "I made the font bigger in
8
+ * the floating window, dock it and the sidebar must show the same size" — which
9
+ * is the whole point (it is ONE editor, only its mount changes).
10
+ *
11
+ * The pure parse/serialize half is exported because the self-check harness
12
+ * imports this module in Node: it must not read localStorage at module load
13
+ * (private mode throws on `getItem`).
14
+ */
15
+
16
+ /** One shared view preference set. */
17
+ export interface EditorSettings {
18
+ /** Soft wrap the long lines. */
19
+ wrap: boolean
20
+ /** Editor type size in px (0.5 px steps are legal). */
21
+ fontSize: number
22
+ }
23
+
24
+ /** localStorage key: ONE JSON object, so the two fields cannot drift apart. */
25
+ export const EDITOR_SETTINGS_KEY = 'dsh-remote-vs.editor.settings'
26
+
27
+ /** Legal font-size range, shared with the floating window's Ctrl+wheel zoom. */
28
+ export const FONT_MIN = 9
29
+ export const FONT_MAX = 28
30
+ export const FONT_STEP = 1
31
+
32
+ /** Defaults used before anything was stored (matches the theme's 13px fallback). */
33
+ export const DEFAULT_EDITOR_SETTINGS: EditorSettings = { wrap: false, fontSize: 13 }
34
+
35
+ /** Clamp any input to a legal font size; non-numbers answer undefined. */
36
+ export function parseFontSize(value: unknown): number | undefined {
37
+ const numeric = typeof value === 'number'
38
+ ? value
39
+ : typeof value === 'string' && value.trim() !== ''
40
+ ? Number(value)
41
+ : Number.NaN
42
+ if (!Number.isFinite(numeric)) return undefined
43
+ // Half-pixel steps are legal (historically 12.5px); 13.3333 noise snaps to the grid.
44
+ const snapped = Math.round(numeric * 2) / 2
45
+ return Math.min(FONT_MAX, Math.max(FONT_MIN, snapped))
46
+ }
47
+
48
+ /** One zoom step (-1 = smaller, +1 = bigger), already clamped. */
49
+ export function stepFontSize(size: number, direction: -1 | 1): number {
50
+ const current = parseFontSize(size) ?? DEFAULT_EDITOR_SETTINGS.fontSize
51
+ return parseFontSize(current + direction * FONT_STEP) ?? current
52
+ }
53
+
54
+ /**
55
+ * Parse the persisted JSON.
56
+ *
57
+ * Anything damaged (not JSON, not an object, wrong field types) falls back to
58
+ * the defaults: this data only affects presentation, and a dirty localStorage
59
+ * entry must never keep the page from starting.
60
+ */
61
+ export function parseEditorSettings(raw: string | null | undefined): EditorSettings {
62
+ if (typeof raw !== 'string' || raw === '') return DEFAULT_EDITOR_SETTINGS
63
+ let parsed: unknown
64
+ try {
65
+ parsed = JSON.parse(raw) as unknown
66
+ } catch {
67
+ return DEFAULT_EDITOR_SETTINGS
68
+ }
69
+ if (typeof parsed !== 'object' || parsed === null) return DEFAULT_EDITOR_SETTINGS
70
+ const record = parsed as Record<string, unknown>
71
+ const fontSize = parseFontSize(record.fontSize) ?? DEFAULT_EDITOR_SETTINGS.fontSize
72
+ const wrap = typeof record.wrap === 'boolean' ? record.wrap : DEFAULT_EDITOR_SETTINGS.wrap
73
+ return { wrap, fontSize }
74
+ }
75
+
76
+ /** Serialize only the known fields (never whatever else the caller passed). */
77
+ export function serializeEditorSettings(settings: EditorSettings): string {
78
+ return JSON.stringify({ wrap: settings.wrap, fontSize: settings.fontSize })
79
+ }
80
+
81
+ // ------------------------------------------------------------------ store
82
+
83
+ const listeners = new Set<() => void>()
84
+ /** Lazy current value; undefined = localStorage not read yet. */
85
+ let current: EditorSettings | undefined
86
+
87
+ function readFromStorage(): EditorSettings {
88
+ try {
89
+ return parseEditorSettings(localStorage.getItem(EDITOR_SETTINGS_KEY))
90
+ } catch {
91
+ // Private mode / storage disabled: the defaults still work this session.
92
+ return DEFAULT_EDITOR_SETTINGS
93
+ }
94
+ }
95
+
96
+ function persist(settings: EditorSettings): void {
97
+ try {
98
+ localStorage.setItem(EDITOR_SETTINGS_KEY, serializeEditorSettings(settings))
99
+ } catch {
100
+ // Same as above: failing to persist does not affect this session.
101
+ }
102
+ }
103
+
104
+ function emit(): void {
105
+ for (const listener of [...listeners]) {
106
+ try {
107
+ listener()
108
+ } catch {
109
+ // One broken surface must not starve the others.
110
+ }
111
+ }
112
+ }
113
+
114
+ /** Current snapshot (identity-stable while unchanged, safe for useSyncExternalStore). */
115
+ export function editorSettingsSnapshot(): EditorSettings {
116
+ if (current === undefined) current = readFromStorage()
117
+ return current
118
+ }
119
+
120
+ /** Subscribe to preference changes; returns the unsubscribe. */
121
+ export function subscribeEditorSettings(listener: () => void): () => void {
122
+ listeners.add(listener)
123
+ return () => {
124
+ listeners.delete(listener)
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Change one preference and persist it.
130
+ *
131
+ * Illegal values (out-of-range size) are clamped BEFORE the "did it change"
132
+ * comparison: without that, every click on a "+" already at the cap would
133
+ * re-render all three surfaces for nothing.
134
+ */
135
+ export function updateEditorSettings(patch: Partial<EditorSettings>): void {
136
+ const before = editorSettingsSnapshot()
137
+ const fontSize = patch.fontSize === undefined
138
+ ? before.fontSize
139
+ : parseFontSize(patch.fontSize) ?? before.fontSize
140
+ const wrap = patch.wrap === undefined ? before.wrap : patch.wrap
141
+ if (fontSize === before.fontSize && wrap === before.wrap) return
142
+ const next: EditorSettings = { wrap, fontSize }
143
+ current = next
144
+ persist(next)
145
+ emit()
146
+ }
@@ -29,11 +29,10 @@ function chrome(p: Palette, dark: boolean): Extension {
29
29
  '&': {
30
30
  backgroundColor: p.bg,
31
31
  color: p.fg,
32
- // The floating window changes ONLY its own editor's type size (Ctrl+wheel,
33
- // see FloatingEditorWindow); the variable is unset everywhere else, so the
34
- // normal editor keeps 13px. A plain literal here would freeze the size and
35
- // make the zoom silently do nothing. The zoom is a property of the window,
36
- // so a docked editor always renders at the default size.
32
+ // Type size comes from a CSS variable: the docked pane and the
33
+ // conversation tab set it from the shared editor preference (font buttons /
34
+ // Ctrl+wheel), while the floating window sets it from its own per-window
35
+ // zoom. A plain literal here would freeze the size and make both silent.
37
36
  fontSize: 'var(--rvs-editor-font-size, 13px)',
38
37
  height: '100%',
39
38
  },