@jidekaixin2dian/dsh-file-actions 0.1.18 → 0.1.19

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.19 — 2026-10-31
4
+
5
+ - 设置页新增中英文「项目与反馈」区域,可打开 File Actions GitHub 项目或新建反馈。
6
+ - Add bilingual project and issue links to the settings page.
7
+ - 设置下拉框改为统一圆角选项面板:选中勾、悬停高亮、箭头旋转与双向开合动画;支持键盘选择、Esc/外部点击收起、屏幕边缘避让和减少动画偏好。
8
+ - Style settings dropdown panels and animate opening and closing, with keyboard navigation, dismissal, viewport positioning and reduced-motion support.
9
+ - 优化设置页分组、紧凑行布局与亮暗/窄屏适配;侧栏缩短为「文件操作 / File Actions」,保留详情中英文全名,新增文件与指针图标。
10
+ - Refine settings layout and theme support, shorten the sidebar label, and add a file-and-pointer icon while retaining the full bilingual detail name.
11
+ - 新增原生设置侧栏入口:首选应用查看/取消/清除、完整/精简菜单、引用前后文范围,以及关联应用缓存清理;沿用原有首选应用数据,默认行为保持不变。
12
+ - 设置按当前客户端保存,存储失败保留旧值并提示;缓存清理隔离尚未完成的旧查询,卸载时注销入口。菜单与页面内容保留原生 DOM,仅使用宿主 React 作为设置槽的挂载适配,不新增运行时依赖。
13
+
14
+ - 新增「查看引用上下文」:只读行号预览、高亮引用行与有限前后文;沿用 UTF-8、2 MiB、工作区外明确确认,关闭、切换目标或会话后忽略迟到结果。
15
+ - 新增「复制片段及来源」:复制相对路径、行段与原始引用正文;保留内部换行,动态 Markdown 围栏保护代码内容,复制前核对文件版本。
16
+ - 中英文详情名称同时保留中文与英文,更新简介;默认兼容验证宿主升级至 DSH rc.5,并保留 rc.2 / rc.3 / rc.4。行列跳转暂缓,rc.5 官方接口仍无位置字段。
17
+ - Add read-only reference context and source-attributed excerpt copying. Preserve the existing file access gates and reject stale reads; verify DSH rc.5 while retaining earlier host coverage.
18
+
3
19
  ## 0.1.18 — 2026-10-30
4
20
 
5
21
  - 新增「复制引用行」:带行号的文本引用可复制对应整行或行段;保留原始内部换行,沿用 UTF-8、2 MiB 与工作区外确认限制;超出文件范围时拒绝复制。
package/README.en.md CHANGED
@@ -1,8 +1,8 @@
1
- # File Actions
1
+ # File Actions · 文件与链接操作
2
2
 
3
3
  **Turn a file reference in your conversation into the next action.**
4
4
 
5
- [中文](README.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-file-actions/v/0.1.18) · [Marketplace](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-file-actions/) · [Download](https://github.com/jidekaixin2dian/dsh-file-actions/releases/latest) · [Changelog](CHANGELOG.md)
5
+ [中文](README.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-file-actions/v/0.1.19) · [Marketplace](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-file-actions/) · [Download](https://github.com/jidekaixin2dian/dsh-file-actions/releases/latest) · [Changelog](CHANGELOG.md)
6
6
 
7
7
  Once a model gives you a file, the next step is usually to open it, keep editing or take its contents elsewhere. File Actions puts application choices, reveal, copy, preview and save into one context menu across chat references, delivery cards, tool results and sidebars that expose file paths.
8
8
 
@@ -27,7 +27,7 @@ Snapshot: **2026-10-29**. GitHub counts release-asset requests, including checks
27
27
 
28
28
  ## Install and update
29
29
 
30
- Requires **DSH >=0.2.1-rc.2 and Node >=24**. CI verifies DSH rc.2 / rc.3 / rc.4.
30
+ Requires **DSH >=0.2.1-rc.2 and Node >=24**. CI verifies DSH rc.2 / rc.3 / rc.4 / rc.5.
31
31
 
32
32
  Search for **dsh-file-actions** in the marketplace and verify author **jidekaixin2dian**. Existing users can check updates under installed plugins. Catalog and registry mirrors may take time to refresh.
33
33
 
@@ -60,13 +60,27 @@ dsh plugin --profile desktop remove @jidekaixin2dian/dsh-file-actions
60
60
  2. Search **Open with** and star an application to remember it for that file type. OS defaults stay unchanged.
61
61
  3. Enlarge image thumbnails or view supported documents, audio and video in the browser.
62
62
  4. For text references such as `src/app.ts:42:7` or `notes.md#L42-L48`, choose **Copy referenced lines** to copy that line or range. Locations beyond the current file show an error instead of copying the whole file.
63
+ 5. Choose **View reference context** for a read-only view with line numbers, highlighted referenced lines and nearby context. **Copy excerpt with source** includes the relative path, line range and referenced text, without the surrounding context. Preview display is bounded for long lines and large selections; copying retains the complete referenced lines. Reading outside the workspace requires confirmation before any content is read.
63
64
 
64
- The option appears only when the reference retains its line numbers. If the host renders a link as a button exposing only its path, hidden line information cannot be recovered.
65
+ Referenced-line copying and context preview appear only when the reference retains its line numbers. If the host renders a link as a button exposing only its path, hidden line information cannot be recovered.
65
66
 
66
67
  Keyboard: `Shift+F10` opens the menu, `↑ ↓` move, `→` enters a submenu, `Enter` runs and `Esc` closes. `Shift+right-click` gives the page's own handler priority.
67
68
 
68
69
  The marketplace checks versions and installs after your click; it does not silently upgrade in the background. Restart DSH when requested.
69
70
 
71
+ ## Settings
72
+
73
+ Open **File Actions** in the DSH settings sidebar (**文件操作** in Chinese); the page retains the full bilingual name:
74
+
75
+ - **Menu display**: full by default; compact mode keeps common open, reveal, reference preview, copy and save actions.
76
+ - **Reference context**: 4, 8 or 16 lines before and after, with 8 as the default. This does not change which referenced lines are copied.
77
+ - **Preferred applications**: view and remove individual preferences or clear them all. Set new preferences from a file's **Open with** menu.
78
+ - **Application cache**: clear after installing or removing applications. The next file menu queries again; preferences are retained.
79
+
80
+ Changes take effect immediately and persist in this browser or Desktop client. Resetting menu and preview defaults retains preferred applications. Preferences do not change system defaults or sync automatically to other clients.
81
+
82
+ Use **Project and feedback** at the bottom of settings to visit this plugin's GitHub repository or report an issue. Ideas and suggestions are welcome.
83
+
70
84
  ## Boundaries
71
85
 
72
86
  - File operations use official DSH APIs and path authorization. Application lists depend on system associations; the plugin does not repair registry entries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
- # File Actions · 文件与链接操作
1
+ # 文件与链接操作 · File Actions
2
2
 
3
3
  **从聊天里的文件引用,直接到你要做的操作。**
4
4
 
5
- [English](README.en.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-file-actions/v/0.1.18) · [插件市场](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-file-actions/) · [下载](https://github.com/jidekaixin2dian/dsh-file-actions/releases/latest) · [更新记录](CHANGELOG.md)
5
+ [English](README.en.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-file-actions/v/0.1.19) · [插件市场](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-file-actions/) · [下载](https://github.com/jidekaixin2dian/dsh-file-actions/releases/latest) · [更新记录](CHANGELOG.md)
6
6
 
7
7
  模型给出文件后,下一步通常是打开、继续编辑,或把内容带走。File Actions 把打开方式、文件定位、路径与内容复制、预览和另存放进一个右键菜单,覆盖聊天引用、交付卡片、工具结果及提供文件路径的侧栏。
8
8
 
@@ -27,7 +27,7 @@
27
27
 
28
28
  ## 安装与更新
29
29
 
30
- 需要 **DSH >=0.2.1-rc.2、Node >=24**;持续验证 DSH rc.2 / rc.3 / rc.4。
30
+ 需要 **DSH >=0.2.1-rc.2、Node >=24**;持续验证 DSH rc.2 / rc.3 / rc.4 / rc.5。
31
31
 
32
32
  在插件市场搜索 **dsh-file-actions**,确认作者为 **jidekaixin2dian** 后安装;已有用户在「已安装」中检查更新。市场数据与 npm 镜像可能有同步延迟。
33
33
 
@@ -62,17 +62,31 @@ dsh plugin --profile desktop remove @jidekaixin2dian/dsh-file-actions
62
62
  2. 选择「打开方式」可搜索应用,点击星标保存当前文件类型的首选;不会改变系统默认应用。
63
63
  3. 图片支持缩略图与放大预览;支持的文档、音视频可在浏览器中查看。
64
64
  4. 对 `src/app.ts:42:7` 或 `notes.md#L42-L48` 这类文本引用,可选「复制引用行」复制该行或该段,不必复制整个文件。行号超出当前文件范围时会提示,不会改为复制全文。
65
+ 5. 选择「查看引用上下文」,在只读预览中查看行号、高亮引用行及少量前后文;「复制片段及来源」一次带走相对路径、行号与引用正文,不包含额外上下文。长行或较大引用会在预览中缩短显示,复制保留完整引用行。
65
66
 
66
- 该选项仅在引用仍保留行号时出现;宿主若把链接渲染为仅暴露路径的按钮,插件无法恢复已隐藏的行号。
67
+ 引用行复制和上下文预览仅在引用仍保留行号时出现;宿主若把链接渲染为仅暴露路径的按钮,插件无法恢复已隐藏的行号。
67
68
 
68
69
  键盘:`Shift+F10` 打开菜单,`↑ ↓` 移动,`→` 进入子菜单,`Enter` 执行,`Esc` 关闭。`Shift+右键` 优先交给页面原有菜单。
69
70
 
70
71
  更新由市场检查并在你点击后安装,不会静默后台升级;需要时按提示重启 DSH。
71
72
 
73
+ ## 设置
74
+
75
+ 在 DSH 设置侧栏打开 **文件操作**(英文界面为 **File Actions**);页面保留完整中英文名称:
76
+
77
+ - **菜单显示**:默认完整菜单;精简模式保留常用打开、定位、引用预览、复制和另存操作。
78
+ - **引用前后文**:前后各 4 / 8 / 16 行,默认各 8 行;不改变引用正文的复制范围。
79
+ - **首选应用**:查看已设置的文件类型,单独取消或全部清除;选择新首选仍在文件的「打开方式」菜单中完成。
80
+ - **关联应用缓存**:安装或卸载应用后可清除缓存,下次右键重新查询;保留首选应用。
81
+
82
+ 修改立即生效,并保留在当前浏览器或 Desktop 客户端。恢复菜单与预览默认设置不会清除首选应用;这些偏好不会修改系统默认应用,也不会自动同步到其他客户端。
83
+
84
+ 页尾的「项目与反馈」可打开本插件的 GitHub 项目或新建反馈;欢迎提出问题和改进想法。
85
+
72
86
  ## 使用边界
73
87
 
74
88
  - 打开与定位沿用 DSH 官方接口和路径授权;应用列表取决于系统关联。失效关联可能导致列表不可用,插件不会修改注册表。
75
- - 复制内容与引用行仅支持 **有效 UTF-8、文件最大 2 MiB**。引用行按整行复制,保留所选行之间的原始换行;列号不裁剪内容。工作区外复制需要明确确认;确认不可用时取消读取。
89
+ - 复制内容与引用行仅支持 **有效 UTF-8、文件最大 2 MiB**。引用行按整行复制,保留所选行之间的原始换行;列号不裁剪内容。工作区外复制或引用上下文预览需要先明确确认;确认不可用时取消读取。
76
90
  - 另存为和浏览器预览最多读取 **64 MiB**,分块内容不一致时中止;不是文件系统原子快照。
77
91
  - HTML / SVG 默认静态预览并阻止脚本和外部资源。仅在信任文件后启用脚本与联网;预览仍与 DSH 页面隔离。相对资源可能不可用,点击文件内链接属于主动导航。
78
92
  - 编辑器打开暂不跳到行列位置;另存为使用浏览器下载行为。插件用于 DSH 图形 / Web 界面,终端界面不适用。
package/icon.svg CHANGED
@@ -1,7 +1,13 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="dsh-file-actions">
2
- <rect width="64" height="64" rx="14" fill="#1b1d21"/>
3
- <path d="M18 16h18l10 10v22a4 4 0 0 1-4 4H18a4 4 0 0 1-4-4V20a4 4 0 0 1 4-4z" fill="none" stroke="#e8e8e8" stroke-width="2.4" stroke-linejoin="round"/>
4
- <path d="M36 16v10h10" fill="none" stroke="#e8e8e8" stroke-width="2.4" stroke-linejoin="round"/>
5
- <circle cx="45" cy="45" r="11" fill="#c8f663"/>
6
- <path d="M40.5 45h9M45 40.5v9" stroke="#1b1d21" stroke-width="2.6" stroke-linecap="round"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="File Actions">
2
+ <defs>
3
+ <linearGradient id="surface" x1="8" y1="4" x2="56" y2="62" gradientUnits="userSpaceOnUse">
4
+ <stop stop-color="#3578ef"/>
5
+ <stop offset="1" stop-color="#158eaa"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <rect x="1" y="1" width="62" height="62" rx="15" fill="url(#surface)"/>
9
+ <rect x="1.5" y="1.5" width="61" height="61" rx="14.5" fill="none" stroke="#fff" stroke-opacity=".16"/>
10
+ <path d="M34 13H19a3 3 0 0 0-3 3v31a3 3 0 0 0 3 3h22a3 3 0 0 0 3-3V23z" fill="#fff" fill-opacity=".12" stroke="#fff" stroke-width="2.4" stroke-linejoin="round"/>
11
+ <path d="M34 13v10h10M23 31h9M23 37h6" fill="none" stroke="#fff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>
12
+ <path d="m34 35 16 10-8 2-3.5 8z" fill="#fff" stroke="#176b9d" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
7
13
  </svg>
package/lib/client.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // the path against the composed filesystem before touching the desktop.
16
16
  // DSH concatenates classic bundles; every registration needs its own scope.
17
17
  ;(() => {
18
- const factory = () => {
18
+ const factory = (require) => {
19
19
  const module = { exports: {} }
20
20
  const exports = module.exports
21
21
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
@@ -29,6 +29,28 @@ const factory = () => {
29
29
  /* ─────────────────────────────── copy ─────────────────────────────── */
30
30
 
31
31
  const ZH = {
32
+ settings: {
33
+ title: '文件与链接操作 · File Actions', nav: '文件操作',
34
+ resetShort: '恢复默认', clearShort: '全部清除', removeShort: '取消',
35
+ menuHint: '按习惯选择右键菜单的详细程度', contextHint: '只影响预览,复制仍只包含引用行',
36
+ scopeShort: '仅在当前客户端保存,不改变系统默认应用。',
37
+ cacheHint: '下次右键重新查询,首选应用保留。',
38
+ intro: '让文件操作更顺手。修改后立即生效。',
39
+ project: '项目与反馈', projectHint: '有问题或想法?欢迎在 GitHub 留言,一起把文件操作做得更顺手。',
40
+ github: 'GitHub 项目', feedback: '反馈问题',
41
+ scope: '仅保存在当前浏览器或 Desktop 客户端;不会修改系统默认应用。',
42
+ display: '菜单与预览', menuMode: '菜单显示', full: '完整菜单', compact: '精简菜单',
43
+ menuHelp: '精简模式保留打开、打开方式、定位、引用预览、复制路径与正文、另存等常用操作。',
44
+ contextLines: '引用前后文', contextOption: '前后各 {count} 行',
45
+ defaults: '恢复菜单与预览默认设置',
46
+ apps: '首选应用', appsHelp: '在文件右键菜单的「打开方式」中设置首选;这里可查看和取消。',
47
+ noApps: '尚未设置首选应用', noExtension: '无扩展名', remove: '取消首选', clearApps: '清除全部首选应用',
48
+ cache: '关联应用缓存', cacheHelp: '安装或卸载应用后,可清除缓存。下次右键文件时会重新查询,不会清除首选应用。',
49
+ cacheCount: '已缓存 {count} 种文件类型', clearCache: '清除关联缓存',
50
+ saved: '设置已保存', reset: '已恢复完整菜单与前后各 8 行', removed: '首选应用已清除',
51
+ cacheCleared: '关联缓存已清除,下次右键将重新查询',
52
+ failed: '无法保存,请检查当前客户端的存储权限;原设置保留。',
53
+ },
32
54
  open: '打开文件',
33
55
  openFolder: '打开文件夹',
34
56
  openIn: (name) => `在 ${name} 中打开`,
@@ -43,6 +65,14 @@ const factory = () => {
43
65
  copyMarkdown: '复制为 Markdown',
44
66
  copyContents: '复制文件内容',
45
67
  copyLines: '复制引用行',
68
+ referencePreview: '查看引用上下文',
69
+ copySource: '复制片段及来源',
70
+ copiedSource: '片段及来源已复制',
71
+ closePreview: '关闭预览',
72
+ referenceLoading: '正在读取引用上下文…',
73
+ referenceWindow: '预览第 {from}–{to} 行,共 {total} 行 · 复制仅包含引用行',
74
+ previewClipped: '长行或较大引用仅显示部分内容,复制保留完整引用行',
75
+ confirmOutsidePreview: '该文件在会话工作区之外。确认读取并预览它的内容吗?\n{path}',
46
76
  saveAs: '另存为…',
47
77
  copiedPath: '路径已复制',
48
78
  copiedRelPath: '相对路径已复制',
@@ -128,6 +158,28 @@ const factory = () => {
128
158
  }
129
159
 
130
160
  const EN = {
161
+ settings: {
162
+ title: 'File Actions · 文件与链接操作', nav: 'File Actions',
163
+ resetShort: 'Reset', clearShort: 'Clear all', removeShort: 'Remove',
164
+ menuHint: 'Choose how much appears in the file menu', contextHint: 'Preview only; copying keeps the referenced lines',
165
+ scopeShort: 'Saved on this client. System defaults stay unchanged.',
166
+ cacheHint: 'Queries again on the next file menu; preferences stay.',
167
+ intro: 'File actions, the way you work. Changes apply immediately.',
168
+ project: 'Project and feedback', projectHint: 'Found a problem or have an idea? Help make File Actions better on GitHub.',
169
+ github: 'GitHub project', feedback: 'Report an issue',
170
+ scope: 'Saved in this browser or Desktop client only. System default applications stay unchanged.',
171
+ display: 'Menu and preview', menuMode: 'Menu display', full: 'Full menu', compact: 'Compact menu',
172
+ menuHelp: 'Compact mode keeps open, open with, reveal, reference context, path and text copying, and save actions.',
173
+ contextLines: 'Reference context', contextOption: '{count} lines before and after',
174
+ defaults: 'Reset menu and preview defaults',
175
+ apps: 'Preferred applications', appsHelp: 'Set preferences from a file’s Open with menu; view and remove them here.',
176
+ noApps: 'No preferred applications yet', noExtension: 'No extension', remove: 'Remove preference', clearApps: 'Clear all preferred applications',
177
+ cache: 'Application cache', cacheHelp: 'After installing or removing applications, clear this cache. The next file menu queries applications again; preferences are retained.',
178
+ cacheCount: '{count} file types cached', clearCache: 'Clear application cache',
179
+ saved: 'Settings saved', reset: 'Full menu and 8 context lines restored', removed: 'Application preferences cleared',
180
+ cacheCleared: 'Cache cleared; the next file menu will query applications again',
181
+ failed: 'Could not save. Check client storage permissions; previous settings are retained.',
182
+ },
131
183
  open: 'Open file',
132
184
  openFolder: 'Open folder',
133
185
  openIn: (name) => `Open in ${name}`,
@@ -142,6 +194,14 @@ const factory = () => {
142
194
  copyMarkdown: 'Copy as Markdown',
143
195
  copyContents: 'Copy file contents',
144
196
  copyLines: 'Copy referenced lines',
197
+ referencePreview: 'View reference context',
198
+ copySource: 'Copy excerpt with source',
199
+ copiedSource: 'Excerpt and source copied',
200
+ closePreview: 'Close preview',
201
+ referenceLoading: 'Loading reference context…',
202
+ referenceWindow: 'Showing lines {from}–{to} of {total} · Copy includes referenced lines only',
203
+ previewClipped: 'Long lines or large references are shortened in preview; copying retains the full referenced lines',
204
+ confirmOutsidePreview: 'This file is outside the session workspace. Read and preview its contents?\n{path}',
145
205
  saveAs: 'Save as…',
146
206
  copiedPath: 'Path copied',
147
207
  copiedRelPath: 'Relative path copied',
@@ -538,7 +598,7 @@ const factory = () => {
538
598
  }
539
599
 
540
600
  // Store application IDs only, never commands. Host validation still owns opens.
541
- function applicationPreferences(storage) {
601
+ function applicationPreferences(storage, notify = () => {}) {
542
602
  const key = 'dsh-file-actions.preferred-apps.v1'
543
603
  const type = (path) => extname(path).toLowerCase() || '[no extension]'
544
604
  const read = () => {
@@ -549,18 +609,41 @@ const factory = () => {
549
609
  }
550
610
  return {
551
611
  get(path) { const value = read()[type(path)]; return typeof value === 'string' ? value : '' },
612
+ list() { return Object.entries(read()).filter(([key, value]) => key && typeof value === 'string' && value).sort(([a], [b]) => a.localeCompare(b)).map(([type, appId]) => ({ type, appId })) },
613
+ remove(type) {
614
+ try { const value = read(); delete value[type]; storage.setItem(key, JSON.stringify(value)); notify(); return true } catch { return false }
615
+ },
616
+ clear() { try { storage.removeItem(key); notify(); return true } catch { return false } },
552
617
  set(path, appId) {
553
618
  try {
554
619
  const value = read()
555
620
  if (appId) Object.defineProperty(value, type(path), { value: appId, enumerable: true, configurable: true, writable: true })
556
621
  else delete value[type(path)]
557
622
  storage.setItem(key, JSON.stringify(value))
623
+ notify()
558
624
  return true
559
625
  } catch { return false }
560
626
  },
561
627
  }
562
628
  }
563
629
 
630
+ const CLIENT_SETTINGS_KEY = 'dsh-file-actions.settings.v1'
631
+ function clientPreferences(storage) {
632
+ const sanitize = value => ({ menuMode: value?.menuMode === 'compact' ? 'compact' : 'full',
633
+ contextLines: [4, 8, 16].includes(value?.contextLines) ? value.contextLines : 8 })
634
+ return {
635
+ get() { try { return sanitize(JSON.parse(storage.getItem(CLIENT_SETTINGS_KEY) || '{}')) } catch { return sanitize(null) } },
636
+ set(patch) { try { storage.setItem(CLIENT_SETTINGS_KEY, JSON.stringify(sanitize({ ...this.get(), ...patch }))); return true } catch { return false } },
637
+ reset() { try { storage.removeItem(CLIENT_SETTINGS_KEY); return true } catch { return false } },
638
+ }
639
+ }
640
+
641
+ function visibleMenuSections(sections, mode) {
642
+ if (mode !== 'compact') return sections.filter(section => section.length)
643
+ const common = new Set(['open', 'openWith', 'reveal', 'referencePreview', 'copyPath', 'copyLines', 'copyContents', 'saveAs', 'openLink', 'copyLink'])
644
+ return sections.map(section => section.filter(item => common.has(item.id))).filter(section => section.length)
645
+ }
646
+
564
647
  function buildStatusModel(path, message, t, retry = false) {
565
648
  return { title: basename(path) || path, subtitle: path, pathLine: path, kind: 'binary',
566
649
  status: true, sections: [[{ id: 'status', label: message, disabled: true }],
@@ -614,6 +697,34 @@ const factory = () => {
614
697
  return line === range.endLine && start !== null && lineStart < text.length ? text.slice(start) : null
615
698
  }
616
699
 
700
+ function referenceContext(text, location, contextLines = 8) {
701
+ const range = referenceRange(location)
702
+ if (!range || referencedText(text, range) === null) return null
703
+ const lines = text.split(/\r\n|\n|\r/)
704
+ if (lines.at(-1) === '') lines.pop()
705
+ const padding = [4, 8, 16].includes(contextLines) ? contextLines : 8
706
+ const from = Math.max(1, range.line - padding)
707
+ const to = Math.min(lines.length, range.endLine + padding, from + 79)
708
+ const rows = lines.slice(from - 1, to).map((value, index) => ({
709
+ line: from + index, text: value.length > 2400 ? value.slice(0, 2400) + '…' : value,
710
+ selected: from + index >= range.line && from + index <= range.endLine,
711
+ }))
712
+ return { from, to, total: lines.length, rows,
713
+ clipped: to < range.endLine || lines.slice(from - 1, to).some(value => value.length > 2400) }
714
+ }
715
+
716
+ function sourceExcerpt(text, target) {
717
+ const range = referenceRange(target)
718
+ const selected = referencedText(text, target)
719
+ if (!range || selected === null) return null
720
+ const path = String(target.displayPath || target.absolutePath).replace(/[\r\n]/g, ' ')
721
+ const location = `${path}#L${range.line}${range.endLine === range.line ? '' : `-L${range.endLine}`}`
722
+ let fenceLength = 3
723
+ for (const match of selected.matchAll(/`+/g)) fenceLength = Math.max(fenceLength, match[0].length + 1)
724
+ const fence = '`'.repeat(fenceLength)
725
+ return `${location}\n\n${fence}\n${selected}\n${fence}`
726
+ }
727
+
617
728
  function buildMenuModel(input) {
618
729
  const t = input.t || ZH
619
730
  const { absolutePath, displayPath, isDir, bytes } = input
@@ -678,6 +789,9 @@ const factory = () => {
678
789
  action: 'browser',
679
790
  })
680
791
  }
792
+ if (!isDir && file.canCopyText && referenceRange(input.location)) {
793
+ navigate.push({ id: 'referencePreview', label: t.referencePreview, icon: 'doc', action: 'referencePreview', keepOpen: true })
794
+ }
681
795
  navigate.push({
682
796
  id: 'reveal',
683
797
  label: isDir ? t.revealFolder : t.reveal,
@@ -735,7 +849,7 @@ const factory = () => {
735
849
  kind: file.kind,
736
850
  preview: file.kind === 'image' || file.kind === 'video' || extname(absolutePath) === 'svg',
737
851
  outsideWorkspace: input.outsideWorkspace === true,
738
- sections: sections.filter((section) => section.length > 0),
852
+ sections: visibleMenuSections(sections, input.menuMode),
739
853
  }
740
854
  }
741
855
 
@@ -770,16 +884,23 @@ const factory = () => {
770
884
  meta: t.kinds.link,
771
885
  kind: 'link',
772
886
  outsideWorkspace: false,
773
- sections: [
887
+ sections: visibleMenuSections([
774
888
  [{ id: 'openLink', label: t.openLink, icon: 'external', action: 'openLink' }],
775
889
  copy,
776
- ],
890
+ ], input.menuMode),
777
891
  }
778
892
  }
779
893
 
780
894
  /* ─────────────────────────────── icons ─────────────────────────────── */
781
895
 
782
896
  const ICON_PATHS = {
897
+ feedback: '<path d="M6 4h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-7l-5 4v-4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><path d="M8 9h8M8 13h5"/>',
898
+ check: '<path d="m5 12 4 4L19 6"/>',
899
+ sliders: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="2" fill="Canvas"/><circle cx="15" cy="17" r="2" fill="Canvas"/>',
900
+ apps: '<rect x="4" y="4" width="6" height="6" rx="1.5"/><rect x="14" y="4" width="6" height="6" rx="1.5"/><rect x="4" y="14" width="6" height="6" rx="1.5"/><rect x="14" y="14" width="6" height="6" rx="1.5"/>',
901
+ refresh: '<path d="M19 8a7 7 0 1 0 .2 7M19 4v4h-4"/>',
902
+ info: '<circle cx="12" cy="12" r="8"/><path d="M12 11v5M12 8h.01"/>',
903
+ fileActions: '<path d="M13 3.5H6.5A1.5 1.5 0 0 0 5 5v14a1.5 1.5 0 0 0 1.5 1.5h7M13 3.5l5 5h-5z"/><path d="m14 12 6.5 4.1-3.3.9-1.4 3.2z"/>',
783
904
  file: '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>',
784
905
  folder: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2.6h8a2 2 0 0 1 2 2V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',
785
906
  folderOpen: '<path d="M3 18V7a2 2 0 0 1 2-2h4l2 2.6h8a2 2 0 0 1 2 2V11"/><path d="M3 18.5 5.7 12a2 2 0 0 1 1.9-1.3H22l-2.7 7.6a2 2 0 0 1-1.9 1.3H4.8a1.8 1.8 0 0 1-1.8-1.1z"/>',
@@ -987,6 +1108,38 @@ const factory = () => {
987
1108
  .dfa-foot{display:flex;justify-content:center;gap:12px;margin:6px 7px 0;padding:6px 0 2px;
988
1109
  border-top:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.28));
989
1110
  font-size:.85em;line-height:1.4;color:var(--dsw-alias-label-tertiary,rgba(160,160,160,.95))}
1111
+
1112
+ .dfa-reference-overlay{position:fixed;inset:0;z-index:2147483004;background:rgba(0,0,0,.38);display:flex;align-items:center;justify-content:center;padding:16px;font:1rem/1.5 system-ui,sans-serif}
1113
+ .dfa-reference{background:var(--dfa-floor,Canvas);color:inherit;border:1px solid color-mix(in srgb,currentColor 18%,transparent);border-radius:12px;box-shadow:0 16px 56px #0005;width:min(860px,100%);max-height:82vh;display:flex;flex-direction:column;overflow:hidden}
1114
+ .dfa-reference-head{padding:16px 18px 12px;display:flex;align-items:flex-start;gap:12px;border-bottom:1px solid color-mix(in srgb,currentColor 15%,transparent)}
1115
+ .dfa-reference-info{min-width:0;flex:1}.dfa-reference-title{font-weight:650}.dfa-reference-path{font: .8rem/1.5 Consolas,monospace;overflow-wrap:anywhere;opacity:.75;margin-top:4px}
1116
+ .dfa-reference button{font:inherit;color:inherit;background:transparent;border:1px solid color-mix(in srgb,currentColor 25%,transparent);border-radius:6px;padding:6px 10px;cursor:pointer}
1117
+ .dfa-reference button:focus-visible{outline:2px solid Highlight;outline-offset:2px}.dfa-reference button:disabled{opacity:.45;cursor:default}
1118
+ .dfa-reference-body{overflow:auto;min-height:80px;max-height:56vh;overscroll-behavior:contain;padding:8px 0;font:.82rem/1.65 Consolas,"Microsoft YaHei",monospace;tab-size:4}
1119
+ .dfa-reference-row{display:flex;min-width:100%;width:max-content;padding-right:18px}.dfa-reference-row[data-selected="true"]{background:color-mix(in srgb,Highlight 14%,transparent);box-shadow:inset 3px 0 Highlight}
1120
+ .dfa-reference-number{position:sticky;left:0;flex:none;width:4.5em;text-align:right;padding-right:14px;opacity:.65;user-select:none;background:var(--dfa-floor,Canvas)}
1121
+ .dfa-reference-code{white-space:pre}.dfa-reference-status{padding:14px 18px;white-space:normal;font: .875rem/1.6 system-ui,sans-serif}
1122
+ .dfa-reference-footer{display:flex;gap:10px;align-items:center;justify-content:space-between;flex-wrap:wrap;padding:12px 18px;border-top:1px solid color-mix(in srgb,currentColor 15%,transparent)}
1123
+ .dfa-reference-hint{font-size:.75rem;opacity:.7;flex:1;min-width:130px}.dfa-reference-actions{display:flex;gap:8px;flex-wrap:wrap}
1124
+
1125
+
1126
+
1127
+ .dfa-settings{--dfa-accent:var(--dsw-alias-brand,#367bf5);--dfa-line:var(--dsw-alias-border-l2,#8883);max-width:760px;padding:4px 0 20px;color:var(--dsw-alias-label-primary,inherit);font:.875rem/1.5 var(--dsw-font-family,system-ui,sans-serif)}
1128
+ .dfa-settings *{box-sizing:border-box}.dfa-settings h2,.dfa-settings h3,.dfa-settings p{margin:0}.dfa-settings-header{display:flex;align-items:center;gap:12px;margin:0 0 22px}.dfa-settings-mark{display:grid;place-items:center;width:42px;height:42px;border:1px solid color-mix(in srgb,var(--dfa-accent) 20%,transparent);border-radius:12px;color:var(--dfa-accent);background:color-mix(in srgb,var(--dfa-accent) 10%,transparent);flex:none}
1129
+ .dfa-settings-mark svg{width:25px;height:25px;stroke-width:1.6}.dfa-settings h2{font-size:1.08rem;font-weight:650;letter-spacing:-.02em;line-height:1.4}.dfa-settings-intro{font-size:.8rem;opacity:.65;margin-top:3px!important}
1130
+ .dfa-project{margin:4px 0 16px;padding:16px 4px 0;border-top:1px solid var(--dfa-line)}.dfa-project h3{margin-bottom:5px!important}.dfa-project-links{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.dfa-settings .dfa-project-link{display:inline-flex;align-items:center;gap:7px;margin:0;padding:7px 10px;border:1px solid var(--dfa-line);border-radius:7px;background:var(--dsw-alias-bg-layer-2,Canvas);color:inherit;text-decoration:none;font-size:.78rem;line-height:1.5}.dfa-project-link svg{width:15px;height:15px;flex:none;opacity:.75}.dfa-project-link:hover{border-color:var(--dfa-accent)}.dfa-project-link:focus-visible{outline:2px solid var(--dfa-accent);outline-offset:2px}
1131
+ .dfa-settings-card{background:var(--dfa-settings-floor,var(--dsw-alias-bg-layer-1,Canvas));border:1px solid var(--dfa-line);border-radius:12px;margin:0 0 14px;overflow:hidden}.dfa-settings-card-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 16px 8px}.dfa-settings h3{font-size:.86rem;font-weight:650;display:flex;align-items:center;gap:8px}.dfa-settings-card-head h3>svg{opacity:.55}.dfa-settings-note{font-size:.76rem;line-height:1.6;opacity:.62}.dfa-settings-row{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:14px 16px;border-top:1px solid var(--dfa-line)}
1132
+ .dfa-settings-copy{min-width:0;flex:1}.dfa-settings label{font-weight:550;display:block;margin-bottom:4px}.dfa-settings button,.dfa-settings select{margin:0;font:inherit;line-height:1.45;color:inherit;max-width:100%;border:1px solid var(--dfa-line);border-radius:7px;background:var(--dsw-alias-bg-layer-2,Canvas);padding:7px 10px}
1133
+ .dfa-settings select{min-width:126px;flex:none;font-size:.8rem}.dfa-settings button{cursor:pointer;font-size:.78rem;transition:background .12s,border-color .12s}.dfa-settings button:hover:not(:disabled){border-color:color-mix(in srgb,currentColor 32%,transparent);background:color-mix(in srgb,var(--dfa-accent) 6%,var(--dsw-alias-bg-layer-2,Canvas))}.dfa-settings button:disabled{opacity:.36;cursor:default}.dfa-settings :is(button,select):focus-visible{outline:2px solid var(--dfa-accent);outline-offset:2px}.dfa-settings .dfa-settings-ghost{border-color:transparent;background:transparent;padding:4px 6px;opacity:.7;white-space:nowrap}
1134
+ .dfa-settings .dfa-select-trigger{display:flex;align-items:center;justify-content:space-between;gap:14px;min-width:126px;flex:none;text-align:left;font-size:.8rem;padding:8px 10px;transition:background .16s,border-color .16s,box-shadow .16s}.dfa-select-trigger>svg{width:14px;height:14px;opacity:.65;transform:rotate(90deg);transition:transform .16s cubic-bezier(.2,.7,.3,1)}.dfa-settings .dfa-select-trigger[aria-expanded="true"]{border-color:var(--dfa-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dfa-accent) 12%,transparent)}.dfa-select-trigger[aria-expanded="true"]>svg{transform:rotate(270deg)}
1135
+ .dfa-select-menu{position:fixed;z-index:2147483004;box-sizing:border-box;padding:5px;border:1px solid var(--dfa-line,#8883);border-radius:11px;background:var(--dfa-select-floor,Canvas);color:var(--dsw-alias-label-primary,CanvasText);box-shadow:0 4px 10px #0000000c,0 14px 34px #00000024;font:.8rem/1.5 var(--dsw-font-family,system-ui,sans-serif);overflow-y:auto;overscroll-behavior:contain;outline:none}.dfa-select-option{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:36px;padding:8px 10px;box-sizing:border-box;border-radius:7px;cursor:pointer;user-select:none;white-space:nowrap}.dfa-select-option>svg{width:15px;height:15px;flex:none;color:var(--dfa-accent,#367bf5);opacity:0}.dfa-select-option[aria-selected="true"]{color:var(--dfa-accent,#367bf5);font-weight:550}.dfa-select-option[aria-selected="true"]>svg{opacity:1}.dfa-select-option[data-active="true"]{background:color-mix(in srgb,var(--dfa-accent,#367bf5) 12%,transparent)}.dfa-select-menu[data-state="closing"]{pointer-events:none}
1136
+ @media(prefers-reduced-motion:reduce){.dfa-settings .dfa-select-trigger,.dfa-select-trigger>svg{transition:none}}
1137
+ .dfa-settings-count{border:1px solid var(--dfa-line);border-radius:5px;font-size:.68rem;font-weight:500;padding:0 5px;opacity:.7;line-height:1.6}.dfa-settings-app{display:flex;align-items:center;gap:12px;justify-content:space-between;padding:11px 16px;border-top:1px solid var(--dfa-line)}
1138
+ .dfa-settings-app-info{min-width:0;display:flex;align-items:center;gap:12px;flex:1}.dfa-settings-app-info strong{display:inline-block;min-width:56px;padding:4px 7px;border-radius:5px;background:color-mix(in srgb,var(--dfa-accent) 7%,transparent);color:var(--dfa-accent);font:500 .73rem/1.5 Consolas,monospace}.dfa-settings-app-info span{overflow-wrap:anywhere;font-size:.8rem}.dfa-settings-empty{display:flex;align-items:center;gap:12px;padding:15px 16px 19px}.dfa-settings-empty>svg{flex:none;opacity:.4;width:25px;height:25px}.dfa-settings-empty strong{display:block;font-size:.8rem;font-weight:500;margin-bottom:4px}
1139
+ .dfa-settings-cache{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:13px 4px 15px}.dfa-settings-cache-title{display:flex;gap:7px;align-items:center;font-size:.8rem;font-weight:550;margin-bottom:4px}.dfa-settings-cache-title>svg{opacity:.5}.dfa-settings-cache button{display:flex;align-items:center;gap:7px;white-space:nowrap;font-size:.76rem}.dfa-settings-footer{padding:12px 4px 0;border-top:1px solid var(--dfa-line);display:flex;align-items:flex-start;gap:7px;font-size:.72rem;line-height:1.6;opacity:.55}.dfa-settings-footer svg{width:13px;height:13px;flex:none;margin-top:2px}.dfa-settings-status{min-height:1.5em;margin-top:8px;font-size:.76rem;padding:0 4px;overflow-wrap:anywhere}.dfa-settings-status[data-error="true"]{color:var(--dsw-alias-danger,#b42318)}
1140
+ button[data-dfa-nav-icon="file-actions"]>svg{display:none}button[data-dfa-nav-icon="file-actions"]::before{content:"";width:16px;height:16px;flex:none;background:currentColor;mask: url("data:image/svg+xml,${encodeURIComponent(iconSvg('fileActions').replace('<svg ', '<svg xmlns="http://www.w3.org/2000/svg" '))}") center/contain no-repeat}
1141
+ @media(max-width:500px){.dfa-settings-header{gap:10px;margin-bottom:18px}.dfa-settings h2{font-size:1rem}.dfa-settings-row{padding:13px 14px;gap:10px;align-items:flex-start;flex-wrap:wrap}.dfa-settings-copy{flex-basis:140px}.dfa-settings select{min-width:0;max-width:100%;font-size:.78rem}.dfa-settings-card-head,.dfa-settings-app{padding-left:14px;padding-right:14px}.dfa-settings-app-info{gap:8px}.dfa-settings-app-info strong{min-width:48px}.dfa-settings-cache{align-items:flex-start;flex-wrap:wrap}.dfa-settings-cache>div{flex-basis:180px;flex-grow:1}}
1142
+
990
1143
  .dfa-toast{position:fixed;left:50%;bottom:32px;transform:translateX(-50%);z-index:2147483002;
991
1144
  padding:7px 14px;border-radius:8px;font-size:.875rem;line-height:1.4;pointer-events:none;
992
1145
  background-color:var(--dfa-floor,Canvas);
@@ -1247,7 +1400,7 @@ const factory = () => {
1247
1400
  function candidateFromEvent(event, doc) {
1248
1401
  const target = event.target
1249
1402
  if (!target || !target.closest) return null
1250
- if (isEditable(target)) return null
1403
+ if (isEditable(target) || target.closest('.dfa-settings')) return null
1251
1404
 
1252
1405
  // A resource address owns its Session and path, even when its child has a
1253
1406
  // different title. Do not reinterpret it against the selected chat.
@@ -1358,6 +1511,264 @@ const factory = () => {
1358
1511
  return node
1359
1512
  }
1360
1513
 
1514
+ function mountSettings(root, controller, t) {
1515
+ const c = t.settings
1516
+ let message = '', failed = false
1517
+ let dropdown = null
1518
+ const closingDropdowns = new Map()
1519
+ const glyph = name => makeNode('span', { html: iconSvg(name) }).firstChild
1520
+ const reducedMotion = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
1521
+ const closeDropdown = (animate = true) => {
1522
+ const current = dropdown
1523
+ if (!current) return
1524
+ dropdown = null
1525
+ current.stop()
1526
+ current.trigger.setAttribute('aria-expanded', 'false')
1527
+ current.trigger.removeAttribute('aria-activedescendant')
1528
+ const { popup } = current
1529
+ popup.setAttribute('aria-hidden', 'true')
1530
+ popup.removeAttribute('id')
1531
+ for (const row of popup.children) row.removeAttribute('id')
1532
+ popup.inert = true
1533
+ popup.dataset.state = 'closing'
1534
+ const style = getComputedStyle(popup)
1535
+ const from = { opacity: style.opacity, transform: style.transform }
1536
+ current.animation?.cancel()
1537
+ if (!animate || reducedMotion() || !popup.animate) { popup.remove(); return }
1538
+ const animation = popup.animate([from, { opacity: 0, transform: `translateY(${current.above ? 4 : -4}px) scale(.98)` }], { duration: 120, easing: 'ease-in', fill: 'forwards' })
1539
+ closingDropdowns.set(popup, animation)
1540
+ const finish = () => { popup.remove(); closingDropdowns.delete(popup) }
1541
+ animation.finished.then(finish, finish)
1542
+ }
1543
+ const openDropdown = (trigger, options, value, choose, initialIndex) => {
1544
+ closeDropdown()
1545
+ const popup = makeNode('div', { id: trigger.id + '-options', class: 'dfa-select-menu', role: 'listbox', 'aria-labelledby': trigger.id + '-label', 'data-state': 'opening' })
1546
+ const style = getComputedStyle(trigger)
1547
+ for (const name of ['--dfa-accent', '--dfa-line']) popup.style.setProperty(name, style.getPropertyValue(name))
1548
+ popup.style.color = style.color
1549
+ popup.style.fontFamily = style.fontFamily
1550
+ const floor = menuFloor()
1551
+ // The list overlays other controls, so keep their labels from showing through.
1552
+ if (floor) popup.style.setProperty('--dfa-select-floor', floor.replace(', 0.94)', ', 1)'))
1553
+ let active = initialIndex ?? Math.max(0, options.findIndex(([key]) => key === value))
1554
+ const current = { popup, trigger, above: false, animation: null, stop: () => {} }
1555
+ dropdown = current
1556
+ const rows = options.map(([key, text], index) => {
1557
+ const row = makeNode('div', { id: popup.id + '-' + index, class: 'dfa-select-option', role: 'option', 'aria-selected': String(key === value), 'data-value': key }, [makeNode('span', { text }), glyph('check')])
1558
+ row.addEventListener('pointermove', () => highlight(index))
1559
+ row.addEventListener('pointerdown', event => event.preventDefault())
1560
+ row.addEventListener('click', () => select(index))
1561
+ popup.appendChild(row)
1562
+ return row
1563
+ })
1564
+ const highlight = index => {
1565
+ active = (index + rows.length) % rows.length
1566
+ rows.forEach((row, i) => { row.dataset.active = String(i === active) })
1567
+ trigger.setAttribute('aria-activedescendant', rows[active].id)
1568
+ rows[active].scrollIntoView({ block: 'nearest' })
1569
+ }
1570
+ const select = index => { closeDropdown(); choose(options[index][0]) }
1571
+ const position = () => {
1572
+ const rect = trigger.getBoundingClientRect(), gap = 6, margin = 8
1573
+ popup.style.minWidth = Math.min(Math.max(rect.width, 164), innerWidth - margin * 2) + 'px'
1574
+ popup.style.maxWidth = Math.max(0, innerWidth - margin * 2) + 'px'
1575
+ popup.style.maxHeight = Math.max(0, innerHeight - margin * 2) + 'px'
1576
+ const height = popup.getBoundingClientRect().height
1577
+ const below = innerHeight - rect.bottom - gap - margin, above = rect.top - gap - margin
1578
+ current.above = below < height && above > below
1579
+ popup.style.maxHeight = Math.max(0, current.above ? above : below) + 'px'
1580
+ const box = popup.getBoundingClientRect()
1581
+ popup.style.left = Math.max(margin, Math.min(rect.right - box.width, innerWidth - margin - box.width)) + 'px'
1582
+ popup.style.top = Math.max(margin, current.above ? rect.top - gap - box.height : rect.bottom + gap) + 'px'
1583
+ popup.style.transformOrigin = current.above ? 'bottom right' : 'top right'
1584
+ }
1585
+ let search = '', searchedAt = 0
1586
+ const keydown = event => {
1587
+ if (event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return
1588
+ if (event.key === 'Tab') { closeDropdown(); return }
1589
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End', 'Enter', ' ', 'Escape'].includes(event.key)) {
1590
+ event.preventDefault(); event.stopPropagation()
1591
+ if (event.key === 'Escape') closeDropdown()
1592
+ else if (event.key === 'Enter' || event.key === ' ') select(active)
1593
+ else highlight(event.key === 'Home' ? 0 : event.key === 'End' ? rows.length - 1 : active + (event.key === 'ArrowDown' ? 1 : -1))
1594
+ } else if (event.key.length === 1) {
1595
+ event.preventDefault(); event.stopPropagation()
1596
+ const now = Date.now(); search = (now - searchedAt < 700 ? search : '') + event.key.toLocaleLowerCase(); searchedAt = now
1597
+ const start = (active + 1) % rows.length
1598
+ const index = options.findIndex((_, offset) => options[(start + offset) % rows.length][1].toLocaleLowerCase().startsWith(search))
1599
+ if (index >= 0) highlight(start + index)
1600
+ }
1601
+ }
1602
+ const outside = event => { if (!trigger.contains(event.target) && !popup.contains(event.target)) closeDropdown() }
1603
+ const scroll = event => { if (!popup.contains(event.target)) closeDropdown() }
1604
+ document.addEventListener('pointerdown', outside, true)
1605
+ document.addEventListener('scroll', scroll, true)
1606
+ window.addEventListener('resize', position)
1607
+ trigger.addEventListener('keydown', keydown)
1608
+ current.stop = () => {
1609
+ document.removeEventListener('pointerdown', outside, true); document.removeEventListener('scroll', scroll, true)
1610
+ window.removeEventListener('resize', position); trigger.removeEventListener('keydown', keydown)
1611
+ }
1612
+ document.body.appendChild(popup)
1613
+ position()
1614
+ trigger.setAttribute('aria-expanded', 'true')
1615
+ highlight(active)
1616
+ if (!reducedMotion() && popup.animate) {
1617
+ current.animation = popup.animate([{ opacity: 0, transform: `translateY(${current.above ? 4 : -4}px) scale(.98)` }, { opacity: 1, transform: 'none' }], { duration: 160, easing: 'cubic-bezier(.2,.7,.3,1)' })
1618
+ current.animation.finished.then(() => { if (dropdown === current) popup.dataset.state = 'open' }, () => {})
1619
+ } else popup.dataset.state = 'open'
1620
+ }
1621
+ const button = (label, key, action, disabled = false, accessibleLabel = label, ghost = false) => {
1622
+ const node = makeNode('button', { type: 'button', text: label, 'data-dfa-setting': key, disabled,
1623
+ 'aria-label': accessibleLabel, class: ghost ? 'dfa-settings-ghost' : undefined })
1624
+ node.addEventListener('click', () => commit(action, key))
1625
+ return node
1626
+ }
1627
+ const commit = (action, key) => {
1628
+ const ok = action()
1629
+ failed = !ok
1630
+ message = ok ? (key === 'cache' ? c.cacheCleared : key === 'defaults' ? c.reset : key.startsWith('app') ? c.removed : c.saved) : c.failed
1631
+ render()
1632
+ }
1633
+ function render() {
1634
+ closeDropdown()
1635
+ const focused = document.activeElement?.getAttribute('data-dfa-setting')
1636
+ const value = controller.config.get()
1637
+ const page = makeNode('div', { class: 'dfa-settings', 'data-dfa-settings': '1' })
1638
+ const floor = menuFloor()
1639
+ if (floor) page.style.setProperty('--dfa-settings-floor', floor)
1640
+ page.appendChild(makeNode('header', { class: 'dfa-settings-header' }, [
1641
+ makeNode('span', { class: 'dfa-settings-mark', 'aria-hidden': 'true' }, [glyph('fileActions')]),
1642
+ makeNode('div', {}, [makeNode('h2', { text: c.title }), makeNode('p', { class: 'dfa-settings-intro', text: c.intro })]),
1643
+ ]))
1644
+ const display = makeNode('section', { class: 'dfa-settings-card' }, [
1645
+ makeNode('div', { class: 'dfa-settings-card-head' }, [
1646
+ makeNode('h3', {}, [glyph('sliders'), c.display]),
1647
+ button(c.resetShort, 'defaults', () => controller.reset(), false, c.defaults, true),
1648
+ ]),
1649
+ ])
1650
+ for (const [key, label, help, options] of [
1651
+ ['menuMode', c.menuMode, c.menuHint, [['full', c.full], ['compact', c.compact]]],
1652
+ ['contextLines', c.contextLines, c.contextHint, [4, 8, 16].map(n => [String(n), c.contextOption.replace('{count}', n)])],
1653
+ ]) {
1654
+ const id = `dfa-setting-${key}`
1655
+ const selected = String(value[key])
1656
+ const select = makeNode('button', { type: 'button', id, class: 'dfa-select-trigger', role: 'combobox', 'aria-haspopup': 'listbox', 'aria-expanded': 'false', 'aria-controls': id + '-options', 'aria-labelledby': id + '-label', 'data-dfa-setting': key, 'data-value': selected, 'aria-describedby': id + '-help' }, [makeNode('span', { text: options.find(([option]) => option === selected)[1] }), glyph('chevron')])
1657
+ const open = index => openDropdown(select, options, selected, option => commit(() => controller.update({ [key]: key === 'contextLines' ? Number(option) : option }), key), index)
1658
+ select.addEventListener('click', () => { if (dropdown?.trigger === select) closeDropdown(); else open() })
1659
+ select.addEventListener('keydown', event => {
1660
+ if (dropdown?.trigger === select || event.isComposing || event.altKey || event.ctrlKey || event.metaKey) return
1661
+ if (['ArrowDown', 'ArrowUp', 'Enter', ' ', 'Home', 'End'].includes(event.key)) {
1662
+ event.preventDefault(); event.stopPropagation()
1663
+ open(event.key === 'Home' ? 0 : event.key === 'End' ? options.length - 1 : undefined)
1664
+ }
1665
+ })
1666
+ display.appendChild(makeNode('div', { class: 'dfa-settings-row' }, [
1667
+ makeNode('div', { class: 'dfa-settings-copy' }, [makeNode('label', { id: id + '-label', for: id, text: label }), makeNode('p', { id: id + '-help', class: 'dfa-settings-note', text: help })]), select,
1668
+ ]))
1669
+ }
1670
+ const rows = controller.apps.list()
1671
+ const apps = makeNode('section', { class: 'dfa-settings-card' }, [
1672
+ makeNode('div', { class: 'dfa-settings-card-head' }, [
1673
+ makeNode('h3', {}, [glyph('apps'), c.apps, makeNode('span', { class: 'dfa-settings-count', text: rows.length })]),
1674
+ button(c.clearShort, 'apps', () => controller.apps.clear(), !rows.length, c.clearApps, true),
1675
+ ]),
1676
+ ])
1677
+ if (!rows.length) apps.appendChild(makeNode('div', { class: 'dfa-settings-empty' }, [glyph('apps'), makeNode('div', {}, [
1678
+ makeNode('strong', { text: c.noApps }), makeNode('p', { class: 'dfa-settings-note', text: c.appsHelp }),
1679
+ ])]))
1680
+ for (const row of rows) {
1681
+ const name = controller.applicationName(row.appId)
1682
+ const typeLabel = row.type === '[no extension]' ? c.noExtension : row.type.startsWith('.') ? row.type : '.' + row.type
1683
+ apps.appendChild(makeNode('div', { class: 'dfa-settings-app' }, [
1684
+ makeNode('div', { class: 'dfa-settings-app-info' }, [makeNode('strong', { text: typeLabel }), makeNode('span', { text: name })]),
1685
+ button(c.removeShort, `app:${row.type}`, () => controller.apps.remove(row.type), false, `${c.remove}: ${typeLabel}`, true),
1686
+ ]))
1687
+ }
1688
+ const cacheButton = button(c.clearCache, 'cache', () => controller.clearCache())
1689
+ cacheButton.prepend(glyph('refresh'))
1690
+ const cache = makeNode('section', { class: 'dfa-settings-cache' }, [
1691
+ makeNode('div', {}, [makeNode('div', { class: 'dfa-settings-cache-title' }, [glyph('refresh'), c.cache,
1692
+ makeNode('span', { class: 'dfa-settings-count', text: controller.cacheCount(), 'aria-label': c.cacheCount.replace('{count}', controller.cacheCount()) })]),
1693
+ makeNode('p', { class: 'dfa-settings-note', text: c.cacheHint }),
1694
+ ]), cacheButton,
1695
+ ])
1696
+ page.appendChild(display); page.appendChild(apps); page.appendChild(cache)
1697
+ const project = makeNode('section', { class: 'dfa-project', 'aria-label': c.project }, [
1698
+ makeNode('h3', { text: c.project }), makeNode('p', { class: 'dfa-settings-note', text: c.projectHint }),
1699
+ ])
1700
+ const links = makeNode('div', { class: 'dfa-project-links' })
1701
+ for (const [label, href, icon] of [
1702
+ [c.github, 'https://github.com/jidekaixin2dian/dsh-file-actions', 'code'],
1703
+ [c.feedback, 'https://github.com/jidekaixin2dian/dsh-file-actions/issues/new', 'feedback'],
1704
+ ]) links.appendChild(makeNode('a', { class: 'dfa-project-link', href, target: '_blank', rel: 'noopener noreferrer' }, [glyph(icon), label]))
1705
+ project.appendChild(links); page.appendChild(project)
1706
+ page.appendChild(makeNode('footer', { class: 'dfa-settings-footer' }, [glyph('info'), c.scopeShort]))
1707
+ page.appendChild(makeNode('div', { class: 'dfa-settings-status', role: failed ? 'alert' : 'status', 'data-error': failed, text: message, 'aria-live': 'polite' }))
1708
+ root.replaceChildren(page)
1709
+ if (focused) [...root.querySelectorAll('[data-dfa-setting]')].find(node => node.getAttribute('data-dfa-setting') === focused)?.focus({ preventScroll: true })
1710
+ }
1711
+ render()
1712
+ const stop = controller.subscribe(render)
1713
+ return () => {
1714
+ stop(); closeDropdown(false)
1715
+ for (const [popup, animation] of closingDropdowns) { animation.cancel(); popup.remove() }
1716
+ closingDropdowns.clear(); root.replaceChildren()
1717
+ }
1718
+ }
1719
+
1720
+ // rc.5 draws a fixed gear for third-party sections. Decorate only our unique,
1721
+ // exact-label row; body observation is shallow and nav observation stays local.
1722
+ function settingsNavigationIcon(slots) {
1723
+ if (typeof document === 'undefined' || typeof MutationObserver === 'undefined') return () => {}
1724
+ const navObserver = new MutationObserver(() => sync())
1725
+ const sync = () => {
1726
+ navObserver.disconnect()
1727
+ const labels = new Set([ZH.settings.nav, EN.settings.nav])
1728
+ const rows = slots.entries?.('settings.section') || []
1729
+ const own = rows.find(row => row.options?.id === 'file-actions')
1730
+ const unique = !rows.length || own && rows.filter(row => {
1731
+ const label = row.options?.label
1732
+ return labels.has(typeof label === 'function' ? label() : label)
1733
+ }).length === 1
1734
+ for (const nav of document.querySelectorAll('[role="dialog"] nav')) {
1735
+ for (const node of nav.querySelectorAll('button')) {
1736
+ const label = node.querySelector(':scope > span')?.textContent?.trim()
1737
+ if (unique && labels.has(label)) node.setAttribute('data-dfa-nav-icon', 'file-actions')
1738
+ else if (node.getAttribute('data-dfa-nav-icon') === 'file-actions') node.removeAttribute('data-dfa-nav-icon')
1739
+ }
1740
+ navObserver.observe(nav, { childList: true, subtree: true, characterData: true })
1741
+ }
1742
+ }
1743
+ const bodyObserver = new MutationObserver(sync)
1744
+ bodyObserver.observe(document.body, { childList: true })
1745
+ const off = slots.subscribe?.('settings.section', sync)
1746
+ sync()
1747
+ return () => {
1748
+ bodyObserver.disconnect(); navObserver.disconnect()
1749
+ if (typeof off === 'function') off()
1750
+ for (const node of document.querySelectorAll('[data-dfa-nav-icon="file-actions"]')) node.removeAttribute('data-dfa-nav-icon')
1751
+ }
1752
+ }
1753
+
1754
+ function registerSettings(ctx, controller) {
1755
+ const slots = ctx.get?.('slots')
1756
+ if (!slots || typeof require !== 'function') return () => {}
1757
+ const React = require('react')
1758
+ function SettingsPage() {
1759
+ const root = React.useRef(null)
1760
+ const language = detectLanguage(ctx)
1761
+ React.useLayoutEffect(() => mountSettings(root.current, controller, messages(language)), [language])
1762
+ return React.createElement('div', { ref: root })
1763
+ }
1764
+ const dispose = slots.inject('settings.section', () => slots.register({
1765
+ name: 'settings.section', id: 'file-actions', order: 19,
1766
+ label: () => messages(detectLanguage(ctx)).settings.nav,
1767
+ }, SettingsPage))
1768
+ const stopIcon = settingsNavigationIcon(slots)
1769
+ return () => { stopIcon(); if (typeof dispose === 'function') dispose() }
1770
+ }
1771
+
1361
1772
  class FileMenu {
1362
1773
  constructor(options) {
1363
1774
  this.model = options.model
@@ -1542,6 +1953,71 @@ const factory = () => {
1542
1953
  return wrap
1543
1954
  }
1544
1955
 
1956
+ async openReference(target, context) {
1957
+ this.closeReference()
1958
+ this.closeSubmenu()
1959
+ const overlay = makeNode('div', { class: 'dfa-reference-overlay' })
1960
+ const panel = makeNode('section', { class: 'dfa-reference', role: 'dialog', 'aria-modal': 'true', 'aria-label': this.t.referencePreview })
1961
+ const floor = menuFloor()
1962
+ if (floor) overlay.style.setProperty('--dfa-floor', floor.replace(/, 0\.94\)$/, ', 1)'))
1963
+ overlay.style.color = getComputedStyle(this.root).color
1964
+ const info = makeNode('div', { class: 'dfa-reference-info' }, [
1965
+ makeNode('div', { class: 'dfa-reference-title', text: this.t.referencePreview }),
1966
+ makeNode('div', { class: 'dfa-reference-path', text: `${target.displayPath || target.absolutePath} · ${formatLocation(target, this.t)}` }),
1967
+ ])
1968
+ const close = makeNode('button', { type: 'button', text: this.t.closePreview })
1969
+ const body = makeNode('div', { class: 'dfa-reference-body', tabindex: '0', 'aria-label': this.t.referencePreview })
1970
+ body.appendChild(makeNode('div', { class: 'dfa-reference-status', text: this.t.referenceLoading, role: 'status' }))
1971
+ const hint = makeNode('div', { class: 'dfa-reference-hint' })
1972
+ const copy = makeNode('button', { type: 'button', text: this.t.copySource, disabled: true })
1973
+ const open = makeNode('button', { type: 'button', text: this.t.open })
1974
+ panel.appendChild(makeNode('div', { class: 'dfa-reference-head' }, [info, close]))
1975
+ panel.appendChild(body)
1976
+ panel.appendChild(makeNode('div', { class: 'dfa-reference-footer' }, [hint, makeNode('div', { class: 'dfa-reference-actions' }, [open, copy])]))
1977
+ overlay.appendChild(panel)
1978
+ this.referencePreview = overlay
1979
+ const current = () => !this.closed && this.referencePreview === overlay && (!context.isCurrent || context.isCurrent())
1980
+ const readContext = { ...context, isCurrent: current, confirmMessage: this.t.confirmOutsidePreview }
1981
+ close.addEventListener('click', () => this.closeReference())
1982
+ overlay.addEventListener('click', event => { if (event.target === overlay) this.closeReference() })
1983
+ open.addEventListener('click', () => { if (current()) void dispatch({ action: 'open' }, target, readContext) })
1984
+ copy.addEventListener('click', async () => {
1985
+ if (!current() || copy.disabled) return
1986
+ copy.disabled = true
1987
+ // Re-read with the original version: never copy a file newer than the preview.
1988
+ await dispatch({ action: 'copySource' }, target, { ...readContext, outsideConfirmed: true })
1989
+ if (current()) copy.disabled = false
1990
+ })
1991
+ document.body.appendChild(overlay)
1992
+ close.focus({ preventScroll: true })
1993
+ const result = await readTextTarget(target, readContext)
1994
+ if (!current()) return
1995
+ if (!result) { this.closeReference(); return }
1996
+ const preview = result && !result.error ? referenceContext(result.text, target, context.contextLines) : null
1997
+ body.replaceChildren()
1998
+ if (!preview) {
1999
+ body.appendChild(makeNode('div', { class: 'dfa-reference-status', role: 'status', text: result?.error || this.t.invalidLines }))
2000
+ return
2001
+ }
2002
+ // A later copy must match the read even if the original carrier had no version.
2003
+ if (result.version !== undefined) target = { ...target, version: result.version }
2004
+ for (const row of preview.rows) body.appendChild(makeNode('div', { class: 'dfa-reference-row', 'data-selected': row.selected }, [
2005
+ makeNode('span', { class: 'dfa-reference-number', text: row.line, 'aria-hidden': 'true' }),
2006
+ makeNode('span', { class: 'dfa-reference-code', text: row.text || ' ' }),
2007
+ ]))
2008
+ hint.textContent = this.t.referenceWindow.replace('{from}', preview.from).replace('{to}', preview.to).replace('{total}', preview.total)
2009
+ + (preview.clipped ? ` · ${this.t.previewClipped}` : '')
2010
+ copy.disabled = false
2011
+ body.querySelector('[data-selected="true"]')?.scrollIntoView({ block: 'center' })
2012
+ }
2013
+
2014
+ closeReference() {
2015
+ if (!this.referencePreview) return
2016
+ this.referencePreview.remove()
2017
+ this.referencePreview = null
2018
+ try { this.root?.focus({ preventScroll: true }) } catch { /* menu unmounted */ }
2019
+ }
2020
+
1545
2021
  /** Show the same preview at full size; the menu stays open behind it. */
1546
2022
  openPreview() {
1547
2023
  if (!this.thumbUrl || this.lightbox) return
@@ -1931,6 +2407,16 @@ const factory = () => {
1931
2407
  handleKeyDown(event) {
1932
2408
  if (!this.root) return
1933
2409
  if (event.isComposing || event.keyCode === 229) return
2410
+ if (this.referencePreview) {
2411
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.closeReference() }
2412
+ if (event.key === 'Tab') {
2413
+ const controls = [...this.referencePreview.querySelectorAll('button:not(:disabled), [tabindex="0"]')]
2414
+ const at = controls.indexOf(document.activeElement)
2415
+ event.preventDefault()
2416
+ controls[(at + (event.shiftKey ? -1 : 1) + controls.length) % controls.length]?.focus()
2417
+ }
2418
+ return
2419
+ }
1934
2420
  // The lightbox is modal: Escape dismisses it. Every other key is left alone so
1935
2421
  // the video transport (space, arrows) keeps working.
1936
2422
  if (this.lightbox) {
@@ -2037,7 +2523,7 @@ const factory = () => {
2037
2523
  // menu when it opens. Only a real window blur may close it.
2038
2524
  if (event.type === 'blur' && event.target !== window) return
2039
2525
  const target = event.target
2040
- if (target instanceof Node && this.lightbox?.contains(target)) return
2526
+ if (target instanceof Node && (this.lightbox?.contains(target) || this.referencePreview?.contains(target))) return
2041
2527
  if (target instanceof Node && (this.root.contains(target) || (this.submenu && this.submenu.contains(target)))) return
2042
2528
  this.close()
2043
2529
  }
@@ -2083,6 +2569,7 @@ const factory = () => {
2083
2569
  close() {
2084
2570
  if (this.closed) return
2085
2571
  this.closed = true
2572
+ this.closeReference()
2086
2573
  this.closeLightbox()
2087
2574
  this.closeSubmenu()
2088
2575
  document.removeEventListener('keydown', this.handleKeyDown, true)
@@ -2245,10 +2732,40 @@ const factory = () => {
2245
2732
 
2246
2733
  const MAX_COPY_BYTES = 2 * 1024 * 1024
2247
2734
 
2735
+ async function readTextTarget(target, context) {
2736
+ const { bridge, t, sessionId } = context
2737
+ const current = () => !context.isCurrent || context.isCurrent()
2738
+ if (!current()) return null
2739
+ if (typeof target.bytes === 'number' && target.bytes > MAX_COPY_BYTES) return { error: t.tooLarge }
2740
+ if (target.outsideWorkspace === true && !context.outsideConfirmed) {
2741
+ const ask = context.confirm || (typeof confirm === 'function' ? confirm : null)
2742
+ try {
2743
+ if (!ask) return { error: t.confirmUnavailable }
2744
+ if (await ask((context.confirmMessage || t.confirmOutsideCopy).replace('{path}', target.absolutePath)) !== true) return null
2745
+ } catch { return { error: t.confirmUnavailable } }
2746
+ }
2747
+ if (!current()) return null
2748
+ let result
2749
+ try { result = await boundedCall(() => bridge.readBytes(sessionId, target.absolutePath, { range: { offset: 0, length: MAX_COPY_BYTES } })) }
2750
+ catch { if (current()) return { error: t.readFailed }; return null }
2751
+ if (!current()) return null
2752
+ if (!result || !(result.data instanceof Uint8Array)) return { error: t.readFailed }
2753
+ if (result.data.byteLength > MAX_COPY_BYTES || result.eof === false) return { error: t.tooLarge }
2754
+ if (target.version !== undefined && result.version !== target.version) {
2755
+ context.onFileChanged?.()
2756
+ return { error: t.fileChanged }
2757
+ }
2758
+ let text
2759
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(result.data) }
2760
+ catch { return { error: t.invalidEncoding } }
2761
+ if (text.includes('\u0000')) return { error: t.binary }
2762
+ return { text, version: result.version }
2763
+ }
2764
+
2248
2765
  async function dispatch(item, target, context) {
2249
2766
  const { bridge, t, sessionId } = context
2250
2767
  const path = target.absolutePath
2251
- const copyingText = item.action === 'copyContents' || item.action === 'copyLines'
2768
+ const copyingText = item.action === 'copyContents' || item.action === 'copyLines' || item.action === 'copySource'
2252
2769
  if (item.action === 'openLink' || item.action === 'copyLink' || item.action === 'copyLinkText') {
2253
2770
  if (item.action === 'openLink') {
2254
2771
  if (!openExternal(target.link)) toast(t.openFailed, { error: true })
@@ -2330,48 +2847,16 @@ const factory = () => {
2330
2847
  return
2331
2848
  }
2332
2849
  if (copyingText) {
2333
- // Chat text can plant absolute paths from outside the workspace; require
2334
- // an explicit confirmation before its bytes reach the clipboard.
2335
- if (target.outsideWorkspace === true) {
2336
- const ask = context.confirm || (typeof confirm === 'function' ? confirm : null)
2337
- let allowed = false
2338
- try {
2339
- if (!ask) throw new Error('Confirmation unavailable')
2340
- allowed = await ask(t.confirmOutsideCopy.replace('{path}', path)) === true
2341
- } catch { toast(t.confirmUnavailable, { error: true }) }
2342
- if (!allowed) return
2343
- }
2344
- const options = { range: { offset: 0, length: MAX_COPY_BYTES } }
2345
- const result = await bridge.readBytes(sessionId, path, options)
2346
- if (!result || !(result.data instanceof Uint8Array)) {
2347
- toast(t.readFailed, { error: true })
2348
- return
2349
- }
2350
- const bytes = result.data
2351
- if (bytes.byteLength > MAX_COPY_BYTES || result.eof === false) {
2352
- toast(t.tooLarge, { error: true })
2353
- return
2354
- }
2355
- let text = ''
2356
- try {
2357
- text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
2358
- } catch {
2359
- toast(t.invalidEncoding, { error: true })
2360
- return
2361
- }
2362
- if (text.includes('\u0000')) {
2363
- toast(t.binary, { error: true })
2364
- return
2365
- }
2366
- if (item.action === 'copyLines') {
2367
- text = referencedText(text, target)
2368
- if (text === null) {
2369
- toast(t.invalidLines, { error: true })
2370
- return
2371
- }
2372
- }
2850
+ const result = await readTextTarget(target, context)
2851
+ if (!result) return
2852
+ if (result.error) { toast(result.error, { error: true }); return }
2853
+ let text = result.text
2854
+ if (item.action === 'copyLines') text = referencedText(text, target)
2855
+ if (item.action === 'copySource') text = sourceExcerpt(text, target)
2856
+ if (text === null) { toast(t.invalidLines, { error: true }); return }
2857
+ if (context.isCurrent && !context.isCurrent()) return
2373
2858
  const ok = await copyText(text)
2374
- toast(ok ? (item.action === 'copyLines' ? t.copiedLines : t.copiedContents) : t.copyFailed, { error: !ok })
2859
+ toast(ok ? (item.action === 'copyLines' ? t.copiedLines : item.action === 'copySource' ? t.copiedSource : t.copiedContents) : t.copyFailed, { error: !ok })
2375
2860
  }
2376
2861
  }
2377
2862
 
@@ -2454,7 +2939,10 @@ const factory = () => {
2454
2939
  }
2455
2940
  let preferenceStorage
2456
2941
  try { preferenceStorage = window.localStorage } catch { /* private storage may be disabled */ }
2457
- const preferences = applicationPreferences(preferenceStorage)
2942
+ const settingsViews = new Set()
2943
+ const notifySettings = () => { for (const render of settingsViews) render() }
2944
+ const config = clientPreferences(preferenceStorage)
2945
+ const preferences = applicationPreferences(preferenceStorage, notifySettings)
2458
2946
 
2459
2947
  async function openAt(candidate, x, y, keyboard) {
2460
2948
  if (disposed) return
@@ -2465,7 +2953,7 @@ const factory = () => {
2465
2953
  if (candidate.link) {
2466
2954
  const text = String(candidate.element?.textContent || '').trim().slice(0, 512)
2467
2955
  const target = { link: candidate.link, text }
2468
- handle = new FileMenu({ model: buildLinkMenuModel({ url: candidate.link, text, t }),
2956
+ handle = new FileMenu({ model: buildLinkMenuModel({ url: candidate.link, text, t, menuMode: config.get().menuMode }),
2469
2957
  x, y, keyboard, anchor: candidate.element, t,
2470
2958
  onClose: () => { if (menu === handle) menu = null },
2471
2959
  onPick: (item) => { void dispatch(item, target, { bridge, t }) },
@@ -2476,12 +2964,15 @@ const factory = () => {
2476
2964
  }
2477
2965
  const { session, located, path } = locate(candidate)
2478
2966
  const modelInput = { absolutePath: path, displayPath: located.path, apps: [], appsState: 'loading',
2479
- location: located, reference: candidate.reference || candidate.path, t }
2967
+ location: located, reference: candidate.reference || candidate.path, t, menuMode: config.get().menuMode }
2480
2968
  let target
2969
+ const activeSessionId = bridge.activeSession()?.id
2970
+ const isCurrent = () => !disposed && attempt === generation && bridge.activeSession()?.id === activeSessionId
2481
2971
  handle = new FileMenu({ model: buildStatusModel(path, t.checking, t),
2482
2972
  x, y, keyboard, anchor: candidate.element, t,
2483
2973
  onClose: () => { if (menu === handle) menu = null },
2484
2974
  onPick: (item) => {
2975
+ if (item.action === 'referencePreview' && target) { void handle.openReference(target, { bridge, t, sessionId: session.id, isCurrent, contextLines: config.get().contextLines, onFileChanged: () => probeCache.delete(locate(candidate).key) }); return }
2485
2976
  if (item.action === 'retry') { void openAt(candidate, x, y, keyboard); return }
2486
2977
  if (item.action === 'preferApp') {
2487
2978
  const appId = preferences.get(path) === item.appId ? '' : item.appId
@@ -2490,6 +2981,7 @@ const factory = () => {
2490
2981
  return
2491
2982
  }
2492
2983
  if (target) void dispatch(item, target, { bridge, t, sessionId: session.id,
2984
+ onFileChanged: () => probeCache.delete(locate(candidate).key),
2493
2985
  validateApplication: async (file, id) => {
2494
2986
  const cached = appsCache.get(extname(file).toLowerCase())
2495
2987
  const result = await applicationsFor(file, cached?.needsValidation === true)
@@ -2520,7 +3012,7 @@ const factory = () => {
2520
3012
  bytes: probe.bytes, outsideWorkspace: !isInside(session.cwd, probe.absolutePath),
2521
3013
  cwd: session.cwd, preferredId: preferences.get(probe.absolutePath) })
2522
3014
  target = { absolutePath: probe.absolutePath, displayPath,
2523
- isDir: probe.isDir, line: located.line, endLine: located.endLine, column: located.column, bytes: probe.bytes,
3015
+ isDir: probe.isDir, version: probe.version, line: located.line, endLine: located.endLine, column: located.column, bytes: probe.bytes,
2524
3016
  reference: candidate.reference || candidate.path, outsideWorkspace: !isInside(session.cwd, probe.absolutePath) }
2525
3017
  handle.setModel(buildMenuModel(modelInput))
2526
3018
  if (!probe.isDir) void enrich(handle, modelInput)
@@ -2549,6 +3041,7 @@ const factory = () => {
2549
3041
  const APPS_STORE_RECORD_MAX_CHARS = 48 * 1024
2550
3042
  const appsCache = new Map()
2551
3043
  const appsPending = new Map()
3044
+ let appsEpoch = 0
2552
3045
  let storeTimer = 0
2553
3046
 
2554
3047
  function readAppsStore() {
@@ -2611,20 +3104,22 @@ const factory = () => {
2611
3104
  if (!refresh && cached && Date.now() - cached.at < cached.ttl) return Promise.resolve(cached.result)
2612
3105
  const pending = appsPending.get(key)
2613
3106
  if (pending) return pending
3107
+ const epoch = appsEpoch
2614
3108
  const request = bridge.applications(path).then((result) => {
2615
- if (disposed) return result
3109
+ if (disposed || epoch !== appsEpoch) return result
2616
3110
  // A successful empty answer is cached briefly: the OS may still be
2617
3111
  // registering a handler, but it is not worth a walk on every click.
2618
3112
  if (result.state === 'ready') {
2619
3113
  if (appsCache.size >= 64) appsCache.delete(appsCache.keys().next().value)
2620
3114
  appsCache.set(key, { result, at: Date.now(), ttl: result.apps.length ? APPS_TTL_MS : APPS_EMPTY_TTL_MS })
2621
3115
  scheduleStoreWrite()
3116
+ notifySettings()
2622
3117
  } else if (refresh) {
2623
3118
  appsCache.delete(key)
2624
3119
  scheduleStoreWrite()
2625
3120
  }
2626
3121
  return result
2627
- }).finally(() => appsPending.delete(key))
3122
+ }).finally(() => { if (appsPending.get(key) === request) appsPending.delete(key) })
2628
3123
  appsPending.set(key, request)
2629
3124
  return request
2630
3125
  }
@@ -2767,6 +3262,7 @@ const factory = () => {
2767
3262
  let shiftEvent = null
2768
3263
 
2769
3264
  function onContextMenu(event) {
3265
+ if (event.target?.closest?.('.dfa-reference-overlay')) return
2770
3266
  if (event.defaultPrevented) return
2771
3267
  if (event.shiftKey) {
2772
3268
  shiftEvent = event
@@ -2804,7 +3300,7 @@ const factory = () => {
2804
3300
  }
2805
3301
 
2806
3302
  function onWarm(event) {
2807
- if (event.shiftKey || event.target?.closest?.(`[${MENU_ATTR}]`)) return
3303
+ if (event.shiftKey || event.target?.closest?.(`[${MENU_ATTR}], .dfa-reference-overlay, .dfa-settings`)) return
2808
3304
  const rect = event.target?.getBoundingClientRect?.()
2809
3305
  warmCandidate(candidateFromEvent({ target: event.target,
2810
3306
  clientX: event.clientX ?? rect?.left, clientY: event.clientY ?? rect?.top }, document))
@@ -2812,7 +3308,7 @@ const factory = () => {
2812
3308
 
2813
3309
  function onPointerDown(event) {
2814
3310
  const target = event.target
2815
- if (target && target.closest && target.closest(`[${MENU_ATTR}], .dfa-lightbox`)) return
3311
+ if (target && target.closest && target.closest(`[${MENU_ATTR}], .dfa-lightbox, .dfa-reference-overlay`)) return
2816
3312
  closeMenu()
2817
3313
  }
2818
3314
 
@@ -2820,7 +3316,7 @@ const factory = () => {
2820
3316
  // Scrolling the menu's own long lists (or the "open with" submenu) is not
2821
3317
  // the page moving; closing on it would make those lists unusable.
2822
3318
  const target = event && event.target
2823
- if (target && target.closest && target.closest(`[${MENU_ATTR}]`)) return
3319
+ if (target && target.closest && target.closest(`[${MENU_ATTR}], .dfa-reference-overlay`)) return
2824
3320
  if (!menu) return
2825
3321
  if (event && event.type === 'scroll') {
2826
3322
  // One read per frame: a scroll burst fires many events, and each follow()
@@ -2848,8 +3344,41 @@ const factory = () => {
2848
3344
  // A DOM marker survives page-side identity quirks and gives the e2e driver
2849
3345
  // one stable readiness signal instead of guessing at boot timing.
2850
3346
  document.documentElement.setAttribute('data-dfa-ready', '1')
3347
+ let sessionId = bridge.activeSession()?.id
3348
+ let unsubscribe
3349
+ try { unsubscribe = ctx.sessions?.list?.subscribe?.(() => {
3350
+ const next = bridge.activeSession()?.id
3351
+ if (next !== sessionId) { sessionId = next; closeMenu() }
3352
+ }) } catch { /* optional observable */ }
3353
+ const settingsController = {
3354
+ config, apps: preferences,
3355
+ subscribe(render) { settingsViews.add(render); return () => settingsViews.delete(render) },
3356
+ update(patch) { const ok = config.set(patch); if (ok) { closeMenu(); notifySettings() } return ok },
3357
+ reset() { const ok = config.reset(); if (ok) { closeMenu(); notifySettings() } return ok },
3358
+ applicationName(id) {
3359
+ for (const { result } of appsCache.values()) { const app = result.apps.find(app => app.id === id); if (app) return app.name }
3360
+ return basename(id) || id
3361
+ },
3362
+ cacheCount: () => appsCache.size,
3363
+ clearCache() {
3364
+ try { preferenceStorage.removeItem(APPS_STORE_KEY) } catch { return false }
3365
+ if (storeTimer) { clearTimeout(storeTimer); storeTimer = 0 }
3366
+ appsEpoch++; appsCache.clear(); appsPending.clear(); closeMenu(); notifySettings()
3367
+ return true
3368
+ },
3369
+ }
3370
+ const disposeSettings = registerSettings(ctx, settingsController)
3371
+ const onStorage = event => {
3372
+ if (event.key === CLIENT_SETTINGS_KEY || event.key === 'dsh-file-actions.preferred-apps.v1' || event.key === null) { closeMenu(); notifySettings() }
3373
+ if (event.key === APPS_STORE_KEY || event.key === null) { appsEpoch++; appsCache.clear(); appsPending.clear(); notifySettings() }
3374
+ }
3375
+ window.addEventListener('storage', onStorage)
2851
3376
  const cleanup = () => {
2852
3377
  disposed = true
3378
+ disposeSettings()
3379
+ settingsViews.clear()
3380
+ window.removeEventListener('storage', onStorage)
3381
+ if (typeof unsubscribe === 'function') unsubscribe()
2853
3382
  document.documentElement.removeAttribute('data-dfa-ready')
2854
3383
  document.removeEventListener('contextmenu', onContextMenu, true)
2855
3384
  window.removeEventListener('contextmenu', onContextMenuFallback)
@@ -2925,12 +3454,19 @@ const factory = () => {
2925
3454
  pickEditor,
2926
3455
  orderApplications,
2927
3456
  applicationPreferences,
3457
+ clientPreferences,
3458
+ visibleMenuSections,
3459
+ mountSettings,
3460
+ registerSettings,
2928
3461
  buildStatusModel,
2929
3462
  FileMenu,
2930
3463
  buildMenuModel,
2931
3464
  buildLinkMenuModel,
2932
3465
  formatLocation,
2933
3466
  referencedText,
3467
+ referenceContext,
3468
+ sourceExcerpt,
3469
+ readTextTarget,
2934
3470
  linkFromHref,
2935
3471
  candidateFromEvent,
2936
3472
  createBridge,
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "File Actions",
4
- "description": "Right-click files and links to open, reveal, copy or save; choose preferred applications by file type."
3
+ "title": "File Actions · 文件与链接操作",
4
+ "description": "Act on files and links in chat: open, reveal, preview or save; choose preferred apps, inspect reference context and copy excerpts with their source."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "文件与链接操作",
4
- "description": "右键文件和链接,直接打开、定位、复制或另存;支持按文件类型选择首选应用。"
3
+ "title": "文件与链接操作 · File Actions",
4
+ "description": "右键聊天文件与链接,打开、定位、预览或另存;支持首选应用、引用上下文预览及带来源复制。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jidekaixin2dian/dsh-file-actions",
3
- "version": "0.1.18",
4
- "description": "File and link actions for DeepSeek Harness: open, choose applications, reveal, copy paths or contents, and save files from the chat.",
3
+ "version": "0.1.19",
4
+ "description": "Act on files and links in chat: open, reveal, preview or save; choose preferred apps, inspect reference context and copy excerpts with their source.",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
7
7
  "main": "lib/index.js",
@@ -55,7 +55,8 @@
55
55
  "inject": [
56
56
  "@deepseek-ai/dsh-api-remotes",
57
57
  "@deepseek-ai/dsh-api-session-controller",
58
- "@deepseek-ai/dsh-api-workspace-files"
58
+ "@deepseek-ai/dsh-api-workspace-files",
59
+ "@deepseek-ai/dsh-client-ui-settings"
59
60
  ]
60
61
  }
61
62
  },