dsh-remote-vs 0.24.0 → 0.26.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 (125) hide show
  1. package/README.en.md +50 -16
  2. package/README.md +40 -15
  3. package/THIRD-PARTY-NOTICES.md +188 -0
  4. package/lib/client.js +6512 -77887
  5. package/lib/index.js +1461 -1024
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +25 -0
  8. package/lib/types/client/EditorPane.d.ts +16 -5
  9. package/lib/types/client/FloatingPlaceholder.d.ts +16 -5
  10. package/lib/types/client/RemoteEditorView.d.ts +13 -10
  11. package/lib/types/client/RemoteExplorer.d.ts +53 -0
  12. package/lib/types/client/RemoteRoot.d.ts +5 -5
  13. package/lib/types/client/TerminalSnippets.d.ts +36 -0
  14. package/lib/types/client/TerminalView.d.ts +1 -1
  15. package/lib/types/client/XTerm.d.ts +33 -0
  16. package/lib/types/client/api.d.ts +37 -2
  17. package/lib/types/client/changes/review-state.d.ts +19 -0
  18. package/lib/types/client/connection.d.ts +16 -0
  19. package/lib/types/client/editor-capability.d.ts +27 -0
  20. package/lib/types/client/i18n.d.ts +1 -1
  21. package/lib/types/client/request-gate.d.ts +110 -0
  22. package/lib/types/client/scm/DiffView.d.ts +45 -7
  23. package/lib/types/client/scm/actions.d.ts +31 -3
  24. package/lib/types/client/store.d.ts +112 -4
  25. package/lib/types/client/terminal-input.d.ts +23 -0
  26. package/lib/types/client/terminal-snippets.d.ts +86 -0
  27. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  28. package/lib/types/client/vsc/breadcrumb.d.ts +30 -0
  29. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  30. package/lib/types/client/vsc/editor-caret.d.ts +32 -0
  31. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  32. package/lib/types/client/vsc/editor-langs.d.ts +9 -0
  33. package/lib/types/client/vsc/editor-settings.d.ts +55 -0
  34. package/lib/types/client/vsc/image-preview.d.ts +36 -0
  35. package/lib/types/client/vsc/kit.d.ts +13 -0
  36. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  37. package/lib/types/client/vsc/terminal-clipboard.d.ts +15 -0
  38. package/lib/types/client/vsc/terminal-line.d.ts +25 -0
  39. package/lib/types/client/vsc/terminal-links.d.ts +62 -0
  40. package/lib/types/client/vsc/terminal-theme.d.ts +48 -0
  41. package/lib/types/client/vsc/terminal-writer.d.ts +52 -0
  42. package/lib/types/forward.d.ts +12 -0
  43. package/lib/types/fs-ops.d.ts +42 -0
  44. package/lib/types/http.d.ts +2 -0
  45. package/lib/types/keygen.d.ts +9 -0
  46. package/lib/types/monitor.d.ts +8 -0
  47. package/lib/types/notices.d.ts +16 -1
  48. package/lib/types/p2/helper-rpc.d.ts +45 -0
  49. package/lib/types/pool.d.ts +25 -0
  50. package/lib/types/routes.d.ts +2 -0
  51. package/lib/types/store.d.ts +7 -0
  52. package/lib/types/terminal.d.ts +33 -1
  53. package/lib/types/view-settings.d.ts +5 -0
  54. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  55. package/package.json +2 -1
  56. package/src/client/CodeEditor.tsx +205 -10
  57. package/src/client/DirectoryFlow.tsx +16 -0
  58. package/src/client/DoctorPanel.tsx +70 -7
  59. package/src/client/EditorPane.tsx +545 -118
  60. package/src/client/FloatingPlaceholder.tsx +34 -5
  61. package/src/client/HostsView.tsx +12 -3
  62. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  63. package/src/client/RemoteEditorView.tsx +14 -11
  64. package/src/client/RemoteExplorer.tsx +929 -40
  65. package/src/client/RemoteRoot.tsx +167 -147
  66. package/src/client/SearchView.tsx +8 -0
  67. package/src/client/TerminalSnippets.tsx +432 -0
  68. package/src/client/TerminalView.tsx +50 -1
  69. package/src/client/XTerm.tsx +228 -58
  70. package/src/client/api.ts +106 -13
  71. package/src/client/auto-open-remote.ts +11 -9
  72. package/src/client/changes/ChangesDock.tsx +188 -6
  73. package/src/client/changes/changes.css +10 -3
  74. package/src/client/changes/review-state.ts +34 -0
  75. package/src/client/connection.ts +29 -0
  76. package/src/client/downloads.ts +49 -4
  77. package/src/client/editor-capability.ts +42 -0
  78. package/src/client/i18n.ts +228 -12
  79. package/src/client/index.tsx +22 -6
  80. package/src/client/request-gate.ts +221 -0
  81. package/src/client/scm/CommitPane.tsx +20 -2
  82. package/src/client/scm/DiffView.tsx +343 -117
  83. package/src/client/scm/HistoryPanel.tsx +23 -2
  84. package/src/client/scm/RepoPicker.tsx +1 -1
  85. package/src/client/scm/ScmPanel.tsx +391 -87
  86. package/src/client/scm/actions.ts +95 -12
  87. package/src/client/store.tsx +537 -22
  88. package/src/client/terminal-input.ts +44 -0
  89. package/src/client/terminal-snippets.ts +216 -0
  90. package/src/client/ui.tsx +4 -0
  91. package/src/client/vsc/FindWidget.tsx +24 -9
  92. package/src/client/vsc/breadcrumb.tsx +339 -0
  93. package/src/client/vsc/change-marks.ts +93 -44
  94. package/src/client/vsc/editor-caret.ts +30 -0
  95. package/src/client/vsc/editor-keymap.ts +59 -1
  96. package/src/client/vsc/editor-langs.ts +20 -0
  97. package/src/client/vsc/editor-settings.ts +146 -0
  98. package/src/client/vsc/editor-theme.ts +4 -5
  99. package/src/client/vsc/file-icons.tsx +17 -3
  100. package/src/client/vsc/image-preview.tsx +110 -0
  101. package/src/client/vsc/kit.tsx +46 -10
  102. package/src/client/vsc/save-shortcut.ts +47 -1
  103. package/src/client/vsc/terminal-clipboard.ts +19 -0
  104. package/src/client/vsc/terminal-line.ts +101 -0
  105. package/src/client/vsc/terminal-links.ts +166 -0
  106. package/src/client/vsc/terminal-theme.ts +97 -0
  107. package/src/client/vsc/terminal-writer.ts +112 -0
  108. package/src/client/vsc/vsc.css +1078 -181
  109. package/src/forward.ts +47 -9
  110. package/src/fs-ops.ts +124 -4
  111. package/src/git-ops.ts +20 -3
  112. package/src/http.ts +35 -4
  113. package/src/keygen.ts +55 -4
  114. package/src/monitor.ts +13 -0
  115. package/src/notices.ts +23 -1
  116. package/src/p2/helper-rpc.ts +113 -7
  117. package/src/p2/worlds.ts +14 -1
  118. package/src/pool.ts +99 -27
  119. package/src/routes.ts +212 -43
  120. package/src/sftp.ts +51 -14
  121. package/src/store.ts +10 -0
  122. package/src/terminal.ts +225 -24
  123. package/src/view-settings.ts +50 -10
  124. package/lib/types/client/Dialog.d.ts +0 -14
  125. package/src/client/Dialog.tsx +0 -76
@@ -0,0 +1,44 @@
1
+ /**
2
+ * One registry for "type this into that terminal's command line".
3
+ *
4
+ * The snippet panel lives in the terminal's HEADER while the xterm instance is
5
+ * owned by a child component, so the panel needs an imperative handle without
6
+ * lifting xterm state into React (a re-render per keystroke would be absurd).
7
+ * Each mounted `XTerm` registers a paste function under its tab id and removes
8
+ * it on unmount; the panel asks for the ACTIVE tab.
9
+ *
10
+ * Deliberately NOT exported as a React hook: callers are event handlers inside
11
+ * a portal, not render code.
12
+ */
13
+
14
+ /** Registered terminals: tab id → "paste this text, do not press Enter". */
15
+ const pasters = new Map<string, (text: string) => void>()
16
+
17
+ /** Register one mounted terminal; returns the unregister. */
18
+ export function registerTerminalPaste(tabId: string, paste: (text: string) => void): () => void {
19
+ pasters.set(tabId, paste)
20
+ return () => {
21
+ // Only remove OUR entry: a remount (reconnect) registers again under the
22
+ // same id and its cleanup must not delete the newcomer.
23
+ if (pasters.get(tabId) === paste) pasters.delete(tabId)
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Insert one command into the given terminal without sending it.
29
+ *
30
+ * @returns false when that tab has no mounted terminal any more (a closed tab, a
31
+ * panel that is not rendered) — the caller says so instead of pretending.
32
+ */
33
+ export function pasteIntoTerminal(tabId: string | undefined, text: string): boolean {
34
+ if (tabId === undefined || text === '') return false
35
+ const paste = pasters.get(tabId)
36
+ if (paste === undefined) return false
37
+ paste(text)
38
+ return true
39
+ }
40
+
41
+ /** How many terminals are registered (diagnostics; also handy for the gate). */
42
+ export function registeredTerminalCount(): number {
43
+ return pasters.size
44
+ }
@@ -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
+ }
package/src/client/ui.tsx CHANGED
@@ -107,6 +107,10 @@ export function Spinner(props: { size?: number }): ReactNode {
107
107
  export function Notice(props: { kind: 'info' | 'error'; children: ReactNode }): ReactNode {
108
108
  return (
109
109
  <div
110
+ // A banner is how a remote failure reaches the user (a refused write, a
111
+ // dead link): announce it. An error asserts; informational copy is polite
112
+ // so it does not interrupt what the user is typing.
113
+ role={props.kind === 'error' ? 'alert' : 'status'}
110
114
  style={{
111
115
  margin: '8px 0',
112
116
  padding: '6px 10px',
@@ -250,6 +250,12 @@ export function stepFind(view: EditorView, forward: boolean, state?: FindState):
250
250
  export function FindWidget(props: {
251
251
  view: EditorView | undefined
252
252
  open: boolean
253
+ /**
254
+ * The page's dictionary translator. Required, not defaulted: the widget has
255
+ * no language of its own, and a silent Chinese fallback is exactly the
256
+ * hardcoded copy this prop replaced.
257
+ */
258
+ t: (key: string) => string
253
259
  /** A selection carried in by Ctrl+F (`id` bumps to re-trigger). */
254
260
  seed: { text: string; id: number }
255
261
  /**
@@ -419,11 +425,21 @@ export function FindWidget(props: {
419
425
  <input
420
426
  ref={inputRef}
421
427
  className="rvs-find-input"
422
- placeholder="查找"
428
+ placeholder={props.t('find.placeholder')}
423
429
  value={state.query}
424
430
  spellCheck={false}
425
431
  onChange={(e) => patch({ query: e.target.value })}
426
432
  onKeyDown={(e) => {
433
+ // An IME candidate window uses Enter to pick a character and Escape
434
+ // to drop it. Acting on them would seek to a half-composed query or
435
+ // close the widget mid-composition, and preventDefault here can
436
+ // swallow the candidate commit. Stopping propagation first keeps the
437
+ // host's editor/tree shortcuts out of the composing keystroke.
438
+ // `isComposing` is the platform-agnostic signal; `keyCode === 229` is
439
+ // the fallback for engines that dispatch compositionend before this
440
+ // keydown (Chrome), so one Enter cannot seek twice.
441
+ e.stopPropagation()
442
+ if (e.nativeEvent.isComposing === true || e.keyCode === 229) return
427
443
  if (e.key === 'Enter') {
428
444
  e.preventDefault()
429
445
  seek(!e.shiftKey)
@@ -435,30 +451,29 @@ export function FindWidget(props: {
435
451
  e.preventDefault()
436
452
  e.currentTarget.select()
437
453
  }
438
- e.stopPropagation()
439
454
  }}
440
455
  />
441
456
  <span className="rvs-toggles">
442
- {toggle('caseSensitive', '区分大小写(Aa)')}
443
- {toggle('wholeWord', '全字匹配(ab_)')}
444
- {toggle('regexp', '正则表达式(.*)')}
457
+ {toggle('caseSensitive', props.t('find.caseSensitive'))}
458
+ {toggle('wholeWord', props.t('find.wholeWord'))}
459
+ {toggle('regexp', props.t('find.regexp'))}
445
460
  </span>
446
461
  <span className={count.total === 0 ? 'rvs-find-count none' : 'rvs-find-count'}>
447
- {state.query === '' ? '' : count.total === 0 ? '无结果' : `${count.index || 1}/${count.total}`}
462
+ {state.query === '' ? '' : count.total === 0 ? props.t('find.noResults') : `${count.index || 1}/${count.total}`}
448
463
  </span>
449
464
  <IconButton
450
- title="上一个(Shift+Enter)"
465
+ title={props.t('find.prev')}
451
466
  onClick={() => seek(false)}
452
467
  >
453
468
  <span style={{ fontSize: 13 }}>↑</span>
454
469
  </IconButton>
455
470
  <IconButton
456
- title="下一个(Enter)"
471
+ title={props.t('find.next')}
457
472
  onClick={() => seek(true)}
458
473
  >
459
474
  <span style={{ fontSize: 13 }}>↓</span>
460
475
  </IconButton>
461
- <IconButton title="关闭(Esc)" onClick={props.onClose}>
476
+ <IconButton title={props.t('find.close')} onClick={props.onClose}>
462
477
  <IconClose size={11} />
463
478
  </IconButton>
464
479
  </div>
@@ -0,0 +1,339 @@
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 {
14
+ useEffect,
15
+ useMemo,
16
+ useRef,
17
+ useState,
18
+ type KeyboardEvent as ReactKeyboardEvent,
19
+ type MouseEvent as ReactMouseEvent,
20
+ type ReactNode,
21
+ } from 'react'
22
+ import { api } from '../api.ts'
23
+ import type { RemoteFileEntry } from '../../protocol.ts'
24
+
25
+ /** One breadcrumb segment. */
26
+ interface Crumb {
27
+ /** Display text. */
28
+ label: string
29
+ /** Absolute remote path. */
30
+ path: string
31
+ }
32
+
33
+ /** Split an absolute POSIX path into segments (empty path = empty list). */
34
+ function pathSegments(path: string): string[] {
35
+ return path.replace(/\\/g, '/').split('/').filter(part => part !== '')
36
+ }
37
+
38
+ /** Root display name: the binding's name, else the last segment of the root. */
39
+ function rootLabel(root: string, rootName: string, fallback: string): string {
40
+ if (rootName !== '') return rootName
41
+ const parts = pathSegments(root)
42
+ return parts[parts.length - 1] ?? fallback
43
+ }
44
+
45
+ /** Open dropdown state. */
46
+ interface MenuState {
47
+ /** Absolute directory being listed. */
48
+ dir: string
49
+ /** Menu's left edge, relative to the breadcrumb container (px). */
50
+ left: number
51
+ }
52
+
53
+ /** Props of {@link Breadcrumb}. */
54
+ export interface BreadcrumbProps {
55
+ /** i18n lookup (falls back to inline copy when a key is missing). */
56
+ t: (key: string) => string
57
+ /** SSH host alias the workspace lives on (the file route's first argument). */
58
+ alias: string
59
+ /** Remote workspace root, absolute. */
60
+ root: string
61
+ /** Display name of the workspace root. */
62
+ rootName: string
63
+ /** Absolute path of the file on screen. */
64
+ path: string
65
+ /** Open one remote file in the editor. */
66
+ onOpen: (fullPath: string) => void
67
+ }
68
+
69
+ /** Translate one key, falling back to the inline copy when the dictionary lacks it. */
70
+ function tr(t: (key: string) => string, key: string, fallback: string): string {
71
+ const value = t(key)
72
+ return value === undefined || value === '' || value === key ? fallback : value
73
+ }
74
+
75
+ /** Breadcrumb: path segments + sibling dropdown. */
76
+ export function Breadcrumb(props: BreadcrumbProps): ReactNode {
77
+ const navRef = useRef<HTMLElement>(null)
78
+ const [menu, setMenu] = useState<MenuState | undefined>(undefined)
79
+ const [entries, setEntries] = useState<RemoteFileEntry[]>([])
80
+ const [loading, setLoading] = useState(false)
81
+ const [error, setError] = useState<string | undefined>(undefined)
82
+ /** Load token: two quick segment clicks must only let the last answer land. */
83
+ const loadSeq = useRef(0)
84
+ /** The menu box, so opening it can hand over the keyboard. */
85
+ const menuRef = useRef<HTMLDivElement>(null)
86
+ /** The crumb that opened the menu; focus goes back here on an Esc dismissal. */
87
+ const openerRef = useRef<HTMLElement | null>(null)
88
+ /** True when the last close was Esc (only then is focus handed back). */
89
+ const restoreFocus = useRef(false)
90
+ /** The first item is focused once per opening, not on every directory reload. */
91
+ const firstItemFocused = useRef(false)
92
+
93
+ const t = props.t
94
+ const root = props.root.replace(/\/+$/, '')
95
+ /**
96
+ * A path OUTSIDE the workspace root (a repo sitting next to the binding, a
97
+ * diff path that left the tree) cannot be split into root-relative crumbs:
98
+ * doing it anyway would build `/root/home/...` and the sibling picker would
99
+ * list the wrong directory. Fall back to the plain path line.
100
+ */
101
+ const underRoot = root !== ''
102
+ && (props.path === root || props.path.startsWith(`${root}/`))
103
+ const segments = useMemo(() => {
104
+ const full = props.path.replace(/\/+$/, '')
105
+ if (root !== '' && full.startsWith(`${root}/`)) return pathSegments(full.slice(root.length + 1))
106
+ return pathSegments(full)
107
+ }, [props.path, root])
108
+ const crumbs = useMemo<Crumb[]>(() => {
109
+ const list: Crumb[] = [{ label: rootLabel(root, props.rootName, tr(t, 'editor.crumbRoot', '工作区')), path: root }]
110
+ for (const [index, segment] of segments.entries()) {
111
+ list.push({ label: segment, path: `${root}/${segments.slice(0, index + 1).join('/')}` })
112
+ }
113
+ return list
114
+ }, [root, props.rootName, segments, t])
115
+
116
+ /** List one directory and show the menu; `left` keeps the current position. */
117
+ const openMenu = (dir: string, left: number): void => {
118
+ setMenu({ dir, left })
119
+ setLoading(true)
120
+ setError(undefined)
121
+ loadSeq.current += 1
122
+ const token = loadSeq.current
123
+ void (async () => {
124
+ try {
125
+ const listed = await api.fileOp.list(props.alias, dir)
126
+ if (loadSeq.current !== token) return
127
+ // Directories first, then names: same order as the tree, faster to scan.
128
+ const sorted = [...listed].sort((a, b) => {
129
+ const aDir = a.isDir ? 0 : 1
130
+ const bDir = b.isDir ? 0 : 1
131
+ if (aDir !== bDir) return aDir - bDir
132
+ return a.name.localeCompare(b.name)
133
+ })
134
+ setEntries(sorted)
135
+ } catch (caught) {
136
+ if (loadSeq.current !== token) return
137
+ setEntries([])
138
+ setError(caught instanceof Error ? caught.message : String(caught))
139
+ } finally {
140
+ if (loadSeq.current === token) setLoading(false)
141
+ }
142
+ })()
143
+ }
144
+
145
+ // Close on an outside click / Esc. Capture phase: CodeMirror's own mousedown
146
+ // handling must not run first (it grabs focus back and the menu looks stuck).
147
+ useEffect(() => {
148
+ if (menu === undefined) return
149
+ const onMouseDown = (event: MouseEvent): void => {
150
+ const nav = navRef.current
151
+ if (nav !== null && event.target instanceof Node && nav.contains(event.target)) return
152
+ setMenu(undefined)
153
+ }
154
+ const onKeyDown = (event: KeyboardEvent): void => {
155
+ // During IME composition Esc cancels the candidate, not the menu.
156
+ if (event.isComposing) return
157
+ if (event.key === 'Escape') {
158
+ restoreFocus.current = true
159
+ setMenu(undefined)
160
+ }
161
+ }
162
+ document.addEventListener('mousedown', onMouseDown, true)
163
+ document.addEventListener('keydown', onKeyDown, true)
164
+ return () => {
165
+ document.removeEventListener('mousedown', onMouseDown, true)
166
+ document.removeEventListener('keydown', onKeyDown, true)
167
+ }
168
+ }, [menu])
169
+
170
+ // Another file closes the menu: a stale dropdown over a new file is misaligned.
171
+ useEffect(() => {
172
+ setMenu(undefined)
173
+ }, [props.path])
174
+
175
+ /**
176
+ * Menu keyboard model (audit I-12): the menu declared `role="menu"` but had no
177
+ * arrow keys and no initial focus, so a screen reader announced a menu whose
178
+ * items could only be reached with Tab. Opening hands the keyboard to the menu
179
+ * box, and the first item takes it as soon as the (async) listing lands.
180
+ */
181
+ useEffect(() => {
182
+ if (menu === undefined) return
183
+ firstItemFocused.current = false
184
+ menuRef.current?.focus()
185
+ }, [menu])
186
+
187
+ useEffect(() => {
188
+ if (menu === undefined || loading || error !== undefined || entries.length === 0) return
189
+ if (firstItemFocused.current) return
190
+ const box = menuRef.current
191
+ if (box === null) return
192
+ const active = document.activeElement
193
+ // Never pull focus away from a control the user already reached.
194
+ if (active !== box && box.contains(active)) return
195
+ firstItemFocused.current = true
196
+ box.querySelector<HTMLElement>('.rvs-crumb-menu-item')?.focus()
197
+ }, [menu, loading, error, entries])
198
+
199
+ // Esc is a dismissal, so it gives the keyboard back to the crumb that opened
200
+ // the menu instead of dropping focus on <body>. An outside click keeps focus
201
+ // where the user clicked, and picking an entry moves it on by itself.
202
+ useEffect(() => {
203
+ if (menu !== undefined || !restoreFocus.current) return
204
+ restoreFocus.current = false
205
+ const opener = openerRef.current
206
+ if (opener !== null && document.body.contains(opener)) opener.focus()
207
+ }, [menu])
208
+
209
+ if (!underRoot) {
210
+ return (
211
+ <nav className="rvs-breadcrumb" aria-label={tr(t, 'editor.crumbLabel', '文件路径')}>
212
+ <span className="rvs-einfo-path" title={props.path}>{props.path}</span>
213
+ </nav>
214
+ )
215
+ }
216
+
217
+ /** Click a segment: a directory lists itself; the file lists its parent. */
218
+ const clickCrumb = (crumb: Crumb, index: number, event: ReactMouseEvent<HTMLButtonElement>): void => {
219
+ openerRef.current = event.currentTarget
220
+ const isFile = index === crumbs.length - 1
221
+ const dir = isFile ? crumb.path.slice(0, Math.max(0, crumb.path.lastIndexOf('/'))) : crumb.path
222
+ openMenu(dir === '' ? '/' : dir, Math.max(0, event.currentTarget.offsetLeft))
223
+ }
224
+
225
+ const parentDirOf = (dir: string): string | undefined => {
226
+ if (dir === '' || dir === root || dir === '/') return undefined
227
+ const parts = pathSegments(dir)
228
+ parts.pop()
229
+ return parts.length === 0 ? undefined : `/${parts.join('/')}`
230
+ }
231
+
232
+ /** The enabled entries of the open menu, in DOM order. */
233
+ const menuItems = (): HTMLElement[] => {
234
+ const box = menuRef.current
235
+ if (box === null) return []
236
+ return Array.from(box.querySelectorAll<HTMLElement>('.rvs-crumb-menu-item'))
237
+ }
238
+
239
+ /** ↑/↓/Home/End between entries (Enter/Space is the button's own activation). */
240
+ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>): void => {
241
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp' && event.key !== 'Home' && event.key !== 'End') return
242
+ const items = menuItems()
243
+ if (items.length === 0) return
244
+ event.preventDefault()
245
+ const at = items.indexOf(document.activeElement as HTMLElement)
246
+ const next = event.key === 'Home'
247
+ ? 0
248
+ : event.key === 'End'
249
+ ? items.length - 1
250
+ : event.key === 'ArrowDown'
251
+ ? (at + 1) % items.length
252
+ : (at <= 0 ? items.length - 1 : at - 1)
253
+ items[next]?.focus()
254
+ }
255
+
256
+ return (
257
+ <nav className="rvs-breadcrumb" ref={navRef} aria-label={tr(t, 'editor.crumbLabel', '文件路径')}>
258
+ {crumbs.map((crumb, index) => {
259
+ const isFile = index === crumbs.length - 1
260
+ return (
261
+ <span className="rvs-crumb-wrap" key={`${crumb.path}:${index}`}>
262
+ {index > 0 && <span className="rvs-crumb-sep" aria-hidden="true">›</span>}
263
+ <button
264
+ type="button"
265
+ className={`rvs-crumb${isFile ? ' rvs-crumb-file' : ''}`}
266
+ // The last segment is the FILE (its menu lists siblings); a
267
+ // directory segment lists ITSELF, so the hint must not promise
268
+ // sibling files there.
269
+ title={isFile ? props.path : crumb.path}
270
+ aria-haspopup="menu"
271
+ onClick={event => clickCrumb(crumb, index, event)}
272
+ >
273
+ {crumb.label}
274
+ </button>
275
+ </span>
276
+ )
277
+ })}
278
+
279
+ {menu !== undefined && (
280
+ <div
281
+ ref={menuRef}
282
+ className="rvs-crumb-menu"
283
+ role="menu"
284
+ // A non-modal picker: Ctrl+S stays live while it is open (the editor is
285
+ // still the surface in use). `isModalLayerOpen()` reads this marker.
286
+ data-rvs-nonmodal=""
287
+ tabIndex={-1}
288
+ onKeyDown={onMenuKeyDown}
289
+ style={{ left: menu.left }}
290
+ >
291
+ <div className="rvs-crumb-menu-head">
292
+ <button
293
+ type="button"
294
+ className="rvs-crumb-menu-up"
295
+ title={tr(t, 'editor.crumbUp', '上一级')}
296
+ disabled={parentDirOf(menu.dir) === undefined}
297
+ onClick={() => {
298
+ const parent = parentDirOf(menu.dir)
299
+ if (parent === undefined) return
300
+ openMenu(parent, menu.left)
301
+ }}
302
+ >
303
+ ↑
304
+ </button>
305
+ <span className="rvs-crumb-menu-path" title={menu.dir}>{menu.dir}</span>
306
+ </div>
307
+ <div className="rvs-crumb-menu-list">
308
+ {loading && <div className="rvs-crumb-menu-note">{tr(t, 'common.loading', '加载中…')}</div>}
309
+ {!loading && error !== undefined && <div className="rvs-crumb-menu-note rvs-status-error">{error}</div>}
310
+ {!loading && error === undefined && entries.length === 0 && (
311
+ <div className="rvs-crumb-menu-note">{tr(t, 'editor.crumbEmpty', '空目录')}</div>
312
+ )}
313
+ {!loading && error === undefined && entries.map(entry => (
314
+ <button
315
+ key={entry.path}
316
+ type="button"
317
+ role="menuitem"
318
+ className={`rvs-crumb-menu-item${entry.isDir ? ' rvs-dir' : ''}`}
319
+ title={entry.path}
320
+ onClick={() => {
321
+ if (entry.isDir) {
322
+ openMenu(entry.path, menu.left)
323
+ return
324
+ }
325
+ // Stay on the surface this breadcrumb belongs to: no sidebar jump.
326
+ props.onOpen(entry.path)
327
+ setMenu(undefined)
328
+ }}
329
+ >
330
+ <span className="rvs-crumb-menu-glyph" aria-hidden="true">{entry.isDir ? '▸' : '·'}</span>
331
+ <span className="rvs-crumb-menu-name">{entry.name}</span>
332
+ </button>
333
+ ))}
334
+ </div>
335
+ </div>
336
+ )}
337
+ </nav>
338
+ )
339
+ }