merge feat/212-editor-git-gutter into dev(#212 编辑器变更提示:code 视图行号槽着色 + 左侧细色条 + hover blame,一个布尔开关,样式极简)
This commit is contained in:
commit
bce22cfaf1
37 files changed
+1376
-5
No files matched your search
@@ -525,7 +525,7 @@ interface FileViewerProps {
|
||||
|
||||
> **head 字节从哪来**:第一次匹配(纯扩展名)没有 head。`fsRead` 策略读取后若文件为二进制,host 的 `fs.read` 响应会带 `head` 字段(base64,前 4KB,`src/index.ts` 的 `READ_HEAD_LIMIT`),编辑器会用它对 `detect` viewer **重匹配一次**——所以 detect 型 viewer 的实际触发场景是"扩展名匹配落空/二进制文件"。文本文件的 detect 嗅探不在内置流程内(用 `exts` 或 `custom` 策略替代)。
|
||||
|
||||
> **内置 viewer**(不可重复注册,全部 3 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体 src 重写走 `/sidebar/file`;≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存)。
|
||||
> **内置 viewer**(不可重复注册,全部 3 个):markdown(0, fsRead;内嵌 HTML 支持:DOMPurify 白名单消毒、`<details>` 跨段嵌套、本地媒体 src 重写走 `/sidebar/file`;≥3 标题时浮动目录大纲。实现 `markdown-html.ts` / `MarkdownHtml.tsx` / `md-toc.tsx`,[设计文档](plans/2026-08-24-markdown-html-toc-design.md)) / html(0, fsRead, 沙箱 iframe 预览 + `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` 两个宿主没有的逃生门) / code(-100, catch-all, fsRead, **可编辑** CodeMirror + 保存 + 未提交变更提示(行号着色 / 左侧细色条 / hover blame,一个 `editorGitGutter` 开关,[设计文档](plans/2026-10-05-editor-git-gutter.md)))。
|
||||
> code 是兜底 viewer:任何其他 viewer 未认领的文件都会落到 code(CodeMirror 文本编辑);二进制文件经 head 重匹配找不到 sniffer,落到编辑器的下载面板。外部 viewer 注册同扩展名 + 更高 priority 即可覆盖内置的那三个。
|
||||
>
|
||||
> ⚠️ **让给宿主的格式(重要,影响你的 viewer 能不能被调用)**:DSH 0.1.7 的 `ui-sidebar-documentpreview` 自带 code / excel(xlsx,xls,csv,tsv) / office(宿主侧转 PDF)/ pdf / image / html / markdown / text 预览,并带缩放与**按目录自动刷新**——本插件原有的 image / pdf / binary-download 三个 viewer 描述符因此删除。更重要的是**路由**:插件的 `editor` 类型在 `canOpen` 里对下列扩展名一律返回 false(`src/client/native/index.ts` 的 `HOST_OWNED_EXTS`),把地址让给内置 `text` 档,**根本不会进入本插件的 `matchFileViewer`**:
|
||||
@@ -954,7 +954,7 @@ ctx.effect(() =>
|
||||
)
|
||||
```
|
||||
|
||||
> ⚠️ **`toggles` 的 key 必须是本插件 `PrefsSchema` 的字段**(`PrefsSchema` 已并入本插件 Loader 行的 `Config`;内置键:`autoOpenSubagent` / `autoOpenJobs` / `tasksViewMode` / `mobileNoAutoOpen` / `mobileDefaultTree` / `agentOpenTools` / `editorExplorer` / `explorerExclude` / `titleBarScheme` / `titleBarPresetId` / `customCss` / `titleBarCompat` / `titleBarStripPx` / `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` / `tabsEnabled` / `viewersEnabled` / `pluginSettings`;**已删除**:`workspaceFence`(v0.23.0,围栏整体移除,见 §8.1)/ `agentTerminalTools` / `terminalShell` / `terminalShellArgs` / `terminalFontFamily` / `terminalFontSize` / `bottomPanelAutoTerminal` / `browserNoSandbox` / `browserAllowedLoopback` / 三个按协议分流的旧外链接管键)。**v0.12.0 起设置 seam 已开放**:你自己的设置走 `pluginToggles`(声明式行)或 `render`(自定义面板),值持久化在 `pluginSettings[id]`——不再需要本插件的 schema 字段,也不再被 seam 丢弃。值须 JSON 可序列化(行控件只产出 string/number/boolean;自定义面板自行负责)。
|
||||
> ⚠️ **`toggles` 的 key 必须是本插件 `PrefsSchema` 的字段**(`PrefsSchema` 已并入本插件 Loader 行的 `Config`;内置键:`autoOpenSubagent` / `autoOpenJobs` / `tasksViewMode` / `mobileNoAutoOpen` / `mobileDefaultTree` / `agentOpenTools` / `editorExplorer` / `editorGitGutter` / `explorerExclude` / `titleBarScheme` / `titleBarPresetId` / `customCss` / `titleBarCompat` / `titleBarStripPx` / `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` / `tabsEnabled` / `viewersEnabled` / `pluginSettings`;**已删除**:`workspaceFence`(v0.23.0,围栏整体移除,见 §8.1)/ `agentTerminalTools` / `terminalShell` / `terminalShellArgs` / `terminalFontFamily` / `terminalFontSize` / `bottomPanelAutoTerminal` / `browserNoSandbox` / `browserAllowedLoopback` / 三个按协议分流的旧外链接管键)。**v0.12.0 起设置 seam 已开放**:你自己的设置走 `pluginToggles`(声明式行)或 `render`(自定义面板),值持久化在 `pluginSettings[id]`——不再需要本插件的 schema 字段,也不再被 seam 丢弃。值须 JSON 可序列化(行控件只产出 string/number/boolean;自定义面板自行负责)。
|
||||
|
||||
### 8.2 宿主设置表单(DSH 0.1.7+:`SettingsForms`)
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# 编辑器未提交变更提示:行号着色 + 左侧细色条 + hover blame(issue #212)
|
||||
|
||||
> 分支 `feat/212-editor-git-gutter`(基于 `dev`,DSH 0.2.0-rc.1 线)。
|
||||
> 口径按维护者定调:**和 VS Code 一样,左侧颜色小提示即可,样式不要浮夸** ——
|
||||
> 不做行尾常驻作者 widget、不做彩色徽章、不做动画、不做渐变色。
|
||||
|
||||
## 落地内容
|
||||
|
||||
`code` 视图(可编辑 CodeMirror)多出三层提示,全部挂在**一个**布尔设置
|
||||
`editorGitGutter`(默认开)下:
|
||||
|
||||
1. **行号槽着色**:新增 / 修改 / 删除行的行号取对应状态色;
|
||||
2. **左侧细色条**:行号左边 2px 竖条,位置与 VS Code 一致(颜色同上);
|
||||
3. **hover blame**:鼠标停在某行时按需取该行 blame,纯文本 tooltip 显示
|
||||
`作者 · 时间` + 提交摘要。
|
||||
|
||||
## 设计要点
|
||||
|
||||
- **行映射只有一个来源**:`useGitStatus`(文件树着色用的同一个共享 store,全插件
|
||||
只有一个 `git status` 轮询器)决定「这个文件有没有改动 / 是不是未跟踪」;行级类型
|
||||
来自 `git diff --no-color -U3` 的输出,经**既有**统一 diff 引擎
|
||||
(`src/client/diff/rows.ts` 的 `parseUnifiedDiff` + `unifiedSegments`)折成
|
||||
`行号 → add | mod | del`。上下文行不产生任何标记;重写行由引擎的配对规则合成一个
|
||||
`mod`(不会在上一行多出一根删除条);未配对的删除锚在**缺口上一行**(文件头删除锚
|
||||
第 1 行)——与 VS Code 的位置一致。
|
||||
- **新路由 `git.diff-head`**:`git diff HEAD -- <path>` 一次给出「已暂存 + 未暂存」的
|
||||
整份未提交变更。既有的 `git.diff` 两个 side 各自只看一半(一个文件部分暂存时,
|
||||
gutter 会漏掉另一半),所以这里没有拼两次 diff、也没有新增第三个「status」概念。
|
||||
HEAD 尚未出生(`git init` 后有暂存无提交)时 `diff HEAD` 必然失败,此时回退
|
||||
`diff --cached`(索引对空树,同一问题的未出生 HEAD 形态)。
|
||||
- **未跟踪文件不走 diff**:`git diff` 任何一侧都不会列出未跟踪文件,客户端按状态
|
||||
store 的 `untracked` 音调把整篇标成新增(与 VS Code 一致)。
|
||||
- **blame 只在 hover 时按需请求**:`src/git.ts` 新增 `blame()`(`git blame --porcelain -L`),
|
||||
每次只取被 hover 的那一行;结果按 `sessionId + path + line` 记忆化(同一行反复 hover
|
||||
不再打 git),滚动不触发请求,整篇文件永不预取;该文件变更集重算时清掉它的 memo。
|
||||
未跟踪文件、非 git 仓库、路径不存在、命令失败**一律 catch 成空数组**(route 也是空
|
||||
列表),tooltip 什么都不显示,绝不能影响编辑面。
|
||||
- **只给 `code`**:`gitGutterExtensions(null)` 返回**空扩展数组**(不是「装了但没画」
|
||||
——DOM 里连 gutter 包裹元素都不存在),markdown / html 视图与关闭开关后都是这一支。
|
||||
开关用 `useSyncExternalStore` 读(与 EditorHost 读 `editorExplorer` 同一 seam),
|
||||
经 CodeMirror `Compartment` 原地重配:关掉即拆掉扩展,文档 / 撤销栈 / 滚动位置不丢。
|
||||
- **取色复用既有 tone 口径**:新增 / 未跟踪取 `--dsw-alias-state-success-primary`、
|
||||
修改取 `--dsw-alias-state-warn-primary`、删除取 `--dsw-alias-state-error-primary`,
|
||||
与文件树 `explorerGitName[data-git-tone]` 完全一致;样式写在
|
||||
`src/client/sidebar.module.css`(class 名以 `elementClass` / marker DOM 交回
|
||||
CodeMirror),因此 `tests/theme.spec.ts` 的皮肤契约照常扫描。
|
||||
- **一个开关,不是四个**:作者 / hash / 日期 / 摘要没有独立开关;行尾 widget、
|
||||
徽章、动画、渐变都不做。
|
||||
|
||||
## 实施偏差
|
||||
|
||||
- **`useGitStatus` 补了 `useSyncExternalStore` 的第三个参数(server snapshot)**:
|
||||
`TextEditor` 会被 markdown 预览用例整份 SSR 成字符串,缺这一参数 React 直接抛
|
||||
`Missing getServerSnapshot`。slot 版本号两侧同为 0,行为不变。
|
||||
- **`tests/text-editor-conflict.spec.tsx` 的 api mock 改为保留真实 api 对象**
|
||||
(原先只替换出 `{ fsWrite }`):`code` 视图现在也会读共享 git status store,
|
||||
部分 mock 会让 store 拿到 `api.gitStatus is not a function`。这是 mock 的既有形状
|
||||
问题,不是产品回归。
|
||||
- **`tests/prefs.spec.ts` 三个「整份 prefs 深比较」补上 `editorGitGutter: true`**:
|
||||
新增 schema 字段的既有约定动作。
|
||||
|
||||
## 验收
|
||||
|
||||
- `tests/editor-git-gutter.spec.tsx`(17 例):行映射(新增 / 重写 / 纯删除 / 头删 /
|
||||
混合 hunk / mode-only / 空 patch / 未跟踪整篇)、扩展门(关=空数组、类名落到真实
|
||||
样式表、空 state 上 dispatch 不炸)、blame memo(同一行只问一次、失败回 null、
|
||||
变更集重算清 memo)、`TextEditor` 真实 DOM(code 有 gutter / 关掉没有 / markdown
|
||||
没有 / 中途关开关就地拆除)。
|
||||
- `tests/git-blame.spec.ts`(14 例):真实 git 产出上的 porcelain 解析(含未提交
|
||||
全零 hash 行与「同一 commit 第二行只给 header」的缩写形态)、`blame()` 四条失败
|
||||
路径(未跟踪 / 非仓库 / 路径不存在 / 命令失败)、`diffHead()` 的「部分暂存给全量」、
|
||||
未出生 HEAD 回退、未跟踪不出现,以及**真实 git 输出 → 行类型**的端到端映射。
|
||||
@@ -13,7 +13,7 @@
|
||||
* the FileViewerProps toolbar callbacks so the host's path-input header
|
||||
* renders the controls instead.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import clsx from 'clsx'
|
||||
import { EditorState } from '@codemirror/state'
|
||||
@@ -22,6 +22,12 @@ import { defaultKeymap, history, historyKeymap } from '@codemirror/commands'
|
||||
import { openSearchPanel } from '@codemirror/search'
|
||||
import { IconCheckOutlineRegular, IconSearchOutlineRegular, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { markdownTextProps } from './markdown-labels.tsx'
|
||||
import {
|
||||
applyGitLineKinds,
|
||||
CmGitGutterCompartment,
|
||||
useEditorGitGutter,
|
||||
type GitGutterHost,
|
||||
} from './editor-git-gutter.ts'
|
||||
import { api, htmlUrl, SidebarApiError } from './api.ts'
|
||||
import { hostTransportBase } from './desktop-env.ts'
|
||||
import { markdownPreviewSource } from './markdown-frontmatter.ts'
|
||||
@@ -75,6 +81,9 @@ export function TextEditor(props: FileViewerProps) {
|
||||
/** The search-phrases compartment of the current view (reconfigured on a
|
||||
* language switch — the panel copy is baked into the EditorState). */
|
||||
const searchPhrasesRef = useRef<CmSearchPhrases | null>(null)
|
||||
/** The uncommitted-change gutter compartment (issue #212; reconfigured on a
|
||||
* setting flip instead of rebuilding the view). */
|
||||
const gitCompRef = useRef<CmGitGutterCompartment | null>(null)
|
||||
/** The effective UI language (DSH locale id + better-locale override id).
|
||||
* Read during render and subscribed below: the tab-cell memo only
|
||||
* compares the DSH locale revision, so a better-locale override switch
|
||||
@@ -86,6 +95,30 @@ export function TextEditor(props: FileViewerProps) {
|
||||
const mdRef = useRef<HTMLDivElement>(null)
|
||||
const markdown = viewerId === 'markdown'
|
||||
const html = viewerId === 'html'
|
||||
/** The uncommitted-change gutter (issue #212): the `code` viewer only,
|
||||
* gated by ONE boolean setting (on by default). Nothing else — no
|
||||
* end-of-line author widget, no badges, no animation. Read reactively
|
||||
* (same seam as the host's editorExplorer read) so flipping the switch
|
||||
* reconfigures the live view in place instead of waiting for a reopen. */
|
||||
const gitGutterPref = useSyncExternalStore(
|
||||
useCallback((callback: () => void) => props.store.subscribe(callback), [props.store]),
|
||||
useCallback(() => props.store.getSnapshot().prefs.editorGitGutter !== false, [props.store]),
|
||||
// Server snapshot: this component is rendered to a string by the markdown
|
||||
// preview specs. The value only feeds effects (the extensions are built
|
||||
// client-side), so the store answers on both sides alike.
|
||||
useCallback(() => props.store.getSnapshot().prefs.editorGitGutter !== false, [props.store]),
|
||||
)
|
||||
const gitGutterEnabled = viewerId === 'code' && gitGutterPref
|
||||
/** Bumped by every save: the uncommitted diff moved while the file's git
|
||||
* status entry (which only tracks its XY code) did not. */
|
||||
const [gitRevision, setGitRevision] = useState(0)
|
||||
/** The view-side identity of the gutter's git source (stable across the
|
||||
* scope object's per-render identity churn). */
|
||||
const gitHost = useMemo<GitGutterHost>(
|
||||
() => ({ scope: { sessionId: scope.sessionId, cwd: scope.cwd, repoRoot: scope.repoRoot }, path }),
|
||||
[scope.sessionId, scope.cwd, scope.repoRoot, path],
|
||||
)
|
||||
const gitKinds = useEditorGitGutter({ enabled: gitGutterEnabled, scope, path, content, revision: gitRevision })
|
||||
/** Preview scroll position across the preview<->edit toggle. The preview
|
||||
* container re-mounts on every mode switch and its scrollTop lives on that
|
||||
* element, so capture it on scroll and restore after each remount. Seeded
|
||||
@@ -177,10 +210,17 @@ export function TextEditor(props: FileViewerProps) {
|
||||
themeCompRef.current = themeComp
|
||||
const searchPhrases = new CmSearchPhrases()
|
||||
searchPhrasesRef.current = searchPhrases
|
||||
const gitComp = new CmGitGutterCompartment()
|
||||
gitCompRef.current = gitComp
|
||||
const state = EditorState.create({
|
||||
doc: content,
|
||||
extensions: [
|
||||
CodeMirrorView.lineWrapping,
|
||||
// The change bar sits BEFORE the line numbers (VS Code's own order):
|
||||
// a thin colored bar at the far left, the number tinted beside it.
|
||||
// The compartment carries all of it (hover blame included), so the
|
||||
// setting can flip it in place below.
|
||||
gitComp.of(gitGutterEnabled ? gitHost : null),
|
||||
lineNumbers(),
|
||||
history(),
|
||||
EditorState.tabSize.of(2),
|
||||
@@ -266,6 +306,7 @@ export function TextEditor(props: FileViewerProps) {
|
||||
viewRef.current = null
|
||||
themeCompRef.current = null
|
||||
searchPhrasesRef.current = null
|
||||
gitCompRef.current = null
|
||||
}
|
||||
// The keymap's save() reads live refs; scope/path are stable for a
|
||||
// tab's lifetime, and the dark flip is handled by the reconfigure
|
||||
@@ -312,6 +353,26 @@ export function TextEditor(props: FileViewerProps) {
|
||||
view.dispatch({ effects: searchPhrases.reconfigure() })
|
||||
}, [localeSig])
|
||||
|
||||
// The uncommitted-change gutter follows the setting in place: the
|
||||
// compartment swap installs (or removes) the decoration extensions and the
|
||||
// hover blame without rebuilding the view — the document, history and
|
||||
// scroll survive, exactly like the theme and search flips above.
|
||||
useEffect(() => {
|
||||
const view = viewRef.current
|
||||
const gitComp = gitCompRef.current
|
||||
if (view === null || gitComp === null) return
|
||||
view.dispatch({ effects: gitComp.reconfigure(gitGutterEnabled ? gitHost : null) })
|
||||
}, [gitGutterEnabled, gitHost])
|
||||
|
||||
// Push the line map into the live view. `content` / `truncated` re-run this
|
||||
// after the view was rebuilt for a new file, and `gitGutterEnabled` after a
|
||||
// re-install (a reconfigured state field starts empty).
|
||||
useEffect(() => {
|
||||
const view = viewRef.current
|
||||
if (view === null) return
|
||||
applyGitLineKinds(view, gitKinds)
|
||||
}, [gitKinds, gitGutterEnabled, content, path, truncated])
|
||||
|
||||
// The editor may have been display:none while previewing; re-measure when
|
||||
// it becomes visible again (CodeMirror sizes itself on reveal). A mode
|
||||
// flip also invalidates any anchored selection popup. When entering edit
|
||||
@@ -396,6 +457,10 @@ export function TextEditor(props: FileViewerProps) {
|
||||
setDirty(false)
|
||||
setConflict(false)
|
||||
setSaveState('saved')
|
||||
// The saved bytes are a new revision of the uncommitted diff: re-read
|
||||
// the change set (the file's XY status code usually stays the same, so
|
||||
// the status store alone would never wake the gutter up again).
|
||||
setGitRevision(value => value + 1)
|
||||
}).catch((error: unknown) => {
|
||||
savingRef.current = false
|
||||
if (error instanceof SidebarApiError && error.code === 'fs-conflict') {
|
||||
|
||||
@@ -139,6 +139,19 @@ export interface GitLogEntry {
|
||||
refs: string
|
||||
}
|
||||
|
||||
/** One `git blame --porcelain` row (the editor's hover blame). */
|
||||
export interface GitBlameLine {
|
||||
/** 1-based line number in the file as it exists in the worktree. */
|
||||
line: number
|
||||
/** The blamed commit (40 hex chars; all zeros for an uncommitted line). */
|
||||
hash: string
|
||||
author: string
|
||||
/** ISO 8601 author time carrying the author's own UTC offset. */
|
||||
date: string
|
||||
/** The commit's subject line. */
|
||||
summary: string
|
||||
}
|
||||
|
||||
/** Text read result. `mtimeMs` is the save route's conflict baseline. */
|
||||
export interface FsTextResult { kind: 'text'; content: string; truncated: boolean; mtimeMs?: number }
|
||||
/** Binary read result (no content; images load through the media route).
|
||||
@@ -435,6 +448,17 @@ export const api = {
|
||||
* reads both sides' full contents through this. */
|
||||
gitShow: (scope: SessionScope, rev: string, path: string, worktree?: string, signal?: AbortSignal) =>
|
||||
call<{ content: string | null }>('git.show', gitPayload(scope, worktree, { rev, path }), signal),
|
||||
/** ONE file's whole uncommitted change (worktree against HEAD, staged and
|
||||
* unstaged in one patch). The editor's change gutter maps this onto the
|
||||
* buffer's line numbers; untracked files are marked from the status store
|
||||
* instead, because no diff side ever lists them. */
|
||||
gitDiffHead: (scope: SessionScope, path: string, worktree?: string, signal?: AbortSignal) =>
|
||||
call<{ diff: string }>('git.diff-head', gitPayload(scope, worktree, { path }), signal),
|
||||
/** Blame ONE line range (`git blame --porcelain -L`). Never throws: every
|
||||
* failure (untracked file, not a repository, command failure) answers with
|
||||
* an empty list. Called on hover only — a file is never prefetched. */
|
||||
gitBlame: (scope: SessionScope, path: string, startLine: number, endLine: number, worktree?: string, signal?: AbortSignal) =>
|
||||
call<{ lines: GitBlameLine[] }>('git.blame', gitPayload(scope, worktree, { path, startLine, endLine }), signal),
|
||||
/** The session's file-tool events for the changes tab's session lens: the
|
||||
* `tool/call` + `tool/result` rows past `afterSeq` (0 = whole window),
|
||||
* capped to the recent window host-side. The client runtime exposes no
|
||||
|
||||
@@ -88,6 +88,16 @@ export function builtinViewers(): readonly FileViewerDescriptor[] {
|
||||
exts: [],
|
||||
priority: -100,
|
||||
fetchStrategy: 'fsRead',
|
||||
// Declarative settings: ONE switch for the whole uncommitted-change
|
||||
// gutter (line tint + left bar + hover blame). Deliberately no
|
||||
// per-part switches.
|
||||
settings: {
|
||||
toggles: [{
|
||||
key: 'editorGitGutter',
|
||||
title: () => t('settingsEditorGitGutterTitle'),
|
||||
desc: () => t('settingsEditorGitGutterDesc'),
|
||||
}],
|
||||
},
|
||||
component: (props) => <LazyTextEditor {...props} />,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
/**
|
||||
* The editor's uncommitted-change gutter (issue #212), kept deliberately
|
||||
* close to what VS Code shows and nothing more: the line-number gutter tints
|
||||
* a changed line's number, a 2px bar sits at the left edge of the numbers
|
||||
* (added / modified / deleted), and hovering a line reveals that line's
|
||||
* blame as a PLAIN TEXT tooltip (author · time, then the commit summary). No
|
||||
* end-of-line author widget, no badges, no animation, no gradient.
|
||||
*
|
||||
* Three rules shape the wiring:
|
||||
* - ONE git status source. `useGitStatus` (the plugin's shared store, also
|
||||
* behind the file tree's ink) decides WHICH files changed and whether a
|
||||
* file is untracked; this module never starts a second poller. The line
|
||||
* map itself comes from `git diff --no-color` through the existing
|
||||
* unified-diff parser (`diff/rows.ts`), so a line's class is git's own
|
||||
* answer — context rows are never marked.
|
||||
* - Only the `code` viewer carries the extensions (the caller passes null
|
||||
* for every other viewer and when the user switched the feature off), and
|
||||
* the bar/number colors come from the same `--dsw-alias-state-*` tones the
|
||||
* file tree already uses for its rows.
|
||||
* - Blame is fetched ON HOVER for the hovered line only, memoized per
|
||||
* session + path + line. Scrolling never re-requests a range, a file is
|
||||
* never prefetched, and the memo is dropped when the file's change set is
|
||||
* recomputed (a new diff means new commits may be involved).
|
||||
*/
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { RangeSet, Compartment, StateEffect, StateField, type EditorState, type Extension } from '@codemirror/state'
|
||||
import { EditorView, GutterMarker, gutter, gutterLineClass, hoverTooltip, type Tooltip } from '@codemirror/view'
|
||||
import { api, type GitBlameLine, type SessionScope } from './api.ts'
|
||||
import { parseUnifiedDiff, unifiedSegments } from './diff/rows.ts'
|
||||
import { relativeTime } from './locales.ts'
|
||||
import { useGitStatus } from './ui/git-status.ts'
|
||||
import css from './sidebar.module.css'
|
||||
|
||||
/** The change class of one line, as the gutter paints it. */
|
||||
export type GitLineKind = 'add' | 'mod' | 'del'
|
||||
|
||||
/** The line-number ink of each class (the file tree's own tone mapping:
|
||||
* added/untracked green, modified amber, deleted red). */
|
||||
export const GIT_LINE_CLASS: Record<GitLineKind, string> = {
|
||||
add: css.editorGitAdd ?? '',
|
||||
mod: css.editorGitMod ?? '',
|
||||
del: css.editorGitDel ?? '',
|
||||
}
|
||||
|
||||
/** The class of the thin left bar's filled element, per class. */
|
||||
const GIT_BAR_CLASS: Record<GitLineKind, string> = {
|
||||
add: css.editorGitBarAdd ?? '',
|
||||
mod: css.editorGitBarMod ?? '',
|
||||
del: css.editorGitBarDel ?? '',
|
||||
}
|
||||
|
||||
/** Structural class of the bar gutter (also the DOM hook tests query). */
|
||||
export const GIT_BAR_GUTTER_CLASS = 'cm-dsh-git-gutter'
|
||||
|
||||
const EMPTY_KINDS: ReadonlyMap<number, GitLineKind> = new Map()
|
||||
|
||||
/**
|
||||
* The changed NEW-side lines of a `git diff` patch, as line number → class.
|
||||
*
|
||||
* The patch is read through the shared unified-diff engine, so the pairing
|
||||
* rules (a rewritten line is one `mod`, not a `del` plus an `add`) are the
|
||||
* same ones every other diff surface in the plugin renders. Deletions have no
|
||||
* line of their own on the new side: each unpaired deletion is anchored to
|
||||
* the line ABOVE the gap — where VS Code draws it too — and to line 1 when
|
||||
* the deleted run sits at the head of the file. Context rows contribute
|
||||
* nothing, and the anchor never overwrites a line an addition or a rewrite
|
||||
* already claimed.
|
||||
* @param diffText - `git diff --no-color` output (unified, `-U3`).
|
||||
* @returns the changed lines (1-based, worktree side).
|
||||
*/
|
||||
export function gitLineKinds(diffText: string): Map<number, GitLineKind> {
|
||||
const kinds = new Map<number, GitLineKind>()
|
||||
if (diffText === '') return kinds
|
||||
for (const file of parseUnifiedDiff(diffText).files) {
|
||||
for (const segment of unifiedSegments(file)) {
|
||||
if (segment.kind !== 'hunk') continue
|
||||
let lastNew = 0
|
||||
for (const row of segment.rows) {
|
||||
if (row.newLine !== undefined) lastNew = row.newLine
|
||||
if (row.kind === 'add' && row.newLine !== undefined) {
|
||||
kinds.set(row.newLine, 'add')
|
||||
} else if (row.kind === 'mod' && row.newLine !== undefined) {
|
||||
// The deleted half of a rewritten pair carries no new-side line;
|
||||
// only the addition half maps onto the buffer.
|
||||
kinds.set(row.newLine, 'mod')
|
||||
} else if (row.kind === 'del') {
|
||||
const anchor = Math.max(1, lastNew)
|
||||
if (!kinds.has(anchor)) kinds.set(anchor, 'del')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return kinds
|
||||
}
|
||||
|
||||
/** Every line of a file that git does not track yet is an addition. */
|
||||
export function addedLineKinds(lineCount: number): Map<number, GitLineKind> {
|
||||
const kinds = new Map<number, GitLineKind>()
|
||||
for (let line = 1; line <= lineCount; line += 1) kinds.set(line, 'add')
|
||||
return kinds
|
||||
}
|
||||
|
||||
// ── CodeMirror plumbing ─────────────────────────────────────────────────────
|
||||
|
||||
const setGitLineKinds = StateEffect.define<ReadonlyMap<number, GitLineKind>>()
|
||||
|
||||
/** The changed lines of the open buffer (empty while the file is clean). */
|
||||
const gitLineKindsField = StateField.define<ReadonlyMap<number, GitLineKind>>({
|
||||
create: () => EMPTY_KINDS,
|
||||
update: (value, transaction) => {
|
||||
let next = value
|
||||
for (const effect of transaction.effects) {
|
||||
if (effect.is(setGitLineKinds)) next = effect.value
|
||||
}
|
||||
return next
|
||||
},
|
||||
})
|
||||
|
||||
/** Marker carrying the line-number ink; `gutterLineClass` copies its class
|
||||
* onto every gutter element of that line (numbers included). */
|
||||
class GitNumberMarker extends GutterMarker {
|
||||
readonly elementClass: string
|
||||
|
||||
constructor(kind: GitLineKind) {
|
||||
super()
|
||||
this.elementClass = GIT_LINE_CLASS[kind]
|
||||
}
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof GitNumberMarker && other.elementClass === this.elementClass
|
||||
}
|
||||
}
|
||||
|
||||
/** Marker carrying the thin bar element drawn inside the bar gutter. */
|
||||
class GitBarMarker extends GutterMarker {
|
||||
constructor(private readonly kind: GitLineKind | null) {
|
||||
super()
|
||||
}
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof GitBarMarker && other.kind === this.kind
|
||||
}
|
||||
|
||||
override toDOM(): Node {
|
||||
const bar = document.createElement('div')
|
||||
bar.className = this.kind === null
|
||||
? css.editorGitBarSpacer ?? ''
|
||||
: `${css.editorGitBar ?? ''} ${GIT_BAR_CLASS[this.kind]}`
|
||||
return bar
|
||||
}
|
||||
}
|
||||
|
||||
/** The per-line classes of the line-number gutter (one entry per line). */
|
||||
const gitLineNumberClasses = gutterLineClass.compute([gitLineKindsField], (state: EditorState) => {
|
||||
const ranges = []
|
||||
for (const [line, kind] of state.field(gitLineKindsField)) {
|
||||
if (line < 1 || line > state.doc.lines) continue
|
||||
ranges.push(new GitNumberMarker(kind).range(state.doc.line(line).from))
|
||||
}
|
||||
return RangeSet.of(ranges, true)
|
||||
})
|
||||
|
||||
/** The bar gutter, ordered BEFORE the line numbers by the caller. */
|
||||
const gitBarGutter = gutter({
|
||||
class: `${css.editorGitBarGutter ?? ''} ${GIT_BAR_GUTTER_CLASS}`,
|
||||
lineMarker: (view, block) => {
|
||||
const kind = view.state.field(gitLineKindsField).get(view.state.doc.lineAt(block.from).number)
|
||||
return kind === undefined ? null : new GitBarMarker(kind)
|
||||
},
|
||||
lineMarkerChange: update => update.startState.field(gitLineKindsField) !== update.state.field(gitLineKindsField),
|
||||
// A hidden spacer keeps the bar's 2px reserved while the file is clean, so
|
||||
// the numbers never shift sideways when a change appears.
|
||||
initialSpacer: () => new GitBarMarker(null),
|
||||
})
|
||||
|
||||
/**
|
||||
* The blame tooltip's surface. CodeMirror's own base theme paints
|
||||
* `.cm-tooltip` light gray (`#f5f5f5` over `#bbb`, hardcoded), which on a dark
|
||||
* skin is a light box holding light label text — so the one tooltip this
|
||||
* editor can show takes its surface from the same tokens as every other
|
||||
* layer.
|
||||
*/
|
||||
const gitGutterTheme = EditorView.theme({
|
||||
'.cm-tooltip': {
|
||||
border: '1px solid var(--dsw-alias-border-l2)',
|
||||
backgroundColor: 'var(--dsw-alias-bg-layer-2)',
|
||||
color: 'var(--dsw-alias-label-primary)',
|
||||
},
|
||||
})
|
||||
|
||||
/** What the blame tooltip needs from the view that owns it. */
|
||||
export interface GitGutterHost {
|
||||
scope: SessionScope
|
||||
path: string
|
||||
}
|
||||
|
||||
/** Build the gutter extensions for one view (empty = the feature is off). */
|
||||
export function gitGutterExtensions(host: GitGutterHost | null): Extension[] {
|
||||
if (host === null) return []
|
||||
const source = (view: EditorView, pos: number): Promise<Tooltip | null> => {
|
||||
const line = view.state.doc.lineAt(pos)
|
||||
return loadBlameLine(host.scope, host.path, line.number).then((entry) => {
|
||||
if (entry === null) return null
|
||||
return {
|
||||
pos: line.from,
|
||||
end: line.to,
|
||||
above: true,
|
||||
create: () => ({ dom: blameTooltipDom(entry) }),
|
||||
}
|
||||
})
|
||||
}
|
||||
return [gitLineKindsField, gitLineNumberClasses, gitBarGutter, gitGutterTheme, hoverTooltip(source, { hoverTime: 250 })]
|
||||
}
|
||||
|
||||
/** Push one change set into a live view (no-op without the extensions). */
|
||||
export function applyGitLineKinds(view: EditorView, kinds: ReadonlyMap<number, GitLineKind>): void {
|
||||
if (!view.state.field(gitLineKindsField, false)) return
|
||||
view.dispatch({ effects: setGitLineKinds.of(kinds) })
|
||||
}
|
||||
|
||||
/**
|
||||
* A Compartment holding the gutter extensions. Created once per editor view;
|
||||
* flipping the setting dispatches `reconfigure(host)`, so the document, undo
|
||||
* history, scroll and keymaps survive (host `null` = nothing is installed and
|
||||
* no decoration exists at all).
|
||||
*/
|
||||
export class CmGitGutterCompartment {
|
||||
private readonly compartment = new Compartment()
|
||||
|
||||
/** `of(...)` payload for EditorState.create. */
|
||||
of(host: GitGutterHost | null): Extension {
|
||||
return this.compartment.of(gitGutterExtensions(host))
|
||||
}
|
||||
|
||||
/** Reconfigure for a setting flip (or a new file). */
|
||||
reconfigure(host: GitGutterHost | null): ReturnType<Compartment['reconfigure']> {
|
||||
return this.compartment.reconfigure(gitGutterExtensions(host))
|
||||
}
|
||||
}
|
||||
|
||||
// ── Blame (hover only; memoized per session + path + line) ──────────────────
|
||||
|
||||
/** Upper bound on memoized blame lines; the whole memo is dropped past it. */
|
||||
const BLAME_CACHE_LIMIT = 500
|
||||
const blameCache = new Map<string, Promise<GitBlameLine | null>>()
|
||||
|
||||
const blameKey = (sessionId: string, path: string, line: number): string =>
|
||||
`${sessionId}\u0000${path}\u0000${String(line)}`
|
||||
|
||||
/** Drop the memo of one file (its change set was recomputed). */
|
||||
export function forgetBlame(sessionId: string, path: string): void {
|
||||
const prefix = `${sessionId}\u0000${path}\u0000`
|
||||
for (const key of [...blameCache.keys()]) {
|
||||
if (key.startsWith(prefix)) blameCache.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
/** Blame one line, or null when git has no answer (untracked file, no
|
||||
* repository, command failure) — the tooltip then simply never shows. */
|
||||
export function loadBlameLine(scope: SessionScope, path: string, line: number): Promise<GitBlameLine | null> {
|
||||
const key = blameKey(scope.sessionId, path, line)
|
||||
const memo = blameCache.get(key)
|
||||
if (memo !== undefined) return memo
|
||||
if (blameCache.size >= BLAME_CACHE_LIMIT) blameCache.clear()
|
||||
const pending = api.gitBlame(scope, path, line, line).then(
|
||||
result => result.lines.find(entry => entry.line === line) ?? null,
|
||||
() => null,
|
||||
)
|
||||
blameCache.set(key, pending)
|
||||
return pending
|
||||
}
|
||||
|
||||
/** The tooltip body: plain text, two lines (who/when, then the summary). */
|
||||
function blameTooltipDom(entry: GitBlameLine): HTMLElement {
|
||||
const dom = document.createElement('div')
|
||||
dom.className = css.editorBlame ?? ''
|
||||
const head = document.createElement('div')
|
||||
head.className = css.editorBlameHead ?? ''
|
||||
head.textContent = [entry.author, relativeTime(entry.date)].filter(part => part !== '').join(' · ')
|
||||
dom.append(head)
|
||||
if (entry.summary !== '') {
|
||||
const summary = document.createElement('div')
|
||||
summary.className = css.editorBlameSummary ?? ''
|
||||
summary.textContent = entry.summary
|
||||
dom.append(summary)
|
||||
}
|
||||
return dom
|
||||
}
|
||||
|
||||
// ── The React side: which lines are marked ─────────────────────────────────
|
||||
|
||||
/** Everything the gutter needs from the editor component. */
|
||||
export interface EditorGitGutterOptions {
|
||||
/** False for every viewer but `code`, and when the setting is off. */
|
||||
enabled: boolean
|
||||
scope: SessionScope
|
||||
path: string
|
||||
/** The loaded text; a reload re-reads the change set. */
|
||||
content: string | undefined
|
||||
/** Bumped after a save: the diff changed while the status entry did not. */
|
||||
revision: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The changed lines of the open file, from the SHARED git status store (which
|
||||
* decides whether the file is modified at all, and whether it is untracked)
|
||||
* plus one `git diff HEAD` request per change. Clean files, unknown files and
|
||||
* the disabled state all resolve to an empty map — no decoration.
|
||||
*/
|
||||
export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap<number, GitLineKind> {
|
||||
const { enabled, path, content, revision } = options
|
||||
const sessionId = options.scope.sessionId
|
||||
const cwd = options.scope.cwd
|
||||
const repoRoot = options.scope.repoRoot
|
||||
const scope = useMemo<SessionScope>(
|
||||
() => ({ sessionId, cwd, ...(repoRoot !== undefined ? { repoRoot } : {}) }),
|
||||
[sessionId, cwd, repoRoot],
|
||||
)
|
||||
const status = useGitStatus(scope, { visible: enabled })
|
||||
const entry = enabled ? status.statusOf(path) : undefined
|
||||
const [kinds, setKinds] = useState<ReadonlyMap<number, GitLineKind>>(EMPTY_KINDS)
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || entry === undefined) {
|
||||
setKinds(EMPTY_KINDS)
|
||||
return undefined
|
||||
}
|
||||
let cancelled = false
|
||||
// A fresh change set invalidates the file's blame memo (the lines that
|
||||
// moved may now belong to other commits).
|
||||
forgetBlame(scope.sessionId, path)
|
||||
if (entry.tone === 'untracked') {
|
||||
setKinds(addedLineKinds(content === undefined || content === '' ? 0 : content.split('\n').length))
|
||||
return undefined
|
||||
}
|
||||
api.gitDiffHead(scope, path).then(
|
||||
(result) => { if (!cancelled) setKinds(gitLineKinds(result.diff)) },
|
||||
() => { if (!cancelled) setKinds(EMPTY_KINDS) },
|
||||
)
|
||||
return () => { cancelled = true }
|
||||
}, [enabled, scope, path, content, revision, entry])
|
||||
|
||||
return kinds
|
||||
}
|
||||
@@ -352,6 +352,8 @@ export const ar: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'عند التفعيل، تبدأ كل معاينة HTML مفتوحة حديثاً في الحالة غير المحمية (نفس أصل الواجهة — يمكنها قراءة ملفات الجلسة وواجهات API الداخلية)؛ يوفر صف الحالة استعادة بلمسة واحدة',
|
||||
settingsHtmlSandboxTitle: 'تعطيل حماية معاينة HTML (غير آمن)',
|
||||
settingsHtmlSandboxDesc: 'مع تعطيل الحماية، يعمل HTML المعاين بنفس أصل الواجهة: يمكنه قراءة ملفات الجلسة والتخزين المحلي واستدعاء واجهات API الداخلية. فعّله فقط للملفات الموثوقة بالكامل',
|
||||
settingsEditorGitGutterTitle: 'علامات التغييرات غير المُودَعة في المحرر',
|
||||
settingsEditorGitGutterDesc: 'تلّون هامش أرقام الأسطر في محرر الشيفرة للتغييرات غير المُودَعة، وتعرض عند المرور سجلّ السطر (المؤلف والوقت وملخّص الإيداع)؛ الإيقاف يخفي كل العلامات',
|
||||
settingsBrowserSandboxTitle: 'تعطيل حماية المتصفح (غير آمن)',
|
||||
settingsBrowserSandboxDesc: 'مع تعطيل الحماية، يعمل أي موقع تزوره بنفس أصل الواجهة: يمكنه قراءة بيانات الجلسة وانتحال جلسة تسجيل الدخول الخاصة بك. فعّله فقط للمواقع الموثوقة بالكامل',
|
||||
settingsBrowserLoopbackTitle: 'العناوين المحلية المسموح بها',
|
||||
|
||||
@@ -337,6 +337,8 @@ export const de: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Wenn aktiviert, startet jede neu geöffnete HTML-Vorschau ohne Sandbox (gleiche Herkunft wie die Oberfläche – sie kann Sitzungsdateien und interne APIs lesen); die Statuszeile bietet weiterhin eine einmalige Wiederherstellung',
|
||||
settingsHtmlSandboxTitle: 'HTML-Vorschau-Sandbox deaktivieren (unsicher)',
|
||||
settingsHtmlSandboxDesc: 'Ohne Sandbox läuft das angezeigte HTML mit der gleichen Herkunft wie die Oberfläche: Es kann Sitzungsdateien und lokalen Speicher lesen und interne APIs aufrufen. Nur für vollständig vertrauenswürdige Dateien aktivieren',
|
||||
settingsEditorGitGutterTitle: 'Markierungen für nicht committete Änderungen',
|
||||
settingsEditorGitGutterDesc: 'Färbt den Zeilennummernbereich des Code-Editors für nicht committete Änderungen und zeigt beim Überfahren den Blame der Zeile (Autor, Zeit und Commit-Zusammenfassung); aus blendet jede Markierung aus',
|
||||
settingsBrowserSandboxTitle: 'Browser-Sandbox deaktivieren (unsicher)',
|
||||
settingsBrowserSandboxDesc: 'Ohne Sandbox läuft jede besuchte Website mit der gleichen Herkunft wie die Oberfläche: Sie kann Sitzungsdaten lesen und sich als Ihre Anmeldung ausgeben. Nur für vollständig vertrauenswürdige Websites aktivieren',
|
||||
settingsBrowserLoopbackTitle: 'Erlaubte lokale Adressen',
|
||||
|
||||
@@ -344,6 +344,8 @@ export const fr: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Une fois activé, chaque ouverture d’un fichier HTML démarre l’aperçu en état non bac à sable (même origine que l’interface, pouvant lire les fichiers de session et les interfaces internes) ; la barre d’état permet de restaurer temporairement le bac à sable',
|
||||
settingsHtmlSandboxTitle: 'Désactiver le bac à sable de l’aperçu HTML (non sécurisé)',
|
||||
settingsHtmlSandboxDesc: 'Une fois désactivé, le HTML de l’aperçu s’exécute avec la même origine que l’interface, peut lire les fichiers de session, le stockage local et appeler les interfaces internes. À activer uniquement pour des fichiers entièrement fiables',
|
||||
settingsEditorGitGutterTitle: 'Marqueurs des modifications non validées',
|
||||
settingsEditorGitGutterDesc: 'Colore la marge des numéros de ligne pour les modifications non validées et affiche le blame de la ligne au survol (auteur, date et résumé du commit) ; désactivé masque toute marque',
|
||||
settingsBrowserSandboxTitle: 'Désactiver le bac à sable du navigateur (non sécurisé)',
|
||||
settingsBrowserSandboxDesc: 'Une fois désactivé, tout site visité s’exécute avec la même origine que l’interface, peut lire les données de session et usurper votre état de connexion. À activer uniquement pour des sites entièrement fiables',
|
||||
settingsBrowserLoopbackTitle: 'Adresses locales autorisées',
|
||||
|
||||
@@ -351,6 +351,8 @@ export const hi: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'चालू होने पर, हर नया खुला HTML पूर्वावलोकन अनसैंडबॉक्स्ड स्थिति में शुरू होता है (GUI के समान मूल — सत्र फ़ाइलें और आंतरिक API पढ़ सकता है); स्थिति पंक्ति अभी भी एक-टैप पुनर्स्थापना देती है',
|
||||
settingsHtmlSandboxTitle: 'HTML पूर्वावलोकन सैंडबॉक्स अक्षम करें (असुरक्षित)',
|
||||
settingsHtmlSandboxDesc: 'सैंडबॉक्स बंद होने पर, पूर्वावलोकित HTML GUI के समान मूल के साथ चलता है: सत्र फ़ाइलें, स्थानीय स्टोरेज पढ़ सकता है और आंतरिक API कॉल कर सकता है। केवल पूर्ण विश्वसनीय फ़ाइलों के लिए सक्षम करें',
|
||||
settingsEditorGitGutterTitle: 'एडिटर में बिना कमिट बदलाव के निशान',
|
||||
settingsEditorGitGutterDesc: 'कोड एडिटर की पंक्ति-संख्या पट्टी में बिना कमिट बदलावों को रंग देता है और माउस ले जाने पर उस पंक्ति का blame (लेखक, समय और कमिट सारांश) दिखाता है; बंद करने पर कोई निशान नहीं दिखता',
|
||||
settingsBrowserSandboxTitle: 'ब्राउज़र सैंडबॉक्स अक्षम करें (असुरक्षित)',
|
||||
settingsBrowserSandboxDesc: 'सैंडबॉक्स बंद होने पर, कोई भी विज़िट की गई साइट GUI के समान मूल के साथ चलती है: सत्र डेटा पढ़ सकती है और आपके लॉग-इन सत्र के रूप में कार्य कर सकती है। केवल पूर्ण विश्वसनीय साइटों के लिए सक्षम करें',
|
||||
settingsBrowserLoopbackTitle: 'अनुमत स्थानीय पते',
|
||||
|
||||
@@ -349,6 +349,8 @@ export const id: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Saat aktif, setiap pratinjau HTML yang baru dibuka dimulai dalam keadaan tanpa sandbox (asal yang sama dengan GUI — dapat membaca berkas sesi dan API internal); baris status masih menawarkan pemulihan sekali ketuk',
|
||||
settingsHtmlSandboxTitle: 'Nonaktifkan sandbox pratinjau HTML (tidak aman)',
|
||||
settingsHtmlSandboxDesc: 'Dengan sandbox mati, HTML yang dipratinjau berjalan dengan asal yang sama dengan GUI: dapat membaca berkas sesi, penyimpanan lokal, dan memanggil API internal. Hanya aktifkan untuk berkas yang sepenuhnya tepercaya',
|
||||
settingsEditorGitGutterTitle: 'Penanda perubahan belum di-commit di editor',
|
||||
settingsEditorGitGutterDesc: 'Mewarnai margin nomor baris editor kode untuk perubahan yang belum di-commit dan menampilkan blame baris itu saat kursor diarahkan (penulis, waktu, ringkasan commit); nonaktif menyembunyikan semua penanda',
|
||||
settingsBrowserSandboxTitle: 'Nonaktifkan sandbox browser (tidak aman)',
|
||||
settingsBrowserSandboxDesc: 'Dengan sandbox mati, situs yang dikunjungi berjalan dengan asal yang sama dengan GUI: dapat membaca data sesi dan menyamar sebagai sesi login Anda. Hanya aktifkan untuk situs yang sepenuhnya tepercaya',
|
||||
settingsBrowserLoopbackTitle: 'Alamat lokal yang diizinkan',
|
||||
|
||||
@@ -342,6 +342,8 @@ export const it: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Se attivato, ogni anteprima HTML appena aperta inizia nello stato senza sandbox (stessa origine dell’interfaccia — può leggere i file di sessione e le API interne); la riga di stato offre ancora un ripristino con un tocco',
|
||||
settingsHtmlSandboxTitle: 'Disattiva la sandbox dell’anteprima HTML (non sicuro)',
|
||||
settingsHtmlSandboxDesc: 'Con la sandbox disattivata, l’HTML in anteprima viene eseguito con la stessa origine dell’interfaccia: può leggere i file di sessione, l’archiviazione locale e chiamare le API interne. Attivi solo per file completamente attendibili',
|
||||
settingsEditorGitGutterTitle: 'Indicatori delle modifiche non committate',
|
||||
settingsEditorGitGutterDesc: 'Colora il margine dei numeri di riga per le modifiche non committate e mostra al passaggio del mouse il blame della riga (autore, data e riassunto del commit); disattivato nasconde ogni indicatore',
|
||||
settingsBrowserSandboxTitle: 'Disattiva la sandbox del browser (non sicuro)',
|
||||
settingsBrowserSandboxDesc: 'Con la sandbox disattivata, ogni sito visitato viene eseguito con la stessa origine dell’interfaccia: può leggere i dati di sessione e fingersi la sua sessione di login. Attivi solo per siti completamente attendibili',
|
||||
settingsBrowserLoopbackTitle: 'Indirizzi locali consentiti',
|
||||
|
||||
@@ -351,6 +351,8 @@ export const ja: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'オンにすると、新しく開く HTML プレビューは非サンドボックス状態で起動(GUI と同一オリジン、会話ファイルや内部 API を読み取り可)。ステータス行から一時的にサンドボックスを復元可能',
|
||||
settingsHtmlSandboxTitle: 'HTML プレビューのサンドボックスを無効化(非安全)',
|
||||
settingsHtmlSandboxDesc: 'サンドボックスをオフにすると、プレビューされる HTML は GUI と同一オリジンで動作し、会話ファイル・ローカルストレージ・内部 API にアクセス可能。完全に信頼できるファイルのみで有効化',
|
||||
settingsEditorGitGutterTitle: 'エディターの未コミット変更マーカー',
|
||||
settingsEditorGitGutterDesc: 'コードエディターの行番号欄に未コミットの変更を色付けし、ホバーでその行の blame(作者・時刻・コミット概要)を表示します。オフにすると変更マーカーを表示しません',
|
||||
settingsBrowserSandboxTitle: 'ブラウザーサンドボックスを無効化(非安全)',
|
||||
settingsBrowserSandboxDesc: 'サンドボックスをオフにすると、訪問するあらゆるサイトが GUI と同一オリジンで動作し、会話データを読み取ったりログイン状態を偽装したりできます。完全に信頼できるサイトのみで有効化',
|
||||
settingsBrowserLoopbackTitle: '許可されたローカルアドレス',
|
||||
|
||||
@@ -343,6 +343,8 @@ export const ko: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: '켜면 HTML 파일을 열 때마다 미리보기가 기본적으로 샌드박스 없이 열립니다(인터페이스와 동일 출처로 세션 파일과 내부 인터페이스를 읽을 수 있음). 상태 표시줄에서 임시로 샌드박스를 복원할 수 있습니다',
|
||||
settingsHtmlSandboxTitle: 'HTML 미리보기 샌드박스 끄기(안전하지 않음)',
|
||||
settingsHtmlSandboxDesc: '끄면 미리보기 HTML이 인터페이스와 동일 출처로 실행되어 세션 파일, 로컬 저장소를 읽고 내부 인터페이스를 호출할 수 있습니다. 완전히 신뢰하는 파일에서만 켜세요',
|
||||
settingsEditorGitGutterTitle: '편집기 미커밋 변경 표시',
|
||||
settingsEditorGitGutterDesc: '코드 편집기 줄 번호 여백에 미커밋 변경을 색으로 표시하고, 마우스를 올리면 해당 줄의 blame(작성자·시각·커밋 요약)을 보여 줍니다. 끄면 모든 표시가 사라집니다',
|
||||
settingsBrowserSandboxTitle: '브라우저 샌드박스 끄기(안전하지 않음)',
|
||||
settingsBrowserSandboxDesc: '끄면 방문하는 모든 사이트가 인터페이스와 동일 출처로 실행되어 세션 데이터를 읽고 사용자의 로그인 상태를 가장할 수 있습니다. 완전히 신뢰하는 사이트에서만 켜세요',
|
||||
settingsBrowserLoopbackTitle: '허용된 로컬 주소',
|
||||
|
||||
@@ -349,6 +349,8 @@ export const nl: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Indien aan, start elke nieuw geopende HTML-voorbeeld in de niet-gesandboxte staat (zelfde origin als de GUI — kan sessiebestanden en interne API\'s lezen); de statusbalk biedt nog een eenkliks-herstel',
|
||||
settingsHtmlSandboxTitle: 'HTML-voorbeeld-sandbox uitschakelen (onveilig)',
|
||||
settingsHtmlSandboxDesc: 'Met de sandbox uit draait gepreviewde HTML met dezelfde origin als de GUI: kan sessiebestanden, lokale opslag lezen en interne API\'s aanroepen. Alleen inschakelen voor volledig vertrouwde bestanden',
|
||||
settingsEditorGitGutterTitle: 'Markeringen voor niet-gecommitte wijzigingen',
|
||||
settingsEditorGitGutterDesc: 'Kleurt de regelnummer-marge van de code-editor voor niet-gecommitte wijzigingen en toont bij hover de blame van die regel (auteur, tijd en commit-samenvatting); uit verbergt elke markering',
|
||||
settingsBrowserSandboxTitle: 'Browser-sandbox uitschakelen (onveilig)',
|
||||
settingsBrowserSandboxDesc: 'Met de sandbox uit draait elke bezochte site met dezelfde origin als de GUI: kan sessiegegevens lezen en zich voordoen als uw ingelogde sessie. Alleen inschakelen voor volledig vertrouwde sites',
|
||||
settingsBrowserLoopbackTitle: 'Toegestane lokale adressen',
|
||||
|
||||
@@ -353,6 +353,8 @@ export const pl: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Po włączeniu każdy nowo otwarty podgląd HTML zaczyna się bez piaskownicy (ten sam origin co interfejs — może czytać pliki sesji i wewnętrzne API); pasek stanu nadal pozwala przywrócić piaskownicę',
|
||||
settingsHtmlSandboxTitle: 'Wyłącz piaskownicę podglądu HTML (niebezpieczne)',
|
||||
settingsHtmlSandboxDesc: 'Po wyłączeniu podglądany HTML działa w tym samym originie co interfejs: może czytać pliki sesji, localStorage i wywoływać wewnętrzne API. Włączaj tylko dla w pełni zaufanych plików',
|
||||
settingsEditorGitGutterTitle: 'Oznaczenia niezacommitowanych zmian',
|
||||
settingsEditorGitGutterDesc: 'Koloruje margines numerów wierszy dla niezacommitowanych zmian i pokazuje po najechaniu blame wiersza (autor, czas i podsumowanie commita); wyłączenie ukrywa wszystkie oznaczenia',
|
||||
settingsBrowserSandboxTitle: 'Wyłącz piaskownicę przeglądarki (niebezpieczne)',
|
||||
settingsBrowserSandboxDesc: 'Po wyłączeniu każda odwiedzana strona działa w tym samym originie co interfejs: może czytać dane sesji i podszywać się pod Twoją sesję logowania. Włączaj tylko dla w pełni zaufanych witryn',
|
||||
settingsBrowserLoopbackTitle: 'Dozwolone adresy lokalne',
|
||||
|
||||
@@ -334,6 +334,8 @@ export const pt: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Quando ativado, toda pré-visualização de HTML recém-aberta começa sem sandbox (mesma origem da interface — pode ler arquivos de sessão e APIs internas); a linha de status ainda oferece restauração em um toque',
|
||||
settingsHtmlSandboxTitle: 'Desativar o sandbox da pré-visualização de HTML (inseguro)',
|
||||
settingsHtmlSandboxDesc: 'Com o sandbox desativado, o HTML pré-visualizado roda com a mesma origem da interface: pode ler arquivos de sessão, armazenamento local e chamar APIs internas. Ative apenas para arquivos totalmente confiáveis',
|
||||
settingsEditorGitGutterTitle: 'Marcadores de alterações não confirmadas',
|
||||
settingsEditorGitGutterDesc: 'Colore a margem dos números de linha para alterações não confirmadas e mostra o blame da linha ao passar o mouse (autor, data e resumo do commit); desativado oculta todas as marcas',
|
||||
settingsBrowserSandboxTitle: 'Desativar o sandbox do navegador (inseguro)',
|
||||
settingsBrowserSandboxDesc: 'Com o sandbox desativado, qualquer site visitado roda com a mesma origem da interface: pode ler dados da sessão e agir como sua sessão conectada. Ative apenas para sites totalmente confiáveis',
|
||||
settingsBrowserLoopbackTitle: 'Endereços locais permitidos',
|
||||
|
||||
@@ -348,6 +348,8 @@ export const ru: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Если включено, каждый новый HTML-предпросмотр стартует без песочницы (тот же источник, что у интерфейса — может читать файлы сессии и внутренние API); в строке состояния можно временно включить песочницу',
|
||||
settingsHtmlSandboxTitle: 'Отключить песочницу HTML-предпросмотра (небезопасно)',
|
||||
settingsHtmlSandboxDesc: 'При отключении предпросматриваемый HTML работает в том же источнике, что интерфейс: может читать файлы сессии, локальное хранилище и вызывать внутренние API. Включайте только для полностью доверенных файлов',
|
||||
settingsEditorGitGutterTitle: 'Отметки незакоммиченных изменений',
|
||||
settingsEditorGitGutterDesc: 'Подсвечивает поле номеров строк для незакоммиченных изменений и показывает при наведении blame строки (автор, время и сводка коммита); выключение скрывает все отметки',
|
||||
settingsBrowserSandboxTitle: 'Отключить песочницу браузера (небезопасно)',
|
||||
settingsBrowserSandboxDesc: 'При отключении любой посещаемый сайт работает в том же источнике, что интерфейс: может читать данные сессии и выдавать себя за ваш вход. Включайте только для полностью доверенных сайтов',
|
||||
settingsBrowserLoopbackTitle: 'Разрешённые локальные адреса',
|
||||
|
||||
@@ -334,6 +334,8 @@ export const sv: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'När på, startar varje nyöppnad HTML-förhandsgranskning i osandlådat tillstånd (samma ursprung som GUI — kan läsa sessionsfiler och interna API:er); statusraden erbjuder fortfarande en återställning med ett klick',
|
||||
settingsHtmlSandboxTitle: 'Avaktivera sandlåda för HTML-förhandsgranskning (osäkert)',
|
||||
settingsHtmlSandboxDesc: 'Med sandlådan av körs förhandsgranskad HTML med samma ursprung som GUI: kan läsa sessionsfiler, lokal lagring och anropa interna API:er. Aktivera endast för fullt betrodda filer',
|
||||
settingsEditorGitGutterTitle: 'Markeringar för ej incheckade ändringar',
|
||||
settingsEditorGitGutterDesc: 'Färgar radnummer-marginalen för ej incheckade ändringar och visar radens blame vid hovring (författare, tid och commit-sammanfattning); av döljer alla markeringar',
|
||||
settingsBrowserSandboxTitle: 'Avaktivera webbläsarsandlåda (osäkert)',
|
||||
settingsBrowserSandboxDesc: 'Med sandlådan av körs alla besökta sajter med samma ursprung som GUI: kan läsa sessionsdata och agera som er inloggade session. Aktivera endast för fullt betrodda sajter',
|
||||
settingsBrowserLoopbackTitle: 'Tillåtna lokala adresser',
|
||||
|
||||
@@ -351,6 +351,8 @@ export const th: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'เมื่อเปิด พรีวิว HTML ที่เปิดใหม่ทุกครั้งจะเริ่มในสถานะไม่มีแซนด์บ็อกซ์ (origin เดียวกับ GUI — สามารถอ่านไฟล์เซสชันและ API ภายในได้); แถวสถานะยังคงเสนอการคืนค่าแบบแตะครั้งเดียว',
|
||||
settingsHtmlSandboxTitle: 'ปิดแซนด์บ็อกซ์พรีวิว HTML (ไม่ปลอดภัย)',
|
||||
settingsHtmlSandboxDesc: 'เมื่อปิดแซนด์บ็อกซ์ HTML ที่พรีวิวจะทำงานด้วย origin เดียวกับ GUI: สามารถอ่านไฟล์เซสชัน, ที่เก็บข้อมูลในเครื่อง และเรียก API ภายในได้ เปิดใช้เฉพาะสำหรับไฟล์ที่เชื่อถือได้อย่างเต็มที่',
|
||||
settingsEditorGitGutterTitle: 'เครื่องหมายการเปลี่ยนแปลงที่ยังไม่คอมมิต',
|
||||
settingsEditorGitGutterDesc: 'ระบายสีแถบเลขบรรทัดของโค้ดเอดิเตอร์สำหรับการเปลี่ยนแปลงที่ยังไม่คอมมิต และแสดง blame ของบรรทัดนั้นเมื่อวางเมาส์ (ผู้เขียน เวลา และสรุปคอมมิต) ปิดแล้วจะไม่แสดงเครื่องหมายใด ๆ',
|
||||
settingsBrowserSandboxTitle: 'ปิดแซนด์บ็อกซ์เบราว์เซอร์ (ไม่ปลอดภัย)',
|
||||
settingsBrowserSandboxDesc: 'เมื่อปิดแซนด์บ็อกซ์ ไซต์ที่เยี่ยมชมใดๆ จะทำงานด้วย origin เดียวกับ GUI: สามารถอ่านข้อมูลเซสชันและแสดงเป็นเซสชันล็อกอินของคุณได้ เปิดใช้เฉพาะสำหรับไซต์ที่เชื่อถือได้อย่างเต็มที่',
|
||||
settingsBrowserLoopbackTitle: 'ที่อยู่ภายในเครื่องที่อนุญาต',
|
||||
|
||||
@@ -351,6 +351,8 @@ export const tr: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Açıkken, yeni açılan her HTML önizlemesi kumsuz durumda başlar (arayüzle aynı kaynak — oturum dosyalarını ve iç API’leri okuyabilir); durum satırı yine tek dokunuşla geri yükleme sunar',
|
||||
settingsHtmlSandboxTitle: 'HTML önizleme kumunu devre dışı bırak (güvenli değil)',
|
||||
settingsHtmlSandboxDesc: 'Kum kapalıyken önizlenen HTML arayüzle aynı kaynakta çalışır: oturum dosyalarını, yerel depoyu okuyabilir ve iç API’leri çağırabilir. Yalnızca tamamen güvenilen dosyalar için etkinleştirin',
|
||||
settingsEditorGitGutterTitle: 'Düzenleyicide işlenmemiş değişiklik işaretleri',
|
||||
settingsEditorGitGutterDesc: 'Kod düzenleyicisinin satır numarası kenarını işlenmemiş değişiklikler için renklendirir ve fareyle üzerine gelindiğinde o satırın blame bilgisini (yazar, zaman ve commit özeti) gösterir; kapatınca hiçbir işaret görünmez',
|
||||
settingsBrowserSandboxTitle: 'Tarayıcı kumunu devre dışı bırak (güvenli değil)',
|
||||
settingsBrowserSandboxDesc: 'Kum kapalıyken ziyaret edilen her site arayüzle aynı kaynakta çalışır: oturum verilerini okuyabilir ve oturum açmış halinize bürünebilir. Yalnızca tamamen güvenilen siteler için etkinleştirin',
|
||||
settingsBrowserLoopbackTitle: 'İzin verilen yerel adresler',
|
||||
|
||||
@@ -351,6 +351,8 @@ export const vi: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'Khi bật, mỗi lần mở tệp HTML xem trước sẽ mặc định không sandbox (cùng nguồn UI, có thể đọc tệp phiên và API nội bộ); có thể khôi phục sandbox tạm thời trên thanh trạng thái',
|
||||
settingsHtmlSandboxTitle: 'Tắt sandbox xem trước HTML (không an toàn)',
|
||||
settingsHtmlSandboxDesc: 'Khi tắt, HTML xem trước sẽ chạy cùng nguồn với UI: có thể đọc tệp phiên, local storage và gọi API nội bộ. Chỉ bật cho tệp hoàn toàn đáng tin cậy',
|
||||
settingsEditorGitGutterTitle: 'Dấu thay đổi chưa commit trong trình soạn thảo',
|
||||
settingsEditorGitGutterDesc: 'Tô màu lề số dòng của trình soạn thảo mã cho các thay đổi chưa commit và hiện blame của dòng khi rê chuột (tác giả, thời gian và tóm tắt commit); tắt sẽ ẩn mọi dấu',
|
||||
settingsBrowserSandboxTitle: 'Tắt sandbox trình duyệt (không an toàn)',
|
||||
settingsBrowserSandboxDesc: 'Khi tắt, mọi trang truy cập sẽ chạy cùng nguồn với UI: có thể đọc dữ liệu phiên và mạo danh phiên đăng nhập. Chỉ bật cho trang hoàn toàn đáng tin cậy',
|
||||
settingsBrowserLoopbackTitle: 'Địa chỉ cục bộ được phép',
|
||||
|
||||
@@ -366,6 +366,8 @@ export const zhHK: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: '開啟後,每次開啟 HTML 檔案時預覽預設處於非沙箱狀態(與介面同源,可讀取工作階段檔案與內部介面);可在狀態列臨時恢復沙箱',
|
||||
settingsHtmlSandboxTitle: '關閉 HTML 預覽沙箱(不安全)',
|
||||
settingsHtmlSandboxDesc: '關閉後,預覽的 HTML 將與介面同源執行,可讀取工作階段檔案、本地儲存並呼叫內部介面。僅對完全可信的檔案開啟',
|
||||
settingsEditorGitGutterTitle: '編輯器未提交變更提示',
|
||||
settingsEditorGitGutterDesc: '在程式碼編輯器的行號欄以顏色標出未提交的變更,並在滑鼠懸停時顯示該行 blame(作者、時間與提交摘要);關閉後編輯器不顯示任何變更標記',
|
||||
settingsBrowserSandboxTitle: '關閉瀏覽器沙箱(不安全)',
|
||||
settingsBrowserSandboxDesc: '關閉後,存取的任何網站都將與介面同源執行,可讀取工作階段資料並冒充你的登入狀態。僅對完全可信的網站開啟',
|
||||
settingsBrowserLoopbackTitle: '允許訪問的本機地址',
|
||||
|
||||
@@ -366,6 +366,8 @@ export const zhMO: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: '開啟後,每次開啟 HTML 檔案時預覽預設處於非沙箱狀態(與介面同源,可讀取工作階段檔案與內部介面);可在狀態列臨時恢復沙箱',
|
||||
settingsHtmlSandboxTitle: '關閉 HTML 預覽沙箱(不安全)',
|
||||
settingsHtmlSandboxDesc: '關閉後,預覽的 HTML 將與介面同源執行,可讀取工作階段檔案、本地儲存並呼叫內部介面。僅對完全可信的檔案開啟',
|
||||
settingsEditorGitGutterTitle: '編輯器未提交變更提示',
|
||||
settingsEditorGitGutterDesc: '在程式碼編輯器的行號欄以顏色標出未提交的變更,並在滑鼠懸停時顯示該行 blame(作者、時間與提交摘要);關閉後編輯器不顯示任何變更標記',
|
||||
settingsBrowserSandboxTitle: '關閉瀏覽器沙箱(不安全)',
|
||||
settingsBrowserSandboxDesc: '關閉後,存取的任何網站都將與介面同源執行,可讀取工作階段資料並冒充你的登入狀態。僅對完全可信的網站開啟',
|
||||
settingsBrowserLoopbackTitle: '允許訪問的本機地址',
|
||||
|
||||
@@ -366,6 +366,8 @@ export const zhTW: Record<string, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: '開啟後,每次開啟 HTML 檔案時預覽預設處於非沙箱狀態(與介面同源,可讀取工作階段檔案與內部介面);可在狀態列臨時恢復沙箱',
|
||||
settingsHtmlSandboxTitle: '關閉 HTML 預覽沙箱(不安全)',
|
||||
settingsHtmlSandboxDesc: '關閉後,預覽的 HTML 將與介面同源執行,可讀取工作階段檔案、本地儲存並呼叫內部介面。僅對完全可信的檔案開啟',
|
||||
settingsEditorGitGutterTitle: '編輯器未提交變更提示',
|
||||
settingsEditorGitGutterDesc: '在程式碼編輯器的行號欄以顏色標出未提交的變更,並在滑鼠懸停時顯示該行 blame(作者、時間與提交摘要);關閉後編輯器不顯示任何變更標記',
|
||||
settingsBrowserSandboxTitle: '關閉瀏覽器沙箱(不安全)',
|
||||
settingsBrowserSandboxDesc: '關閉後,存取的任何網站都將與介面同源執行,可讀取工作階段資料並冒充你的登入狀態。僅對完全可信的網站開啟',
|
||||
settingsBrowserLoopbackTitle: '允許存取的本機地址',
|
||||
|
||||
@@ -363,6 +363,8 @@ export const zh = {
|
||||
settingsHtmlDefaultUnsafeDesc: '开启后,每次打开 HTML 文件时预览默认处于非沙箱状态(与界面同源,可读取会话文件与内部接口);可在状态行临时恢复沙箱',
|
||||
settingsHtmlSandboxTitle: '关闭 HTML 预览沙箱(不安全)',
|
||||
settingsHtmlSandboxDesc: '关闭后,预览的 HTML 将与界面同源运行,可读取会话文件、本地存储并调用内部接口。仅对完全可信的文件开启',
|
||||
settingsEditorGitGutterTitle: '编辑器未提交变更提示',
|
||||
settingsEditorGitGutterDesc: '在代码编辑器的行号槽用颜色标出未提交的变更,并在鼠标悬停时显示该行 blame(作者、时间与提交摘要);关闭后编辑器不显示任何变更标记',
|
||||
settingsBrowserSandboxTitle: '关闭浏览器沙箱(不安全)',
|
||||
settingsBrowserSandboxDesc: '关闭后,访问的任何网站都将与界面同源运行,可读取会话数据并冒充你的登录状态。仅对完全可信的站点开启',
|
||||
settingsBrowserLoopbackTitle: '允许访问的本机地址',
|
||||
@@ -932,6 +934,8 @@ export const en: Record<keyof typeof zh, string> = {
|
||||
settingsHtmlDefaultUnsafeDesc: 'When on, every newly opened HTML preview starts in the unsandboxed state (same origin as the GUI — it can read session files and internal APIs); the status row still offers a one-tap restore',
|
||||
settingsHtmlSandboxTitle: 'Disable HTML preview sandbox (unsafe)',
|
||||
settingsHtmlSandboxDesc: 'With the sandbox off, previewed HTML runs with the same origin as the GUI: it can read session files, local storage and call internal APIs. Only enable for fully trusted files',
|
||||
settingsEditorGitGutterTitle: 'Editor uncommitted-change markers',
|
||||
settingsEditorGitGutterDesc: 'Tint the line-number gutter of the code editor for uncommitted changes and show that line\'s blame (author, time and commit summary) on hover; off hides every marker',
|
||||
settingsBrowserSandboxTitle: 'Disable browser sandbox (unsafe)',
|
||||
settingsBrowserSandboxDesc: 'With the sandbox off, any visited site runs with the same origin as the GUI: it can read session data and act as your logged-in session. Only enable for fully trusted sites',
|
||||
settingsBrowserLoopbackTitle: 'Allowed local addresses',
|
||||
|
||||
@@ -62,6 +62,9 @@ export function parsePrefs(value: unknown): SidebarPrefs {
|
||||
editorExplorer: typeof record.editorExplorer === 'boolean'
|
||||
? record.editorExplorer
|
||||
: SIDEBAR_PREFS_DEFAULTS.editorExplorer,
|
||||
editorGitGutter: typeof record.editorGitGutter === 'boolean'
|
||||
? record.editorGitGutter
|
||||
: SIDEBAR_PREFS_DEFAULTS.editorGitGutter,
|
||||
explorerExclude: stringArrayOf(record.explorerExclude),
|
||||
// The title-bar scheme (auto | web | preset | custom). The schema
|
||||
// declares the field WITHOUT a default, so documents written by older
|
||||
|
||||
@@ -1522,6 +1522,54 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ── Uncommitted-change gutter (issue #212) ─────────────────────────────────
|
||||
VS Code's restraint: the line NUMBER takes the tone of its change, and a
|
||||
2px bar sits at the far left of the numbers. The classes are handed to
|
||||
CodeMirror as gutter-marker class names (see editor-git-gutter.ts), which
|
||||
is why they are referenced from TS as well as styled here. The tones are
|
||||
the file tree's own mapping (added/untracked green, modified amber,
|
||||
deleted red). Deliberately nothing else: no end-of-line widget, no badge,
|
||||
no animation, no gradient. */
|
||||
.editorGitAdd { color: var(--dsw-alias-state-success-primary); }
|
||||
.editorGitMod { color: var(--dsw-alias-state-warn-primary); }
|
||||
.editorGitDel { color: var(--dsw-alias-state-error-primary); }
|
||||
|
||||
/* The bar column: 2px of ink, plus the hidden spacer that keeps the width
|
||||
reserved while the file is clean (the numbers never shift sideways). */
|
||||
.editorGitBarGutter {
|
||||
width: 2px;
|
||||
min-width: 2px;
|
||||
}
|
||||
|
||||
.editorGitBar,
|
||||
.editorGitBarSpacer {
|
||||
width: 2px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.editorGitBarAdd { background: var(--dsw-alias-state-success-primary); }
|
||||
.editorGitBarMod { background: var(--dsw-alias-state-warn-primary); }
|
||||
.editorGitBarDel { background: var(--dsw-alias-state-error-primary); }
|
||||
|
||||
/* Hover blame: plain text, two rows (author · when, then the summary). */
|
||||
.editorBlame {
|
||||
max-width: 420px;
|
||||
padding: 4px 8px;
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.editorBlameHead {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.editorBlameSummary {
|
||||
margin-top: 2px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Live sandbox status row (HTML preview / browser tab): GREEN while the
|
||||
sandbox is on (with the one-tap temporary unlock), RED while it is off
|
||||
(global setting or temporary unlock) — the red state is the persistent
|
||||
|
||||
@@ -322,7 +322,10 @@ export function useGitStatus(
|
||||
slot.listeners.add(listener)
|
||||
return () => { slot.listeners.delete(listener) }
|
||||
}, [slot])
|
||||
useSyncExternalStore(subscribe, () => slot.version)
|
||||
// The third argument (server snapshot) keeps a consumer that is rendered to
|
||||
// a string alive — the editor does exactly that in the markdown specs, and
|
||||
// the slot's version is 0 on both sides.
|
||||
useSyncExternalStore(subscribe, () => slot.version, () => slot.version)
|
||||
|
||||
useEffect(() => {
|
||||
slot.pollMs = pollMs
|
||||
|
||||
@@ -95,6 +95,7 @@ export const PrefsSchema: z<SidebarPrefs> = z.object({
|
||||
mobileDefaultTree: z.boolean().default(true),
|
||||
agentOpenTools: z.boolean().default(false),
|
||||
editorExplorer: z.boolean().default(false),
|
||||
editorGitGutter: z.boolean().default(true),
|
||||
explorerExclude: z.array(z.string()).default([...EXPLORER_EXCLUDE_DEFAULTS]),
|
||||
titleBarScheme: z.union([z.const('auto'), z.const('web'), z.const('preset'), z.const('custom')]),
|
||||
titleBarPresetId: z.string(),
|
||||
|
||||
+123
@@ -286,6 +286,109 @@ export function runGitRaw(cwd: string, args: string[], timeoutMs = 30_000): Prom
|
||||
return runGit(cwd, args, timeoutMs)
|
||||
}
|
||||
|
||||
/** One parsed `git blame --porcelain` row (the editor's hover blame). */
|
||||
export interface GitBlameLine {
|
||||
/** 1-based line number in the file as it exists in the worktree. */
|
||||
line: number
|
||||
/** The blamed commit (40 hex chars; all zeros for a line that is not
|
||||
* committed yet — a worktree edit git cannot attribute to a commit). */
|
||||
hash: string
|
||||
author: string
|
||||
/** Author time as ISO 8601 carrying the AUTHOR's UTC offset, so the value
|
||||
* is stable regardless of the host machine's timezone. */
|
||||
date: string
|
||||
/** The commit's subject line (git's own placeholder for uncommitted rows). */
|
||||
summary: string
|
||||
}
|
||||
|
||||
/** Format epoch seconds plus a `+HHMM`/`-HHMM` timezone as ISO 8601. */
|
||||
function isoWithOffset(seconds: number, timezone: string): string {
|
||||
const zone = /^([+-])(\d{2})(\d{2})$/.exec(timezone)
|
||||
const offsetMinutes = zone === null
|
||||
? 0
|
||||
: (zone[1] === '-' ? -1 : 1) * (Number(zone[2]) * 60 + Number(zone[3]))
|
||||
const shifted = new Date((seconds + offsetMinutes * 60) * 1000)
|
||||
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||
const stamp = `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`
|
||||
+ `T${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}`
|
||||
return zone === null ? `${stamp}Z` : `${stamp}${zone[1]}${zone[2]}:${zone[3]}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `git blame --porcelain -L <a>,<b>` output into one row per blamed
|
||||
* line. Porcelain repeats only the `<hash> <orig> <final>` header for the
|
||||
* SECOND and later lines of the same commit (the author / committer / summary
|
||||
* block is emitted once per commit per run), so metadata is carried forward
|
||||
* per hash; every record ends with its `\t`-prefixed content line, which is
|
||||
* where the walk resumes. Unknown lines are skipped, never fatal.
|
||||
*/
|
||||
export function parseBlamePorcelain(output: string): GitBlameLine[] {
|
||||
const rows: GitBlameLine[] = []
|
||||
const seen = new Map<string, { author: string; date: string; summary: string }>()
|
||||
const lines = output.split('\n')
|
||||
let index = 0
|
||||
while (index < lines.length) {
|
||||
const header = /^([0-9a-f]{40,64}) \d+ (\d+)(?: \d+)?$/.exec(lines[index]!)
|
||||
if (header === null) {
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
const hash = header[1]!
|
||||
const line = Number(header[2])
|
||||
index += 1
|
||||
let author: string | undefined
|
||||
let date: string | undefined
|
||||
let summary: string | undefined
|
||||
while (index < lines.length && !lines[index]!.startsWith('\t')) {
|
||||
const text = lines[index]!
|
||||
index += 1
|
||||
if (text.startsWith('author ')) author = text.slice('author '.length)
|
||||
else if (text.startsWith('author-time ')) {
|
||||
const seconds = Number(text.slice('author-time '.length))
|
||||
const zone = /^author-tz (.+)$/.exec(lines[index] ?? '')
|
||||
if (Number.isFinite(seconds)) date = isoWithOffset(seconds, zone?.[1] ?? '')
|
||||
} else if (text.startsWith('summary ')) summary = text.slice('summary '.length)
|
||||
}
|
||||
// The record's content line; the next header follows it.
|
||||
if (index < lines.length && lines[index]!.startsWith('\t')) index += 1
|
||||
const known = seen.get(hash)
|
||||
if (known === undefined) {
|
||||
const record = { author: author ?? '', date: date ?? '', summary: summary ?? '' }
|
||||
seen.set(hash, record)
|
||||
rows.push({ hash, line, ...record })
|
||||
} else {
|
||||
rows.push({ hash, line, ...known })
|
||||
}
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
/**
|
||||
* Blame one line range of a file (`git blame --porcelain -L <a>,<b>`).
|
||||
* Every failure mode — not a repository, an untracked file (`git blame`
|
||||
* exits non-zero: no such path in HEAD), a bad revision, a stalled mount
|
||||
* hitting the command timeout — resolves to an EMPTY result: the editor's
|
||||
* hover tooltip shows nothing and a missing answer can never break the
|
||||
* editing surface.
|
||||
*/
|
||||
export async function blame(
|
||||
cwd: string,
|
||||
path: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
selected?: string,
|
||||
): Promise<GitBlameLine[]> {
|
||||
try {
|
||||
const root = await repoRoot(cwd, selected)
|
||||
const output = await runGit(root, [
|
||||
'blame', '--porcelain', '-L', `${String(startLine)},${String(endLine)}`, '--', path,
|
||||
])
|
||||
return parseBlamePorcelain(output)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Cap on child directories probed by the workspace-container fallback scan.
|
||||
* A home-directory cwd can hold hundreds of visible folders (Library, iCloud
|
||||
* mounts…); probing them all serially is what froze the panel in #369. */
|
||||
@@ -526,6 +629,26 @@ export async function diff(cwd: string, path: string | undefined, staged: boolea
|
||||
return runGit(root, args)
|
||||
}
|
||||
|
||||
/**
|
||||
* Diff text of the worktree against HEAD — staged and unstaged changes in
|
||||
* ONE patch, which is what "uncommitted changes" means for the editor's
|
||||
* change gutter (the two-sided `diff()` above would each miss half of a file
|
||||
* that is partly staged). A repository whose HEAD is not born yet cannot
|
||||
* answer `diff HEAD`, so that one failure falls back to `diff --cached`
|
||||
* (index against the empty tree — the unborn-HEAD shape of the same
|
||||
* question). Untracked files never appear in either: the caller marks them
|
||||
* from the status store instead.
|
||||
*/
|
||||
export async function diffHead(cwd: string, path: string | undefined, selected?: string): Promise<string> {
|
||||
const root = await repoRoot(cwd, selected)
|
||||
const tail = path !== undefined ? ['--', path] : []
|
||||
try {
|
||||
return await runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', 'HEAD', ...tail])
|
||||
} catch {
|
||||
return runGit(root, ['diff', '--no-ext-diff', '--no-color', '-U3', '--cached', ...tail])
|
||||
}
|
||||
}
|
||||
|
||||
/** Stage paths (all when path is undefined). */
|
||||
export async function stage(cwd: string, path: string | undefined, selected?: string): Promise<void> {
|
||||
await runGit(await repoRoot(cwd, selected), ['add', '-A', ...(path !== undefined ? ['--', path] : [])])
|
||||
|
||||
@@ -181,6 +181,15 @@ function selectedRepoOf(payload: unknown): string | undefined {
|
||||
return requireAbsolute(requireString(payload, 'repoRoot'))
|
||||
}
|
||||
|
||||
/** One required 1-based line number of a `git blame -L` request. */
|
||||
function requireLineNumber(payload: unknown, key: string): number {
|
||||
const value = (payload as Record<string, unknown> | null)?.[key]
|
||||
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) {
|
||||
throw new SidebarError('bad-request', `"${key}" must be a positive integer line number`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a relative path an EDITOR surface carried (the file tree, the
|
||||
* editor buffer, and `fs.read`, which the untracked-diff fallback reads
|
||||
@@ -677,6 +686,16 @@ function buildApi(
|
||||
const path = record.path === undefined ? undefined : await resolveStatusPath(cwd, requireString(payload, 'path'), repoRoot)
|
||||
return { diff: await git.diff(cwd, path, record.staged === true, repoRoot) }
|
||||
},
|
||||
// The editor's change gutter asks for the WHOLE uncommitted change of one
|
||||
// file (worktree against HEAD, staged and unstaged together) — the two
|
||||
// existing `git.diff` sides would each report only half of a partly
|
||||
// staged file, and the gutter's line numbers are the worktree's.
|
||||
'git.diff-head': async (payload) => {
|
||||
const { cwd } = await gitCwdOf(payload)
|
||||
const repoRoot = selectedRepoOf(payload)
|
||||
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot))
|
||||
return { diff: await git.diffHead(cwd, path, repoRoot) }
|
||||
},
|
||||
'git.stage': async (payload) => {
|
||||
const { cwd } = await gitCwdOf(payload)
|
||||
const record = payload as { path?: unknown }
|
||||
@@ -764,6 +783,17 @@ function buildApi(
|
||||
const rev = requireString(payload, 'rev')
|
||||
return { content: await git.show(cwd, rev, path, repoRoot) }
|
||||
},
|
||||
// The editor's hover blame: ONE line range per request (the tooltip never
|
||||
// prefetches a file) and an empty list for every failure — see git.blame.
|
||||
'git.blame': async (payload) => {
|
||||
const { cwd } = await gitCwdOf(payload)
|
||||
const repoRoot = selectedRepoOf(payload)
|
||||
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), repoRoot))
|
||||
const startLine = requireLineNumber(payload, 'startLine')
|
||||
const endLine = requireLineNumber(payload, 'endLine')
|
||||
if (endLine < startLine) throw new SidebarError('bad-request', '"endLine" must not precede "startLine"')
|
||||
return { lines: await git.blame(cwd, path, startLine, endLine, repoRoot) }
|
||||
},
|
||||
// Commit-message suggestion: build a prompt from the pending changes and
|
||||
// stream it through the harness LLM service (`ctx.llm`) — no agent is
|
||||
// spawned, no session event is written, and the sidebar never sees a
|
||||
|
||||
@@ -61,6 +61,15 @@ export interface SidebarPrefs {
|
||||
* Side card settings; off restores the pre-merge editor exactly.
|
||||
*/
|
||||
editorExplorer: boolean
|
||||
/**
|
||||
* Whether the `code` editor paints its uncommitted changes the way VS Code
|
||||
* does (issue #212): the line number takes the tone of its change, a thin
|
||||
* colored bar sits at the left of the numbers, and hovering a line shows
|
||||
* that line's blame as a plain-text tooltip. On by default — there is ONE
|
||||
* switch for the whole feature (no per-part toggles: no author / hash /
|
||||
* date / summary switches, no end-of-line widget).
|
||||
*/
|
||||
editorGitGutter: boolean
|
||||
/**
|
||||
* VS Code `files.exclude`-style glob patterns (the editor card's gear
|
||||
* popup manages the list): matched entries are REMOVED from the file tree
|
||||
@@ -181,6 +190,7 @@ export const SIDEBAR_PREFS_DEFAULTS: SidebarPrefs = {
|
||||
mobileDefaultTree: true,
|
||||
agentOpenTools: false,
|
||||
editorExplorer: false,
|
||||
editorGitGutter: true,
|
||||
explorerExclude: [...EXPLORER_EXCLUDE_DEFAULTS],
|
||||
titleBarScheme: 'auto',
|
||||
titleBarPresetId: '',
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
/**
|
||||
* The editor's uncommitted-change gutter (issue #212).
|
||||
*
|
||||
* Three behaviors are pinned here:
|
||||
* - the LINE MAPPING: a `git diff` patch becomes line number → class, with
|
||||
* additions and rewritten lines on the worktree side, an unpaired deletion
|
||||
* anchored to the line above the gap, and context rows never marked
|
||||
* (a gutter that tints unchanged lines is worse than no gutter at all);
|
||||
* - the DECORATION GATE: the extensions are absent — not merely empty — for
|
||||
* every viewer but `code` and while the ONE setting is switched off,
|
||||
* checked against the real CodeMirror DOM the editor builds;
|
||||
* - the BLAME MEMO: hovering the same line twice asks git once, and a fresh
|
||||
* change set drops the file's memo (nothing is prefetched).
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { EditorState } from '@codemirror/state'
|
||||
import { EditorView } from '@codemirror/view'
|
||||
import type { GitStatusResult } from '../src/client/api.ts'
|
||||
|
||||
const { gitStatus, gitDiffHead, gitBlame } = vi.hoisted(() => ({
|
||||
gitStatus: vi.fn(),
|
||||
gitDiffHead: vi.fn(),
|
||||
gitBlame: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../src/client/api.ts', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
|
||||
return {
|
||||
...actual,
|
||||
api: {
|
||||
...actual.api,
|
||||
gitStatus: (...args: unknown[]) => gitStatus(...args),
|
||||
gitDiffHead: (...args: unknown[]) => gitDiffHead(...args),
|
||||
gitBlame: (...args: unknown[]) => gitBlame(...args),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
import {
|
||||
addedLineKinds,
|
||||
applyGitLineKinds,
|
||||
forgetBlame,
|
||||
GIT_BAR_GUTTER_CLASS,
|
||||
GIT_LINE_CLASS,
|
||||
gitGutterExtensions,
|
||||
gitLineKinds,
|
||||
loadBlameLine,
|
||||
type GitLineKind,
|
||||
} from '../src/client/editor-git-gutter.ts'
|
||||
import { TextEditor } from '../src/client/TextEditor.tsx'
|
||||
import { attachLocale } from '../src/client/locales.ts'
|
||||
import { invalidateGitStatus } from '../src/client/ui/git-status.ts'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
import type { FileViewerProps } from '../src/client/service.ts'
|
||||
|
||||
setupReactAct()
|
||||
|
||||
/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */
|
||||
class FakeLocale {
|
||||
active: string = 'en'
|
||||
getSnapshot(): { active: string } { return { active: this.active } }
|
||||
subscribe(_fn: () => void): () => void { return () => {} }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
attachLocale(new FakeLocale())
|
||||
gitStatus.mockReset()
|
||||
gitDiffHead.mockReset()
|
||||
gitBlame.mockReset()
|
||||
gitStatus.mockResolvedValue({ isRepo: false, entries: [], repositories: [] })
|
||||
gitDiffHead.mockResolvedValue({ diff: '' })
|
||||
gitBlame.mockResolvedValue({ lines: [] })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
attachLocale(undefined)
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
/** One `git diff --no-color -U3` patch over `path`, exactly git's own frame. */
|
||||
function patch(path: string, hunks: string): string {
|
||||
return [
|
||||
`diff --git a/${path} b/${path}`,
|
||||
'index 1111111..2222222 100644',
|
||||
`--- a/${path}`,
|
||||
`+++ b/${path}`,
|
||||
hunks,
|
||||
].join('\n') + '\n'
|
||||
}
|
||||
|
||||
/** The mapping as a sorted array, for readable assertions. */
|
||||
function entries(kinds: Map<number, GitLineKind>): Array<[number, GitLineKind]> {
|
||||
return [...kinds.entries()].sort((left, right) => left[0] - right[0])
|
||||
}
|
||||
|
||||
describe('git diff → changed lines', () => {
|
||||
it('marks added lines and leaves every context line alone', () => {
|
||||
const diff = patch('src/a.ts', [
|
||||
'@@ -1,4 +1,6 @@',
|
||||
' const one = 1',
|
||||
' const two = 2',
|
||||
'+const three = 3',
|
||||
'+const four = 4',
|
||||
' const five = 5',
|
||||
' const six = 6',
|
||||
].join('\n'))
|
||||
expect(entries(gitLineKinds(diff))).toEqual([[3, 'add'], [4, 'add']])
|
||||
})
|
||||
|
||||
it('marks a rewritten line as modified — once, not as a delete plus an add', () => {
|
||||
const diff = patch('src/a.ts', [
|
||||
'@@ -1,3 +1,3 @@',
|
||||
' const one = 1',
|
||||
'-const two = 2',
|
||||
'+const TWO = 2',
|
||||
' const three = 3',
|
||||
].join('\n'))
|
||||
// The deleted half of the pair carries no worktree line of its own, so the
|
||||
// buffer sees ONE modified row — no stray deletion bar on the line above.
|
||||
expect(entries(gitLineKinds(diff))).toEqual([[2, 'mod']])
|
||||
})
|
||||
|
||||
it('anchors a pure deletion to the line above the gap', () => {
|
||||
const diff = patch('src/a.ts', [
|
||||
'@@ -1,6 +1,4 @@',
|
||||
' const one = 1',
|
||||
' const two = 2',
|
||||
'-const gone = 3',
|
||||
'-const alsoGone = 4',
|
||||
' const five = 5',
|
||||
' const six = 6',
|
||||
].join('\n'))
|
||||
expect(entries(gitLineKinds(diff))).toEqual([[2, 'del']])
|
||||
})
|
||||
|
||||
it('anchors a deletion at the head of the file to line 1', () => {
|
||||
const diff = patch('src/a.ts', [
|
||||
'@@ -1,4 +1,2 @@',
|
||||
'-const first = 1',
|
||||
'-const second = 2',
|
||||
' const third = 3',
|
||||
' const fourth = 4',
|
||||
].join('\n'))
|
||||
expect(entries(gitLineKinds(diff))).toEqual([[1, 'del']])
|
||||
})
|
||||
|
||||
it('keeps a mixed hunk straight: add, mod and del on their own lines', () => {
|
||||
const diff = patch('src/a.ts', [
|
||||
'@@ -1,6 +1,7 @@',
|
||||
' const one = 1',
|
||||
'+const inserted = 2',
|
||||
' const three = 3',
|
||||
'-const four = 4',
|
||||
'+const FOUR = 4',
|
||||
' const five = 5',
|
||||
'-const six = 6',
|
||||
' const seven = 7',
|
||||
].join('\n'))
|
||||
expect(entries(gitLineKinds(diff))).toEqual([
|
||||
[2, 'add'],
|
||||
[4, 'mod'],
|
||||
// The unpaired deletion follows the rewritten line, so it anchors to the
|
||||
// line ABOVE the gap in the NEW numbering (5 is `const five = 5`).
|
||||
[5, 'del'],
|
||||
])
|
||||
})
|
||||
|
||||
it('returns nothing for an empty patch, and nothing for a mode-only change', () => {
|
||||
expect(entries(gitLineKinds(''))).toEqual([])
|
||||
const modeOnly = [
|
||||
'diff --git a/src/a.ts b/src/a.ts',
|
||||
'old mode 100644',
|
||||
'new mode 100755',
|
||||
'',
|
||||
].join('\n')
|
||||
expect(entries(gitLineKinds(modeOnly))).toEqual([])
|
||||
})
|
||||
|
||||
it('marks every line of an untracked file as added', () => {
|
||||
expect(entries(addedLineKinds(3))).toEqual([[1, 'add'], [2, 'add'], [3, 'add']])
|
||||
expect(entries(addedLineKinds(0))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('the gutter gate (setting off / other viewers)', () => {
|
||||
it('installs no extension at all when the feature is off', () => {
|
||||
expect(gitGutterExtensions(null)).toEqual([])
|
||||
expect(gitGutterExtensions({ scope: { sessionId: 's1', cwd: '/p' }, path: '/p/a.ts' }).length)
|
||||
.toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('every class the gutter hands to CodeMirror names a real stylesheet rule', () => {
|
||||
// These class names are strings passed to CodeMirror, so a typo would
|
||||
// silently paint nothing (theme.spec only scans the sheets themselves).
|
||||
const sheet = readFileSync(resolve(import.meta.dirname, '../src/client/sidebar.module.css'), 'utf8')
|
||||
for (const source of [
|
||||
'editorGitAdd', 'editorGitMod', 'editorGitDel', 'editorGitBarGutter',
|
||||
'editorGitBar', 'editorGitBarSpacer', 'editorGitBarAdd', 'editorGitBarMod', 'editorGitBarDel',
|
||||
'editorBlame', 'editorBlameHead', 'editorBlameSummary',
|
||||
]) {
|
||||
expect(sheet, source).toContain(`.${source}`)
|
||||
}
|
||||
for (const cls of Object.values(GIT_LINE_CLASS)) expect(cls).not.toBe('')
|
||||
})
|
||||
|
||||
it('applies a change set to an equipped view and is a no-op on a bare one', () => {
|
||||
const host = document.createElement('div')
|
||||
document.body.append(host)
|
||||
const equipped = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: 'one\ntwo\nthree\n',
|
||||
extensions: gitGutterExtensions({ scope: { sessionId: 's1', cwd: '/p' }, path: '/p/a.ts' }),
|
||||
}),
|
||||
parent: host,
|
||||
})
|
||||
const bare = new EditorView({ state: EditorState.create({ doc: 'one\n' }), parent: host })
|
||||
try {
|
||||
const kinds = gitLineKinds(patch('a.ts', '@@ -1,1 +1,3 @@\n one\n+two\n+three\n'))
|
||||
expect(() => { applyGitLineKinds(equipped, kinds) }).not.toThrow()
|
||||
// No gutter field in the state: the effect is dropped, not fatal.
|
||||
expect(() => { applyGitLineKinds(bare, kinds) }).not.toThrow()
|
||||
} finally {
|
||||
equipped.destroy()
|
||||
bare.destroy()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('blame memo (hover only)', () => {
|
||||
const scope = { sessionId: 's1', cwd: '/p' }
|
||||
|
||||
it('asks git once per line and never prefetches a neighbour', async () => {
|
||||
gitBlame.mockResolvedValue({
|
||||
lines: [{ line: 7, hash: 'a'.repeat(40), author: 'Ada', date: '2024-01-01T10:00:00+08:00', summary: 'feat: x' }],
|
||||
})
|
||||
const first = await loadBlameLine(scope, '/p/a.ts', 7)
|
||||
const second = await loadBlameLine(scope, '/p/a.ts', 7)
|
||||
expect(gitBlame).toHaveBeenCalledTimes(1)
|
||||
expect(gitBlame).toHaveBeenCalledWith(scope, '/p/a.ts', 7, 7)
|
||||
expect(second).toBe(first)
|
||||
expect(second?.author).toBe('Ada')
|
||||
// A different line is a different range — the file is never read ahead.
|
||||
await loadBlameLine(scope, '/p/a.ts', 8)
|
||||
expect(gitBlame).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('answers null — never throws — when git has no blame for the line', async () => {
|
||||
gitBlame.mockRejectedValue(new Error('git exited with 128'))
|
||||
await expect(loadBlameLine(scope, '/p/untracked.ts', 1)).resolves.toBeNull()
|
||||
gitBlame.mockResolvedValue({ lines: [] })
|
||||
await expect(loadBlameLine(scope, '/p/untracked.ts', 2)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('drops one file\u2019s memo when its change set is recomputed', async () => {
|
||||
await loadBlameLine(scope, '/p/a.ts', 1)
|
||||
await loadBlameLine(scope, '/p/b.ts', 1)
|
||||
forgetBlame('s1', '/p/a.ts')
|
||||
await loadBlameLine(scope, '/p/a.ts', 1)
|
||||
await loadBlameLine(scope, '/p/b.ts', 1)
|
||||
expect(gitBlame.mock.calls.filter(call => call[1] === '/p/a.ts')).toHaveLength(2)
|
||||
expect(gitBlame.mock.calls.filter(call => call[1] === '/p/b.ts')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('TextEditor wiring (code viewer only, one switch)', () => {
|
||||
function viewerProps(overrides: Partial<FileViewerProps> = {}): FileViewerProps {
|
||||
return {
|
||||
ctx: {} as FileViewerProps['ctx'],
|
||||
store: createSidebarStore(),
|
||||
scope: { sessionId: 's1', cwd: '/p' },
|
||||
path: '/p/a.ts',
|
||||
title: 'a.ts',
|
||||
viewerId: 'code',
|
||||
content: 'one\ntwo\nthree\n',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const MODIFIED: GitStatusResult = { isRepo: true, root: '/p', entries: [{ path: 'a.ts', xy: ' M' }] }
|
||||
|
||||
it('installs the gutter for the code viewer (default on)', async () => {
|
||||
gitStatus.mockResolvedValue(MODIFIED)
|
||||
gitDiffHead.mockResolvedValue({ diff: patch('a.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') })
|
||||
const mounted = renderRoot(createElement(TextEditor, viewerProps()))
|
||||
try {
|
||||
// The bar is a real CodeMirror gutter: its wrapper element exists as
|
||||
// soon as the extension is installed, changed lines or not.
|
||||
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).not.toBeNull()
|
||||
expect(mounted.container.querySelector('.cm-gutters')).not.toBeNull()
|
||||
} finally {
|
||||
mounted.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('produces no decoration at all when the setting is off', async () => {
|
||||
const store = createSidebarStore()
|
||||
store.setPrefs({ ...store.getPrefs(), editorGitGutter: false })
|
||||
gitStatus.mockResolvedValue(MODIFIED)
|
||||
gitDiffHead.mockResolvedValue({ diff: patch('a.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') })
|
||||
// A SECOND editor on the same session keeps the shared status store live
|
||||
// (exactly what the file tree does in the merged editor), so the gate
|
||||
// under test is this editor's own — not an idle store. The forced refresh
|
||||
// is what makes the shared snapshot's arrival deterministic.
|
||||
const live = renderRoot(createElement(TextEditor, viewerProps()))
|
||||
const off = renderRoot(createElement(TextEditor, viewerProps({ store })))
|
||||
try {
|
||||
await act(async () => {
|
||||
invalidateGitStatus('s1')
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
// Only the ENABLED editor ever asked for the change set.
|
||||
expect(gitDiffHead).toHaveBeenCalledTimes(1)
|
||||
expect(off.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).toBeNull()
|
||||
// The line-number gutter is still there — only OUR decoration is gone.
|
||||
expect(off.container.querySelector('.cm-gutters')).not.toBeNull()
|
||||
// The enabled editor on the same session DID get its gutter.
|
||||
expect(live.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).not.toBeNull()
|
||||
} finally {
|
||||
off.unmount()
|
||||
live.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('leaves the markdown viewer alone (the feature is code-only)', () => {
|
||||
const mounted = renderRoot(createElement(TextEditor, viewerProps({ viewerId: 'markdown' })))
|
||||
try {
|
||||
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).toBeNull()
|
||||
} finally {
|
||||
mounted.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops the gutter in place when the setting is switched off mid-session', () => {
|
||||
const store = createSidebarStore()
|
||||
const mounted = renderRoot(createElement(TextEditor, viewerProps({ store })))
|
||||
try {
|
||||
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).not.toBeNull()
|
||||
// The pref read is an external store: flipping it re-renders the editor
|
||||
// and the compartment swap removes the gutter — no reopen needed.
|
||||
act(() => { store.setPrefs({ ...store.getPrefs(), editorGitGutter: false }) })
|
||||
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).toBeNull()
|
||||
act(() => { store.setPrefs({ ...store.getPrefs(), editorGitGutter: true }) })
|
||||
expect(mounted.container.querySelector(`.${GIT_BAR_GUTTER_CLASS}`)).not.toBeNull()
|
||||
} finally {
|
||||
mounted.unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* `git blame` for the editor's hover tooltip (issue #212) and `git diff HEAD`
|
||||
* for its change gutter — both exercised against the REAL git binary, because
|
||||
* the failure paths are the interesting half: an untracked file, a directory
|
||||
* outside any repository, and a path git cannot resolve must all answer with
|
||||
* an empty result instead of an exception (the hover tooltip then shows
|
||||
* nothing and the editing surface is never disturbed).
|
||||
*
|
||||
* The porcelain parser is additionally pinned on output captured from a real
|
||||
* run, which is where the two shapes that matter come from: an UNCOMMITTED
|
||||
* line (all-zero hash, "Not Committed Yet") and the SECOND line of one commit,
|
||||
* for which git emits only the header and the content line — the author,
|
||||
* time and summary must be carried forward from the first line of that commit.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { blame, diff, diffHead, parseBlamePorcelain } from '../src/git.ts'
|
||||
import { gitLineKinds } from '../src/client/editor-git-gutter.ts'
|
||||
|
||||
const created: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of created.splice(0)) rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
/** A fresh temporary directory (removed after the test). */
|
||||
function tempDir(prefix: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), prefix))
|
||||
created.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
/** A temporary repository with one committed file, deterministic identity. */
|
||||
function repo(files: Record<string, string>): string {
|
||||
const root = tempDir('dsh-better-sidebar-blame-')
|
||||
const git = (...args: string[]): string =>
|
||||
execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' })
|
||||
git('init', '-q')
|
||||
git('config', 'user.email', 'ada@example.com')
|
||||
git('config', 'user.name', 'Ada')
|
||||
for (const [name, content] of Object.entries(files)) {
|
||||
writeFileSync(join(root, name), content)
|
||||
git('add', '--', name)
|
||||
}
|
||||
execFileSync('git', ['-C', root, 'commit', '-q', '-m', 'feat: add files'], {
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_AUTHOR_DATE: '2024-01-02T03:04:05+0800',
|
||||
GIT_COMMITTER_DATE: '2024-01-02T03:04:05+0800',
|
||||
},
|
||||
})
|
||||
return root
|
||||
}
|
||||
|
||||
/** `git blame --porcelain -L 1,3 -- a.txt` captured from a real run: line 1 is
|
||||
* a worktree edit, lines 2 and 3 are one commit (line 3 abbreviated). */
|
||||
const REAL_PORCELAIN = [
|
||||
'0000000000000000000000000000000000000000 1 1 1',
|
||||
'author Not Committed Yet',
|
||||
'author-mail <not.committed.yet>',
|
||||
'author-time 1704136000',
|
||||
'author-tz +0800',
|
||||
'committer Not Committed Yet',
|
||||
'committer-mail <not.committed.yet>',
|
||||
'committer-time 1704136000',
|
||||
'committer-tz +0800',
|
||||
'summary Version of a.txt from a.txt',
|
||||
'previous 9433ffd0f069d4c3d8c31f4ba81ac2ec99a266df a.txt',
|
||||
'filename a.txt',
|
||||
'\tONE',
|
||||
'9433ffd0f069d4c3d8c31f4ba81ac2ec99a266df 2 2 2',
|
||||
'author Ada',
|
||||
'author-mail <ada@example.com>',
|
||||
'author-time 1704135845',
|
||||
'author-tz +0800',
|
||||
'committer Ada',
|
||||
'committer-mail <ada@example.com>',
|
||||
'committer-time 1704135845',
|
||||
'committer-tz +0800',
|
||||
'summary feat: add a',
|
||||
'boundary',
|
||||
'filename a.txt',
|
||||
'\ttwo',
|
||||
'9433ffd0f069d4c3d8c31f4ba81ac2ec99a266df 3 3',
|
||||
'\tthree',
|
||||
'',
|
||||
].join('\n')
|
||||
|
||||
describe('git blame --porcelain parsing', () => {
|
||||
it('reads one row per line, with the author, the offset-stamped date and the summary', () => {
|
||||
const rows = parseBlamePorcelain(REAL_PORCELAIN)
|
||||
expect(rows.map(row => row.line)).toEqual([1, 2, 3])
|
||||
expect(rows[1]).toEqual({
|
||||
line: 2,
|
||||
hash: '9433ffd0f069d4c3d8c31f4ba81ac2ec99a266df',
|
||||
author: 'Ada',
|
||||
// Epoch 1704135845 is 2024-01-02T03:04:05+08:00 — the AUTHOR's zone, so
|
||||
// the value does not drift with the machine's timezone.
|
||||
date: '2024-01-02T03:04:05+08:00',
|
||||
summary: 'feat: add a',
|
||||
})
|
||||
})
|
||||
|
||||
it('carries the commit metadata forward for the abbreviated repeat', () => {
|
||||
// git emits only `<hash> <orig> <final>` for the 2nd+ line of one commit.
|
||||
const rows = parseBlamePorcelain(REAL_PORCELAIN)
|
||||
expect(rows[2]).toMatchObject({ line: 3, author: 'Ada', summary: 'feat: add a', date: '2024-01-02T03:04:05+08:00' })
|
||||
})
|
||||
|
||||
it('keeps git\u2019s uncommitted placeholder honest (all-zero hash)', () => {
|
||||
const [first] = parseBlamePorcelain(REAL_PORCELAIN)
|
||||
expect(first).toMatchObject({
|
||||
line: 1,
|
||||
hash: '0'.repeat(40),
|
||||
author: 'Not Committed Yet',
|
||||
summary: 'Version of a.txt from a.txt',
|
||||
date: '2024-01-02T03:06:40+08:00',
|
||||
})
|
||||
})
|
||||
|
||||
it('is empty for empty output and never throws on unknown framing', () => {
|
||||
expect(parseBlamePorcelain('')).toEqual([])
|
||||
expect(parseBlamePorcelain('fatal: no such path\n')).toEqual([])
|
||||
expect(parseBlamePorcelain('author Ada\n\tloose content\n')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('blame() against the real git binary', () => {
|
||||
it('blames a committed line range', async () => {
|
||||
const root = repo({ 'a.txt': 'one\ntwo\nthree\n' })
|
||||
const rows = await blame(root, join(root, 'a.txt'), 2, 3)
|
||||
expect(rows.map(row => row.line)).toEqual([2, 3])
|
||||
for (const row of rows) {
|
||||
expect(row.author).toBe('Ada')
|
||||
expect(row.summary).toBe('feat: add files')
|
||||
expect(row.hash).toMatch(/^[0-9a-f]{40}$/)
|
||||
expect(row.hash).not.toMatch(/^0+$/)
|
||||
// The commit was authored at 2024-01-02T03:04:05+0800.
|
||||
expect(row.date).toBe('2024-01-02T03:04:05+08:00')
|
||||
}
|
||||
})
|
||||
|
||||
it('answers empty for an untracked file (git exits 128)', async () => {
|
||||
const root = repo({ 'a.txt': 'one\n' })
|
||||
writeFileSync(join(root, 'fresh.txt'), 'brand new\n')
|
||||
await expect(blame(root, join(root, 'fresh.txt'), 1, 1)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('answers empty outside any repository', async () => {
|
||||
const dir = tempDir('dsh-better-sidebar-norepo-')
|
||||
writeFileSync(join(dir, 'a.txt'), 'one\n')
|
||||
await expect(blame(dir, join(dir, 'a.txt'), 1, 1)).resolves.toEqual([])
|
||||
})
|
||||
|
||||
it('answers empty when the path itself does not resolve', async () => {
|
||||
const root = repo({ 'a.txt': 'one\n' })
|
||||
await expect(blame(root, join(root, 'missing.txt'), 1, 1)).resolves.toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('diffHead() (the editor gutter\u2019s change source)', () => {
|
||||
it('reports BOTH sides of a partly staged file, which the two-sided diff() splits', async () => {
|
||||
const root = repo({ 'a.txt': 'one\ntwo\nthree\n' })
|
||||
writeFileSync(join(root, 'a.txt'), 'ONE\ntwo\nthree\n')
|
||||
execFileSync('git', ['-C', root, 'add', '--', 'a.txt'])
|
||||
writeFileSync(join(root, 'a.txt'), 'ONE\nTWO\nthree\n')
|
||||
|
||||
const [unstaged, staged] = await Promise.all([
|
||||
diff(root, 'a.txt', false),
|
||||
diff(root, 'a.txt', true),
|
||||
])
|
||||
// Each side alone misses half of the file's uncommitted change.
|
||||
expect(unstaged).toContain('+TWO')
|
||||
expect(unstaged).not.toContain('+ONE')
|
||||
expect(staged).toContain('+ONE')
|
||||
expect(staged).not.toContain('+TWO')
|
||||
|
||||
const union = await diffHead(root, join(root, 'a.txt'))
|
||||
expect(union).toContain('-one')
|
||||
expect(union).toContain('+ONE')
|
||||
expect(union).toContain('-two')
|
||||
expect(union).toContain('+TWO')
|
||||
})
|
||||
|
||||
it('returns nothing for a clean file', async () => {
|
||||
const root = repo({ 'a.txt': 'one\ntwo\nthree\n' })
|
||||
await expect(diffHead(root, 'a.txt')).resolves.toBe('')
|
||||
await expect(diffHead(root, join(root, 'a.txt'))).resolves.toBe('')
|
||||
})
|
||||
|
||||
it('falls back to the index when HEAD is not born yet', async () => {
|
||||
const dir = tempDir('dsh-better-sidebar-unborn-')
|
||||
execFileSync('git', ['-C', dir, 'init', '-q'])
|
||||
writeFileSync(join(dir, 'n.txt'), 'n\n')
|
||||
execFileSync('git', ['-C', dir, 'add', '--', 'n.txt'])
|
||||
// `git diff HEAD` cannot answer here (bad revision); the index against the
|
||||
// empty tree is the unborn-HEAD shape of the same question.
|
||||
const patch = await diffHead(dir, join(dir, 'n.txt'))
|
||||
expect(patch).toContain('new file mode')
|
||||
expect(patch).toContain('+n')
|
||||
})
|
||||
|
||||
it('never reports an untracked file (the status store marks those)', async () => {
|
||||
const root = repo({ 'a.txt': 'one\n' })
|
||||
writeFileSync(join(root, 'fresh.txt'), 'brand new\n')
|
||||
await expect(diffHead(root, join(root, 'fresh.txt'))).resolves.toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('real git output → gutter line classes (end to end)', () => {
|
||||
it('maps a real partly staged patch onto the worktree lines', async () => {
|
||||
// The parser fixtures above are hand-written; this one runs the real
|
||||
// binary so the hunk framing, the pairing and the "context is untouched"
|
||||
// rule are pinned against git itself, not against my idea of git.
|
||||
const root = repo({ 'a.txt': 'one\ntwo\nthree\n' })
|
||||
writeFileSync(join(root, 'a.txt'), 'ONE\ntwo\nthree\n')
|
||||
execFileSync('git', ['-C', root, 'add', '--', 'a.txt'])
|
||||
writeFileSync(join(root, 'a.txt'), 'ONE\nTWO\nthree\n')
|
||||
|
||||
const kinds = gitLineKinds(await diffHead(root, join(root, 'a.txt')))
|
||||
expect([...kinds.entries()].sort((left, right) => left[0] - right[0]))
|
||||
.toEqual([[1, 'mod'], [2, 'mod']])
|
||||
})
|
||||
|
||||
it('maps a real deletion onto the line above the gap', async () => {
|
||||
const root = repo({ 'a.txt': 'one\ntwo\nthree\nfour\n' })
|
||||
writeFileSync(join(root, 'a.txt'), 'one\nthree\nfour\n')
|
||||
const kinds = gitLineKinds(await diffHead(root, join(root, 'a.txt')))
|
||||
expect([...kinds.entries()]).toEqual([[1, 'del']])
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,7 @@ describe('side card preferences', () => {
|
||||
mobileDefaultTree: true,
|
||||
agentOpenTools: true,
|
||||
editorExplorer: false,
|
||||
editorGitGutter: true,
|
||||
explorerExclude: ['.DS_Store', 'Thumbs.db'],
|
||||
titleBarScheme: 'auto',
|
||||
titleBarPresetId: '',
|
||||
@@ -63,6 +64,7 @@ describe('side card preferences', () => {
|
||||
mobileDefaultTree: true,
|
||||
agentOpenTools: false,
|
||||
editorExplorer: false,
|
||||
editorGitGutter: true,
|
||||
explorerExclude: ['.DS_Store', 'Thumbs.db'],
|
||||
titleBarScheme: 'auto',
|
||||
titleBarPresetId: '',
|
||||
@@ -87,6 +89,7 @@ describe('side card preferences', () => {
|
||||
mobileDefaultTree: true,
|
||||
agentOpenTools: false,
|
||||
editorExplorer: false,
|
||||
editorGitGutter: true,
|
||||
explorerExclude: ['.DS_Store', 'Thumbs.db'],
|
||||
titleBarScheme: 'auto',
|
||||
titleBarPresetId: '',
|
||||
|
||||
@@ -23,7 +23,9 @@ vi.mock('../src/client/api.ts', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
|
||||
return {
|
||||
...actual,
|
||||
api: { fsWrite: (...args: unknown[]) => fsWrite(...args) },
|
||||
// The real api object with only the save call replaced: TextEditor also
|
||||
// reads the shared git status store in the code viewer.
|
||||
api: { ...actual.api, fsWrite: (...args: unknown[]) => fsWrite(...args) },
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user