diff --git a/.changeset/tui-change-list-scroll.md b/.changeset/tui-change-list-scroll.md new file mode 100644 index 00000000..5481fa83 --- /dev/null +++ b/.changeset/tui-change-list-scroll.md @@ -0,0 +1,5 @@ +--- +"@noormdev/cli": patch +--- + +TUI: the Changes screen scrolls. It drew every change at once, so a project with more changes than the terminal had rows squashed the list, hid the newest changes and pushed the status bar off screen; it now windows around the cursor with `↑ N more` / `↓ N more` lines, keeps its detail box to three lines, and drops the box on a terminal too short to hold it. Every terminal-sized list (select lists, searchable lists, the file picker) now counts its scroll-indicator lines in its row budget instead of drawing one or two rows past it. diff --git a/.claude/rules/tui-development.md b/.claude/rules/tui-development.md index c396128b..ec88fc8d 100644 --- a/.claude/rules/tui-development.md +++ b/.claude/rules/tui-development.md @@ -426,7 +426,7 @@ It is **on** unless `ui.mouse` is false in `.noorm/settings.yml`. Off means iner | API | What it covers | |-----|----------------| | `usePaste` | Bracketed paste delivered as a single string. `SqlInput` currently submits only the first line of a multi-line paste. | -| `useBoxMetrics` | Used for the height of `Form`'s status error and the width `TextInput` scrolls within. Still unused for measured box width/height/left/top instead of the hand-counted chrome constants at `SqlTerminalScreen.tsx:57` and `ConfigEditScreen.tsx:268`. | +| `useBoxMetrics` | Used for the height of `Form`'s status error, the width `TextInput` scrolls within, and the rows `ChangeListScreen`'s hint row wraps to. Still unused for measured box width/height/left/top instead of the hand-counted chrome constants at `SqlTerminalScreen.tsx:57` and `ConfigEditScreen.tsx:268`. | | `useAnimation`, `suspendTerminal()`, `interactive` | No current need. | `` no longer accepts `wrap="end"` or `wrap="middle"`. Both were undocumented no-ops on 6.8.0 and were dropped from the type in 7.0.0. This codebase uses `wrap="wrap"`, `wrap="truncate"`, and `wrap="truncate-start"` (`FilePicker` paths, where the end is what identifies a file), so nothing changed. diff --git a/docs/public/image/tui/changes-list.png b/docs/public/image/tui/changes-list.png index c9d23153..45176b56 100644 Binary files a/docs/public/image/tui/changes-list.png and b/docs/public/image/tui/changes-list.png differ diff --git a/src/tui/components/dialogs/FilePicker.tsx b/src/tui/components/dialogs/FilePicker.tsx index 88562e34..1fbf9a15 100644 --- a/src/tui/components/dialogs/FilePicker.tsx +++ b/src/tui/components/dialogs/FilePicker.tsx @@ -23,7 +23,7 @@ import type { ReactElement } from 'react'; import { useFocusScope } from '../../focus.js'; import { hoverBackground, useRowMouse } from '../../mouse.js'; -import { useViewportRows } from '../../hooks/useViewportRows.js'; +import { rowsThatFit, useViewportRows } from '../../hooks/useViewportRows.js'; import { Panel } from '../layout/Panel.js'; import { Hotkey } from '../layout/Hotkey.js'; @@ -116,7 +116,6 @@ export function FilePicker({ }: FilePickerProps): ReactElement { const availableRows = useViewportRows(PICKER_CHROME_ROWS + reserveRows); - const visibleCount = pinnedVisibleCount ?? availableRows; const { isFocused } = useFocusScope(focusLabel); @@ -129,6 +128,7 @@ export function FilePicker({ // Filtered files based on search const filteredFiles = useMemo(() => filterFiles(files, search), [files, search]); + const visibleCount = pinnedVisibleCount ?? rowsThatFit(filteredFiles.length, availableRows); // Visible files window const visibleFiles = useMemo( diff --git a/src/tui/components/lists/SearchableList.tsx b/src/tui/components/lists/SearchableList.tsx index 55b75e56..5cc523bd 100644 --- a/src/tui/components/lists/SearchableList.tsx +++ b/src/tui/components/lists/SearchableList.tsx @@ -20,7 +20,6 @@ import { TextInput } from '../forms/TextInput.js'; import type { ReactElement } from 'react'; import { useFocusScope } from '../../focus.js'; -import { useViewportRows } from '../../hooks/useViewportRows.js'; import { SelectList } from './SelectList.js'; import { Hotkey, KeyTarget } from '../layout/Hotkey.js'; @@ -130,11 +129,6 @@ export function SearchableList({ renderItem, }: SearchableListProps): ReactElement { - // The wrapped SelectList is handed a resolved number, so it never - // double-counts this component's search and hint rows. - const availableRows = useViewportRows(SEARCH_CHROME_ROWS + reserveRows); - const visibleCount = pinnedVisibleCount ?? availableRows; - // Focus management const hasExternalFocus = externalFocused !== undefined; const internalFocus = useFocusScope({ @@ -346,7 +340,8 @@ export function SearchableList({ items={filteredItems} onSelect={onSelect} onHighlight={handleHighlightChange} - visibleCount={visibleCount} + visibleCount={pinnedVisibleCount} + reserveRows={SEARCH_CHROME_ROWS + reserveRows} isFocused={isFocused && !searchMode} numberNav={numberNav} defaultValue={currentHighlightedKey} diff --git a/src/tui/components/lists/SelectList.tsx b/src/tui/components/lists/SelectList.tsx index 40681fd2..46da4ef3 100644 --- a/src/tui/components/lists/SelectList.tsx +++ b/src/tui/components/lists/SelectList.tsx @@ -22,7 +22,7 @@ import { useFocusScope } from '../../focus.js'; import { hoverBackground, useRowMouse } from '../../mouse.js'; import { useOptionalRouter } from '../../router.js'; import { listMemoryKey, recallListPosition, rememberListPosition } from '../../list-memory.js'; -import { useViewportRows } from '../../hooks/useViewportRows.js'; +import { rowsThatFit, useViewportRows } from '../../hooks/useViewportRows.js'; /** * Item in a SelectList. @@ -176,7 +176,6 @@ export function SelectList({ // under-fills a mixed list rather than running it off the bottom. const availableRows = useViewportRows(reserveRows); const rowsPerItem = showDescriptionBelow ? 2 : 1; - const visibleCount = pinnedVisibleCount ?? Math.max(1, Math.floor(availableRows / rowsPerItem)); // Use external focus if provided, otherwise manage own focus scope const hasExternalFocus = externalFocused !== undefined; @@ -189,6 +188,10 @@ export function SelectList({ // Filter enabled items const enabledItems = useMemo(() => items.filter((item) => !item.disabled), [items]); + // A pinned count is an item count by contract, so the indicators stay on top of it. + const itemRows = rowsThatFit(enabledItems.length * rowsPerItem, availableRows); + const visibleCount = pinnedVisibleCount ?? Math.max(1, Math.floor(itemRows / rowsPerItem)); + // Refs for latest values - useInput handler reads these to avoid stale closures const enabledItemsRef = useRef(enabledItems); const onSelectRef = useRef(onSelect); diff --git a/src/tui/components/terminal/viewport.ts b/src/tui/components/terminal/viewport.ts index 313378a7..9d073931 100644 --- a/src/tui/components/terminal/viewport.ts +++ b/src/tui/components/terminal/viewport.ts @@ -19,20 +19,14 @@ */ import type { Key } from 'ink'; +import { SCROLL_INDICATOR_ROWS } from '../../hooks/useViewportRows.js'; + /** Columns a Panel spends on its border and horizontal padding. */ const PANEL_CHROME_COLUMNS = 4; /** Narrowest row worth planning for. Below it the terminal is unusable anyway. */ const MIN_ROW_COLUMNS = 24; -/** - * Rows the two scroll indicators claim once the content overflows. - * - * Held back as a pair rather than per-indicator so the viewport keeps one - * height for the whole scroll, instead of growing a row at each end. - */ -const INDICATOR_ROWS = 2; - /** * Columns a row inside a Panel actually gets. * @@ -83,7 +77,7 @@ export function rowWindow(total: number, offset: number, budget: number): RowWin } - const count = Math.max(1, budget - INDICATOR_ROWS); + const count = Math.max(1, budget - SCROLL_INDICATOR_ROWS); const start = Math.min(Math.max(offset, 0), total - count); return { start, count, above: start, below: total - start - count }; diff --git a/src/tui/hooks/useViewportRows.ts b/src/tui/hooks/useViewportRows.ts index d9513052..8a1ff03a 100644 --- a/src/tui/hooks/useViewportRows.ts +++ b/src/tui/hooks/useViewportRows.ts @@ -75,6 +75,37 @@ export function viewportRows(terminalRows: number, reserveRows = 0): number { } +/** + * Rows the `↑ N more` and `↓ N more` lines claim once a list overflows. + * + * Held back as a pair rather than per indicator, so the list keeps one height + * for the whole scroll instead of growing a row at each end. + */ +export const SCROLL_INDICATOR_ROWS = 2; + +/** + * Rows a list's items may take once its scroll indicators are paid for, or its + * indicators push the screen's footer off the bottom. Below + * `MIN_VIEWPORT_ROWS + SCROLL_INDICATOR_ROWS` the indicators overflow instead + * of shrinking the list under the floor. + * + * @example + * rowsThatFit(4, 20); // 20 — fits, no indicators + * rowsThatFit(60, 20); // 18 — two rows go to the indicators + * rowsThatFit(60, 5); // 5 — the floor + */ +export function rowsThatFit(itemRows: number, budget: number): number { + + if (itemRows <= budget) { + + return budget; + + } + + return Math.max(budget - SCROLL_INDICATOR_ROWS, MIN_VIEWPORT_ROWS); + +} + /** * Rows the calling component may draw, recomputed whenever the terminal resizes. * @@ -83,9 +114,12 @@ export function viewportRows(terminalRows: number, reserveRows = 0): number { * size. Call it above any early return, or the hook count changes across an * async load boundary. * + * Pass a list's chrome as `reserveRows` rather than pinning this as its + * `visibleCount`: a pinned count is an item count, so the list's scroll + * indicators would be drawn on top of the budget. + * * @example * const rows = useViewportRows(bannerRows); - * */ export function useViewportRows(reserveRows = 0): number { diff --git a/src/tui/screens/change/ChangeListScreen.tsx b/src/tui/screens/change/ChangeListScreen.tsx index af2c85e0..cdbb9bdd 100644 --- a/src/tui/screens/change/ChangeListScreen.tsx +++ b/src/tui/screens/change/ChangeListScreen.tsx @@ -10,23 +10,41 @@ * noorm change list # Same thing * ``` */ -import { useState, useMemo } from 'react'; -import { Box, Text, useInput } from 'ink'; +import { useRef, useState } from 'react'; +import { Box, Text, useBoxMetrics, useInput, useWindowSize } from 'ink'; +import type { DOMElement } from 'ink'; import type { ReactElement } from 'react'; import type { ScreenProps } from '../../types.js'; +import type { SelectListItem, SelectListRowState } from '../../components/index.js'; import type { ChangeListItem } from '../../../core/change/types.js'; import { attempt } from '@logosdx/utils'; import { useRouter } from '../../router.js'; import { useFocusScope } from '../../focus.js'; import { useAppContext } from '../../app-context.js'; -import { Panel, Spinner } from '../../components/index.js'; +import { Panel, Spinner, SelectList } from '../../components/index.js'; import { useAsyncEffect } from '../../hooks/index.js'; -import { getErrorMessage, loadChangesWithStatus, buildMergedChangeList } from '../../utils/index.js'; +import { MIN_VIEWPORT_ROWS, SCREEN_CHROME_ROWS, SCROLL_INDICATOR_ROWS } from '../../hooks/useViewportRows.js'; +import { getErrorMessage, loadChangesWithStatus, buildMergedChangeList, oneLine } from '../../utils/index.js'; import { relativeTimeAgo } from '../../utils/date.js'; import { Hotkey, KeyTarget } from '../../components/layout/Hotkey.js'; +/** + * Rows this screen spends inside its Panel above the list: the statistics line + * and the gap under it. The hint row's first line and the gap above it are in + * `SCREEN_CHROME_ROWS`; any line the hints wrap onto is measured. + */ +const CHROME_ROWS = 2; + +/** + * Rows the detail box costs: the gap above it, two borders, three lines. + * + * Fixed at three lines whatever the change, as in `ChangeHistoryScreen`, so a + * long database error cannot push the list off the screen. + */ +const DETAIL_ROWS = 6; + /** * Get status indicator for a change. */ @@ -57,6 +75,68 @@ function getStatusIndicator(item: ChangeListItem): { symbol: string; color: stri } +/** + * Whether Enter and `r` run this change. + */ +function isRunnable(item: ChangeListItem): boolean { + + return item.status === 'pending' || item.status === 'failed' || item.status === 'reverted'; + +} + +/** + * What Enter does on this change, for the detail box's last line. + */ +function detailHint(item: ChangeListItem): string { + + if (isRunnable(item)) { + + return 'Press Enter to run'; + + } + + if (item.status === 'success') { + + return 'Press Enter to revert'; + + } + + return ''; + +} + +/** + * One change row. Must stay one line: `SelectList` windows by item, not by row. + */ +function changeRow(cs: ChangeListItem, state: SelectListRowState): ReactElement { + + const indicator = getStatusIndicator(cs); + const isActive = state.isHighlighted && state.isFocused; + + return ( + <> + {indicator.symbol} + + {oneLine(cs.name)} + + + {cs.status === 'success' && cs.appliedAt && ( + <> {relativeTimeAgo(cs.appliedAt)} + )} + {cs.status === 'pending' && ' pending'} + {cs.status === 'reverted' && ' reverted'} + {cs.status === 'failed' && ' failed'} + {cs.orphaned && ' (orphaned)'} + + + ); + +} + /** * ChangeListScreen component. */ @@ -69,7 +149,12 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement const [changes, setChanges] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); - const [selectedIndex, setSelectedIndex] = useState(0); + const [selectedChange, setSelectedChange] = useState(null); + + // Above every early return so the hook count stays fixed across the async load. + const { rows: terminalRows } = useWindowSize(); + const hintsRef = useRef(null); + const { height: hintRows } = useBoxMetrics(hintsRef); // Load changes useAsyncEffect(async (isCancelled) => { @@ -95,6 +180,10 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement const merged = buildMergedChangeList(diskChanges, statuses, failures); + // The list reports a highlight only while it has rows, so an empty + // reload would otherwise leave the keys acting on a vanished change. + if (merged.length === 0) setSelectedChange(null); + setChanges(merged); }); @@ -113,35 +202,12 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement }, [activeConfig, activeConfigName, loadingStatus]); - // Get selected change - const selectedChange = useMemo(() => { - - return changes[selectedIndex]; - - }, [changes, selectedIndex]); - - // Keyboard handling + // Arrows and Enter belong to the SelectList below; this handles only what + // the screen itself owns. useInput((input, key) => { if (!isFocused) return; - // Navigation - if (key.upArrow) { - - setSelectedIndex((prev) => Math.max(0, prev - 1)); - - return; - - } - - if (key.downArrow) { - - setSelectedIndex((prev) => Math.min(changes.length - 1, prev + 1)); - - return; - - } - if (key.escape) { back(); @@ -175,7 +241,7 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement } - if (input === 'r' && selectedChange && (selectedChange.status === 'pending' || selectedChange.status === 'failed' || selectedChange.status === 'reverted')) { + if (input === 'r' && selectedChange && isRunnable(selectedChange)) { navigate('change/run', { name: selectedChange.name }); @@ -219,24 +285,6 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement navigate('change/history'); - return; - - } - - // Enter - smart action based on status - if (key.return && selectedChange) { - - if (selectedChange.status === 'pending' || selectedChange.status === 'failed' || selectedChange.status === 'reverted') { - - navigate('change/run', { name: selectedChange.name }); - - } - else if (selectedChange.status === 'success') { - - navigate('change/revert', { name: selectedChange.name }); - - } - } }); @@ -283,6 +331,19 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement const failed = changes.filter((cs) => cs.status === 'failed').length; const orphaned = changes.filter((cs) => cs.orphaned).length; + const items: SelectListItem[] = changes.map((cs) => ({ + key: cs.name, + label: cs.name, + value: cs, + })); + + // The detail box is the first thing a short terminal gives up: the list row + // already carries the status, and a list cut below its floor overflows. + const wrappedHintRows = Math.max(0, hintRows - 1); + const rowsBesideDetail = terminalRows - SCREEN_CHROME_ROWS - CHROME_ROWS - wrappedHintRows - DETAIL_ROWS; + const showDetail = rowsBesideDetail >= Math.min(changes.length, MIN_VIEWPORT_ROWS + SCROLL_INDICATOR_ROWS); + const reserveRows = CHROME_ROWS + wrappedHintRows + (showDetail ? DETAIL_ROWS : 0); + return ( @@ -311,80 +372,66 @@ export function ChangeListScreen({ params: _params }: ScreenProps): ReactElement {/* Change List */} {changes.length === 0 ? ( - + No changes found. Press [a] to create one. ) : ( - - {changes.map((cs, index) => { - - const isSelected = index === selectedIndex; - const indicator = getStatusIndicator(cs); - - return ( - - - {isSelected ? '>' : ' '} - - {indicator.symbol} - - {cs.name} - - - {cs.status === 'success' && cs.appliedAt && ( - <> {relativeTimeAgo(cs.appliedAt)} - )} - {cs.status === 'pending' && ' pending'} - {cs.status === 'reverted' && ' reverted'} - {cs.status === 'failed' && ' failed'} - {cs.orphaned && ' (orphaned)'} - - - ); + + changeRow(item.value, state)} + onHighlight={(item) => setSelectedChange(item.value)} + onSelect={(item) => { + + if (isRunnable(item.value)) { + + navigate('change/run', { name: item.value.name }); + + } + else if (item.value.status === 'success') { + + navigate('change/revert', { name: item.value.name }); - })} + } + + }} + /> )} - {/* Selected change details */} - {selectedChange && ( + {/* Selected change details, fixed at three lines - see DETAIL_ROWS */} + {showDetail && selectedChange && ( - {selectedChange.name} - - - Change files: {selectedChange.changeFiles?.length ?? 0} - - - Revert files: {selectedChange.revertFiles?.length ?? 0} - - - {selectedChange.appliedBy && ( - Applied by: {selectedChange.appliedBy} - )} - {selectedChange.status === 'failed' && selectedChange.errorMessage && ( - - Error: - - {selectedChange.errorMessage} - + {oneLine(selectedChange.name)} + + Change files: {selectedChange.changeFiles?.length ?? 0} + {' '}Revert files: {selectedChange.revertFiles?.length ?? 0} + {selectedChange.appliedBy && ` Applied by: ${selectedChange.appliedBy}`} + + {selectedChange.status === 'failed' && selectedChange.errorMessage ? ( + + + {oneLine(selectedChange.errorMessage)} + + + full error: [h] History, select it, [e] + + ) : ( + {detailHint(selectedChange)} )} )} - {/* Keyboard hints */} - + {/* Keyboard hints, measured - see CHROME_ROWS */} + Add Edit Delete diff --git a/tests/cli/hooks/useViewportRows.test.tsx b/tests/cli/hooks/useViewportRows.test.tsx index 771226db..8b251599 100644 --- a/tests/cli/hooks/useViewportRows.test.tsx +++ b/tests/cli/hooks/useViewportRows.test.tsx @@ -146,6 +146,38 @@ describe('cli: useViewportRows', () => { }); + // The `↑ N more` / `↓ N more` lines are rows too. Left out of the + // budget, a scrolled list drew two rows past it and pushed the screen's + // hotkey footer off the bottom of the terminal. + it('should fit its scroll indicators inside the budget while scrolled', async () => { + + pinTerminal(30); + + const { stdin, lastFrame, unmount } = render( + , + ); + + // Press until the window has scrolled off both ends, polling rather + // than betting on a fixed sleep for focus and each repaint. + const scrolled = () => /↑ \d+ more/.test(lastFrame() ?? '') && /↓ \d+ more/.test(lastFrame() ?? ''); + const deadline = Date.now() + 2000; + + while (!scrolled() && Date.now() < deadline) { + + stdin.write('\u001B[B'); + await new Promise((resolve) => setTimeout(resolve, 10)); + + } + + const frame = lastFrame() ?? ''; + unmount(); + + expect(frame).toMatch(/↑ \d+ more/); + expect(frame).toMatch(/↓ \d+ more/); + expect(frame.split('\n').length).toBeLessThanOrEqual(viewportRows(30)); + + }); + }); describe('SearchableList', () => { @@ -167,6 +199,21 @@ describe('cli: useViewportRows', () => { }); + it('should draw no more lines than the budget, search row and scroll indicators included', () => { + + pinTerminal(30); + + const { lastFrame, unmount } = render( + , + ); + const frame = lastFrame() ?? ''; + unmount(); + + expect(frame).toMatch(/↓ \d+ more/); + expect(frame.split('\n').length).toBeLessThanOrEqual(viewportRows(30)); + + }); + }); describe('FilePicker', () => { @@ -180,6 +227,25 @@ describe('cli: useViewportRows', () => { }); + // The picker brings its own Panel and help line, so the whole frame has + // to fit what the shell leaves: the terminal less the breadcrumb, the + // status bar and their two rules. + it('should fit the terminal, scroll indicator included', () => { + + pinTerminal(30); + + const files = Array.from({ length: 60 }, (_, index) => `row-${index}.sql`); + const { lastFrame, unmount } = render( + {}} onCancel={() => {}} />, + ); + const frame = lastFrame() ?? ''; + unmount(); + + expect(frame).toMatch(/↓ \d+ more/); + expect(frame.split('\n').length).toBeLessThanOrEqual(30 - 4); + + }); + }); describe('resize', () => { diff --git a/tests/cli/screens/change/change-list-scroll.test.tsx b/tests/cli/screens/change/change-list-scroll.test.tsx new file mode 100644 index 00000000..99deeeef --- /dev/null +++ b/tests/cli/screens/change/change-list-scroll.test.tsx @@ -0,0 +1,258 @@ +/** + * ChangeListScreen windowing tests: the frame fits the terminal whatever the + * change count, and the arrow keys reach every change. Changes are real folders + * scanned against a real sqlite database, so the row count is what a project loads. + */ +import { describe, it, expect, vi, mock, beforeEach, afterEach } from 'bun:test'; +import { render } from 'ink-testing-library'; +import React from 'react'; +import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { FocusProvider } from '../../../../src/tui/focus.js'; +import { RouterProvider } from '../../../../src/tui/router.js'; +import { AppContextProvider } from '../../../../src/tui/app-context.js'; +import { ToastProvider } from '../../../../src/tui/components/index.js'; +import { ChangeListScreen } from '../../../../src/tui/screens/change/ChangeListScreen.js'; + +const actualCore = await import('../../../../src/core/index.js'); +const actualIdentity = await import('../../../../src/core/identity/index.js'); + +/** Rows the app shell takes outside the screen: breadcrumb, status bar, and their rules. */ +const SHELL_ROWS = 4; + +/** More changes than either terminal size under test can hold, so the list must window. */ +const CHANGE_COUNT = 40; + +/** Property descriptors to put back, so a pinned size cannot leak to the next file. */ +const originalStdout = { + columns: Object.getOwnPropertyDescriptor(process.stdout, 'columns'), + rows: Object.getOwnPropertyDescriptor(process.stdout, 'rows'), +}; + +let database = ''; + +function makeConfig() { + + return { + name: 'test', + type: 'local' as const, + isTest: true, + access: { user: 'admin' as const, agent: 'admin' as const }, + connection: { dialect: 'sqlite' as const, database }, + }; + +} + +const mockStateManager = { + load: vi.fn().mockResolvedValue(undefined), + getActiveConfig: vi.fn(() => makeConfig()), + getActiveConfigName: vi.fn().mockReturnValue('test'), + listConfigs: vi.fn(() => [makeConfig()]), + getConfig: vi.fn(() => makeConfig()), + setConfig: vi.fn().mockResolvedValue(undefined), + setActiveConfig: vi.fn().mockResolvedValue(undefined), + hasPrivateKey: vi.fn().mockReturnValue(true), + isLoaded: true, +}; + +const mockSettingsManager = { + load: vi.fn().mockResolvedValue({ version: '0.1.0' }), + isLoaded: true, + settings: { version: '0.1.0' }, + getStages: vi.fn().mockReturnValue({}), + getStage: vi.fn().mockReturnValue(undefined), +}; + +mock.module('../../../../src/core/index.js', () => ({ + ...actualCore, + getStateManager: vi.fn(() => mockStateManager), + getSettingsManager: vi.fn(() => mockSettingsManager), + resetStateManager: vi.fn(), + resetSettingsManager: vi.fn(), +})); + +mock.module('../../../../src/core/identity/index.js', () => ({ + ...actualIdentity, + loadExistingIdentity: vi.fn().mockResolvedValue(null), +})); + +// eslint-disable-next-line no-control-regex -- matching the ANSI SGR escape is the point +const plain = (frame: string | undefined) => (frame ?? '').replace(/\x1B\[[0-9;]*m/g, ''); + +/** + * Poll rather than sleep a guessed duration: a fixed wait is the suite's known + * flake class under load. + */ +async function waitFor(predicate: () => boolean, timeoutMs = 4000): Promise { + + const deadline = Date.now() + timeoutMs; + + while (!predicate()) { + + if (Date.now() > deadline) throw new Error(`condition not met within ${timeoutMs}ms`); + + await new Promise((resolve) => setTimeout(resolve, 10)); + + } + +} + +/** Change folder name for index `i`, one day apart so the sort order is fixed. */ +function changeName(i: number): string { + + const day = new Date(Date.UTC(2025, 0, 1 + i)).toISOString().slice(0, 10); + + return `${day}-change-${String(i).padStart(2, '0')}`; + +} + +describe('cli: ChangeListScreen windowing', () => { + + let projectRoot: string; + + beforeEach(async () => { + + projectRoot = await mkdtemp(join(tmpdir(), 'noorm-change-list-')); + database = join(projectRoot, 'test.db'); + + for (let i = 0; i < CHANGE_COUNT; i++) { + + const changeDir = join(projectRoot, 'db', 'changes', changeName(i), 'change'); + await mkdir(changeDir, { recursive: true }); + await writeFile(join(changeDir, '001_step.sql'), 'SELECT 1;'); + + } + + }); + + afterEach(async () => { + + // `process.stdout` usually has no own `rows`/`columns`, and leaving the + // pinned ones behind hands this terminal size to every later file. + for (const [key, descriptor] of Object.entries(originalStdout)) { + + if (descriptor) { + + Object.defineProperty(process.stdout, key, descriptor); + + } + else { + + Reflect.deleteProperty(process.stdout, key); + + } + + } + + await rm(projectRoot, { recursive: true, force: true }); + + }); + + /** + * Render the screen into a terminal `rows` high. + * + * Both dimensions are pinned because `terminal-size` only trusts + * `process.stdout` when both are set. + */ + function open(rows: number) { + + Object.defineProperty(process.stdout, 'columns', { value: 100, configurable: true }); + Object.defineProperty(process.stdout, 'rows', { value: rows, configurable: true }); + + return render( + + + + + + + + + , + ); + + } + + /** + * Wait until the loaded frame fits the rows the shell leaves the screen. + * + * The hint row is measured, and the detail box appears once the list reports + * its first highlight, so the early frames differ from the one the screen + * settles on. `mustShow` names text that only the settled frame carries. + */ + async function waitToFit(lastFrame: () => string | undefined, rows: number, mustShow = '[Esc] Back'): Promise { + + await waitFor(() => { + + const frame = plain(lastFrame()); + + return frame.includes(`Total: ${CHANGE_COUNT}`) + && frame.includes(mustShow) + && frame.split('\n').length <= rows - SHELL_ROWS; + + }); + + return plain(lastFrame()); + + } + + it('should fit the terminal and keep the hotkey hints on screen when changes outnumber the rows', async () => { + + const { lastFrame, unmount } = open(30); + + const frame = await waitToFit(lastFrame, 30, 'Revert files'); + unmount(); + + expect(frame).toContain('[Esc] Back'); + expect(frame).toContain(changeName(CHANGE_COUNT - 1)); + expect(frame).toMatch(/↓ \d+ more/); + + }, 20_000); + + it('should still fit a 24-row terminal, where the detail box no longer has room', async () => { + + const { lastFrame, unmount } = open(24); + + await waitToFit(lastFrame, 24); + + // A fixed wait is the only way to show something does not appear: the + // detail box would land on the render after the list's first highlight. + await new Promise((resolve) => setTimeout(resolve, 300)); + const frame = plain(lastFrame()); + unmount(); + + expect(frame.split('\n').length).toBeLessThanOrEqual(24 - SHELL_ROWS); + expect(frame).not.toContain('Revert files'); + expect(frame).toContain('[Esc] Back'); + expect(frame).toContain(changeName(CHANGE_COUNT - 1)); + expect(frame).toMatch(/↓ \d+ more/); + + }, 20_000); + + it('should scroll the last change into view when the cursor walks down to it', async () => { + + const { stdin, lastFrame, unmount } = open(30); + + await waitToFit(lastFrame, 30, 'Revert files'); + + for (let i = 0; i < CHANGE_COUNT - 1; i++) { + + stdin.write('\x1B[B'); + await new Promise((resolve) => setTimeout(resolve, 5)); + + } + + const oldest = changeName(0); + await waitFor(() => plain(lastFrame()).includes(`❯ ○ ${oldest}`)); + const frame = await waitToFit(lastFrame, 30); + unmount(); + + expect(frame).not.toContain(changeName(CHANGE_COUNT - 1)); + expect(frame).toMatch(/↑ \d+ more/); + expect(frame).toContain('[Esc] Back'); + + }, 20_000); + +});