dsh-remote-vs 0.13.0 → 0.15.1

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 (128) hide show
  1. package/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
@@ -261,6 +261,13 @@ export function FindWidget(props: {
261
261
  * that subtree travels away with the text. Fixed coordinates cannot.
262
262
  */
263
263
  anchor?: { top: number; right: number } | undefined
264
+ /**
265
+ * Bumped by the editor whenever its selection changes while this widget is
266
+ * open. The `n/N` readout is derived from the caret, and moves made OUTSIDE the
267
+ * widget (F3 / Shift-F3, a click, an arrow key) never told it — the numbers
268
+ * stayed on the previous match while the caret had moved on.
269
+ */
270
+ tick?: number
264
271
  onClose: () => void
265
272
  }): ReactNode {
266
273
  const [state, setState] = useState<FindState>(EMPTY)
@@ -356,6 +363,19 @@ export function FindWidget(props: {
356
363
  // eslint-disable-next-line react-hooks/exhaustive-deps
357
364
  }, [state, props.open, props.view])
358
365
 
366
+ /**
367
+ * Re-read the `n/N` readout when the EDITOR's selection changed under us.
368
+ *
369
+ * `refreshCount` is declared after the early return below (it is written for
370
+ * event handlers), so this uses the same module-level `countFor` helper it
371
+ * wraps. Stepping from inside the widget already refreshes itself; this covers
372
+ * the moves that do not pass through the widget at all.
373
+ */
374
+ useEffect(() => {
375
+ if (!props.open || props.view === undefined) return
376
+ setCount(countFor(props.view))
377
+ }, [props.tick, props.open, props.view])
378
+
359
379
  if (!props.open) return null
360
380
 
361
381
  /**
@@ -15,6 +15,7 @@ import {
15
15
  createElement,
16
16
  useCallback,
17
17
  useEffect,
18
+ useId,
18
19
  useLayoutEffect,
19
20
  useRef,
20
21
  useState,
@@ -23,6 +24,7 @@ import {
23
24
  type ReactNode,
24
25
  } from 'react'
25
26
  import { createPortal } from 'react-dom'
27
+ import { detectLang, makeT } from '../i18n.ts'
26
28
 
27
29
  // ------------------------------------------------------------------ icons
28
30
 
@@ -483,6 +485,24 @@ function subscribe(listener: () => void): () => void {
483
485
  }
484
486
  }
485
487
 
488
+ /**
489
+ * Dismiss the question that is on screen, if any, as "cancelled".
490
+ *
491
+ * `modalRequest` is a SINGLE slot: a second `confirmDialog`/`promptDialog` used
492
+ * to overwrite the pending one without settling its promise, so every awaiter
493
+ * hung forever. That is not academic — the workspace-switch guard awaits a
494
+ * confirm and holds a module-level `busy` flag while it does, so one overwritten
495
+ * dialog made every later dirty switch silently do nothing until a reload. The
496
+ * newest question is the one the user can actually answer; the older one is
497
+ * answered "cancelled" here.
498
+ */
499
+ function dismissPendingModal(): void {
500
+ const pending = modalRequest
501
+ if (pending === undefined) return
502
+ modalRequest = undefined
503
+ pending.resolve(pending.kind === 'prompt' ? undefined : false)
504
+ }
505
+
486
506
  /** Themed confirm; resolves false when dismissed. */
487
507
  export function confirmDialog(opts: {
488
508
  title: string
@@ -491,6 +511,7 @@ export function confirmDialog(opts: {
491
511
  okText?: string
492
512
  cancelText?: string
493
513
  }): Promise<boolean> {
514
+ dismissPendingModal()
494
515
  return new Promise<boolean>((resolve) => {
495
516
  modalSeq += 1
496
517
  modalRequest = {
@@ -518,6 +539,7 @@ export function promptDialog(opts: {
518
539
  okText?: string
519
540
  cancelText?: string
520
541
  }): Promise<string | undefined> {
542
+ dismissPendingModal()
521
543
  return new Promise<string | undefined>((resolve) => {
522
544
  modalSeq += 1
523
545
  modalRequest = {
@@ -595,15 +617,43 @@ export function DialogHost(): ReactNode {
595
617
  )
596
618
  }
597
619
 
620
+ /**
621
+ * Focusable elements inside one dialog, in DOM order.
622
+ *
623
+ * The modal is portaled to the END of `<body>`, so without a Tab trap a
624
+ * keyboard user tabs through the whole page to reach its buttons.
625
+ */
626
+ function focusables(root: HTMLElement | null): HTMLElement[] {
627
+ if (root === null) return []
628
+ return Array.from(root.querySelectorAll<HTMLElement>(
629
+ 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',
630
+ ))
631
+ }
632
+
598
633
  function ModalCard(props: { request: ModalRequest }): ReactNode {
599
634
  const { request } = props
600
635
  const [value, setValue] = useState(request.initial)
601
636
  const inputRef = useRef<HTMLInputElement>(null)
637
+ const boxRef = useRef<HTMLDivElement>(null)
638
+ const cancelRef = useRef<HTMLButtonElement>(null)
639
+ const titleId = useId()
640
+ /** Focus is returned here when the dialog goes away. */
641
+ const openerRef = useRef<HTMLElement | null>(
642
+ typeof document === 'undefined' ? null : (document.activeElement as HTMLElement | null),
643
+ )
644
+ const t = makeT(detectLang())
602
645
 
603
646
  useEffect(() => {
647
+ // A prompt starts in its input; a confirmation starts on the safe button.
604
648
  if (request.kind === 'prompt') {
605
649
  inputRef.current?.focus()
606
650
  inputRef.current?.select()
651
+ } else {
652
+ cancelRef.current?.focus()
653
+ }
654
+ return () => {
655
+ const opener = openerRef.current
656
+ if (opener !== null && document.body.contains(opener)) opener.focus()
607
657
  }
608
658
  }, [request.kind])
609
659
 
@@ -617,6 +667,20 @@ function ModalCard(props: { request: ModalRequest }): ReactNode {
617
667
  e.preventDefault()
618
668
  request.resolve(value)
619
669
  closeModal()
670
+ } else if (e.key === 'Tab') {
671
+ // Keep focus inside the dialog (first <-> last).
672
+ const items = focusables(boxRef.current)
673
+ if (items.length === 0) return
674
+ const first = items[0] as HTMLElement
675
+ const last = items[items.length - 1] as HTMLElement
676
+ const active = document.activeElement
677
+ if (e.shiftKey && (active === first || active === null || !boxRef.current?.contains(active))) {
678
+ e.preventDefault()
679
+ last.focus()
680
+ } else if (!e.shiftKey && active === last) {
681
+ e.preventDefault()
682
+ first.focus()
683
+ }
620
684
  }
621
685
  }
622
686
  window.addEventListener('keydown', onKey)
@@ -634,8 +698,8 @@ function ModalCard(props: { request: ModalRequest }): ReactNode {
634
698
 
635
699
  return (
636
700
  <div className="rvs-portal rvs-modal-mask" onMouseDown={(e) => { if (e.target === e.currentTarget) cancel() }}>
637
- <div className="rvs-modal-box" role="dialog" aria-modal="true">
638
- <div className="rvs-modal-title">{request.title}</div>
701
+ <div ref={boxRef} className="rvs-modal-box" role="dialog" aria-modal="true" aria-labelledby={titleId}>
702
+ <div className="rvs-modal-title" id={titleId}>{request.title}</div>
639
703
  {request.text !== '' && <div className="rvs-modal-text">{request.text}</div>}
640
704
  {request.kind === 'prompt' && (
641
705
  <input
@@ -647,15 +711,15 @@ function ModalCard(props: { request: ModalRequest }): ReactNode {
647
711
  />
648
712
  )}
649
713
  <div className="rvs-modal-row">
650
- <button type="button" className="rvs-modal-btn" onClick={cancel}>
651
- {request.cancelText ?? '取消'}
714
+ <button ref={cancelRef} type="button" className="rvs-modal-btn" onClick={cancel}>
715
+ {request.cancelText ?? t('common.cancel')}
652
716
  </button>
653
717
  <button
654
718
  type="button"
655
719
  className={request.danger ? 'rvs-modal-btn danger' : 'rvs-modal-btn primary'}
656
720
  onClick={ok}
657
721
  >
658
- {request.okText ?? '确定'}
722
+ {request.okText ?? t('common.ok')}
659
723
  </button>
660
724
  </div>
661
725
  </div>
@@ -694,6 +758,50 @@ export function ContextMenu(props: {
694
758
  const [pos, setPos] = useState({ left: props.x, top: props.y })
695
759
  /** When this menu appeared (monotonic): see MENU_OPEN_GRACE_MS. */
696
760
  const openedAt = useRef(typeof performance === 'undefined' ? 0 : performance.now())
761
+ /** Element focus must return to when the menu closes. */
762
+ const openerRef = useRef<HTMLElement | null>(
763
+ typeof document === 'undefined' ? null : (document.activeElement as HTMLElement | null),
764
+ )
765
+
766
+ /** Enabled items in DOM order (arrow navigation skips separators/disabled). */
767
+ const itemsOf = (): HTMLButtonElement[] => {
768
+ const box = boxRef.current
769
+ if (box === null) return []
770
+ return Array.from(box.querySelectorAll<HTMLButtonElement>('.rvs-menu-item:not([disabled])'))
771
+ }
772
+
773
+ /**
774
+ * Keyboard access to the menu.
775
+ *
776
+ * Opening it focuses the first item; ↑/↓/Home/End move, Enter/Space activate
777
+ * (native button semantics), Esc closes (the window listener above), and the
778
+ * previously focused element gets focus back on unmount. Without this the
779
+ * menu was pointer-only: a keyboard user could open it (Shift+F10) and then
780
+ * had no way to choose anything and no way to know where focus was.
781
+ */
782
+ useEffect(() => {
783
+ itemsOf()[0]?.focus()
784
+ return () => {
785
+ const opener = openerRef.current
786
+ if (opener !== null && document.body.contains(opener)) opener.focus()
787
+ }
788
+ }, [])
789
+
790
+ const onMenuKeyDown = (e: React.KeyboardEvent<HTMLDivElement>): void => {
791
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return
792
+ e.preventDefault()
793
+ const items = itemsOf()
794
+ if (items.length === 0) return
795
+ const at = items.indexOf(document.activeElement as HTMLButtonElement)
796
+ const next = e.key === 'Home'
797
+ ? 0
798
+ : e.key === 'End'
799
+ ? items.length - 1
800
+ : e.key === 'ArrowDown'
801
+ ? (at + 1) % items.length
802
+ : (at <= 0 ? items.length - 1 : at - 1)
803
+ items[next]?.focus()
804
+ }
697
805
 
698
806
  useLayoutEffect(() => {
699
807
  const box = boxRef.current
@@ -758,12 +866,13 @@ export function ContextMenu(props: {
758
866
  if (typeof document === 'undefined') return null
759
867
  return createPortal(
760
868
  <div className="rvs-portal">
761
- <div ref={boxRef} className="rvs-menu" style={{ left: pos.left, top: pos.top }}>
869
+ <div ref={boxRef} className="rvs-menu" role="menu" style={{ left: pos.left, top: pos.top }} onKeyDown={onMenuKeyDown}>
762
870
  {props.entries.map((entry, index) => (
763
871
  <div key={`${entry.label}-${index}`}>
764
872
  {entry.separated === true && index > 0 && <div className="rvs-menu-sep" />}
765
873
  <button
766
874
  type="button"
875
+ role="menuitem"
767
876
  className={entry.danger === true ? 'rvs-menu-item danger' : 'rvs-menu-item'}
768
877
  disabled={entry.disabled === true}
769
878
  onClick={() => {
@@ -34,6 +34,37 @@ export const revealLineField = StateField.define<DecorationSet>({
34
34
  /** How long the landing highlight stays lit. */
35
35
  const LIT_MS = 2600
36
36
 
37
+ /**
38
+ * The pending extinguish timer of each editor.
39
+ *
40
+ * A second jump used to be switched off by the FIRST jump's timer: the highlight
41
+ * is documented as ~2.6 s and jumping repeatedly in one file is an advertised
42
+ * flow, so a new jump has to CANCEL the previous one's timer instead of letting
43
+ * it land early. Keyed by view because more than one editor exists at a time
44
+ * (the diff panes mount their own).
45
+ */
46
+ const litTimers = new WeakMap<EditorView, number>()
47
+
48
+ /**
49
+ * Light the landing line and (re)arm its extinguish timer.
50
+ *
51
+ * Replacing the previous timer is the whole point (see `litTimers`): without it
52
+ * the older jump's timer fires mid-way through the newer highlight.
53
+ */
54
+ function scheduleExtinguish(view: EditorView, lit: (position: number | null) => void): void {
55
+ const previous = litTimers.get(view)
56
+ if (previous !== undefined) window.clearTimeout(previous)
57
+ const timer = window.setTimeout(() => {
58
+ litTimers.delete(view)
59
+ try {
60
+ lit(null)
61
+ } catch {
62
+ // A disposed view: nothing to switch off.
63
+ }
64
+ }, LIT_MS)
65
+ litTimers.set(view, timer)
66
+ }
67
+
37
68
  /**
38
69
  * Scroll to a 1-based line, put the caret on it and light it up.
39
70
  *
@@ -67,13 +98,7 @@ export function revealLine(view: EditorView, target: number, lit: (position: num
67
98
  // No layout: the CodeMirror scroll already did its best.
68
99
  }
69
100
  }, 30)
70
- window.setTimeout(() => {
71
- try {
72
- lit(null)
73
- } catch {
74
- // Disposed.
75
- }
76
- }, LIT_MS)
101
+ scheduleExtinguish(view, lit)
77
102
  }
78
103
 
79
104
  /** The rendered `.cm-line` element for a 1-based line number, if visible. */
@@ -132,11 +157,5 @@ export function revealRange(
132
157
  // No layout: the CodeMirror scroll already did its best.
133
158
  }
134
159
  }, 30)
135
- window.setTimeout(() => {
136
- try {
137
- lit?.(null)
138
- } catch {
139
- // Disposed.
140
- }
141
- }, LIT_MS)
160
+ if (lit !== undefined) scheduleExtinguish(view, lit)
142
161
  }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The window-level Ctrl/Cmd+S shortcut.
3
+ *
4
+ * `CodeEditor` owns that keystroke only while its CodeMirror view has focus (the
5
+ * editor's keymap), so after clicking the tab strip, the info row, the find box
6
+ * or any sidebar panel the very same keystroke did nothing at all — silently,
7
+ * while the UI advertises Ctrl+S as the save key (the save button's title and
8
+ * the empty-pane hint). A missed save is invisible until the tab is closed.
9
+ *
10
+ * Two rules make a global listener safe here:
11
+ *
12
+ * - BUBBLE phase plus `defaultPrevented`: CodeMirror handles its own keydown
13
+ * first and calls `preventDefault()` when a keymap binding matches (its event
14
+ * dispatch does exactly that), so this listener must step aside then — one
15
+ * press may never save twice.
16
+ * - the CALLER decides what "save" means: `resolve()` returns undefined when the
17
+ * surface on screen has nothing of ours to save (a diff tab is `DiffView`'s own
18
+ * contract, a themed dialog owns its input, a terminal owns its keys).
19
+ *
20
+ * Dependency-free on purpose (no React, no CodeMirror): the gate drives it with
21
+ * real `KeyboardEvent`s in jsdom, so the rule is testable without mounting the
22
+ * whole editor.
23
+ */
24
+
25
+ /** The fields `isSaveShortcut` reads — a structural type keeps it testable. */
26
+ export interface SaveShortcutEvent {
27
+ key: string
28
+ ctrlKey: boolean
29
+ metaKey: boolean
30
+ altKey: boolean
31
+ shiftKey: boolean
32
+ isComposing?: boolean | undefined
33
+ defaultPrevented: boolean
34
+ target: EventTarget | null
35
+ }
36
+
37
+ /**
38
+ * Areas where Ctrl+S belongs to somebody else.
39
+ *
40
+ * A terminal (xterm) forwards keys to the remote shell and a themed dialog's
41
+ * input is mid-edit; hijacking the key there would be a surprise, and for the
42
+ * shell it would also steal a control character (`^S`).
43
+ */
44
+ const FOREIGN_TARGET = '.xterm, textarea, input, [contenteditable="true"]'
45
+
46
+ /**
47
+ * Is this the save shortcut this module should act on?
48
+ *
49
+ * Pure: the caller passes the event's fields, so the gate can pin every rule
50
+ * without a DOM.
51
+ */
52
+ export function isSaveShortcut(event: SaveShortcutEvent): boolean {
53
+ // Already handled by CodeMirror (or anything else): never save a second time.
54
+ if (event.defaultPrevented) return false
55
+ // An IME composition is typing, not a command; Alt-combinations are characters
56
+ // on some platforms and are never our shortcut.
57
+ if (event.isComposing === true || event.altKey) return false
58
+ // Ctrl+Shift+S belongs to "Save As", which this plugin does not have yet:
59
+ // claiming it would be a surprise the day it is added.
60
+ if (event.shiftKey) return false
61
+ if (!(event.ctrlKey || event.metaKey)) return false
62
+ if (event.key.toLowerCase() !== 's') return false
63
+ const target = typeof Element !== 'undefined' && event.target instanceof Element ? event.target : null
64
+ if (target !== null && target.closest(FOREIGN_TARGET) !== null) return false
65
+ return true
66
+ }
67
+
68
+ /** A registered save target: `undefined` = this surface has nothing to save. */
69
+ export type SaveShortcutResolver = () => (() => void) | undefined
70
+
71
+ /**
72
+ * The registered surfaces, MOST RECENT LAST.
73
+ *
74
+ * One press must save ONCE. Several `EditorPane` instances can be mounted at the
75
+ * same time (every native session tab keeps its `RemoteRoot` mounted; the
76
+ * sidebar/centre/floating surfaces overlap briefly during a swap), and each used
77
+ * to add its own window listener — one Ctrl+S then ran two `saveActive`s, which
78
+ * the per-tab save queue (P2-D4) folded into two writes of the same content, two
79
+ * toasts and two git refreshes. Dispatch walks this set newest-first and stops at
80
+ * the first surface that can save, so the count is one no matter how many panes
81
+ * are alive. `EditorPane` additionally only registers while it is VISIBLE, so the
82
+ * surface that answers is the one on screen.
83
+ */
84
+ const resolvers = new Set<SaveShortcutResolver>()
85
+
86
+ /** True while the single window listener is installed. */
87
+ let listening = false
88
+
89
+ function onKeyDown(event: KeyboardEvent): void {
90
+ if (!isSaveShortcut(event)) return
91
+ for (const resolve of [...resolvers].reverse()) {
92
+ const save = resolve()
93
+ if (save === undefined) continue
94
+ // Claim the keystroke only when a surface actually acts on it: otherwise the
95
+ // browser default ("save page") stays available exactly as before.
96
+ event.preventDefault()
97
+ save()
98
+ return
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Install the window-level save shortcut for one surface.
104
+ *
105
+ * Re-entrant by design: the FIRST call installs the one window listener, later
106
+ * calls only register their resolver (no second listener), and the last disposer
107
+ * removes it.
108
+ *
109
+ * @param resolve - What to save RIGHT NOW; return the save action, or undefined
110
+ * when this surface is not ours to save. Called once per candidate keypress, so
111
+ * it always sees the current state.
112
+ * @returns the disposer (unregisters this resolver; removes the listener when the
113
+ * last surface is gone).
114
+ */
115
+ export function installSaveShortcut(resolve: SaveShortcutResolver): () => void {
116
+ if (typeof window === 'undefined') return () => {}
117
+ resolvers.add(resolve)
118
+ if (!listening) {
119
+ listening = true
120
+ // Bubble phase on purpose: CodeMirror runs first, and its `preventDefault()`
121
+ // is what tells this listener to keep its hands off (see the header).
122
+ window.addEventListener('keydown', onKeyDown)
123
+ }
124
+ return () => {
125
+ resolvers.delete(resolve)
126
+ if (resolvers.size === 0 && listening) {
127
+ listening = false
128
+ window.removeEventListener('keydown', onKeyDown)
129
+ }
130
+ }
131
+ }