Skip to content
Merged
14 changes: 10 additions & 4 deletions forge-web/components/repo/diff-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,17 @@ export const InlineCommentsContext = createContext<InlineComments | null>(null)
/** Files whose patches load per page. */
const FILE_PAGE = 25
/** A change set of at most this many files has its lines counted as it opens; a bigger one on request. */
const AUTO_COUNT = 100
const AUTO_COUNT = 300
/** Rows a file renders before a "show more lines" button. */
const LINE_PAGE = 400
/** Patch reads in flight at once. */
const PATCH_CONCURRENCY = 4
/**
* Patch reads in flight at once: those of files on screen, and of a whole change set being counted
* (QW-027). Blob reads that run side by side share their chunk queries (`queueChunkSeqs`), so a
* wider pool costs fewer round trips, not more requests: dashpay/dash v22.0.0...v23.0.0's 1,530
* files were 1,287 requests over 176 s four at a time, and are ~80 over ~20 s.
*/
const PATCH_CONCURRENCY = 12
const COUNT_CONCURRENCY = 24
/** Finished patches are committed to state in batches at most this often (ms). */
const PATCH_FLUSH_MS = 100

Expand Down Expand Up @@ -163,7 +169,7 @@ export function DiffView({
const key = (path: string): string => `${ignoreWhitespace ? 'w' : 'x'}:${path}`
const todo = (countAll ? changes : changes.slice(0, shown)).filter((c) => !requested.current.has(key(c.path)))
for (const c of todo) requested.current.add(key(c.path))
void mapPooled(todo, PATCH_CONCURRENCY, async (change) => {
void mapPooled(todo, countAll ? COUNT_CONCURRENCY : PATCH_CONCURRENCY, async (change) => {
// loadFilePatch turns read failures into placeholders; anything else must still settle
// the file, or it would sit on "Reading file…" with its key already requested.
const patch = await loadFilePatch(sides, change, { ignoreWhitespace }).catch(
Expand Down
140 changes: 140 additions & 0 deletions forge-web/components/repo/go-to-file.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// @vitest-environment jsdom
/**
* Go to file (QW-028): results from the history index at once, then the walk's exact list; fuzzy
* ranking; the arrow keys and Enter open a result; `t` focuses the box.
*/

import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const push = vi.fn()
vi.mock('next/link', () => ({ default: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => <a href={href} {...rest}>{children}</a> }))
vi.mock('next/navigation', () => ({ useRouter: () => ({ push, replace: () => undefined }) }))

/** The walk resolves when the test says; the index answers at once (null: the repo has none). */
const INDEX = ['src/validation.cpp', 'src/net_processing.cpp', 'src/deleted_since.cpp']
let index: string[] | null = INDEX
let finishWalk: (files: string[], truncated?: boolean) => void = () => undefined
vi.mock('@/lib/view/repo-facts', () => ({
indexedFilePaths: async () => index,
repoFilesWalk: () =>
new Promise((resolve) => {
finishWalk = (files, truncated = false) => resolve({ files: files.map((path) => ({ path, oid: '', mode: 0o100644, size: 0 })), truncated })
}),
}))

import { GoToFile } from './go-to-file'

let root: Root
let el: HTMLDivElement
beforeEach(() => {
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
push.mockClear()
index = INDEX
// jsdom has no layout, so no scrollIntoView.
Element.prototype.scrollIntoView = () => undefined
el = document.createElement('div')
document.body.append(el)
root = createRoot(el)
})
afterEach(() => {
act(() => root.unmount())
el.remove()
})

const input = (): HTMLInputElement => el.querySelector('[data-testid="go-to-file"]') as HTMLInputElement
const results = (): string[] => [...el.querySelectorAll('[data-testid="go-to-file-result"]')].map((a) => a.textContent ?? '')

async function type(text: string): Promise<void> {
await act(async () => {
const box = input()
box.focus()
// React listens for the native setter's input event.
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set?.call(box, text)
box.dispatchEvent(new Event('input', { bubbles: true }))
})
}

async function key(k: string, target: EventTarget = input()): Promise<void> {
await act(async () => {
target.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }))
})
}

async function render(): Promise<void> {
await act(async () => {
root.render(
<GoToFile reader={{} as never} repoKey="r" tipOid={'a'.repeat(40)} rootTree={async () => 'tree'} addr={{ owner: 'o', name: 'n' }} refParam="" />,
)
})
}

describe('GoToFile', () => {
it('answers from the history index before the walk, then from the walk', async () => {
await render()
await type('deleted')
await vi.waitFor(() => expect(results()).toEqual(['src/deleted_since.cpp']))
// The walk's list is exact: a file the index still named is gone.
await act(async () => finishWalk(['src/validation.cpp', 'src/net_processing.cpp']))
await vi.waitFor(() => expect(el.textContent).toContain('No matching file.'))
})

it('a walk cut off at its file cap does not replace a complete index', async () => {
await render()
await type('src')
await vi.waitFor(() => expect(results()).toHaveLength(3))
// Past the walk's cap: the index names more of the tip than the partial walk.
await act(async () => finishWalk(['src/validation.cpp'], true))
expect(results()).toHaveLength(3)
expect(el.textContent).not.toContain('Searched the first')
})

it('with no index, a cut-off walk is the list, and says so', async () => {
index = null
await render()
await type('src')
await act(async () => finishWalk(['src/validation.cpp', 'src/init.cpp'], true))
await vi.waitFor(() => expect(results()).toHaveLength(2))
expect(el.textContent).toContain('Searched the first 2 files')
})

it('a new list of results resets the highlight, so Enter still opens one', async () => {
await render()
await type('src')
await vi.waitFor(() => expect(results()).toHaveLength(3))
await key('ArrowDown')
await key('ArrowDown')
// The walk's exact list replaces the index's under the same query: one result now.
await act(async () => finishWalk(['src/validation.cpp']))
await vi.waitFor(() => expect(results()).toEqual(['src/validation.cpp']))
await key('Enter')
expect(push).toHaveBeenCalledWith(expect.stringContaining(`path=${encodeURIComponent('src/validation.cpp')}`))
})

it('ranks fuzzily, moves with the arrow keys and opens the choice with Enter', async () => {
await render()
await type('netproc')
await vi.waitFor(() => expect(results()).toEqual(['src/net_processing.cpp']))
await type('src')
await vi.waitFor(() => expect(results()).toHaveLength(3))
const first = results()[0]
await key('ArrowDown')
expect(el.querySelector('[role=option][aria-selected=true]')?.textContent).toBe(results()[1])
await key('ArrowUp')
await key('Enter')
expect(push).toHaveBeenCalledWith(expect.stringContaining(`path=${encodeURIComponent(first as string)}`))
})

it('focuses on t, and Escape clears it', async () => {
await render()
// jsdom lays nothing out: give the box a client rect so it counts as visible.
input().getClientRects = () => [{}] as unknown as DOMRectList
await key('t', document.body)
expect(document.activeElement).toBe(input())
await type('val')
await key('Escape')
expect(input().value).toBe('')
expect(document.activeElement).not.toBe(input())
})
})
189 changes: 189 additions & 0 deletions forge-web/components/repo/go-to-file.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
'use client'

/**
* Go to file (QW-028): GitHub's file finder on the repo home and every directory. Fuzzy matching
* ({@link fuzzyRank}: `netproc` finds `src/net_processing.cpp`), the arrow keys and Enter to open
* a result, Escape to leave, and `t` anywhere on the page to start typing.
*
* The list comes from the history index first: the index the file list's column already loaded
* names every path at the tip, so the first results need no read at all. The tree walk the
* language bar shares ({@link repoFilesWalk}, its reads in parallel) starts on first focus and,
* once done, is the list: it is exact where an index a delta extends can still name a deleted file.
*/

import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Search } from 'lucide-react'
import type { ObjectReader } from '@/lib/view/tree-nav'
import { indexedFilePaths, repoFilesWalk } from '@/lib/view/repo-facts'
import { fuzzyRank, type FuzzyHit } from '@/lib/view/fuzzy'
import { plural } from '@/lib/view/format'
import { isPageShortcut } from '@/lib/focus'
import { useAsync } from '@/hooks/use-async'
import { Input } from '@/components/ui/input'
import { repoHref, type RepoAddress } from '@/hooks/use-query-param'
import { cn } from '@/lib/utils'

/** Results shown at once (the list scrolls). */
const RESULTS = 20

/** A path with its matched characters marked. */
function Marked({ hit }: { hit: FuzzyHit }): JSX.Element {
const at = new Set(hit.positions)
const parts: JSX.Element[] = []
let run = ''
let marked = false
const flush = (key: number): void => {
if (run === '') return
parts.push(marked ? <mark key={key} className="bg-transparent font-semibold text-anvil-900 dark:text-anvil-50">{run}</mark> : <span key={key}>{run}</span>)
run = ''
}
for (let i = 0; i < hit.path.length; i++) {
if (at.has(i) !== marked) {
flush(i)
marked = at.has(i)
}
run += hit.path[i]
}
flush(hit.path.length)
return <>{parts}</>
}

export function GoToFile({
reader,
repoKey: key,
tipOid,
rootTree,
addr,
refParam,
className,
}: {
reader: ObjectReader & { readonly memoScope?: object }
repoKey: string
tipOid: string
/** The tip's root tree, read when the walk starts. */
rootTree: () => Promise<string>
addr: RepoAddress
refParam: string
className?: string
}): JSX.Element {
const [started, setStarted] = useState(false)
const [query, setQuery] = useState('')
const [active, setActive] = useState(0)
const input = useRef<HTMLInputElement>(null)
const listId = useId()
const router = useRouter()
// The index's list (no read when the column already loaded it), then the walk's exact one.
const indexed = useAsync(() => indexedFilePaths(reader, tipOid), [key, tipOid], { enabled: started })
const walk = useAsync(async () => repoFilesWalk(key, tipOid, reader, await rootTree()), [key, tipOid], { enabled: started })
// A walk that stopped at its file cap names fewer paths than a complete index: the index then
// stays the list, and the walk's partial one answers only when there is no index.
const walkPaths = useMemo(() => walk.data?.files.map((f) => f.path) ?? null, [walk.data])
const walkInUse = walkPaths !== null && (!walk.data?.truncated || indexed.data == null)
const paths = walkInUse ? walkPaths : (indexed.data ?? walkPaths)
const q = query.trim()
const hits = useMemo(() => (q === '' || paths === null ? [] : fuzzyRank(q, paths, RESULTS)), [q, paths])
const hrefOf = (path: string): string => repoHref('/repo/blob', addr, { path, ...(refParam ? { ref: refParam } : {}) })
const optionId = (i: number): string => `${listId}-${i}`

// `t` starts typing a file name, as on GitHub.
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
if (!isPageShortcut(e, 't')) return
const box = input.current
if (box === null || box.getClientRects().length === 0) return
e.preventDefault()
box.focus()
box.select()
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])

// A new list of results (a new query, or the walk's list replacing the index's) starts from its
// best match, so the highlighted row always exists and Enter always opens something.
useEffect(() => setActive(0), [hits])

const onKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>): void => {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
if (hits.length === 0) return
e.preventDefault()
const next = (active + (e.key === 'ArrowDown' ? 1 : -1) + hits.length) % hits.length
setActive(next)
document.getElementById(optionId(next))?.scrollIntoView({ block: 'nearest' })
} else if (e.key === 'Enter') {
const hit = hits[active]
if (hit === undefined) return
e.preventDefault()
router.push(hrefOf(hit.path))
} else if (e.key === 'Escape') {
e.preventDefault()
setQuery('')
input.current?.blur()
}
}

const searching = paths === null && (walk.loading || indexed.loading || !started)
const open = q !== ''
return (
<div className={cn('relative w-full sm:w-56', className)}>
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-anvil-500 dark:text-anvil-400" aria-hidden />
<label htmlFor={`${listId}-input`} className="sr-only">
Go to file
</label>
<Input
ref={input}
id={`${listId}-input`}
value={query}
onFocus={() => setStarted(true)}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
placeholder="Go to file"
className="h-8 py-1 pl-8 pr-7"
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={open && hits[active] !== undefined ? optionId(active) : undefined}
autoComplete="off"
spellCheck={false}
data-testid="go-to-file"
/>
<kbd className="pointer-events-none absolute right-2 top-1/2 hidden -translate-y-1/2 rounded border border-anvil-300 px-1 font-mono text-[10px] text-anvil-500 sm:block dark:border-anvil-700 dark:text-anvil-400" aria-hidden>
t
</kbd>
{open ? (
<ul
id={listId}
role="listbox"
aria-label="Files"
className="absolute right-0 z-20 mt-1 max-h-80 w-full overflow-y-auto rounded-lg border border-anvil-200 bg-white py-1 shadow-lg dark:border-anvil-750 dark:bg-anvil-900 sm:w-96"
>
{searching ? <li className="px-3 py-1.5 text-anvil-500 dark:text-anvil-400">Listing files…</li> : null}
{walk.error && paths === null ? <li className="px-3 py-1.5 text-danger-700 dark:text-danger-400">{walk.error}</li> : null}
{!searching && paths !== null && hits.length === 0 ? <li className="px-3 py-1.5 text-anvil-500 dark:text-anvil-400">No matching file.</li> : null}
{hits.map((hit, i) => (
<li key={hit.path} id={optionId(i)} role="option" aria-selected={i === active} onMouseMove={() => setActive(i)}>
<Link
href={hrefOf(hit.path)}
// The input keeps focus (and the arrow keys) while the list is open.
tabIndex={-1}
className={cn(
'block truncate px-3 py-1.5 font-mono text-[12px] text-anvil-600 coarse:min-h-11 coarse:py-3 dark:text-anvil-300',
i === active && 'bg-anvil-100 dark:bg-anvil-800',
)}
data-testid="go-to-file-result"
>
<Marked hit={hit} />
</Link>
</li>
))}
{walkInUse && walk.data?.truncated ? (
<li className="px-3 py-1.5 text-[11px] text-anvil-500 dark:text-anvil-400">Searched the first {plural(walk.data.files.length, 'file')}.</li>
) : null}
</ul>
) : null}
</div>
)
}
Loading
Loading