From 56e89c726e18a157a1afa20a055a891c3a41c0d3 Mon Sep 17 00:00:00 2001 From: yansfil Date: Sat, 19 Sep 2026 12:45:10 +0900 Subject: [PATCH 1/5] Add PRD: editor preview tab (VS Code model) --- agents/prd/editor-preview-tab/prd.md | 86 ++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 agents/prd/editor-preview-tab/prd.md diff --git a/agents/prd/editor-preview-tab/prd.md b/agents/prd/editor-preview-tab/prd.md new file mode 100644 index 0000000000..aba24972be --- /dev/null +++ b/agents/prd/editor-preview-tab/prd.md @@ -0,0 +1,86 @@ +--- +topic: "Editor preview tab (VS Code 방식)" +status: "ready" +human_approval: "approved" # user 2026-09-19 verbatim: 승인, 그대로 진행해 +review_profile: "standard" +review_rationale: "A user-visible change to how the editor tab strip opens and replaces file and diff tabs, with no persisted data, credentials, or external effect beyond the pull request." +source_intake: "current conversation" +created_at: "2026-09-19" +updated_at: "2026-09-19" +--- + +# PRD: Editor preview tab (VS Code 방식) + +## Goal + +Hide에서 Explorer의 파일을 한 번 클릭할 때마다 영구 탭이 하나씩 쌓여, 파일을 훑어보기만 해도 탭 스트립이 금방 가득 찬다(`open_file_tab`은 파일마다 탭을 push한다). +VS Code의 preview tab 모델을 그대로 들여온다: 한 번 클릭은 체크아웃당 하나뿐인 교체형 미리보기 탭(기울임꼴 제목)을 열고, 더블클릭·편집·명시적 Keep Open이 그 탭을 일반 탭으로 승격하며, 수정된 탭은 절대 교체되지 않는다. +사용자는 파일을 아무리 훑어봐도 탭이 늘지 않고, 계속 볼 파일만 의도적으로 남긴다. + +## Non-goals + +- preview를 끄는 설정 토글(VS Code `workbench.editor.enablePreview`): v1은 항상 켜져 있다. 끄고 싶은 사용자가 나타나면 재검토 (D-08). +- JetBrains식 탭 개수 상한·LRU 자동 닫기, Sublime식 "탭 없는 transient 뷰": VS Code 모델을 골랐으므로 채택하지 않는다 (D-01). +- Recent Panels 전환기와 Explorer 행에 기울임꼴을 확장하는 것: preview 표시는 탭 스트립에서만 한다. 스트립 밖에서 preview 여부를 구별해야 하는 요구가 생기면 재검토 (D-06). +- 편집기 탭의 앱 재시작 복원: 편집기 탭은 지금처럼 ephemeral이며, preview 상태를 저장할 곳이 없다 (D-07). +- 원격 체크아웃: 원격 컨텍스트에는 파일 탭이 없으므로(`rebuild_tab_strips`) 대상이 아니다. +- `design/principles.md` 5(기존 패턴을 따른다)는 이 PRD가 새 UI 패턴을 만들지 않고 스트립·툴팁·아이콘 버튼의 기존 컴포넌트만 쓰는 것으로 만족하며, 관찰 가능한 행으로 따로 두지 않는다 (D-14). + +## Decisions + +| D-n | 결정 | 근거 | +| --- | --- | --- | +| D-01 | VS Code의 preview tab 모델을 채택한다: 한 번 클릭 = 교체형 preview 탭, 더블클릭·편집·Keep Open = 승격. JetBrains(탭 상한), Sublime(transient 뷰), Xcode(현재 탭 교체) 모델은 기각. | 사용자 "VS Code 방식으로 PRD 잡아줘" (2026-09-19); 네 모델 비교는 같은 대화의 앞 턴 | +| D-02 | preview 탭은 체크아웃당 정확히 하나이고, 파일 탭과 diff 탭이 같은 슬롯을 공유한다. Changes 패널의 한 번 클릭도 preview diff 탭을 연다. | 사용자 "one per checkout"; 가정: 스트립이 파일·diff를 한 줄에 섞어 그리므로 diff만 영구로 쌓이면 문제가 그대로 남는다. VS Code SCM 뷰의 diff도 preview로 열린다 | +| D-03 | 승격 트리거는 네 가지: Explorer 행 더블클릭, 탭 제목 더블클릭, 첫 draft 변경(편집), 메뉴 명령 Keep Open. 탭을 드래그해 순서를 바꾸는 것도 승격한다. | 사용자 "double-click, edit, or explicit keep promotes it"; 드래그 승격은 VS Code와 같은 동작을 유지하려는 가정 | +| D-04 | 교체는 제자리에서 일어난다: 새 preview 탭은 기존 preview 탭의 스트립 슬롯을 물려받고, 교체된 탭의 문서·Markdown 모드·wrap 상태는 버려진다. 교체된 preview 탭은 Recent Closed에 기록하지 않는다. | VS Code와 같은 동작; 가정: 훑어본 파일마다 Recent Closed에 남기면 목록이 사용자가 닫은 탭이 아닌 것으로 채워진다 | +| D-05 | 수정된(dirty) 탭은 어떤 경우에도 교체되지 않는다. 첫 draft 변경이 승격이므로 정상 경로에서 dirty preview는 생기지 않지만, 코어는 교체 전에 dirty를 검사하고 dirty면 승격 후 새 preview를 옆에 연다. | 사용자 "dirty tabs never replaced"; `engineering/principles.md` 4(잘못된 상태를 조용히 넘기지 않는다) | +| D-06 | preview 탭은 탭 스트립에서 제목을 기울임꼴로 그린다. 기울임꼴 폰트 변형은 `HideTheme`에 토큰으로 추가하고 인라인 값은 쓰지 않는다. 툴팁과 접근성 라벨에는 "Preview"를 덧붙인다. | 사용자 "italic label"; `AGENTS.md` Design Reference(새 값은 HideTheme에 먼저) | +| D-07 | preview 여부는 코어가 소유한다: `EditorTabSnapshot`과 스트립 항목에 `preview` 플래그를 두고, 셸은 `file_open`/`changes_select`에 preview 요청 여부를, 승격은 새 이벤트 하나로 보낸다. 교체·승격 판단은 코어 안에서만 한다. 영속 UI 상태에는 넣지 않는다. | `docs/ARCHITECTURE.md` "코어가 UI 상태를 소유하고 셸은 권한이 없다"; `DESIGN.md` "편집기 탭은 ephemeral" | +| D-08 | preview를 끄는 설정은 두지 않는다. | `engineering/principles.md` 2(현재 요구를 충족하는 가장 단순한 구현), 7(기존 것에 기댄다) | +| D-09 | Explorer 한 번 클릭 외의 진입점(Cmd+P 파일 검색, Recent Closed 재열기, Markdown 상대 링크)은 영구 탭으로 연다. | VS Code 기본값(`enablePreviewFromQuickOpen`, `enablePreviewFromCodeNavigation` 모두 false); 가정: 검색해 찾아간 파일은 의도적으로 연 파일이다 | +| D-10 | 이미 영구 탭으로 열린 파일을 한 번 클릭하면 그 탭을 포커스만 하고 preview를 만들지 않는다. 현재 preview인 파일을 한 번 클릭하면 포커스만 한다. | VS Code와 같은 동작; 한 파일이 두 탭으로 열리지 않는다는 기존 `prepare_file_tab` 규칙 유지 | +| D-11 | 코어 규칙(교체·승격·dirty 거부·슬롯 상속·Recent Closed 제외)은 Rust 런타임 테스트로, 스트립의 기울임꼴·툴팁은 Swift 프레젠테이션 테스트로 고정한다. | `agents/config.json`의 `verify-cargo.sh`/`verify-swift.sh`; `engineering/principles.md` 12 | +| D-12 | Delivery: hide의 sasu PR 모드(`agents/config.json`: base `main`, worktree, CI watch)로 PR을 열고 사람이 머지한다. | `agents/config.json` `delivery.mode: pr` | +| D-13 | 설계 캔버스: `design/hide.pen`에 `Screen / Workbench / Preview tab` 보드를 preview·승격·dirty 세 상태로 그리고, 기울임꼴 토큰을 `scripts/pen-token-map.json`에 매핑한 뒤 구현을 시작한다. | `AGENTS.md` The Design Canvas("PRD가 바꾸는 화면을 Screen 보드로 먼저 그린다") | +| D-14 | Principles intake: `~/projects/oh-my-principle` `fa5186d`의 `engineering/principles.md`와 `design/principles.md`를 전부 읽었다. engineering 2·4·7·12, design 3·7·9는 위 결정과 행으로 번역했고, design 5는 non-goal로 뒀다. | `sasu principles list` 결과 | + +## Behaviors + +| # | 사용자가 관찰하는 행동 | 결정 | +| --- | --- | --- | +| B1 | Explorer에서 파일을 한 번 클릭하면 그 파일이 스트립 끝에 새 탭으로 열리고 활성화되며, 탭 제목이 기울임꼴이다. | D-01, D-02, D-06 | +| B2 | 같은 체크아웃에서 preview 탭이 열린 채 다른 파일을 한 번 클릭하면, 새 파일이 그 preview 탭의 슬롯을 제자리에서 물려받고 이전 파일은 스트립에서 사라진다. 탭 개수는 늘지 않는다. | D-02, D-04 | +| B3 | 체크아웃마다 preview 탭이 하나씩 따로 있다. 다른 체크아웃의 파일을 한 번 클릭해도 이 체크아웃의 preview 탭은 그대로다. | D-02 | +| B4 | Explorer에서 파일을 더블클릭하면 영구 탭(정체 제목)으로 열린다. 그 파일이 현재 preview 탭이면 같은 슬롯에서 제목만 정체로 바뀐다. | D-03 | +| B5 | preview 탭에서 첫 글자를 편집하면 그 프레임에서 제목이 정체가 되고 탭이 영구가 된다. 이후 다른 파일을 한 번 클릭하면 새 preview 탭이 옆에 열린다. | D-03, D-05 | +| B6 | 탭 제목을 더블클릭하거나 메뉴의 Keep Open을 실행하면 preview 탭이 제자리에서 영구 탭이 된다. 영구 탭에서는 두 동작 모두 아무것도 바꾸지 않는다. | D-03 | +| B7 | preview 탭을 드래그해 순서를 바꾸면 영구 탭이 된다. | D-03 | +| B8 | 어떤 경로로든 preview 탭이 dirty인 채로 다른 파일이 한 번 클릭되면, dirty 탭은 그대로 남아 영구가 되고 새 파일은 새 preview 탭으로 옆에 열린다. 편집 중인 내용은 사라지지 않는다. | D-05 | +| B9 | 이미 영구 탭으로 열린 파일을 한 번 클릭하면 그 탭이 포커스되고 preview 탭은 만들어지지도, 교체되지도 않는다. | D-10 | +| B10 | 현재 preview 탭인 파일을 한 번 더 클릭하면 포커스만 되고 탭은 그대로다. | D-10 | +| B11 | Cmd+P 파일 검색, Recent Closed 재열기, Markdown 미리보기의 상대 파일 링크로 연 파일은 영구 탭이다. | D-09 | +| B12 | Changes 패널에서 변경 파일을 한 번 클릭하면 preview diff 탭이 열리고, 같은 체크아웃의 preview 파일 탭이 있으면 그 슬롯을 물려받는다. 파일 탭과 diff 탭은 하나의 preview 슬롯을 나눠 쓴다. | D-02, D-04 | +| B13 | preview 탭을 닫기 버튼이나 Cmd+W로 닫으면 지금과 같이 Recent Closed에 기록되고, 이전 활성 탭으로 돌아간다. | D-04 | +| B14 | 다른 파일에 의해 교체된 preview 탭은 Recent Closed에 나타나지 않는다. | D-04 | +| B15 | 한 번 클릭한 파일을 읽을 수 없으면 지금과 같은 `file.open_failed` 오류가 보이고, 기존 preview 탭은 교체되지 않고 그대로 남는다. | D-04 | +| B16 | preview 탭의 툴팁과 접근성 라벨은 파일명에 "Preview"를 덧붙여 읽히고, 승격되면 그 접미사가 사라진다. | D-06 | +| B17 | preview 탭의 활성·비활성·hover 색과 닫기 버튼·단축키 힌트는 다른 탭과 같고, 기울임꼴만 다르다. | D-06 | +| B18 | preview 탭은 Recent Panels 전환기에 다른 파일 탭과 같은 모양으로 나열된다. | D-06 | +| B19 | 앱을 재시작하면 지금처럼 편집기 탭은 하나도 남지 않는다. | D-07 | +| B20 | preview 탭이 교체될 때 Explorer의 선택 강조는 새 파일로 옮겨 간다. | D-02 | + +## Technical structure + +코어가 preview 상태를 소유한다: `EditorTabSnapshot`과 `StripTabSnapshot`에 `preview` 플래그가 추가되고, `file_open`과 `changes_select` 이벤트가 preview 요청 여부를 실어 오며, 승격은 새 편집기 이벤트 하나로 들어온다. +교체·승격·dirty 거부는 모두 `Mutex` 안의 편집기 런타임에서 결정되고, 셸은 스냅샷을 그리기만 한다. +셸은 Explorer 아웃라인의 더블클릭 액션, 탭 제목 더블클릭, Keep Open 메뉴 명령(단축키 레지스트리에 등록)을 추가하고, `HideTheme`에 기울임꼴 폰트 토큰을 더한다. +Herdr 와이어 계약, 영속 UI 상태, 파일 저장 경로, Markdown 미리보기는 바뀌지 않는다. + +## Risks + +- AppKit `NSOutlineView`는 더블클릭의 첫 클릭에서 `action`을 먼저 보내므로 더블클릭은 항상 "preview로 열림 → 승격"의 두 프레임으로 보인다. VS Code도 같은 순서로 동작하므로 허용하되, 두 번째 프레임이 제목만 바꾸고 문서를 다시 읽지 않는지 확인한다. +- 편집 승격(B5)은 `file_draft`가 코어에 닿는 순간 일어난다. 셸이 draft를 debounce하면 그 사이 한 번 클릭이 들어올 수 있고, 그 경우 B8이 dirty 탭을 지킨다. 구현은 B8을 Rust 테스트로 고정한다. +- 기울임꼴은 `HideTheme` 토큰과 `hideFont` 경로로만 들어가야 `check-design-contract.mjs`를 통과한다. pen 캔버스는 JetBrains Mono/Inter 대체 글꼴이라 기울임꼴 형태는 정확하지 않으며, 크기와 간격만 검토 대상이다. +- 설계 보드(D-13)는 구현 시작 전에 `design/hide.pen`에 그려야 하고 `node scripts/check-pen.mjs`를 통과해야 한다. 아직 그리지 않았다. +- 사용자에게 필요한 사전 작업은 없다. From b69b5172ad5b801f6fc823e00c831efc00350a07 Mon Sep 17 00:00:00 2001 From: yansfil Date: Sat, 19 Sep 2026 12:54:45 +0900 Subject: [PATCH 2/5] Draw the editor preview tab board and add the italic chrome variant The Screen / Workbench / Preview tab board shows the preview, promoted and dirty-kept states. Inter's bundled face has no italic axis, so the variant is the same face slanted by HideTheme.Typography.previewSlant through the font matrix, reached through hideFont(italic:), and mapped to the canvas as --text-preview-slant. --- design/hide.pen | 677 +++++++++++++++++- .../Sources/HerdrMacOS/HideEnvironment.swift | 17 +- macos/Sources/HerdrMacOS/HideTheme.swift | 36 +- scripts/pen-token-map.json | 1 + 4 files changed, 699 insertions(+), 32 deletions(-) diff --git a/design/hide.pen b/design/hide.pen index 97523068f6..6d81cff548 100644 --- a/design/hide.pen +++ b/design/hide.pen @@ -11487,7 +11487,7 @@ "x": 0, "y": -100, "name": "Band / Screen", - "width": 24273, + "width": 25841, "layout": "vertical", "gap": "$--spacing-sm", "children": [ @@ -13956,9 +13956,632 @@ }, { "type": "frame", - "id": "arb009", + "id": "pvt-board", "x": 1320, "y": 0, + "name": "Screen / Workbench / Preview tab", + "width": 1488, + "fill": "$--color-background", + "layout": "vertical", + "gap": "$--spacing-lg", + "padding": "$--spacing-xl", + "children": [ + { + "type": "text", + "id": "pvt-title", + "name": "Title", + "fill": "$--color-primary", + "content": "Preview tab", + "fontFamily": "$--font-ui", + "fontSize": "$--text-headline", + "fontWeight": "normal", + "textGrowth": "fixed-width", + "width": "fill_container" + }, + { + "type": "text", + "id": "pvt-spec", + "name": "Spec", + "fill": "$--color-secondary", + "content": "One click in Explorer or Changes opens the file or diff in the checkout's one preview slot: the title is drawn in the theme's italic variant (--text-preview-slant, an oblique of the same Inter face; pen substitutes the family's own italic) and the tooltip and accessibility label read \"name · Preview\". The next single click replaces the slot in place. Double-click on the Explorer row or the title, the first edit, Keep Open (⇧⌘K) or a drag promotes the tab: the same slot, the title upright, nothing else changes. Colours, the close button and the keycap are the tab's ordinary ones (B17). A dirty preview is never replaced: it is promoted where it sits and the new preview opens beside it (B8).", + "fontFamily": "$--font-ui", + "fontSize": "$--text-subhead", + "fontWeight": "normal", + "textGrowth": "fixed-width", + "width": "fill_container" + }, + { + "type": "frame", + "id": "pvt-preview", + "name": "State / Preview", + "width": "fill_container", + "layout": "vertical", + "gap": "$--spacing-xs", + "children": [ + { + "type": "text", + "id": "pvt-preview-name", + "name": "State name", + "fill": "$--color-muted", + "content": "Preview", + "fontFamily": "$--font-ui", + "fontSize": "$--text-micro", + "fontWeight": "600" + }, + { + "type": "frame", + "id": "pvt-preview-strip", + "name": "Work tab strip", + "width": "fill_container", + "height": 32, + "fill": "$--color-panel", + "alignItems": "center", + "children": [ + { + "type": "frame", + "id": "pvt-p-work", + "name": "Tab 작업", + "width": 180, + "height": 32, + "fill": "$--color-panel", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-p-work-icon", + "name": "Type icon", + "library": "lucide", + "icon": "columns-2", + "width": 14, + "height": 14, + "fill": "$--color-secondary" + }, + { + "type": "text", + "id": "pvt-p-work-label", + "name": "Tab label", + "fill": "$--color-secondary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "작업", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "500" + }, + { + "id": "pvt-p-work-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-p-readme", + "name": "Tab README.md preview", + "width": 180, + "height": 32, + "fill": "$--color-elevated", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-p-readme-icon", + "name": "Type icon", + "library": "lucide", + "icon": "file-text", + "width": 14, + "height": 14, + "fill": "$--color-primary" + }, + { + "type": "text", + "id": "pvt-p-readme-label", + "name": "Tab label", + "fill": "$--color-primary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "README.md", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "600", + "fontStyle": "$--font-style-preview" + }, + { + "id": "pvt-p-readme-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-preview-strip-space", + "name": "Tab elastic space", + "width": "fill_container", + "height": 1 + }, + { + "id": "pvt-preview-strip-new", + "type": "ref", + "ref": "Nyvom", + "name": "New tab", + "descendants": { + "ZIZFR": { + "icon": "plus" + } + } + } + ] + }, + { + "type": "text", + "id": "pvt-preview-note", + "name": "State note", + "fill": "$--color-secondary", + "content": "Single click on README.md: a new tab at the end of the strip, active, italic title.", + "fontFamily": "$--font-ui", + "fontSize": "$--text-caption", + "fontWeight": "normal", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ] + }, + { + "type": "frame", + "id": "pvt-promoted", + "name": "State / Promoted", + "width": "fill_container", + "layout": "vertical", + "gap": "$--spacing-xs", + "children": [ + { + "type": "text", + "id": "pvt-promoted-name", + "name": "State name", + "fill": "$--color-muted", + "content": "Promoted", + "fontFamily": "$--font-ui", + "fontSize": "$--text-micro", + "fontWeight": "600" + }, + { + "type": "frame", + "id": "pvt-promoted-strip", + "name": "Work tab strip", + "width": "fill_container", + "height": 32, + "fill": "$--color-panel", + "alignItems": "center", + "children": [ + { + "type": "frame", + "id": "pvt-k-work", + "name": "Tab 작업", + "width": 180, + "height": 32, + "fill": "$--color-panel", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-k-work-icon", + "name": "Type icon", + "library": "lucide", + "icon": "columns-2", + "width": 14, + "height": 14, + "fill": "$--color-secondary" + }, + { + "type": "text", + "id": "pvt-k-work-label", + "name": "Tab label", + "fill": "$--color-secondary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "작업", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "500" + }, + { + "id": "pvt-k-work-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-k-readme", + "name": "Tab README.md", + "width": 180, + "height": 32, + "fill": "$--color-elevated", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-k-readme-icon", + "name": "Type icon", + "library": "lucide", + "icon": "file-text", + "width": 14, + "height": 14, + "fill": "$--color-primary" + }, + { + "type": "text", + "id": "pvt-k-readme-label", + "name": "Tab label", + "fill": "$--color-primary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "README.md", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "600" + }, + { + "id": "pvt-k-readme-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-promoted-strip-space", + "name": "Tab elastic space", + "width": "fill_container", + "height": 1 + }, + { + "id": "pvt-promoted-strip-new", + "type": "ref", + "ref": "Nyvom", + "name": "New tab", + "descendants": { + "ZIZFR": { + "icon": "plus" + } + } + } + ] + }, + { + "type": "text", + "id": "pvt-promoted-note", + "name": "State note", + "fill": "$--color-secondary", + "content": "Double-click, edit, Keep Open or drag: the title turns upright in the same slot.", + "fontFamily": "$--font-ui", + "fontSize": "$--text-caption", + "fontWeight": "normal", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ] + }, + { + "type": "frame", + "id": "pvt-dirty", + "name": "State / Dirty preview kept", + "width": "fill_container", + "layout": "vertical", + "gap": "$--spacing-xs", + "children": [ + { + "type": "text", + "id": "pvt-dirty-name", + "name": "State name", + "fill": "$--color-muted", + "content": "Dirty preview kept", + "fontFamily": "$--font-ui", + "fontSize": "$--text-micro", + "fontWeight": "600" + }, + { + "type": "frame", + "id": "pvt-dirty-strip", + "name": "Work tab strip", + "width": "fill_container", + "height": 32, + "fill": "$--color-panel", + "alignItems": "center", + "children": [ + { + "type": "frame", + "id": "pvt-d-work", + "name": "Tab 작업", + "width": 180, + "height": 32, + "fill": "$--color-panel", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-d-work-icon", + "name": "Type icon", + "library": "lucide", + "icon": "columns-2", + "width": 14, + "height": 14, + "fill": "$--color-secondary" + }, + { + "type": "text", + "id": "pvt-d-work-label", + "name": "Tab label", + "fill": "$--color-secondary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "작업", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "500" + }, + { + "id": "pvt-d-work-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-d-readme", + "name": "Tab README.md dirty", + "width": 180, + "height": 32, + "fill": "$--color-panel", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-d-readme-icon", + "name": "Type icon", + "library": "lucide", + "icon": "file-text", + "width": 14, + "height": 14, + "fill": "$--color-secondary" + }, + { + "type": "text", + "id": "pvt-d-readme-label", + "name": "Tab label", + "fill": "$--color-secondary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "README.md", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "500" + }, + { + "type": "ellipse", + "id": "pvt-d-readme-dirty", + "name": "Dirty dot 5", + "width": 5, + "height": 5, + "fill": "$--color-secondary" + }, + { + "id": "pvt-d-readme-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-d-notes", + "name": "Tab notes.md preview", + "width": 180, + "height": 32, + "fill": "$--color-elevated", + "gap": "$--spacing-sm", + "padding": [ + "$--spacing-none", + "$--spacing-sm", + "$--spacing-none", + "$--spacing-md" + ], + "alignItems": "center", + "stroke": "$--color-divider", + "strokeWidth": { + "right": "$--size-hairline" + }, + "strokeAlignment": "inner", + "children": [ + { + "type": "icon", + "id": "pvt-d-notes-icon", + "name": "Type icon", + "library": "lucide", + "icon": "file-text", + "width": 14, + "height": 14, + "fill": "$--color-primary" + }, + { + "type": "text", + "id": "pvt-d-notes-label", + "name": "Tab label", + "fill": "$--color-primary", + "textGrowth": "fixed-width", + "width": "fill_container", + "content": "notes.md", + "fontFamily": "$--font-ui", + "fontSize": "$--text-body", + "fontWeight": "600", + "fontStyle": "$--font-style-preview" + }, + { + "id": "pvt-d-notes-close", + "type": "ref", + "ref": "Nyvom", + "name": "Close tab", + "descendants": { + "ZIZFR": { + "icon": "x" + } + } + } + ] + }, + { + "type": "frame", + "id": "pvt-dirty-strip-space", + "name": "Tab elastic space", + "width": "fill_container", + "height": 1 + }, + { + "id": "pvt-dirty-strip-new", + "type": "ref", + "ref": "Nyvom", + "name": "New tab", + "descendants": { + "ZIZFR": { + "icon": "plus" + } + } + } + ] + }, + { + "type": "text", + "id": "pvt-dirty-note", + "name": "State note", + "fill": "$--color-secondary", + "content": "README.md was edited (promoted, dirty mark) when notes.md was clicked: notes.md opens as the new preview beside it.", + "fontFamily": "$--font-ui", + "fontSize": "$--text-caption", + "fontWeight": "normal", + "textGrowth": "fixed-width", + "width": "fill_container" + } + ] + } + ] + }, + { + "type": "frame", + "id": "arb009", + "x": 2888, + "y": 0, "name": "Screen / Sidebar / Agent row states", "clip": false, "width": 1240, @@ -14399,7 +15022,7 @@ { "type": "frame", "id": "arb00l", - "x": 2640, + "x": 4208, "y": 0, "name": "Screen / Pane / Header states", "clip": false, @@ -15153,7 +15776,7 @@ { "type": "frame", "id": "acv-main", - "x": 3960, + "x": 5528, "y": 0, "name": "Screen / Pane / Conversation - Main Claude working", "width": 760, @@ -15546,7 +16169,7 @@ { "type": "frame", "id": "acv-codex", - "x": 4800, + "x": 6368, "y": 0, "name": "Screen / Pane / Conversation - Codex idle", "width": 760, @@ -15862,7 +16485,7 @@ { "type": "frame", "id": "acv-terminal", - "x": 5640, + "x": 7208, "y": 0, "name": "Screen / Pane / Conversation - Terminal baseline", "width": 760, @@ -16054,7 +16677,7 @@ { "type": "frame", "id": "acv-needs-you", - "x": 6480, + "x": 8048, "y": 0, "name": "Screen / Pane / Conversation - Needs You fallback", "width": 760, @@ -16271,7 +16894,7 @@ { "type": "frame", "id": "acv-empty", - "x": 7320, + "x": 8888, "y": 0, "name": "Screen / Pane / Conversation - Empty", "width": 760, @@ -16447,7 +17070,7 @@ { "type": "frame", "id": "acv-failed", - "x": 8160, + "x": 9728, "y": 0, "name": "Screen / Pane / Conversation - Failed", "width": 760, @@ -17036,7 +17659,7 @@ "padding": "$--spacing-lg" } ], - "x": 9000, + "x": 10568, "y": 0 }, { @@ -17454,13 +18077,13 @@ ] } ], - "x": 10920, + "x": 12488, "y": 0 }, { "type": "frame", "id": "Snwg0", - "x": 12096, + "x": 13664, "y": 0, "name": "Screen / Agents / My Work status groups", "width": 1488, @@ -17828,7 +18451,7 @@ { "type": "frame", "id": "Vmhg4", - "x": 13664, + "x": 15232, "y": 0, "name": "Screen / Sidebar / Agents", "clip": true, @@ -19592,7 +20215,7 @@ { "type": "frame", "id": "i0UQT9", - "x": 14036, + "x": 15604, "y": 0, "name": "Screen / Panel / Overview", "clip": true, @@ -21070,7 +21693,7 @@ { "type": "frame", "id": "YfDhQ", - "x": 14471, + "x": 16039, "y": 0, "name": "Screen / Panel / Explorer", "clip": true, @@ -24429,7 +25052,7 @@ { "type": "frame", "id": "eXxKb", - "x": 14906, + "x": 16474, "y": 0, "name": "Screen / Pane / Relationship modal", "width": 1488, @@ -24645,7 +25268,7 @@ { "type": "frame", "id": "h4P2jZ", - "x": 16474, + "x": 18042, "y": 0, "name": "Screen / Panel / Changes", "clip": true, @@ -26269,7 +26892,7 @@ { "type": "frame", "id": "c3Lf5", - "x": 16909, + "x": 18477, "y": 0, "name": "Screen / Overview / Project task forest", "width": 520, @@ -27087,7 +27710,7 @@ { "type": "frame", "id": "AZvEA", - "x": 17509, + "x": 19077, "y": 0, "name": "Screen / Overview / Inspect without moving", "width": 900, @@ -27184,7 +27807,7 @@ { "type": "frame", "id": "wzrRI", - "x": 18489, + "x": 20057, "y": 0, "name": "Screen / Workbench / Parent", "width": 1488, @@ -28517,7 +29140,7 @@ { "type": "frame", "id": "IhnIO", - "x": 20057, + "x": 21625, "y": 0, "name": "Screen / Workbench / Delegated child tab", "width": 1488, @@ -28664,7 +29287,7 @@ { "type": "frame", "id": "m5T3n1", - "x": 21625, + "x": 23193, "y": 0, "name": "Screen / Overview / Availability states", "width": 1080, @@ -29112,7 +29735,7 @@ { "type": "frame", "id": "n2oTPf", - "x": 22785, + "x": 24353, "y": 0, "name": "Screen / Explorer / Git in workbench", "width": 1488, @@ -30137,6 +30760,14 @@ "--size-device-test-stage-col": { "type": "number", "value": 64 + }, + "--font-style-preview": { + "type": "string", + "value": "italic" + }, + "--text-preview-slant": { + "type": "number", + "value": 12 } }, "fileToken": "61e6a599-bafe-4c87-80e7-10732d9e7fe4" diff --git a/macos/Sources/HerdrMacOS/HideEnvironment.swift b/macos/Sources/HerdrMacOS/HideEnvironment.swift index 29f7207050..bb037fb438 100644 --- a/macos/Sources/HerdrMacOS/HideEnvironment.swift +++ b/macos/Sources/HerdrMacOS/HideEnvironment.swift @@ -45,22 +45,31 @@ private struct HideScaledFontModifier: ViewModifier { let size: CGFloat let weight: Font.Weight let design: Font.Design + let italic: Bool @Environment(\.hideFontScale) private var scale @Environment(\.hidePetAppearance) private var petAppearance func body(content: Content) -> some View { content.font(petAppearance - ? .system(size: size * scale, weight: weight, design: design) - : HideTheme.font(size: size * scale, weight: weight, design: design)) + ? systemFont + : HideTheme.font(size: size * scale, weight: weight, design: design, italic: italic)) + } + + private var systemFont: Font { + let font = Font.system(size: size * scale, weight: weight, design: design) + return italic ? font.italic() : font } } extension View { + /// `italic` selects the theme's slanted variant (`HideTheme.Typography.previewSlant`); + /// the strip draws a preview tab's title with it and nothing else does. func hideFont( size: CGFloat, weight: Font.Weight = .regular, - design: Font.Design = .default + design: Font.Design = .default, + italic: Bool = false ) -> some View { - modifier(HideScaledFontModifier(size: size, weight: weight, design: design)) + modifier(HideScaledFontModifier(size: size, weight: weight, design: design, italic: italic)) } } diff --git a/macos/Sources/HerdrMacOS/HideTheme.swift b/macos/Sources/HerdrMacOS/HideTheme.swift index d3d1fd8756..2b639f02fd 100644 --- a/macos/Sources/HerdrMacOS/HideTheme.swift +++ b/macos/Sources/HerdrMacOS/HideTheme.swift @@ -13,12 +13,28 @@ enum HideTheme { return font }() - @MainActor static func font(size: CGFloat, weight: SwiftUI.Font.Weight, design: SwiftUI.Font.Design) -> SwiftUI.Font { - if design == .monospaced { return .system(size: size, weight: weight, design: .monospaced) } - return SwiftUI.Font(nativeFont(size: size, weight: weight)) + @MainActor static func font( + size: CGFloat, + weight: SwiftUI.Font.Weight, + design: SwiftUI.Font.Design, + italic: Bool = false + ) -> SwiftUI.Font { + if design == .monospaced { + let system = SwiftUI.Font.system(size: size, weight: weight, design: .monospaced) + return italic ? system.italic() : system + } + return SwiftUI.Font(nativeFont(size: size, weight: weight, italic: italic)) } - @MainActor static func nativeFont(size: CGFloat, weight: SwiftUI.Font.Weight = .regular) -> NSFont { + /// The bundled Inter face carries weight and optical-size axes and no + /// italic, so the italic variant is the same face slanted by + /// `Typography.previewSlant` through the font matrix rather than a + /// second font file. Every italic chrome label takes it from here. + @MainActor static func nativeFont( + size: CGFloat, + weight: SwiftUI.Font.Weight = .regular, + italic: Bool = false + ) -> NSFont { let numericWeight: Double = switch weight { case .ultraLight: 100 case .thin: 200 @@ -35,7 +51,13 @@ enum HideTheme { kCTFontFeatureSelectorIdentifierKey: kStylisticAltThreeOnSelector]], kCTFontVariationAttribute: [NSNumber(value: 0x77676874): numericWeight], ] as CFDictionary) - return CTFontCreateWithGraphicsFont(inter, size, nil, descriptor) as NSFont + guard italic else { + return CTFontCreateWithGraphicsFont(inter, size, nil, descriptor) as NSFont + } + var matrix = CGAffineTransform( + a: 1, b: 0, c: tan(Typography.previewSlant * .pi / 180), d: 1, tx: 0, ty: 0 + ) + return CTFontCreateWithGraphicsFont(inter, size, &matrix, descriptor) as NSFont } /// The excluded pet dashboard retains its existing appearance (N2). /// These are active surface tokens, not a second copy of its components. @@ -81,6 +103,10 @@ enum HideTheme { static let title: CGFloat = 13 static let headline: CGFloat = 17 static let display: CGFloat = 30 + /// The italic variant of the chrome face, as the oblique angle in + /// degrees the font matrix applies. A preview tab's title is the one + /// place the strip draws it (PRD editor-preview-tab D-06). + static let previewSlant: CGFloat = 12 } enum Editor { static let contentInset = spacingMD diff --git a/scripts/pen-token-map.json b/scripts/pen-token-map.json index 7c7e471318..239b152e6b 100644 --- a/scripts/pen-token-map.json +++ b/scripts/pen-token-map.json @@ -70,6 +70,7 @@ "--text-terminal-base": "terminalBaseFontSize", "--text-editor-base": "editorBaseFontSize", "--text-editor-document": "Editor.documentFontSize", + "--text-preview-slant": "Typography.previewSlant", "--proposed-conversation-measure": "Conversation.measureWidth", "--proposed-conversation-time-rail": "Conversation.timeRailWidth", "--proposed-conversation-body-line-spacing": "Conversation.bodyLineSpacing", From c68fede3aef788aa513830ec1041f6f932eab8b9 Mon Sep 17 00:00:00 2001 From: yansfil Date: Sat, 19 Sep 2026 13:07:03 +0900 Subject: [PATCH 3/5] Give each checkout one replaceable preview tab in the editor core A single click asks for the preview slot through file_open and changes_select; the core replaces a clean preview tab in place, keeps a dirty one and opens the new preview beside it, and promotes on the first edit, on a drag, on an ordinary open of the same file, and on the new file_keep_open event. A replaced tab is not recorded for reopening. The flag rides EditorTabSnapshot and the strip entry. --- herdr-core/src/model.rs | 28 +- herdr-core/src/runtime/editor.rs | 166 +++++- herdr-core/src/runtime/events.rs | 33 +- herdr-core/src/runtime/session.rs | 27 +- herdr-core/src/runtime/tests.rs | 2 + .../src/runtime/tests/editor_preview.rs | 520 ++++++++++++++++++ herdr-core/src/runtime/tests/editor_reopen.rs | 11 +- 7 files changed, 751 insertions(+), 36 deletions(-) create mode 100644 herdr-core/src/runtime/tests/editor_preview.rs diff --git a/herdr-core/src/model.rs b/herdr-core/src/model.rs index 3f7fe58c6c..61a3ed26de 100644 --- a/herdr-core/src/model.rs +++ b/herdr-core/src/model.rs @@ -542,6 +542,12 @@ pub struct StripTabSnapshot { /// The Herdr tab id or editor tab id this entry stands for. pub source_id: String, pub label: String, + /// Whether this editor entry is the checkout's replaceable preview tab, + /// which the strip titles in italic. A Herdr entry is never one. It rides + /// the strip rather than only the editor tab because promotion and + /// replacement change the slot itself, and both happen once per tab, not + /// per keystroke. + pub preview: bool, /// The one agent this tab holds, when it holds exactly one, drawn as the /// tab's identity where a tab is named: the Recent Panels switcher shows /// its name and mark instead of the Herdr label, which for an unnamed tab @@ -567,32 +573,44 @@ impl StripTabSnapshot { kind: StripTabKind::Herdr, source_id, label: label.into(), + preview: false, agent_identity: None, } } - pub fn file(source_id: impl Into, label: impl Into) -> Self { + pub fn file(source_id: impl Into, label: impl Into, preview: bool) -> Self { let source_id = source_id.into(); Self { id: format!("file:{source_id}"), kind: StripTabKind::File, source_id, label: label.into(), + preview, agent_identity: None, } } - pub fn diff(source_id: impl Into, label: impl Into) -> Self { + pub fn diff(source_id: impl Into, label: impl Into, preview: bool) -> Self { let source_id = source_id.into(); Self { id: format!("diff:{source_id}"), kind: StripTabKind::Diff, source_id, label: label.into(), + preview, agent_identity: None, } } + /// The strip entry an editor tab stands behind, so a replaced preview tab + /// can hand its slot to the tab that took its place. + pub fn editor(tab: &EditorTabSnapshot) -> Self { + match tab.kind { + EditorTabKind::File => Self::file(tab.id.clone(), tab.label.clone(), tab.preview), + EditorTabKind::Diff => Self::diff(tab.id.clone(), tab.label.clone(), tab.preview), + } + } + /// The Herdr half of a strip, in the order the tabs are given. /// /// A tab with no id has no identity to key a strip entry by, so it is @@ -1020,6 +1038,12 @@ pub struct EditorTabSnapshot { pub markdown_preview: bool, pub wrap: bool, pub dirty: bool, + /// The checkout's one replaceable preview tab (VS Code's model): opened by + /// a single click, replaced in place by the next single click, and + /// promoted to an ordinary tab by a double-click, the first edit, Keep + /// Open, or a drag. A dirty tab is never replaced. Editor tabs are + /// ephemeral, so this is never persisted. + pub preview: bool, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)] diff --git a/herdr-core/src/runtime/editor.rs b/herdr-core/src/runtime/editor.rs index 81964af878..eac4c1f442 100644 --- a/herdr-core/src/runtime/editor.rs +++ b/herdr-core/src/runtime/editor.rs @@ -277,18 +277,29 @@ impl Runtime { }) } + /// Shows a prepared file tab. `preview` is what the click asked for: a + /// single click wants the checkout's preview slot, every other entry + /// point wants an ordinary tab (PRD editor-preview-tab D-09). A file that + /// already has a tab is focused, and an ordinary open of the file that + /// currently holds the preview slot promotes it where it sits (D-10, B4). pub(super) fn show_file_tab( &mut self, prepared: PreparedFileTab, workspace_id: &str, checkout_id: &str, path: &str, + preview: bool, ) { let tab_id = match prepared { - PreparedFileTab::Open(tab_id) => tab_id, + PreparedFileTab::Open(tab_id) => { + if !preview { + self.promote_editor_tab(&tab_id); + } + tab_id + } PreparedFileTab::Read { tab_id, document } => { self.editor_documents.insert(tab_id.clone(), document); - self.snapshot.editor.tabs.push(EditorTabSnapshot { + let tab = EditorTabSnapshot { id: tab_id.clone(), workspace_id: workspace_id.to_owned(), checkout_id: checkout_id.to_owned(), @@ -304,9 +315,9 @@ impl Runtime { markdown_preview: true, wrap: false, dirty: false, - }); - // A new file tab takes a slot at the end of the strip. - self.rebuild_tab_strips(); + preview, + }; + self.place_editor_tab(tab); tab_id } }; @@ -316,6 +327,116 @@ impl Runtime { self.snapshot.ui_state.selected_path = Some(path.to_owned()); } + /// Puts a new editor tab into the strip. + /// + /// An ordinary tab takes a slot at the end. A preview tab takes the + /// checkout's preview slot: when the checkout already has a preview tab + /// that is clean, the new tab replaces it in place, inheriting its strip + /// slot, and the replaced tab's document, Markdown mode and wrap state + /// are dropped without a Recent Closed entry (D-04). A dirty preview tab + /// is never replaced: it is promoted where it sits and the new preview + /// opens beside it (D-05). File and diff tabs share the one slot (D-02). + fn place_editor_tab(&mut self, tab: EditorTabSnapshot) { + let replaced = tab.preview.then(|| { + self.snapshot + .editor + .tabs + .iter() + .position(|held| { + held.preview + && held.workspace_id == tab.workspace_id + && held.checkout_id == tab.checkout_id + }) + .map(|index| (index, self.snapshot.editor.tabs[index].dirty)) + }); + match replaced.flatten() { + Some((index, false)) => { + let old = self.retire_editor_tab(index); + let old_entry = StripTabSnapshot::editor(&old).id; + let new_entry = StripTabSnapshot::editor(&tab).id; + for order in self.checkout_tab_order.values_mut() { + for entry in order.iter_mut().filter(|entry| **entry == old_entry) { + *entry = new_entry.clone(); + } + } + for pending in self.pending_tab_move.values_mut() { + for entry in pending + .desired + .iter_mut() + .filter(|entry| **entry == old_entry) + { + *entry = new_entry.clone(); + } + } + self.push_diagnostic( + "editor.preview_replaced", + format!("Preview tab {} replaced by {}", old.id, tab.id), + ); + self.snapshot.editor.tabs.insert(index, tab); + } + Some((index, true)) => { + let dirty = &mut self.snapshot.editor.tabs[index]; + dirty.preview = false; + let kept = dirty.id.clone(); + self.push_diagnostic( + "editor.preview_kept_dirty", + format!("Dirty preview tab {kept} kept and promoted"), + ); + self.snapshot.editor.tabs.push(tab); + } + None => self.snapshot.editor.tabs.push(tab), + } + self.rebuild_tab_strips(); + } + + /// Takes an editor tab out of the runtime: its snapshot entry, its + /// document, its place in the focus history, and, when it was the active + /// diff, the Changes selection it was showing. The caller decides what + /// the removal means: a close records it for reopening, a preview + /// replacement does not. + fn retire_editor_tab(&mut self, index: usize) -> EditorTabSnapshot { + let tab = self.snapshot.editor.tabs.remove(index); + let was_active = self.snapshot.editor.active_tab_id.as_deref() == Some(tab.id.as_str()); + self.editor_documents.remove(&tab.id); + self.editor_tab_history.retain(|known| known != &tab.id); + if was_active { + self.snapshot.editor.active_tab_id = None; + self.snapshot.editor.document = None; + if tab.kind == EditorTabKind::Diff { + self.snapshot.changes.selected_path = None; + self.snapshot.changes.diff = None; + } + } + tab + } + + /// Makes a preview tab an ordinary tab in the same slot. Returns whether + /// anything changed: promoting a tab that is already ordinary is a + /// no-op, and a tab that is not open is refused with a reason. + pub(super) fn promote_editor_tab(&mut self, tab_id: &str) -> bool { + let Some(tab) = self + .snapshot + .editor + .tabs + .iter_mut() + .find(|tab| tab.id == tab_id) + else { + self.set_error( + "editor.keep_open_unknown_tab", + format!("Editor tab {tab_id} is not open"), + false, + ); + return true; + }; + if !tab.preview { + return false; + } + tab.preview = false; + self.push_diagnostic("editor.preview_promoted", format!("Tab {tab_id} kept open")); + self.rebuild_tab_strips(); + true + } + pub(super) fn focus_editor_tab_context(&mut self, tab_id: &str) -> Result<(), String> { let tab = self .snapshot @@ -361,9 +482,17 @@ impl Runtime { Ok(()) } - pub(super) fn open_file_tab(&mut self, workspace_id: &str, checkout_id: &str, path: &str) { + pub(super) fn open_file_tab( + &mut self, + workspace_id: &str, + checkout_id: &str, + path: &str, + preview: bool, + ) { match self.prepare_file_tab(workspace_id, checkout_id, path) { - Ok(prepared) => self.show_file_tab(prepared, workspace_id, checkout_id, path), + Ok(prepared) => self.show_file_tab(prepared, workspace_id, checkout_id, path, preview), + // The read failed before anything moved, so an existing preview + // tab keeps its slot (B15). Err(message) => self.set_error("file.open_failed", message, true), } } @@ -384,9 +513,14 @@ impl Runtime { checkout_id: &str, path: &str, committed: bool, + preview: bool, ) { let tab_id = Self::diff_tab_id(workspace_id, checkout_id, path, committed); - if !self.snapshot.editor.tabs.iter().any(|tab| tab.id == tab_id) { + if self.snapshot.editor.tabs.iter().any(|tab| tab.id == tab_id) { + if !preview { + self.promote_editor_tab(&tab_id); + } + } else { let name = Path::new(path) .file_name() .and_then(|name| name.to_str()) @@ -397,7 +531,7 @@ impl Runtime { } else { "working diff" }; - self.snapshot.editor.tabs.push(EditorTabSnapshot { + self.place_editor_tab(EditorTabSnapshot { id: tab_id.clone(), workspace_id: workspace_id.to_owned(), checkout_id: checkout_id.to_owned(), @@ -408,8 +542,8 @@ impl Runtime { markdown_preview: true, wrap: false, dirty: false, + preview, }); - self.rebuild_tab_strips(); } if let Err(message) = self.activate_editor_tab(&tab_id) { self.set_error("diff.focus_failed", message, false); @@ -496,7 +630,7 @@ impl Runtime { return true; }; let was_active = self.snapshot.editor.active_tab_id.as_deref() == Some(tab_id); - let closed_tab = self.snapshot.editor.tabs.remove(index); + let closed_tab = self.retire_editor_tab(index); if closed_tab.kind == EditorTabKind::File { let key = self.next_recent_closed_key(); let checkout_path = self @@ -518,15 +652,7 @@ impl Runtime { }); } self.rebuild_tab_strips(); - self.editor_documents.remove(tab_id); - self.editor_tab_history.retain(|known| known != tab_id); if was_active { - self.snapshot.editor.active_tab_id = None; - self.snapshot.editor.document = None; - if closed_tab.kind == EditorTabKind::Diff { - self.snapshot.changes.selected_path = None; - self.snapshot.changes.diff = None; - } while let Some(previous_id) = self.editor_tab_history.pop() { if self .snapshot @@ -1997,7 +2123,7 @@ impl Runtime { tab_id: tab_id.clone(), document, }; - self.show_file_tab(prepared, workspace_id, checkout_id, path); + self.show_file_tab(prepared, workspace_id, checkout_id, path, false); if let Err(message) = self.focus_editor_tab_context(&tab_id) { self.set_reopen_notices(vec![live::ReopenNotice { pane_id: None, diff --git a/herdr-core/src/runtime/events.rs b/herdr-core/src/runtime/events.rs index bd2d90372e..831ead2f04 100644 --- a/herdr-core/src/runtime/events.rs +++ b/herdr-core/src/runtime/events.rs @@ -307,6 +307,10 @@ pub(super) struct FileOpenPayload { pub(super) path: String, pub(super) workspace_id: String, pub(super) checkout_id: String, + /// Whether the open wants the checkout's preview slot: an Explorer single + /// click does, a double-click, Cmd+P and every other entry point do not. + #[serde(default)] + pub(super) preview: bool, } #[derive(Debug, Deserialize)] @@ -458,6 +462,10 @@ pub(super) struct ChangesSelectPayload { pub(super) committed: bool, #[serde(default)] pub(super) path: Option, + /// Whether the diff opens in the checkout's preview slot, which a single + /// click on a Changes row asks for. + #[serde(default)] + pub(super) preview: bool, } #[derive(Debug, Deserialize)] @@ -673,6 +681,8 @@ pub(super) enum Event { FileOpen(FileOpenPayload), RevealPath(RevealPathPayload), FileFocus(FileTabPayload), + /// Keep Open: the preview tab becomes an ordinary tab in the same slot. + FileKeepOpen(FileTabPayload), FileClose(FileClosePayload), FileDraft(FileDraftPayload), FileView(FileViewPayload), @@ -804,6 +814,7 @@ pub(super) fn validate_event(event: EventEnvelope) -> Result decode!(FileOpenPayload, FileOpen), "reveal_path" => decode!(RevealPathPayload, RevealPath), "file_focus" => decode!(FileTabPayload, FileFocus), + "file_keep_open" => decode!(FileTabPayload, FileKeepOpen), "file_close" => decode!(FileClosePayload, FileClose), "file_draft" => decode!(FileDraftPayload, FileDraft), "file_view" => decode!(FileViewPayload, FileView), @@ -1876,10 +1887,16 @@ impl Runtime { ); return true; } - self.open_file_tab(&payload.workspace_id, &payload.checkout_id, &payload.path); + self.open_file_tab( + &payload.workspace_id, + &payload.checkout_id, + &payload.path, + payload.preview, + ); self.persist_current_ui_state(); true } + Event::FileKeepOpen(payload) => self.promote_editor_tab(&payload.tab_id), Event::RevealPath(payload) => self.reveal_path(payload), Event::FileFocus(payload) => { let Some(tab) = self @@ -1983,8 +2000,14 @@ impl Runtime { }; match files::update_draft(document, payload.contents_utf8) { Ok(()) => { + let edited = document.dirty; self.sync_file_tab_dirty(&tab_id); self.sync_active_editor_document(); + // The first edit keeps a preview tab (B5); an echo of + // the same contents is not an edit. + if edited { + self.promote_editor_tab(&tab_id); + } } Err(message) => self.set_error("file.draft_rejected", message, false), } @@ -2530,7 +2553,13 @@ impl Runtime { if self.snapshot.editor.active_tab_id.as_deref() == Some(tab_id.as_str()) { return false; } - self.show_diff_tab(&workspace_id, &checkout_id, &path, payload.committed); + self.show_diff_tab( + &workspace_id, + &checkout_id, + &path, + payload.committed, + payload.preview, + ); self.persist_current_ui_state(); true } diff --git a/herdr-core/src/runtime/session.rs b/herdr-core/src/runtime/session.rs index cf92eb6091..d803e25b8a 100644 --- a/herdr-core/src/runtime/session.rs +++ b/herdr-core/src/runtime/session.rs @@ -467,6 +467,11 @@ impl Runtime { self.pending_tab_move.remove(&payload.checkout_id); self.checkout_tab_order .insert(payload.checkout_id.clone(), desired_ids); + // A preview tab the operator placed by hand is one they mean to + // keep (B7); the rebuild below draws the promoted slot. + if moved.preview { + self.promote_editor_tab(&moved.source_id); + } self.rebuild_tab_strips(); return true; } @@ -651,14 +656,7 @@ impl Runtime { .filter(|tab| { tab.workspace_id == checkout.workspace_id && tab.checkout_id == checkout.id }) - .map(|tab| match tab.kind { - EditorTabKind::File => { - StripTabSnapshot::file(tab.id.clone(), tab.label.clone()) - } - EditorTabKind::Diff => { - StripTabSnapshot::diff(tab.id.clone(), tab.label.clone()) - } - }) + .map(StripTabSnapshot::editor) .collect::>(); let stored = order.entry(checkout.id.clone()).or_default(); // A held reorder lands the moment Herdr reports the order it @@ -2498,9 +2496,13 @@ impl Runtime { .map(|(workspace, checkout)| (workspace.id.clone(), checkout.id.clone())) { match self.prepare_file_tab(&workspace_id, &checkout_id, &destination) { - Ok(prepared) => { - self.show_file_tab(prepared, &workspace_id, &checkout_id, &destination) - } + Ok(prepared) => self.show_file_tab( + prepared, + &workspace_id, + &checkout_id, + &destination, + false, + ), Err(message) => { if let Some(slot) = self.snapshot.explorer_operation.as_mut() { slot.message = Some(message.clone()); @@ -2925,11 +2927,14 @@ impl Runtime { } self.snapshot.ui_state.selected_path = Some(payload.path.clone()); if let Some(prepared) = prepared { + // A revealed path was named on purpose: a terminal link or a + // Markdown link opens an ordinary tab, not the preview (D-09). self.show_file_tab( prepared, &payload.workspace_id, &payload.checkout_id, &payload.path, + false, ); } self.push_diagnostic( diff --git a/herdr-core/src/runtime/tests.rs b/herdr-core/src/runtime/tests.rs index 7102a15861..c60a8ba51c 100644 --- a/herdr-core/src/runtime/tests.rs +++ b/herdr-core/src/runtime/tests.rs @@ -7,6 +7,8 @@ use crate::fake_herdr::FakeHerdr; mod agents_settings_remote; #[path = "tests/devices.rs"] mod devices; +#[path = "tests/editor_preview.rs"] +mod editor_preview; #[path = "tests/editor_reopen.rs"] mod editor_reopen; #[path = "tests/lineage.rs"] diff --git a/herdr-core/src/runtime/tests/editor_preview.rs b/herdr-core/src/runtime/tests/editor_preview.rs new file mode 100644 index 0000000000..9c1d299af8 --- /dev/null +++ b/herdr-core/src/runtime/tests/editor_preview.rs @@ -0,0 +1,520 @@ +use super::*; + +// The preview tab rules of PRD editor-preview-tab (D-01..D-05, D-09, D-10): +// what a single click, a double-click, an edit, Keep Open, a drag and a +// dirty tab do to the checkout's one preview slot. + +fn open(runtime: &mut Runtime, checkout_id: &str, path: &Path, preview: bool) -> bool { + runtime.dispatch_json(&explorer_event( + "file_open", + serde_json::json!({ + "path": path.to_string_lossy(), + "workspace_id": "workspace:order", + "checkout_id": checkout_id, + "preview": preview + }), + )) +} + +fn tabs(runtime: &Runtime) -> Vec<(String, bool, bool)> { + runtime + .snapshot() + .editor + .tabs + .iter() + .map(|tab| (tab.label.clone(), tab.preview, tab.dirty)) + .collect() +} + +fn strip_previews(runtime: &Runtime, checkout_id: &str) -> Vec<(String, bool)> { + runtime + .snapshot() + .navigator + .workspaces + .iter() + .flat_map(|workspace| workspace.checkouts.iter()) + .find(|checkout| checkout.id == checkout_id) + .expect("the registered checkout") + .strip + .iter() + .map(|entry| (entry.label.clone(), entry.preview)) + .collect() +} + +fn draft(runtime: &mut Runtime, contents: &str) -> bool { + runtime.dispatch_json(&explorer_event( + "file_draft", + serde_json::json!({"contents_utf8": contents}), + )) +} + +/// B1, B2, B14, B20: a single click opens the preview tab at the end of +/// the strip; the next single click replaces it in the same slot, drops the +/// replaced document, records nothing for reopening, and moves the +/// Explorer selection. +#[test] +fn a_single_click_opens_one_preview_tab_and_the_next_replaces_it_in_place() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-replace"); + let tabs_ids = ["w-order:t1", "w-order:t2"]; + assert!(runtime.ingest_session(Ok(tab_order_payload( + &directory.to_string_lossy(), + &tabs_ids, + &tabs_ids, + "w-order:t1" + )))); + let notes = directory.join("notes.md"); + let second = directory.join("second.md"); + let third = directory.join("third.md"); + std::fs::write(&second, "second\n").expect("fixture"); + std::fs::write(&third, "third\n").expect("fixture"); + + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), true, false)]); + assert_eq!( + strip_previews(&runtime, &checkout_id), + vec![ + ("w-order:t1".to_owned(), false), + ("w-order:t2".to_owned(), false), + ("notes.md".to_owned(), true) + ] + ); + // An ordinary tab beside it, so the slot the preview holds is not the end. + assert!(open(&mut runtime, &checkout_id, &second, false)); + assert_eq!( + tabs(&runtime), + vec![ + ("notes.md".to_owned(), true, false), + ("second.md".to_owned(), false, false) + ] + ); + + assert!(open(&mut runtime, &checkout_id, &third, true)); + let snapshot = runtime.snapshot(); + assert_eq!( + tabs(&runtime), + vec![ + ("third.md".to_owned(), true, false), + ("second.md".to_owned(), false, false) + ], + "the new preview inherits the replaced tab's slot" + ); + assert_eq!( + strip_previews(&runtime, &checkout_id)[2..], + [ + ("third.md".to_owned(), true), + ("second.md".to_owned(), false) + ] + ); + let third_id = Runtime::file_tab_id("workspace:order", &checkout_id, &third.to_string_lossy()); + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + assert_eq!( + snapshot.editor.active_tab_id.as_deref(), + Some(third_id.as_str()) + ); + assert_eq!( + snapshot + .editor + .document + .as_ref() + .map(|document| document.path.as_str()), + Some(third.to_string_lossy().as_ref()) + ); + assert_eq!( + snapshot.ui_state.selected_path.as_deref(), + Some(third.to_string_lossy().as_ref()) + ); + assert!(!runtime.editor_documents.contains_key(¬es_id)); + assert!(!runtime.editor_tab_history.contains(¬es_id)); + assert_eq!( + snapshot.recent_closed.count, 0, + "a replaced preview is not a close" + ); + assert!(snapshot.status.last_error.is_none()); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B4, D-10: opening the preview file as an ordinary tab promotes it where it +/// sits without reading the document again. +#[test] +fn an_ordinary_open_of_the_preview_file_promotes_it_in_place() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-promote-open"); + let notes = directory.join("notes.md"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + let before = runtime + .editor_documents + .get(¬es_id) + .cloned() + .expect("document"); + + assert!(open(&mut runtime, &checkout_id, ¬es, false)); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), false, false)]); + assert_eq!( + strip_previews(&runtime, &checkout_id), + vec![("notes.md".to_owned(), false)] + ); + assert_eq!(runtime.editor_documents.get(¬es_id), Some(&before)); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B9, B10: a single click on a file that is already open focuses its tab +/// and neither creates nor replaces a preview. +#[test] +fn a_single_click_on_an_open_file_focuses_without_touching_the_preview_slot() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-focus-only"); + let notes = directory.join("notes.md"); + let second = directory.join("second.md"); + std::fs::write(&second, "second\n").expect("fixture"); + assert!(open(&mut runtime, &checkout_id, ¬es, false)); + assert!(open(&mut runtime, &checkout_id, &second, true)); + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + let second_id = + Runtime::file_tab_id("workspace:order", &checkout_id, &second.to_string_lossy()); + + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + assert_eq!( + runtime.snapshot().editor.active_tab_id.as_deref(), + Some(notes_id.as_str()) + ); + assert_eq!( + tabs(&runtime), + vec![ + ("notes.md".to_owned(), false, false), + ("second.md".to_owned(), true, false) + ] + ); + + assert!(open(&mut runtime, &checkout_id, &second, true)); + assert_eq!( + runtime.snapshot().editor.active_tab_id.as_deref(), + Some(second_id.as_str()) + ); + assert_eq!( + tabs(&runtime), + vec![ + ("notes.md".to_owned(), false, false), + ("second.md".to_owned(), true, false) + ] + ); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B5: the first edit promotes the preview tab in that frame, and the next +/// single click opens a new preview beside it. An echo of the same contents +/// is not an edit. +#[test] +fn the_first_edit_keeps_a_preview_tab_and_the_next_click_opens_beside_it() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-edit"); + let notes = directory.join("notes.md"); + let second = directory.join("second.md"); + std::fs::write(&second, "second\n").expect("fixture"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + + assert!(draft(&mut runtime, "notes\n")); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), true, false)]); + + assert!(draft(&mut runtime, "notes edited\n")); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), false, true)]); + + assert!(open(&mut runtime, &checkout_id, &second, true)); + assert_eq!( + tabs(&runtime), + vec![ + ("notes.md".to_owned(), false, true), + ("second.md".to_owned(), true, false) + ] + ); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B8, D-05: however a preview tab came to be dirty, the next single click +/// keeps it, promotes it, and opens the new preview beside it; the draft +/// survives. +#[test] +fn a_dirty_preview_tab_is_never_replaced() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-dirty"); + let notes = directory.join("notes.md"); + let second = directory.join("second.md"); + std::fs::write(&second, "second\n").expect("fixture"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + assert!(draft(&mut runtime, "notes edited\n")); + // The shell debounces nothing here, but the core does not rely on the + // edit having promoted the tab: a dirty preview is refused replacement + // on its own. + runtime.snapshot.editor.tabs[0].preview = true; + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + + assert!(open(&mut runtime, &checkout_id, &second, true)); + assert_eq!( + tabs(&runtime), + vec![ + ("notes.md".to_owned(), false, true), + ("second.md".to_owned(), true, false) + ] + ); + assert_eq!( + runtime + .editor_documents + .get(¬es_id) + .and_then(|document| document.contents_utf8.as_deref()), + Some("notes edited\n") + ); + assert_eq!(runtime.snapshot().recent_closed.count, 0); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B6: Keep Open promotes the preview tab in its slot, changes nothing on an +/// ordinary tab, and refuses a tab that is not open. +#[test] +fn keep_open_promotes_a_preview_tab_once() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-keep-open"); + let notes = directory.join("notes.md"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + let keep = |runtime: &mut Runtime, tab_id: &str| { + runtime.dispatch_json(&explorer_event( + "file_keep_open", + serde_json::json!({"tab_id": tab_id}), + )) + }; + + assert!(keep(&mut runtime, ¬es_id)); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), false, false)]); + assert_eq!( + strip_previews(&runtime, &checkout_id), + vec![("notes.md".to_owned(), false)] + ); + + assert!( + !keep(&mut runtime, ¬es_id), + "an ordinary tab has nothing to keep" + ); + assert!(runtime.snapshot().status.last_error.is_none()); + + assert!(keep(&mut runtime, "file:missing")); + assert_eq!( + runtime + .snapshot() + .status + .last_error + .as_ref() + .map(|error| error.kind.as_str()), + Some("editor.keep_open_unknown_tab") + ); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B7: a preview tab the operator drags to a new slot becomes an ordinary +/// tab there. +#[test] +fn dragging_a_preview_tab_promotes_it() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-drag"); + let tabs_ids = ["w-order:t1", "w-order:t2"]; + assert!(runtime.ingest_session(Ok(tab_order_payload( + &directory.to_string_lossy(), + &tabs_ids, + &tabs_ids, + "w-order:t1" + )))); + let notes = directory.join("notes.md"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + let entry = strip_ids(&runtime, &checkout_id)[2].clone(); + + assert!(reorder_tab(&mut runtime, &checkout_id, &entry, 1)); + assert_eq!( + strip_previews(&runtime, &checkout_id), + vec![ + ("w-order:t1".to_owned(), false), + ("notes.md".to_owned(), false), + ("w-order:t2".to_owned(), false) + ] + ); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), false, false)]); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B12, D-02: a Changes single click opens a preview diff in the same slot a +/// preview file tab holds, and a file click takes the slot back from the +/// diff, clearing the Changes selection the diff was showing. +#[test] +fn file_and_diff_previews_share_one_slot() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-diff"); + let notes = directory.join("notes.md"); + let second = directory.join("second.md"); + std::fs::write(&second, "second\n").expect("fixture"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + runtime.snapshot.changes.root_path = Some(directory.to_string_lossy().into_owned()); + runtime.snapshot.changes.entries = vec![crate::model::ChangedFileSnapshot { + path: second.to_string_lossy().into_owned(), + relative_path: "second.md".to_owned(), + previous_relative_path: None, + status: crate::model::ChangedFileStatus::Untracked, + added_lines: Some(1), + removed_lines: Some(0), + }]; + + assert!(runtime.dispatch_json(&explorer_event( + "changes_select", + serde_json::json!({"path": second, "committed": false, "preview": true}), + ))); + let snapshot = runtime.snapshot(); + assert_eq!(snapshot.editor.tabs.len(), 1); + assert_eq!(snapshot.editor.tabs[0].kind, EditorTabKind::Diff); + assert!(snapshot.editor.tabs[0].preview); + assert_eq!( + snapshot.changes.selected_path.as_deref(), + Some(second.to_string_lossy().as_ref()) + ); + assert!(strip_previews(&runtime, &checkout_id)[0].1); + + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + let snapshot = runtime.snapshot(); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), true, false)]); + assert!(snapshot.changes.selected_path.is_none()); + assert!(snapshot.changes.diff.is_none()); + assert_eq!(snapshot.recent_closed.count, 0); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// B3, D-02: each checkout has its own preview slot. +#[test] +fn preview_tabs_are_per_checkout() { + let (mut runtime, first, first_id, second, second_id) = reveal_runtime(); + let first_file = first.join("deep/nested/leaf/target.txt"); + let second_file = second.join("deep/nested/leaf/target.txt"); + runtime.open_file_tab( + "workspace:0", + &first_id, + &first_file.to_string_lossy(), + true, + ); + runtime.open_file_tab( + "workspace:1", + &second_id, + &second_file.to_string_lossy(), + true, + ); + + let previews = runtime + .snapshot() + .editor + .tabs + .iter() + .map(|tab| (tab.checkout_id.clone(), tab.preview)) + .collect::>(); + assert_eq!( + previews, + vec![(first_id.clone(), true), (second_id.clone(), true)] + ); + + std::fs::remove_dir_all(&first).ok(); + std::fs::remove_dir_all(&second).ok(); +} + +/// B13, B15: closing a preview tab records it for reopening like any file +/// tab, and a click on a file that cannot be read leaves the preview tab as +/// it was. +#[test] +fn a_preview_tab_closes_normally_and_survives_a_failed_open() { + let (mut runtime, checkout_id, directory) = strip_checkout("preview-close-fail"); + let notes = directory.join("notes.md"); + assert!(open(&mut runtime, &checkout_id, ¬es, true)); + let notes_id = Runtime::file_tab_id("workspace:order", &checkout_id, ¬es.to_string_lossy()); + + assert!(open( + &mut runtime, + &checkout_id, + &directory.join("missing.md"), + true + )); + assert_eq!( + runtime + .snapshot() + .status + .last_error + .as_ref() + .map(|error| error.kind.as_str()), + Some("file.open_failed") + ); + assert_eq!(tabs(&runtime), vec![("notes.md".to_owned(), true, false)]); + assert_eq!( + runtime.snapshot().editor.active_tab_id.as_deref(), + Some(notes_id.as_str()) + ); + + assert!(runtime.dispatch_json(&explorer_event( + "file_close", + serde_json::json!({"tab_id": notes_id}), + ))); + let snapshot = runtime.snapshot(); + assert!(snapshot.editor.tabs.is_empty()); + assert_eq!(snapshot.recent_closed.count, 1); + assert_eq!( + snapshot.recent_closed.top_label.as_deref(), + Some("notes.md") + ); + + std::fs::remove_dir_all(&directory).ok(); +} + +/// D-09: a revealed path and a reopened tab are ordinary tabs. +#[test] +fn reveal_and_reopen_open_ordinary_tabs() { + let (mut runtime, root, checkout_id, _second, _second_id) = reveal_runtime(); + let target = root.join("deep/nested/leaf/target.txt"); + assert!(runtime.dispatch_json(&reveal_event("workspace:0", &checkout_id, &target, false))); + assert_eq!( + runtime + .snapshot() + .editor + .tabs + .iter() + .map(|tab| tab.preview) + .collect::>(), + vec![false] + ); + + let tab_id = Runtime::file_tab_id("workspace:0", &checkout_id, &target.to_string_lossy()); + assert!(runtime.dispatch_json(&explorer_event( + "file_close", + serde_json::json!({"tab_id": tab_id}), + ))); + let item = runtime + .recent_closed + .back() + .cloned() + .expect("the closed file"); + let request = live::ReopenRequest { + item, + workspace_exists: true, + tab_exists: true, + fallback_pane_id: None, + }; + runtime.reopen_in_flight = Some(request.item.key().to_owned()); + assert!(runtime.ingest_reopen_result( + &request, + Ok(live::FileReopenResultOrHerdr::File( + live::FileReopenResult::Opened(files::open(&target).expect("fixture document")) + )), + )); + assert_eq!( + runtime + .snapshot() + .editor + .tabs + .iter() + .map(|tab| tab.preview) + .collect::>(), + vec![false] + ); + + std::fs::remove_dir_all(&root).ok(); +} diff --git a/herdr-core/src/runtime/tests/editor_reopen.rs b/herdr-core/src/runtime/tests/editor_reopen.rs index 8d9be80d47..b0cbcd88a6 100644 --- a/herdr-core/src/runtime/tests/editor_reopen.rs +++ b/herdr-core/src/runtime/tests/editor_reopen.rs @@ -180,6 +180,7 @@ fn recent_navigation_restores_file_and_diff_across_projects_atomically() { &checkout_id, &file.to_string_lossy(), false, + false, ); } else { open_file(&mut runtime, &checkout_id, &file); @@ -910,7 +911,12 @@ fn selecting_a_change_opens_one_diff_tab_and_keeps_its_reader_alive() { ); std::fs::write(&path, "{}\n").expect("file fixture"); - runtime.open_file_tab("workspace:0", &checkout_id, path.to_string_lossy().as_ref()); + runtime.open_file_tab( + "workspace:0", + &checkout_id, + path.to_string_lossy().as_ref(), + false, + ); assert_eq!(runtime.snapshot().editor.tabs.len(), 2); assert_eq!( runtime @@ -1002,6 +1008,7 @@ fn explorer_rename_carries_expansion_and_open_tabs_to_the_new_path() { markdown_preview: false, wrap: false, dirty: false, + preview: false, }); runtime.editor_documents.insert( "file:w:c:lib".to_owned(), @@ -1123,6 +1130,7 @@ fn explorer_trash_removes_the_item_selects_the_named_row_and_keeps_its_tab() { markdown_preview: false, wrap: false, dirty: false, + preview: false, }); assert!(runtime.dispatch_json(&explorer_event( @@ -1591,6 +1599,7 @@ fn recent_closed_tracks_file_tabs_but_not_diff_tabs() { markdown_preview: false, wrap: false, dirty: false, + preview: false, }); } assert!(runtime.dispatch_json(&explorer_event( From 8d505d280537ddd09f9b0742bcd55a42a9f2aa67 Mon Sep 17 00:00:00 2001 From: yansfil Date: Sat, 19 Sep 2026 13:07:03 +0900 Subject: [PATCH 4/5] Draw preview tabs in italic and promote them from the shell MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The strip titles a preview tab with the theme's slanted variant, names it with a Preview suffix in the tooltip and accessibility label, and promotes it on a title double-click. The Explorer's double-click and Return open an ordinary tab, its single click and a Changes row click open the preview, and File > Keep Open (⇧⌘K) promotes the active editor tab. --- DESIGN.md | 15 ++++ docs/README.md | 1 + macos/Sources/HerdrMacOS/CoreBridge.swift | 14 +++- .../HerdrMacOS/CoreBridgeEditorSnapshot.swift | 3 + .../CoreBridgeWorkspaceSnapshot.swift | 8 +- macos/Sources/HerdrMacOS/HerdrApp.swift | 1 + macos/Sources/HerdrMacOS/HideMainView.swift | 13 ++- macos/Sources/HerdrMacOS/RightPanel.swift | 6 +- .../Sources/HerdrMacOS/ShellMenuCommand.swift | 3 + macos/Sources/HerdrMacOS/ShellModel.swift | 25 +++++- .../HerdrMacOS/ShellModelNavigation.swift | 25 +++++- .../HerdrMacOS/WorkspaceOutlineView.swift | 33 ++++++-- .../EditorPreviewTabPresentationTests.swift | 81 +++++++++++++++++++ .../RightPanelPresentationTests.swift | 3 +- .../WorkspaceOutlineEditingTests.swift | 4 +- 15 files changed, 212 insertions(+), 23 deletions(-) create mode 100644 macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift diff --git a/DESIGN.md b/DESIGN.md index 459aef2c10..d98ea47a07 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1368,6 +1368,21 @@ These few user-outcome tests retain no mock call graph or exact view hierarchy c The core's file-view lifecycle test checks independent tabs, repeated-intent convergence and reopen defaults. Native screenshots remain necessary to approve toolbar spacing, font fallback and narrow-window behavior. +## Editor preview tab + +A single click on an Explorer file or a Changes row opens it in the checkout's one preview tab, VS Code's model: the strip draws the title in the theme's italic variant, and the next single click replaces the tab in the same slot instead of adding one. +The core owns the flag (`EditorTabSnapshot.preview`, and the strip entry beside it), decides replacement and promotion, and the shell only says what the click meant: `file_open` and `changes_select` carry `preview`, and one `file_keep_open` event promotes. +Promotion happens in the same slot, on four triggers: a double-click on the Explorer row, a double-click on the tab title, the first edit, and File > Keep Open (`⇧⌘K`, declared in `ShellMenuCommand`); a drag to a new slot promotes as well. +A dirty tab is never replaced: the core promotes it where it sits and opens the new preview beside it. +Every other entry point - Cmd+P, Reopen Closed Tab, a Markdown or terminal link, a file the Explorer just created - opens an ordinary tab, and a single click on a file that already has a tab focuses it without touching the slot. +A replaced preview tab is not a close: its document, Markdown mode and wrap state are dropped and nothing enters Recent Closed; closing the tab yourself records it as any file tab. +Editor tabs stay ephemeral, so the flag is never persisted. + +The italic variant is `HideTheme.Typography.previewSlant`, an oblique of the bundled Inter face applied through the font matrix, because that face carries no italic axis; it is reached only through `hideFont(italic:)`. +The tooltip and the accessibility label read `name · Preview` while the tab is one and drop the suffix on promotion (`EditorTabTitlePresentation`); the tab's colours, close button, keycap and its Recent Panels row are the ordinary tab's. +The `Screen / Workbench / Preview tab` board draws the preview, promoted and dirty-kept states; pen substitutes the family's own italic, so the angle is not reviewed there, only size and spacing. +The core's rules are fixed by `runtime/tests/editor_preview.rs`, the shell's by `EditorPreviewTabPresentationTests`. + ## Explorer file management The local tree's context menu is the native `NSMenu`, in VS Code's order: New File, New Folder, a separator, Reveal in Finder, Copy Path, Copy Relative Path, a separator, Rename, a separator, Delete. diff --git a/docs/README.md b/docs/README.md index 7b11b72017..73435ebe48 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ A document's location or an old PRD citation does not make it current authority. | Project activity ordering, task-forest and Git Overview, disk and merged-worktree cleanup, registration removal | [DESIGN.md: Projects and checkout context](../DESIGN.md#projects-and-checkout-context), [agent workflow contract](../design/agent-workflow-review.md), [bounded projection cost](PERFORMANCE_TESTING.md#projects-and-overview-cost-contract) | `project_context.rs`, `worktrees.rs`, `disk.rs`, `worktree_cleanup.rs`, `runtime.rs`, `OverviewPresentation.swift`, `CheckoutOverview.swift`, native sidebar | | Recent project and unified-surface navigation | [DESIGN.md](../DESIGN.md#recent-navigation-in-the-native-shell), [input cost and regression owners](PERFORMANCE_TESTING.md#two-level-recent-navigation-cost-contract) | `AgentMRU.swift`, `ShellModel.swift`, `ShellModelNavigation.swift`, shortcut registry and navigation tests | | File toolbar, Markdown modes, draft lifecycle and preview security | [DESIGN.md: File document toolbar and Markdown](../DESIGN.md#file-document-toolbar-and-markdown) | `EditorViewerOverlay.swift`, `MarkdownPreview.swift`, `HighlightedCodeEditor.swift`, core editor events and document tests | +| Editor preview tab: the one replaceable slot per checkout, its promotion triggers, the italic title | [DESIGN.md: Editor preview tab](../DESIGN.md#editor-preview-tab) | `runtime/editor.rs` (`place_editor_tab`, `promote_editor_tab`), `runtime/tests/editor_preview.rs`, `ShellModelNavigation.swift` (`EditorTabTitlePresentation`), `HideTheme.Typography.previewSlant`, `EditorPreviewTabPresentationTests.swift` | | Explorer context menu, inline naming, drag move, Git decorations, and the core-owned file events | [DESIGN.md: Explorer file management](../DESIGN.md#explorer-file-management), [agent workflow contract](../design/agent-workflow-review.md), [bounded projection cost](PERFORMANCE_TESTING.md#projects-and-overview-cost-contract) | `WorkspaceOutlineView.swift`, `WorkspaceOutlinePresentation.swift`, `changes.rs`, `files.rs` explorer operations, runtime explorer tests, `WorkspaceOutlinePresentationTests.swift` | | Terminal file drop and image integration limits | [DESIGN.md: Terminal image attachment boundary](../DESIGN.md#terminal-image-attachment-boundary) | `TerminalFileDrop.swift`, `TerminalHost.swift`, `ImeTerminalView.swift`, existing terminal input path | | Product UI, control ownership and future native catalog review | [DESIGN.md: In-Product Components](../DESIGN.md#in-product-components) | `HideTheme.swift`, `scripts/design-control-policy.json`, `check-design-contract.mjs`, component checks and design tests | diff --git a/macos/Sources/HerdrMacOS/CoreBridge.swift b/macos/Sources/HerdrMacOS/CoreBridge.swift index ab3bde7805..74d5e1af39 100644 --- a/macos/Sources/HerdrMacOS/CoreBridge.swift +++ b/macos/Sources/HerdrMacOS/CoreBridge.swift @@ -855,11 +855,15 @@ final class CoreBridge: ObservableObject, @unchecked Sendable { ]) } - func openFile(_ url: URL, workspaceID: String, checkoutID: String) { + /// `preview` asks for the checkout's replaceable preview tab, which is + /// what an Explorer single click means; every other entry point opens an + /// ordinary tab. The core decides replacement and promotion. + func openFile(_ url: URL, workspaceID: String, checkoutID: String, preview: Bool = false) { dispatch(kind: "file_open", payload: [ "path": url.path, "workspace_id": workspaceID, "checkout_id": checkoutID, + "preview": preview, ]) } @@ -867,6 +871,11 @@ final class CoreBridge: ObservableObject, @unchecked Sendable { dispatch(kind: "file_focus", payload: ["tab_id": tabID]) } + /// Keep Open: the preview tab becomes an ordinary tab in the same slot. + func keepFileTabOpen(_ tabID: String) { + dispatch(kind: "file_keep_open", payload: ["tab_id": tabID]) + } + /// The explorer's five filesystem changes. Each is one event: the core /// decides the paths, runs the call off the runtime mutex, and reports /// through `explorerOperation`, so the tree never touches the disk and @@ -1030,12 +1039,13 @@ final class CoreBridge: ObservableObject, @unchecked Sendable { /// Selects the changed file whose diff the changes view shows, or clears /// the selection when `path` is nil. - func selectChangedFile(path: String?, committed: Bool = false) { + func selectChangedFile(path: String?, committed: Bool = false, preview: Bool = false) { dispatch( kind: "changes_select", payload: [ "path": path.map { $0 as Any } ?? NSNull(), "committed": committed, + "preview": preview, ] ) } diff --git a/macos/Sources/HerdrMacOS/CoreBridgeEditorSnapshot.swift b/macos/Sources/HerdrMacOS/CoreBridgeEditorSnapshot.swift index c6b2123f4f..236fcf3fe8 100644 --- a/macos/Sources/HerdrMacOS/CoreBridgeEditorSnapshot.swift +++ b/macos/Sources/HerdrMacOS/CoreBridgeEditorSnapshot.swift @@ -36,6 +36,8 @@ struct CoreEditorTabSnapshot: Decodable, Identifiable, Equatable { var markdownPreview: Bool? = nil var wrap: Bool? = nil let dirty: Bool + /// The checkout's replaceable preview tab (PRD editor-preview-tab D-07). + var preview: Bool = false enum CodingKeys: String, CodingKey { case id @@ -48,6 +50,7 @@ struct CoreEditorTabSnapshot: Decodable, Identifiable, Equatable { case wrap case diffCommitted = "diff_committed" case dirty + case preview } } diff --git a/macos/Sources/HerdrMacOS/CoreBridgeWorkspaceSnapshot.swift b/macos/Sources/HerdrMacOS/CoreBridgeWorkspaceSnapshot.swift index 04229ae74b..756a3c01e6 100644 --- a/macos/Sources/HerdrMacOS/CoreBridgeWorkspaceSnapshot.swift +++ b/macos/Sources/HerdrMacOS/CoreBridgeWorkspaceSnapshot.swift @@ -510,6 +510,9 @@ struct CoreStripTabSnapshot: Decodable, Identifiable, Equatable { /// Recent Panels switcher names the tab by it; a shell-only tab and a tab /// with several agents carry none and keep their label. let agentIdentity: CoreAgentChip? + /// Whether this editor entry is the checkout's preview tab, whose title + /// the strip draws in italic. The core decides it; a Herdr entry never is. + let preview: Bool enum CodingKeys: String, CodingKey { case id @@ -517,14 +520,16 @@ struct CoreStripTabSnapshot: Decodable, Identifiable, Equatable { case sourceID = "source_id" case label case agentIdentity = "agent_identity" + case preview } - init(id: String, kind: Kind, sourceID: String, label: String, agentIdentity: CoreAgentChip? = nil) { + init(id: String, kind: Kind, sourceID: String, label: String, agentIdentity: CoreAgentChip? = nil, preview: Bool = false) { self.id = id self.kind = kind self.sourceID = sourceID self.label = label self.agentIdentity = agentIdentity + self.preview = preview } init(from decoder: any Decoder) throws { @@ -534,6 +539,7 @@ struct CoreStripTabSnapshot: Decodable, Identifiable, Equatable { sourceID = try container.decode(String.self, forKey: .sourceID) label = try container.decode(String.self, forKey: .label) agentIdentity = try container.decodeIfPresent(CoreAgentChip.self, forKey: .agentIdentity) + preview = try container.decodeIfPresent(Bool.self, forKey: .preview) ?? false } } diff --git a/macos/Sources/HerdrMacOS/HerdrApp.swift b/macos/Sources/HerdrMacOS/HerdrApp.swift index aab2bd5678..d44b81d815 100644 --- a/macos/Sources/HerdrMacOS/HerdrApp.swift +++ b/macos/Sources/HerdrMacOS/HerdrApp.swift @@ -579,6 +579,7 @@ struct ShellCommands: Commands { Divider() menuButton(.closeTab) { model.performCloseShortcut() } + menuButton(.keepOpen) { model.keepActiveEditorTabOpen() } } CommandMenu("Navigate") { diff --git a/macos/Sources/HerdrMacOS/HideMainView.swift b/macos/Sources/HerdrMacOS/HideMainView.swift index 0c05f09859..aba567bb9c 100644 --- a/macos/Sources/HerdrMacOS/HideMainView.swift +++ b/macos/Sources/HerdrMacOS/HideMainView.swift @@ -98,7 +98,11 @@ private struct HideTabStrip: View { .hideFont(size: HideTheme.Typography.caption, weight: .medium) } Text(tab.label + model.tabActivity(for: tab)) - .hideFont(size: HideTheme.Typography.body, weight: tab.active ? .semibold : .medium) + .hideFont( + size: HideTheme.Typography.body, + weight: tab.active ? .semibold : .medium, + italic: EditorTabTitlePresentation.italic(preview: tab.preview) + ) .lineLimit(1) .frame(maxWidth: HideTheme.tabTitleMaxWidth, alignment: .leading) if let notice = model.tabNotice(for: tab) { @@ -129,7 +133,12 @@ private struct HideTabStrip: View { .contentShape(Rectangle()) } .buttonStyle(HideInteractiveButtonStyle()) - .hideTooltip([tab.contextLabel ?? tab.label, tab.focusedAgent.map { AgentStatusPresentation(agent: $0, connected: model.agentsConnected).label }].compactMap { $0 }.joined(separator: " · "), command: model.tabShortcutNumber(tabID: tab.id).map(HideCommand.tab), inline: true) + // A double-click on the title keeps a + // preview tab; the button's own click + // still focuses it on the first click. + .simultaneousGesture(TapGesture(count: 2).onEnded { model.keepUnifiedTabOpen(tab) }) + .accessibilityLabel(EditorTabTitlePresentation.spoken(label: tab.label, preview: tab.preview)) + .hideTooltip([tab.contextLabel ?? EditorTabTitlePresentation.spoken(label: tab.label, preview: tab.preview), tab.focusedAgent.map { AgentStatusPresentation(agent: $0, connected: model.agentsConnected).label }].compactMap { $0 }.joined(separator: " · "), command: model.tabShortcutNumber(tabID: tab.id).map(HideCommand.tab), inline: true) HideIconButton( systemImage: "xmark", diff --git a/macos/Sources/HerdrMacOS/RightPanel.swift b/macos/Sources/HerdrMacOS/RightPanel.swift index 619a2d7c7d..a8bb042af8 100644 --- a/macos/Sources/HerdrMacOS/RightPanel.swift +++ b/macos/Sources/HerdrMacOS/RightPanel.swift @@ -81,7 +81,7 @@ struct RightPanel: View { fontScale: fontScale, operation: model.core.snapshot?.explorerOperation, gitDecorations: explorerGitDecorations, - openFile: model.openFile, + openFile: { url, preview in model.openFile(url, preview: preview) }, updateExpandedPaths: { paths in model.core.persistUIState(expandedPaths: paths) }, @@ -309,8 +309,10 @@ struct ChangesView: View { private func row(_ entry: CoreChangedFile, committed: Bool) -> some View { let isSelected = entry.path == changes.selectedPath && changes.selectedCommitted == committed + // A single click on a row is a preview: the diff takes the + // checkout's one preview slot (B12). return ChangedFileRow(entry: entry, committed: committed, isSelected: isSelected) { - model.selectChangedFile(entry.path, committed: committed) + model.selectChangedFile(entry.path, committed: committed, preview: true) } } } diff --git a/macos/Sources/HerdrMacOS/ShellMenuCommand.swift b/macos/Sources/HerdrMacOS/ShellMenuCommand.swift index 16e3d6bffa..46541bb4e4 100644 --- a/macos/Sources/HerdrMacOS/ShellMenuCommand.swift +++ b/macos/Sources/HerdrMacOS/ShellMenuCommand.swift @@ -29,6 +29,7 @@ enum ShellMenuCommand: String, CaseIterable, Identifiable, Sendable { case search case openFile = "open_file" case closeTab = "close_tab" + case keepOpen = "keep_open" case reopenClosedTab = "reopen_closed_tab" case toggleLeftSidebar = "toggle_left_sidebar" case toggleSidebarView = "toggle_sidebar_view" @@ -63,6 +64,7 @@ enum ShellMenuCommand: String, CaseIterable, Identifiable, Sendable { case .search: "Search" case .openFile: "Open File" case .closeTab: "Close Tab" + case .keepOpen: "Keep Open" case .reopenClosedTab: "Reopen Closed Tab" case .toggleLeftSidebar: "Toggle Left Sidebar" case .toggleSidebarView: "Toggle Sidebar View" @@ -83,6 +85,7 @@ enum ShellMenuCommand: String, CaseIterable, Identifiable, Sendable { case .search: PaneShortcut(key: "k", modifiers: [.command]) case .openFile: PaneShortcut(key: "p", modifiers: [.command]) case .closeTab: PaneShortcut(key: "w", modifiers: [.command]) + case .keepOpen: PaneShortcut(key: "k", modifiers: [.command, .shift]) case .reopenClosedTab: PaneShortcut(key: "t", modifiers: [.command, .shift]) case .toggleLeftSidebar: PaneShortcut(key: "b", modifiers: [.command]) case .toggleSidebarView: PaneShortcut(key: "e", modifiers: [.command]) diff --git a/macos/Sources/HerdrMacOS/ShellModel.swift b/macos/Sources/HerdrMacOS/ShellModel.swift index 40fa887351..b0ae688b81 100644 --- a/macos/Sources/HerdrMacOS/ShellModel.swift +++ b/macos/Sources/HerdrMacOS/ShellModel.swift @@ -1806,7 +1806,9 @@ final class ShellModel: ObservableObject { focus(.terminal) } - func openFile(_ url: URL) { + /// `preview` is the Explorer single click; Cmd+P, a double-click and every + /// other caller open an ordinary tab (PRD editor-preview-tab D-09). + func openFile(_ url: URL, preview: Bool = false) { guard !isRemoteContext, let workspace = focusedWorkspace, let checkout = focusedCheckout @@ -1814,10 +1816,25 @@ final class ShellModel: ObservableObject { interactionNotice = "Select a local workspace before opening a file." return } - core.openFile(url, workspaceID: workspace.id, checkoutID: checkout.id) + core.openFile(url, workspaceID: workspace.id, checkoutID: checkout.id, preview: preview) interactionNotice = nil } + /// Keep Open from the menu: the active editor tab, if it is a preview, + /// becomes an ordinary tab. With no editor tab active there is nothing + /// to keep, and the menu item is a no-op rather than a notice. + func keepActiveEditorTabOpen() { + guard let tabID = core.snapshot?.editor.activeTabID else { return } + core.keepFileTabOpen(tabID) + } + + /// A double-click on a strip title. A Herdr tab has no preview state, so + /// only an editor entry sends anything. + func keepUnifiedTabOpen(_ item: ShellTabItem) { + guard case .editor(let tab) = item.kind, item.preview else { return } + core.keepFileTabOpen(tab.id) + } + func focusEditorTab(_ tab: CoreEditorTabSnapshot) { guard !isRemoteContext else { interactionNotice = "Remote file tabs are not available in the current read-only contract." @@ -2022,8 +2039,8 @@ final class ShellModel: ObservableObject { core.snapshot?.changes ?? .empty } - func selectChangedFile(_ path: String?, committed: Bool = false) { - core.selectChangedFile(path: path, committed: committed) + func selectChangedFile(_ path: String?, committed: Bool = false, preview: Bool = false) { + core.selectChangedFile(path: path, committed: committed, preview: preview) } /// What the summary card shows beyond the checkout row's own facts. diff --git a/macos/Sources/HerdrMacOS/ShellModelNavigation.swift b/macos/Sources/HerdrMacOS/ShellModelNavigation.swift index 0be9b9e857..359b736714 100644 --- a/macos/Sources/HerdrMacOS/ShellModelNavigation.swift +++ b/macos/Sources/HerdrMacOS/ShellModelNavigation.swift @@ -18,6 +18,25 @@ struct ShellTabItem: Identifiable { /// named rather than drawn as a strip slot - the Recent Panels switcher - /// this is the title and the mark; a tab without one keeps `label`. var agentIdentity: CoreAgentChip? = nil + /// The checkout's preview tab: titled in italic, named with "Preview", + /// promoted by a double-click on the title (PRD editor-preview-tab D-06). + var preview: Bool = false +} + +/// What a preview tab says about itself wherever it is named rather than +/// drawn: the tooltip and the accessibility label carry "Preview" after the +/// file name, and lose it the moment the tab is promoted (B16). The strip's +/// colours, close button and keycap are the ordinary tab's (B17). +enum EditorTabTitlePresentation { + static let previewSuffix = "Preview" + + static func spoken(label: String, preview: Bool) -> String { + preview ? "\(label) · \(previewSuffix)" : label + } + + static func italic(preview: Bool) -> Bool { + preview + } } /// Only the overlay subscribes to held-key presentation changes. The shell's @@ -113,7 +132,8 @@ enum ShellTabStrip { label: entry.label, dirty: tab.dirty, active: entry.sourceID == activeFileTabID, - kind: .editor(tab) + kind: .editor(tab), + preview: entry.preview ) case .diff: guard let tab = editorByID[entry.sourceID] @@ -123,7 +143,8 @@ enum ShellTabStrip { label: entry.label, dirty: false, active: entry.sourceID == activeFileTabID, - kind: .editor(tab) + kind: .editor(tab), + preview: entry.preview ) } } diff --git a/macos/Sources/HerdrMacOS/WorkspaceOutlineView.swift b/macos/Sources/HerdrMacOS/WorkspaceOutlineView.swift index b09a8df015..cfd65c18e7 100644 --- a/macos/Sources/HerdrMacOS/WorkspaceOutlineView.swift +++ b/macos/Sources/HerdrMacOS/WorkspaceOutlineView.swift @@ -363,7 +363,9 @@ struct WorkspaceOutlineView: NSViewRepresentable { let fontScale: CGFloat let operation: CoreExplorerOperation? let gitDecorations: WorkspaceGitDecorations? - let openFile: (URL) -> Void + /// Opens a file; the flag says whether as the checkout's preview tab (a + /// single click) or as an ordinary tab (a double-click or Return). + let openFile: (URL, _ preview: Bool) -> Void let updateExpandedPaths: ([String]) -> Void let fileOperations: WorkspaceFileOperations @@ -405,6 +407,10 @@ struct WorkspaceOutlineView: NSViewRepresentable { outline.dataSource = coordinator outline.target = coordinator outline.action = #selector(Coordinator.activateClickedRow) + // AppKit sends `action` for the first click of a double-click too, so + // a double-click on a file is a preview open followed by a promotion + // of the same tab, the order VS Code shows as well (PRD Risks). + outline.doubleAction = #selector(Coordinator.keepClickedRowOpen) outline.onActivate = { [weak coordinator] in coordinator?.activateSelection() } @@ -468,7 +474,7 @@ struct WorkspaceOutlineView: NSViewRepresentable { @MainActor final class Coordinator: NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextFieldDelegate { - var openFile: (URL) -> Void + var openFile: (URL, _ preview: Bool) -> Void var updateExpandedPaths: ([String]) -> Void var fileOperations: WorkspaceFileOperations private weak var outline: WorkspaceNSOutlineView? @@ -497,7 +503,7 @@ struct WorkspaceOutlineView: NSViewRepresentable { private var suppressExpansionPersistence = false init( - openFile: @escaping (URL) -> Void, + openFile: @escaping (URL, _ preview: Bool) -> Void, updateExpandedPaths: @escaping ([String]) -> Void, fileOperations: WorkspaceFileOperations ) { @@ -659,24 +665,37 @@ struct WorkspaceOutlineView: NSViewRepresentable { guard let outline, outline.clickedRow >= 0, let node = outline.item(atRow: outline.clickedRow) as? WorkspaceOutlineNode else { return } - activate(node) + activate(node, preview: true) + } + + /// The second click of a double-click: the file the first click + /// previewed is kept open. A folder's double-click changes nothing + /// beyond what its first click already toggled. + @objc func keepClickedRowOpen() { + guard let outline, outline.clickedRow >= 0, + let node = outline.item(atRow: outline.clickedRow) as? WorkspaceOutlineNode, + WorkspaceOutlineActivationPolicy.activation( + isDirectory: node.isDirectory, isPlaceholder: node.isPlaceholder + ) == .open + else { return } + openFile(node.url, false) } @objc func activateSelection() { guard let outline, outline.selectedRow >= 0, let node = outline.item(atRow: outline.selectedRow) as? WorkspaceOutlineNode else { return } - activate(node) + activate(node, preview: false) } - private func activate(_ node: WorkspaceOutlineNode) { + private func activate(_ node: WorkspaceOutlineNode, preview: Bool) { guard let outline else { return } switch WorkspaceOutlineActivationPolicy.activation( isDirectory: node.isDirectory, isPlaceholder: node.isPlaceholder ) { case .open: - openFile(node.url) + openFile(node.url, preview) case .toggle: if outline.isItemExpanded(node) { outline.collapseItem(node) diff --git a/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift b/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift new file mode 100644 index 0000000000..871014e562 --- /dev/null +++ b/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift @@ -0,0 +1,81 @@ +import AppKit +import CoreText +import Foundation +import Testing +@testable import HerdrMacOS + +/// The strip's side of PRD editor-preview-tab: the italic title, the +/// "Preview" name, and the Keep Open chord (D-06, D-11, B16, B17). The core +/// decides which tab is the preview; these fix what the shell does with it. +@Suite("Editor preview tab presentation") +struct EditorPreviewTabPresentationTests { + private func editorTab(_ id: String, preview: Bool, kind: CoreEditorTabKind = .file) -> CoreEditorTabSnapshot { + CoreEditorTabSnapshot( + id: id, workspaceID: "w1", checkoutID: "c1", path: "/tmp/repo/\(id).md", label: "\(id).md", + kind: kind, diffCommitted: kind == .diff ? false : nil, dirty: false, preview: preview + ) + } + + @Test func thePreviewFlagRidesTheStripEntryOntoTheDrawnItem() { + let items = ShellTabStrip.items( + strip: [ + CoreStripTabSnapshot(id: "file:a", kind: .file, sourceID: "a", label: "a.md", preview: true), + CoreStripTabSnapshot(id: "diff:b", kind: .diff, sourceID: "b", label: "b.md (working diff)"), + CoreStripTabSnapshot(id: "herdr:t", kind: .herdr, sourceID: "t", label: "Tab 1"), + ], + herdrTabs: [], + editorTabs: [editorTab("a", preview: true), editorTab("b", preview: false, kind: .diff)], + activeHerdrTabID: nil, + activeFileTabID: "a" + ) + #expect(items.map(\.preview) == [true, false]) + #expect(items.map(\.active) == [true, false]) + } + + @Test func aPreviewTabIsNamedWithPreviewAndDrawnInItalicUntilPromoted() { + #expect(EditorTabTitlePresentation.spoken(label: "notes.md", preview: true) == "notes.md · Preview") + #expect(EditorTabTitlePresentation.spoken(label: "notes.md", preview: false) == "notes.md") + #expect(EditorTabTitlePresentation.italic(preview: true)) + #expect(!EditorTabTitlePresentation.italic(preview: false)) + } + + @Test func aStripEntryWithoutTheFlagDecodesAsAnOrdinaryTab() throws { + let entry = try JSONDecoder().decode( + CoreStripTabSnapshot.self, + from: Data(#"{"id":"file:a","kind":"file","source_id":"a","label":"a.md"}"#.utf8) + ) + #expect(!entry.preview) + let preview = try JSONDecoder().decode( + CoreStripTabSnapshot.self, + from: Data(#"{"id":"file:a","kind":"file","source_id":"a","label":"a.md","preview":true}"#.utf8) + ) + #expect(preview.preview) + } + + /// The italic variant is the same Inter face with the theme's slant in + /// its matrix, so the title changes only its angle: weight, features and + /// family stay what every other chrome label uses. + @Test @MainActor func theItalicChromeFontIsInterSlantedByThePreviewToken() throws { + let upright = HideTheme.nativeFont(size: HideTheme.Typography.body, weight: .semibold) + let italic = HideTheme.nativeFont(size: HideTheme.Typography.body, weight: .semibold, italic: true) + #expect(italic.familyName == upright.familyName) + #expect(italic.pointSize == upright.pointSize) + let matrix = CTFontGetMatrix(italic as CTFont) + let expected = tan(HideTheme.Typography.previewSlant * .pi / 180) + #expect(abs(matrix.c - expected) < 0.0001) + #expect(matrix.a == 1 && matrix.d == 1 && matrix.b == 0) + #expect(CTFontGetMatrix(upright as CTFont).c == 0) + let features = try #require(CTFontCopyAttribute(italic as CTFont, kCTFontFeatureSettingsAttribute) + as? [[String: Any]]) + #expect(features.contains { + ($0[kCTFontFeatureSelectorIdentifierKey as String] as? Int) == kStylisticAltThreeOnSelector + }) + } + + @Test func keepOpenIsAMenuCommandOnCommandShiftK() { + #expect(ShellMenuCommand.keepOpen.title == "Keep Open") + #expect(ShellMenuCommand.keepOpen.shortcut.canonical == "command+shift+k") + #expect(ShellMenuCommand.keepOpen.displayShortcut == "⇧⌘K") + #expect(ShellMenuCommand.keepOpen.scope == .applicationMenu) + } +} diff --git a/macos/Tests/HerdrMacOSTests/RightPanelPresentationTests.swift b/macos/Tests/HerdrMacOSTests/RightPanelPresentationTests.swift index b3cde2c774..efd5484d35 100644 --- a/macos/Tests/HerdrMacOSTests/RightPanelPresentationTests.swift +++ b/macos/Tests/HerdrMacOSTests/RightPanelPresentationTests.swift @@ -237,7 +237,8 @@ struct RightPanelPresentationTests { "label": "README.md", "kind": "file", "diff_committed": null, - "dirty": true + "dirty": true, + "preview": false }], "active_tab_id": "file:w:c:/repo/README.md", "document": { diff --git a/macos/Tests/HerdrMacOSTests/WorkspaceOutlineEditingTests.swift b/macos/Tests/HerdrMacOSTests/WorkspaceOutlineEditingTests.swift index c56f2061fe..538225fb91 100644 --- a/macos/Tests/HerdrMacOSTests/WorkspaceOutlineEditingTests.swift +++ b/macos/Tests/HerdrMacOSTests/WorkspaceOutlineEditingTests.swift @@ -101,7 +101,7 @@ import Testing #expect(FileManager.default.createFile(atPath: root.appendingPathComponent("src/lib.rs").path, contents: Data())) let calls = Calls() let coordinator = WorkspaceOutlineView.Coordinator( - openFile: { _ in }, + openFile: { _, _ in }, updateExpandedPaths: { _ in }, fileOperations: WorkspaceFileOperations( createFile: { calls.created.append(($0, $1)) }, @@ -345,7 +345,7 @@ import Testing let host = try await Self.makeHost() defer { host.tearDown() } let coordinator = WorkspaceOutlineView.Coordinator( - openFile: { _ in }, updateExpandedPaths: { _ in }, + openFile: { _, _ in }, updateExpandedPaths: { _ in }, fileOperations: WorkspaceFileOperations( createFile: { _, _ in }, createDirectory: { _, _ in }, rename: { _, _ in }, move: { _, _ in }, requestTrash: { _ in } From 07761b4381df7483d6cc3954ab575abda3e501b3 Mon Sep 17 00:00:00 2001 From: yansfil Date: Sat, 19 Sep 2026 13:22:06 +0900 Subject: [PATCH 5/5] Answer the Keep Open chord from the key monitor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The editor and the terminal both consume key equivalents before the application menu sees them, so ⇧⌘K reached nothing while a preview tab was showing; it now takes the same local monitor path as Reopen Closed Tab. --- macos/Sources/HerdrMacOS/HerdrApp.swift | 18 ++++++++++++++++++ .../EditorPreviewTabPresentationTests.swift | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/macos/Sources/HerdrMacOS/HerdrApp.swift b/macos/Sources/HerdrMacOS/HerdrApp.swift index d44b81d815..a20b518eb1 100644 --- a/macos/Sources/HerdrMacOS/HerdrApp.swift +++ b/macos/Sources/HerdrMacOS/HerdrApp.swift @@ -10,6 +10,18 @@ enum ReopenShortcutPolicy { } } +/// Keep Open reaches the model through the same local monitor as Reopen +/// Closed Tab: the chord is pressed while the editor or a terminal holds the +/// keyboard, and either responder can consume a key equivalent before the +/// application menu sees it. +@MainActor +enum KeepOpenShortcutPolicy { + static func shouldKeepOpen(_ event: NSEvent) -> Bool { + event.type == .keyDown + && ShellMenuCommand.keepOpen.shortcut.matches(event) + } +} + @MainActor enum MainWindowPresentation { static func present(_ window: NSWindow, application: NSApplication = .shared, background: Bool = false) { @@ -253,6 +265,12 @@ final class HerdrApplicationDelegate: NSObject, NSApplicationDelegate, NSMenuDel } return nil } + if KeepOpenShortcutPolicy.shouldKeepOpen(event) { + MainActor.assumeIsolated { + self.model.keepActiveEditorTabOpen() + } + return nil + } return event } presentMainWindow(window, source: "launch") diff --git a/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift b/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift index 871014e562..11f5da2273 100644 --- a/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift +++ b/macos/Tests/HerdrMacOSTests/EditorPreviewTabPresentationTests.swift @@ -78,4 +78,20 @@ struct EditorPreviewTabPresentationTests { #expect(ShellMenuCommand.keepOpen.displayShortcut == "⇧⌘K") #expect(ShellMenuCommand.keepOpen.scope == .applicationMenu) } + + /// The chord is pressed while the editor holds the keyboard, so the local + /// monitor answers it the way it answers Reopen Closed Tab; a plain ⌘K + /// (Search) and a key-up are not it. + @MainActor + @Test func keepOpenChordIsAnsweredRegardlessOfFocus() { + func event(_ type: NSEvent.EventType, _ modifiers: NSEvent.ModifierFlags) -> NSEvent { + NSEvent.keyEvent( + with: type, location: .zero, modifierFlags: modifiers, timestamp: 0, windowNumber: 0, + context: nil, characters: "K", charactersIgnoringModifiers: "k", isARepeat: false, keyCode: 40 + )! + } + #expect(KeepOpenShortcutPolicy.shouldKeepOpen(event(.keyDown, [.command, .shift]))) + #expect(!KeepOpenShortcutPolicy.shouldKeepOpen(event(.keyDown, [.command]))) + #expect(!KeepOpenShortcutPolicy.shouldKeepOpen(event(.keyUp, [.command, .shift]))) + } }