Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rapid-themes-stay-open.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hunkdiff": patch
---

Keep the theme selector responsive and its highlighted row visible during rapid keyboard navigation.
99 changes: 79 additions & 20 deletions src/ui/components/chrome/ThemeSelectorDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,40 @@ export interface ThemeSelectorItem {

const THEME_HOVER_PREVIEW_DELAY_MS = 200;

interface ThemeSelectorWindowState {
itemCount: number;
selectedIndex: number;
visibleRows: number;
windowStart: number;
}

/** Keep the selected theme visible when selector geometry or selection changes. */
function synchronizeThemeSelectorWindow(
current: ThemeSelectorWindowState,
selectedIndex: number,
itemCount: number,
visibleRows: number,
): ThemeSelectorWindowState {
if (
current.selectedIndex === selectedIndex &&
current.itemCount === itemCount &&
current.visibleRows === visibleRows
) {
return current;
}

const maxWindowStart = Math.max(0, itemCount - visibleRows);
const clamped = Math.min(Math.max(current.windowStart, 0), maxWindowStart);
const windowStart =
selectedIndex < clamped
? Math.max(0, selectedIndex)
: selectedIndex >= clamped + visibleRows
? Math.min(maxWindowStart, selectedIndex - visibleRows + 1)
: clamped;

return { itemCount, selectedIndex, visibleRows, windowStart };
}

/** Render an opencode-style selector for Hunk themes. */
export function ThemeSelectorDialog({
items,
Expand All @@ -39,11 +73,27 @@ export function ThemeSelectorDialog({
const bodyWidth = Math.max(1, width - 4);
// ModalFrame contributes border/title/padding; reserve help/footer rows inside the body.
const visibleRows = Math.max(4, modalHeight - 7);
const [windowStart, setWindowStart] = useState(() =>
listWindowStart(selectedIndex, items.length, visibleRows),
);
const [windowState, setWindowState] = useState<ThemeSelectorWindowState>(() => ({
itemCount: items.length,
selectedIndex,
visibleRows,
windowStart: listWindowStart(selectedIndex, items.length, visibleRows),
}));
const previewTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const maxWindowStart = Math.max(0, items.length - visibleRows);
const synchronizedWindowState = synchronizeThemeSelectorWindow(
windowState,
selectedIndex,
items.length,
visibleRows,
);

// Adjust during render so the selected row cannot paint outside a stale window. React restarts
// this component immediately, avoiding the passive-effect update loop that rapid key repeat hit.
if (synchronizedWindowState !== windowState) {
setWindowState(synchronizedWindowState);
}
const windowStart = synchronizedWindowState.windowStart;

/** Cancel a hover preview that has not reached its dwell threshold. */
const cancelPendingPreview = () => {
Expand All @@ -62,21 +112,8 @@ export function ThemeSelectorDialog({
}, THEME_HOVER_PREVIEW_DELAY_MS);
};

// Keyboard selection changes keep their row visible and supersede pending pointer previews,
// while mouse-wheel scrolling can move the window without changing the current preview.
useEffect(() => {
cancelPendingPreview();
setWindowStart((current) => {
const clamped = Math.min(Math.max(current, 0), maxWindowStart);
if (selectedIndex < clamped) {
return Math.max(0, selectedIndex);
}
if (selectedIndex >= clamped + visibleRows) {
return Math.min(maxWindowStart, selectedIndex - visibleRows + 1);
}
return clamped;
});
}, [maxWindowStart, selectedIndex, visibleRows]);
// Selection, catalog, or geometry changes supersede a pointer dwell without another render.
useEffect(cancelPendingPreview, [items, selectedIndex, visibleRows]);

useEffect(
() => () => {
Expand All @@ -103,9 +140,31 @@ export function ThemeSelectorDialog({
cancelPendingPreview();
const direction = event.scroll?.direction;
if (direction === "up") {
setWindowStart((current) => Math.max(0, current - 1));
setWindowState((current) => {
const synchronized = synchronizeThemeSelectorWindow(
current,
selectedIndex,
items.length,
visibleRows,
);
const windowStart = Math.max(0, synchronized.windowStart - 1);
return windowStart === synchronized.windowStart
? synchronized
: { ...synchronized, windowStart };
});
} else if (direction === "down") {
setWindowStart((current) => Math.min(maxWindowStart, current + 1));
setWindowState((current) => {
const synchronized = synchronizeThemeSelectorWindow(
current,
selectedIndex,
items.length,
visibleRows,
);
const windowStart = Math.min(maxWindowStart, synchronized.windowStart + 1);
return windowStart === synchronized.windowStart
? synchronized
: { ...synchronized, windowStart };
});
}
}}
>
Expand Down
37 changes: 36 additions & 1 deletion test/pty/chrome.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createPtyHarness, lineIndexOf, rowCellBackgrounds } from "./harness";
import { availableThemes } from "../../src/ui/themes";
import { createPtyHarness, lineIndexOf, rowCellBackgrounds, sleep } from "./harness";

const harness = createPtyHarness();

Expand Down Expand Up @@ -82,6 +83,40 @@ describe("PTY chrome", () => {
}
});

test("rapid theme preview key repeats keep the selector responsive", async () => {
const initialThemeId = "github-dark-default";
const themes = availableThemes();
const fixture = harness.createRapidThemePreviewTestRepoFixture();
const session = await harness.launchHunk({
args: ["diff", "--theme", initialThemeId],
cwd: fixture.dir,
cols: 120,
rows: 24,
});

try {
await session.waitForText(/View\s+Navigate\s+Agent\s+Help/, { timeout: 15_000 });
await session.press("t");
await session.waitForText(/Theme selector/, { timeout: 5_000 });

// OS key repeat arrives as a rapid stream while React/OpenTUI drains each preview render.
for (let index = 0; index < 100; index += 1) {
session.writeRaw("j");
await sleep(30);
}
await session.waitIdle({ timeout: 800 });
const selector = await session.text({ immediate: true });

expect(selector).not.toContain("Maximum update depth exceeded");
expect(selector).toContain("Theme selector");
const selectedIndex = themes.findIndex((theme) => selector.includes(`› ${theme.id}`));
expect(selectedIndex).toBeGreaterThanOrEqual(0);
expect(themes[selectedIndex]?.id).not.toBe(initialThemeId);
} finally {
Comment on lines +113 to +115

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Navigation assertion accepts no movement

The test accepts any highlighted theme, including the initial github-dark-default selection, so it can pass when all repeated j inputs are ignored and never exercise the selection/window synchronization regression.

Prompt To Fix With AI
This is a comment left during a code review.
Path: test/pty/chrome.test.ts
Line: 113-114

Comment:
**Navigation assertion accepts no movement**

The test accepts any highlighted theme, including the initial `github-dark-default` selection, so it can pass when all repeated `j` inputs are ignored and never exercise the selection/window synchronization regression.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Updated the PTY regression to assert that the selected theme differs from the configured initial theme, so ignored repeat input now fails the test. The focused regression passes across five consecutive runs.

Responded by Pi using gpt-5.6-sol.

This comment was generated by Pi using gpt-5.6-sol

session.close();
}
});

test("quit prompt shows the config diff and saves preferences on mouse click", async () => {
// Own both config scopes so the test can assert what the save action wrote without an
// ambient repository `.hunk/config.toml` changing the starting preferences.
Expand Down
12 changes: 12 additions & 0 deletions test/pty/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,17 @@ end
]);
}

/** Build enough syntax-highlighted changes to exercise rapid whole-review theme previews. */
function createRapidThemePreviewTestRepoFixture() {
return createGitRepoFixture(
Array.from({ length: 8 }, (_, fileIndex) => ({
path: `theme-preview-${fileIndex}.ts`,
before: `${createNumberedExportLines(1, 150, fileIndex * 1_000)}\n`,
after: `${createNumberedExportLines(1, 150, (fileIndex + 8) * 1_000)}\n`,
})),
);
}

function createCollapsedTopRepoFixture() {
const longBefore =
Array.from(
Expand Down Expand Up @@ -1083,6 +1094,7 @@ end
createNarrowHeaderTestRepoFixture,
createPagerPatchFixture,
createPinnedHeaderRepoFixture,
createRapidThemePreviewTestRepoFixture,
createScrollableFilePair,
createSidebarJumpRepoFixture,
createTabbedFilePair,
Expand Down
Loading