dsh-ris-ide 1.6.11 → 1.7.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.
package/lib/client.js CHANGED
@@ -668,6 +668,33 @@ window.__ModuleLoader__.load({
668
668
  }
669
669
 
670
670
  /** One message from an unknown thrown value. */
671
+ /**
672
+ * Row-mask label while a start/stop/debug call is in flight.
673
+ *
674
+ * It used to be derived from `alive` alone: debugging a RUNNING program (the
675
+ * host restarts it under JDWP) therefore flashed 停止中, which reads like the
676
+ * click was a plain stop. The operation kind is the only thing that knows.
677
+ * @param {boolean} alive - whether the program had a live pid when clicked.
678
+ * @param {string} kind - `start` | `stop` | `restart` | `debug`.
679
+ * @returns {string} the label, ellipsis included.
680
+ */
681
+ function busyMaskText(alive, kind) {
682
+ if (kind === 'debug') return '调试中…'
683
+ if (kind === 'restart') return '重启中…'
684
+ return alive === true ? '停止中…' : '启动中…'
685
+ }
686
+ /**
687
+ * Tooltip for that mask: the full action, so "调试中…" does not read like a
688
+ * plain stop of a running program.
689
+ * @param {boolean} alive - whether the program had a live pid when clicked.
690
+ * @param {string} kind - `start` | `stop` | `restart` | `debug`.
691
+ * @param {string} name - program name.
692
+ * @returns {string} the tooltip.
693
+ */
694
+ function busyMaskTitle(alive, kind, name) {
695
+ var verb = kind === 'debug' ? '以调试模式重启' : kind === 'restart' ? '重启' : alive === true ? '停止' : '启动'
696
+ return '正在' + verb + ' ' + name + '…'
697
+ }
671
698
  function messageOf(error) {
672
699
  if (error === null || error === undefined) return ''
673
700
  return error instanceof Error ? error.message : String(error)
@@ -837,6 +864,53 @@ window.__ModuleLoader__.load({
837
864
  return lines.map(parseLine)
838
865
  }
839
866
 
867
+ /**
868
+ * Whether one parsed log line declares a level the viewer's filter wants.
869
+ * @param {{level?: string}} line - one `parseLog` entry.
870
+ * @param {'all'|'warn'|'error'} filter - the viewer's current filter.
871
+ * @returns {boolean} true when the line's own level passes.
872
+ */
873
+ function logLineVisible(line, filter) {
874
+ if (filter !== 'warn' && filter !== 'error') return true
875
+ var level = line !== null && line !== undefined && typeof line.level === 'string' ? line.level.toUpperCase() : ''
876
+ if (level === 'ERROR' || level === 'FATAL') return true
877
+ return filter === 'warn' && (level === 'WARN' || level === 'WARNING')
878
+ }
879
+
880
+ /** The raw text of one parsed line (parts joined, no styles). */
881
+ function logLineText(line) {
882
+ if (line === null || line === undefined || Array.isArray(line.parts) !== true) return ''
883
+ return line.parts.map(function (part) { return part.text }).join('')
884
+ }
885
+
886
+ /**
887
+ * Apply the viewer's level filter to parsed lines. A line with no level of its
888
+ * own is kept while it is INDENTED right after a kept line: stack traces and
889
+ * multi-line messages are continuations, not levels, and hiding them would
890
+ * turn one ERROR into an isolated header.
891
+ * @param {Array<{level?: string, parts: Array}>} lines - `parseLog` output.
892
+ * @param {'all'|'warn'|'error'} filter - the viewer's current filter.
893
+ * @returns {Array} the lines to render.
894
+ */
895
+ function filterLogLines(lines, filter) {
896
+ if (filter !== 'warn' && filter !== 'error') return lines
897
+ var kept = []
898
+ var carry = false
899
+ lines.forEach(function (line) {
900
+ if (logLineVisible(line, filter) === true) {
901
+ kept.push(line)
902
+ carry = true
903
+ return
904
+ }
905
+ if (carry === true && /^\s/.test(logLineText(line)) === true) {
906
+ kept.push(line)
907
+ return
908
+ }
909
+ carry = false
910
+ })
911
+ return kept
912
+ }
913
+
840
914
  /**
841
915
  * Whether a double click belongs to the pane TITLE (and should therefore
842
916
  * toggle that pane's maximised state). Every pane header also carries
@@ -1219,11 +1293,16 @@ window.__ModuleLoader__.load({
1219
1293
  /** Program workbench: a collapsible debug pane above the reused log viewer. */
1220
1294
  workbench: { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0 },
1221
1295
  /** Left identity block: shrinks (ellipsis on the path) before anything else. */
1296
+ /** Console program rows carry the same horizontal inset before/after they are
1297
+ * picked: the highlight is a background wash only, with no extra border or
1298
+ * padding, so selecting a row never nudges its content sideways. */
1299
+ consoleRow: {
1300
+ display: 'flex', alignItems: 'center', gap: 6, padding: '1px 6px', borderRadius: 3,
1301
+ },
1222
1302
  /** The console row of the program both panes currently show. */
1223
1303
  consoleRowOn: {
1224
- display: 'flex', alignItems: 'center', gap: 6, padding: '1px 4px', borderRadius: 3,
1304
+ display: 'flex', alignItems: 'center', gap: 6, padding: '1px 6px', borderRadius: 3,
1225
1305
  background: 'color-mix(in srgb, currentColor 14%, transparent)',
1226
- boxShadow: 'inset 2px 0 0 #d29922',
1227
1306
  },
1228
1307
  /** Status-bar 💬 button: modest, with a count when there are unread messages. */
1229
1308
  messageButton: {
@@ -1316,6 +1395,29 @@ window.__ModuleLoader__.load({
1316
1395
  background: 'transparent', color: 'inherit', borderRadius: 4,
1317
1396
  border: '1px solid color-mix(in srgb, currentColor 22%, transparent)',
1318
1397
  },
1398
+ /**
1399
+ * The log pane's own find bar. It mirrors the editor's two-row find panel
1400
+ * (`SEARCH_PANEL_CSS` / `ideFindPanel`): same 22px control height, same chip
1401
+ * look for the arrows and the close button, same tabular match counter — the
1402
+ * two find surfaces used to disagree in height and button size.
1403
+ */
1404
+ logFindBar: {
1405
+ display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'nowrap',
1406
+ padding: '5px 6px', fontSize: 12,
1407
+ borderBottom: '1px solid color-mix(in srgb, currentColor 12%, transparent)',
1408
+ },
1409
+ logFindInput: {
1410
+ flex: '1 1 auto', minWidth: 0, height: 22, boxSizing: 'border-box', font: 'inherit', fontSize: 12, padding: '0 6px',
1411
+ color: 'inherit', background: 'color-mix(in srgb, Canvas 99%, transparent)',
1412
+ border: '1px solid color-mix(in srgb, currentColor 20%, transparent)', borderRadius: 3, outline: 'none',
1413
+ },
1414
+ logFindChip: {
1415
+ height: 22, width: 24, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
1416
+ background: 'color-mix(in srgb, currentColor 6%, transparent)', color: 'inherit',
1417
+ border: '1px solid color-mix(in srgb, currentColor 14%, transparent)', borderRadius: 3,
1418
+ font: 'inherit', fontSize: 11, lineHeight: 1, cursor: 'pointer', opacity: 0.9,
1419
+ },
1420
+ logFindCount: { fontSize: 11, opacity: 0.62, fontVariantNumeric: 'tabular-nums', minWidth: 36, textAlign: 'right' },
1319
1421
  /** Workspace path in the top bar: one line, ellipsis when long. */
1320
1422
  headPath: { flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 600 },
1321
1423
  /** "已暂停" pill next to the path. */
@@ -1423,6 +1525,43 @@ window.__ModuleLoader__.load({
1423
1525
  },
1424
1526
  treeRow: { display: 'flex', alignItems: 'center', gap: 4, padding: '0 6px', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden' },
1425
1527
  treeRowOn: { display: 'flex', alignItems: 'center', gap: 4, padding: '0 6px', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', background: 'color-mix(in srgb, currentColor 12%, transparent)' },
1528
+ /** Extra rows of a multi-selection (the primary keeps `treeRowOn`). */
1529
+ /** 「↑ 上级」行(文件树根被点到子目录时出现)。 */
1530
+ treeUpRow: { display: 'flex', alignItems: 'center', gap: 4, padding: '0 6px', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', opacity: 0.85 },
1531
+ /** Add/remove rows of the editor's diff view. */
1532
+ diffAdd: { background: 'rgba(63,185,80,0.18)' },
1533
+ diffDel: { background: 'rgba(248,81,73,0.18)' },
1534
+ /** Diff / test output float ABOVE the editor instead of replacing it: the
1535
+ * CodeMirror instance keeps its document and undo history the whole time,
1536
+ * so 「回到编辑」 returns to the exact edit stack. Opaque so the editor
1537
+ * underneath never shows through. */
1538
+ paneOverlay: {
1539
+ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, zIndex: 3,
1540
+ display: 'flex', flexDirection: 'column', minHeight: 0,
1541
+ background: 'color-mix(in srgb, Canvas 96%, currentColor 4%)',
1542
+ },
1543
+ /** Scrollable body of an overlay pane: `pre` keeps code columns aligned,
1544
+ * `overflow: auto` scrolls long lines instead of clipping them. */
1545
+ paneScroll: {
1546
+ flex: '1 1 auto', minHeight: 0, margin: 0, overflow: 'auto',
1547
+ fontFamily: 'inherit', padding: '4px 8px', whiteSpace: 'pre',
1548
+ },
1549
+ diffLine: { display: 'flex', gap: 6, whiteSpace: 'pre', minWidth: '100%' },
1550
+ diffNum: { flex: '0 0 auto', width: 34, textAlign: 'right', opacity: 0.45, userSelect: 'none' },
1551
+ diffSign: { flex: '0 0 auto', width: 10, opacity: 0.8 },
1552
+ treeRowMulti: { display: 'flex', alignItems: 'center', gap: 4, padding: '0 6px', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', background: 'color-mix(in srgb, #d29922 18%, transparent)' },
1553
+ /**
1554
+ * Multi-selection read-out above the rows: batch operations are keyboard-only
1555
+ * and silent, so without a count the user cannot tell a 2-row selection from a
1556
+ * 40-row one (PM review P1-3).
1557
+ */
1558
+ treeSelectionBar: {
1559
+ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto',
1560
+ padding: '2px 6px', minHeight: 22,
1561
+ borderBottom: '1px solid color-mix(in srgb, currentColor 12%, transparent)',
1562
+ background: 'color-mix(in srgb, #d29922 14%, transparent)',
1563
+ fontSize: '0.9em',
1564
+ },
1426
1565
  treeTwist: { width: 12, flex: '0 0 auto', opacity: 0.7 },
1427
1566
  /** Folded-chain separator: bold + a 1.5px halo makes the dot readable on dark. */
1428
1567
  foldSeparator: { fontWeight: 700, padding: '0 0.5px', textShadow: '0 0 1.5px currentColor' },
@@ -1487,9 +1626,16 @@ window.__ModuleLoader__.load({
1487
1626
  fontFamily: 'system-ui, -apple-system, Segoe UI, sans-serif', fontSize: 12,
1488
1627
  },
1489
1628
  /** Right-aligned 预览 / 编辑 switch directly above the file's editor area. */
1490
- previewToggleBar: {
1491
- flex: '0 0 auto', display: 'flex', justifyContent: 'flex-end', alignItems: 'center',
1492
- padding: '2px 6px 0',
1629
+ /**
1630
+ * The 预览/编辑 toggle floats over the editor's TOP-RIGHT corner instead of
1631
+ * taking a strip above the code (user口径: 不要面板,悬浮在右上角): the code
1632
+ * starts at the very top and the chip only covers what it must.
1633
+ */
1634
+ previewFloat: {
1635
+ position: 'absolute', top: 4, right: 6, zIndex: 4, display: 'flex', gap: 4,
1636
+ padding: '1px 2px', borderRadius: 4,
1637
+ background: 'color-mix(in srgb, Canvas 88%, transparent)',
1638
+ border: '1px solid color-mix(in srgb, currentColor 16%, transparent)',
1493
1639
  },
1494
1640
  previewBody: {
1495
1641
  flex: '1 1 0', minHeight: 0, overflow: 'auto', padding: '10px 14px',
@@ -1954,7 +2100,12 @@ window.__ModuleLoader__.load({
1954
2100
  setHasMore(view.more === true || (typeof view.from === 'number' && view.from > 0) || (typeof view.elided === 'number' && view.elided > 0))
1955
2101
  }, [view.ok, view.from, view.elided, view.more, path])
1956
2102
 
1957
- var lines = React.useMemo(function () { return parseLog(view.content) }, [view.content])
2103
+ // Level filter (PM gap #4): hide lines at render time so the find bar and the
2104
+ // 「N/M」counters only ever see what the user can actually look at.
2105
+ var filterLevel = props.level === 'warn' || props.level === 'error' ? props.level : 'all'
2106
+ var lines = React.useMemo(function () {
2107
+ return filterLogLines(parseLog(view.content), filterLevel)
2108
+ }, [view.content, filterLevel])
1958
2109
  var lineTexts = React.useMemo(function () {
1959
2110
  return lines.map(function (line) { return line.parts.map(function (part) { return part.text }).join('') })
1960
2111
  }, [lines])
@@ -2114,13 +2265,14 @@ window.__ModuleLoader__.load({
2114
2265
  }
2115
2266
  },
2116
2267
  'data-wrap': wrap ? 'on' : 'off',
2268
+ 'data-log-level': filterLevel,
2117
2269
  'data-service': canStop ? 'running' : service === undefined ? 'none' : 'stopped',
2118
2270
  },
2119
2271
  findOpen
2120
- ? h('div', { style: { display: 'flex', alignItems: 'center', gap: 4, padding: '2px 4px', borderBottom: '1px solid rgba(127,127,127,0.25)' }, 'data-log-find-bar': '1' },
2272
+ ? h('div', { style: S.logFindBar, 'data-log-find-bar': '1' },
2121
2273
  h('input', {
2122
2274
  ref: findInputRef, type: 'search', value: findText, placeholder: '在日志中查找(Enter 下一个,Shift+Enter 上一个)',
2123
- style: Object.assign({}, S.headSearch, { flex: '1 1 auto', minWidth: 0 }),
2275
+ style: S.logFindInput,
2124
2276
  'data-log-find': '1',
2125
2277
  onChange: function (event) { setFindText(event.target.value); setFindIndex(0) },
2126
2278
  onKeyDown: function (event) {
@@ -2138,24 +2290,24 @@ window.__ModuleLoader__.load({
2138
2290
  }
2139
2291
  },
2140
2292
  }),
2141
- h('span', { style: S.meta, 'data-log-find-count': '1' },
2293
+ h('span', { style: S.logFindCount, 'data-log-find-count': '1' },
2142
2294
  findText === '' ? '' : (findMatches.length === 0 ? '0/0' : (Math.min(findIndex, findMatches.length - 1) + 1) + '/' + findMatches.length)),
2143
2295
  h('button', {
2144
- type: 'button', style: S.button, 'data-action': 'log-find-prev', title: '上一个(Shift+Enter)',
2296
+ type: 'button', style: S.logFindChip, 'data-action': 'log-find-prev', title: '上一个(Shift+Enter)',
2145
2297
  onClick: function () {
2146
2298
  if (findMatches.length === 0) return
2147
2299
  setFindIndex(function (previous) { return (previous - 1 + findMatches.length) % findMatches.length })
2148
2300
  },
2149
2301
  }, '↑'),
2150
2302
  h('button', {
2151
- type: 'button', style: S.button, 'data-action': 'log-find-next', title: '下一个(Enter)',
2303
+ type: 'button', style: S.logFindChip, 'data-action': 'log-find-next', title: '下一个(Enter)',
2152
2304
  onClick: function () {
2153
2305
  if (findMatches.length === 0) return
2154
2306
  setFindIndex(function (previous) { return (previous + 1) % findMatches.length })
2155
2307
  },
2156
2308
  }, '↓'),
2157
2309
  h('button', {
2158
- type: 'button', style: Object.assign({}, S.buttonOff, { padding: '0 4px' }), 'data-action': 'log-find-close', title: '关闭查找(Esc)',
2310
+ type: 'button', style: S.logFindChip, 'data-action': 'log-find-close', title: '关闭查找(Esc)',
2159
2311
  onClick: function () { setFindOpen(false); setFindText('') },
2160
2312
  }, '×'))
2161
2313
  : null,
@@ -2302,6 +2454,46 @@ window.__ModuleLoader__.load({
2302
2454
  return viewerState !== undefined && viewerState.dirty === true
2303
2455
  }
2304
2456
 
2457
+ /**
2458
+ * Line-level LCS diff for the "what did I actually change" view (PM gap #5).
2459
+ * Deliberately tiny and dependency-free; a pathological pair (over four million
2460
+ * line pairs) degrades to "everything replaced" instead of freezing the window.
2461
+ * @param {string} oldText - the saved copy (what is on disk).
2462
+ * @param {string} newText - the buffer's current text.
2463
+ * @returns {Array<{kind: 'same'|'add'|'del', text: string}>} rows in file order.
2464
+ */
2465
+ function lineDiff(oldText, newText) {
2466
+ var before = String(oldText === undefined || oldText === null ? '' : oldText).split('\n')
2467
+ var after = String(newText === undefined || newText === null ? '' : newText).split('\n')
2468
+ if (before.length === 1 && before[0] === '' && after.length === 1 && after[0] === '') return []
2469
+ if (before.length * after.length > 4000000) {
2470
+ return before.map(function (text) { return { kind: 'del', text: text } })
2471
+ .concat(after.map(function (text) { return { kind: 'add', text: text } }))
2472
+ }
2473
+ var table = [new Array(after.length + 1).fill(0)]
2474
+ for (var rowIndex = 1; rowIndex <= before.length; rowIndex += 1) {
2475
+ var row = new Array(after.length + 1).fill(0)
2476
+ var previous = table[rowIndex - 1]
2477
+ for (var column = 1; column <= after.length; column += 1) {
2478
+ row[column] = before[rowIndex - 1] === after[column - 1]
2479
+ ? previous[column - 1] + 1
2480
+ : Math.max(previous[column], row[column - 1])
2481
+ }
2482
+ table.push(row)
2483
+ }
2484
+ var rows = []
2485
+ var x = before.length
2486
+ var y = after.length
2487
+ while (x > 0 && y > 0) {
2488
+ if (before[x - 1] === after[y - 1]) { rows.push({ kind: 'same', text: before[x - 1] }); x -= 1; y -= 1 }
2489
+ else if (table[x - 1][y] >= table[x][y - 1]) { rows.push({ kind: 'del', text: before[x - 1] }); x -= 1 }
2490
+ else { rows.push({ kind: 'add', text: after[y - 1] }); y -= 1 }
2491
+ }
2492
+ while (x > 0) { rows.push({ kind: 'del', text: before[x - 1] }); x -= 1 }
2493
+ while (y > 0) { rows.push({ kind: 'add', text: after[y - 1] }); y -= 1 }
2494
+ return rows.reverse()
2495
+ }
2496
+
2305
2497
  /**
2306
2498
  * The panel-wide chord that focuses the workspace search.
2307
2499
  * Ctrl+R was tried first but DSH itself binds it; Ctrl+F belongs to editors.
@@ -2763,10 +2955,10 @@ window.__ModuleLoader__.load({
2763
2955
  title: '通用',
2764
2956
  rows: [
2765
2957
  { keys: 'Ctrl+S', desc: '保存当前文件' },
2766
- { keys: 'Ctrl+W', desc: '关闭当前页签(有未保存修改会先确认)' },
2767
- { keys: 'Ctrl+R / F3', desc: '聚焦工作空间文件检索框(面板内会屏蔽浏览器刷新;编辑器内 Ctrl+F 是文件内查找)' },
2768
- { keys: 'Ctrl+W / Alt+W', desc: '关闭当前源码页签(浏览器抢占 Ctrl+W 时用 Alt+W,Ctrl+F4 亦可)' },
2769
- { keys: '焦点在 IDE 内时', desc: 'DSH 自身的单修饰键快捷键被屏蔽,浏览器右键菜单也不弹出(编辑器/输入框内不拦截)' },
2958
+ { keys: 'Alt+W', desc: '关闭当前源码页签(有未保存修改会先确认);Ctrl+W 是浏览器保留键,页面拦不住' },
2959
+ { keys: 'Ctrl+R / Ctrl+Shift+R / F3', desc: '聚焦工作空间文件检索框(只在 RIS-IDE 自己的独立窗口里接管,那里同时屏蔽浏览器刷新/强制刷新;DSH 页面上的 Ctrl+R 仍归浏览器)' },
2960
+ { keys: '焦点在 IDE 内时', desc: '独立窗口内的单键快捷键由面板接管,浏览器右键菜单也不弹出(编辑器/输入框内不拦截)' },
2961
+ { keys: '有未保存页签时关闭/刷新页面', desc: '浏览器会先弹确认(IDE 页面自己拦的,避免误关丢改动)' },
2770
2962
  { keys: '双击标题', desc: '最大化 / 还原该面板' },
2771
2963
  { keys: '拖分隔条', desc: '调整左列 / 调试区 / 下层的尺寸' },
2772
2964
  ],
@@ -2775,24 +2967,57 @@ window.__ModuleLoader__.load({
2775
2967
  title: '文件树',
2776
2968
  rows: [
2777
2969
  { keys: '右键', desc: '新建文件(Java/JS/Vue/XML/YAML…)、新建文件夹、粘贴、复制、剪切、删除、刷新、复制文件名/路径' },
2778
- { keys: 'Del', desc: '删除(移入回收站,可撤销)' },
2779
- { keys: 'Ctrl+Z', desc: '撤销文件操作:删除 / 新建 / 粘贴 / 移动' },
2780
- { keys: 'Ctrl+C / X / V', desc: '复制 / 剪切 / 粘贴' },
2781
- { keys: '拖放', desc: '拖到文件夹或文件上移动(文件 = 移到它所在目录);拖到树空白处移到工作区根' },
2970
+ { keys: 'Ctrl+点击', desc: '多选文件/文件夹(再点一次取消);Ctrl+A 全选当前可见行;选中多项时树顶显示「已选 N 项」,Esc 清空' },
2971
+ { keys: 'Del', desc: '删除(移入回收站,可撤销;提示条里带「撤销」按钮);多选时删除所选全部' },
2972
+ { keys: 'Ctrl+Z', desc: '撤销文件操作:删除 / 新建 / 粘贴 / 移动(焦点需在文件树内,或直接点提示条里的「撤销」)' },
2973
+ { keys: 'Ctrl+C / X / V', desc: '复制 / 剪切 / 粘贴文件或文件夹——焦点在文件树内才算文件操作(日志/编辑器里是普通文本操作);多选时批量;重名自动生成「 副本」/「 副本(n)」并用一条提示说明;单条粘贴撞名弹「粘贴为」预填「A - 副本.java」' },
2974
+ { keys: '拖放', desc: '拖到文件夹或文件上移动(文件 = 移到它所在目录);拖到树空白处移到工作区根;拖多选中的任意一行 = 移动整个选择' },
2975
+ { keys: '点击文件夹', desc: '展开/折叠该目录(同三角 ▸/▾);右键「进入」= 把这个目录当作文件树根(行首出现「↑ 上级」逐级返回工作区根)' },
2782
2976
  { keys: '⟳ / ⌖', desc: '标题栏:刷新文件树 / 定位当前文件' },
2783
2977
  ],
2784
2978
  },
2979
+ {
2980
+ title: '检索',
2981
+ rows: [
2982
+ { keys: '输入', desc: '检索框同时搜**文件名**和**文件内容**:文件行图标 📄/▸,内容行图标 ≡ 并显示 `路径:行号 文本`;内容搜索是 `git grep`(无索引),比文件名稍慢,最多 200 条' },
2983
+ { keys: '↑ / ↓', desc: '在文件行与内容行之间连续移动高亮(不影响输入框光标,可继续打字);默认高亮「文件名完全匹配」的行,否则第一行' },
2984
+ { keys: 'Enter', desc: '打开高亮结果:文件直接打开;内容结果打开文件并**自动在编辑器里填入该检索词并执行一次 find**,光标落到命中行' },
2985
+ { keys: 'Esc', desc: '关闭下拉;再按一次清空检索词' },
2986
+ { keys: '最近打开', desc: '检索框为空且聚焦时,下拉显示最近打开的文件,↑/↓ + Enter 也能选' },
2987
+ ],
2988
+ },
2785
2989
  {
2786
2990
  title: '编辑器',
2787
2991
  rows: [
2788
2992
  { keys: '右键', desc: '撤销/重做、剪切/复制/粘贴、全选、注释、缩进、删除行、插入行、上下移行、查找、转到行、保存' },
2789
2993
  { keys: 'Ctrl+Z / Ctrl+Shift+Z', desc: '撤销 / 重做(退回到保存内容时页签 * 消失)' },
2790
- { keys: 'Ctrl+Shift+K', desc: '删除当前行' },
2994
+ { keys: 'Ctrl+D / Ctrl+Shift+K', desc: '删除当前行(多行选中时删除整段)' },
2791
2995
  { keys: 'Alt+↑ / Alt+↓', desc: '上移 / 下移当前行' },
2792
2996
  { keys: 'Ctrl+/', desc: '注释 / 取消注释' },
2793
- { keys: 'Ctrl+F', desc: '查找 / 替换' },
2997
+ { keys: 'Ctrl+F', desc: '查找 / 替换(面板两行:查找一行、替换一行;↑/↓ 上/下一个,Aa 区分大小写,.* 正则,ab 全词,⇥ 替换 / ⇥⇥ 全部替换,右侧显示匹配数)' },
2794
2998
  { keys: 'Ctrl+G', desc: '转到行' },
2795
2999
  { keys: 'Tab / Shift+Tab', desc: '增加 / 减少缩进' },
3000
+ { keys: '± ', desc: '标题栏 ±:与磁盘版本逐行对比(+ 新增 / − 删除),只在有未保存修改时可用;「回到编辑」返回' },
3001
+ { keys: '▶ 运行测试', desc: '打开 `src/test/java/**/xxxTest.java` 时标题栏出现 ▶:执行 `mvn -pl <module> test -Dtest=<全限定类名>`(以工作区第一段为 Maven reactor 根),输出面板显示结果,可重新运行' },
3002
+ ],
3003
+ },
3004
+ {
3005
+ title: '日志',
3006
+ rows: [
3007
+ { keys: 'Ctrl+F', desc: '日志内查找(高亮命中,Enter 跳下一个;Esc 关闭)' },
3008
+ { keys: '换行', desc: '日志标题栏的「自动换行」按钮:长行折行 / 保持原样,选择会被记住' },
3009
+ { keys: 'A− / A+', desc: '日志字号(与编辑器共用同一字号偏好)' },
3010
+ { keys: '跟随', desc: '标题栏「跟随」开关:关掉后新日志不再把视图拉到底,方便回看旧内容' },
3011
+ { keys: '级 / W+ / E+', desc: '日志级别过滤:全部 → WARN 及以上 → ERROR 及以上;缩进的堆栈/续行跟着上一行一起保留' },
3012
+ { keys: '本次启动', desc: '日志默认只看本次启动(按启动分隔行裁剪),滚到顶部可加载更早内容;未运行时也能看历史日志' },
3013
+ ],
3014
+ },
3015
+ {
3016
+ title: '配置',
3017
+ rows: [
3018
+ { keys: '📄 / ⚙', desc: '在控制台标题栏:📄 打开 .dsh-ris-ide.json,⚙ 按当前扫描结果生成/更新(你改过的字段与自定义程序保留)' },
3019
+ { keys: '.dsh-ris-ide.json', desc: '在工作区根,是隐藏文件——文件树和检索里都看不到,用 📄 打开;defaults.jvmArgs 与每个程序的 jvmArgs / startCommand 都写这里' },
3020
+ { keys: '生效时间', desc: '保存后约 3 秒被读取;jvmArgs 改动要重启该程序才生效' },
2796
3021
  ],
2797
3022
  },
2798
3023
  {
@@ -2807,8 +3032,9 @@ window.__ModuleLoader__.load({
2807
3032
  title: '使用说明',
2808
3033
  rows: [
2809
3034
  { keys: '启动服务', desc: '控制台点该行的 ▶ 启动、■ 停止、调试图标(bug + ▶);日志区自动跟随选中程序' },
3035
+ { keys: '批量启停', desc: '控制台每行左侧复选框,勾选 2 行以上时标题栏出现「已勾选 N 项」+ ▶ / ■:按列表顺序启动、倒序停止,自动跳过已在运行/已停止的;⟳ 是重启该程序' },
2810
3036
  { keys: '看日志', desc: '只有运行中的程序流式加载日志;未运行也能看历史日志' },
2811
- { keys: '配置文件', desc: '源码标题栏 📄 打开 .dsh-ris-ide.json(jvmArgs / startCommand),⚙ 按扫描结果更新' },
3037
+ { keys: '配置文件', desc: '控制台标题栏 📄/⚙(独立窗口与右侧栏控制台都有);首次自动生成、手动同步、工作区漂移都会在面板顶部给出提示' },
2812
3038
  { keys: '官方预览', desc: 'pdf / doc / xlsx 等会自动用 DSH 官方预览标签打开;.md / .html 在编辑器标题栏点 👁 预览' },
2813
3039
  ],
2814
3040
  },
@@ -2870,6 +3096,48 @@ window.__ModuleLoader__.load({
2870
3096
  return raw.slice(0, dot) + suffix + raw.slice(dot)
2871
3097
  }
2872
3098
 
3099
+ /**
3100
+ * Name for a copy whose plain target name is already taken: the first
3101
+ * candidate keeps the name plus ` 副本` (`A.java` → `A 副本.java`), later ones
3102
+ * add an index (`A 副本(2).java`, `A 副本(3).java`). Folders take the suffix
3103
+ * whole (`pkg` → `pkg 副本`). This is the convention the BATCH paste/move
3104
+ * collision path uses (the single-entry 粘贴为 prompt keeps ` - 副本`).
3105
+ * @param {string} name - leaf name of the source entry.
3106
+ * @param {boolean} isDir - folders have no extension to preserve.
3107
+ * @param {number} [index] - 1 = ` 副本`, 2 = ` 副本(2)`, … (1-based).
3108
+ * @returns {string} the collision-safe candidate name.
3109
+ */
3110
+ function collisionCopyName(name, isDir, index) {
3111
+ var raw = String(name === undefined || name === null ? '' : name).trim()
3112
+ if (raw === '') return 'copy'
3113
+ var number = Math.max(1, Math.floor(Number(index) || 1))
3114
+ var suffix = ' 副本' + (number > 1 ? '(' + number + ')' : '')
3115
+ if (isDir === true) return raw + suffix
3116
+ // Keep a dotfile (`.gitignore`) whole; otherwise insert before the last dot.
3117
+ var dot = raw.lastIndexOf('.')
3118
+ if (dot <= 0) return raw + suffix
3119
+ return raw.slice(0, dot) + suffix + raw.slice(dot)
3120
+ }
3121
+
3122
+ /**
3123
+ * Ctrl/Cmd+click membership toggle for the tree's multi-selection.
3124
+ *
3125
+ * The list is ordered (the LAST entry is the primary selection that menus,
3126
+ * rename/delete and the paste target keep acting on); toggling an entry off
3127
+ * keeps every other entry. Returns a NEW array so React sees the change.
3128
+ * @param {string[]} paths - current selection, absolute paths.
3129
+ * @param {string} path - the row that was Ctrl+clicked.
3130
+ * @returns {string[]} the new selection.
3131
+ */
3132
+ function toggleTreeSelection(paths, path) {
3133
+ var list = Array.isArray(paths) ? paths.slice() : []
3134
+ if (typeof path !== 'string' || path === '') return list
3135
+ var at = list.indexOf(path)
3136
+ if (at === -1) list.push(path)
3137
+ else list.splice(at, 1)
3138
+ return list
3139
+ }
3140
+
2873
3141
  /** Colour kind of one tree entry (`dir` for folders, `dot` for dot-entries). */
2874
3142
  function fileKind(entry) {
2875
3143
  if (entry === null || entry === undefined) return 'other'
@@ -3031,11 +3299,36 @@ window.__ModuleLoader__.load({
3031
3299
  * the panel so the arrow keys work while the SEARCH BOX keeps focus: hovering a
3032
3300
  * row only reports itself (`props.onHover`), it never touches focus or the caret.
3033
3301
  */
3302
+ /**
3303
+ * The workspace search dropdown: file-name matches first, then CONTENT hits
3304
+ * (PM gap #2). Two row kinds share ONE highlighted index (`props.active`) so
3305
+ * ↓/↑ walks the whole list; the leading icon tells them apart (📄 file vs ≡
3306
+ * content line) exactly like the search itself is two different questions.
3307
+ */
3308
+ /** Rows the file-search dropdown paints before the user scrolls (a content search can return hundreds). */
3309
+ var SEARCH_ROWS_FIRST = 40
3310
+ /** Rows appended each time the dropdown is scrolled near its bottom. */
3311
+ var SEARCH_ROWS_MORE = 60
3312
+
3034
3313
  function SearchResults(props) {
3035
3314
  var S = stylesFor(props && typeof props.fontRatio === 'number' ? props.fontRatio : 1)
3036
3315
  var hits = props.hits
3316
+ var content = Array.isArray(props.content) ? props.content : []
3037
3317
  var cwd = typeof props.cwd === 'string' ? props.cwd : ''
3038
3318
  var active = typeof props.active === 'number' ? props.active : -1
3319
+ var fileMatches = hits !== null && hits !== undefined && Array.isArray(hits.matches) ? hits.matches : []
3320
+ var dirs = hits !== null && hits !== undefined && hits.dirs !== null && hits.dirs !== undefined ? hits.dirs : {}
3321
+ // One row model for both lists, so the keyboard walks exactly what is drawn.
3322
+ var rows = []
3323
+ var index = 0
3324
+ fileMatches.forEach(function (path) {
3325
+ rows.push({ kind: 'path', path: path, isDir: dirs[path] === true, index: index })
3326
+ index += 1
3327
+ })
3328
+ content.forEach(function (hit) {
3329
+ rows.push({ kind: 'content', hit: hit, index: index })
3330
+ index += 1
3331
+ })
3039
3332
  // Keep the highlighted row inside the dropdown's OWN scroll box: the list is
3040
3333
  // `overflow:auto`, so its scrollTop moves and the page never scrolls.
3041
3334
  var listRef = useRef(null)
@@ -3048,30 +3341,79 @@ window.__ModuleLoader__.load({
3048
3341
  var rect = row.getBoundingClientRect()
3049
3342
  var next = revealScrollTop(rect.top, rect.bottom, box.top, box.bottom, list.scrollTop)
3050
3343
  if (next !== list.scrollTop) list.scrollTop = next
3051
- }, [active, hits])
3344
+ }, [active, hits, content])
3345
+ // A content search can return hundreds of rows; painting them all — on every
3346
+ // debounce tick and again on every re-open — is what made "search, then come
3347
+ // back to the box" feel slow. Paint a window instead: append when the list is
3348
+ // scrolled near its bottom, and widen it when the keyboard walks past the end.
3349
+ var [rowLimit, setRowLimit] = useState(SEARCH_ROWS_FIRST)
3350
+ useEffect(function () {
3351
+ setRowLimit(SEARCH_ROWS_FIRST)
3352
+ }, [hits, content])
3353
+ useEffect(function () {
3354
+ if (active < 0 || active < rowLimit) return
3355
+ setRowLimit(Math.min(rows.length, Math.max(rowLimit + SEARCH_ROWS_MORE, active + 1)))
3356
+ }, [active, rowLimit, rows.length])
3052
3357
  if (hits === null || hits === undefined) return null
3053
- var rows
3358
+ var headerText = props.busy === true
3359
+ ? '检索中…'
3360
+ : '匹配 ' + (fileMatches.length + content.length) + ' 个'
3361
+ + (props.contentBusy === true ? ',内容检索中…' : '')
3362
+ + (content.length > 0 && props.contentBusy !== true
3363
+ ? '(文件 ' + fileMatches.length + ' · 内容 ' + content.length + ' 处)'
3364
+ : '')
3365
+ var rowsNode
3054
3366
  if (hits.error !== undefined) {
3055
- rows = [h('div', { key: 'err', style: S.idePlaceholder }, '检索失败:' + hits.error)]
3056
- } else if (!Array.isArray(hits.matches) || hits.matches.length === 0) {
3057
- rows = [h('div', { key: 'none', style: S.idePlaceholder }, '没有匹配的文件')]
3367
+ rowsNode = [h('div', { key: 'err', style: S.idePlaceholder }, '检索失败:' + hits.error)]
3368
+ } else if (rows.length === 0) {
3369
+ rowsNode = [h('div', { key: 'none', style: S.idePlaceholder },
3370
+ props.contentBusy === true ? '正在检索文件内容…' : '没有匹配的文件或内容')]
3058
3371
  } else {
3059
- rows = hits.matches.map(function (path, index) {
3060
- var isDir = hits.dirs !== undefined && hits.dirs !== null && hits.dirs[path] === true
3061
- var isActive = index === active
3372
+ rowsNode = rows.slice(0, rowLimit).map(function (row) {
3373
+ var isActive = row.index === active
3374
+ var onHover = function () { if (typeof props.onHover === 'function') props.onHover(row.index) }
3375
+ var onClick
3376
+ if (row.kind === 'content') {
3377
+ onClick = function () { props.onPick({ kind: 'content', hit: row.hit, query: props.query }) }
3378
+ return h('div', {
3379
+ key: 'content:' + row.hit.path + ':' + row.hit.line,
3380
+ style: isActive ? Object.assign({}, S.searchRow, S.searchRowOn) : S.searchRow,
3381
+ title: row.hit.path + ':' + row.hit.line,
3382
+ 'data-search-hit': 'content',
3383
+ 'data-search-hit-path': row.hit.path,
3384
+ 'data-search-line': String(row.hit.line),
3385
+ 'data-search-hit-active': isActive ? '1' : '0',
3386
+ onMouseEnter: onHover,
3387
+ onClick: onClick,
3388
+ },
3389
+ h('span', { style: { opacity: 0.7, flex: '0 0 auto', width: 12 }, title: '内容匹配', 'data-search-hit-icon': 'content' }, '≡'),
3390
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
3391
+ displayWorkspacePath(row.hit.path, cwd) + ':' + row.hit.line + ' ' + row.hit.text.trim()))
3392
+ }
3393
+ onClick = function () { props.onPick(row.path, row.isDir) }
3062
3394
  return h('div', {
3063
- key: path,
3395
+ key: row.path,
3064
3396
  style: isActive ? Object.assign({}, S.searchRow, S.searchRowOn) : S.searchRow,
3065
- title: path,
3066
- 'data-search-hit': isDir ? 'dir' : 'file',
3067
- 'data-search-hit-path': path,
3397
+ title: row.path,
3398
+ 'data-search-hit': row.isDir ? 'dir' : 'file',
3399
+ 'data-search-hit-path': row.path,
3068
3400
  'data-search-hit-active': isActive ? '1' : '0',
3069
- onMouseEnter: function () { if (typeof props.onHover === 'function') props.onHover(index) },
3070
- onClick: function () { props.onPick(path, isDir) },
3401
+ onMouseEnter: onHover,
3402
+ onClick: onClick,
3071
3403
  },
3072
- h('span', { style: { opacity: 0.55, flex: '0 0 auto' } }, isDir ? '▸' : '·'),
3073
- h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis' } }, displayWorkspacePath(path, cwd)))
3404
+ h('span', {
3405
+ style: { opacity: 0.55, flex: '0 0 auto', width: 12 },
3406
+ 'data-search-hit-icon': row.isDir ? 'dir' : 'file',
3407
+ }, row.isDir ? '▸' : '📄'),
3408
+ h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis' } }, displayWorkspacePath(row.path, cwd)))
3074
3409
  })
3410
+ if (rowLimit < rows.length) {
3411
+ rowsNode.push(h('div', {
3412
+ key: 'more',
3413
+ style: S.idePlaceholder,
3414
+ 'data-search-more': String(rows.length - rowLimit),
3415
+ }, '… 滚动加载更多(剩余 ' + (rows.length - rowLimit) + ' 行)'))
3416
+ }
3075
3417
  }
3076
3418
  return h('div', {
3077
3419
  ref: listRef,
@@ -3080,9 +3422,19 @@ window.__ModuleLoader__.load({
3080
3422
  // caret stays put and the user can keep typing (same trick as the history
3081
3423
  // list above).
3082
3424
  onMouseDown: function (event) { event.preventDefault() },
3425
+ // Lazy rows: near the bottom of the list, append the next window. The header
3426
+ // row and the hint row do not scroll on their own, so `scrollHeight` here is
3427
+ // the whole dropdown box and the threshold keeps the next batch invisible.
3428
+ onScroll: function (event) {
3429
+ var box = event.currentTarget
3430
+ if (box === null || box === undefined) return
3431
+ if (rowLimit >= rows.length) return
3432
+ if (box.scrollTop + box.clientHeight < box.scrollHeight - 120) return
3433
+ setRowLimit(Math.min(rows.length, rowLimit + SEARCH_ROWS_MORE))
3434
+ },
3083
3435
  },
3084
- h('div', { style: S.searchHeader }, props.busy === true ? '检索中…' : ('匹配 ' + (hits.matches ? hits.matches.length : 0) + ' 个')),
3085
- rows)
3436
+ h('div', { style: S.searchHeader }, headerText),
3437
+ rowsNode)
3086
3438
  }
3087
3439
 
3088
3440
  /**
@@ -3273,6 +3625,13 @@ window.__ModuleLoader__.load({
3273
3625
  var scope = props ? props.scope : undefined
3274
3626
  var cwd = scope ? scope.cwd : undefined
3275
3627
  var rootPath = props.rootPath || cwd || '.'
3628
+ /**
3629
+ * 文件树当前的「根」用栈表示:点文件夹行 = 把树切到该目录(user 口径:
3630
+ * 「点击文件夹打开文件树」,不只是折叠展开),行首出现「↑ 上级」逐级弹回;
3631
+ * 弹空即回到 `rootPath`(工作区根)。`rootPath` 本身不变。
3632
+ */
3633
+ var [rootTrail, setRootTrail] = useState([])
3634
+ var activeRoot = rootTrail.length > 0 ? rootTrail[rootTrail.length - 1] : rootPath
3276
3635
  var [expanded, setExpanded] = useState(function () { return {} })
3277
3636
  /** Directories whose FIRST read is in flight (the twisty shows …). */
3278
3637
  var [levels, setLevels] = useState(function () { return {} })
@@ -3301,6 +3660,42 @@ window.__ModuleLoader__.load({
3301
3660
  * watchdog never fights manual scrolling.
3302
3661
  */
3303
3662
  var treeListRef = useRef(null)
3663
+ /** Where the pointer last pressed: the file dialogs open next to it. */
3664
+ var pointerRef = useRef(null)
3665
+ useEffect(function () {
3666
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return undefined
3667
+ function onPointerDown(event) {
3668
+ pointerRef.current = { x: event.clientX, y: event.clientY }
3669
+ }
3670
+ window.addEventListener('pointerdown', onPointerDown, true)
3671
+ return function () { window.removeEventListener('pointerdown', onPointerDown, true) }
3672
+ }, [])
3673
+ /**
3674
+ * The pointer position frozen when the current dialog OPENED. Reading the
3675
+ * live pointer on every render made an anchored dialog jump as soon as the
3676
+ * user pressed the mouse again (the press updates the tracked point, the
3677
+ * click re-renders, and the dialog moved out from under the cursor).
3678
+ */
3679
+ var dialogPointRef = useRef(null)
3680
+ /**
3681
+ * Anchor a tree dialog just right of / below the pointer that opened it,
3682
+ * clamped into the viewport. A centered modal made the eye jump to the middle
3683
+ * of the window right after acting on a row near an edge.
3684
+ * @param {number} width - dialog width in px.
3685
+ * @param {number} height - approximate dialog height in px.
3686
+ * @returns {{left: number, top: number}} viewport coordinates.
3687
+ */
3688
+ function dialogAnchor(width, height) {
3689
+ var point = dialogPointRef.current
3690
+ var vw = typeof window !== 'undefined' && window.innerWidth ? window.innerWidth : 1280
3691
+ var vh = typeof window !== 'undefined' && window.innerHeight ? window.innerHeight : 800
3692
+ var x = point === null || point === undefined ? Math.round(vw / 2 - width / 2) : point.x + 14
3693
+ var y = point === null || point === undefined ? Math.round(vh / 3) : point.y + 10
3694
+ return {
3695
+ left: Math.max(8, Math.min(x, vw - width - 8)),
3696
+ top: Math.max(8, Math.min(y, vh - height - 8)),
3697
+ }
3698
+ }
3304
3699
  var lastGoodTopRef = useRef(0)
3305
3700
  var userInputUntilRef = useRef(0)
3306
3701
  var pointerDownRef = useRef(false)
@@ -3409,7 +3804,9 @@ window.__ModuleLoader__.load({
3409
3804
  inflightRef.current[path] = pending
3410
3805
  return pending
3411
3806
  }
3412
- useEffect(function () { void loadLevel(rootPath, false) }, [rootPath])
3807
+ useEffect(function () { void loadLevel(activeRoot, false) }, [activeRoot])
3808
+ // 换工作区 / 换 base root:栈清空,文件树回到工作区根。
3809
+ useEffect(function () { setRootTrail([]) }, [rootPath])
3413
3810
 
3414
3811
  /** Expand one directory level (idempotent) without opening a file. */
3415
3812
  async function expandDir(path) {
@@ -3429,7 +3826,7 @@ window.__ModuleLoader__.load({
3429
3826
  */
3430
3827
  async function locate(target) {
3431
3828
  var filePath = absolutePath(cwd, target)
3432
- var current = absolutePath(cwd, rootPath)
3829
+ var current = absolutePath(cwd, activeRoot)
3433
3830
  var visited = {}
3434
3831
  for (var guard = 0; guard < 64; guard += 1) {
3435
3832
  if (visited[current] === true) break
@@ -3505,7 +3902,7 @@ window.__ModuleLoader__.load({
3505
3902
  if (props.openFiles.indexOf(selectedPath) !== -1) return
3506
3903
  var entry = findEntry(selectedPath)
3507
3904
  if (entry.isDir === true) return
3508
- setSelectedPath(null)
3905
+ selectOne(null)
3509
3906
  }, [props.openFiles, selectedPath])
3510
3907
 
3511
3908
  // Opening ANOTHER file (tab click, history, search) must move the tree
@@ -3516,7 +3913,7 @@ window.__ModuleLoader__.load({
3516
3913
  var active = typeof props.activePath === 'string' ? props.activePath : ''
3517
3914
  if (active === '') return
3518
3915
  if (selectedPath === active) return
3519
- setSelectedPath(active)
3916
+ selectOne(active)
3520
3917
  }, [props.activePath])
3521
3918
 
3522
3919
  // Keep the input listeners attached to whichever list node is current, and
@@ -3605,25 +4002,45 @@ window.__ModuleLoader__.load({
3605
4002
  var locateRequest = props.locateRequest
3606
4003
  useEffect(function () {
3607
4004
  if (locateRequest === null || locateRequest === undefined) return
3608
- if (locateRequest.kind === 'dir') void expandDir(locateRequest.path)
4005
+ if (locateRequest.kind === 'dir') openDirRoot(locateRequest.path)
3609
4006
  else void locate(locateRequest.path)
3610
4007
  }, [locateRequest === null || locateRequest === undefined ? 0 : locateRequest.nonce])
3611
4008
 
3612
4009
  // ── tree mutations: context menu, prompt, clipboard, drag&drop ────────
3613
4010
  /** Open context menu: `{entry, dir, x, y, sub}`. */
3614
4011
  var [treeMenu, setTreeMenu] = useState(null)
4012
+ /** Hover flyout of 「新建文件」: offset inside the menu box, or null. */
4013
+ var [menuSub, setMenuSub] = useState(null)
4014
+ // Any open/close of the menu invalidates the flyout's anchor.
4015
+ useEffect(function () { setMenuSub(null) }, [treeMenu])
3615
4016
  /** Pending creation dialog: `{mode:'file'|'dir', dir, ext?, title}`. */
3616
4017
  var [prompt, setPrompt] = useState(null)
3617
4018
  var [promptName, setPromptName] = useState('')
4019
+ /** Inline error line inside the prompt card (`''` = none). */
4020
+ var [promptNotice, setPromptNotice] = useState('')
4021
+ /**
4022
+ * A batch paste/move that hit existing names: the card has NO name field,
4023
+ * only 覆盖 (replace them) and 生成副本 (suffix them as `… 副本`).
4024
+ * `{ mode, dir, items, created, origins, touched }`.
4025
+ */
4026
+ var [batchConflict, setBatchConflict] = useState(null)
3618
4027
  /** Pending delete confirmation: the entry to remove. */
3619
4028
  var [pendingDelete, setPendingDelete] = useState(null)
3620
- /** Clipboard for copy/cut: `{mode, path, isDir, name}`. */
4029
+ /** Clipboard for copy/cut: `{mode, items:[{path,isDir,name}]}`. */
3621
4030
  var [clipboard, setClipboard] = useState(null)
3622
4031
  var [selectedPath, setSelectedPath] = useState(null)
4032
+ /**
4033
+ * Ctrl/Cmd+click multi-selection: ordered absolute paths, primary included.
4034
+ * `selectedPath` stays the PRIMARY (menus, rename/delete, paste target);
4035
+ * this list is only what batch copy/cut/move act on.
4036
+ */
4037
+ var [selectedPaths, setSelectedPaths] = useState([])
3623
4038
  var [dropTarget, setDropTarget] = useState(null)
3624
4039
  /** LIFO of invertible file operations (Ctrl+Z). Ref: no re-render needed. */
3625
4040
  var undoStackRef = useRef([])
3626
4041
  var promptInputRef = useRef(null)
4042
+ /** The delete dialog's 取消 button: focus target so Esc/Enter never fall to BODY. */
4043
+ var confirmCancelRef = useRef(null)
3627
4044
  /** Auto-retry bookkeeping for an unreachable/reloading host. */
3628
4045
  var treeRetryRef = useRef({ attempt: 0, timer: null })
3629
4046
  var levelsRef = useRef(levels)
@@ -3652,30 +4069,72 @@ window.__ModuleLoader__.load({
3652
4069
  var name = String(path).slice(String(path).lastIndexOf('/') + 1)
3653
4070
  return { path: path, name: name, isDir: false }
3654
4071
  }
4072
+ /**
4073
+ * Replace the selection with a single row (or clear it): the primary
4074
+ * `selectedPath` AND the multi-selection list always agree.
4075
+ * @param {string|null} path - row to select, or null to clear.
4076
+ */
4077
+ function selectOne(path) {
4078
+ var value = typeof path === 'string' && path !== '' ? path : null
4079
+ setSelectedPath(value)
4080
+ setSelectedPaths(value === null ? [] : [value])
4081
+ }
4082
+ /**
4083
+ * Rows a tree command acts on: the whole multi-selection when `path` is
4084
+ * part of it, otherwise just that one row (a menu/command on an unrelated
4085
+ * row must not silently act on a stale selection).
4086
+ * @param {string} path - the row the command was invoked from.
4087
+ * @returns {string[]} absolute paths, primary last.
4088
+ */
4089
+ function selectionFor(path) {
4090
+ if (typeof path !== 'string' || path === '') return []
4091
+ if (selectedPaths.indexOf(path) !== -1) return selectedPaths.slice()
4092
+ return [path]
4093
+ }
3655
4094
  function notify(message) {
3656
4095
  if (props !== null && props !== undefined && typeof props.onNote === 'function') props.onNote(message)
3657
4096
  }
4097
+ /**
4098
+ * Toast that carries an inline「撤销」button, for operations the undo stack
4099
+ * can invert: expecting the user to remember Ctrl+Z is not a UI.
4100
+ * @param {string} message - the text.
4101
+ * @param {{label: string, run: Function, title?: string}} action - the button.
4102
+ */
4103
+ function notifyWithAction(message, action) {
4104
+ if (props !== null && props !== undefined && typeof props.onActionNote === 'function') props.onActionNote(message, action)
4105
+ else notify(message)
4106
+ }
4107
+ /** The undo button for a toast (LIFO: the operation just done is on top). */
4108
+ function undoAction(title) {
4109
+ return { label: '撤销', title: title, run: function () { return undoLast() } }
4110
+ }
3658
4111
  /** Re-read one directory level in the background (no spinner, no banner). */
3659
4112
  async function refreshLevel(dirPath) {
3660
4113
  await loadLevel(dirPath, true, { background: true })
3661
4114
  }
3662
- /** Reload the root and every expanded folder (title-bar ⟳ / recovery). */
3663
- async function refreshTree() {
3664
- var paths = [absolutePath(cwd, rootPath)].concat(Object.keys(expanded).filter(function (path) { return expanded[path] === true }))
4115
+ /**
4116
+ * Reload the root and every expanded folder.
4117
+ *
4118
+ * @param {boolean} announce - true only for the title bar's ⟳: that click has
4119
+ * no other visible effect, so it confirms with a toast. Background refreshes
4120
+ * (filter mode change, watcher-driven reloads) stay silent — the list itself
4121
+ * is the feedback, and a toast there showed up unasked.
4122
+ */
4123
+ async function refreshTree(announce) {
4124
+ var paths = [absolutePath(cwd, activeRoot)].concat(Object.keys(expanded).filter(function (path) { return expanded[path] === true }))
3665
4125
  var failed = 0
3666
4126
  for (var index = 0; index < paths.length; index += 1) {
3667
4127
  var ok = await loadLevel(paths[index], true)
3668
4128
  if (ok === false) failed += 1
3669
4129
  }
3670
- // The button re-reads silently otherwise (no spinner/loading state), so a
3671
- // short toast is the only confirmation that the click did something.
4130
+ if (announce !== true) return
3672
4131
  notify(failed === 0
3673
4132
  ? '文件树已刷新'
3674
4133
  : ('文件树刷新失败 ' + failed + ' 个目录(其余已更新)'))
3675
4134
  }
3676
4135
  useEffect(function () {
3677
4136
  if (props.refreshNonce === undefined || props.refreshNonce === null || props.refreshNonce === 0) return undefined
3678
- void refreshTree()
4137
+ void refreshTree(props.refreshAnnounce === true)
3679
4138
  return undefined
3680
4139
  }, [props.refreshNonce])
3681
4140
 
@@ -3686,7 +4145,7 @@ window.__ModuleLoader__.load({
3686
4145
  * ignored (nothing to redraw).
3687
4146
  */
3688
4147
  function refreshChanged(relatives) {
3689
- changedLevelsToRefresh(levels, cwd, rootPath, relatives).forEach(function (dir) {
4148
+ changedLevelsToRefresh(levels, cwd, activeRoot, relatives).forEach(function (dir) {
3690
4149
  var now = Date.now()
3691
4150
  var last = treeRefreshAtRef.current[dir] || 0
3692
4151
  if (now - last < TREE_REFRESH_THROTTLE_MS) {
@@ -3758,7 +4217,7 @@ window.__ModuleLoader__.load({
3758
4217
 
3759
4218
  /** Reload the root (and every expanded level) after the host comes back. */
3760
4219
  async function recoverTree() {
3761
- var paths = [rootPath].concat(Object.keys(expanded).filter(function (path) { return expanded[path] === true }))
4220
+ var paths = [activeRoot].concat(Object.keys(expanded).filter(function (path) { return expanded[path] === true }))
3762
4221
  for (var index = 0; index < paths.length; index += 1) await loadLevel(paths[index], true)
3763
4222
  }
3764
4223
  // While an error is on screen, keep retrying by itself: stopping dsh used to
@@ -3815,11 +4274,52 @@ window.__ModuleLoader__.load({
3815
4274
  setPromptName('')
3816
4275
 
3817
4276
  }
4277
+ /** Hand keyboard focus back to the tree (Del / Ctrl+Z / Ctrl+C live there). */
4278
+ function focusTreeRoot() {
4279
+ var node = treeListRef.current
4280
+ if (node !== null && node !== undefined && typeof node.focus === 'function') node.focus()
4281
+ }
3818
4282
  useEffect(function () {
3819
- if (prompt === null || promptInputRef.current === null) return
4283
+ if (prompt === null || promptInputRef.current === null) return undefined
3820
4284
  promptInputRef.current.focus()
3821
4285
  promptInputRef.current.select()
4286
+ // Closing the dialog returns focus to the tree: the file shortcuts only
4287
+ // answer while the tree owns the keyboard, and the user is still there.
4288
+ return function () { focusTreeRoot() }
3822
4289
  }, [prompt])
4290
+ // The delete confirmation is a modal strip drawn inside the tree: it takes
4291
+ // focus to its 取消 button, answers Esc, and hands focus back to the tree
4292
+ // when it closes — otherwise Del / Ctrl+Z go dead right after a delete while
4293
+ // the toast still promises「可 Ctrl+Z 撤销」.
4294
+ useEffect(function () {
4295
+ if (pendingDelete === null) return undefined
4296
+ var cancel = confirmCancelRef.current
4297
+ if (cancel !== null && cancel !== undefined && typeof cancel.focus === 'function') cancel.focus()
4298
+ function onKey(event) {
4299
+ if (event.key !== 'Escape') return
4300
+ event.preventDefault()
4301
+ setPendingDelete(null)
4302
+ }
4303
+ document.addEventListener('keydown', onKey, true)
4304
+ return function () {
4305
+ document.removeEventListener('keydown', onKey, true)
4306
+ focusTreeRoot()
4307
+ }
4308
+ }, [pendingDelete])
4309
+
4310
+ // The selection follows the disk: a path that vanished (deleted, moved away,
4311
+ // watcher reload, folded folder) must leave the batch, or the status bar and
4312
+ // the delete dialog count ghosts (PM review P1-3, found live: 「删除 3 项?」
4313
+ // over 2 highlighted rows).
4314
+ useEffect(function () {
4315
+ if (selectedPaths.length === 0) return
4316
+ var alive = selectedPaths.filter(function (path) { return findEntry(path) !== undefined })
4317
+ if (alive.length === selectedPaths.length) return
4318
+ setSelectedPaths(alive)
4319
+ if (selectedPath !== null && alive.indexOf(selectedPath) === -1) {
4320
+ setSelectedPath(alive.length === 0 ? null : alive[alive.length - 1])
4321
+ }
4322
+ }, [levels, selectedPaths, selectedPath])
3823
4323
 
3824
4324
  async function submitPrompt() {
3825
4325
  if (prompt === null) return
@@ -3837,7 +4337,7 @@ window.__ModuleLoader__.load({
3837
4337
  return
3838
4338
  }
3839
4339
  await duplicateEntry(source, name)
3840
- setPrompt(null)
4340
+ setPrompt(null); setPromptNotice('')
3841
4341
  return
3842
4342
  }
3843
4343
  if (prompt.mode === 'rename') {
@@ -3856,9 +4356,9 @@ window.__ModuleLoader__.load({
3856
4356
  remapRenamed(renamed, entry.path)
3857
4357
  })
3858
4358
  await refreshLevel(parent)
3859
- setSelectedPath(renamed)
4359
+ selectOne(renamed)
3860
4360
  remapRenamed(entry.path, renamed)
3861
- setPrompt(null)
4361
+ setPrompt(null); setPromptNotice('')
3862
4362
  return
3863
4363
  }
3864
4364
  if (prompt.mode === 'paste') {
@@ -3868,14 +4368,15 @@ window.__ModuleLoader__.load({
3868
4368
  }
3869
4369
  var pasteDir = prompt.dir
3870
4370
  var pasteSource = prompt.source
3871
- // A colliding paste asked for a DIFFERENT name: keeping the old one
3872
- // would just bounce back to this prompt forever.
4371
+ // A colliding paste asks for a DIFFERENT name: keeping the old one is
4372
+ // refused inline (the card itself says 请改名) instead of pasting over
4373
+ // it — overwriting is the explicit 覆盖 button's job.
3873
4374
  if (prompt.conflict !== undefined && name === prompt.conflict) {
3874
- notify('「' + name + '」已存在,请改个名字')
4375
+ setPromptNotice('同名文件已存在,请改名(或点「覆盖」)')
3875
4376
  return
3876
4377
  }
3877
- setPrompt(null)
3878
- await runPaste(pasteSource, pasteDir, name)
4378
+ setPrompt(null); setPromptNotice('')
4379
+ await runPaste(pasteSource, pasteDir, name, false, prompt.pasteMode)
3879
4380
  return
3880
4381
  }
3881
4382
  if (prompt.mode === 'package') {
@@ -3893,8 +4394,8 @@ window.__ModuleLoader__.load({
3893
4394
  })
3894
4395
  await refreshLevel(packageBase)
3895
4396
  setExpanded(function (prev) { var next = Object.assign({}, prev); next[packageBase] = true; return next })
3896
- setSelectedPath(packageDir)
3897
- setPrompt(null)
4397
+ selectOne(packageDir)
4398
+ setPrompt(null); setPromptNotice('')
3898
4399
  return
3899
4400
  }
3900
4401
  if (prompt.mode === 'dir') {
@@ -3925,7 +4426,7 @@ window.__ModuleLoader__.load({
3925
4426
  await refreshLevel(parentOf(target))
3926
4427
  props.onOpen(target)
3927
4428
  }
3928
- setPrompt(null)
4429
+ setPrompt(null); setPromptNotice('')
3929
4430
  } catch (problem) {
3930
4431
  notify((prompt.mode === 'duplicate' ? '复制副本失败:' : prompt.mode === 'rename' ? '重命名失败:' : prompt.mode === 'paste' ? '粘贴失败:' : prompt.mode === 'dir' ? '新建文件夹失败:' : '新建文件失败:') + messageOf(problem))
3931
4432
  }
@@ -3952,7 +4453,7 @@ window.__ModuleLoader__.load({
3952
4453
  await refreshLevel(dir)
3953
4454
  })
3954
4455
  await refreshLevel(dir)
3955
- setSelectedPath(copied)
4456
+ selectOne(copied)
3956
4457
  }
3957
4458
 
3958
4459
  /** Ask for a new name for a tree entry (file or folder). */
@@ -3963,17 +4464,30 @@ window.__ModuleLoader__.load({
3963
4464
  setPromptName(entry.name || fileBaseName(entry.path))
3964
4465
  }
3965
4466
 
4467
+ /**
4468
+ * Copy/cut the current selection (one row, or every Ctrl+clicked row).
4469
+ *
4470
+ * Ctrl+C / Ctrl+X arrive with no context menu open, so the entry comes from
4471
+ * the tree selection as well — the keyboard used to no-op silently (only the
4472
+ * right-click menu ever worked). A menu command on a row that is part of a
4473
+ * multi-selection copies the whole selection; a menu command on an unrelated
4474
+ * row copies just that row.
4475
+ * @param {'copy'|'cut'} mode - clipboard mode.
4476
+ */
3966
4477
  function beginCopy(mode) {
3967
- // Ctrl+C / Ctrl+X arrive with no context menu open, so resolve the entry
3968
- // from the tree selection as well — the keyboard used to no-op silently
3969
- // (only the right-click menu ever worked).
3970
- var entry = treeMenu !== null && treeMenu.entry !== null && treeMenu.entry !== undefined
3971
- ? treeMenu.entry
3972
- : (selectedPath === null ? null : findEntry(selectedPath))
3973
- if (entry === null || entry === undefined) return
3974
- setClipboard({ mode: mode, path: entry.path, isDir: entry.isDir === true, name: entry.name || entry.path })
4478
+ var seed = treeMenu !== null && treeMenu.entry !== null && treeMenu.entry !== undefined
4479
+ ? treeMenu.entry.path
4480
+ : (selectedPath === null ? '' : selectedPath)
4481
+ var paths = selectionFor(seed)
4482
+ var items = []
4483
+ for (var index = 0; index < paths.length; index += 1) {
4484
+ var entry = findEntry(paths[index])
4485
+ items.push({ path: entry.path, isDir: entry.isDir === true, name: entry.name || fileBaseName(entry.path) })
4486
+ }
3975
4487
  setTreeMenu(null)
3976
- notify((mode === 'copy' ? '已复制 ' : '已剪切 ') + (entry.name || entry.path))
4488
+ if (items.length === 0) return
4489
+ setClipboard({ mode: mode, items: items })
4490
+ notify((mode === 'copy' ? '已复制 ' : '已剪切 ') + (items.length > 1 ? items.length + ' 项' : '「' + items[0].name + '」'))
3977
4491
  }
3978
4492
 
3979
4493
  /** Whether a failed host call was the "target exists" collision. */
@@ -3981,69 +4495,271 @@ window.__ModuleLoader__.load({
3981
4495
  return String(problem !== null && problem !== undefined && problem.code !== undefined ? problem.code : '') === 'exists'
3982
4496
  }
3983
4497
 
4498
+ /** The clipboard's entries in one shape (also tolerates a legacy single item). */
4499
+ function clipboardItems() {
4500
+ if (clipboard === null) return []
4501
+ if (Array.isArray(clipboard.items)) return clipboard.items
4502
+ if (typeof clipboard.path === 'string' && clipboard.path !== '') {
4503
+ return [{ path: clipboard.path, isDir: clipboard.isDir === true, name: clipboard.name || fileBaseName(clipboard.path) }]
4504
+ }
4505
+ return []
4506
+ }
4507
+ /** Human label for the clipboard: `N 项` for a batch, else the one name. */
4508
+ function clipboardLabel() {
4509
+ var items = clipboardItems()
4510
+ if (items.length > 1) return items.length + ' 项'
4511
+ return items.length === 1 ? '「' + items[0].name + '」' : ''
4512
+ }
3984
4513
  /** Leaf name a paste would create for one source. */
3985
4514
  function pasteEntryName(source, requestedName) {
3986
4515
  if (typeof requestedName === 'string' && requestedName.trim() !== '') return requestedName.trim()
3987
- if (source.kind === 'clipboard' && clipboard !== null) return fileBaseName(clipboard.path)
4516
+ if (source.kind === 'clipboard') {
4517
+ var items = clipboardItems()
4518
+ return items.length === 0 ? '' : items[0].name
4519
+ }
3988
4520
  if (source.kind === 'file' && source.file !== undefined) return String(source.file.name || '')
3989
4521
  if (source.kind === 'path') return fileBaseName(source.path)
4522
+ if (source.kind === 'entry') return fileBaseName(source.path)
3990
4523
  return ''
3991
4524
  }
3992
4525
 
3993
4526
  /**
3994
- * Park a colliding paste and ask for a different leaf name.
4527
+ * Park a colliding single paste: the card opens with the REAL name already in
4528
+ * the field (so both「改名后确定」and「覆盖」start from it), no 副本 prefill.
3995
4529
  *
3996
- * A collision is not a failure and not a 覆盖 question: the source is still
3997
- * on disk, so the only way forward is a new name. The prompt is prefilled with
3998
- * the tree's own 副本 convention (`A.java` → `A - 副本.java`) and refuses to
3999
- * resubmit the colliding name (see the prompt's `paste` branch).
4530
+ * Only the SINGLE-entry flows (one clipboard row, an OS paste, a dragged-in
4531
+ * path) ask: a collision there is a choice. Batches never stop for a dialog —
4532
+ * see {@link pasteBatch} (they add `… 副本` instead).
4000
4533
  * @param {object} source - the paste source (`clipboard` | `file` | `path`).
4001
4534
  * @param {string} dir - absolute destination directory.
4002
4535
  * @param {string} name - the leaf name that already exists there.
4003
4536
  */
4004
- function parkPasteName(source, dir, name) {
4005
- notify('「' + name + '」已存在,请改个名字')
4006
- setPrompt({ mode: 'paste', dir: dir, ext: '', title: '粘贴为', source: source, conflict: name })
4007
- setPromptName(duplicateName(name, false))
4537
+ function parkPasteName(source, dir, name, forcedMode) {
4538
+ setPrompt({ mode: 'paste', dir: dir, ext: '', title: '粘贴为', source: source, conflict: name, pasteMode: forcedMode })
4539
+ setPromptName(name)
4540
+ setPromptNotice('')
4008
4541
  }
4009
4542
 
4010
4543
  /**
4011
- * Perform ONE paste (tree clipboard, an uploaded `File`, or an outside path).
4544
+ * The 覆盖 button of a colliding single paste: place it under the SAME name,
4545
+ * replacing what is already there (the host routes know `overwrite`). No
4546
+ * confirmation step — the button IS the confirmation.
4547
+ */
4548
+ async function overwritePaste() {
4549
+ if (prompt === null || prompt.mode !== 'paste' || typeof prompt.conflict !== 'string') return
4550
+ var source = prompt.source
4551
+ var dir = prompt.dir
4552
+ var name = prompt.conflict
4553
+ setPrompt(null); setPromptNotice('')
4554
+ await runPaste(source, dir, name, true, prompt.pasteMode)
4555
+ }
4556
+
4557
+ /**
4558
+ * Place ONE clipboard entry into `dir`, auto-renaming to `… 副本` while the
4559
+ * name is taken (60 attempts, then give up). Used by batch paste and by
4560
+ * drag&drop move, where a dialog must not interrupt the gesture.
4561
+ * @param {{path:string,isDir:boolean,name:string}} item - the source entry.
4562
+ * @param {string} dir - absolute destination directory.
4563
+ * @param {string} mode - `'copy'` | `'cut'`.
4564
+ * @returns {Promise<{path:string, renamed:boolean}>} where it landed.
4565
+ */
4566
+ async function pasteEntryInto(item, dir, mode, ask) {
4567
+ var trimmedDir = dir.replace(/[\\/]+$/, '')
4568
+ var attempt = 0
4569
+ while (attempt < 60) {
4570
+ var name = attempt === 0 ? item.name : collisionCopyName(item.name, item.isDir === true, attempt)
4571
+ var target = trimmedDir + '/' + name
4572
+ if (mode === 'cut' && target === item.path) return { path: target, renamed: attempt > 0 }
4573
+ try {
4574
+ if (mode === 'cut') await fsMoveEntry(scope, item.path, dir, name)
4575
+ else await fsCopyEntry(scope, item.path, dir, name)
4576
+ return { path: target, renamed: attempt > 0 }
4577
+ } catch (problem) {
4578
+ if (!isExistsProblem(problem)) throw problem
4579
+ // A single-file gesture asks (覆盖/改名/取消) instead of inventing a
4580
+ // name; batches must not stop, so they keep the `… 副本` rule.
4581
+ if (ask === true && attempt === 0) return { path: target, conflict: true, renamed: false }
4582
+ attempt += 1
4583
+ }
4584
+ }
4585
+ throw new Error('同名条目太多,换个目标目录再试')
4586
+ }
4587
+
4588
+ /**
4589
+ * Resolve a parked batch collision: 覆盖 replaces the existing names,
4590
+ * 生成副本 suffixes them (`… 副本`, `… 副本(2)`). Every created/deleted path is
4591
+ * folded into ONE undo entry.
4592
+ * @param {string} policy - `'overwrite'` | `'copy'`.
4593
+ */
4594
+ async function resolveBatchConflict(policy) {
4595
+ if (batchConflict === null) return
4596
+ var pending = batchConflict
4597
+ setBatchConflict(null)
4598
+ var created = pending.created.slice()
4599
+ var origins = pending.origins.slice()
4600
+ var touched = pending.touched.slice()
4601
+ var renamed = []
4602
+ var failures = []
4603
+ for (var index = 0; index < pending.items.length; index += 1) {
4604
+ var item = pending.items[index]
4605
+ var leaf = fileBaseName(item.path)
4606
+ try {
4607
+ if (policy === 'overwrite') {
4608
+ if (pending.mode === 'cut') await fsMoveEntry(scope, item.path, pending.dir, leaf, true)
4609
+ else await fsCopyEntry(scope, item.path, pending.dir, leaf, true)
4610
+ created.push(pending.dir + '/' + leaf)
4611
+ origins.push(item.path)
4612
+ } else {
4613
+ var placed = await pasteEntryInto(item, pending.dir, pending.mode, false)
4614
+ created.push(placed.path)
4615
+ origins.push(item.path)
4616
+ if (placed.renamed === true) renamed.push(fileBaseName(placed.path))
4617
+ }
4618
+ var sourceDir = parentOf(item.path)
4619
+ if (touched.indexOf(sourceDir) === -1) touched.push(sourceDir)
4620
+ } catch (problem) {
4621
+ failures.push(leaf + '(' + messageOf(problem) + ')')
4622
+ }
4623
+ }
4624
+ if (created.length > 0) {
4625
+ var note = pending.mode === 'cut' ? '移动 ' : '粘贴 '
4626
+ rememberUndo(note + created.length + ' 项', async function () {
4627
+ for (var undo = created.length - 1; undo >= 0; undo -= 1) {
4628
+ if (pending.mode === 'cut') await fsMoveEntry(scope, created[undo], parentOf(origins[undo]), fileBaseName(origins[undo]))
4629
+ else await fsRemoveEntry(scope, created[undo], true)
4630
+ }
4631
+ for (var scan = 0; scan < touched.length; scan += 1) await refreshLevel(touched[scan])
4632
+ })
4633
+ if (pending.mode === 'cut') setClipboard(null)
4634
+ setExpanded(function (prev) { var next = Object.assign({}, prev); next[pending.dir] = true; return next })
4635
+ setSelectedPaths(created.slice())
4636
+ setSelectedPath(created[created.length - 1])
4637
+ }
4638
+ for (var refresh = 0; refresh < touched.length; refresh += 1) await refreshLevel(touched[refresh])
4639
+ if (renamed.length > 0 || failures.length > 0) notifyCollisionCopies(renamed, failures)
4640
+ if (created.length > 0) {
4641
+ notifyWithAction((pending.mode === 'cut' ? '已移动 ' : '已粘贴 ') + created.length + ' 项',
4642
+ undoAction('撤销这次' + (pending.mode === 'cut' ? '移动' : '粘贴') + '(也可 Ctrl+Z)'))
4643
+ }
4644
+ }
4645
+
4646
+ /** Toast that says where the `… 副本` names came from (batch collision rule). */
4647
+ function notifyCollisionCopies(renamed, failures) {
4648
+ var parts = []
4649
+ if (renamed.length > 0) {
4650
+ parts.push('存在同名文件,已生成' + (renamed.length === 1
4651
+ ? '「' + renamed[0] + '」'
4652
+ : '「' + renamed[0] + '」等 ' + renamed.length + ' 个副本'))
4653
+ }
4654
+ if (failures.length > 0) {
4655
+ parts.push(failures.length + ' 项失败:' + failures[0])
4656
+ }
4657
+ if (parts.length > 0) notify(parts.join(';'))
4658
+ }
4659
+
4660
+ /**
4661
+ * Batch copy/cut the selected rows into `dir`.
4012
4662
  *
4013
- * A collision does not just fail: it opens the 粘贴为 prompt with a 副本 name,
4014
- * because the source is still on disk and the only way forward is a different
4015
- * leaf name. Pasting a CUT entry back into its own folder is silently ignored —
4016
- * that is a no-op, not an error, and it must never be mistaken for "overwrite
4017
- * the source". Pasting a COPY onto its own path is NOT a no-op either: it falls
4018
- * through to the same prompt, i.e. "duplicate under a new name".
4663
+ * Name collisions never open a dialog in a batch: each colliding entry gets
4664
+ * the ` 副本` / ` 副本(n)` suffix (see {@link collisionCopyName}) and a toast
4665
+ * reports it. Landed paths become the new selection; one compound undo entry
4666
+ * (Ctrl+Z) reverses the whole batch.
4667
+ * @param {Array<{path:string,isDir:boolean,name:string}>} items - sources.
4668
+ * @param {string} dir - absolute destination directory.
4669
+ * @param {string} mode - `'copy'` | `'cut'`.
4670
+ */
4671
+ async function pasteBatch(items, dir, mode) {
4672
+ var trimmedDir = dir.replace(/[\\/]+$/, '')
4673
+ var created = []
4674
+ var origins = []
4675
+ var renamed = []
4676
+ var failures = []
4677
+ var conflicts = []
4678
+ var touched = [trimmedDir]
4679
+ for (var index = 0; index < items.length; index += 1) {
4680
+ var item = items[index]
4681
+ if (mode === 'cut' && parentOf(item.path) === trimmedDir) continue
4682
+ try {
4683
+ var placed = await pasteEntryInto(item, dir, mode, true)
4684
+ if (placed.conflict === true) { conflicts.push(item); continue }
4685
+ created.push(placed.path)
4686
+ origins.push(item.path)
4687
+ if (placed.renamed === true) renamed.push(fileBaseName(placed.path))
4688
+ var sourceDir = parentOf(item.path)
4689
+ if (touched.indexOf(sourceDir) === -1) touched.push(sourceDir)
4690
+ } catch (problem) {
4691
+ failures.push(item.name + '(' + messageOf(problem) + ')')
4692
+ }
4693
+ }
4694
+ if (created.length > 0) {
4695
+ rememberUndo(mode === 'cut' ? '移动 ' + created.length + ' 项' : '粘贴 ' + created.length + ' 项', async function () {
4696
+ for (var undo = created.length - 1; undo >= 0; undo -= 1) {
4697
+ if (mode === 'cut') await fsMoveEntry(scope, created[undo], parentOf(origins[undo]), fileBaseName(origins[undo]))
4698
+ else await fsRemoveEntry(scope, created[undo], true)
4699
+ }
4700
+ for (var scan = 0; scan < touched.length; scan += 1) await refreshLevel(touched[scan])
4701
+ })
4702
+ if (mode === 'cut') setClipboard(null)
4703
+ setExpanded(function (prev) { var next = Object.assign({}, prev); next[trimmedDir] = true; return next })
4704
+ setSelectedPaths(created.slice())
4705
+ setSelectedPath(created[created.length - 1])
4706
+ }
4707
+ for (var refresh = 0; refresh < touched.length; refresh += 1) await refreshLevel(touched[refresh])
4708
+ if (conflicts.length > 0) {
4709
+ setBatchConflict({ mode: mode, dir: trimmedDir, items: conflicts, created: created, origins: origins, touched: touched })
4710
+ return
4711
+ }
4712
+ if (renamed.length > 0 || failures.length > 0) notifyCollisionCopies(renamed, failures)
4713
+ if (created.length > 0) {
4714
+ notifyWithAction((mode === 'cut' ? '已移动 ' : '已粘贴 ')
4715
+ + (created.length > 1 ? created.length + ' 项' : '「' + fileBaseName(created[0]) + '」'),
4716
+ undoAction('撤销这次' + (mode === 'cut' ? '移动' : '粘贴') + '(也可 Ctrl+Z)'))
4717
+ }
4718
+ }
4719
+
4720
+ /**
4721
+ * Perform ONE paste (a single tree row, an uploaded `File`, or an outside path).
4722
+ *
4723
+ * A single collision does NOT just fail: it opens the 粘贴为 prompt with a 副本
4724
+ * name, because the source is still on disk and the only way forward is a
4725
+ * different leaf name. Pasting a CUT entry back into its own folder is silently
4726
+ * ignored — that is a no-op, not an error, and it must never be mistaken for
4727
+ * "overwrite the source". Pasting a COPY onto its own path is NOT a no-op
4728
+ * either: it falls through to the same prompt, i.e. "duplicate under a new name".
4729
+ * A MULTI-row clipboard is handed to {@link pasteBatch} instead.
4019
4730
  * @param {object} source - `{kind:'clipboard'}` | `{kind:'file', file}` |
4020
4731
  * `{kind:'path', path}`.
4021
4732
  * @param {string} dir - absolute destination directory.
4022
4733
  * @param {string} [requestedName] - explicit leaf name (改名 flow), else derived.
4023
4734
  * @returns {Promise<string|undefined>} the created path, or undefined.
4024
4735
  */
4025
- async function runPaste(source, dir, requestedName) {
4736
+ async function runPaste(source, dir, requestedName, overwrite, forcedMode) {
4737
+ var mode = forcedMode === 'cut' || forcedMode === 'copy' ? forcedMode : clipboard !== null ? clipboard.mode : 'copy'
4738
+ if (source.kind === 'clipboard' && clipboard !== null && clipboardItems().length > 1) {
4739
+ await pasteBatch(clipboardItems(), dir, mode === 'copy' ? 'copy' : 'cut')
4740
+ return undefined
4741
+ }
4742
+ var single = source.kind === 'clipboard' && clipboardItems().length === 1 ? clipboardItems()[0] : null
4026
4743
  var name = pasteEntryName(source, requestedName)
4027
4744
  if (name === '') return undefined
4028
4745
  var trimmedDir = dir.replace(/[\\/]+$/, '')
4029
4746
  var target = trimmedDir + '/' + name
4030
- var from = source.kind === 'clipboard' && clipboard !== null ? clipboard.path : ''
4031
- if (source.kind === 'clipboard' && target === from && clipboard.mode !== 'copy') {
4747
+ var isEntry = source.kind === 'entry'
4748
+ var from = single !== null ? single.path : isEntry ? source.path : ''
4749
+ if (source.kind === 'clipboard' && target === from && mode !== 'copy') {
4032
4750
  // Cut → its own folder: a no-op, not an error. A copy onto its own path is
4033
4751
  // the user asking for a duplicate, so it falls through to the 409 below.
4034
4752
  return undefined
4035
4753
  }
4754
+ var replace = overwrite === true
4036
4755
  try {
4037
- if (source.kind === 'clipboard') {
4038
- if (clipboard.mode === 'copy') {
4039
- await fsCopyEntry(scope, from, dir, name)
4040
- } else {
4041
- await fsMoveEntry(scope, from, dir, name)
4042
- }
4756
+ if (source.kind === 'clipboard' || isEntry) {
4757
+ if (mode === 'copy') await fsCopyEntry(scope, from, dir, name, replace)
4758
+ else await fsMoveEntry(scope, from, dir, name, replace)
4043
4759
  } else if (source.kind === 'file') {
4044
- await fsUpload(scope, dir, name, source.file)
4760
+ await fsUpload(scope, dir, name, source.file, replace)
4045
4761
  } else {
4046
- await fsImportPath(scope, dir, source.path, name)
4762
+ await fsImportPath(scope, dir, source.path, name, replace)
4047
4763
  }
4048
4764
  } catch (problem) {
4049
4765
  if (isExistsProblem(problem)) {
@@ -4053,14 +4769,14 @@ window.__ModuleLoader__.load({
4053
4769
  notify('粘贴失败:' + messageOf(problem))
4054
4770
  return undefined
4055
4771
  }
4056
- if (source.kind === 'clipboard' && clipboard.mode === 'move') {
4772
+ if ((source.kind === 'clipboard' || isEntry) && mode !== 'copy') {
4057
4773
  var originParent = parentOf(from)
4058
4774
  rememberUndo('粘贴 ' + name, async function () {
4059
4775
  await fsMoveEntry(scope, target, originParent, fileBaseName(from))
4060
4776
  await refreshLevel(originParent)
4061
4777
  await refreshLevel(dir)
4062
4778
  })
4063
- setClipboard(null)
4779
+ if (source.kind === 'clipboard') setClipboard(null)
4064
4780
  } else {
4065
4781
  rememberUndo('粘贴 ' + name, async function () {
4066
4782
  await fsRemoveEntry(scope, target, true)
@@ -4071,7 +4787,8 @@ window.__ModuleLoader__.load({
4071
4787
  var sourceDir = from === '' ? '' : parentOf(from)
4072
4788
  if (source.kind === 'clipboard' && sourceDir !== trimmedDir) await refreshLevel(sourceDir)
4073
4789
  setExpanded(function (prev) { var next = Object.assign({}, prev); next[trimmedDir] = true; return next })
4074
- setSelectedPath(target)
4790
+ selectOne(target)
4791
+ notifyWithAction((mode === 'copy' ? '已粘贴「' : '已移动「') + name + '」', undoAction('撤销这次粘贴(也可 Ctrl+Z)'))
4075
4792
  return target
4076
4793
  }
4077
4794
 
@@ -4148,49 +4865,139 @@ window.__ModuleLoader__.load({
4148
4865
  }
4149
4866
  }
4150
4867
 
4151
- async function removeEntry(entry) {
4868
+ /**
4869
+ * Delete one row, or every row of the multi-selection (Del / menu 删除).
4870
+ *
4871
+ * Delete = move into `<workspace>/.dsh-ris-ide-trash`, so Ctrl+Z restores it
4872
+ * and nothing is lost by a mis-click. A batch is one compound undo entry.
4873
+ * @param {Array<object>} entries - entries to remove, primary last.
4874
+ */
4875
+ async function removeEntries(entries) {
4152
4876
  try {
4153
- // Delete = move into <workspace>/.dsh-ris-ide-trash, so Ctrl+Z restores
4154
- // it and nothing is lost by a mis-click.
4155
4877
  var rootDir = absolutePath(cwd, rootPath)
4156
4878
  var trash = trashDirFor(rootDir)
4157
4879
  await fsMkdir(scope, trash)
4158
- var parked = trashNameFor(entry.path)
4159
- await fsMoveEntry(scope, entry.path, trash, parked)
4160
- await refreshLevel(parentOf(entry.path))
4161
- rememberUndo('删除 ' + (entry.name || fileBaseName(entry.path)), async function () {
4162
- await fsMoveEntry(scope, trash + '/' + parked, parentOf(entry.path), fileBaseName(entry.path))
4163
- await refreshLevel(parentOf(entry.path))
4164
- })
4165
- if (selectedPath === entry.path) setSelectedPath(null)
4166
- notify('已移到回收站 ' + (entry.name || fileBaseName(entry.path)) + '(Ctrl+Z 撤销)')
4167
- } catch (problem) {
4168
- notify('删除失败:' + messageOf(problem))
4880
+ var parked = []
4881
+ var moved = []
4882
+ var failures = []
4883
+ for (var index = 0; index < entries.length; index += 1) {
4884
+ var entry = entries[index]
4885
+ try {
4886
+ var name = trashNameFor(entry.path)
4887
+ await fsMoveEntry(scope, entry.path, trash, name)
4888
+ parked.push({ entry: entry, name: name })
4889
+ moved.push(entry.path)
4890
+ } catch (problem) {
4891
+ failures.push((entry.name || fileBaseName(entry.path)) + '(' + messageOf(problem) + ')')
4892
+ }
4893
+ }
4894
+ if (parked.length > 0) {
4895
+ rememberUndo(parked.length > 1 ? '删除 ' + parked.length + ' 项' : '删除 ' + (parked[0].entry.name || fileBaseName(parked[0].entry.path)), async function () {
4896
+ for (var undo = parked.length - 1; undo >= 0; undo -= 1) {
4897
+ var item = parked[undo]
4898
+ await fsMoveEntry(scope, trash + '/' + item.name, parentOf(item.entry.path), fileBaseName(item.entry.path))
4899
+ await refreshLevel(parentOf(item.entry.path))
4900
+ }
4901
+ })
4902
+ var parents = []
4903
+ for (var scan = 0; scan < parked.length; scan += 1) {
4904
+ var parent = parentOf(parked[scan].entry.path)
4905
+ if (parents.indexOf(parent) === -1) parents.push(parent)
4906
+ }
4907
+ for (var load = 0; load < parents.length; load += 1) await refreshLevel(parents[load])
4908
+ setSelectedPaths(selectedPaths.filter(function (path) { return moved.indexOf(path) === -1 }))
4909
+ if (selectedPath === null || moved.indexOf(selectedPath) !== -1) setSelectedPath(null)
4910
+ notifyWithAction('已移到回收站 ' + (parked.length > 1 ? parked.length + ' 项' : '「' + (parked[0].entry.name || fileBaseName(parked[0].entry.path)) + '」'), undoAction('把这次删除恢复回来(也可 Ctrl+Z)'))
4911
+ }
4912
+ if (failures.length > 0) notify('删除失败:' + failures[0])
4169
4913
  } finally {
4170
4914
  setPendingDelete(null)
4171
4915
  }
4172
4916
  }
4173
- async function moveInto(from, dirPath) {
4174
- if (from === dirPath || parentOf(from) === dirPath) return
4917
+ /**
4918
+ * Move rows (a drag & drop of one row, or of the whole multi-selection) into
4919
+ * `dirPath`.
4920
+ *
4921
+ * Every collision becomes a `… 副本` name — a drag gesture must not open a
4922
+ * dialog — and the batch is reported in one toast. Rows already inside the
4923
+ * target (or a directory dropped into itself) are skipped. One compound undo
4924
+ * entry (Ctrl+Z) puts everything back.
4925
+ * @param {string[]} paths - absolute source paths, in drop order.
4926
+ * @param {string} dirPath - absolute destination directory.
4927
+ */
4928
+ async function moveEntriesInto(paths, dirPath) {
4929
+ var trimmedDir = dirPath.replace(/[\\/]+$/, '')
4930
+ var created = []
4931
+ var origins = []
4932
+ var renamed = []
4933
+ var failures = []
4934
+ var conflicts = []
4935
+ var touched = [trimmedDir]
4175
4936
  try {
4176
- await fsMoveEntry(scope, from, dirPath)
4177
- var moved = dirPath.replace(/[\\/]+$/, '') + '/' + fileBaseName(from)
4178
- rememberUndo('移动 ' + fileBaseName(from), async function () {
4179
- await fsMoveEntry(scope, moved, parentOf(from), fileBaseName(from))
4180
- await refreshLevel(dirPath)
4181
- await refreshLevel(parentOf(from))
4182
- })
4183
- await refreshLevel(dirPath)
4184
- await refreshLevel(parentOf(from))
4185
- } catch (problem) {
4186
- notify('移动失败:' + messageOf(problem))
4937
+ for (var index = 0; index < paths.length; index += 1) {
4938
+ var from = paths[index]
4939
+ if (typeof from !== 'string' || from === '') continue
4940
+ var entry = findEntry(from)
4941
+ var isDir = entry.isDir === true
4942
+ // Already there — or a folder dragged into itself: nothing to do.
4943
+ if (from === trimmedDir || parentOf(from) === trimmedDir) continue
4944
+ if (isDir === true && trimmedDir.indexOf(from + '/') === 0) continue
4945
+ try {
4946
+ var placed = await pasteEntryInto({ path: from, isDir: isDir, name: fileBaseName(from) }, dirPath, 'cut', true)
4947
+ if (placed.conflict === true) {
4948
+ if (paths.length === 1) {
4949
+ parkPasteName({ kind: 'entry', path: from, isDir: isDir, name: fileBaseName(from) }, dirPath, fileBaseName(from), 'cut')
4950
+ break
4951
+ }
4952
+ conflicts.push({ path: from, isDir: isDir, name: fileBaseName(from) })
4953
+ continue
4954
+ }
4955
+ created.push(placed.path)
4956
+ origins.push(from)
4957
+ if (placed.renamed === true) renamed.push(fileBaseName(placed.path))
4958
+ var sourceDir = parentOf(from)
4959
+ if (touched.indexOf(sourceDir) === -1) touched.push(sourceDir)
4960
+ } catch (problem) {
4961
+ failures.push(fileBaseName(from) + '(' + messageOf(problem) + ')')
4962
+ }
4963
+ }
4964
+ if (created.length > 0) {
4965
+ rememberUndo('移动 ' + created.length + ' 项', async function () {
4966
+ for (var undo = created.length - 1; undo >= 0; undo -= 1) {
4967
+ await fsMoveEntry(scope, created[undo], parentOf(origins[undo]), fileBaseName(origins[undo]))
4968
+ }
4969
+ for (var scan = 0; scan < touched.length; scan += 1) await refreshLevel(touched[scan])
4970
+ })
4971
+ setExpanded(function (prev) { var next = Object.assign({}, prev); next[trimmedDir] = true; return next })
4972
+ setSelectedPaths(created.slice())
4973
+ setSelectedPath(created[created.length - 1])
4974
+ }
4975
+ for (var refresh = 0; refresh < touched.length; refresh += 1) await refreshLevel(touched[refresh])
4976
+ notifyCollisionCopies(renamed, failures)
4187
4977
  } finally {
4188
4978
  setDropTarget(null)
4189
4979
  }
4190
4980
  }
4981
+ /** Read the paths a drag started inside the tree carries (JSON first). */
4982
+ function dragPaths(transfer) {
4983
+ var raw = ''
4984
+ try { raw = transfer.getData('application/x-dsh-ris-ide-paths') || '' } catch { raw = '' }
4985
+ if (raw !== '') {
4986
+ try {
4987
+ var parsed = JSON.parse(raw)
4988
+ if (Array.isArray(parsed)) {
4989
+ return parsed.filter(function (item) { return typeof item === 'string' && item !== '' })
4990
+ }
4991
+ } catch {
4992
+ // fall through to the single path below
4993
+ }
4994
+ }
4995
+ try { raw = transfer.getData('text/plain') || '' } catch { raw = '' }
4996
+ return raw === '' ? [] : [raw]
4997
+ }
4191
4998
  /** Folder a paste should land in: the selection itself, or its parent. */
4192
4999
  function pasteTargetDir() {
4193
- if (selectedPath === null) return absolutePath(cwd, rootPath)
5000
+ if (selectedPath === null) return absolutePath(cwd, activeRoot)
4194
5001
  var entry = findEntry(selectedPath)
4195
5002
  return entry.isDir === true ? entry.path : parentOf(entry.path)
4196
5003
  }
@@ -4217,8 +5024,26 @@ window.__ModuleLoader__.load({
4217
5024
  )
4218
5025
  if (!inside) return
4219
5026
  if (prompt !== null || pendingDelete !== null) return
4220
- if (selectedPath === null) return
5027
+ if (event.key === 'Escape' && selectedPaths.length > 1) {
5028
+ // Esc drops the batch but keeps the primary row: batch ops are silent,
5029
+ // so there must be a one-key way out of a mis-clicked selection.
5030
+ event.preventDefault()
5031
+ selectOne(selectedPath)
5032
+ return
5033
+ }
4221
5034
  var meta = event.ctrlKey || event.metaKey
5035
+ if (meta && (event.key === 'a' || event.key === 'A')) {
5036
+ // 全选 = every VISIBLE row (folders and files). Without this the key
5037
+ // was claimed and did nothing — or worse, the browser selected the
5038
+ // whole page and Ctrl+C copied page text instead of the files.
5039
+ event.preventDefault()
5040
+ var visible = visibleEntries()
5041
+ if (visible.length === 0) return
5042
+ setSelectedPaths(visible.map(function (row) { return row.path }))
5043
+ setSelectedPath(visible[0].path)
5044
+ return
5045
+ }
5046
+ if (selectedPath === null) return
4222
5047
  if (event.key === 'F2') {
4223
5048
  event.preventDefault()
4224
5049
  openRenamePrompt(findEntry(selectedPath))
@@ -4226,7 +5051,7 @@ window.__ModuleLoader__.load({
4226
5051
  }
4227
5052
  if (event.key === 'Delete') {
4228
5053
  event.preventDefault()
4229
- setPendingDelete(findEntry(selectedPath))
5054
+ setPendingDelete(selectionFor(selectedPath).map(findEntry))
4230
5055
  return
4231
5056
  }
4232
5057
  if (meta && (event.key === 'z' || event.key === 'Z') && event.shiftKey !== true) {
@@ -4235,9 +5060,8 @@ window.__ModuleLoader__.load({
4235
5060
  return
4236
5061
  }
4237
5062
  if (meta && (event.key === 'a' || event.key === 'A')) {
4238
- // The tree is single-selection, so 全选 has nothing to expand into.
4239
- // Claim the key anyway: unclaimed, the browser selected the whole page
4240
- // and the following Ctrl+C copied that page text instead of the file.
5063
+ // Handled above, before the "no selection" guard (Ctrl+A must work
5064
+ // with nothing selected too).
4241
5065
  event.preventDefault()
4242
5066
  return
4243
5067
  }
@@ -4262,7 +5086,7 @@ window.__ModuleLoader__.load({
4262
5086
  }
4263
5087
  window.addEventListener('keydown', onKey, true)
4264
5088
  return function () { window.removeEventListener('keydown', onKey, true) }
4265
- }, [selectedPath, clipboard, prompt, pendingDelete, expanded, levels, treeMenu])
5089
+ }, [selectedPath, selectedPaths, clipboard, prompt, pendingDelete, expanded, levels, treeMenu])
4266
5090
 
4267
5091
  // A click anywhere else closes the menu.
4268
5092
  useEffect(function () {
@@ -4277,6 +5101,27 @@ window.__ModuleLoader__.load({
4277
5101
  return function () { window.removeEventListener('mousedown', onDown) }
4278
5102
  }, [treeMenu])
4279
5103
 
5104
+ /**
5105
+ * Re-root the file tree at `path` (folder row click / folder search hit).
5106
+ * Inside the current root the trail grows so 「↑ 上级」 walks back; a path
5107
+ * outside it starts a fresh trail.
5108
+ * @param {string} path - the folder to show as the tree root.
5109
+ */
5110
+ function openDirRoot(path) {
5111
+ if (typeof path !== 'string' || path === '') return
5112
+ setRootTrail(function (prev) {
5113
+ var current = prev.length > 0 ? prev[prev.length - 1] : rootPath
5114
+ var base = String(current).replace(/[\\/]+$/, '')
5115
+ var inside = path === current || (base !== '' && path.indexOf(base + '/') === 0)
5116
+ return inside && path !== current ? prev.concat([path]) : [path]
5117
+ })
5118
+ setTreeMenu(null)
5119
+ }
5120
+ /** Walk one level back towards the base root (the 「↑ 上级」 row). */
5121
+ function closeDirRoot() {
5122
+ setRootTrail(function (prev) { return prev.length <= 1 ? [] : prev.slice(0, prev.length - 1) })
5123
+ setTreeMenu(null)
5124
+ }
4280
5125
  function toggle(entry) {
4281
5126
  if (!entry.isDir) {
4282
5127
  props.onOpen(entry.path)
@@ -4338,29 +5183,40 @@ window.__ModuleLoader__.load({
4338
5183
  var isRevealed = reveal !== null && reveal.path === entry.path
4339
5184
  var isSelected = selectedPath === entry.path
4340
5185
  && (entry.isDir === true || !Array.isArray(props.openFiles) || props.openFiles.indexOf(entry.path) !== -1)
5186
+ // Extra rows of a multi-selection: highlighted but NOT the primary row
5187
+ // (menus, rename/delete and the paste target keep acting on `selectedPath`).
5188
+ var isMulti = selectedPaths.length > 1 && selectedPaths.indexOf(entry.path) !== -1 && !isSelected
4341
5189
  // Dropping ON a file means "into the folder that file lives in" — a row
4342
5190
  // is always a drop target; only the expand/collapse toggle is dir-only.
4343
5191
  var dropDir = entry.isDir === true ? entry.path : parentOf(entry.path)
4344
5192
  var isDropTarget = dropTarget === entry.path
4345
5193
  out.push(h('div', {
4346
5194
  key: entry.path,
4347
- style: Object.assign({}, isActive || isRevealed || isSelected ? S.treeRowOn : S.treeRow, {
4348
- paddingLeft: indent,
4349
- boxShadow: isDropTarget ? 'inset 0 0 0 1px #d29922' : undefined,
4350
- }),
4351
- title: entry.path + '(右键:新建/粘贴/复制/剪切/删除/刷新)',
5195
+ style: Object.assign({},
5196
+ isActive || isRevealed || isSelected ? S.treeRowOn : (isMulti ? S.treeRowMulti : S.treeRow),
5197
+ {
5198
+ paddingLeft: indent,
5199
+ boxShadow: isDropTarget ? 'inset 0 0 0 1px #d29922' : undefined,
5200
+ }),
5201
+ title: entry.path + (entry.isDir === true ? '(点击:把这个目录当作文件树根 / 三角:展开折叠)' : '') + '(Ctrl+点击 多选 / 右键:新建/粘贴/复制/剪切/删除/刷新)',
4352
5202
  'data-tree-path': entry.path,
4353
5203
  'data-tree-revealed': isRevealed ? '1' : undefined,
4354
5204
  'data-tree-selected': isSelected ? '1' : undefined,
5205
+ 'data-tree-multi': isMulti ? '1' : undefined,
4355
5206
  'data-tree-drop': isDropTarget ? '1' : undefined,
4356
5207
  draggable: true,
4357
5208
  onDragStart: function (event) {
5209
+ // Drag carries the whole selection when the grabbed row is part of it,
5210
+ // so Ctrl+selected rows move together in one gesture.
5211
+ var dragged = selectionFor(entry.path)
4358
5212
  try {
5213
+ event.dataTransfer.setData('application/x-dsh-ris-ide-paths', JSON.stringify(dragged))
4359
5214
  event.dataTransfer.setData('text/plain', entry.path)
4360
- event.dataTransfer.effectAllowed = 'move'
5215
+ event.dataTransfer.effectAllowed = 'copyMove'
4361
5216
  } catch {
4362
5217
  // older engines: the drop handler re-reads the selection
4363
5218
  }
5219
+ setSelectedPaths(dragged)
4364
5220
  setSelectedPath(entry.path)
4365
5221
  },
4366
5222
  onDragOver: function (event) {
@@ -4381,21 +5237,40 @@ window.__ModuleLoader__.load({
4381
5237
  setDropTarget(null)
4382
5238
  return
4383
5239
  }
4384
- var from = ''
4385
- try { from = event.dataTransfer.getData('text/plain') } catch { from = '' }
4386
- if (from === '') from = selectedPath === null ? '' : selectedPath
4387
- if (from !== '' && from !== entry.path) void moveInto(from, dropDir)
5240
+ var paths = dragPaths(event.dataTransfer)
5241
+ if (paths.length === 0 && selectedPath !== null) paths = [selectedPath]
5242
+ paths = paths.filter(function (item) { return item !== entry.path })
5243
+ if (paths.length > 0) void moveEntriesInto(paths, dropDir)
4388
5244
  setDropTarget(null)
4389
5245
  },
4390
- onClick: function () {
4391
- setSelectedPath(entry.path)
5246
+ onClick: function (event) {
5247
+ var additive = event.ctrlKey === true || event.metaKey === true
5248
+ if (additive === true) {
5249
+ // Ctrl/Cmd+click = toggle this row in the multi-selection. It never
5250
+ // opens a file nor expands a folder: the gesture is "mark rows".
5251
+ var next = toggleTreeSelection(selectedPaths, entry.path)
5252
+ setSelectedPaths(next)
5253
+ setSelectedPath(next.indexOf(entry.path) !== -1 ? entry.path
5254
+ : (next.length === 0 ? null : next[next.length - 1]))
5255
+ if (treeListRef.current !== null) treeListRef.current.focus({ preventScroll: true })
5256
+ return
5257
+ }
5258
+ selectOne(entry.path)
5259
+ // A folder row only expands/collapses, exactly like its ▸ twisty.
5260
+ // Drilling in is the explicit 「进入」 entry in the context menu: a
5261
+ // click that re-roots the tree on its own kept moving the user away
5262
+ // from the workspace root.
4392
5263
  toggle(entry)
4393
5264
  if (treeListRef.current !== null) treeListRef.current.focus({ preventScroll: true })
4394
5265
  },
4395
5266
  onContextMenu: function (event) {
4396
5267
  event.preventDefault()
4397
5268
  event.stopPropagation()
4398
- setSelectedPath(entry.path)
5269
+ // Right-clicking a row that is part of the multi-selection keeps the
5270
+ // whole selection (so 复制/剪切/删除 act on all of it); right-clicking
5271
+ // an unrelated row re-targets the selection to just that row.
5272
+ if (selectedPaths.indexOf(entry.path) === -1) selectOne(entry.path)
5273
+ else setSelectedPath(entry.path)
4399
5274
  setTreeMenu({
4400
5275
  entry: entry,
4401
5276
  dir: entry.isDir === true ? entry.path : parentOf(entry.path),
@@ -4412,7 +5287,7 @@ window.__ModuleLoader__.load({
4412
5287
  // Same outcome as clicking the row: select + expand/collapse. The
4413
5288
  // stopPropagation only prevents the row handler running twice.
4414
5289
  onClick: entry.isDir === true
4415
- ? function (event) { event.stopPropagation(); setSelectedPath(entry.path); toggle(entry) }
5290
+ ? function (event) { event.stopPropagation(); selectOne(entry.path); toggle(entry) }
4416
5291
  : undefined,
4417
5292
  }, entry.isDir ? (open ? '▾' : '▸') : ''),
4418
5293
  h('span', {
@@ -4422,7 +5297,10 @@ window.__ModuleLoader__.load({
4422
5297
  opacity: fileKind(entry) === 'dot' ? 0.85 : undefined,
4423
5298
  },
4424
5299
  'data-file-kind': fileKind(entry),
4425
- }, treeLabel(S, entry))))
5300
+ }, treeLabel(S, entry),
5301
+ Array.isArray(props.dirtyPaths) === true && props.dirtyPaths.indexOf(entry.path) !== -1
5302
+ ? h('span', { style: S.editedMark, 'data-file-dirty': '1', title: '有未保存的修改' }, '●')
5303
+ : null)))
4426
5304
  if (entry.isDir && open && chain[entry.path] !== true) {
4427
5305
  out = out.concat(rowsFor(entry.path, depth + 1, Object.assign({}, chain, defineKey(entry.path)), seen))
4428
5306
  }
@@ -4430,21 +5308,60 @@ window.__ModuleLoader__.load({
4430
5308
  return out
4431
5309
  }
4432
5310
 
5311
+ /**
5312
+ * Flatten the CURRENTLY VISIBLE rows (same order as {@link rowsFor}) into
5313
+ * plain entries — what Ctrl+A selects. Kept in step with `rowsFor`'s
5314
+ * duplicate/cycle guards so 全选 can never pick a row that is not drawn.
5315
+ * @returns {Array<object>} visible entries, depth-first.
5316
+ */
5317
+ function visibleEntries() {
5318
+ var out = []
5319
+ var seen = {}
5320
+ function walk(path, depth, chain) {
5321
+ if (depth > TREE_MAX_DEPTH) return
5322
+ var entries = levels[path]
5323
+ if (entries === undefined) return
5324
+ entries.forEach(function (entry) {
5325
+ if (seen[entry.path] === true) return
5326
+ seen[entry.path] = true
5327
+ out.push(entry)
5328
+ if (entry.isDir === true && expanded[entry.path] === true && chain[entry.path] !== true) {
5329
+ walk(entry.path, depth + 1, Object.assign({}, chain, defineKey(entry.path)))
5330
+ }
5331
+ })
5332
+ }
5333
+ walk(activeRoot, 0, {})
5334
+ return out
5335
+ }
5336
+
4433
5337
  /** The row context menu (main list or the "new file" sub-list). */
4434
5338
  function renderTreeMenu() {
4435
5339
  if (treeMenu === null) return null
4436
5340
  var items
4437
- if (treeMenu.sub === 'new') {
4438
- items = [h('div', { key: 'hint', style: S.searchHeader }, '新建文件')]
4439
- NEW_FILE_TYPES.forEach(function (type) {
4440
- items.push(h('button', {
4441
- key: 'new-' + type.ext, type: 'button', style: S.tabMenuItem, 'data-tree-new': type.ext,
4442
- onClick: function () { openCreatePrompt('file', treeMenu.dir, type.ext) },
4443
- }, type.ext === '' ? type.label : (type.label + ' .' + type.ext)))
4444
- })
4445
- } else {
5341
+ {
4446
5342
  items = [
4447
- h('button', { key: 'new-file', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'new-file', onClick: function () { setTreeMenu(function (prev) { return prev === null ? prev : Object.assign({}, prev, { sub: 'new' }) }) } }, '新建文件 ▸'),
5343
+ treeMenu.entry.isDir === true
5344
+ ? h('button', {
5345
+ key: 'enter-dir', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'enter-dir',
5346
+ title: '把这个目录当作文件树根(行首出现「↑ 上级」逐级返回)',
5347
+ onClick: function () { openDirRoot(treeMenu.entry.path) },
5348
+ }, '进入')
5349
+ : null,
5350
+ // 「新建文件」opens a FLYOUT on hover (click also opens it, for touch):
5351
+ // replacing the whole menu in place made the type list a second screen
5352
+ // instead of a submenu.
5353
+ h('button', {
5354
+ key: 'new-file', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'new-file',
5355
+ 'data-tree-submenu': menuSub === null ? 'closed' : 'open',
5356
+ onMouseEnter: function (event) {
5357
+ var rect = event.currentTarget.getBoundingClientRect()
5358
+ setMenuSub({ left: Math.round(rect.width), top: Math.round(rect.top - treeMenu.y) })
5359
+ },
5360
+ onClick: function (event) {
5361
+ var rect = event.currentTarget.getBoundingClientRect()
5362
+ setMenuSub({ left: Math.round(rect.width), top: Math.round(rect.top - treeMenu.y) })
5363
+ },
5364
+ }, '新建文件 ▸'),
4448
5365
  h('button', { key: 'new-dir', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'new-dir', onClick: function () { openCreatePrompt('dir', treeMenu.dir) } }, '新建文件夹'),
4449
5366
  // Packages only exist under a Java source root: reveal the action only there
4450
5367
  // (elsewhere a dotted name would just be a weird folder name).
@@ -4455,7 +5372,7 @@ window.__ModuleLoader__.load({
4455
5372
  key: 'paste', type: 'button', 'data-tree-action': 'paste',
4456
5373
  style: clipboard === null ? Object.assign({}, S.tabMenuItem, { opacity: 0.45 }) : S.tabMenuItem,
4457
5374
  disabled: clipboard === null,
4458
- title: clipboard === null ? '剪贴板为空' : ('粘贴「' + clipboard.name + '」到 ' + treeMenu.dir),
5375
+ title: clipboard === null ? '剪贴板为空' : ('粘贴 ' + clipboardLabel() + ' 到 ' + treeMenu.dir),
4459
5376
  onClick: function () {
4460
5377
  if (clipboard === null) return
4461
5378
  var dir = treeMenu.dir
@@ -4470,7 +5387,9 @@ window.__ModuleLoader__.load({
4470
5387
  }, '重命名'),
4471
5388
  h('button', {
4472
5389
  key: 'copy', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'copy',
4473
- title: '复制到剪贴板(Ctrl+C;到目标目录再用粘贴)',
5390
+ title: selectedPaths.length > 1
5391
+ ? '复制所选 ' + selectedPaths.length + ' 项到剪贴板(Ctrl+C)'
5392
+ : '复制到剪贴板(Ctrl+C;到目标目录再用粘贴)',
4474
5393
  onClick: function () { beginCopy('copy') },
4475
5394
  }, '复制'),
4476
5395
  h('button', {
@@ -4483,8 +5402,14 @@ window.__ModuleLoader__.load({
4483
5402
  setPromptName(duplicateName(entry.name || fileBaseName(entry.path), entry.isDir === true, 1))
4484
5403
  },
4485
5404
  }, '创建副本'),
4486
- h('button', { key: 'cut', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'cut', onClick: function () { beginCopy('cut') } }, '剪切'),
4487
- h('button', { key: 'delete', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'delete', onClick: function () { setPendingDelete(treeMenu.entry); setTreeMenu(null) } }, '删除'),
5405
+ h('button', {
5406
+ key: 'cut', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'cut',
5407
+ title: selectedPaths.length > 1 ? '剪切所选 ' + selectedPaths.length + ' 项(Ctrl+X)' : '剪切(Ctrl+X)',
5408
+ onClick: function () { beginCopy('cut') },
5409
+ }, '剪切'),
5410
+ h('button', { key: 'delete', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'delete', title: selectionFor(treeMenu.entry.path).length > 1
5411
+ ? '删除所选 ' + selectionFor(treeMenu.entry.path).length + ' 项(移到回收站,Ctrl+Z 撤销)'
5412
+ : '删除(移到回收站,Ctrl+Z 撤销)', onClick: function () { setPendingDelete(selectionFor(treeMenu.entry.path).map(findEntry)); setTreeMenu(null) } }, '删除'),
4488
5413
  h('button', {
4489
5414
  key: 'copy-name', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'copy-name',
4490
5415
  onClick: function () {
@@ -4501,17 +5426,46 @@ window.__ModuleLoader__.load({
4501
5426
  notify(copyText(entry.path) ? '已复制路径:' + entry.path : '复制失败:剪贴板不可用')
4502
5427
  },
4503
5428
  }, '复制文件路径'),
5429
+ h('button', {
5430
+ key: 'select-all', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'select-all',
5431
+ title: '选中当前可见的全部行(Ctrl+A)',
5432
+ onClick: function () {
5433
+ setTreeMenu(null)
5434
+ var visible = visibleEntries()
5435
+ if (visible.length === 0) return
5436
+ setSelectedPaths(visible.map(function (row) { return row.path }))
5437
+ setSelectedPath(visible[0].path)
5438
+ },
5439
+ }, '全选'),
4504
5440
  h('button', {
4505
5441
  key: 'refresh', type: 'button', style: S.tabMenuItem, 'data-tree-action': 'refresh',
4506
5442
  onClick: function () { var dir = treeMenu.dir; setTreeMenu(null); void refreshLevel(dir) },
4507
5443
  }, '刷新'),
4508
5444
  ]
4509
5445
  }
5446
+ var flyout = menuSub === null
5447
+ ? null
5448
+ : h('div', {
5449
+ key: 'new-flyout', 'data-tree-submenu-panel': 'new',
5450
+ style: Object.assign({}, S.tabMenu, {
5451
+ position: 'absolute', left: menuSub.left, top: menuSub.top, zIndex: 901, minWidth: 150,
5452
+ maxHeight: 320, overflowY: 'auto',
5453
+ }),
5454
+ onMouseDown: function (event) { event.stopPropagation() },
5455
+ },
5456
+ h('div', { style: S.searchHeader }, '新建文件'),
5457
+ NEW_FILE_TYPES.map(function (type) {
5458
+ return h('button', {
5459
+ key: 'new-' + type.ext, type: 'button', style: S.tabMenuItem, 'data-tree-new': type.ext,
5460
+ onClick: function () { openCreatePrompt('file', treeMenu.dir, type.ext) },
5461
+ }, type.ext === '' ? type.label : (type.label + ' .' + type.ext))
5462
+ }))
4510
5463
  return h('div', {
4511
5464
  style: Object.assign({}, S.tabMenu, { left: treeMenu.x, top: treeMenu.y, position: 'fixed', zIndex: 900, minWidth: 150 }),
4512
5465
  'data-tree-menu': '1',
4513
5466
  onMouseDown: function (event) { event.stopPropagation() },
4514
- }, items)
5467
+ onMouseLeave: function () { setMenuSub(null) },
5468
+ }, items, flyout)
4515
5469
  }
4516
5470
 
4517
5471
  /** The "new file/folder" dialog (name + optional package). */
@@ -4531,12 +5485,18 @@ window.__ModuleLoader__.load({
4531
5485
  : isPackage
4532
5486
  ? prompt.dir.replace(/[\\/]+$/, '') + '/' + (promptName === '' ? '<包名>' : (packagePathOf(promptName) || promptName))
4533
5487
  : ''
4534
- return h('div', {
4535
- style: { position: 'fixed', inset: 0, zIndex: 950, background: 'rgba(0,0,0,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center' },
4536
- 'data-tree-prompt': prompt.mode,
4537
- onMouseDown: function (event) { if (event.target === event.currentTarget) setPrompt(null) },
4538
- },
4539
- h('div', { style: { width: 380, maxWidth: '92vw', background: 'Canvas', color: 'inherit', border: '1px solid color-mix(in srgb, currentColor 25%, transparent)', borderRadius: 6, boxShadow: '0 18px 48px rgba(0,0,0,0.4)', padding: 10, display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', fontSize: 12 } },
5488
+ var pasteConflict = isPaste && typeof prompt.conflict === 'string'
5489
+ var anchor = dialogAnchor(380, pasteConflict ? 244 : 196)
5490
+ return [
5491
+ h('div', {
5492
+ key: 'prompt-mask', style: { position: 'fixed', inset: 0, zIndex: 949, background: 'transparent' },
5493
+ 'data-tree-prompt-mask': '1', onMouseDown: function () { setPrompt(null) },
5494
+ }),
5495
+ h('div', {
5496
+ key: 'prompt-card',
5497
+ style: { position: 'fixed', left: anchor.left, top: anchor.top, zIndex: 950, width: 380, maxWidth: '92vw', background: 'Canvas', color: 'inherit', border: '1px solid color-mix(in srgb, currentColor 25%, transparent)', borderRadius: 6, boxShadow: '0 18px 48px rgba(0,0,0,0.4)', padding: 10, display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', fontSize: 12 },
5498
+ 'data-tree-prompt': prompt.mode,
5499
+ },
4540
5500
  h('div', { style: { fontWeight: 600 } }, prompt.title),
4541
5501
  h('label', { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
4542
5502
  h('span', { style: { opacity: 0.7 } }, isRename ? '新名称' : isDuplicate ? '副本名称' : isPaste ? '新名称' : isFile ? '文件名' : isPackage ? '包名' : '文件夹名'),
@@ -4563,27 +5523,95 @@ window.__ModuleLoader__.load({
4563
5523
  isFile || isPackage || isRename || isDuplicate || isPaste
4564
5524
  ? h('div', { style: Object.assign({}, S.meta, { wordBreak: 'break-all' }), 'data-tree-prompt-path': '1' }, preview)
4565
5525
  : null,
5526
+ promptNotice === ''
5527
+ ? null
5528
+ : h('div', { style: { color: '#e5534b', wordBreak: 'break-all' }, 'data-tree-prompt-notice': '1' }, promptNotice),
4566
5529
  h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 6 } },
5530
+ pasteConflict
5531
+ ? h('button', {
5532
+ type: 'button',
5533
+ style: Object.assign({}, S.button, { color: '#e5534b' }),
5534
+ title: '用这个文件覆盖目标目录里的同名文件',
5535
+ 'data-tree-prompt-overwrite': '1',
5536
+ onClick: function () { void overwritePaste() },
5537
+ }, '覆盖')
5538
+ : null,
4567
5539
  h('button', { type: 'button', style: S.buttonOff, onClick: function () { setPrompt(null) } }, '取消'),
4568
- h('button', { type: 'button', style: S.button, 'data-tree-prompt-ok': '1', onClick: function () { void submitPrompt() } }, '确定'))))
5540
+ h('button', { type: 'button', style: S.button, 'data-tree-prompt-ok': '1', onClick: function () { void submitPrompt() } }, '确定'))),
5541
+ ]
5542
+ }
5543
+
5544
+ /**
5545
+ * The batch-collision card: NO name input, two buttons 覆盖 / 生成副本, and the
5546
+ * list of names that already exist. Esc / the mask cancels (nothing written).
5547
+ */
5548
+ function renderBatchConflict() {
5549
+ if (batchConflict === null) return null
5550
+ var items = batchConflict.items
5551
+ var anchor = dialogAnchor(380, 220)
5552
+ return [
5553
+ h('div', {
5554
+ key: 'batch-mask', style: { position: 'fixed', inset: 0, zIndex: 949, background: 'transparent' },
5555
+ 'data-tree-batch-mask': '1', onMouseDown: function () { setBatchConflict(null) },
5556
+ }),
5557
+ h('div', {
5558
+ key: 'batch-card',
5559
+ style: { position: 'fixed', left: anchor.left, top: anchor.top, zIndex: 950, width: 380, maxWidth: '92vw', background: 'Canvas', color: 'inherit', border: '1px solid color-mix(in srgb, currentColor 25%, transparent)', borderRadius: 6, boxShadow: '0 18px 48px rgba(0,0,0,0.4)', padding: 10, display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', fontSize: 12 },
5560
+ 'data-tree-batch-conflict': '1',
5561
+ },
5562
+ h('div', { style: { fontWeight: 600 } }, '有 ' + items.length + ' 个同名文件'),
5563
+ h('div', { style: { opacity: 0.75, wordBreak: 'break-all' } },
5564
+ items.map(function (item) { return item.name }).join('、')),
5565
+ h('div', { style: { opacity: 0.6 } },
5566
+ batchConflict.mode === 'cut' ? '覆盖 = 用拖进来的文件替换;生成副本 = 保留两边并加「 副本」后缀' : '覆盖 = 替换目标目录里的同名文件;生成副本 = 保留两边并加「 副本」后缀'),
5567
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 6 } },
5568
+ h('button', {
5569
+ type: 'button', style: Object.assign({}, S.button, { color: '#e5534b' }), 'data-tree-batch-overwrite': '1',
5570
+ onClick: function () { void resolveBatchConflict('overwrite') },
5571
+ }, '覆盖'),
5572
+ h('button', {
5573
+ type: 'button', style: S.button, 'data-tree-batch-copy': '1',
5574
+ onClick: function () { void resolveBatchConflict('copy') },
5575
+ }, '生成副本'))),
5576
+ ]
4569
5577
  }
4570
5578
 
4571
5579
  /** The delete confirmation (recursive for folders). */
4572
5580
  function renderTreeConfirm() {
4573
5581
  if (pendingDelete === null) return null
4574
- var isDir = pendingDelete.isDir === true
4575
- return h('div', {
4576
- style: { position: 'fixed', inset: 0, zIndex: 950, background: 'rgba(0,0,0,0.32)', display: 'flex', alignItems: 'center', justifyContent: 'center' },
4577
- 'data-tree-confirm': '1',
4578
- },
4579
- h('div', { style: { width: 340, maxWidth: '92vw', background: 'Canvas', color: 'inherit', border: '1px solid color-mix(in srgb, currentColor 25%, transparent)', borderRadius: 6, boxShadow: '0 18px 48px rgba(0,0,0,0.4)', padding: 10, display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', fontSize: 12 } },
4580
- h('div', { style: { fontWeight: 600 } }, isDir ? '删除文件夹?' : '删除文件?'),
4581
- h('div', { style: { opacity: 0.75, wordBreak: 'break-all' } }, pendingDelete.path + (isDir ? '(连同内容)' : '')),
5582
+ var items = Array.isArray(pendingDelete) ? pendingDelete : [pendingDelete]
5583
+ if (items.length === 0) return null
5584
+ var isDir = items[0].isDir === true
5585
+ var label = items.length > 1
5586
+ ? '删除 ' + items.length + ' 项?'
5587
+ : (isDir ? '删除文件夹?' : '删除文件?')
5588
+ var detail = items.length > 1
5589
+ ? items.map(function (item) { return fileBaseName(item.path) + (item.isDir === true ? '/' : '') }).join('、')
5590
+ : items[0].path + (isDir ? '(连同内容)' : '')
5591
+ var anchor = dialogAnchor(340, 176)
5592
+ return [
5593
+ h('div', { key: 'confirm-mask', style: { position: 'fixed', inset: 0, zIndex: 949, background: 'transparent' }, 'data-tree-confirm-mask': '1' }),
5594
+ h('div', {
5595
+ key: 'confirm-card',
5596
+ style: { position: 'fixed', left: anchor.left, top: anchor.top, zIndex: 950, width: 340, maxWidth: '92vw', background: 'Canvas', color: 'inherit', border: '1px solid color-mix(in srgb, currentColor 25%, transparent)', borderRadius: 6, boxShadow: '0 18px 48px rgba(0,0,0,0.4)', padding: 10, display: 'flex', flexDirection: 'column', gap: 8, fontFamily: 'system-ui, sans-serif', fontSize: 12 },
5597
+ 'data-tree-confirm': '1',
5598
+ },
5599
+ h('div', { style: { fontWeight: 600 } }, label),
5600
+ h('div', { style: { opacity: 0.75, wordBreak: 'break-all' } }, detail),
5601
+ h('div', { style: { opacity: 0.6 } }, '删除 = 移到回收站,可 Ctrl+Z 撤销'),
4582
5602
  h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 6 } },
4583
- h('button', { type: 'button', style: S.buttonOff, onClick: function () { setPendingDelete(null) } }, '取消'),
4584
- h('button', { type: 'button', style: Object.assign({}, S.button, { color: '#e5534b' }), 'data-tree-confirm-ok': '1', onClick: function () { void removeEntry(pendingDelete) } }, '删除'))))
5603
+ h('button', { type: 'button', style: S.buttonOff, ref: confirmCancelRef, 'data-tree-confirm-cancel': '1', onClick: function () { setPendingDelete(null) } }, '取消'),
5604
+ h('button', { type: 'button', style: Object.assign({}, S.button, { color: '#e5534b' }), 'data-tree-confirm-ok': '1', onClick: function () { void removeEntries(items) } }, '删除'))),
5605
+ ]
4585
5606
  }
4586
5607
 
5608
+ // Freeze the anchor once per dialog opening and release it when the last
5609
+ // dialog closes. Assigning during render is safe here: it only pins the
5610
+ // point the JSX below already reads; it never drives rendering.
5611
+ var anyDialogOpen = prompt !== null || pendingDelete !== null || batchConflict !== null
5612
+ if (anyDialogOpen === false) dialogPointRef.current = null
5613
+ else if (dialogPointRef.current === null && pointerRef.current !== null) dialogPointRef.current = pointerRef.current
5614
+
4587
5615
  return h('div', { style: S.treeWrap, 'data-ide-tree': '1' },
4588
5616
  degraded === true && treeDismissals.isOpen('tree-degraded', 'v1')
4589
5617
  ? h(ClosableNotice, {
@@ -4602,27 +5630,45 @@ window.__ModuleLoader__.load({
4602
5630
  onClick: function () { setError(undefined) },
4603
5631
  }, '×'))
4604
5632
  : null,
5633
+ selectedPaths.length > 1
5634
+ ? h('div', { style: S.treeSelectionBar, 'data-tree-selection': String(selectedPaths.length) },
5635
+ h('span', { style: { flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, '已选 ' + selectedPaths.length + ' 项'),
5636
+ h('button', {
5637
+ type: 'button', style: Object.assign({}, S.buttonOff, { flex: '0 0 auto', padding: '0 5px' }),
5638
+ 'data-tree-selection-clear': '1', title: '清空多选(Esc)',
5639
+ onClick: function () { selectOne(selectedPath); setTreeMenu(null) },
5640
+ }, '×'))
5641
+ : null,
4605
5642
  h('div', {
4606
- ref: treeListRef, style: Object.assign({}, S.treeList, { outline: 'none' }), 'data-tree-root': rootPath,
5643
+ ref: treeListRef, style: Object.assign({}, S.treeList, { outline: 'none' }), 'data-tree-root': activeRoot,
4607
5644
  tabIndex: -1,
4608
5645
  onClick: function () { setTreeMenu(null) },
4609
5646
  onPaste: handleTreePaste,
4610
5647
  onDragOver: function (event) { event.preventDefault() },
4611
5648
  onDrop: function (event) {
4612
5649
  event.preventDefault()
4613
- var rootDir = absolutePath(cwd, rootPath)
5650
+ var rootDir = absolutePath(cwd, activeRoot)
4614
5651
  var external = []
4615
5652
  try { external = Array.prototype.slice.call(event.dataTransfer.files || []) } catch { external = [] }
4616
5653
  if (external.length > 0) { void importExternal(rootDir, external, []); return }
4617
- var from = ''
4618
- try { from = event.dataTransfer.getData('text/plain') } catch { from = '' }
4619
- if (from === '') from = selectedPath === null ? '' : selectedPath
4620
- if (from !== '' && parentOf(from) !== rootDir) void moveInto(from, rootDir)
5654
+ var paths = dragPaths(event.dataTransfer)
5655
+ if (paths.length === 0 && selectedPath !== null) paths = [selectedPath]
5656
+ paths = paths.filter(function (item) { return parentOf(item) !== rootDir })
5657
+ if (paths.length > 0) void moveEntriesInto(paths, rootDir)
4621
5658
  },
4622
- }, rowsFor(rootPath, 0, {}, {})),
5659
+ }, rootTrail.length > 0
5660
+ ? h('div', {
5661
+ key: 'tree-up', style: Object.assign({}, S.treeRow, S.treeUpRow), 'data-tree-up': '1',
5662
+ title: '返回上级文件夹(当前文件树根:' + activeRoot + ')',
5663
+ onClick: function (event) { event.stopPropagation(); closeDirRoot() },
5664
+ },
5665
+ h('span', { style: Object.assign({}, S.treeTwist, { cursor: 'pointer' }) }, '↑'),
5666
+ h('span', { style: { opacity: 0.75 } }, '上级'))
5667
+ : null, rowsFor(activeRoot, 0, {}, {})),
4623
5668
  renderTreeMenu(),
4624
5669
  renderTreePrompt(),
4625
- renderTreeConfirm())
5670
+ renderTreeConfirm(),
5671
+ renderBatchConflict())
4626
5672
  }
4627
5673
 
4628
5674
  /**
@@ -4969,14 +6015,45 @@ window.__ModuleLoader__.load({
4969
6015
  * keep `auto`: neither `overflow-y:scroll` nor `scrollbar-gutter:stable` here —
4970
6016
  * both would reserve an empty gutter on files that do not overflow.
4971
6017
  */
6018
+ // Neutral light-grey scrollbars (user口径: 正常浅灰就行,不用亮色): the old
6019
+ // teal thumb read as a UI accent and competed with the code; the track stays
6020
+ // barely visible so the gutter still shows the bars are permanent.
4972
6021
  var SCROLLBAR_CSS = '[data-workbench="ris-ide"] ::-webkit-scrollbar{width:10px;height:10px}'
4973
- + '[data-workbench="ris-ide"] ::-webkit-scrollbar-track{background:rgba(127,127,127,0.14);border-radius:999px}'
6022
+ + '[data-workbench="ris-ide"] ::-webkit-scrollbar-track{background:rgba(127,127,127,0.10);border-radius:999px}'
4974
6023
  + '[data-workbench="ris-ide"] ::-webkit-scrollbar-thumb'
4975
- + '{background:rgba(86,182,194,0.55);border:2px solid transparent;border-radius:999px;background-clip:content-box}'
4976
- + '[data-workbench="ris-ide"] ::-webkit-scrollbar-thumb:hover{background:rgba(86,182,194,0.80);background-clip:content-box}'
6024
+ + '{background:rgba(140,140,140,0.45);border:2px solid transparent;border-radius:999px;background-clip:content-box}'
6025
+ + '[data-workbench="ris-ide"] ::-webkit-scrollbar-thumb:hover{background:rgba(140,140,140,0.68);background-clip:content-box}'
4977
6026
  + '[data-workbench="ris-ide"] ::-webkit-scrollbar-corner{background:0 0}'
4978
6027
  + '@supports not selector(::-webkit-scrollbar){'
4979
- + '[data-workbench="ris-ide"] *{scrollbar-width:thin;scrollbar-color:rgba(86,182,194,0.65) rgba(127,127,127,0.14)}}'
6028
+ + '[data-workbench="ris-ide"] *{scrollbar-width:thin;scrollbar-color:rgba(140,140,140,0.55) rgba(127,127,127,0.10)}}'
6029
+
6030
+ /**
6031
+ * The editor's find panel, restyled to belong to the IDE (user口径: 美化一下
6032
+ * 编辑器的搜索面板,风格和整体不一致). CodeMirror ships a 2018-looking strip:
6033
+ * gradient `.cm-button`s, 15px inputs, its own colours. This scopes a 20px
6034
+ * row of ghost buttons + 3px-radius inputs to `[data-workbench="ris-ide"]`,
6035
+ * using the same `color-mix` / inherited-colour palette as the title bars, so
6036
+ * light and dark themes both follow the page instead of hard-coding colours.
6037
+ */
6038
+ var SEARCH_PANEL_CSS = '[data-workbench="ris-ide"] .cm-panels{background:color-mix(in srgb, Canvas 96%, transparent) !important;color:inherit !important;border:0 !important}'
6039
+ + '[data-workbench="ris-ide"] .cm-panels-top{border-bottom:1px solid color-mix(in srgb, currentColor 12%, transparent) !important}'
6040
+ + '[data-workbench="ris-ide"] .cm-panels-bottom{border-top:1px solid color-mix(in srgb, currentColor 12%, transparent) !important}'
6041
+ // The panel is the IDE's own (`ideFindPanel` in the editor chunk): two rows,
6042
+ // both inputs in the same grid column so they are exactly the same width, and
6043
+ // fixed 24px button columns so find-row and replace-row controls line up.
6044
+ + '[data-workbench="ris-ide"] .cm-search{display:grid;grid-template-columns:minmax(0,1fr) repeat(6,24px);row-gap:5px;column-gap:5px;align-items:center;padding:5px 6px;font:inherit;font-size:12px}'
6045
+ + '[data-workbench="ris-ide"] .cm-search input{grid-column:1;width:100%;min-width:0;height:22px;box-sizing:border-box;padding:0 6px;font:inherit;font-size:12px;color:inherit;background:color-mix(in srgb, Canvas 99%, transparent);border:1px solid color-mix(in srgb, currentColor 20%, transparent);border-radius:3px;outline:none}'
6046
+ + '[data-workbench="ris-ide"] .cm-search input:focus{border-color:color-mix(in srgb, currentColor 48%, transparent)}'
6047
+ + '[data-workbench="ris-ide"] .cm-search button{height:22px;width:24px;padding:0;display:inline-flex;align-items:center;justify-content:center;background:color-mix(in srgb, currentColor 6%, transparent) !important;background-image:none !important;color:inherit !important;border:1px solid color-mix(in srgb, currentColor 14%, transparent);border-radius:3px;font:inherit;font-size:11px;line-height:1;cursor:pointer;opacity:.9}'
6048
+ + '[data-workbench="ris-ide"] .cm-search button:hover{background:color-mix(in srgb, currentColor 12%, transparent) !important;opacity:1}'
6049
+ + '[data-workbench="ris-ide"] .cm-search button:active{background:color-mix(in srgb, currentColor 18%, transparent) !important}'
6050
+ // Active toggles keep the family's teal accent instead of a heavy bold face.
6051
+ + '[data-workbench="ris-ide"] .cm-search button[aria-pressed="true"]{background:rgba(86,182,194,0.30) !important;border-color:rgba(86,182,194,0.70) !important;opacity:1}'
6052
+ // The count sits between the replace controls (col 6/7) and the input column.
6053
+ + '[data-workbench="ris-ide"] .cm-search .dsh-find-count{grid-row:2;grid-column:2 / span 4;font-size:11px;opacity:.62;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:2px;font-variant-numeric:tabular-nums}'
6054
+ + '[data-workbench="ris-ide"] .cm-search br{display:none}'
6055
+ + '[data-workbench="ris-ide"] .cm-searchMatch{background:rgba(255,190,80,0.28) !important;outline:1px solid rgba(255,170,40,0.55)}'
6056
+ + '[data-workbench="ris-ide"] .cm-searchMatch-selected{background:rgba(255,150,40,0.42) !important;outline:1px solid rgba(255,140,20,0.7)}'
4980
6057
 
4981
6058
  /**
4982
6059
  * Selection colours for the embedded editor, injected from the panel itself.
@@ -5186,8 +6263,13 @@ window.__ModuleLoader__.load({
5186
6263
  },
5187
6264
  })
5188
6265
  handleRef.current = handle
6266
+ // Expose the handle so the workspace content search can drive the find
6267
+ // panel (`controls.searchFor`) — without this the pending find never had
6268
+ // a target and a click on a content hit only opened the file.
6269
+ if (typeof props.onToolbarControls === 'function') props.onToolbarControls(handle)
5189
6270
  if (typeof props.onToolbarState === 'function') props.onToolbarState({ dirty: false, saveState: 'saved', mode: 'editable', editable: true })
5190
6271
  return function () {
6272
+ if (typeof props.onToolbarControls === 'function') props.onToolbarControls(null)
5191
6273
  handle.destroy()
5192
6274
  handleRef.current = null
5193
6275
  }
@@ -5315,6 +6397,108 @@ window.__ModuleLoader__.load({
5315
6397
  * {@link IdeMediaView}. The debug pane and log pane take one tab per program
5316
6398
  * and poll `/debug/poll` only while their tab is visible.
5317
6399
  */
6400
+ /**
6401
+ * Read-only preview of a text file above the whole-read limit.
6402
+ *
6403
+ * MUST stay module scope: declared inside `ProgramWorkbench` it became a new
6404
+ * component type on every parent render, so each loaded page (a parent state
6405
+ * update) remounted the scroll box and threw the reader back to the top —
6406
+ * "no scrollbar, can't reach the bottom, jumps back up".
6407
+ * Position is remembered per path so switching tabs and coming back keeps it.
6408
+ */
6409
+ /** Per-path scroll offset of the large-file preview (see the restore effect). */
6410
+ var LARGE_TEXT_VIEW = new Map()
6411
+
6412
+ function LargeTextPreview(props) {
6413
+ var doc = props.doc
6414
+ var boxRef = React.useRef(null)
6415
+ var [scrollTop, setScrollTop] = React.useState(0)
6416
+ var [viewportHeight, setViewportHeight] = React.useState(600)
6417
+ var lineHeight = 18
6418
+ var lines = React.useMemo(function () { return String(doc.text || '').split('\n') }, [doc.text])
6419
+ var dropLines = typeof doc.dropLines === 'number' ? doc.dropLines : 0
6420
+ var total = dropLines + lines.length
6421
+ var prevDropRef = React.useRef(dropLines)
6422
+ var first = Math.max(0, Math.floor(scrollTop / lineHeight) - 4)
6423
+ var count = Math.max(0, Math.ceil(viewportHeight / lineHeight) + 8)
6424
+ var visible = lines.slice(first, first + count)
6425
+ function onScroll(event) {
6426
+ var box = event.currentTarget
6427
+ setScrollTop(box.scrollTop)
6428
+ setViewportHeight(box.clientHeight)
6429
+ LARGE_TEXT_VIEW.set(props.path, box.scrollTop)
6430
+ if (box.scrollTop + box.clientHeight > box.scrollHeight - 240) props.onLoadMore()
6431
+ }
6432
+ // Hiding the pane (`display:none`, every inactive tab) collapses its scroll
6433
+ // height and the browser clamps `scrollTop` to 0, so coming back landed at
6434
+ // the top of a 1.6 MB file. Only restore when the box sits at the top — a
6435
+ // mid-file offset means the reader is scrolling and must not be moved.
6436
+ var useLayout = React.useLayoutEffect !== undefined ? React.useLayoutEffect : React.useEffect
6437
+ useLayout(function () {
6438
+ var box = boxRef.current
6439
+ if (box === null || props.active === false) return
6440
+ var memory = LARGE_TEXT_VIEW.get(props.path)
6441
+ if (typeof memory !== 'number' || memory <= 0 || box.scrollTop > 0) return
6442
+ box.scrollTop = memory
6443
+ setScrollTop(memory)
6444
+ }, [props.active, doc.text, doc.size])
6445
+ React.useEffect(function () {
6446
+ if (boxRef.current !== null) setViewportHeight(boxRef.current.clientHeight)
6447
+ }, [doc.size])
6448
+ // 首帧 / 页面没填满窗口时也要拉下一页:滚动是唯一的加载触发点时,"已加载
6449
+ // 0 KB" 的预览既没有内容也没有滚动条,就永远等不到下一页(review 记的 P1)。
6450
+ React.useEffect(function () {
6451
+ if (doc.error !== undefined || doc.eof === true || doc.loading === true) return
6452
+ var box = boxRef.current
6453
+ if (box === null) return
6454
+ if (box.scrollHeight <= box.clientHeight + 240) props.onLoadMore()
6455
+ }, [doc.text, doc.loading, doc.eof, doc.error, doc.size])
6456
+ // Freeing the front shrinks the scroll height: move the viewport by the
6457
+ // same amount so the line the reader is looking at stays put.
6458
+ React.useEffect(function () {
6459
+ var freed = dropLines - prevDropRef.current
6460
+ prevDropRef.current = dropLines
6461
+ if (freed > 0 && boxRef.current !== null) {
6462
+ boxRef.current.scrollTop = Math.max(0, boxRef.current.scrollTop - freed * lineHeight)
6463
+ LARGE_TEXT_VIEW.set(props.path, boxRef.current.scrollTop)
6464
+ }
6465
+ }, [dropLines])
6466
+ var loadedKb = Math.round(String(doc.text || '').length / 1024)
6467
+ var totalMb = typeof doc.size === 'number' && doc.size > 0 ? doc.size / (1024 * 1024) : 0
6468
+ var loadedNote = '已加载 ' + loadedKb + ' KB / ' + totalMb.toFixed(1) + ' MB'
6469
+ return h('div', { style: S.largeText, 'data-large-text': '1' },
6470
+ h('div', { style: S.largeTextBar, 'data-large-text-bar': '1' },
6471
+ h('span', { style: { fontWeight: 600 } }, '只读预览 · 大文件'),
6472
+ h('span', { style: S.spacer }),
6473
+ h('span', { style: S.meta, 'data-large-text-loaded': String(loadedKb) }, loadedNote),
6474
+ doc.eof === true
6475
+ ? h('span', { style: S.meta }, '(已全部加载)')
6476
+ : h('span', { style: S.meta }, '(滚动到底继续加载)'),
6477
+ dropLines > 0
6478
+ ? h('span', { style: S.meta, 'data-large-text-freed': String(dropLines) }, '已释放前面 ' + dropLines + ' 行')
6479
+ : null,
6480
+ dropLines > 0
6481
+ ? h('button', {
6482
+ type: 'button', style: S.buttonOff, 'data-large-text-restart': '1', title: '从文件开头重新加载(会丢弃当前已释放的部分)',
6483
+ onClick: function () { props.onRestart() },
6484
+ }, '从头加载')
6485
+ : null,
6486
+ doc.loading === true ? h('span', { style: S.meta }, '加载中…') : null,
6487
+ h('button', {
6488
+ type: 'button', style: S.buttonOff, 'data-large-text-edit': '1',
6489
+ title: '强制加载整个文件并进入编辑(大文件会占用较多内存;超过 ' + formatBytes(LARGE_TEXT_FORCE_MAX_BYTES) + ' 拒绝)',
6490
+ onClick: function () { if (typeof props.onForceEdit === 'function') props.onForceEdit() },
6491
+ }, '编辑')),
6492
+ doc.error !== undefined
6493
+ ? h('div', { style: S.error, role: 'alert', 'data-large-text-error': '1' }, '读取失败:' + String(doc.error))
6494
+ : null,
6495
+ h('div', { ref: boxRef, style: S.largeTextBox, onScroll: onScroll, tabIndex: 0, 'data-large-text-body': '1' },
6496
+ h('div', { style: { position: 'relative', height: Math.max(1, total) * lineHeight } },
6497
+ h('div', { style: { position: 'absolute', top: first * lineHeight, left: 0, right: 0 } },
6498
+ visible.map(function (line, index) {
6499
+ return h('div', { key: first + index, style: S.largeTextLine, 'data-large-text-line': String(first + index + 1) }, line === '' ? '\u00a0' : line)
6500
+ })))))
6501
+ }
5318
6502
  function ProgramWorkbench(props) {
5319
6503
  var scope = props ? props.scope : undefined
5320
6504
  var tab = props ? props.tab : undefined
@@ -5325,6 +6509,14 @@ window.__ModuleLoader__.load({
5325
6509
  var metaKind = typeof meta.kind === 'string' ? meta.kind : 'spring'
5326
6510
  var metaLogPath = typeof meta.logPath === 'string' ? meta.logPath : ''
5327
6511
  var programKey = typeof meta.programId === 'string' ? meta.programId : ''
6512
+ /**
6513
+ * The row the window was OPENED on (the sidebar console's 🐞 button). The tab
6514
+ * meta only describes a DSH-page IDE tab, so the standalone window has to
6515
+ * carry its target separately: without it the window opened on the workspace
6516
+ * and `autoDebug` never reached the workbench.
6517
+ */
6518
+ var openProgram = props !== null && props !== undefined && props.openProgram !== null && typeof props.openProgram === 'object' ? props.openProgram : null
6519
+ var openLogPath = openProgram !== null && typeof openProgram.logPath === 'string' ? openProgram.logPath : ''
5328
6520
  var visible = props ? props.visible !== false : true
5329
6521
  /** The workspace search box (Ctrl+Alt+F / F3 target outside the editor). */
5330
6522
  var searchInputRef = useRef(null)
@@ -5344,6 +6536,11 @@ window.__ModuleLoader__.load({
5344
6536
  var savedUi = readSavedUi(storageKey)
5345
6537
 
5346
6538
  var [consoleBusy, setConsoleBusy] = useState('')
6539
+ /** Which action that row mask is running (`start|stop|restart|debug`). */
6540
+ var [consoleBusyKind, setConsoleBusyKind] = useState('')
6541
+ /** Workspace-console start-all/stop-all pass: `{kind,index,total}` | null. */
6542
+ var [consoleBulk, setConsoleBulk] = useState(null)
6543
+ var consoleBulkRef = useRef(false)
5347
6544
  var [ui, setUi] = useState(function () {
5348
6545
  // First ever open of an IDE tab (no saved layout, real browser): start with
5349
6546
  // the SOURCE pane maximised so the editor gets the whole area, and let the
@@ -5396,13 +6593,27 @@ var [ui, setUi] = useState(function () {
5396
6593
  /** Dropdown payload for the toolbar search: null | {matches,dirs} | {error}. */
5397
6594
  var [searchHits, setSearchHits] = useState(null)
5398
6595
  var [searchBusy, setSearchBusy] = useState(false)
6596
+ /** Content-search hits for the SAME query (PM gap #2), merged in the dropdown. */
6597
+ var [contentHits, setContentHits] = useState([])
6598
+ var [contentBusy, setContentBusy] = useState(false)
6599
+ /**
6600
+ * Query → results, kept across picks: opening a hit must not throw the
6601
+ * query (or the `git grep` output) away, so the same row can be reopened.
6602
+ */
6603
+ var searchCacheRef = useRef(new Map())
6604
+ /** A shortcut asked for the box: focus AND select its text once mounted. */
6605
+ var [searchFocusNonce, setSearchFocusNonce] = useState(0)
6606
+ var searchFocusPendingRef = useRef(false)
5399
6607
  /** Dropdown highlight: an index into `searchHits.matches`, -1 when there is none. */
5400
6608
  var [searchActive, setSearchActive] = useState(-1)
5401
6609
  /** One-shot "reveal this hit in the tree" request (nonce makes repeats work). */
5402
6610
  var [locateRequest, setLocateRequest] = useState(null)
5403
6611
  var locateNonceRef = useRef(0)
5404
- /** Bumped by the tree title bar's ⟳ (the tree reloads its loaded levels). */
5405
- var [treeRefreshTick, setTreeRefreshTick] = useState(0)
6612
+ /**
6613
+ * Bumped by the tree title bar's ⟳ and by the .gitignore filter toggle.
6614
+ * `announce` rides along so only the explicit ⟳ click gets a toast.
6615
+ */
6616
+ var [treeRefresh, setTreeRefresh] = useState({ tick: 0, announce: false })
5406
6617
  /** The workspace sits in a git repo, so .gitignore filtering is meaningful. */
5407
6618
  var [treeGit, setTreeGit] = useState(false)
5408
6619
  /** false = apply .gitignore (default when git exists), true = show all files. */
@@ -5417,7 +6628,7 @@ var [ui, setUi] = useState(function () {
5417
6628
  var next = treeShowAll !== true
5418
6629
  TREE_FILTER_ALL = next
5419
6630
  setTreeShowAll(next)
5420
- setTreeRefreshTick(function (value) { return value + 1 })
6631
+ setTreeRefresh(function (value) { return { tick: value.tick + 1, announce: false } })
5421
6632
  note(next ? '文件树:显示所有文件(含 .gitignore 忽略的)' : '文件树:按 .gitignore 过滤')
5422
6633
  }
5423
6634
  // Warm the editor chunk while the panel is idle: opening the first file then
@@ -5632,6 +6843,11 @@ var [ui, setUi] = useState(function () {
5632
6843
  /** Latest docs map for async loaders (state is closure-stale otherwise). */
5633
6844
  var docsRef = useRef(docs)
5634
6845
  docsRef.current = docs
6846
+ /**
6847
+ * Paths the user chose to force-edit from a large preview: reopening such a
6848
+ * tab must skip the read-only preview and load the whole file again.
6849
+ */
6850
+ var forceEditPathsRef = useRef(new Set())
5635
6851
  var [savingPath, setSavingPath] = useState(undefined)
5636
6852
  var [pendingClose, setPendingClose] = useState(undefined)
5637
6853
  /** Bulk close waiting for a decision: `{keepActive, victims, dirty}`. */
@@ -5653,10 +6869,16 @@ var [ui, setUi] = useState(function () {
5653
6869
  var [pendingSaveClose, setPendingSaveClose] = useState(undefined)
5654
6870
  /** path -> the viewer's `{ save, setMode }` commands (a ref: never re-renders). */
5655
6871
  var viewerControlsRef = useRef({})
6872
+ /**
6873
+ * path -> `{ needle, line }` waiting for that viewer to register. A content
6874
+ * hit opens a file whose CodeMirror chunk may still be loading, so the find
6875
+ * is delivered when `onToolbarControls` finally runs instead of being lost.
6876
+ */
6877
+ var pendingFindRef = useRef({})
5656
6878
  var [reloadTick, setReloadTick] = useState(0)
5657
6879
  // ONE selected program drives the debug pane AND the log pane (the console
5658
6880
  // switches them together), so neither pane keeps a tab strip.
5659
- var [activePath, setActivePath] = useState(metaLogPath)
6881
+ var [activePath, setActivePath] = useState(metaLogPath !== '' ? metaLogPath : openLogPath)
5660
6882
  var activePathRef = useRef(metaLogPath)
5661
6883
  activePathRef.current = activePath
5662
6884
  var viewPath = activePath
@@ -5759,6 +6981,88 @@ var [ui, setUi] = useState(function () {
5759
6981
  */
5760
6982
  var [logFollowing, setLogFollowing] = useState(true)
5761
6983
  var [logWrap, setLogWrap] = useState(function () { return readPref(PREF_WRAP, '1') !== '0' })
6984
+ /**
6985
+ * Log level filter (PM gap #4): `'all'` → `'warn'` → `'error'` → `'all'`.
6986
+ * The viewer keeps every line in memory and hides the rest at render time, so
6987
+ * toggling is instant and the find bar still counts the real text.
6988
+ */
6989
+ var [logLevel, setLogLevel] = useState('all')
6990
+ function cycleLogLevel() {
6991
+ setLogLevel(function (previous) {
6992
+ return previous === 'all' ? 'warn' : previous === 'warn' ? 'error' : 'all'
6993
+ })
6994
+ }
6995
+ /** The path whose diff view is open (PM gap #5), or null for the editor. */
6996
+ var [diffPath, setDiffPath] = useState(null)
6997
+ useEffect(function () { setDiffPath(null) }, [openFile])
6998
+ /**
6999
+ * One `mvn -pl <module> test -Dtest=…` run opened from the editor (PM gap #6).
7000
+ * `{path, id, className, command, status, output, exitCode}`; the pane replaces
7001
+ * the editor body while it is open.
7002
+ */
7003
+ var [testRun, setTestRun] = useState(null)
7004
+ var testPollRef = useRef(null)
7005
+ useEffect(function () {
7006
+ return function () { if (testPollRef.current !== null) clearTimeout(testPollRef.current) }
7007
+ }, [])
7008
+ /**
7009
+ * Human status line for the test pane.
7010
+ * @param {{status: string, exitCode: number|null}} run - the run record.
7011
+ * @returns {string} one short Chinese phrase.
7012
+ */
7013
+ function testRunStatusText(run) {
7014
+ if (run.status === 'starting') return '启动中…'
7015
+ if (run.status === 'running') return '运行中…'
7016
+ if (run.status === 'done') return '通过'
7017
+ if (run.status === 'timeout') return '超时(900 秒)'
7018
+ if (run.exitCode !== null) return '失败(退出码 ' + run.exitCode + ')'
7019
+ return '失败'
7020
+ }
7021
+ /** Poll one run until it settles (1s while running; the pane shows the output). */
7022
+ function pollTestRun(id) {
7023
+ function tick() {
7024
+ runTestStatus(scopeRef.current, id).then(function (state) {
7025
+ setTestRun(function (previous) {
7026
+ if (previous === null || previous.id !== id) return previous
7027
+ return Object.assign({}, previous, {
7028
+ status: state.status, output: state.output, exitCode: state.exitCode,
7029
+ })
7030
+ })
7031
+ if (state.running === true) testPollRef.current = setTimeout(tick, 1000)
7032
+ }).catch(function (problem) {
7033
+ setTestRun(function (previous) {
7034
+ if (previous === null || previous.id !== id) return previous
7035
+ return Object.assign({}, previous, {
7036
+ status: 'failed',
7037
+ output: (previous.output === '' ? '' : previous.output + '\n') + (messageOf(problem) || '查询测试状态失败'),
7038
+ })
7039
+ })
7040
+ })
7041
+ }
7042
+ testPollRef.current = setTimeout(tick, 400)
7043
+ }
7044
+ /**
7045
+ * Run the test method/class the given Java file belongs to.
7046
+ * @param {string} path - absolute path of a `src/test/java/**.java` file.
7047
+ */
7048
+ function runTestFor(path) {
7049
+ var target = testRunTarget(path, cwd)
7050
+ if (target === null) return
7051
+ if (testPollRef.current !== null) { clearTimeout(testPollRef.current); testPollRef.current = null }
7052
+ setTestRun({ path: path, id: '', className: target.className, command: '', status: 'starting', output: '', exitCode: null })
7053
+ runTestStart(scopeRef.current, target).then(function (started) {
7054
+ setTestRun(function (previous) {
7055
+ if (previous === null) return previous
7056
+ return Object.assign({}, previous, { id: started.id, command: started.command, status: 'running' })
7057
+ })
7058
+ pollTestRun(started.id)
7059
+ }).catch(function (problem) {
7060
+ setTestRun(function (previous) {
7061
+ if (previous === null) return previous
7062
+ return Object.assign({}, previous, { status: 'failed', output: messageOf(problem) || '启动测试失败' })
7063
+ })
7064
+ })
7065
+ }
5762
7066
  var [logFontSize, setLogFontSize] = useState(function () { return clampFontSize(readPref(PREF_FONT_SIZE, DEFAULT_FONT_SIZE)) })
5763
7067
  // A different log file re-follows (the viewer used to remount and reset this).
5764
7068
  useEffect(function () {
@@ -5813,11 +7117,17 @@ var [ui, setUi] = useState(function () {
5813
7117
  * be dismissed by hand and only ever showed the LAST message).
5814
7118
  * @param {string} text - the message.
5815
7119
  */
5816
- function note(text) {
7120
+ function note(text, action) {
5817
7121
  if (typeof text !== 'string' || text === '') return
5818
7122
  toastSeqRef.current += 1
5819
7123
  var id = toastSeqRef.current
5820
- setToasts(function (prev) { return capToasts((prev || []).concat([{ id: id, text: text }])) })
7124
+ var item = { id: id, text: text }
7125
+ // An inline action (undo) turns "remember Ctrl+Z" into one click.
7126
+ if (action !== null && typeof action === 'object' && typeof action.label === 'string'
7127
+ && typeof action.run === 'function') {
7128
+ item.action = action
7129
+ }
7130
+ setToasts(function (prev) { return capToasts((prev || []).concat([item])) })
5821
7131
  setMessages(function (prev) { return capMessages((prev || []).concat([{ id: id, text: text, at: Date.now() }])) })
5822
7132
  setUnreadMessages(function (prev) { return prev + 1 })
5823
7133
  if (typeof setTimeout !== 'function') return
@@ -5874,6 +7184,25 @@ var [ui, setUi] = useState(function () {
5874
7184
  function isDirty(path) {
5875
7185
  return docDirty(docs[path], viewerStates[path])
5876
7186
  }
7187
+ /**
7188
+ * Guard the whole window against an accidental close/reload while any open
7189
+ * buffer is dirty (PM gap #3 — the last irreversible action left). The
7190
+ * browser owns the dialog text; `preventDefault` + `returnValue` is the only
7191
+ * portable way to raise it, and Firefox additionally reads the return value.
7192
+ */
7193
+ useEffect(function () {
7194
+ var dirty = (Array.isArray(openFiles) ? openFiles : []).filter(function (path) {
7195
+ return isDirty(path) === true
7196
+ })
7197
+ if (dirty.length === 0) return undefined
7198
+ var onBeforeUnload = function (event) {
7199
+ event.preventDefault()
7200
+ event.returnValue = ''
7201
+ return ''
7202
+ }
7203
+ window.addEventListener('beforeunload', onBeforeUnload)
7204
+ return function () { window.removeEventListener('beforeunload', onBeforeUnload) }
7205
+ }, [openFiles, docs, viewerStates])
5877
7206
  /**
5878
7207
  * Forget one path's document AND the last viewer state it reported.
5879
7208
  *
@@ -5919,6 +7248,18 @@ var [ui, setUi] = useState(function () {
5919
7248
  }).catch(function (problem) {
5920
7249
  if (cancelled.current) return
5921
7250
  var code = problem && problem.kind !== undefined ? problem.kind : undefined
7251
+ if (code === 'too-large' && forceEditPathsRef.current.has(path)) {
7252
+ // The user already asked for this file to be editable: skip the preview
7253
+ // and pull the whole thing in chunks.
7254
+ setDocs(function (prev) {
7255
+ if (prev[path] !== undefined) return prev
7256
+ var next = Object.assign({}, prev)
7257
+ next[path] = { kind: 'large-text', text: '', offset: 0, next: 0, eof: false, size: typeof problem.size === 'number' ? problem.size : 0, loading: false, error: undefined, dropLines: 0 }
7258
+ return next
7259
+ })
7260
+ setTimeout(function () { void forceEditLargeText(path) }, 50)
7261
+ return
7262
+ }
5922
7263
  if (code === 'too-large') {
5923
7264
  // Above the whole-read limit: open a windowed READ-ONLY preview
5924
7265
  // instead of an empty "文件过大" state.
@@ -5929,7 +7270,20 @@ var [ui, setUi] = useState(function () {
5929
7270
  next[path] = { kind: 'large-text', text: '', offset: 0, next: 0, eof: false, size: size, loading: false, error: undefined, dropLines: 0 }
5930
7271
  return next
5931
7272
  })
5932
- void loadLargeTextPage(path)
7273
+ // The doc we just queued is not in `docsRef` until React commits, and
7274
+ // `loadLargeTextPage` reads that ref: called here it saw `undefined` and
7275
+ // returned, leaving the preview at "已加载 0 KB" forever. Wait for the
7276
+ // commit (bounded retry), then pull the first window.
7277
+ function startFirstPage(attempt) {
7278
+ var current = docsRef.current[path]
7279
+ if (current !== undefined && current.kind === 'large-text') {
7280
+ void loadLargeTextPage(path)
7281
+ return
7282
+ }
7283
+ if (attempt >= 20) return
7284
+ setTimeout(function () { startFirstPage(attempt + 1) }, 50)
7285
+ }
7286
+ startFirstPage(0)
5933
7287
  return
5934
7288
  }
5935
7289
  setDocs(function (prev) {
@@ -5942,59 +7296,129 @@ var [ui, setUi] = useState(function () {
5942
7296
  })
5943
7297
  }
5944
7298
  /**
5945
- * Append the next page to a large text preview.
7299
+ * Append the next page to a large text preview.
7300
+ *
7301
+ * The preview keeps the loaded text in memory but only renders the visible
7302
+ * slice, and stops at `LARGE_TEXT_MAX_BYTES`, so opening a 1 GB log costs one
7303
+ * window, not the file.
7304
+ * @param {string} path - file path whose page should be appended.
7305
+ */
7306
+ async function loadLargeTextPage(path) {
7307
+ var doc = docsRef.current[path]
7308
+ if (doc === undefined || doc.kind !== 'large-text') return
7309
+ if (doc.loading === true || doc.eof === true) return
7310
+ var from = typeof doc.next === 'number' ? doc.next : 0
7311
+ setDocs(function (prev) {
7312
+ var current = prev[path]
7313
+ if (current === undefined || current.kind !== 'large-text' || current.loading === true) return prev
7314
+ var next = Object.assign({}, prev)
7315
+ next[path] = Object.assign({}, current, { loading: true })
7316
+ return next
7317
+ })
7318
+ var page
7319
+ try {
7320
+ page = await fsWindowRead(scopeRef.current, path, from, LARGE_TEXT_WINDOW_BYTES)
7321
+ } catch (problem) {
7322
+ setDocs(function (prev) {
7323
+ var current = prev[path]
7324
+ if (current === undefined || current.kind !== 'large-text') return prev
7325
+ var next = Object.assign({}, prev)
7326
+ next[path] = Object.assign({}, current, { loading: false, error: messageOf(problem) || '读取失败' })
7327
+ return next
7328
+ })
7329
+ return
7330
+ }
7331
+ setDocs(function (prev) {
7332
+ var current = prev[path]
7333
+ if (current === undefined || current.kind !== 'large-text') return prev
7334
+ // Keep memory bounded while the reader keeps scrolling: drop the front
7335
+ // (at a line boundary) once the buffer passes the cap, and remember how
7336
+ // many lines went away so the virtual grid stays aligned.
7337
+ var loaded = String(current.text || '') + page.text
7338
+ var trimmed = trimLargeTextFront(loaded, LARGE_TEXT_MAX_BYTES)
7339
+ var next = Object.assign({}, prev)
7340
+ next[path] = Object.assign({}, current, {
7341
+ text: trimmed.text,
7342
+ dropLines: (typeof current.dropLines === 'number' ? current.dropLines : 0) + trimmed.droppedLines,
7343
+ offset: page.offset,
7344
+ next: page.next,
7345
+ eof: page.eof,
7346
+ size: page.size || current.size,
7347
+ loading: false,
7348
+ error: undefined,
7349
+ })
7350
+ return next
7351
+ })
7352
+ }
7353
+
7354
+ /**
7355
+ * Read a whole file in window-sized chunks (the preview deliberately drops
7356
+ * its front, so a forced edit has to walk the file itself).
7357
+ * @param {string} path - absolute file path.
7358
+ * @returns {Promise<string>} the entire file content.
7359
+ */
7360
+ async function readWholeFileText(path) {
7361
+ var text = ''
7362
+ var from = 0
7363
+ for (;;) {
7364
+ var page = await fsWindowRead(scopeRef.current, path, from, LARGE_TEXT_WINDOW_BYTES)
7365
+ text += page.text
7366
+ if (page.eof === true || typeof page.next !== 'number' || page.next <= from) break
7367
+ from = page.next
7368
+ if (text.length > LARGE_TEXT_FORCE_MAX_BYTES) throw { message: '文件超过 ' + formatBytes(LARGE_TEXT_FORCE_MAX_BYTES) }
7369
+ }
7370
+ return text
7371
+ }
7372
+
7373
+ /**
7374
+ * Turn a read-only large preview into a normal editable document.
5946
7375
  *
5947
- * The preview keeps the loaded text in memory but only renders the visible
5948
- * slice, and stops at `LARGE_TEXT_MAX_BYTES`, so opening a 1 GB log costs one
5949
- * window, not the file.
5950
- * @param {string} path - file path whose page should be appended.
7376
+ * Only the explicit 编辑 button (or a path the user already forced) does this:
7377
+ * the whole file lands in `docs[path]` as `kind:'text'`, and the path is
7378
+ * remembered so closing/reopening the tab keeps the editable form.
7379
+ * @param {string} path - absolute file path.
5951
7380
  */
5952
- async function loadLargeTextPage(path) {
7381
+ async function forceEditLargeText(path) {
5953
7382
  var doc = docsRef.current[path]
5954
7383
  if (doc === undefined || doc.kind !== 'large-text') return
5955
- if (doc.loading === true || doc.eof === true) return
5956
- var from = typeof doc.next === 'number' ? doc.next : 0
7384
+ var size = typeof doc.size === 'number' ? doc.size : 0
7385
+ if (size > LARGE_TEXT_FORCE_MAX_BYTES) {
7386
+ notify('文件太大(' + formatBytes(size) + '),不能强制全量编辑;右端按钮上限 ' + formatBytes(LARGE_TEXT_FORCE_MAX_BYTES))
7387
+ return
7388
+ }
7389
+ forceEditPathsRef.current.add(path)
5957
7390
  setDocs(function (prev) {
5958
7391
  var current = prev[path]
5959
- if (current === undefined || current.kind !== 'large-text' || current.loading === true) return prev
7392
+ if (current === undefined || current.kind !== 'large-text') return prev
5960
7393
  var next = Object.assign({}, prev)
5961
- next[path] = Object.assign({}, current, { loading: true })
7394
+ next[path] = Object.assign({}, current, { loading: true, error: undefined })
5962
7395
  return next
5963
7396
  })
5964
- var page
7397
+ var text
5965
7398
  try {
5966
- page = await fsWindowRead(scopeRef.current, path, from, LARGE_TEXT_WINDOW_BYTES)
7399
+ text = await readWholeFileText(path)
5967
7400
  } catch (problem) {
7401
+ forceEditPathsRef.current.delete(path)
5968
7402
  setDocs(function (prev) {
5969
7403
  var current = prev[path]
5970
7404
  if (current === undefined || current.kind !== 'large-text') return prev
5971
7405
  var next = Object.assign({}, prev)
5972
- next[path] = Object.assign({}, current, { loading: false, error: messageOf(problem) || '读取失败' })
7406
+ next[path] = Object.assign({}, current, { loading: false, error: messageOf(problem) || '强制加载失败' })
5973
7407
  return next
5974
7408
  })
7409
+ notify('强制加载失败:' + (messageOf(problem) || '读取失败'))
5975
7410
  return
5976
7411
  }
7412
+ var eol = text.indexOf('\r\n') !== -1 ? '\r\n' : '\n'
7413
+ var normalized = eol === '\r\n' ? text.replace(/\r\n/g, '\n') : text
5977
7414
  setDocs(function (prev) {
5978
7415
  var current = prev[path]
5979
7416
  if (current === undefined || current.kind !== 'large-text') return prev
5980
- // Keep memory bounded while the reader keeps scrolling: drop the front
5981
- // (at a line boundary) once the buffer passes the cap, and remember how
5982
- // many lines went away so the virtual grid stays aligned.
5983
- var loaded = String(current.text || '') + page.text
5984
- var trimmed = trimLargeTextFront(loaded, LARGE_TEXT_MAX_BYTES)
5985
7417
  var next = Object.assign({}, prev)
5986
- next[path] = Object.assign({}, current, {
5987
- text: trimmed.text,
5988
- dropLines: (typeof current.dropLines === 'number' ? current.dropLines : 0) + trimmed.droppedLines,
5989
- offset: page.offset,
5990
- next: page.next,
5991
- eof: page.eof,
5992
- size: page.size || current.size,
5993
- loading: false,
5994
- error: undefined,
5995
- })
7418
+ next[path] = { kind: 'text', text: normalized, saved: normalized, eol: eol }
5996
7419
  return next
5997
7420
  })
7421
+ notify('已全量加载并进入编辑:' + fileBaseName(path))
5998
7422
  }
5999
7423
 
6000
7424
  /**
@@ -6065,6 +7489,20 @@ var [ui, setUi] = useState(function () {
6065
7489
  setOpenFile(path)
6066
7490
  setRecentFiles(function (previous) { return pushRecent(previous, path, SEARCH_RECENT_LIMIT) })
6067
7491
  }
7492
+ // 📄 in the CONSOLE title bar of the standalone window: that window has no
7493
+ // DSH sidebar editor, so the panel hands the config path over and it opens
7494
+ // here as an ordinary tab (`.dsh-ris-ide.json` is a hidden dotfile, so the
7495
+ // tree and the search box cannot reach it).
7496
+ var configOpenNonce = props.openConfigRequest !== null && typeof props.openConfigRequest === 'object'
7497
+ && typeof props.openConfigRequest.nonce === 'number' ? props.openConfigRequest.nonce : 0
7498
+ useEffect(function () {
7499
+ if (configOpenNonce === 0) return
7500
+ var request = props.openConfigRequest
7501
+ if (request === null || typeof request !== 'object') return
7502
+ if (typeof request.path !== 'string' || request.path === '') return
7503
+ openPath(request.path)
7504
+ note('已在编辑器打开 ' + shortName(request.path) + '(改完保存即生效)')
7505
+ }, [configOpenNonce])
6068
7506
  function closePath(path) {
6069
7507
  debugOpenedRef.current = debugOpenedRef.current.filter(function (item) { return item !== path })
6070
7508
  var index = openFiles.indexOf(path)
@@ -6216,11 +7654,13 @@ var [ui, setUi] = useState(function () {
6216
7654
  setUi(function (prev) { return Object.assign({}, prev, { busy: true, note: '' }) })
6217
7655
  statusNote('正在启动 ' + program.name + '…', 0)
6218
7656
  setConsoleBusy(program.id)
7657
+ setConsoleBusyKind('start')
6219
7658
  var result
6220
7659
  try {
6221
7660
  result = await requestStart(program.id, scopeRef.current)
6222
7661
  } finally {
6223
7662
  setConsoleBusy('')
7663
+ setConsoleBusyKind('')
6224
7664
  }
6225
7665
  setUi(function (prev) { return Object.assign({}, prev, { busy: false }) })
6226
7666
  if (logPath !== '') {
@@ -6233,15 +7673,96 @@ var [ui, setUi] = useState(function () {
6233
7673
  async function consoleStop(program) {
6234
7674
  statusNote('正在停止 ' + program.name + '…', 0)
6235
7675
  setConsoleBusy(program.id)
7676
+ setConsoleBusyKind('stop')
6236
7677
  var result
6237
7678
  try {
6238
7679
  result = await requestStop(program.logPath, scopeRef.current)
6239
7680
  } finally {
6240
7681
  setConsoleBusy('')
7682
+ setConsoleBusyKind('')
6241
7683
  }
6242
7684
  statusNote('')
6243
7685
  if (result.ok !== true) return note('停止失败:' + result.error)
6244
7686
  }
7687
+ /** Restart one program: the host stops it (pidfile released) then starts it. */
7688
+ async function consoleRestart(program) {
7689
+ selectProgram(program)
7690
+ broadcastLogFocus(program.logPath)
7691
+ var logPath = typeof program.logPath === 'string' ? program.logPath : ''
7692
+ var baseline = logPath === '' ? undefined : await logSizeOf(logPath)
7693
+ statusNote('正在重启 ' + program.name + '…', 0)
7694
+ setConsoleBusy(program.id)
7695
+ setConsoleBusyKind('restart')
7696
+ var result
7697
+ try {
7698
+ result = await requestStart(program.id, scopeRef.current, true)
7699
+ } finally {
7700
+ setConsoleBusy('')
7701
+ setConsoleBusyKind('')
7702
+ }
7703
+ statusNote('')
7704
+ setLogNonce(function (value) { return value + 1 })
7705
+ if (logPath !== '' && result.ok === true) watchLogOutput(logPath, baseline)
7706
+ if (result.ok !== true) return note('重启失败:' + result.error)
7707
+ }
7708
+ /**
7709
+ * Programs ticked in the console for a batch start/stop (PM gap #7): the
7710
+ * batch bar appears only once more than one row is ticked.
7711
+ */
7712
+ var [checkedIds, setCheckedIds] = useState([])
7713
+ function toggleChecked(programId) {
7714
+ setCheckedIds(function (previous) {
7715
+ if (previous.indexOf(programId) === -1) return previous.concat([programId])
7716
+ return previous.filter(function (id) { return id !== programId })
7717
+ })
7718
+ }
7719
+ /**
7720
+ * Start every runnable program in console order, or stop them in reverse.
7721
+ * Sequential: each start waits for a pidfile/build, and console order IS the
7722
+ * dependency order the config file lists (PM gap #7).
7723
+ * @param {'start'|'stop'} kind - which direction.
7724
+ */
7725
+ async function consoleBatch(kind) {
7726
+ if (consoleBulkRef.current === true) return
7727
+ var targets = programs.filter(function (program) {
7728
+ if (checkedIds.indexOf(program.id) === -1) return false
7729
+ if (program.kind === 'instance') return false
7730
+ var alive = program.running !== null && program.running !== undefined && program.running.alive === true
7731
+ return kind === 'stop' ? alive : !alive
7732
+ })
7733
+ if (kind === 'stop') targets = targets.slice().reverse()
7734
+ if (targets.length === 0) return note(kind === 'start' ? '没有需要启动的项目' : '没有正在运行的项目')
7735
+ consoleBulkRef.current = true
7736
+ var failures = 0
7737
+ try {
7738
+ for (var index = 0; index < targets.length; index += 1) {
7739
+ setConsoleBulk({ kind: kind, index: index, total: targets.length })
7740
+ setConsoleBusy(targets[index].id)
7741
+ setConsoleBusyKind(kind)
7742
+ if (kind === 'start') {
7743
+ selectProgram(targets[index])
7744
+ broadcastLogFocus(targets[index].logPath)
7745
+ }
7746
+ try {
7747
+ var result = kind === 'start'
7748
+ ? await requestStart(targets[index].id, scopeRef.current)
7749
+ : await requestStop(targets[index].logPath, scopeRef.current)
7750
+ if (result.ok !== true) failures += 1
7751
+ } catch {
7752
+ failures += 1
7753
+ }
7754
+ }
7755
+ } finally {
7756
+ setConsoleBusy('')
7757
+ setConsoleBusyKind('')
7758
+ consoleBulkRef.current = false
7759
+ setConsoleBulk(null)
7760
+ }
7761
+ setLogNonce(function (value) { return value + 1 })
7762
+ // Row states already show what happened; only failures need a toast.
7763
+ if (failures > 0) note(failures + ' 项失败:' + (kind === 'start' ? '启动' : '停止') + '没有成功')
7764
+ setCheckedIds([])
7765
+ }
6245
7766
  async function consoleDebug(program) {
6246
7767
  selectProgram(program)
6247
7768
  broadcastLogFocus(program.logPath)
@@ -6251,11 +7772,13 @@ var [ui, setUi] = useState(function () {
6251
7772
  // The row keeps its own mask for the whole JDWP restart: the console must
6252
7773
  // not accept a second start/debug click while the JVM is coming up.
6253
7774
  setConsoleBusy(program.id)
7775
+ setConsoleBusyKind('debug')
6254
7776
  var result
6255
7777
  try {
6256
7778
  result = await requestDebug('start', scopeRef.current, { id: program.id })
6257
7779
  } finally {
6258
7780
  setConsoleBusy('')
7781
+ setConsoleBusyKind('')
6259
7782
  }
6260
7783
  setUi(function (prev) { return Object.assign({}, prev, { busy: false, note: result.ok === true ? ('已连接调试 ' + program.name + ',端口 ' + (result.port ?? '?')) : ('调试启动失败:' + result.error) }) })
6261
7784
  await pollOnce(program.logPath)
@@ -6828,12 +8351,20 @@ var [ui, setUi] = useState(function () {
6828
8351
  useEffect(function () {
6829
8352
  var text = treeQuery.trim()
6830
8353
  if (text === '') { setSearchHits(null); setSearchBusy(false); return undefined }
8354
+ var cached = searchCacheRef.current.get('name:' + text)
8355
+ if (cached !== undefined && cached !== null) {
8356
+ setSearchHits(cached)
8357
+ setSearchBusy(false)
8358
+ return undefined
8359
+ }
6831
8360
  var cancelled = false
6832
8361
  setSearchBusy(true)
6833
8362
  var timer = setTimeout(function () {
6834
8363
  fsSearch(scopeRef.current, text).then(function (result) {
6835
8364
  if (cancelled) return
6836
- setSearchHits(searchHitPayload(result, cwd))
8365
+ var payload = searchHitPayload(result, cwd)
8366
+ rememberSearchEntry(searchCacheRef.current, 'name:' + text, payload)
8367
+ setSearchHits(payload)
6837
8368
  setSearchBusy(false)
6838
8369
  }).catch(function (problem) {
6839
8370
  if (cancelled) return
@@ -6844,6 +8375,51 @@ var [ui, setUi] = useState(function () {
6844
8375
  return function () { cancelled = true; clearTimeout(timer) }
6845
8376
  }, [treeQuery, cwd])
6846
8377
 
8378
+ /**
8379
+ * Content search for the same query: slower than the name search (one
8380
+ * `git grep -n` per call, no index — a deliberate product promise), so it
8381
+ * runs on its own slightly longer debounce and never blocks the file list.
8382
+ */
8383
+ useEffect(function () {
8384
+ var text = treeQuery.trim()
8385
+ if (text.length < 2) { setContentHits([]); setContentBusy(false); return undefined }
8386
+ var cached = searchCacheRef.current.get('content:' + text)
8387
+ if (cached !== undefined && Array.isArray(cached)) {
8388
+ setContentHits(cached)
8389
+ setContentBusy(false)
8390
+ return undefined
8391
+ }
8392
+ var cancelled = false
8393
+ setContentBusy(true)
8394
+ var timer = setTimeout(function () {
8395
+ fsSearchContent(scopeRef.current, text).then(function (list) {
8396
+ if (cancelled) return
8397
+ rememberSearchEntry(searchCacheRef.current, 'content:' + text, Array.isArray(list) ? list : [])
8398
+ setContentHits(list)
8399
+ setContentBusy(false)
8400
+ }).catch(function () {
8401
+ if (cancelled) return
8402
+ setContentHits([])
8403
+ setContentBusy(false)
8404
+ })
8405
+ }, 450)
8406
+ return function () { cancelled = true; clearTimeout(timer) }
8407
+ }, [treeQuery, cwd])
8408
+
8409
+ /**
8410
+ * A shortcut (Ctrl+R / Ctrl+Shift+R / F3) focused the box: select its text
8411
+ * once React has painted the value, otherwise the controlled update resets
8412
+ * the selection to the end and the highlight the user asked for is lost.
8413
+ */
8414
+ useEffect(function () {
8415
+ if (searchFocusPendingRef.current !== true) return
8416
+ var input = searchInputRef.current
8417
+ if (input === null) return
8418
+ searchFocusPendingRef.current = false
8419
+ input.focus()
8420
+ input.select()
8421
+ }, [searchFocusNonce, treeQuery])
8422
+
6847
8423
  /**
6848
8424
  * New results (and every keystroke) reset the highlight: the row whose file
6849
8425
  * name matches the query exactly, else the first row — so the dropdown opens
@@ -6851,17 +8427,61 @@ var [ui, setUi] = useState(function () {
6851
8427
  */
6852
8428
  useEffect(function () {
6853
8429
  setSearchActive(searchHitActiveIndex(searchHits, treeQuery))
6854
- }, [searchHits, treeQuery])
8430
+ }, [searchHits, treeQuery, contentHits.length])
6855
8431
 
6856
- /** A dropdown pick: open files, reveal either kind in the tree, close the list. */
8432
+ /**
8433
+ * A dropdown pick: open files, reveal either kind in the tree, close the list.
8434
+ * The QUERY and the result set survive (user口径): the picked row can be
8435
+ * reopened, and `searchCacheRef` already holds the `git grep` output.
8436
+ */
6857
8437
  function pickSearchHit(path, isDir) {
6858
- setTreeQuery('')
6859
- setSearchHits(null)
8438
+ setSearchFocused(false)
8439
+ // Blur so clicking the box again fires focus (and reopens the cached
8440
+ // dropdown) instead of leaving it silently focused-but-closed.
8441
+ if (searchInputRef.current !== null) searchInputRef.current.blur()
6860
8442
  locateNonceRef.current += 1
6861
8443
  setLocateRequest({ kind: isDir === true ? 'dir' : 'file', path: path, nonce: locateNonceRef.current })
6862
8444
  if (isDir !== true) openPath(path)
6863
8445
  }
6864
8446
 
8447
+ /**
8448
+ * A CONTENT hit: open the file, then run its own find for that text once, so
8449
+ * the caret lands on the match (user口径:选中内容检索结果后,编辑器弹出内容检索框
8450
+ * 并填入内容执行一次 find)。
8451
+ * @param {{hit: {path: string, line: number, text: string}, query?: string}} pick - the row.
8452
+ */
8453
+ function openContentHit(pick) {
8454
+ var hit = pick !== null && pick !== undefined && pick.hit !== undefined ? pick.hit : null
8455
+ if (hit === null || typeof hit.path !== 'string') return
8456
+ // Keep the query (and the cached hits): reopening the same row must work.
8457
+ setSearchFocused(false)
8458
+ if (searchInputRef.current !== null) searchInputRef.current.blur()
8459
+ var path = hit.path
8460
+ var needle = typeof pick.query === 'string' && pick.query !== ''
8461
+ ? pick.query
8462
+ : typeof hit.text === 'string' ? hit.text.trim() : ''
8463
+ // The query goes INTO the editor's own find box (user口径: 打开结果文件
8464
+ // 同时触发一次编辑内容查询). The viewer registers asynchronously and
8465
+ // `openPath` is not guaranteed to return a promise, so retry a few frames
8466
+ // instead of assuming either (`... undefined.then` used to throw a toast).
8467
+ function applyFind(attempt) {
8468
+ var controls = viewerControlsRef.current[path]
8469
+ if (controls !== undefined && controls !== null && typeof controls.searchFor === 'function') {
8470
+ delete pendingFindRef.current[path]
8471
+ controls.searchFor(needle, hit.line)
8472
+ return
8473
+ }
8474
+ if (attempt >= 200) return
8475
+ setTimeout(function () { applyFind(attempt + 1) }, 50)
8476
+ }
8477
+ pendingFindRef.current[path] = { needle: needle, line: hit.line }
8478
+ var opened = openPath(path)
8479
+ if (opened !== null && opened !== undefined && typeof opened.then === 'function') {
8480
+ void opened.then(function (ok) { if (ok !== false) applyFind(0) })
8481
+ } else {
8482
+ applyFind(0)
8483
+ }
8484
+ }
6865
8485
  var runningSignature = programs.filter(function (program) {
6866
8486
  return program.running !== null && program.running !== undefined && program.running.alive === true
6867
8487
  }).map(function (program) { return program.kind + '|' + program.logPath }).join(',')
@@ -7071,14 +8691,22 @@ var [ui, setUi] = useState(function () {
7071
8691
  return function () { window.removeEventListener('keydown', onKey) }
7072
8692
  }, [visible, viewPath, dbg.attached, dbg.suspended])
7073
8693
 
7074
- /** `autoDebug` (the 「调试」 button) starts the session on arrival. */
8694
+ /**
8695
+ * `autoDebug` (the sidebar 🐞 button) starts the JDWP session on arrival.
8696
+ *
8697
+ * It cannot run on mount: the program list is still empty then, so neither
8698
+ * the debuggable kind nor `debugProgramId` is known yet and `startDebug()`
8699
+ * bailed out for good. The effect now waits for that row and fires once.
8700
+ */
8701
+ var autoDebugRef = useRef(meta.autoDebug === true || (openProgram !== null && openProgram.autoDebug === true))
7075
8702
  useEffect(function () {
7076
- if (!debuggable || startedRef.current) return
7077
- if (meta.autoDebug === true && typeof sessionId === 'string' && sessionId !== '') {
7078
- startedRef.current = true
7079
- void startDebug()
7080
- }
7081
- }, [])
8703
+ if (autoDebugRef.current !== true || startedRef.current) return
8704
+ if (!debuggable || debugProgramId === undefined || ui.busy) return
8705
+ if (typeof sessionId !== 'string' || sessionId === '') return
8706
+ autoDebugRef.current = false
8707
+ startedRef.current = true
8708
+ void startDebug()
8709
+ }, [debuggable, debugProgramId, ui.busy, sessionId])
7082
8710
 
7083
8711
  // ── small pieces ─────────────────────────────────────────────────────
7084
8712
  /**
@@ -7388,78 +9016,6 @@ var [ui, setUi] = useState(function () {
7388
9016
  : '(这里还没有数据)')
7389
9017
  : rows))
7390
9018
 
7391
- /**
7392
- * Read-only preview of a text file above the whole-read limit.
7393
- *
7394
- * Pages are fetched on demand (`loadLargeTextPage`) as the box scrolls near
7395
- * its bottom, and only the visible lines are rendered (fixed 18px rows), so
7396
- * the DOM and the memory stay bounded by one page plus the viewport.
7397
- * Editing is impossible by construction: no editor is mounted and nothing
7398
- * writes this file back.
7399
- */
7400
- function LargeTextPreview(props) {
7401
- var doc = props.doc
7402
- var boxRef = React.useRef(null)
7403
- var [scrollTop, setScrollTop] = React.useState(0)
7404
- var [viewportHeight, setViewportHeight] = React.useState(600)
7405
- var lineHeight = 18
7406
- var lines = React.useMemo(function () { return String(doc.text || '').split('\n') }, [doc.text])
7407
- var dropLines = typeof doc.dropLines === 'number' ? doc.dropLines : 0
7408
- var total = dropLines + lines.length
7409
- var prevDropRef = React.useRef(dropLines)
7410
- var first = Math.max(0, Math.floor(scrollTop / lineHeight) - 4)
7411
- var count = Math.max(0, Math.ceil(viewportHeight / lineHeight) + 8)
7412
- var visible = lines.slice(first, first + count)
7413
- function onScroll(event) {
7414
- var box = event.currentTarget
7415
- setScrollTop(box.scrollTop)
7416
- setViewportHeight(box.clientHeight)
7417
- if (box.scrollTop + box.clientHeight > box.scrollHeight - 240) props.onLoadMore()
7418
- }
7419
- React.useEffect(function () {
7420
- if (boxRef.current !== null) setViewportHeight(boxRef.current.clientHeight)
7421
- }, [doc.size])
7422
- // Freeing the front shrinks the scroll height: move the viewport by the
7423
- // same amount so the line the reader is looking at stays put.
7424
- React.useEffect(function () {
7425
- var freed = dropLines - prevDropRef.current
7426
- prevDropRef.current = dropLines
7427
- if (freed > 0 && boxRef.current !== null) {
7428
- boxRef.current.scrollTop = Math.max(0, boxRef.current.scrollTop - freed * lineHeight)
7429
- }
7430
- }, [dropLines])
7431
- var loadedKb = Math.round(String(doc.text || '').length / 1024)
7432
- var totalMb = typeof doc.size === 'number' && doc.size > 0 ? doc.size / (1024 * 1024) : 0
7433
- var loadedNote = '已加载 ' + loadedKb + ' KB / ' + totalMb.toFixed(1) + ' MB'
7434
- return h('div', { style: S.largeText, 'data-large-text': '1' },
7435
- h('div', { style: S.largeTextBar, 'data-large-text-bar': '1' },
7436
- h('span', { style: { fontWeight: 600 } }, '只读预览 · 大文件'),
7437
- h('span', { style: S.spacer }),
7438
- h('span', { style: S.meta, 'data-large-text-loaded': String(loadedKb) }, loadedNote),
7439
- doc.eof === true
7440
- ? h('span', { style: S.meta }, '(已全部加载)')
7441
- : h('span', { style: S.meta }, '(滚动到底继续加载)'),
7442
- dropLines > 0
7443
- ? h('span', { style: S.meta, 'data-large-text-freed': String(dropLines) }, '已释放前面 ' + dropLines + ' 行')
7444
- : null,
7445
- dropLines > 0
7446
- ? h('button', {
7447
- type: 'button', style: S.buttonOff, 'data-large-text-restart': '1', title: '从文件开头重新加载(会丢弃当前已释放的部分)',
7448
- onClick: function () { props.onRestart() },
7449
- }, '从头加载')
7450
- : null,
7451
- doc.loading === true ? h('span', { style: S.meta }, '加载中…') : null),
7452
- doc.error !== undefined
7453
- ? h('div', { style: S.error, role: 'alert', 'data-large-text-error': '1' }, '读取失败:' + String(doc.error))
7454
- : null,
7455
- h('div', { ref: boxRef, style: S.largeTextBox, onScroll: onScroll, tabIndex: 0, 'data-large-text-body': '1' },
7456
- h('div', { style: { position: 'relative', height: Math.max(1, total) * lineHeight } },
7457
- h('div', { style: { position: 'absolute', top: first * lineHeight, left: 0, right: 0 } },
7458
- visible.map(function (line, index) {
7459
- return h('div', { key: first + index, style: S.largeTextLine, 'data-large-text-line': String(first + index + 1) }, line === '' ? '\u00a0' : line)
7460
- })))))
7461
- }
7462
-
7463
9019
  /** The source pane: paged/closable file tabs + the editor or a preview. */
7464
9020
  /**
7465
9021
  * One mounted file pane. ALL open files stay mounted (inactive ones are
@@ -7478,9 +9034,10 @@ var [ui, setUi] = useState(function () {
7478
9034
  body = h(IdeMediaView, { scope: scopeRef.current, path: path, kind: doc.kind, fontRatio: fontRatio })
7479
9035
  } else if (doc.kind === 'large-text') {
7480
9036
  body = h(LargeTextPreview, {
7481
- doc: doc,
9037
+ doc: doc, path: path, active: active,
7482
9038
  onLoadMore: function () { void loadLargeTextPage(path) },
7483
9039
  onRestart: function () { reloadLargeTextFromStart(path) },
9040
+ onForceEdit: function () { void forceEditLargeText(path) },
7484
9041
  })
7485
9042
  } else if (doc.kind === 'error') {
7486
9043
  body = workbenchDismissals.isOpen('file-error', path + ':' + String(doc.error)) ? h('div', { style: Object.assign({}, S.error, { display: 'flex', alignItems: 'center', gap: 6 }), role: 'alert', 'data-file-error': '1' },
@@ -7536,6 +9093,13 @@ var [ui, setUi] = useState(function () {
7536
9093
  var store = viewerControlsRef.current
7537
9094
  if (controls === null || controls === undefined) delete store[path]
7538
9095
  else store[path] = controls
9096
+ // A content-search hit may have arrived before this viewer existed.
9097
+ var pending = pendingFindRef.current[path]
9098
+ if (pending !== undefined && controls !== null && controls !== undefined
9099
+ && typeof controls.searchFor === 'function') {
9100
+ delete pendingFindRef.current[path]
9101
+ controls.searchFor(pending.needle, pending.line)
9102
+ }
7539
9103
  },
7540
9104
  })
7541
9105
  }
@@ -7585,7 +9149,7 @@ var [ui, setUi] = useState(function () {
7585
9149
  function previewToggleBar() {
7586
9150
  if (openFile === '' || supportsTextPreview(openFile) !== true) return null
7587
9151
  var previewing = previewOpen[openFile] === true
7588
- return h('div', { style: S.previewToggleBar, 'data-preview-toggle': previewing ? 'open' : 'closed' },
9152
+ return h('div', { style: S.previewFloat, 'data-preview-toggle': previewing ? 'open' : 'closed' },
7589
9153
  h('button', {
7590
9154
  type: 'button', style: Object.assign({}, S.buttonOff, { padding: '0 8px' }),
7591
9155
  'data-action': previewing ? 'preview-exit' : 'preview-enter',
@@ -7624,6 +9188,21 @@ var [ui, setUi] = useState(function () {
7624
9188
  }, '×'))
7625
9189
  })),
7626
9190
  h('button', { type: 'button', style: S.tabPage, 'data-tab-page': 'next', title: '下一页页签', onClick: function () { pageTabs(1) } }, '▶'),
9191
+ h('button', {
9192
+ type: 'button', style: S.tabPage, 'data-action': 'diff',
9193
+ title: openFile === '' ? '先打开一个文件' : '与磁盘版本对比:看这一版到底改了哪几行(有未保存修改时可用)',
9194
+ disabled: openFile === '' || isDirty(openFile) !== true,
9195
+ onClick: function () { setDiffPath(diffPath === openFile ? null : openFile) },
9196
+ }, '±'),
9197
+ testRunTarget(openFile, cwd) === null
9198
+ ? null
9199
+ : h('button', {
9200
+ type: 'button', style: S.tabPage, 'data-action': 'run-test',
9201
+ 'data-test-target': testRunTarget(openFile, cwd).className,
9202
+ title: '运行这个文件所属的测试:'
9203
+ + testRunTarget(openFile, cwd).test + '(mvn -pl ' + testRunTarget(openFile, cwd).module + ' test)',
9204
+ onClick: function () { runTestFor(openFile) },
9205
+ }, '▶'),
7627
9206
  h('button', {
7628
9207
  type: 'button', style: S.tabPage, 'data-action': 'tabs-menu', title: '已打开的文件与最近历史(最多 30 条)',
7629
9208
  onMouseDown: function (event) { event.stopPropagation() },
@@ -7745,18 +9324,104 @@ var [ui, setUi] = useState(function () {
7745
9324
  }))
7746
9325
  : null
7747
9326
  var previewing = openFile !== '' && previewOpen[openFile] === true && supportsTextPreview(openFile) === true
9327
+ // "What did I change": a rendered line diff between the saved copy and the
9328
+ // buffer up front, so the user can review before saving (PM gap #5).
9329
+ var diffing = diffPath !== null && diffPath === openFile && openFile !== ''
9330
+ && docs[openFile] !== undefined && docs[openFile].kind === 'text'
9331
+ var diffPane = diffing === true
9332
+ ? (function () {
9333
+ var doc = docs[openFile]
9334
+ var rows = lineDiff(typeof doc.saved === 'string' ? doc.saved : '', typeof doc.text === 'string' ? doc.text : '')
9335
+ var changed = rows.filter(function (row) { return row.kind !== 'same' }).length
9336
+ return h('div', { style: S.paneOverlay, 'data-editor-diff': openFile },
9337
+ h('div', { style: Object.assign({}, S.notice, { display: 'flex', alignItems: 'center', gap: 6 }), 'data-diff-head': '1' },
9338
+ h('span', { style: { flex: '1 1 auto', minWidth: 0 } },
9339
+ '与磁盘版本对比:' + shortName(openFile) + '(' + changed + ' 行变化;+ 新增 / − 删除)'),
9340
+ h('button', {
9341
+ type: 'button', style: S.button, 'data-action': 'diff-close',
9342
+ onClick: function () { setDiffPath(null) },
9343
+ }, '回到编辑')),
9344
+ h('pre', {
9345
+ style: S.paneScroll,
9346
+ 'data-diff-body': '1',
9347
+ },
9348
+ rows.length === 0
9349
+ ? h('div', { style: S.meta }, '与磁盘版本一致')
9350
+ : (function () {
9351
+ // Two gutters (old line → new line) so an inserted/deleted block
9352
+ // is readable at a glance; both are 0 on the side that has no line.
9353
+ var oldLine = 0
9354
+ var newLine = 0
9355
+ return rows.map(function (row, index) {
9356
+ if (row.kind !== 'add') oldLine += 1
9357
+ if (row.kind !== 'del') newLine += 1
9358
+ return h('div', {
9359
+ key: index,
9360
+ 'data-diff-row': row.kind,
9361
+ style: Object.assign({}, S.diffLine,
9362
+ row.kind === 'add' ? S.diffAdd : row.kind === 'del' ? S.diffDel : undefined),
9363
+ },
9364
+ h('span', { style: S.diffNum }, row.kind === 'add' ? '' : String(oldLine)),
9365
+ h('span', { style: S.diffNum }, row.kind === 'del' ? '' : String(newLine)),
9366
+ h('span', { style: S.diffSign }, row.kind === 'add' ? '+' : row.kind === 'del' ? '-' : ' '),
9367
+ h('span', null, row.text))
9368
+ })
9369
+ })()))
9370
+ })()
9371
+ : null
9372
+ // Test output replaces the editor while a run pane is open (PM gap #6).
9373
+ // Everything the host sent is rendered verbatim — the host already capped
9374
+ // the text (head 4k + …(省略 N 字符)… + tail 400k).
9375
+ var testPane = testRun !== null && testRun.path === openFile
9376
+ ? h('div', { style: S.paneOverlay, 'data-test-pane': testRun.className },
9377
+ h('div', {
9378
+ style: Object.assign({}, S.notice, { display: 'flex', alignItems: 'center', gap: 6 }),
9379
+ 'data-test-head': '1',
9380
+ },
9381
+ h('span', { style: { flex: '1 1 auto', minWidth: 0 } },
9382
+ '测试 · ' + testRun.className + ' · ' + testRunStatusText(testRun)),
9383
+ h('button', {
9384
+ type: 'button', style: S.button, 'data-action': 'test-rerun', disabled: testRun.status === 'running' || testRun.status === 'starting',
9385
+ title: '重新运行同样的测试选择器', onClick: function () { runTestFor(testRun.path) },
9386
+ }, '重新运行'),
9387
+ h('button', {
9388
+ type: 'button', style: S.buttonOff, 'data-action': 'test-close', disabled: testRun.status === 'running' || testRun.status === 'starting',
9389
+ title: '关闭测试输出(运行中不能关闭)', onClick: function () { setTestRun(null) },
9390
+ }, '关闭')),
9391
+ testRun.command === '' ? null : h('div', { style: S.meta, 'data-test-command': '1' }, testRun.command),
9392
+ h('pre', {
9393
+ style: S.paneScroll,
9394
+ 'data-test-output': '1',
9395
+ }, testRun.output === '' ? '(等待输出…)' : testRun.output))
9396
+ : null
7748
9397
  return h('div', { style: Object.assign({}, S.editorPane, { position: 'relative' }), 'data-editor-pane': '1' },
7749
9398
  bar,
7750
9399
  tabsMenu,
7751
9400
  prompt,
7752
9401
  bulkPrompt,
7753
- previewToggleBar(),
7754
- h('div', { style: S.filePanes }, body, previewing ? previewPaneNode() : null))
9402
+ h('div', { style: S.filePanes },
9403
+ // The editor is NEVER swapped out: hiding it behind an overlay keeps
9404
+ // the CodeMirror instance (and its undo history) alive, so closing the
9405
+ // diff/test pane returns to a working Ctrl+Z.
9406
+ body,
9407
+ previewing ? previewPaneNode() : null,
9408
+ diffPane,
9409
+ testPane,
9410
+ previewToggleBar()))
7755
9411
  }
7756
9412
 
7757
9413
  /** The console: every discoverable program with start/stop/debug/log. */
7758
9414
  function consoleBody() {
9415
+ var batchBar = checkedIds.length > 1
9416
+ ? h('div', { style: Object.assign({}, S.bar, { flex: '0 0 auto' }), 'data-console-batch': '1' },
9417
+ h('span', { style: S.status }, '已勾选 ' + checkedIds.length + ' 项'),
9418
+ h('span', { style: S.spacer }),
9419
+ button('▶', function () { void consoleBatch('start') }, { icon: true, width: 25, start: true, action: 'batch-start', title: '按列表顺序启动勾选的项目(跳过已运行的)' }),
9420
+ button('■', function () { void consoleBatch('stop') }, { icon: true, width: 25, stop: true, action: 'batch-stop', title: '按列表倒序停止勾选的项目(跳过未运行的)' }),
9421
+ button('清除', function () { setCheckedIds([]) }, { action: 'batch-clear', title: '取消全部勾选' }))
9422
+ : null
7759
9423
  return h('div', { style: S.ideBody },
9424
+ batchBar,
7760
9425
  programs.map(function (program) {
7761
9426
  var alive = program.running !== null && program.running !== undefined && program.running.alive === true
7762
9427
  var startable = program.kind !== 'instance'
@@ -7764,10 +9429,23 @@ var [ui, setUi] = useState(function () {
7764
9429
  var busy = consoleBusy === program.id
7765
9430
  return h('div', {
7766
9431
  key: program.id,
7767
- style: Object.assign({}, selected ? S.consoleRowOn : S.debugRow, { position: 'relative', overflow: 'hidden' }),
9432
+ // The whole row is the hit area: the name, and the blank stretch
9433
+ // between the name and the run buttons, both pick the program.
9434
+ style: Object.assign({}, selected ? S.consoleRowOn : S.consoleRow, {
9435
+ position: 'relative', overflow: 'hidden', cursor: 'pointer',
9436
+ }),
7768
9437
  'data-console-on': selected ? '1' : undefined,
7769
- title: selected ? program.name + '(当前项目)' : undefined,
9438
+ title: selected ? program.name + '(当前项目)' : program.name + '(点击切换到这个项目的日志 + 调试)',
9439
+ onClick: function () { selectProgram(program) },
7770
9440
  },
9441
+ h('input', {
9442
+ type: 'checkbox', 'data-console-check': program.id,
9443
+ checked: checkedIds.indexOf(program.id) !== -1,
9444
+ title: '勾选后可与其它项目一起批量启动/停止(勾选 2 个以上出现批量按钮)',
9445
+ style: { flex: '0 0 auto', margin: '0 4px 0 0', cursor: 'pointer' },
9446
+ onClick: function (event) { event.stopPropagation() },
9447
+ onChange: function () { toggleChecked(program.id) },
9448
+ }),
7771
9449
  h('span', { style: alive ? S.instDotOn : S.instDotOff, title: alive ? '运行中' : '未运行' }, '●'),
7772
9450
  h('span', {
7773
9451
  style: Object.assign({}, S.debugMono, { cursor: 'pointer' }),
@@ -7779,20 +9457,22 @@ var [ui, setUi] = useState(function () {
7779
9457
  alive && formatMemory(program.running.rssBytes) !== ''
7780
9458
  ? h('span', { style: S.meta, title: '常驻内存(VmRSS)' }, formatMemory(program.running.rssBytes))
7781
9459
  : null,
7782
- startable && !alive ? button('▶', function () { void consoleStart(program) }, { icon: true, width: 25, start: true, action: 'console-start', title: '启动 ' + program.name }) : null,
7783
- alive ? button('■', function () { void consoleStop(program) }, { icon: true, width: 25, stop: true, action: 'console-stop', title: '停止 ' + program.name }) : null,
7784
- program.kind === 'spring' ? button(ideBadgeIcon('bug', 'play', 13), function () { void consoleDebug(program) }, { icon: true, width: 25, debug: true, off: ui.busy, action: 'console-debug', title: '调试 ' + program.name }) : null,
9460
+ startable && !alive ? button('▶', function (event) { event.stopPropagation(); void consoleStart(program) }, { icon: true, width: 25, start: true, action: 'console-start', title: '启动 ' + program.name }) : null,
9461
+ alive ? button('■', function (event) { event.stopPropagation(); void consoleStop(program) }, { icon: true, width: 25, stop: true, action: 'console-stop', title: '停止 ' + program.name }) : null,
9462
+ // ⟳ shares ▶'s green: both (re)start the program, only ■ is red.
9463
+ startable ? button('⟳', function (event) { event.stopPropagation(); void consoleRestart(program) }, { icon: true, width: 25, start: true, action: 'console-restart', title: '重启 ' + program.name }) : null,
9464
+ program.kind === 'spring' ? button(ideBadgeIcon('bug', 'play', 13), function (event) { event.stopPropagation(); void consoleDebug(program) }, { icon: true, width: 25, debug: true, off: ui.busy, action: 'console-debug', title: '调试 ' + program.name }) : null,
7785
9465
  busy
7786
9466
  ? h('div', {
7787
9467
  key: 'loading',
7788
9468
  className: 'dsh-ris-ide-loading',
7789
9469
  'data-program-loading': program.id,
7790
- title: '正在' + (alive ? '停止' : '启动') + ' ' + program.name + '…',
9470
+ title: busyMaskTitle(alive, consoleBusyKind, program.name),
7791
9471
  onClick: function (event) { event.stopPropagation(); event.preventDefault() },
7792
9472
  onMouseDown: function (event) { event.stopPropagation(); event.preventDefault() },
7793
9473
  },
7794
9474
  h('span', { className: 'dsh-ris-ide-spinner' }),
7795
- h('span', null, alive ? '停止中…' : '启动中…'))
9475
+ h('span', { 'data-program-loading-kind': consoleBusyKind }, busyMaskText(alive, consoleBusyKind)))
7796
9476
  : null)
7797
9477
  }),
7798
9478
  h('div', { style: S.idePlaceholder },
@@ -7839,7 +9519,8 @@ var [ui, setUi] = useState(function () {
7839
9519
  // while the box is empty, the results once a query is typed.
7840
9520
  var matches = searchHits !== null && searchHits !== undefined && Array.isArray(searchHits.matches) ? searchHits.matches : []
7841
9521
  var inHistory = searchHistoryRows.length > 0
7842
- var count = inHistory ? searchHistoryRows.length : matches.length
9522
+ // Two row kinds in one list: file-name matches, then content hits.
9523
+ var count = inHistory ? searchHistoryRows.length : matches.length + contentHits.length
7843
9524
  if (count === 0) return
7844
9525
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
7845
9526
  // The arrow moves the highlighted ROW, not the caret: the box keeps
@@ -7863,11 +9544,20 @@ var [ui, setUi] = useState(function () {
7863
9544
  void openRecentPath(row.path)
7864
9545
  return
7865
9546
  }
9547
+ if (index >= matches.length) {
9548
+ var hit = contentHits[index - matches.length]
9549
+ if (hit !== undefined) openContentHit({ hit: hit, query: treeQuery.trim() })
9550
+ return
9551
+ }
7866
9552
  var chosen = matches[index]
7867
9553
  pickSearchHit(chosen, searchHits.dirs !== undefined && searchHits.dirs !== null && searchHits.dirs[chosen] === true)
7868
9554
  },
7869
9555
  }),
7870
- searchFocused === true && treeQuery.trim() === ''
9556
+ // The dropdown belongs to FOCUS: a pick closes it (the query and the
9557
+ // cached hits stay, so refocusing the box shows them again instantly).
9558
+ searchFocused !== true
9559
+ ? null
9560
+ : treeQuery.trim() === ''
7871
9561
  ? (function () {
7872
9562
  if (searchHistoryRows.length === 0) return null
7873
9563
  return h('div', {
@@ -7896,7 +9586,12 @@ var [ui, setUi] = useState(function () {
7896
9586
  }))
7897
9587
  })()
7898
9588
  : h(SearchResults, {
7899
- hits: searchHits, busy: searchBusy, onPick: pickSearchHit,
9589
+ hits: searchHits, busy: searchBusy,
9590
+ content: contentHits, contentBusy: contentBusy, query: treeQuery.trim(),
9591
+ onPick: function (chosen, isDir) {
9592
+ if (chosen !== null && chosen !== undefined && typeof chosen === 'object') openContentHit(chosen)
9593
+ else pickSearchHit(chosen, isDir)
9594
+ },
7900
9595
  active: searchActive, onHover: setSearchActive,
7901
9596
  fontRatio: fontRatio, cwd: cwd,
7902
9597
  }))
@@ -7908,6 +9603,10 @@ var [ui, setUi] = useState(function () {
7908
9603
  function inPanel(target) {
7909
9604
  var root = workbenchRef.current
7910
9605
  if (root === null || target === null || target === undefined) return false
9606
+ // Synthetic events dispatched on `window` are not Nodes: `contains`
9607
+ // throws for them (`parameter 1 is not of type 'Node'`), which used to
9608
+ // surface as a scary "界面出错" toast.
9609
+ if (typeof target.nodeType !== 'number') return false
7911
9610
  return typeof root.contains === 'function' && root.contains(target)
7912
9611
  }
7913
9612
  function onKey(event) {
@@ -7921,11 +9620,10 @@ var [ui, setUi] = useState(function () {
7921
9620
  event.preventDefault()
7922
9621
  event.stopPropagation()
7923
9622
  event.stopImmediatePropagation()
7924
- var input = searchInputRef.current
7925
- if (input !== null) {
7926
- input.focus()
7927
- input.select()
7928
- }
9623
+ // Focus through the effect so a controlled value update cannot put
9624
+ // the caret at the end AFTER select() and drop the highlight.
9625
+ searchFocusPendingRef.current = true
9626
+ setSearchFocusNonce(function (value) { return value + 1 })
7929
9627
  return
7930
9628
  }
7931
9629
  }
@@ -7951,17 +9649,16 @@ var [ui, setUi] = useState(function () {
7951
9649
  // the find chord only belongs to the IDE when the event is ours.
7952
9650
  if (!ownsKeyTarget(event.target)) return
7953
9651
  if (!isGlobalFindChord(event)) return
7954
- var input = searchInputRef.current
7955
- if (input === null) return
9652
+ if (searchInputRef.current === null) return
7956
9653
  // A single-line selection in the editor IS the query the user means:
7957
9654
  // Ctrl+R searches for it instead of asking them to copy it by hand.
7958
9655
  var picked = selectedEditorText()
7959
9656
  if (picked !== '') {
7960
9657
  event.preventDefault()
7961
9658
  event.stopPropagation()
9659
+ searchFocusPendingRef.current = true
7962
9660
  setTreeQuery(picked)
7963
- input.focus()
7964
- input.select()
9661
+ setSearchFocusNonce(function (value) { return value + 1 })
7965
9662
  return
7966
9663
  }
7967
9664
  var target = event.target
@@ -7972,8 +9669,8 @@ var [ui, setUi] = useState(function () {
7972
9669
  })) return
7973
9670
  event.preventDefault()
7974
9671
  event.stopPropagation()
7975
- input.focus()
7976
- input.select()
9672
+ searchFocusPendingRef.current = true
9673
+ setSearchFocusNonce(function (value) { return value + 1 })
7977
9674
  }
7978
9675
  window.addEventListener('keydown', onKey)
7979
9676
  return function () { window.removeEventListener('keydown', onKey) }
@@ -8025,12 +9722,17 @@ var [ui, setUi] = useState(function () {
8025
9722
  + '(点击切换 跟随系统 → 深色 → 浅色;IDE 全部跟随 DSH)',
8026
9723
  }))
8027
9724
  }
9725
+ // The config actions belong to the CONSOLE title bar, not the source pane's:
9726
+ // `.dsh-ris-ide.json` describes the PROGRAMS the console lists (the sidebar
9727
+ // console already keeps 打开配置/更新配置 there), so the two controls moved
9728
+ // next to the program list.
8028
9729
  var paneConfig = props.onConfig !== null && typeof props.onConfig === 'object' ? props.onConfig : null
9730
+ var consoleConfigActions = []
8029
9731
  if (paneConfig !== null && typeof paneConfig.open === 'function') {
8030
- paneActions.push(button('📄', function () { paneConfig.open() }, { key: 'config-open', icon: true, height: 20, action: 'config-open', title: '打开配置文件 .dsh-ris-ide.json(启动参数由你维护)' }))
9732
+ consoleConfigActions.push(button('📄', function () { paneConfig.open() }, { key: 'config-open', icon: true, height: 20, action: 'config-open', title: '打开配置文件 .dsh-ris-ide.json(启动参数由你维护)' }))
8031
9733
  }
8032
9734
  if (paneConfig !== null && typeof paneConfig.generate === 'function') {
8033
- paneActions.push(button('⚙', function () { paneConfig.generate() }, { key: 'config-generate', icon: true, height: 20, action: 'config-generate', title: paneConfig.exists === true ? '更新配置:按当前扫描结果同步 .dsh-ris-ide.json(保留你改过的字段)' : '生成配置:把扫描到的程序写成 .dsh-ris-ide.json' }))
9735
+ consoleConfigActions.push(button('⚙', function () { paneConfig.generate() }, { key: 'config-generate', icon: true, height: 20, action: 'config-generate', title: paneConfig.exists === true ? '更新配置:按当前扫描结果同步 .dsh-ris-ide.json(保留你改过的字段)' : '生成配置:把扫描到的程序写成 .dsh-ris-ide.json' }))
8034
9736
  }
8035
9737
  paneActions.push(button('⟲', resetLayout, { key: 'layout-reset', icon: true, height: 20, action: 'layout-reset', title: '还原布局尺寸:左列 300px、调试区 300px、两个下层 260px(不改变最大化状态)' }))
8036
9738
 
@@ -8147,13 +9849,15 @@ var [ui, setUi] = useState(function () {
8147
9849
  },
8148
9850
  // The sidebar's CodeMirror theme pins 13px, so the embedded viewer needs
8149
9851
  // this rule, not inheritance, to follow A−/A+.
8150
- h('style', { key: 'ide-font' }, viewerFontCss(uiFont) + viewerThemeCss(pageDark) + DEBUG_LINE_CSS + PREVIEW_CSS + SELECTION_CSS + SCROLLBAR_CSS + TOAST_CSS + PROGRAM_LOADING_CSS),
9852
+ h('style', { key: 'ide-font' }, viewerFontCss(uiFont) + viewerThemeCss(pageDark) + DEBUG_LINE_CSS + PREVIEW_CSS + SELECTION_CSS + SCROLLBAR_CSS + SEARCH_PANEL_CSS + TOAST_CSS + PROGRAM_LOADING_CSS),
8151
9853
  (function () {
8152
9854
  var panes = {
8153
9855
  tree: h(IdeTree, {
8154
9856
  scope: scope, rootPath: cwd || '.', locateRequest: locateRequest, activePath: openFile,
8155
9857
  openFiles: openFiles,
8156
- onOpen: openPath, onRename: renamePaths, fontRatio: fontRatio, refreshNonce: treeRefreshTick, onNote: note, visible: visible,
9858
+ /** Unsaved buffers, for the tree's per-file dirty badge (PM gap #5). */
9859
+ dirtyPaths: openFiles.filter(function (path) { return isDirty(path) === true }),
9860
+ onOpen: openPath, onRename: renamePaths, fontRatio: fontRatio, refreshNonce: treeRefresh.tick, refreshAnnounce: treeRefresh.announce, onNote: note, onActionNote: note, visible: visible,
8157
9861
  onTreeMeta: function (meta) { setTreeGit(meta.git === true) },
8158
9862
  }),
8159
9863
  console: consoleBody(),
@@ -8174,6 +9878,7 @@ var [ui, setUi] = useState(function () {
8174
9878
  // log text); the viewer renders whatever the title bar decides.
8175
9879
  following: logFollowing,
8176
9880
  wrap: logWrap,
9881
+ level: logLevel,
8177
9882
  fontSize: logFontSize,
8178
9883
  onFollowingChange: setLogFollowing,
8179
9884
  // Paused while the log pane is hidden (another pane maximised, or
@@ -8292,7 +9997,7 @@ var [ui, setUi] = useState(function () {
8292
9997
  }, '⌖'),
8293
9998
  h('button', {
8294
9999
  type: 'button', style: S.buttonOff, 'data-action': 'tree-refresh', title: '刷新文件树(重新读取已展开的目录)',
8295
- onClick: function () { setTreeRefreshTick(function (value) { return value + 1 }) },
10000
+ onClick: function () { setTreeRefresh(function (value) { return { tick: value.tick + 1, announce: true } }) },
8296
10001
  }, '⟳'),
8297
10002
  h('button', {
8298
10003
  type: 'button',
@@ -8309,6 +10014,17 @@ var [ui, setUi] = useState(function () {
8309
10014
  }, ideIcon(treeShowAll === true ? 'eyeOff' : 'eye', 14)),
8310
10015
  maximize)
8311
10016
  }
10017
+ if (id === 'console') {
10018
+ // The console's title bar owns the config actions (see
10019
+ // `consoleConfigActions`): the config file describes exactly the
10020
+ // programs listed below it, which is where the sidebar panel keeps
10021
+ // its 打开配置 / 更新配置 too.
10022
+ return h('div', Object.assign({ style: S.ideHead, 'data-console-head': '1' }, onDouble),
10023
+ h('span', null, titles[id]),
10024
+ h('span', { style: S.spacer }),
10025
+ consoleConfigActions,
10026
+ maximize)
10027
+ }
8312
10028
  if (id === 'log') {
8313
10029
  // The viewer's chrome used to be an in-body bar; it lives HERE now,
8314
10030
  // so the log body is nothing but log text. Every control is an icon
@@ -8331,6 +10047,14 @@ var [ui, setUi] = useState(function () {
8331
10047
  h('span', { style: { whiteSpace: 'nowrap' }, title: activePath === '' ? undefined : activePath }, titles[id]),
8332
10048
  logStatus,
8333
10049
  h('span', { style: S.spacer }),
10050
+ logControls ? button(logLevel === 'all' ? '级' : logLevel === 'warn' ? 'W+' : 'E+', cycleLogLevel, {
10051
+ icon: true, height: 20, action: 'log-level', off: logLevel === 'all',
10052
+ title: logLevel === 'all'
10053
+ ? '级别过滤:全部(点击只看 WARN/ERROR)'
10054
+ : logLevel === 'warn'
10055
+ ? '级别过滤:WARN/ERROR(点击只看 ERROR)'
10056
+ : '级别过滤:仅 ERROR(点击恢复全部)',
10057
+ }) : null,
8334
10058
  logControls ? button(ideIcon('wrap', 13), toggleLogWrap, {
8335
10059
  icon: true, height: 20, action: 'wrap', off: logWrap !== true,
8336
10060
  title: logWrap ? '自动换行:开(点击关闭)' : '自动换行:关(点击打开)',
@@ -8537,6 +10261,12 @@ var [ui, setUi] = useState(function () {
8537
10261
  toasts.map(function (toast) {
8538
10262
  return h('div', { key: toast.id, style: S.toast, 'data-toast': String(toast.id), role: 'status' },
8539
10263
  h('span', { style: { flex: '1 1 auto', minWidth: 0 } }, toast.text),
10264
+ toast.action === undefined || toast.action === null ? null : h('button', {
10265
+ type: 'button', style: Object.assign({}, S.button, { flex: '0 0 auto', padding: '0 6px' }),
10266
+ 'data-toast-action': String(toast.id),
10267
+ title: typeof toast.action.title === 'string' ? toast.action.title : '撤销刚刚的操作',
10268
+ onClick: function () { toast.action.run(); dismissToast(toast.id) },
10269
+ }, toast.action.label),
8540
10270
  h('button', {
8541
10271
  type: 'button', style: Object.assign({}, S.buttonOff, { flex: '0 0 auto', padding: '0 4px' }),
8542
10272
  'data-toast-close': String(toast.id), title: '关闭提示',
@@ -8549,6 +10279,17 @@ var [ui, setUi] = useState(function () {
8549
10279
  styles: S, kind: 'config-note', signature: props.configNote, onDismiss: workbenchDismissals.dismiss,
8550
10280
  }, props.configNote)
8551
10281
  : null,
10282
+ // First-run generation / config sync / drift: the console-level notices
10283
+ // have to reach the user in BOTH shapes (sidebar console and this window).
10284
+ Array.isArray(props.configNotices) === false ? null : props.configNotices.filter(function (item) {
10285
+ return item !== null && typeof item === 'object' && typeof item.kind === 'string'
10286
+ && workbenchDismissals.isOpen(item.kind, item.signature)
10287
+ }).map(function (item) {
10288
+ return h(ClosableNotice, {
10289
+ key: item.kind + ':' + item.signature,
10290
+ styles: S, kind: item.kind, signature: item.signature, onDismiss: workbenchDismissals.dismiss,
10291
+ }, item.text)
10292
+ }),
8552
10293
  // Right-click menu of a tab strip. Sources keep their dirty tabs when
8553
10294
  // bulk-closing (bulkClose); log/debug tabs have no drafts to lose.
8554
10295
  tabMenu === null ? null : h('div', {
@@ -8602,7 +10343,7 @@ var [ui, setUi] = useState(function () {
8602
10343
  // window passes nothing and gets the full IDE.
8603
10344
  return { sessionId: sessionId || '', visible: true, compact: true }
8604
10345
  },
8605
- }, function IdePanelBoundary(props) { return h(IdeErrorBoundary, null, h(ProgramsPanel, props)) })
10346
+ }, function IdePanelBoundary(props) { return h(IdeErrorBoundary, null, h(ProgramsPanel, Object.assign({}, props, { clientCtx: ctx }))) })
8606
10347
  })
8607
10348
  }, 'dsh-ris-ide: right-sidebar tab body')
8608
10349
  ctx.effect(function () {
@@ -9066,6 +10807,12 @@ var [ui, setUi] = useState(function () {
9066
10807
  var LARGE_TEXT_WINDOW_BYTES = 256 * 1024
9067
10808
  /** Stop paging past this much loaded text: the preview stays bounded. */
9068
10809
  var LARGE_TEXT_MAX_BYTES = 16 * 1024 * 1024
10810
+ /**
10811
+ * Upper bound for the 编辑 button on a large preview: force-loading reads the
10812
+ * whole file into one document, so past this size the editor would be the
10813
+ * problem rather than the preview (refuse instead of freezing the window).
10814
+ */
10815
+ var LARGE_TEXT_FORCE_MAX_BYTES = 32 * 1024 * 1024
9069
10816
 
9070
10817
  /**
9071
10818
  * One window of a large text file through THIS plugin's host route
@@ -9541,6 +11288,124 @@ var [ui, setUi] = useState(function () {
9541
11288
  throw new Error((parsed && parsed.message) || ('HTTP ' + response.status))
9542
11289
  }
9543
11290
 
11291
+ /**
11292
+ * Workspace CONTENT search (PM gap #2) — one `git grep -n` per call on the host,
11293
+ * no index. Results carry the line number and the whole matching line so the
11294
+ * dropdown can show "where" and the editor can jump there.
11295
+ * @param {{sessionId: string, cwd?: string}} scope - owning session.
11296
+ * @param {string} query - literal text to find.
11297
+ * @returns {Promise<Array<{path: string, line: number, text: string}>>} hits.
11298
+ */
11299
+ async function fsSearchContent(scope, query) {
11300
+ var url = routeUrl('dsh-ris-ide/search-content')
11301
+ url.searchParams.set('sessionId', scope.sessionId)
11302
+ var routeCwd = scopeCwd(scope)
11303
+ if (routeCwd !== undefined) url.searchParams.set('cwd', routeCwd)
11304
+ url.searchParams.set('q', query)
11305
+ url.searchParams.set('limit', '200')
11306
+ var response = await fetch(url.href, { headers: { accept: 'application/json' } })
11307
+ var parsed = await response.json().catch(function () { return null })
11308
+ if (!response.ok || parsed === null || parsed.ok !== true) {
11309
+ throw new Error(parsed !== null && typeof parsed.message === 'string' ? parsed.message : 'HTTP ' + response.status)
11310
+ }
11311
+ var list = Array.isArray(parsed.hits) ? parsed.hits : Array.isArray(parsed.matches) ? parsed.matches : []
11312
+ return list.filter(function (hit) {
11313
+ return hit !== null && hit !== undefined && typeof hit.path === 'string'
11314
+ }).map(function (hit) {
11315
+ return {
11316
+ path: hit.path,
11317
+ line: typeof hit.line === 'number' ? hit.line : Number(hit.line) || 0,
11318
+ text: typeof hit.text === 'string' ? hit.text : '',
11319
+ }
11320
+ })
11321
+ }
11322
+
11323
+ /**
11324
+ * Work out what `mvn test` call would run one Java test FILE (PM gap #6).
11325
+ *
11326
+ * `-pl` is REACTOR-relative while `-Dtest=` wants the fully-qualified class, so
11327
+ * both sides have to be derived from the file's own path: the reactor root is
11328
+ * the workspace-relative FIRST segment (the 项目根 convention from AGENTS.md),
11329
+ * which is also the dir the spawn must run in.
11330
+ * @param {string} path - absolute path of a file.
11331
+ * @param {string} cwd - the workspace root (absolute).
11332
+ * @returns {{reactorCwd: string, module: string, test: string, className: string}|null}
11333
+ * null when the file is not a Java test under `src/test/java`.
11334
+ */
11335
+ function testRunTarget(path, cwd) {
11336
+ var marker = '/src/test/java/'
11337
+ var at = typeof path === 'string' ? path.indexOf(marker) : -1
11338
+ if (at === -1 || typeof cwd !== 'string' || cwd === '') return null
11339
+ if (path.slice(-5) !== '.java') return null
11340
+ var moduleDir = path.slice(0, at)
11341
+ if (moduleDir.indexOf(cwd + '/') !== 0) return null
11342
+ var relativeModule = moduleDir.slice(cwd.length + 1)
11343
+ if (relativeModule === '') return null
11344
+ var segments = relativeModule.split('/')
11345
+ var reactorCwd = cwd + '/' + segments[0]
11346
+ var module = segments.slice(1).join('/')
11347
+ var className = path.slice(at + marker.length).replace(/\.java$/, '').split('/').join('.')
11348
+ if (className === '') return null
11349
+ return {
11350
+ reactorCwd: reactorCwd,
11351
+ module: module === '' ? '.' : module,
11352
+ test: className,
11353
+ className: className,
11354
+ }
11355
+ }
11356
+
11357
+ /**
11358
+ * POST `/dsh-ris-ide/run-test`: start one Maven test run.
11359
+ * @param {{sessionId: string, cwd?: string}} scope - owning session.
11360
+ * @param {{reactorCwd: string, module: string, test: string, profile?: string}} target - the run.
11361
+ * @returns {Promise<{id: string, command: string}>} the run id + display command.
11362
+ */
11363
+ async function runTestStart(scope, target) {
11364
+ var body = {
11365
+ sessionId: scope.sessionId,
11366
+ cwd: target.reactorCwd,
11367
+ module: target.module,
11368
+ test: target.test,
11369
+ }
11370
+ if (typeof target.profile === 'string' && target.profile !== '') body.profile = target.profile
11371
+ var response = await fetch(routeUrl('dsh-ris-ide/run-test').href, {
11372
+ method: 'POST',
11373
+ headers: { 'content-type': 'application/json' },
11374
+ body: JSON.stringify(body),
11375
+ })
11376
+ var parsed = await response.json().catch(function () { return null })
11377
+ if (!response.ok || parsed === null || parsed.ok !== true) {
11378
+ throw new Error(parsed !== null && typeof parsed.message === 'string' ? parsed.message : 'HTTP ' + response.status)
11379
+ }
11380
+ return { id: String(parsed.id), command: typeof parsed.command === 'string' ? parsed.command : '' }
11381
+ }
11382
+
11383
+ /**
11384
+ * GET `/dsh-ris-ide/run-test?id=`: poll one run (output is head+tail capped).
11385
+ * @param {{sessionId: string, cwd?: string}} scope - owning session.
11386
+ * @param {string} id - the run id from {@link runTestStart}.
11387
+ * @returns {Promise<{status: string, running: boolean, exitCode: number|null, output: string, durationMs: number|null}>} state.
11388
+ */
11389
+ async function runTestStatus(scope, id) {
11390
+ var url = routeUrl('dsh-ris-ide/run-test')
11391
+ url.searchParams.set('sessionId', scope.sessionId)
11392
+ var routeCwd = scopeCwd(scope)
11393
+ if (routeCwd !== undefined) url.searchParams.set('cwd', routeCwd)
11394
+ url.searchParams.set('id', id)
11395
+ var response = await fetch(url.href, { headers: { accept: 'application/json' } })
11396
+ var parsed = await response.json().catch(function () { return null })
11397
+ if (!response.ok || parsed === null || parsed.ok !== true) {
11398
+ throw new Error(parsed !== null && typeof parsed.message === 'string' ? parsed.message : 'HTTP ' + response.status)
11399
+ }
11400
+ return {
11401
+ status: typeof parsed.status === 'string' ? parsed.status : 'running',
11402
+ running: parsed.running === true,
11403
+ exitCode: typeof parsed.exitCode === 'number' ? parsed.exitCode : null,
11404
+ output: typeof parsed.output === 'string' ? parsed.output : '',
11405
+ durationMs: typeof parsed.durationMs === 'number' ? parsed.durationMs : null,
11406
+ }
11407
+ }
11408
+
9544
11409
  /**
9545
11410
  * GET `/dsh-ris-ide/settings`: the IDE-owned settings kept beside the program
9546
11411
  * config (currently the decompiler jar used for dependency classes).
@@ -9613,6 +11478,35 @@ var [ui, setUi] = useState(function () {
9613
11478
  * @param {string} cwd - session workspace root for relative paths.
9614
11479
  * @returns {{matches: string[], dirs: object}} dropdown payload.
9615
11480
  */
11481
+ /** How many query → results pairs the search dropdown keeps warm. */
11482
+ var SEARCH_CACHE_LIMIT = 40
11483
+
11484
+ /**
11485
+ * Remember one search result set (or refresh an existing key's position).
11486
+ *
11487
+ * The dropdown no longer forgets its results when the user opens a row: the
11488
+ * query stays in the box, so re-opening a hit must not pay for `git grep`
11489
+ * again. A query whose text changes gets a NEW key (the old sets age out
11490
+ * through the insertion-order eviction), which is the "检索内容改变后清理"
11491
+ * half of the rule.
11492
+ * @param {Map<string, object>} cache - insertion-ordered LRU by convention.
11493
+ * @param {string} key - `name:<query>` or `content:<query>`.
11494
+ * @param {object} value - the payload to keep.
11495
+ * @param {number} [limit] - max entries (defaults to SEARCH_CACHE_LIMIT).
11496
+ * @returns {Map<string, object>} the same cache, for chaining.
11497
+ */
11498
+ function rememberSearchEntry(cache, key, value, limit) {
11499
+ var cap = typeof limit === 'number' && limit > 0 ? limit : SEARCH_CACHE_LIMIT
11500
+ if (cache.has(key)) cache.delete(key)
11501
+ cache.set(key, value)
11502
+ while (cache.size > cap) {
11503
+ var oldest = cache.keys().next()
11504
+ if (oldest.done === true) break
11505
+ cache.delete(oldest.value)
11506
+ }
11507
+ return cache
11508
+ }
11509
+
9616
11510
  function searchHitPayload(result, cwd) {
9617
11511
  var source = result !== null && result !== undefined ? result : {}
9618
11512
  var rawDirs = source.dirs !== null && source.dirs !== undefined ? source.dirs : {}
@@ -9913,8 +11807,11 @@ var [ui, setUi] = useState(function () {
9913
11807
  * @returns {Promise<object>} `{ ok: true, alreadyRunning, program }` or
9914
11808
  * `{ ok: false, code, error }`.
9915
11809
  */
9916
- async function requestStart(programId, scope) {
11810
+ async function requestStart(programId, scope, restart) {
9917
11811
  var body = { sessionId: scope.sessionId, id: programId }
11812
+ // A restart is stop-then-start on the host, so the pidfile/port are released
11813
+ // before the new JVM boots (PM gap #1: the daily loop was 停止 → 启动 by hand).
11814
+ if (restart === true) body.restart = true
9918
11815
  if (typeof scope.cwd === 'string' && scope.cwd !== '') body.cwd = scope.cwd
9919
11816
  var response = await fetch(routeUrl('dsh-ris-ide/start').href, {
9920
11817
  method: 'POST',
@@ -10169,6 +12066,14 @@ var [ui, setUi] = useState(function () {
10169
12066
  var [compactFont, setCompactFont] = useState(function () {
10170
12067
  return clampFontSize(readPref(PREF_FONT_SIZE, DEFAULT_FONT_SIZE))
10171
12068
  })
12069
+ /**
12070
+ * The standalone window has no DSH sidebar editor, so 📄 hands the config
12071
+ * path down to the workbench (which owns the editor) instead of only telling
12072
+ * the user where the file lives. `nonce` re-opens the same path when the
12073
+ * button is pressed twice.
12074
+ * @type {[{path: string, nonce: number}|null, Function]}
12075
+ */
12076
+ var [openConfigRequest, setOpenConfigRequest] = useState(null)
10172
12077
  var [state, setState] = useState(function () {
10173
12078
  return { loading: true, programs: [], root: undefined, dir: undefined, config: undefined, error: undefined, note: undefined }
10174
12079
  })
@@ -10186,7 +12091,23 @@ var [ui, setUi] = useState(function () {
10186
12091
  }, [state.note])
10187
12092
 
10188
12093
  var [busyId, setBusyId] = useState(undefined)
12094
+ /** Which action `busyId` is running, for the row mask's wording. */
12095
+ var [busyKind, setBusyKind] = useState('')
10189
12096
  var busyRef = useRef(false)
12097
+ /** A start-all/stop-all pass in flight: `{kind, index, total}` or null. */
12098
+ var [bulk, setBulk] = useState(null)
12099
+ /**
12100
+ * Programs ticked for a batch start/stop (PM gap #7). The batch bar only
12101
+ * appears once more than one row is ticked — a single row has its own ▶/■.
12102
+ */
12103
+ var [checkedIds, setCheckedIds] = useState([])
12104
+ function toggleChecked(programId) {
12105
+ setCheckedIds(function (previous) {
12106
+ if (previous.indexOf(programId) === -1) return previous.concat([programId])
12107
+ return previous.filter(function (id) { return id !== programId })
12108
+ })
12109
+ }
12110
+ var bulkRef = useRef(false)
10190
12111
  var panelDismissals = useDismissedNotices()
10191
12112
 
10192
12113
  var refresh = React.useCallback(async function (force) {
@@ -10283,32 +12204,99 @@ var [ui, setUi] = useState(function () {
10283
12204
  return function () { clearInterval(timer) }
10284
12205
  }, [refresh, sessionId, props.visible, streamOk])
10285
12206
 
12207
+ /**
12208
+ * Start (console order) or stop (reverse) the TICKED programs only.
12209
+ *
12210
+ * Sequential on purpose: the host's start route waits for a pidfile and a
12211
+ * Maven build, and firing eight JVMs at once only makes the slowest one
12212
+ * slower. Console order IS the dependency order (config order), which is
12213
+ * why this does not invent a graph (PM gap #7).
12214
+ * @param {'start'|'stop'} kind - which direction.
12215
+ */
12216
+ async function actMany(kind) {
12217
+ if (bulkRef.current === true) return
12218
+ var chosen = state.programs.filter(function (program) { return checkedIds.indexOf(program.id) !== -1 })
12219
+ var targets = chosen.filter(function (program) {
12220
+ if (program.kind === 'instance') return false
12221
+ var alive = program.running !== null && program.running !== undefined && program.running.alive === true
12222
+ return kind === 'stop' ? alive : !alive
12223
+ })
12224
+ if (kind === 'stop') targets = targets.slice().reverse()
12225
+ if (targets.length === 0) {
12226
+ setState(function (prev) { return Object.assign({}, prev, { note: kind === 'start' ? '没有需要启动的项目' : '没有正在运行的项目' }) })
12227
+ return
12228
+ }
12229
+ bulkRef.current = true
12230
+ var failures = 0
12231
+ try {
12232
+ for (var index = 0; index < targets.length; index += 1) {
12233
+ setBulk({ kind: kind, index: index, total: targets.length })
12234
+ setBusyId(targets[index].id)
12235
+ setBusyKind(kind)
12236
+ if (kind === 'start') {
12237
+ setActive(targets[index])
12238
+ broadcastLogFocus(targets[index].logPath)
12239
+ }
12240
+ var scopeArg = { sessionId: sessionId, cwd: cwd }
12241
+ var result
12242
+ try {
12243
+ result = kind === 'start' ? await requestStart(targets[index].id, scopeArg) : await requestStop(targets[index].logPath, scopeArg)
12244
+ } catch (error) {
12245
+ result = { ok: false, error: messageOf(error) }
12246
+ }
12247
+ if (result.ok !== true) failures += 1
12248
+ }
12249
+ } finally {
12250
+ setBusyId(undefined)
12251
+ setBusyKind('')
12252
+ bulkRef.current = false
12253
+ setBulk(null)
12254
+ }
12255
+ setCompactLogNonce(function (value) { return value + 1 })
12256
+ void refresh(false)
12257
+ // Row states already show what happened; only failures need a toast.
12258
+ if (failures > 0) {
12259
+ setState(function (prev) {
12260
+ return Object.assign({}, prev, { note: failures + ' 项失败:' + (kind === 'start' ? '启动' : '停止') + '没有成功' })
12261
+ })
12262
+ }
12263
+ setCheckedIds([])
12264
+ }
12265
+
10286
12266
  /** Start or stop one row, then refresh the state it just changed. */
10287
12267
  function act(kind, program) {
10288
12268
  if (busyId !== undefined) return
10289
12269
  setBusyId(program.id)
12270
+ setBusyKind(kind)
12271
+ var boots = kind === 'start' || kind === 'restart'
10290
12272
  // Show this program's log from the first moment: the start call waits for
10291
12273
  // a pidfile (up to START_WAIT_MS), and Maven compile is silent. The same
10292
12274
  // event moves the standalone IDE window's log pane right away.
10293
- if (kind === 'start') { setActive(program); broadcastLogFocus(program.logPath); setCompactLogNonce(function (value) { return value + 1 }) }
12275
+ if (boots) { setActive(program); broadcastLogFocus(program.logPath); setCompactLogNonce(function (value) { return value + 1 }) }
10294
12276
  var scopeArg = { sessionId: sessionId, cwd: cwd }
10295
- var task = kind === 'start' ? requestStart(program.id, scopeArg) : requestStop(program.logPath, scopeArg)
12277
+ var task = kind === 'stop'
12278
+ ? requestStop(program.logPath, scopeArg)
12279
+ : requestStart(program.id, scopeArg, kind === 'restart')
10296
12280
  task.then(function (result) {
10297
12281
  setBusyId(undefined)
10298
- var note
10299
- if (result.ok !== true) note = (kind === 'start' ? '启动失败:' : '停止失败:') + (result.error || '未知错误')
10300
- else if (kind === 'start') {
10301
- note = result.alreadyRunning === true ? program.name + ' 已在运行' : program.name + ' 已启动' + heapHint(program)
12282
+ setBusyKind('')
12283
+ // The row itself (state dot, ▶/■ swap) already reports a settled
12284
+ // start/stop, so the panel's top note bar stays for failures only:
12285
+ // a "x 已启动" strip just pushes the list down for a second.
12286
+ if (result.ok !== true) {
12287
+ setState(function (prev) {
12288
+ return Object.assign({}, prev, {
12289
+ note: (kind === 'start' ? '启动失败:' : kind === 'restart' ? '重启失败:' : '停止失败:') + (result.error || '未知错误'),
12290
+ })
12291
+ })
10302
12292
  }
10303
- else if (result.alreadyStopped === true) note = program.name + ' 此前已停止'
10304
- else note = program.name + ' 已停止'
10305
- setState(function (prev) { return Object.assign({}, prev, { note: note }) })
10306
12293
  // The start/stop settled and the wrapper wrote its marker: re-read once
10307
12294
  // so the pane cannot stay on the pre-start text.
10308
12295
  setCompactLogNonce(function (value) { return value + 1 })
10309
12296
  void refresh(false)
10310
12297
  }).catch(function (error) {
10311
12298
  setBusyId(undefined)
12299
+ setBusyKind('')
10312
12300
  setState(function (prev) {
10313
12301
  return Object.assign({}, prev, { note: (kind === 'start' ? '启动失败:' : '停止失败:') + messageOf(error) })
10314
12302
  })
@@ -10339,10 +12327,28 @@ var [ui, setUi] = useState(function () {
10339
12327
  function openConfig() {
10340
12328
  var path = state.config !== undefined && state.config !== null ? state.config.path : undefined
10341
12329
  if (typeof path !== 'string' || path === '') return
12330
+ // The sidebar console has no workbench editor of its own, so hand the
12331
+ // hidden dotfile to DSH's right Sidebar as a file resource: it opens in
12332
+ // the sidebar's editor tab (the tree and the search box cannot reach a
12333
+ // dotfile, and a log tab cannot edit it).
12334
+ var sidebar = props.clientCtx !== null && props.clientCtx !== undefined ? props.clientCtx.sidebarRight : undefined
12335
+ if (sidebar !== undefined && sidebar !== null && typeof sidebar.openResource === 'function') {
12336
+ try {
12337
+ sidebar.openResource(officialPreviewAddress({ sessionId: sessionId, cwd: cwd }, path))
12338
+ setState(function (prev) { return Object.assign({}, prev, { note: '已在右侧栏打开 ' + shortName(path) + '(改完保存即生效)' }) })
12339
+ } catch (error) {
12340
+ setState(function (prev) { return Object.assign({}, prev, { note: '打开配置失败:' + messageOf(error) }) })
12341
+ }
12342
+ return
12343
+ }
10342
12344
  // The standalone window has no DSH right sidebar, so there is no sidebar
10343
- // editor to open into. Say WHERE the file is instead of failing loudly.
12345
+ // editor to open into: the workbench editor is the only editor there, so
12346
+ // hand the path over and let it open `.dsh-ris-ide.json` as a normal tab
12347
+ // (a hidden dotfile is not reachable from the tree or the search box).
10344
12348
  if (panelCtx === null || panelCtx === undefined) {
10345
- setState(function (prev) { return Object.assign({}, prev, { note: '独立窗口没有侧边栏编辑器,配置文件在 ' + path }) })
12349
+ setOpenConfigRequest(function (previous) {
12350
+ return { path: path, nonce: previous === null || previous === undefined ? 1 : previous.nonce + 1 }
12351
+ })
10346
12352
  return
10347
12353
  }
10348
12354
  try {
@@ -10352,6 +12358,46 @@ var [ui, setUi] = useState(function () {
10352
12358
  }
10353
12359
  }
10354
12360
 
12361
+ /**
12362
+ * Config notices the console owes the user: first-run generation, a config
12363
+ * sync, and drift between `.dsh-ris-ide.json` and the current scan. The
12364
+ * dismissal signature travels with each item so closing one sticks.
12365
+ * @returns {Array<{kind: string, signature: string, text: string}>} live notices.
12366
+ */
12367
+ function configNoticeItems() {
12368
+ var items = []
12369
+ var config = state.config
12370
+ if (config === undefined || config === null) return items
12371
+ var path = typeof config.path === 'string' ? config.path : ''
12372
+ if (config.status === 'generated') {
12373
+ items.push({
12374
+ kind: 'config-generated',
12375
+ signature: 'generated:' + path,
12376
+ text: '已按扫描结果自动生成配置 ' + path + '(可编辑,保存后生效)',
12377
+ })
12378
+ }
12379
+ if (config.status === 'updated') {
12380
+ items.push({
12381
+ kind: 'config-updated',
12382
+ signature: 'updated',
12383
+ text: '配置已与工作区同步(新增程序已补、失效条目已删;你改过的字段保留)',
12384
+ })
12385
+ }
12386
+ var drift = config.drift
12387
+ if (drift !== undefined && drift !== null && drift.stale === true) {
12388
+ items.push({
12389
+ kind: 'drift',
12390
+ signature: driftSignature(drift),
12391
+ text: '配置与工作区不一致:'
12392
+ + (drift.added.length > 0 ? '新增 ' + drift.added.length + ' 个项目 ' : '')
12393
+ + (drift.missing.length > 0 ? '· 失效 ' + drift.missing.length + ' 条 ' : '')
12394
+ + (drift.changed.length > 0 ? '· 变更 ' + drift.changed.length + ' 条 ' : '')
12395
+ + '⇒ 点「更新配置」(保留你改过的字段与自定义程序)',
12396
+ })
12397
+ }
12398
+ return items
12399
+ }
12400
+
10355
12401
  /** Open one program's workbench tab (debug pane + live log). */
10356
12402
  /** Switch this tab from the project list into one project's IDE. */
10357
12403
  function openWorkbench(program, autoDebug) {
@@ -10472,7 +12518,7 @@ var [ui, setUi] = useState(function () {
10472
12518
  key: program.id,
10473
12519
  // The sidebar is narrow: the name shrinks first, the run controls keep
10474
12520
  // their hit area instead of spilling past the panel edge.
10475
- style: Object.assign({}, picked ? S.consoleRowOn : S.debugRow, { flex: '0 0 auto', minWidth: 0, cursor: 'pointer', position: 'relative', overflow: 'hidden' }),
12521
+ style: Object.assign({}, picked ? S.consoleRowOn : S.consoleRow, { flex: '0 0 auto', minWidth: 0, cursor: 'pointer', position: 'relative', overflow: 'hidden' }),
10476
12522
  'data-compact-row': program.name,
10477
12523
  'data-compact-on': picked ? '1' : undefined,
10478
12524
  title: program.name + (program.dir !== undefined ? '(' + program.dir + ')' : ''),
@@ -10481,6 +12527,16 @@ var [ui, setUi] = useState(function () {
10481
12527
  // reads as "the pick is broken".
10482
12528
  onClick: function () { setCompactPick(program.id) },
10483
12529
  },
12530
+ // Batch selection lives on its own checkbox: ticking must never pick the
12531
+ // row (that switches the log pane) and picking must never tick it.
12532
+ h('input', {
12533
+ type: 'checkbox', 'data-compact-check': program.id,
12534
+ checked: checkedIds.indexOf(program.id) !== -1,
12535
+ title: '勾选后可与其它项目一起批量启动/停止(勾选 2 个以上出现批量按钮)',
12536
+ style: { flex: '0 0 auto', margin: '0 2px 0 0', cursor: 'pointer' },
12537
+ onClick: function (event) { event.stopPropagation() },
12538
+ onChange: function () { toggleChecked(program.id) },
12539
+ }),
10484
12540
  h('span', { style: alive ? S.instDotOn : S.instDotOff, title: alive ? '运行中' : '未运行' }, '●'),
10485
12541
  h('button', {
10486
12542
  type: 'button', style: S.compactPick,
@@ -10509,6 +12565,17 @@ var [ui, setUi] = useState(function () {
10509
12565
  onClick: function (event) { event.stopPropagation(); void act('stop', program) },
10510
12566
  }, busy ? '…' : '■')
10511
12567
  : null,
12568
+ // Restart is the daily loop after a code change (PM gap #1): it works on
12569
+ // a running program (stop → start, pidfile released first) and on a
12570
+ // stopped one (plain start), so it is offered unconditionally.
12571
+ startable
12572
+ ? h('button', {
12573
+ // Same green as ▶: ⟳ also (re)starts the program.
12574
+ type: 'button', style: busy ? S.paneIconOff : S.startIcon, disabled: busy, 'data-action': 'restart',
12575
+ title: '重启 ' + program.name + '(停止后按同样参数再启动)',
12576
+ onClick: function (event) { event.stopPropagation(); void act('restart', program) },
12577
+ }, busy ? '…' : '⟳')
12578
+ : null,
10512
12579
  program.kind === 'spring'
10513
12580
  ? h('button', {
10514
12581
  type: 'button', style: S.debugIcon, 'data-action': 'debug-window',
@@ -10531,12 +12598,12 @@ var [ui, setUi] = useState(function () {
10531
12598
  key: 'loading',
10532
12599
  className: 'dsh-ris-ide-loading',
10533
12600
  'data-program-loading': program.id,
10534
- title: '正在' + (alive ? '停止' : '启动') + ' ' + program.name + '…',
12601
+ title: busyMaskTitle(alive, busyKind, program.name),
10535
12602
  onClick: function (event) { event.stopPropagation(); event.preventDefault() },
10536
12603
  onMouseDown: function (event) { event.stopPropagation(); event.preventDefault() },
10537
12604
  },
10538
12605
  h('span', { className: 'dsh-ris-ide-spinner' }),
10539
- h('span', null, alive ? '停止中…' : '启动中…'))
12606
+ h('span', { 'data-program-loading-kind': busyKind }, busyMaskText(alive, busyKind)))
10540
12607
  : null)
10541
12608
  }
10542
12609
 
@@ -10561,6 +12628,24 @@ var [ui, setUi] = useState(function () {
10561
12628
  h('span', { style: S.status }, state.loading ? '扫描中…' : (state.programs.length + ' 个项目')),
10562
12629
  h('span', { style: S.meta, title: state.root }, state.root || ''),
10563
12630
  h('span', { style: S.spacer }),
12631
+ // The config actions live on the CONSOLE title bar in both shapes: the
12632
+ // sidebar's title bar is this top bar, so it gets the same two icons
12633
+ // the standalone window puts next to its program list.
12634
+ configExists === true
12635
+ ? h('button', {
12636
+ type: 'button', style: S.paneIcon, 'data-action': 'compact-config-open',
12637
+ title: '打开配置文件 .dsh-ris-ide.json(启动参数由你维护)',
12638
+ onClick: openConfig,
12639
+ }, '📄')
12640
+ : null,
12641
+ h('button', {
12642
+ type: 'button', style: busyId === '__config__' ? S.paneIconOff : S.paneIcon,
12643
+ disabled: busyId === '__config__', 'data-action': 'compact-config-generate',
12644
+ title: configExists === true
12645
+ ? '更新配置:按当前扫描结果同步 .dsh-ris-ide.json(保留你改过的字段)'
12646
+ : '生成配置:把扫描到的程序写成 .dsh-ris-ide.json',
12647
+ onClick: function () { generateConfigFile(configExists ? 'update' : undefined) },
12648
+ }, busyId === '__config__' ? '…' : '⚙'),
10564
12649
  h('button', {
10565
12650
  type: 'button', style: S.paneButton, 'data-action': 'ide-window',
10566
12651
  title: '在独立窗口中打开RIS-IDE' + (picked !== undefined ? ':' + picked.name : ''),
@@ -10577,6 +12662,17 @@ var [ui, setUi] = useState(function () {
10577
12662
  state.error !== undefined && state.error !== null
10578
12663
  ? h('div', { style: S.compactNote, 'data-compact-error': '1' }, '扫描失败:' + state.error)
10579
12664
  : null,
12665
+ // Config notices (first-run generation / sync / drift) used to live only
12666
+ // in the retired instance-list markup; the console the user actually
12667
+ // sees has to show them, or nobody learns the config was written.
12668
+ configNoticeItems().filter(function (item) {
12669
+ return panelDismissals.isOpen(item.kind, item.signature)
12670
+ }).map(function (item) {
12671
+ return h(ClosableNotice, {
12672
+ key: item.kind + ':' + item.signature,
12673
+ styles: S, kind: item.kind, signature: item.signature, onDismiss: panelDismissals.dismiss,
12674
+ }, item.text)
12675
+ }),
10580
12676
  state.note !== undefined && state.note !== null
10581
12677
  ? h('div', { style: S.compactNote, 'data-compact-note': '1' },
10582
12678
  h('span', { style: S.compactNoteText }, state.note),
@@ -10587,6 +12683,32 @@ var [ui, setUi] = useState(function () {
10587
12683
  : null,
10588
12684
  // A maximized section parks the other one entirely (its header too: the
10589
12685
  // visible header's ⤡ is the way back, so there is nothing to lose).
12686
+ maxed === 'log'
12687
+ ? null
12688
+ : checkedIds.length > 1
12689
+ // The batch bar appears only once the ticking means something: two
12690
+ // ticks = one gesture instead of two.
12691
+ ? h('div', { style: S.bar, 'data-compact-batch': '1' },
12692
+ h('span', { style: S.status }, '已勾选 ' + checkedIds.length + ' 项'),
12693
+ h('span', { style: S.spacer }),
12694
+ h('button', {
12695
+ type: 'button', style: S.paneIcon, 'data-action': 'batch-start',
12696
+ disabled: busyId !== undefined || bulk !== null,
12697
+ title: '按列表顺序启动勾选的项目(跳过已在运行的)',
12698
+ onClick: function () { void actMany('start') },
12699
+ }, bulk !== null && bulk.kind === 'start' ? (bulk.index + 1) + '/' + bulk.total : '▶'),
12700
+ h('button', {
12701
+ type: 'button', style: S.paneIcon, 'data-action': 'batch-stop',
12702
+ disabled: busyId !== undefined || bulk !== null,
12703
+ title: '按列表倒序停止勾选的项目(跳过未运行的)',
12704
+ onClick: function () { void actMany('stop') },
12705
+ }, bulk !== null && bulk.kind === 'stop' ? (bulk.index + 1) + '/' + bulk.total : '■'),
12706
+ h('button', {
12707
+ type: 'button', style: S.paneButton, 'data-action': 'batch-clear',
12708
+ title: '取消全部勾选',
12709
+ onClick: function () { setCheckedIds([]) },
12710
+ }, '清除'))
12711
+ : null,
10590
12712
  maxed === 'log'
10591
12713
  ? null
10592
12714
  : h('div', { style: S.compactList, 'data-compact-list': '1' },
@@ -10680,6 +12802,14 @@ var [ui, setUi] = useState(function () {
10680
12802
  exists: configExists,
10681
12803
  },
10682
12804
  configNote: state.note,
12805
+ // 📄 in the standalone window: the panel cannot reach a sidebar editor, so
12806
+ // the path arrives here and the workbench opens it in its own tab.
12807
+ openConfigRequest: openConfigRequest,
12808
+ // First-run generation / sync / drift notices (the console-level list).
12809
+ configNotices: configNoticeItems(),
12810
+ // The row the window was opened on (sidebar 🐞): seeds the log pane and
12811
+ // turns on auto-debug. `null` = plain workspace window.
12812
+ openProgram: active !== null && active !== undefined && typeof active === 'object' ? active : null,
10683
12813
  tab: {
10684
12814
  id: PROGRAM_TAB_ID,
10685
12815
  type: PROGRAM_TAB_ID,
@@ -10877,7 +13007,18 @@ var [ui, setUi] = useState(function () {
10877
13007
  viewerThemeCss: viewerThemeCss,
10878
13008
  stylesFor: stylesFor,
10879
13009
  SearchResults: SearchResults,
13010
+ busyMaskText: busyMaskText,
13011
+ busyMaskTitle: busyMaskTitle,
10880
13012
  searchHitActiveIndex: searchHitActiveIndex,
13013
+ rememberSearchEntry: rememberSearchEntry,
13014
+ fsSearchContent: fsSearchContent,
13015
+ runTestStart: runTestStart,
13016
+ runTestStatus: runTestStatus,
13017
+ /**
13018
+ * The `mvn -pl <module> test -Dtest=…` call a Java test file would run; the
13019
+ * reactor root and the `-pl` argument are derived from the workspace path.
13020
+ */
13021
+ testRunTarget: testRunTarget,
10881
13022
  // Which frames the single stream socket delivers to which subscriber: the
10882
13023
  // tail bytes ride in `append` frames, so a strict topic match starved every
10883
13024
  // log pane. Directly testable, and the shape of the bug is easy to regress.
@@ -10895,6 +13036,12 @@ var [ui, setUi] = useState(function () {
10895
13036
  childEntryFor: childEntryFor,
10896
13037
  sourceRelativeSuffix: sourceRelativeSuffix,
10897
13038
  parseGutterLine: parseGutterLine,
13039
+ // Log level filter (PM gap #4) and the "what did I change" diff (#5): both
13040
+ // pure, both user-visible, both easy to break silently.
13041
+ logLineVisible: logLineVisible,
13042
+ filterLogLines: filterLogLines,
13043
+ logLineText: logLineText,
13044
+ lineDiff: lineDiff,
10898
13045
  driftSignature: driftSignature,
10899
13046
  capToasts: capToasts,
10900
13047
  capMessages: capMessages,
@@ -10924,6 +13071,8 @@ var [ui, setUi] = useState(function () {
10924
13071
  trimLogToCurrentRun: trimLogToCurrentRun,
10925
13072
  remapPath: remapPath,
10926
13073
  duplicateName: duplicateName,
13074
+ collisionCopyName: collisionCopyName,
13075
+ toggleTreeSelection: toggleTreeSelection,
10927
13076
  helpSections: helpSections,
10928
13077
  ideIcon: ideIcon,
10929
13078
  ideBadgeIcon: ideBadgeIcon,