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
46 changes: 46 additions & 0 deletions ui-packages/web/src/features/resources/file-filter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { LoaderCircle, Search } from 'lucide-react'
import { useState, useTransition } from 'react'

// The box keeps what is typed, so a key press redraws only the box. The library hears of it in a
// transition: a long list being drawn gives way to the next key instead of holding it up.
export const FileFilter = ({
count,
onQueryChange,
onSubmit,
}: {
count: number
onQueryChange: (query: string) => void
onSubmit: (query: string) => void
}) => {
const [value, setValue] = useState('')
const [pending, startTransition] = useTransition()
const change = (next: string) => {
setValue(next)
startTransition(() => onQueryChange(next))
}
return (
<label className="resource-filter">
{pending ? (
<LoaderCircle className="folder-save-spinner" size={13} aria-hidden="true" />
) : (
<Search size={13} aria-hidden="true" />
)}
<input
type="search"
aria-label="Filter files"
placeholder={`Filter ${count.toLocaleString()} ${count === 1 ? 'file' : 'files'}`}
value={value}
onChange={event => change(event.target.value)}
onKeyDown={event => {
if (event.key === 'Escape' && value) {
event.preventDefault()
change('')
} else if (event.key === 'Enter') {
event.preventDefault()
onSubmit(value)
}
}}
/>
</label>
)
}
18 changes: 18 additions & 0 deletions ui-packages/web/src/features/resources/file-tree.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { normalizeSearchText } from '../../core/document-text'
import { baseName, type StoredFileMetadata } from '../../core/files'

export type FileTreeNode =
Expand Down Expand Up @@ -60,3 +61,20 @@ export const filesInFolder = (files: readonly StoredFileMetadata[], folder: stri
const prefix = `${folder.toLowerCase()}/`
return files.filter(file => file.path.toLowerCase().startsWith(prefix))
}

// Each word of the filter must appear somewhere in the path, ignoring case, so `pi readme` finds
// knowledge/ai-agent-systems/pi/README.md. An empty filter keeps every file.
export const matchesFilter = (path: string, query: string) => {
const terms = normalizeSearchText(query).split(' ').filter(Boolean)
const target = path.toLowerCase()
return terms.every(term => target.includes(term))
}

// The first file in the order the tree shows them: folders first, each one in turn.
export const firstFile = (nodes: readonly FileTreeNode[]): StoredFileMetadata | null => {
for (const node of nodes) {
const file = node.kind === 'file' ? node.file : firstFile(node.children)
if (file) return file
}
return null
}
35 changes: 30 additions & 5 deletions ui-packages/web/src/features/resources/resource-panel.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PanelLeft, X } from 'lucide-react'
import { type DragEvent, useEffect, useRef, useState } from 'react'
import { normalizeSearchText } from '../../core/document-text'
import type { StoredFileMetadata } from '../../core/files'
import type { Project } from '../../core/projects'
import { useSourceDrafts } from '../../shell/workspace-context'
Expand All @@ -9,7 +10,8 @@ import { SourceSyncStatus } from '../source/sync-status'
import { AddFromUrlDialog } from './add-from-url-dialog'
import { AddMenu } from './add-menu'
import { DuplicateFilesDialog, RemoveFileDialog, RemoveFolderDialog } from './file-dialogs'
import { filesInFolder } from './file-tree'
import { FileFilter } from './file-filter'
import { buildFileTree, filesInFolder, firstFile, matchesFilter } from './file-tree'
import { FolderExportControl } from './folder-export-control'
import {
entriesFromInput,
Expand Down Expand Up @@ -80,11 +82,22 @@ export const ResourcePanel = ({
setOpenWhenListed(null)
onOpen(openWhenListed)
}, [openWhenListed, library.files, onOpen])
const [query, setQuery] = useState('')
const filter = normalizeSearchText(query)
const files = library.files.filter(file => (file.collection ?? 'files') === 'files')
// A folder's files are read when the dialog renders and when it confirms, so anything added to
// the folder while it is open is counted and removed too.
const folderFiles = removal?.kind === 'folder' ? filesInFolder(files, removal.path) : []
const attachments = library.files.filter(file => file.collection === 'attachments')
const shownFiles = files.filter(file => matchesFilter(file.path, filter))
const shownAttachments = attachments.filter(file => matchesFilter(file.path, filter))
// Enter reads what is in the box, not the filter still being drawn.
const openFirstMatch = (typed: string) => {
const match = (pool: StoredFileMetadata[]) =>
firstFile(buildFileTree(pool.filter(file => matchesFilter(file.path, typed))))
const first = match(files) ?? match(attachments)
if (first) onOpen(first.id)
}

const dropFiles = (event: DragEvent<HTMLElement>) => {
event.preventDefault()
Expand Down Expand Up @@ -198,6 +211,14 @@ export const ResourcePanel = ({
</button>
</div>
)}
{/* Kept while it holds a filter, so what is typed never filters the library unseen. */}
{(query || (!library.loading && !library.error && library.files.length > 0)) && (
<FileFilter
count={library.files.length}
onQueryChange={setQuery}
onSubmit={openFirstMatch}
/>
)}
<div className="resource-list">
{library.loading ? (
<p className="resource-state" role="status">
Expand All @@ -214,11 +235,14 @@ export const ResourcePanel = ({
<div className="resource-state empty-files">
<p>Add a document when you are ready to read.</p>
</div>
) : filter && shownFiles.length === 0 && shownAttachments.length === 0 ? (
<p className="resource-state">No matching files</p>
) : (
<>
{files.length > 0 && (
{shownFiles.length > 0 && (
<ResourceTree
files={files}
files={shownFiles}
filter={filter}
label="Files"
activeId={activeId}
onOpen={onOpen}
Expand All @@ -229,11 +253,12 @@ export const ResourcePanel = ({
exportBusy={exporter.phase === 'saving' || exporter.savingFileId !== null}
/>
)}
{attachments.length > 0 && (
{shownAttachments.length > 0 && (
<section className="resource-group" aria-labelledby="attachments-heading">
<h3 id="attachments-heading">Attachments</h3>
<ResourceTree
files={attachments}
files={shownAttachments}
filter={filter}
label="Attachments"
activeId={activeId}
onOpen={onOpen}
Expand Down
36 changes: 26 additions & 10 deletions ui-packages/web/src/features/resources/resource-tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { ancestorFolders, buildFileTree, type FileTreeNode } from './file-tree'

type ResourceTreeProps = {
files: StoredFileMetadata[]
// The normalized filter the files were chosen by; empty when nothing is filtered.
filter: string
label: 'Files' | 'Attachments'
activeId: string | null
onOpen: (id: string) => void
Expand All @@ -25,8 +27,8 @@ type ResourceTreeProps = {
exportBusy: boolean
}

type RowContext = Omit<ResourceTreeProps, 'files'> & {
expanded: ReadonlySet<string>
type RowContext = Omit<ResourceTreeProps, 'files' | 'filter'> & {
isOpen: (key: string) => boolean
onToggle: (key: string) => void
}

Expand Down Expand Up @@ -110,7 +112,7 @@ const TreeRows = ({
context={context}
/>
)
const open = context.expanded.has(node.key)
const open = context.isOpen(node.key)
return (
<li key={node.key}>
<div className="resource-row">
Expand Down Expand Up @@ -145,8 +147,23 @@ const TreeRows = ({
)
})

export const ResourceTree = ({ files, ...props }: ResourceTreeProps) => {
const toggled = (set: ReadonlySet<string>, key: string) => {
const next = new Set(set)
if (!next.delete(key)) next.add(key)
return next
}

export const ResourceTree = ({ files, filter, ...props }: ResourceTreeProps) => {
const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set())
// A filtered tree shows every folder holding a match open. Folding one there is kept apart from
// the folders opened by hand, and forgotten when the filter changes, so clearing the filter
// leaves the tree as it was.
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set())
const [collapsedFor, setCollapsedFor] = useState(filter)
if (filter !== collapsedFor) {
setCollapsedFor(filter)
setCollapsed(new Set())
}
const activePath = files.find(file => file.id === props.activeId)?.path ?? null
const [revealedPath, setRevealedPath] = useState<string | null>(null)

Expand All @@ -158,16 +175,15 @@ export const ResourceTree = ({ files, ...props }: ResourceTreeProps) => {
if (ancestors.some(key => !expanded.has(key))) setExpanded(new Set([...expanded, ...ancestors]))
}

const isOpen = (key: string) => (filter ? !collapsed.has(key) : expanded.has(key))
const onToggle = (key: string) =>
setExpanded(current => {
const next = new Set(current)
if (!next.delete(key)) next.add(key)
return next
})
filter
? setCollapsed(current => toggled(current, key))
: setExpanded(current => toggled(current, key))

return (
<ul aria-label={props.label}>
<TreeRows nodes={buildFileTree(files)} depth={0} context={{ ...props, expanded, onToggle }} />
<TreeRows nodes={buildFileTree(files)} depth={0} context={{ ...props, isOpen, onToggle }} />
</ul>
)
}
38 changes: 38 additions & 0 deletions ui-packages/web/src/shell/file-library-ui.integration.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,44 @@ describe('file library', () => {
expect(filesList().queryByRole('button', { name: 'files.ts' })).toBeNull()
})

it('filters files by every word of their path and opens the first match', async () => {
const user = userEvent.setup({ delay: null })
await writeStoredTextFile('knowledge/pi/README.md', '# Pi')
await writeStoredTextFile('knowledge/pi/loop.md', '# Loop')
await writeStoredTextFile('journal/README.md', '# Journal')
render(
<MemoryRouter>
<Workbench project={testProject} />
</MemoryRouter>,
)
await waitForFiles()

const filter = screen.getByRole('searchbox', { name: 'Filter files' })
await user.type(filter, 'pi readme')

await waitFor(() => expect(filesList().queryByRole('button', { name: 'journal' })).toBeNull())
expect(filesList().getByRole('button', { name: 'knowledge' })).toHaveAttribute(
'aria-expanded',
'true',
)
expect(filesList().queryByRole('button', { name: 'loop.md' })).toBeNull()
expect(filesList().getByRole('button', { name: 'README.md' })).toHaveAttribute(
'title',
expect.stringContaining('knowledge/pi/README.md'),
)

await user.keyboard('{Enter}')
expect(await screen.findByRole('tab', { name: 'README.md' })).toHaveAttribute(
'aria-selected',
'true',
)

await user.click(filter)
await user.keyboard('{Escape}')
expect(filter).toHaveValue('')
expect(await filesList().findByRole('button', { name: 'journal' })).toBeInTheDocument()
})

it('adds a chosen folder, leaving out dependencies and reporting what it skipped', async () => {
const user = userEvent.setup({ delay: null })
// jsdom has no folder input; a browser without the folder picker offers one.
Expand Down
34 changes: 32 additions & 2 deletions ui-packages/web/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,36 @@ svg {
.add-menu button:focus-visible {
background: oklch(0.945 0 0);
}
.resource-filter {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 6px;
margin: 0 8px 6px;
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 5px;
color: var(--muted);
}
.resource-filter:focus-within {
border-color: var(--accent);
}
.resource-filter svg {
flex-shrink: 0;
}
.resource-filter input {
width: 100%;
min-width: 0;
border: 0;
outline: none;
background: transparent;
color: oklch(0.28 0 0);
font: inherit;
font-size: 12px;
}
.resource-filter input::placeholder {
color: var(--muted);
}
.resource-list {
flex: 1;
overflow: auto;
Expand All @@ -281,9 +311,9 @@ svg {
.resource-item {
display: flex;
align-items: center;
gap: 9px;
gap: 6px;
width: 100%;
padding: 7px 8px;
padding: 4px 8px;
text-align: left;
border: 0;
border-radius: 5px;
Expand Down