dsh-remote-vs 0.26.0 → 0.28.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 (75) hide show
  1. package/README.en.md +112 -28
  2. package/README.md +84 -25
  3. package/THIRD-PARTY-NOTICES.md +7 -2
  4. package/lib/client.js +1237 -254
  5. package/lib/index.js +821 -17
  6. package/lib/types/changes/recorder.d.ts +119 -2
  7. package/lib/types/client/CodeEditor.d.ts +29 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/api.d.ts +22 -2
  11. package/lib/types/client/blame-model.d.ts +77 -0
  12. package/lib/types/client/changes/apply-failure.d.ts +41 -0
  13. package/lib/types/client/changes/block-confirm.d.ts +97 -0
  14. package/lib/types/client/changes/diff-outcome.d.ts +56 -0
  15. package/lib/types/client/changes/freshness.d.ts +51 -0
  16. package/lib/types/client/changes/model.d.ts +19 -1
  17. package/lib/types/client/changes/session-diff.d.ts +100 -0
  18. package/lib/types/client/changes/staleness.d.ts +98 -0
  19. package/lib/types/client/changes/turn-reverted.d.ts +82 -0
  20. package/lib/types/client/changes/turn-view.d.ts +131 -0
  21. package/lib/types/client/changes/undo-affordance.d.ts +44 -10
  22. package/lib/types/client/changes/undo-target.d.ts +12 -0
  23. package/lib/types/client/i18n.d.ts +1 -1
  24. package/lib/types/client/outline-model.d.ts +59 -0
  25. package/lib/types/client/scm/actions.d.ts +12 -1
  26. package/lib/types/client/store.d.ts +109 -1
  27. package/lib/types/client/vsc/blame.d.ts +19 -0
  28. package/lib/types/client/vsc/change-marks.d.ts +21 -0
  29. package/lib/types/client/vsc/kit.d.ts +0 -2
  30. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  31. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  32. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/processes.d.ts +43 -0
  35. package/lib/types/protocol.d.ts +133 -1
  36. package/package.json +2 -1
  37. package/src/changes/recorder.ts +851 -8
  38. package/src/client/CodeEditor.tsx +86 -4
  39. package/src/client/EditorPane.tsx +581 -41
  40. package/src/client/MonitorView.tsx +16 -5
  41. package/src/client/OutlinePanel.tsx +287 -0
  42. package/src/client/ProcessesSection.tsx +292 -0
  43. package/src/client/api.ts +38 -3
  44. package/src/client/blame-model.ts +242 -0
  45. package/src/client/changes/ChangesDock.tsx +539 -54
  46. package/src/client/changes/apply-failure.ts +73 -0
  47. package/src/client/changes/block-confirm.ts +180 -0
  48. package/src/client/changes/changes.css +45 -0
  49. package/src/client/changes/diff-outcome.ts +97 -0
  50. package/src/client/changes/freshness.ts +68 -0
  51. package/src/client/changes/model.ts +56 -1
  52. package/src/client/changes/session-diff.ts +187 -0
  53. package/src/client/changes/staleness.ts +148 -0
  54. package/src/client/changes/turn-reverted.ts +254 -0
  55. package/src/client/changes/turn-view.ts +195 -0
  56. package/src/client/changes/undo-affordance.ts +295 -63
  57. package/src/client/changes/undo-target.ts +12 -0
  58. package/src/client/i18n.ts +294 -2
  59. package/src/client/index.tsx +4 -0
  60. package/src/client/outline-model.ts +775 -0
  61. package/src/client/scm/DiffView.tsx +32 -13
  62. package/src/client/scm/HistoryPanel.tsx +38 -1
  63. package/src/client/scm/actions.ts +55 -2
  64. package/src/client/store.tsx +446 -21
  65. package/src/client/vsc/blame.ts +147 -0
  66. package/src/client/vsc/change-marks.ts +21 -0
  67. package/src/client/vsc/kit.tsx +3 -11
  68. package/src/client/vsc/preview-document.tsx +326 -0
  69. package/src/client/vsc/preview-model.ts +216 -0
  70. package/src/client/vsc/preview-services.ts +118 -0
  71. package/src/client/vsc/vsc.css +965 -39
  72. package/src/git-ops.ts +34 -0
  73. package/src/processes.ts +177 -0
  74. package/src/protocol.ts +138 -1
  75. package/src/routes.ts +138 -9
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Inline blame gutter for the CodeMirror editor.
3
+ *
4
+ * The data is fetched by the editor pane (one `-L` window at a time) and handed
5
+ * in as a line→commit map; this module only paints it. Keeping the fetch out of
6
+ * here is deliberate: the same model is used by the gate without CodeMirror,
7
+ * and a scroll must not be able to start a request from inside a gutter
8
+ * callback.
9
+ */
10
+ import {
11
+ RangeSetBuilder,
12
+ type Extension,
13
+ type RangeSet,
14
+ } from '@codemirror/state'
15
+ import {
16
+ EditorView,
17
+ GutterMarker,
18
+ ViewPlugin,
19
+ gutter,
20
+ type ViewUpdate,
21
+ } from '@codemirror/view'
22
+ import { blameLabel, blameRuns, blameTitle, isCommittedBlame, type BlameLine } from '../blame-model.ts'
23
+
24
+ /** One gutter cell's label; `null` text means "same commit as the line above". */
25
+ class BlameMarker extends GutterMarker {
26
+ constructor(
27
+ private readonly text: string,
28
+ private readonly title: string,
29
+ private readonly committed: boolean,
30
+ ) {
31
+ super()
32
+ }
33
+
34
+ override toDOM(): HTMLElement {
35
+ const node = document.createElement('span')
36
+ node.className = this.text === ''
37
+ ? 'rvs-blame-cont'
38
+ : `rvs-blame-chip${this.committed ? '' : ' rvs-blame-uncommitted'}`
39
+ node.textContent = this.text
40
+ if (this.title !== '') node.title = this.title
41
+ return node
42
+ }
43
+
44
+ override eq(other: GutterMarker): boolean {
45
+ return other instanceof BlameMarker && other.text === this.text && other.title === this.title
46
+ }
47
+ }
48
+
49
+ const EMPTY = new RangeSetBuilder<GutterMarker>().finish()
50
+
51
+ /** Fixed spacer: keeps the gutter from jumping between files. */
52
+ class SpacerMarker extends GutterMarker {
53
+ override toDOM(): HTMLElement {
54
+ const node = document.createElement('span')
55
+ node.className = 'rvs-blame-spacer'
56
+ node.textContent = 'author · 00y'
57
+ return node
58
+ }
59
+ }
60
+
61
+ const SPACER = new SpacerMarker()
62
+
63
+ /** Viewport-only markers; the gutter itself only renders visible lines. */
64
+ function viewportMarkers(
65
+ view: EditorView,
66
+ entries: ReadonlyMap<number, BlameLine>,
67
+ nowSeconds: number,
68
+ ): RangeSet<GutterMarker> {
69
+ const doc = view.state.doc
70
+ const first = Math.max(1, doc.lineAt(view.viewport.from).number)
71
+ const last = Math.min(doc.lines, doc.lineAt(view.viewport.to).number)
72
+ if (entries.size === 0 || last < first) return EMPTY
73
+ const runStarts = new Set(
74
+ blameRuns([...entries.values()].sort((left, right) => left.line - right.line)).map(run => run.from),
75
+ )
76
+ const builder = new RangeSetBuilder<GutterMarker>()
77
+ for (let number = first; number <= last; number += 1) {
78
+ const entry = entries.get(number)
79
+ if (entry === undefined) continue
80
+ const sameAsAbove = !runStarts.has(number)
81
+ const marker = sameAsAbove
82
+ ? new BlameMarker('', '', true)
83
+ : new BlameMarker(blameLabel(entry, nowSeconds), blameTitle(entry), isCommittedBlame(entry.hash))
84
+ const line = doc.line(number)
85
+ builder.add(line.from, line.to, marker)
86
+ }
87
+ return builder.finish()
88
+ }
89
+
90
+ /** Fire `report` when the viewport (or the document) changes. */
91
+ function viewportReporter(report: (first: number, last: number) => void): Extension {
92
+ const emit = (view: EditorView): void => {
93
+ const doc = view.state.doc
94
+ report(doc.lineAt(view.viewport.from).number, doc.lineAt(view.viewport.to).number)
95
+ }
96
+ return ViewPlugin.fromClass(class {
97
+ constructor(view: EditorView) {
98
+ // A freshly mounted editor gets no update event: report the first
99
+ // viewport here, or the pane would never fetch any blame until scroll.
100
+ emit(view)
101
+ }
102
+
103
+ update(update: ViewUpdate): void {
104
+ if (!update.viewportChanged && !update.docChanged) return
105
+ emit(update.view)
106
+ }
107
+ })
108
+ }
109
+
110
+ /**
111
+ * Build the gutter extension. Rebuilt by the editor's compartment whenever a
112
+ * blame window lands; `nowSeconds` is pinned so every cell in one render has
113
+ * the same clock.
114
+ */
115
+ export function blameExtension(
116
+ entries: ReadonlyMap<number, BlameLine>,
117
+ onOpen?: (entry: BlameLine) => void,
118
+ ): Extension {
119
+ const nowSeconds = Math.floor(Date.now() / 1000)
120
+ const activate = (view: EditorView, line: { from: number }, event: Event): boolean => {
121
+ const number = view.state.doc.lineAt(line.from).number
122
+ const entry = entries.get(number)
123
+ if (entry === undefined || !isCommittedBlame(entry.hash)) return false
124
+ event.preventDefault()
125
+ onOpen?.(entry)
126
+ return true
127
+ }
128
+ return [
129
+ gutter({
130
+ class: 'rvs-blame-gutter',
131
+ markers: view => viewportMarkers(view, entries, nowSeconds),
132
+ initialSpacer: () => SPACER,
133
+ domEventHandlers: onOpen === undefined
134
+ ? {}
135
+ : {
136
+ mousedown(view, line, event) {
137
+ return activate(view, line, event)
138
+ },
139
+ },
140
+ }),
141
+ ]
142
+ }
143
+
144
+ /** Internal export for the editor to forward viewport changes. */
145
+ export function blameViewportReporter(report: (first: number, last: number) => void): Extension {
146
+ return viewportReporter(report)
147
+ }
@@ -143,6 +143,27 @@ export interface ChangeSet {
143
143
  * (新建 / 二进制 / 字节被上限扣下)。
144
144
  */
145
145
  filePatch?: string
146
+ /**
147
+ * 这批 hunk 对应的增删行数(`--numstat` 语义:`+` / `-` 行的条数)。
148
+ *
149
+ * 面板每 3 秒重新统计一次,而屏幕上这批标记只会在这几行真的变了之后才作废;
150
+ * 把"这批标记当初代表多少行"记在数据里,才能拿它和新的统计行比对(见
151
+ * `changes/staleness.ts`)。省略 = 无可比数字:二进制 / 过大的行不做行级比较、
152
+ * 被字节上限扣下的 diff 也不会走到建标记这一步(`changes/diff-outcome.ts`),
153
+ * 所以它们都没有这两个字段,而不是"带一个前缀数字"。
154
+ */
155
+ added?: number
156
+ deleted?: number
157
+ /** 建立这批标记时列表行给出的状态(A/M/D/R/…);省略 = 未知,不参与比对。 */
158
+ status?: string
159
+ /**
160
+ * 每个 hunk 的一枚稳定块标识(与 `patches` 同序,见 `changes/block-confirm.ts`)。
161
+ *
162
+ * 编辑器里的「确认保留」是**块级**本地记账,块必须有一个跨刷新稳定的名字;
163
+ * 行号会随远端变化,hunk 头里的四个数字 + 文件的远端绝对路径才代表"同一处改动"。
164
+ * 省略 = 调用方没有给出文件路径,编辑器的块笔记不启用。
165
+ */
166
+ blocks?: string[]
146
167
  }
147
168
 
148
169
  /** 换一份改动标记;`null` = 清空(有改动数据,但没有任何要画的东西)。 */
@@ -30,6 +30,7 @@ import {
30
30
  type CSSProperties,
31
31
  type ReactNode,
32
32
  } from 'react'
33
+ import { isBytePreview, previewKindOf } from './preview-model.ts'
33
34
  import { createPortal } from 'react-dom'
34
35
  import { detectLang, makeT } from '../i18n.ts'
35
36
  import { FileTypeIcon, FolderGlyph } from './file-icons.tsx'
@@ -405,23 +406,14 @@ export function isImageFile(path: string): boolean {
405
406
  return IMAGE_EXTS.has(extOf(path))
406
407
  }
407
408
 
408
- export function isMarkdownFile(path: string): boolean {
409
- const ext = extOf(path)
410
- return ext === 'md' || ext === 'markdown'
411
- }
412
-
413
- export function isHtmlFile(path: string): boolean {
414
- const ext = extOf(path)
415
- return ext === 'html' || ext === 'htm'
416
- }
417
-
418
409
  export function mimeFor(path: string): string {
419
410
  return MIME[extOf(path)] ?? 'application/octet-stream'
420
411
  }
421
412
 
422
413
  /** True for a file that always opens as a preview, never as a diff. */
423
414
  export function isPreviewOnlyFile(path: string): boolean {
424
- return isImageFile(path) || extOf(path) === 'pdf'
415
+ const kind = previewKindOf(path)
416
+ return kind === 'image' || isBytePreview(kind)
425
417
  }
426
418
 
427
419
  /**
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Document previews for remote files.
3
+ *
4
+ * Text sources (Markdown/HTML/SVG/CSV) are rendered from the editor buffer. PDF,
5
+ * audio/video and Office bytes never pass through `fs.read` (it is a UTF-8 API
6
+ * with a 4 MiB cap): they are streamed from the existing `/download` route into
7
+ * a blob URL, and Office is first converted to PDF by a LibreOffice already
8
+ * present on the REMOTE host. When that engine is missing the notice says so;
9
+ * the plugin never claims a corrupt file.
10
+ */
11
+ import { useEffect, useMemo, useState, type ReactNode } from 'react'
12
+ import { api, RemoteApiError } from '../api.ts'
13
+ import { downloadUrl } from '../download.ts'
14
+ import { shQuote } from '../../git-format.ts'
15
+ import { DEFAULT_TABLE_LIMITS, extensionOf, mediaTypeOf, parseDelimited, tableDelimiterOf } from './preview-model.ts'
16
+ import { readWorkspaceBytes, renderOfficePdf, type PreviewFailureReason } from './preview-services.ts'
17
+
18
+ /** Never assemble a larger preview body than this in the tab. */
19
+ export const MAX_PREVIEW_BYTES = 64 * 1024 * 1024
20
+
21
+ type PreviewError = { kind: PreviewFailureReason; message: string }
22
+
23
+ export function officeExtensionOf(path: string): string | undefined {
24
+ const ext = extensionOf(path)
25
+ return ext === 'doc' || ext === 'docx' || ext === 'ppt' || ext === 'pptx' || ext === 'xls' || ext === 'xlsx'
26
+ ? ext
27
+ : undefined
28
+ }
29
+
30
+ /**
31
+ * Convert one remote Office document to PDF on the remote host.
32
+ *
33
+ * Paths and the extension are quoted/validated here; the only value that ends
34
+ * up in the shell is the remote path. A missing engine is reported as
35
+ * `@@RVS_NO_SOFFICE` (notice), not as a corrupt document.
36
+ */
37
+ export function officeConvertCommand(path: string): string {
38
+ const ext = officeExtensionOf(path)
39
+ if (ext === undefined) throw new Error('unsupported office extension')
40
+ const input = `input.${ext}`
41
+ return [
42
+ "tmp=$(mktemp -d) || { echo '@@RVS_FAIL mktemp'; exit 2; }",
43
+ `cp ${shQuote(path)} "$tmp/${input}" || { rm -rf "$tmp"; echo '@@RVS_FAIL copy'; exit 3; }`,
44
+ 'if command -v soffice >/dev/null 2>&1; then bin=soffice;',
45
+ 'elif command -v libreoffice >/dev/null 2>&1; then bin=libreoffice;',
46
+ 'else rm -rf "$tmp"; echo "@@RVS_NO_SOFFICE"; exit 4; fi',
47
+ "cd \"$tmp\" || { rm -rf \"$tmp\"; echo '@@RVS_FAIL cd'; exit 5; }",
48
+ `"$bin" --headless --convert-to pdf --outdir "$tmp" "$tmp/${input}" >/dev/null 2>&1`,
49
+ 'if [ ! -f "$tmp/input.pdf" ]; then rm -rf "$tmp"; echo "@@RVS_FAIL convert"; exit 6; fi',
50
+ 'echo "@@RVS_PDF $tmp"',
51
+ ].join('\n')
52
+ }
53
+
54
+ function errorMessage(error: unknown): string {
55
+ return error instanceof RemoteApiError ? error.message : error instanceof Error ? error.message : String(error)
56
+ }
57
+
58
+ /** Fetch one remote file body through the streaming download route. */
59
+ export async function fetchRemoteBytes(alias: string, path: string, signal?: AbortSignal): Promise<Uint8Array> {
60
+ const response = await fetch(downloadUrl(alias, path), { signal })
61
+ if (!response.ok) {
62
+ const text = await response.text().catch(() => '')
63
+ let message = `download failed: HTTP ${response.status}`
64
+ try {
65
+ const body = JSON.parse(text) as { error?: unknown }
66
+ if (typeof body.error === 'string') message = body.error
67
+ } catch {
68
+ // Not JSON: keep the status message.
69
+ }
70
+ throw new Error(message)
71
+ }
72
+ const declared = Number(response.headers.get('content-length') ?? '0')
73
+ if (Number.isFinite(declared) && declared > MAX_PREVIEW_BYTES) {
74
+ throw Object.assign(new Error(`file is larger than ${MAX_PREVIEW_BYTES} bytes`), { previewKind: 'too-large' })
75
+ }
76
+ const bytes = new Uint8Array(await response.arrayBuffer())
77
+ if (bytes.byteLength > MAX_PREVIEW_BYTES) {
78
+ throw Object.assign(new Error(`file is larger than ${MAX_PREVIEW_BYTES} bytes`), { previewKind: 'too-large' })
79
+ }
80
+ return bytes
81
+ }
82
+
83
+ async function fetchOfficePdf(alias: string, path: string, signal?: AbortSignal): Promise<Uint8Array> {
84
+ if (officeExtensionOf(path) === undefined) throw new Error('unsupported office document')
85
+ const result = await api.exec(alias, officeConvertCommand(path), 60_000, { signal })
86
+ if (result.error !== undefined) throw new Error(result.error)
87
+ if (result.timedOut) throw new Error('remote LibreOffice conversion timed out')
88
+ const line = result.stdout.split('\n').map(item => item.trim()).find(item => item.startsWith('@@RVS_PDF '))
89
+ if (line === undefined) {
90
+ if (result.stdout.includes('@@RVS_NO_SOFFICE')) {
91
+ throw Object.assign(
92
+ new Error('LibreOffice is not installed on the remote host. Install the host kit with: npm install @deepseek-ai/libreoffice-kit@latest'),
93
+ { previewKind: 'unavailable' },
94
+ )
95
+ }
96
+ throw new Error(result.stderr.trim() || 'remote LibreOffice conversion failed')
97
+ }
98
+ const tempDir = line.slice('@@RVS_PDF '.length).trim()
99
+ try {
100
+ return await fetchRemoteBytes(alias, `${tempDir}/input.pdf`, signal)
101
+ } finally {
102
+ // Best-effort cleanup; a failed rm must not turn a rendered document into
103
+ // an error, but it also must never be skipped silently in this function.
104
+ void api.exec(alias, `rm -rf ${shQuote(tempDir)}`, 15_000).catch(() => undefined)
105
+ }
106
+ }
107
+
108
+ function sizeText(bytes: number): string {
109
+ if (!Number.isFinite(bytes) || bytes < 0) return ''
110
+ if (bytes < 1024) return `${bytes} B`
111
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
112
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`
113
+ }
114
+
115
+ function PreviewNotice(props: {
116
+ path: string
117
+ title: string
118
+ hint: string
119
+ detail?: string
120
+ t: (key: string) => string
121
+ onRetry?: () => void
122
+ }): ReactNode {
123
+ return (
124
+ <div className="rvs-preview-notice" role="alert">
125
+ <div className="rvs-preview-notice-title">{props.title}</div>
126
+ <div className="rvs-preview-notice-path">{props.path}</div>
127
+ <div className="rvs-preview-notice-hint">{props.hint}</div>
128
+ {props.detail !== undefined && <div className="rvs-preview-notice-detail">{props.detail}</div>}
129
+ {props.onRetry !== undefined && (
130
+ <button type="button" className="rvs-preview-retry" onClick={props.onRetry}>{props.t('common.retry')}</button>
131
+ )}
132
+ </div>
133
+ )
134
+ }
135
+
136
+ export function BytePreview(props: {
137
+ alias: string
138
+ path: string
139
+ /** DSH session; lets the host workspaceFiles/officeKit remotes resolve the
140
+ * same remote workspace before the plugin's own download fallback. */
141
+ sessionId?: string
142
+ kind: 'pdf' | 'office' | 'media'
143
+ revision: number
144
+ t: (key: string) => string
145
+ }): ReactNode {
146
+ const [state, setState] = useState<{ status: 'loading' } | { status: 'ready'; url: string; size: number } | { status: 'failed'; error: PreviewError }>({ status: 'loading' })
147
+ const [elementFailed, setElementFailed] = useState(false)
148
+ const [attempt, setAttempt] = useState(0)
149
+
150
+ useEffect(() => { setElementFailed(false) }, [props.path, props.kind])
151
+
152
+ useEffect(() => {
153
+ const controller = new AbortController()
154
+ let alive = true
155
+ let url: string | undefined
156
+ let hostReason: PreviewFailureReason = 'failed'
157
+ setState({ status: 'loading' })
158
+ const download = props.kind === 'office'
159
+ ? () => fetchOfficePdf(props.alias, props.path, controller.signal)
160
+ : () => fetchRemoteBytes(props.alias, props.path, controller.signal)
161
+ const hostRead = props.kind === 'office'
162
+ ? renderOfficePdf(props.sessionId ?? '', props.path, controller.signal)
163
+ : readWorkspaceBytes(props.sessionId ?? '', props.path, controller.signal)
164
+ void hostRead.then((host) => {
165
+ if (host.ok) return host.data
166
+ hostReason = host.reason
167
+ // A missing service or a path the host cannot resolve is exactly why the
168
+ // plugin keeps its own /download path; only the fallback can succeed.
169
+ return download()
170
+ }).then((bytes) => {
171
+ if (!alive) return
172
+ const mime = props.kind === 'media'
173
+ ? mediaTypeOf(props.path)?.mime ?? 'application/octet-stream'
174
+ : 'application/pdf'
175
+ url = URL.createObjectURL(new Blob([bytes], { type: mime }))
176
+ setState({ status: 'ready', url, size: bytes.byteLength })
177
+ }).catch((error: unknown) => {
178
+ if (!alive) return
179
+ const reason = typeof error === 'object' && error !== null && 'previewKind' in error
180
+ ? (error as { previewKind: PreviewError['kind'] }).previewKind
181
+ : hostReason
182
+ setState({ status: 'failed', error: { kind: reason, message: errorMessage(error) } })
183
+ })
184
+ return () => {
185
+ alive = false
186
+ controller.abort()
187
+ if (url !== undefined) URL.revokeObjectURL(url)
188
+ }
189
+ }, [props.alias, props.path, props.kind, props.revision, attempt, props.sessionId])
190
+
191
+ if (state.status === 'loading') {
192
+ return (
193
+ <div className="rvs-preview-loading" role="status">
194
+ <span className="rvs-preview-spinner" aria-hidden="true" />
195
+ <span>{props.kind === 'office' ? props.t('preview.converting') : props.t('common.loading')}</span>
196
+ {props.kind === 'office' && <span className="rvs-preview-loading-hint">{props.t('preview.convertingHint')}</span>}
197
+ </div>
198
+ )
199
+ }
200
+ if (state.status === 'failed') {
201
+ const title = state.error.kind === 'too-large'
202
+ ? props.t('preview.tooLargeTitle')
203
+ : state.error.kind === 'unavailable'
204
+ ? props.t(props.kind === 'office' ? 'preview.officeUnavailableTitle' : 'preview.unavailableTitle')
205
+ : state.error.kind === 'not-found'
206
+ ? props.t('preview.notFoundTitle')
207
+ : state.error.kind === 'remote'
208
+ ? props.t('preview.remoteTitle')
209
+ : props.t('preview.failedTitle')
210
+ const hint = state.error.kind === 'too-large'
211
+ ? props.t('preview.tooLargeHint')
212
+ : state.error.kind === 'unavailable'
213
+ ? props.t(props.kind === 'office' ? 'preview.officeUnavailableHint' : 'preview.unavailableHint')
214
+ : state.error.kind === 'not-found'
215
+ ? props.t('preview.notFoundHint')
216
+ : state.error.kind === 'remote'
217
+ ? props.t('preview.remoteHint')
218
+ : props.t('preview.failedHint')
219
+ return <PreviewNotice path={props.path} title={title} hint={hint} detail={state.error.message} t={props.t} onRetry={() => { setAttempt(value => value + 1) }} />
220
+ }
221
+ if (props.kind === 'media') {
222
+ const media = mediaTypeOf(props.path)
223
+ if (elementFailed) {
224
+ return <PreviewNotice path={props.path} title={props.t('preview.failedTitle')} hint={props.t('preview.mediaUnsupported')} t={props.t} onRetry={() => { setElementFailed(false); setAttempt(value => value + 1) }} />
225
+ }
226
+ return (
227
+ <div className={`rvs-preview-media${media?.kind === 'video' ? ' rvs-preview-media-video' : ''}`}>
228
+ {media?.kind === 'video'
229
+ ? <video className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />
230
+ : <audio className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />}
231
+ <div className="rvs-preview-media-meta">
232
+ {sizeText(state.size)}
233
+ <span className="rvs-preview-media-hint">{props.path}</span>
234
+ </div>
235
+ </div>
236
+ )
237
+ }
238
+ return (
239
+ <div className="rvs-preview-document">
240
+ <iframe className="rvs-preview-document-frame" src={state.url} title={props.path} />
241
+ <div className="rvs-preview-document-meta">
242
+ {sizeText(state.size)}
243
+ <span className="rvs-preview-document-hint">{props.t('preview.documentHint')}</span>
244
+ </div>
245
+ </div>
246
+ )
247
+ }
248
+
249
+ export function SvgPreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
250
+ const [url, setUrl] = useState<string | undefined>(undefined)
251
+ const [failed, setFailed] = useState(false)
252
+ useEffect(() => {
253
+ const next = URL.createObjectURL(new Blob([props.text], { type: 'image/svg+xml' }))
254
+ setUrl(next)
255
+ return () => { URL.revokeObjectURL(next) }
256
+ }, [props.text])
257
+ useEffect(() => { setFailed(false) }, [url])
258
+ if (failed) {
259
+ return <PreviewNotice path={props.path} title={props.t('preview.svgFailed')} hint={props.t('preview.svgFailedHint')} t={props.t} />
260
+ }
261
+ if (url === undefined) return null
262
+ return (
263
+ <div className="rvs-preview-svg">
264
+ <img className="rvs-preview-svg-img" src={url} alt={props.path} onError={() => { setFailed(true) }} />
265
+ <div className="rvs-preview-svg-hint">{props.truncated ? props.t('preview.truncated') : props.t('preview.svgHint')}</div>
266
+ </div>
267
+ )
268
+ }
269
+
270
+ /** DOM ceilings (parsing itself allows more; the rest gets a banner). */
271
+ const RENDER_ROWS = 400
272
+ const RENDER_COLUMNS = 48
273
+
274
+ function padRow(row: readonly string[], columns: number): string[] {
275
+ const cells = row.slice(0, columns)
276
+ while (cells.length < columns) cells.push('')
277
+ return cells
278
+ }
279
+
280
+ export function TablePreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
281
+ const parsed = useMemo(
282
+ () => parseDelimited(props.text, tableDelimiterOf(props.path)),
283
+ [props.text, props.path],
284
+ )
285
+ const columns = Math.min(parsed.columns, RENDER_COLUMNS)
286
+ const rows = parsed.rows.slice(0, RENDER_ROWS)
287
+ const header = rows[0]
288
+ const body = rows.slice(1)
289
+ const hiddenRows = parsed.rows.length - rows.length
290
+ const hiddenColumns = parsed.columns - columns
291
+ const notes: string[] = []
292
+ if (props.truncated) notes.push(props.t('preview.truncated'))
293
+ if (parsed.truncated) {
294
+ notes.push(props.t('preview.tableTruncated')
295
+ .replace('{rows}', String(DEFAULT_TABLE_LIMITS.maxRows))
296
+ .replace('{cells}', String(DEFAULT_TABLE_LIMITS.maxCells)))
297
+ }
298
+ if (hiddenRows > 0) notes.push(props.t('preview.tableHiddenRows').replace('{shown}', String(rows.length)).replace('{rest}', String(hiddenRows)))
299
+ if (hiddenColumns > 0) notes.push(props.t('preview.tableHiddenColumns').replace('{shown}', String(columns)).replace('{rest}', String(hiddenColumns)))
300
+ if (parsed.rows.length === 0) {
301
+ return <PreviewNotice path={props.path} title={props.t('preview.tableEmptyTitle')} hint={props.t('preview.tableEmptyHint')} t={props.t} />
302
+ }
303
+ return (
304
+ <div className="rvs-preview-table-wrap">
305
+ {notes.map((note, index) => <div className="rvs-preview-banner" key={`${String(index)}:${note}`}>{note}</div>)}
306
+ <div className="rvs-preview-table-scroll">
307
+ <table className="rvs-preview-table">
308
+ <thead>
309
+ <tr>
310
+ <th className="rvs-preview-rownum" scope="col">#</th>
311
+ {padRow(header ?? [], columns).map((cell, index) => <th key={index} scope="col">{cell}</th>)}
312
+ </tr>
313
+ </thead>
314
+ <tbody>
315
+ {body.map((row, rowIndex) => (
316
+ <tr key={rowIndex}>
317
+ <th className="rvs-preview-rownum" scope="row">{rowIndex + 2}</th>
318
+ {padRow(row, columns).map((cell, cellIndex) => <td key={cellIndex} title={cell}>{cell}</td>)}
319
+ </tr>
320
+ ))}
321
+ </tbody>
322
+ </table>
323
+ </div>
324
+ </div>
325
+ )
326
+ }