dsh-remote-vs 0.25.0 → 0.27.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 (109) hide show
  1. package/README.en.md +12 -15
  2. package/README.md +11 -12
  3. package/THIRD-PARTY-NOTICES.md +193 -0
  4. package/lib/client.js +7313 -79961
  5. package/lib/index.js +1529 -964
  6. package/lib/p2-router-fs.js +1 -1
  7. package/lib/types/client/CodeEditor.d.ts +22 -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/RemoteExplorer.d.ts +53 -0
  11. package/lib/types/client/api.d.ts +42 -3
  12. package/lib/types/client/blame-model.d.ts +77 -0
  13. package/lib/types/client/changes/review-state.d.ts +19 -0
  14. package/lib/types/client/connection.d.ts +16 -0
  15. package/lib/types/client/i18n.d.ts +1 -1
  16. package/lib/types/client/outline-model.d.ts +59 -0
  17. package/lib/types/client/request-gate.d.ts +110 -0
  18. package/lib/types/client/scm/DiffView.d.ts +45 -7
  19. package/lib/types/client/scm/actions.d.ts +43 -4
  20. package/lib/types/client/store.d.ts +71 -0
  21. package/lib/types/client/vsc/FindWidget.d.ts +6 -0
  22. package/lib/types/client/vsc/blame.d.ts +19 -0
  23. package/lib/types/client/vsc/change-marks.d.ts +16 -6
  24. package/lib/types/client/vsc/editor-keymap.d.ts +35 -1
  25. package/lib/types/client/vsc/kit.d.ts +11 -2
  26. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  27. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  28. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  29. package/lib/types/client/vsc/save-shortcut.d.ts +21 -0
  30. package/lib/types/client/vsc/terminal-theme.d.ts +28 -2
  31. package/lib/types/forward.d.ts +12 -0
  32. package/lib/types/fs-ops.d.ts +42 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/http.d.ts +2 -0
  35. package/lib/types/keygen.d.ts +9 -0
  36. package/lib/types/monitor.d.ts +8 -0
  37. package/lib/types/notices.d.ts +16 -1
  38. package/lib/types/p2/helper-rpc.d.ts +45 -0
  39. package/lib/types/processes.d.ts +43 -0
  40. package/lib/types/protocol.d.ts +34 -0
  41. package/lib/types/routes.d.ts +2 -0
  42. package/lib/types/store.d.ts +7 -0
  43. package/lib/types/terminal.d.ts +8 -0
  44. package/lib/types/view-settings.d.ts +5 -0
  45. package/lib/{worlds-B7gEDBzC.js → worlds-RG8K5eom.js} +113 -15
  46. package/package.json +3 -1
  47. package/src/client/CodeEditor.tsx +194 -9
  48. package/src/client/DirectoryFlow.tsx +16 -0
  49. package/src/client/DoctorPanel.tsx +70 -7
  50. package/src/client/EditorPane.tsx +574 -42
  51. package/src/client/HostsView.tsx +12 -3
  52. package/src/client/MonitorView.tsx +16 -5
  53. package/src/client/OutlinePanel.tsx +287 -0
  54. package/src/client/ProcessesSection.tsx +292 -0
  55. package/src/client/RemoteDirectoryPicker.tsx +12 -0
  56. package/src/client/RemoteExplorer.tsx +929 -40
  57. package/src/client/RemoteRoot.tsx +147 -22
  58. package/src/client/SearchView.tsx +8 -0
  59. package/src/client/TerminalSnippets.tsx +83 -8
  60. package/src/client/api.ts +114 -13
  61. package/src/client/blame-model.ts +242 -0
  62. package/src/client/changes/ChangesDock.tsx +188 -6
  63. package/src/client/changes/changes.css +10 -3
  64. package/src/client/changes/review-state.ts +34 -0
  65. package/src/client/connection.ts +29 -0
  66. package/src/client/downloads.ts +49 -4
  67. package/src/client/i18n.ts +276 -8
  68. package/src/client/index.tsx +4 -0
  69. package/src/client/outline-model.ts +775 -0
  70. package/src/client/request-gate.ts +221 -0
  71. package/src/client/scm/CommitPane.tsx +20 -2
  72. package/src/client/scm/DiffView.tsx +343 -117
  73. package/src/client/scm/HistoryPanel.tsx +61 -3
  74. package/src/client/scm/RepoPicker.tsx +1 -1
  75. package/src/client/scm/ScmPanel.tsx +391 -87
  76. package/src/client/scm/actions.ts +150 -14
  77. package/src/client/store.tsx +426 -14
  78. package/src/client/ui.tsx +4 -0
  79. package/src/client/vsc/FindWidget.tsx +24 -9
  80. package/src/client/vsc/blame.ts +147 -0
  81. package/src/client/vsc/breadcrumb.tsx +91 -3
  82. package/src/client/vsc/change-marks.ts +93 -44
  83. package/src/client/vsc/editor-keymap.ts +59 -1
  84. package/src/client/vsc/file-icons.tsx +17 -3
  85. package/src/client/vsc/kit.tsx +29 -20
  86. package/src/client/vsc/preview-document.tsx +323 -0
  87. package/src/client/vsc/preview-model.ts +216 -0
  88. package/src/client/vsc/preview-services.ts +118 -0
  89. package/src/client/vsc/save-shortcut.ts +47 -1
  90. package/src/client/vsc/terminal-theme.ts +44 -18
  91. package/src/client/vsc/vsc.css +6509 -5458
  92. package/src/forward.ts +47 -9
  93. package/src/fs-ops.ts +124 -4
  94. package/src/git-ops.ts +54 -3
  95. package/src/http.ts +35 -4
  96. package/src/keygen.ts +55 -4
  97. package/src/monitor.ts +13 -0
  98. package/src/notices.ts +23 -1
  99. package/src/p2/helper-rpc.ts +113 -7
  100. package/src/p2/worlds.ts +14 -1
  101. package/src/processes.ts +177 -0
  102. package/src/protocol.ts +37 -0
  103. package/src/routes.ts +330 -43
  104. package/src/sftp.ts +51 -14
  105. package/src/store.ts +10 -0
  106. package/src/terminal.ts +73 -26
  107. package/src/view-settings.ts +50 -10
  108. package/lib/types/client/Dialog.d.ts +0 -14
  109. package/src/client/Dialog.tsx +0 -76
@@ -24,7 +24,15 @@ import { defaultKeymap, historyKeymap, indentWithTab } from '@codemirror/command
24
24
 
25
25
  /** The editor actions the key bindings dispatch into. */
26
26
  export interface EditorKeyHandlers {
27
- /** Ctrl/Cmd+S → the pane's save path. */
27
+ /**
28
+ * Ctrl/Cmd+S → the pane's save path.
29
+ *
30
+ * MUST be a no-op while a modal layer is open: `CodeEditor` (the only caller)
31
+ * checks `isModalLayerOpen()` before saving. The binding itself stays pure —
32
+ * this module imports no DOM — but because CodeMirror handles the key first and
33
+ * prevents the default, the window listener in `save-shortcut.ts` never gets to
34
+ * apply its own gate to this path.
35
+ */
28
36
  save(): void
29
37
  /** Ctrl/Cmd+F → seed our find widget from the selection and open it. */
30
38
  openFindForSelection(view: EditorView): void
@@ -34,6 +42,39 @@ export interface EditorKeyHandlers {
34
42
  stepHunk(delta: 1 | -1): boolean
35
43
  /** Escape → close the find widget; false when it was not open. */
36
44
  closeFind(): boolean
45
+ /**
46
+ * Ctrl/Cmd+G → ask for a line number and jump there.
47
+ *
48
+ * The prompt is the caller's (`promptDialog`), so this module stays free of
49
+ * DOM/React; the binding always claims the key (browsers use Ctrl+G for
50
+ * "find next", which has nothing to do inside a code editor).
51
+ */
52
+ gotoLine(view: EditorView): void
53
+ /**
54
+ * Ctrl/Cmd+D → select the next occurrence of the current selection.
55
+ *
56
+ * Returns the command's own answer: `false` (nothing to expand, or a mixed
57
+ * selection) must fall through to the browser instead of being swallowed —
58
+ * the same rule the hunk bindings follow.
59
+ */
60
+ selectNextOccurrence(view: EditorView): boolean
61
+ }
62
+
63
+ /**
64
+ * Resolve the "go to line" answer to a 1-based line number inside `total`.
65
+ *
66
+ * Accepts what VS Code's box accepts for the LINE half: `42`, ` 42 `, `42:7`
67
+ * (the column half is ignored — this editor jumps to a line, the status bar
68
+ * reports the column). Anything else (empty, `0`, text) is `undefined`, and a
69
+ * number past the end CLAMPS to the last line instead of failing: the answer
70
+ * usually comes from a file the user is reading, not from its exact length.
71
+ */
72
+ export function parseGotoLine(text: string, total: number): number | undefined {
73
+ const match = /^\s*(\d+)(?::\d+)?\s*$/.exec(text)
74
+ if (match === null) return undefined
75
+ const value = Number(match[1])
76
+ if (!Number.isSafeInteger(value) || value < 1) return undefined
77
+ return Math.min(value, Math.max(1, Math.floor(total)))
37
78
  }
38
79
 
39
80
  /**
@@ -93,5 +134,22 @@ export function editorKeymap(handlers: EditorKeyHandlers): KeyBinding[] {
93
134
  key: 'Escape',
94
135
  run: () => handlers.closeFind(),
95
136
  },
137
+ /**
138
+ * Ctrl/Cmd+G → go to line, Ctrl/Cmd+D → select next occurrence.
139
+ *
140
+ * `@codemirror/search` exports both, but this plugin deliberately does NOT
141
+ * mount `searchKeymap`: that keymap also opens the stock search panel, which
142
+ * the editor replaced with its own find widget. So the two commands are
143
+ * wired through injected handlers instead (the goto-line one renders no
144
+ * CodeMirror panel at all — the caller prompts).
145
+ *
146
+ * Mod-g claims the key even when the prompt is dismissed: Ctrl+G means
147
+ * "find next" in the browser and must never leave the editor. Mod-d does NOT
148
+ * set `preventDefault` — CodeMirror prevents the default for a key whenever
149
+ * one of its bindings sets that flag, even when every command returns false,
150
+ * and a failed expansion has to be able to fall through.
151
+ */
152
+ { key: 'Mod-g', run: (view) => { handlers.gotoLine(view); return true }, preventDefault: true },
153
+ { key: 'Mod-d', run: (view) => handlers.selectNextOccurrence(view) },
96
154
  ]
97
155
  }
@@ -300,7 +300,7 @@ export function FileTypeIcon(props: FileIconProps): ReactNode {
300
300
  height={size}
301
301
  viewBox="0 0 16 16"
302
302
  fill="none"
303
- className={props.className}
303
+ className={props.className === undefined ? 'rvs-fi' : `rvs-fi ${props.className}`}
304
304
  aria-hidden="true"
305
305
  >
306
306
  <path
@@ -347,7 +347,14 @@ export function FolderGlyph(props: FolderGlyphProps): ReactNode {
347
347
  const size = props.size ?? 16
348
348
  return props.open === true
349
349
  ? (
350
- <svg width={size} height={size} viewBox="0 0 16 16" fill="none" className={props.className} aria-hidden="true">
350
+ <svg
351
+ width={size}
352
+ height={size}
353
+ viewBox="0 0 16 16"
354
+ fill="none"
355
+ className={props.className === undefined ? 'rvs-fi' : `rvs-fi ${props.className}`}
356
+ aria-hidden="true"
357
+ >
351
358
  <path
352
359
  d="M1.9 12V4.3c0-.6.4-1 1-1h3.2l1.5 1.7h5.6c.6 0 1 .4 1 1v5.4"
353
360
  fill="#c69a3f"
@@ -365,7 +372,14 @@ export function FolderGlyph(props: FolderGlyphProps): ReactNode {
365
372
  </svg>
366
373
  )
367
374
  : (
368
- <svg width={size} height={size} viewBox="0 0 16 16" fill="none" className={props.className} aria-hidden="true">
375
+ <svg
376
+ width={size}
377
+ height={size}
378
+ viewBox="0 0 16 16"
379
+ fill="none"
380
+ className={props.className === undefined ? 'rvs-fi' : `rvs-fi ${props.className}`}
381
+ aria-hidden="true"
382
+ >
369
383
  <path
370
384
  d="M1.9 12.3V4.2c0-.6.4-1 1-1h3.2l1.5 1.7h5.6c.6 0 1 .4 1 1v6.4c0 .6-.4 1-1 1H2.9c-.6 0-1-.4-1-1Z"
371
385
  fill="#d9ab4e"
@@ -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
  /**
@@ -654,13 +646,22 @@ export function DialogHost(): ReactNode {
654
646
  return createPortal(
655
647
  <>
656
648
  {request !== undefined && <ModalCard key={request.id} request={request} />}
657
- {items.length > 0 && (
658
- <div className="rvs-toasts">
659
- {items.map(item => (
660
- <div key={item.id} className={item.error ? 'rvs-toast error' : 'rvs-toast'}>{item.text}</div>
661
- ))}
662
- </div>
663
- )}
649
+ {/* Toast is the plugin's only report channel for "已上传 / 删除失败 / 已推送":
650
+ without a live region a screen reader never heard any of it (WCAG 4.1.3).
651
+ The stack is mounted even while empty so the region EXISTS before the
652
+ message arrives — a `role=status` region inserted together with its text
653
+ is announced by some screen readers and missed by others. It stays
654
+ polite; an error item asserts on its own, so a failure interrupts and a
655
+ success does not. (An empty stack is a zero-sized fixed box: no paint.) */}
656
+ <div className="rvs-toasts" role="status" aria-live="polite">
657
+ {items.map(item => (
658
+ <div
659
+ key={item.id}
660
+ className={item.error ? 'rvs-toast error' : 'rvs-toast'}
661
+ role={item.error ? 'alert' : undefined}
662
+ >{item.text}</div>
663
+ ))}
664
+ </div>
664
665
  </>,
665
666
  document.body,
666
667
  )
@@ -670,9 +671,13 @@ export function DialogHost(): ReactNode {
670
671
  * Focusable elements inside one dialog, in DOM order.
671
672
  *
672
673
  * The modal is portaled to the END of `<body>`, so without a Tab trap a
673
- * keyboard user tabs through the whole page to reach its buttons.
674
+ * keyboard user tabs through the whole page to reach its buttons. Exported for
675
+ * the other portaled layers that need the same walk (the terminal snippet
676
+ * popover); `DoctorPanel` keeps its own copy because it deliberately does not
677
+ * import this module (its copy path must not use the silently-failing
678
+ * `copyText`, which `check-doctor.mjs` pins).
674
679
  */
675
- function focusables(root: HTMLElement | null): HTMLElement[] {
680
+ export function focusables(root: HTMLElement | null): HTMLElement[] {
676
681
  if (root === null) return []
677
682
  return Array.from(root.querySelectorAll<HTMLElement>(
678
683
  'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
@@ -708,6 +713,10 @@ function ModalCard(props: { request: ModalRequest }): ReactNode {
708
713
 
709
714
  useEffect(() => {
710
715
  const onKey = (e: KeyboardEvent): void => {
716
+ // An IME candidate window owns Enter/Escape while composing: acting here
717
+ // would resolve the prompt with a half-composed value (or cancel it while
718
+ // the candidate list is open).
719
+ if (e.isComposing === true || e.keyCode === 229) return
711
720
  if (e.key === 'Escape') {
712
721
  e.preventDefault()
713
722
  request.resolve(request.kind === 'prompt' ? undefined : false)
@@ -0,0 +1,323 @@
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(new Error('LibreOffice is not installed on the remote host'), { previewKind: 'unavailable' })
92
+ }
93
+ throw new Error(result.stderr.trim() || 'remote LibreOffice conversion failed')
94
+ }
95
+ const tempDir = line.slice('@@RVS_PDF '.length).trim()
96
+ try {
97
+ return await fetchRemoteBytes(alias, `${tempDir}/input.pdf`, signal)
98
+ } finally {
99
+ // Best-effort cleanup; a failed rm must not turn a rendered document into
100
+ // an error, but it also must never be skipped silently in this function.
101
+ void api.exec(alias, `rm -rf ${shQuote(tempDir)}`, 15_000).catch(() => undefined)
102
+ }
103
+ }
104
+
105
+ function sizeText(bytes: number): string {
106
+ if (!Number.isFinite(bytes) || bytes < 0) return ''
107
+ if (bytes < 1024) return `${bytes} B`
108
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
109
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`
110
+ }
111
+
112
+ function PreviewNotice(props: {
113
+ path: string
114
+ title: string
115
+ hint: string
116
+ detail?: string
117
+ t: (key: string) => string
118
+ onRetry?: () => void
119
+ }): ReactNode {
120
+ return (
121
+ <div className="rvs-preview-notice" role="alert">
122
+ <div className="rvs-preview-notice-title">{props.title}</div>
123
+ <div className="rvs-preview-notice-path">{props.path}</div>
124
+ <div className="rvs-preview-notice-hint">{props.hint}</div>
125
+ {props.detail !== undefined && <div className="rvs-preview-notice-detail">{props.detail}</div>}
126
+ {props.onRetry !== undefined && (
127
+ <button type="button" className="rvs-preview-retry" onClick={props.onRetry}>{props.t('common.retry')}</button>
128
+ )}
129
+ </div>
130
+ )
131
+ }
132
+
133
+ export function BytePreview(props: {
134
+ alias: string
135
+ path: string
136
+ /** DSH session; lets the host workspaceFiles/officeKit remotes resolve the
137
+ * same remote workspace before the plugin's own download fallback. */
138
+ sessionId?: string
139
+ kind: 'pdf' | 'office' | 'media'
140
+ revision: number
141
+ t: (key: string) => string
142
+ }): ReactNode {
143
+ const [state, setState] = useState<{ status: 'loading' } | { status: 'ready'; url: string; size: number } | { status: 'failed'; error: PreviewError }>({ status: 'loading' })
144
+ const [elementFailed, setElementFailed] = useState(false)
145
+ const [attempt, setAttempt] = useState(0)
146
+
147
+ useEffect(() => { setElementFailed(false) }, [props.path, props.kind])
148
+
149
+ useEffect(() => {
150
+ const controller = new AbortController()
151
+ let alive = true
152
+ let url: string | undefined
153
+ let hostReason: PreviewFailureReason = 'failed'
154
+ setState({ status: 'loading' })
155
+ const download = props.kind === 'office'
156
+ ? () => fetchOfficePdf(props.alias, props.path, controller.signal)
157
+ : () => fetchRemoteBytes(props.alias, props.path, controller.signal)
158
+ const hostRead = props.kind === 'office'
159
+ ? renderOfficePdf(props.sessionId ?? '', props.path, controller.signal)
160
+ : readWorkspaceBytes(props.sessionId ?? '', props.path, controller.signal)
161
+ void hostRead.then((host) => {
162
+ if (host.ok) return host.data
163
+ hostReason = host.reason
164
+ // A missing service or a path the host cannot resolve is exactly why the
165
+ // plugin keeps its own /download path; only the fallback can succeed.
166
+ return download()
167
+ }).then((bytes) => {
168
+ if (!alive) return
169
+ const mime = props.kind === 'media'
170
+ ? mediaTypeOf(props.path)?.mime ?? 'application/octet-stream'
171
+ : 'application/pdf'
172
+ url = URL.createObjectURL(new Blob([bytes], { type: mime }))
173
+ setState({ status: 'ready', url, size: bytes.byteLength })
174
+ }).catch((error: unknown) => {
175
+ if (!alive) return
176
+ const reason = typeof error === 'object' && error !== null && 'previewKind' in error
177
+ ? (error as { previewKind: PreviewError['kind'] }).previewKind
178
+ : hostReason
179
+ setState({ status: 'failed', error: { kind: reason, message: errorMessage(error) } })
180
+ })
181
+ return () => {
182
+ alive = false
183
+ controller.abort()
184
+ if (url !== undefined) URL.revokeObjectURL(url)
185
+ }
186
+ }, [props.alias, props.path, props.kind, props.revision, attempt, props.sessionId])
187
+
188
+ if (state.status === 'loading') {
189
+ return (
190
+ <div className="rvs-preview-loading" role="status">
191
+ <span className="rvs-preview-spinner" aria-hidden="true" />
192
+ <span>{props.kind === 'office' ? props.t('preview.converting') : props.t('common.loading')}</span>
193
+ {props.kind === 'office' && <span className="rvs-preview-loading-hint">{props.t('preview.convertingHint')}</span>}
194
+ </div>
195
+ )
196
+ }
197
+ if (state.status === 'failed') {
198
+ const title = state.error.kind === 'too-large'
199
+ ? props.t('preview.tooLargeTitle')
200
+ : state.error.kind === 'unavailable'
201
+ ? props.t(props.kind === 'office' ? 'preview.officeUnavailableTitle' : 'preview.unavailableTitle')
202
+ : state.error.kind === 'not-found'
203
+ ? props.t('preview.notFoundTitle')
204
+ : state.error.kind === 'remote'
205
+ ? props.t('preview.remoteTitle')
206
+ : props.t('preview.failedTitle')
207
+ const hint = state.error.kind === 'too-large'
208
+ ? props.t('preview.tooLargeHint')
209
+ : state.error.kind === 'unavailable'
210
+ ? props.t(props.kind === 'office' ? 'preview.officeUnavailableHint' : 'preview.unavailableHint')
211
+ : state.error.kind === 'not-found'
212
+ ? props.t('preview.notFoundHint')
213
+ : state.error.kind === 'remote'
214
+ ? props.t('preview.remoteHint')
215
+ : props.t('preview.failedHint')
216
+ return <PreviewNotice path={props.path} title={title} hint={hint} detail={state.error.message} t={props.t} onRetry={() => { setAttempt(value => value + 1) }} />
217
+ }
218
+ if (props.kind === 'media') {
219
+ const media = mediaTypeOf(props.path)
220
+ if (elementFailed) {
221
+ 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) }} />
222
+ }
223
+ return (
224
+ <div className={`rvs-preview-media${media?.kind === 'video' ? ' rvs-preview-media-video' : ''}`}>
225
+ {media?.kind === 'video'
226
+ ? <video className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />
227
+ : <audio className="rvs-preview-media-el" src={state.url} controls onError={() => { setElementFailed(true) }} />}
228
+ <div className="rvs-preview-media-meta">
229
+ {sizeText(state.size)}
230
+ <span className="rvs-preview-media-hint">{props.path}</span>
231
+ </div>
232
+ </div>
233
+ )
234
+ }
235
+ return (
236
+ <div className="rvs-preview-document">
237
+ <iframe className="rvs-preview-document-frame" src={state.url} title={props.path} />
238
+ <div className="rvs-preview-document-meta">
239
+ {sizeText(state.size)}
240
+ <span className="rvs-preview-document-hint">{props.t('preview.documentHint')}</span>
241
+ </div>
242
+ </div>
243
+ )
244
+ }
245
+
246
+ export function SvgPreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
247
+ const [url, setUrl] = useState<string | undefined>(undefined)
248
+ const [failed, setFailed] = useState(false)
249
+ useEffect(() => {
250
+ const next = URL.createObjectURL(new Blob([props.text], { type: 'image/svg+xml' }))
251
+ setUrl(next)
252
+ return () => { URL.revokeObjectURL(next) }
253
+ }, [props.text])
254
+ useEffect(() => { setFailed(false) }, [url])
255
+ if (failed) {
256
+ return <PreviewNotice path={props.path} title={props.t('preview.svgFailed')} hint={props.t('preview.svgFailedHint')} t={props.t} />
257
+ }
258
+ if (url === undefined) return null
259
+ return (
260
+ <div className="rvs-preview-svg">
261
+ <img className="rvs-preview-svg-img" src={url} alt={props.path} onError={() => { setFailed(true) }} />
262
+ <div className="rvs-preview-svg-hint">{props.truncated ? props.t('preview.truncated') : props.t('preview.svgHint')}</div>
263
+ </div>
264
+ )
265
+ }
266
+
267
+ /** DOM ceilings (parsing itself allows more; the rest gets a banner). */
268
+ const RENDER_ROWS = 400
269
+ const RENDER_COLUMNS = 48
270
+
271
+ function padRow(row: readonly string[], columns: number): string[] {
272
+ const cells = row.slice(0, columns)
273
+ while (cells.length < columns) cells.push('')
274
+ return cells
275
+ }
276
+
277
+ export function TablePreview(props: { path: string; text: string; truncated: boolean; t: (key: string) => string }): ReactNode {
278
+ const parsed = useMemo(
279
+ () => parseDelimited(props.text, tableDelimiterOf(props.path)),
280
+ [props.text, props.path],
281
+ )
282
+ const columns = Math.min(parsed.columns, RENDER_COLUMNS)
283
+ const rows = parsed.rows.slice(0, RENDER_ROWS)
284
+ const header = rows[0]
285
+ const body = rows.slice(1)
286
+ const hiddenRows = parsed.rows.length - rows.length
287
+ const hiddenColumns = parsed.columns - columns
288
+ const notes: string[] = []
289
+ if (props.truncated) notes.push(props.t('preview.truncated'))
290
+ if (parsed.truncated) {
291
+ notes.push(props.t('preview.tableTruncated')
292
+ .replace('{rows}', String(DEFAULT_TABLE_LIMITS.maxRows))
293
+ .replace('{cells}', String(DEFAULT_TABLE_LIMITS.maxCells)))
294
+ }
295
+ if (hiddenRows > 0) notes.push(props.t('preview.tableHiddenRows').replace('{shown}', String(rows.length)).replace('{rest}', String(hiddenRows)))
296
+ if (hiddenColumns > 0) notes.push(props.t('preview.tableHiddenColumns').replace('{shown}', String(columns)).replace('{rest}', String(hiddenColumns)))
297
+ if (parsed.rows.length === 0) {
298
+ return <PreviewNotice path={props.path} title={props.t('preview.tableEmptyTitle')} hint={props.t('preview.tableEmptyHint')} t={props.t} />
299
+ }
300
+ return (
301
+ <div className="rvs-preview-table-wrap">
302
+ {notes.map((note, index) => <div className="rvs-preview-banner" key={`${String(index)}:${note}`}>{note}</div>)}
303
+ <div className="rvs-preview-table-scroll">
304
+ <table className="rvs-preview-table">
305
+ <thead>
306
+ <tr>
307
+ <th className="rvs-preview-rownum" scope="col">#</th>
308
+ {padRow(header ?? [], columns).map((cell, index) => <th key={index} scope="col">{cell}</th>)}
309
+ </tr>
310
+ </thead>
311
+ <tbody>
312
+ {body.map((row, rowIndex) => (
313
+ <tr key={rowIndex}>
314
+ <th className="rvs-preview-rownum" scope="row">{rowIndex + 2}</th>
315
+ {padRow(row, columns).map((cell, cellIndex) => <td key={cellIndex} title={cell}>{cell}</td>)}
316
+ </tr>
317
+ ))}
318
+ </tbody>
319
+ </table>
320
+ </div>
321
+ </div>
322
+ )
323
+ }