From 1e3234929ca5fd5c8d5c0d347ba6de33b2be1b1b Mon Sep 17 00:00:00 2001 From: Qijun Date: Fri, 2 Oct 2026 19:57:05 -0700 Subject: [PATCH] feat: add arXiv papers, GitHub code and file links from an address Add from URL takes an arXiv paper page, a GitHub repository, folder or file, or a link to any file. The browser downloads it directly, so no server is involved and no site list is kept: a site that does not allow cross-origin reads gets a sentence asking the reader to download the file and drag it in. An arXiv abstract page stands for its PDF and a GitHub file page for its raw content; both open once added. A GitHub folder is listed once through the API, filtered by the rules a chosen folder follows before anything is downloaded, and then fetched file by file from raw content. --- ui-packages/web/src/core/folder-import.ts | 15 ++- ui-packages/web/src/core/url-import.test.ts | 68 ++++++++++++ ui-packages/web/src/core/url-import.ts | 81 ++++++++++++++ ui-packages/web/src/data/remote-files.ts | 102 ++++++++++++++++++ .../resources/add-from-url-dialog.tsx | 58 ++++++++++ .../web/src/features/resources/add-menu.tsx | 34 +++--- .../src/features/resources/resource-panel.tsx | 23 +++- .../features/resources/use-file-library.ts | 88 ++++++++++++--- .../file-library-ui.integration.test.tsx | 61 ++++++++++- ui-packages/web/src/styles.css | 22 +++- 10 files changed, 508 insertions(+), 44 deletions(-) create mode 100644 ui-packages/web/src/core/url-import.test.ts create mode 100644 ui-packages/web/src/core/url-import.ts create mode 100644 ui-packages/web/src/data/remote-files.ts create mode 100644 ui-packages/web/src/features/resources/add-from-url-dialog.tsx diff --git a/ui-packages/web/src/core/folder-import.ts b/ui-packages/web/src/core/folder-import.ts index d6689f5..f9d6389 100644 --- a/ui-packages/web/src/core/folder-import.ts +++ b/ui-packages/web/src/core/folder-import.ts @@ -5,8 +5,11 @@ export const maximumFolderFileBytes = 1024 * 1024 // A path here starts with the chosen folder's own name, such as 'repo/src/index.ts'. export type FolderEntry = { path: string; file: File } -export type FolderSelection = - | { status: 'ready'; sources: ImportSource[]; skipped: number } +// Enough of a file to decide whether it comes in, so a remote listing is chosen from before any +// of it is downloaded. +type FolderListing = { path: string; file: Pick } +export type FolderSelection = + | { status: 'ready'; sources: T[]; skipped: number } | { status: 'too-many' } // Dependencies, build output and tool state are rarely what a reader came to read, and they are @@ -25,18 +28,20 @@ const ignoredFolders = new Set([ export const isIgnoredFolder = (name: string) => name.startsWith('.') || ignoredFolders.has(name) // The chosen folder itself is never skipped, even when its name starts with a dot. -export const isFolderFileWanted = ({ path, file }: FolderEntry) => +export const isFolderFileWanted = ({ path, file }: FolderListing) => !path.split('/').slice(1, -1).some(isIgnoredFolder) && !baseName(path).startsWith('.') && file.size <= maximumFolderFileBytes && previewKindFor(path, file.type) !== 'unsupported' -const byPath = (left: FolderEntry, right: FolderEntry) => +const byPath = (left: FolderListing, right: FolderListing) => left.path.localeCompare(right.path, undefined, { sensitivity: 'base', numeric: true }) // Files are stored in the order they arrive, which is the order they list in, so a folder is // sorted by path first rather than kept in whatever order the browser walked it. -export const selectFolderFiles = (entries: readonly FolderEntry[]): FolderSelection => { +export const selectFolderFiles = ( + entries: readonly T[], +): FolderSelection => { const sources = entries.filter(isFolderFileWanted).sort(byPath) return sources.length > maximumFolderFiles ? { status: 'too-many' } diff --git a/ui-packages/web/src/core/url-import.test.ts b/ui-packages/web/src/core/url-import.test.ts new file mode 100644 index 0000000..8e8c71c --- /dev/null +++ b/ui-packages/web/src/core/url-import.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { resolveImportUrl } from './url-import' + +describe('import addresses', () => { + it('reads arXiv abstract and PDF pages as the paper PDF', () => { + for (const address of [ + 'https://arxiv.org/abs/1706.03762', + 'https://arxiv.org/pdf/1706.03762', + ' https://www.arxiv.org/pdf/1706.03762.pdf ', + ]) + expect(resolveImportUrl(address)).toEqual({ + kind: 'file', + url: 'https://arxiv.org/pdf/1706.03762', + name: '1706.03762.pdf', + }) + expect(resolveImportUrl('https://arxiv.org/abs/hep-th/9901001v2')).toEqual({ + kind: 'file', + url: 'https://arxiv.org/pdf/hep-th/9901001v2', + name: 'hep-th_9901001v2.pdf', + }) + }) + + it('reads GitHub repositories and folders by listing and files from raw content', () => { + const repository = { kind: 'repository', owner: 'sicp', repo: 'book', name: 'book' } + expect(resolveImportUrl('https://github.com/sicp/book.git')).toEqual({ + ...repository, + ref: 'HEAD', + subpath: '', + }) + expect(resolveImportUrl('https://github.com/sicp/book/tree/main/src/chapter%201')).toEqual({ + ...repository, + ref: 'main', + subpath: 'src/chapter 1', + }) + const file = { + kind: 'file', + url: 'https://raw.githubusercontent.com/sicp/book/main/src/eval.scm', + name: 'eval.scm', + } + expect(resolveImportUrl('https://github.com/sicp/book/blob/main/src/eval.scm')).toEqual(file) + expect(resolveImportUrl(file.url)).toEqual(file) + }) + + it('downloads any other secure address as it is', () => { + expect(resolveImportUrl('https://example.org/papers/notes%20v2.pdf')).toEqual({ + kind: 'file', + url: 'https://example.org/papers/notes%20v2.pdf', + name: 'notes v2.pdf', + }) + expect(resolveImportUrl('https://doi.example.org/')).toEqual({ + kind: 'file', + url: 'https://doi.example.org/', + name: 'doi.example.org', + }) + }) + + it('recognizes no other address', () => { + for (const address of [ + 'arxiv.org/abs/1706.03762', + 'http://example.org/paper.pdf', + 'https://github.com/sicp', + 'https://github.com/sicp/book/issues/1', + 'https://github.com/sicp/book/tree/main/%E0', + 'ftp://arxiv.org/pdf/1706.03762', + ]) + expect(resolveImportUrl(address)).toBeNull() + }) +}) diff --git a/ui-packages/web/src/core/url-import.ts b/ui-packages/web/src/core/url-import.ts new file mode 100644 index 0000000..2b1f919 --- /dev/null +++ b/ui-packages/web/src/core/url-import.ts @@ -0,0 +1,81 @@ +// An address the library can add from: one file the browser downloads, or a GitHub folder read +// file by file. +export type ImportTarget = + | { kind: 'file'; url: string; name: string } + | { + kind: 'repository' + owner: string + repo: string + ref: string + subpath: string + name: string + } + +const segmentsOf = (url: URL) => url.pathname.split('/').filter(Boolean) + +// A segment with a broken escape names nothing the library could store. +const decoded = (segment: string) => { + try { + return decodeURIComponent(segment) + } catch (cause) { + if (cause instanceof URIError) return null + throw cause + } +} + +const fileName = (segment: string | undefined) => (segment ? decoded(segment) || null : null) + +// New identifiers such as 1706.03762v7, and old ones such as hep-th/9901001. +const arxivId = /^(?:\d{4}\.\d{4,5}|[a-z-]+(?:\.[a-z]{2})?\/\d{7})(?:v\d+)?$/i + +// An abstract page stands for its paper's PDF. +const fromArxiv = (url: URL): ImportTarget | null => { + const [kind, ...rest] = segmentsOf(url) + const id = rest.join('/').replace(/\.pdf$/i, '') + if ((kind !== 'abs' && kind !== 'pdf') || !arxivId.test(id)) return null + return { kind: 'file', url: `https://arxiv.org/pdf/${id}`, name: `${id.replace('/', '_')}.pdf` } +} + +// A ref containing a slash cannot be told apart from the path after it, so the first segment +// is taken as the ref. +const fromGithub = (url: URL): ImportTarget | null => { + const [owner, rawRepo, view, ref, ...path] = segmentsOf(url) + const repo = rawRepo?.replace(/\.git$/, '') + if (!owner || !repo) return null + if (view === 'blob' && ref && path.length) { + const name = fileName(path.at(-1)) + return name + ? { + kind: 'file', + url: `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path.join('/')}`, + name, + } + : null + } + if (view !== undefined && !(view === 'tree' && ref)) return null + const subpath = path.map(decoded) + if (subpath.some(segment => segment === null)) return null + return { + kind: 'repository', + owner, + repo, + ref: ref ?? 'HEAD', + subpath: subpath.join('/'), + name: repo, + } +} + +// Any other address is fetched by the browser as it is, which works where the site allows it. +const fromAddress = (url: URL): ImportTarget | null => + url.protocol === 'https:' + ? { kind: 'file', url: url.href, name: fileName(segmentsOf(url).at(-1)) ?? url.hostname } + : null + +export const resolveImportUrl = (text: string): ImportTarget | null => { + const url = URL.parse(text.trim()) + if (url?.protocol !== 'https:' && url?.protocol !== 'http:') return null + const host = url.hostname.replace(/^www\./, '') + if (host === 'arxiv.org') return fromArxiv(url) ?? fromAddress(url) + if (host === 'github.com') return fromGithub(url) + return fromAddress(url) +} diff --git a/ui-packages/web/src/data/remote-files.ts b/ui-packages/web/src/data/remote-files.ts new file mode 100644 index 0000000..6b0857b --- /dev/null +++ b/ui-packages/web/src/data/remote-files.ts @@ -0,0 +1,102 @@ +import { baseName, type ImportSource } from '../core/files' +import { type FolderSelection, selectFolderFiles } from '../core/folder-import' +import type { ImportTarget } from '../core/url-import' + +// A sentence for the reader saying why an address could not be downloaded. +export class RemoteFileError extends Error {} + +// The browser reports a site that refuses cross-origin reads the same way as one it cannot reach. +const unreachable = + 'This site does not let web pages download its files, or could not be reached. Download the file and drag it into Files.' + +const request = async (url: string) => { + const response = await fetch(url).catch((cause: unknown) => { + throw cause instanceof TypeError ? new RemoteFileError(unreachable, { cause }) : cause + }) + if (response.ok) return response + if (response.status === 404) throw new RemoteFileError('Nothing was found at that address.') + if (response.headers.get('x-ratelimit-remaining') === '0') + throw new RemoteFileError( + 'GitHub allows 60 folder listings an hour from one network, and they are used up. Try again later.', + ) + throw new RemoteFileError(`The site returned HTTP ${response.status}.`) +} + +export const downloadFile = async (target: Extract) => { + const response = await request(target.url) + const type = response.headers.get('content-type')?.split(';')[0]?.trim() ?? '' + // An address such as a DOI landing link rarely ends in the extension that says what it holds. + const name = + type === 'application/pdf' && !/\.pdf$/i.test(target.name) ? `${target.name}.pdf` : target.name + return new File([await response.blob()], name, { type }) +} + +type TreeItem = { path: string; type: string; size?: number } +type Tree = { truncated: boolean; tree: TreeItem[] } + +const isTree = (value: unknown): value is Tree => + typeof value === 'object' && + value !== null && + 'tree' in value && + Array.isArray(value.tree) && + 'truncated' in value && + typeof value.truncated === 'boolean' + +// A few downloads at a time keeps a large folder from opening hundreds of connections at once. +const mapWithLimit = async ( + items: readonly T[], + limit: number, + map: (item: T) => Promise, +) => { + const results: R[] = [] + let next = 0 + const work = async () => { + for (let index = next++; index < items.length; index = next++) + results[index] = await map(items[index] as T) + } + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, work)) + return results +} + +const encodePath = (path: string) => path.split('/').map(encodeURIComponent).join('/') + +// One listing gives every path and size, so the files a chosen folder would leave out are left +// out before anything is downloaded, and only the rest are fetched from raw content. +export const downloadRepository = async ( + target: Extract, + onProgress: (done: number, total: number) => void, +): Promise => { + const { owner, repo, ref, subpath, name } = target + const listing: unknown = await ( + await request( + `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(ref)}?recursive=1`, + ) + ).json() + if (!isTree(listing)) + throw new RemoteFileError('GitHub returned a folder listing it could not read.') + if (listing.truncated) return { status: 'too-many' } + const within = subpath ? `${subpath}/` : '' + const selection = selectFolderFiles( + listing.tree.flatMap(item => + item.type === 'blob' && item.path.startsWith(within) + ? [{ path: `${name}/${item.path}`, file: { size: item.size ?? 0, type: '' }, item }] + : [], + ), + ) + if (selection.status === 'too-many') return selection + let done = 0 + const sources = await mapWithLimit( + selection.sources, + 6, + async ({ path, item }): Promise => { + const response = await request( + `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(ref)}/${encodePath(item.path)}`, + ) + const file = new File([await response.blob()], baseName(path)) + done += 1 + onProgress(done, selection.sources.length) + return { path, file } + }, + ) + return { status: 'ready', sources, skipped: selection.skipped } +} diff --git a/ui-packages/web/src/features/resources/add-from-url-dialog.tsx b/ui-packages/web/src/features/resources/add-from-url-dialog.tsx new file mode 100644 index 0000000..c36f579 --- /dev/null +++ b/ui-packages/web/src/features/resources/add-from-url-dialog.tsx @@ -0,0 +1,58 @@ +import { useEffect, useRef, useState } from 'react' +import { ConfirmationDialog as Modal } from '../../components/confirmation-dialog' +import { type ImportTarget, resolveImportUrl } from '../../core/url-import' + +export const AddFromUrlDialog = ({ + onAdd, + onCancel, +}: { + onAdd: (target: ImportTarget) => void + onCancel: () => void +}) => { + const [text, setText] = useState('') + const [invalid, setInvalid] = useState(false) + const inputRef = useRef(null) + useEffect(() => inputRef.current?.focus(), []) + return ( + +
{ + event.preventDefault() + const target = resolveImportUrl(text) + if (target) onAdd(target) + else setInvalid(true) + }} + > +

Add from URL

+

+ An arXiv paper, a GitHub repository, folder or file, or a link to any file its site lets + web pages download. +

+ { + setText(event.target.value) + setInvalid(false) + }} + /> + {invalid && ( +

Paste an https address, such as an arXiv paper or a GitHub repository.

+ )} +
+ + +
+
+
+ ) +} diff --git a/ui-packages/web/src/features/resources/add-menu.tsx b/ui-packages/web/src/features/resources/add-menu.tsx index 8706eb8..3dcea2d 100644 --- a/ui-packages/web/src/features/resources/add-menu.tsx +++ b/ui-packages/web/src/features/resources/add-menu.tsx @@ -1,30 +1,18 @@ import * as Popover from '@radix-ui/react-popover' -import { FilePlus, FolderPlus, Plus } from 'lucide-react' +import { FilePlus, FolderPlus, Link, Plus } from 'lucide-react' import { useState } from 'react' type AddMenuProps = { disabled: boolean - // Absent where the browser cannot choose a folder; the button then adds files directly. + // Absent where the browser cannot choose a folder. onAddFolder?: () => void onAddFiles: () => void + onAddFromUrl: () => void } // One entry point for bringing things in, so it never reads like the folder save beside it. -export const AddMenu = ({ disabled, onAddFolder, onAddFiles }: AddMenuProps) => { +export const AddMenu = ({ disabled, onAddFolder, onAddFiles, onAddFromUrl }: AddMenuProps) => { const [open, setOpen] = useState(false) - if (!onAddFolder) - return ( - - ) // Closing first keeps the picker that follows from opening behind the menu. const choose = (action: () => void) => () => { setOpen(false) @@ -36,7 +24,7 @@ export const AddMenu = ({ disabled, onAddFolder, onAddFiles }: AddMenuProps) => - + )} + diff --git a/ui-packages/web/src/features/resources/resource-panel.tsx b/ui-packages/web/src/features/resources/resource-panel.tsx index 0a8cfae..07ffdbc 100644 --- a/ui-packages/web/src/features/resources/resource-panel.tsx +++ b/ui-packages/web/src/features/resources/resource-panel.tsx @@ -1,10 +1,11 @@ import { PanelLeft, X } from 'lucide-react' -import { type DragEvent, useRef, useState } from 'react' +import { type DragEvent, useEffect, useRef, useState } from 'react' import type { StoredFileMetadata } from '../../core/files' import type { Project } from '../../core/projects' import { useSourceDrafts } from '../../shell/workspace-context' import { sourceDirty } from '../../shell/workspace-store' import { ProjectSwitcher } from '../projects/project-switcher' +import { AddFromUrlDialog } from './add-from-url-dialog' import { AddMenu } from './add-menu' import { DuplicateFilesDialog, RemoveFileDialog, RemoveFolderDialog } from './file-dialogs' import { filesInFolder } from './file-tree' @@ -70,6 +71,14 @@ export const ResourcePanel = ({ setRemoval(null) }) const [dropping, setDropping] = useState(false) + const [addingUrl, setAddingUrl] = useState(false) + // A file from an address opens once the library lists it; opening checks that list. + const [openWhenListed, setOpenWhenListed] = useState(null) + useEffect(() => { + if (!openWhenListed || !library.files.some(file => file.id === openWhenListed)) return + setOpenWhenListed(null) + onOpen(openWhenListed) + }, [openWhenListed, library.files, onOpen]) 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. @@ -123,6 +132,7 @@ export const ResourcePanel = ({ disabled={library.loading || library.importing} onAddFiles={() => inputRef.current?.click()} onAddFolder={addFolder} + onAddFromUrl={() => setAddingUrl(true)} /> )} + {addingUrl && ( + setAddingUrl(false)} + onAdd={target => { + setAddingUrl(false) + void library.addFromUrl(target).then(id => { + if (id) setOpenWhenListed(id) + }) + }} + /> + )} {library.duplicatePaths.length > 0 && ( File = keepFile) => }, []) // Paths already in the library were settled before this point, so anything left replaces. - const commitImport = async ({ sources, skipped }: PendingImport) => { + const commitImport = async ({ + sources, + skipped, + }: PendingImport): Promise => { setImporting(true) setStatus(null) try { @@ -119,9 +129,11 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => await reload() setStatus(skipped === null ? resultStatus(result) : folderStatus(result, skipped)) rememberPersistence(result.imported.length > 0) + return result } catch (cause) { console.error('Unable to import files', cause) setStatus({ message: 'Files could not be added. Try again.' }) + return null } finally { setImporting(false) setProgress(null) @@ -173,9 +185,11 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => [reload, rememberPersistence], ) + // Null while the duplicate question is open, or when the import failed. const queueImport = async (next: PendingImport) => { - if (duplicatePaths(next.sources, files).length > 0) setPending(next) - else await commitImport(next) + if (duplicatePaths(next.sources, files).length === 0) return commitImport(next) + setPending(next) + return null } const addFiles = (selected: readonly File[]) => { @@ -183,6 +197,16 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => void queueImport({ sources: rootSources(selected), skipped: null }) } + const settleFolder = async (selection: FolderSelection) => { + if (selection.status === 'too-many') + setStatus({ + message: `This folder has more than ${maximumFolderFiles} readable files. Choose a smaller folder.`, + }) + else if (selection.sources.length === 0) + setStatus({ message: 'This folder has no files that can be read here.' }) + else await queueImport({ sources: selection.sources, skipped: selection.skipped }) + } + // Reading a large folder takes a moment, so the library counts as importing while it does. const addFolder = async ( load: (onRead: (count: number) => void) => Promise, @@ -192,16 +216,11 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => setStatus(null) setProgress('Reading folder…') try { - const selection = selectFolderFiles( - await load(count => setProgress(`Reading folder… ${count.toLocaleString()} files`)), + await settleFolder( + selectFolderFiles( + await load(count => setProgress(`Reading folder… ${count.toLocaleString()} files`)), + ), ) - if (selection.status === 'too-many') - setStatus({ - message: `This folder has more than ${maximumFolderFiles} readable files. Choose a smaller folder.`, - }) - else if (selection.sources.length === 0) - setStatus({ message: 'This folder has no files that can be read here.' }) - else await queueImport({ sources: selection.sources, skipped: selection.skipped }) } catch (cause) { if (!pickerCancelled(cause)) { console.error('Unable to read the folder', cause) @@ -213,6 +232,48 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => } } + const download = async (name: string, run: () => Promise) => { + setImporting(true) + setStatus(null) + setProgress(`Downloading ${name}…`) + try { + return await run() + } catch (cause) { + console.error('Unable to download from the address', cause) + setStatus({ + message: + cause instanceof RemoteFileError + ? cause.message + : 'The address could not be downloaded. Try again.', + }) + return null + } finally { + setImporting(false) + setProgress(null) + } + } + + // A GitHub folder comes in as a chosen folder would. A single file resolves to its id, so it can + // be opened, unless the duplicate question is still open. + const addFromUrl = async (target: ImportTarget) => { + if (importing) return undefined + if (target.kind === 'repository') { + const selection = await download(target.name, () => + downloadRepository(target, (done, total) => + setProgress( + `Downloading ${target.name}… ${done.toLocaleString()} of ${fileCount(total)}`, + ), + ), + ) + if (selection) await settleFolder(selection) + return undefined + } + const file = await download(target.name, () => downloadFile(target)) + if (!file) return undefined + const result = await queueImport({ sources: rootSources([file]), skipped: null }) + return result?.addedIds[0] ?? result?.replacedIds[0] + } + const resolveDuplicates = (choice: DuplicateChoice | null) => { const selected = pending setPending(null) @@ -248,6 +309,7 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) => duplicatePaths: pending ? duplicatePaths(pending.sources, files) : [], addFiles, addFolder, + addFromUrl, addAttachments, writeTextFile, moveFile, diff --git a/ui-packages/web/src/shell/file-library-ui.integration.test.tsx b/ui-packages/web/src/shell/file-library-ui.integration.test.tsx index 4d7f58c..e006866 100644 --- a/ui-packages/web/src/shell/file-library-ui.integration.test.tsx +++ b/ui-packages/web/src/shell/file-library-ui.integration.test.tsx @@ -205,7 +205,7 @@ describe('file library', () => { , ) await waitForFiles() - await user.click(screen.getByRole('button', { name: 'Add files or a folder' })) + await user.click(screen.getByRole('button', { name: 'Add to Files' })) expect(screen.getByRole('menuitem', { name: 'Add files…' })).toBeVisible() expect(screen.getByRole('menuitem', { name: 'Add folder…' })).toBeVisible() await user.keyboard('{Escape}') @@ -267,6 +267,61 @@ describe('file library', () => { expect(filesList().getByRole('button', { name: 'Start here.md' })).toBeVisible() }) + it('adds a GitHub file and folder from their addresses and opens the file', async () => { + const user = userEvent.setup({ delay: null }) + const listing = { + truncated: false, + tree: [ + { path: 'README.md', type: 'blob', size: 6 }, + { path: 'src', type: 'tree' }, + { path: 'src/eval.scm', type: 'blob', size: 27 }, + { path: 'src/.hidden', type: 'blob', size: 6 }, + ], + } + const requested: string[] = [] + vi.spyOn(globalThis, 'fetch').mockImplementation(async input => { + const url = String(input) + if (url === '/api/agent/config') return Response.json({ enabled: false }) + requested.push(url) + if (url.endsWith('/missing.scm')) return new Response('Not Found', { status: 404 }) + if (url.startsWith('https://api.github.com/')) return Response.json(listing) + return new Response('(define (square x) (* x x))') + }) + render( + + + , + ) + await waitForFiles() + const addFrom = async (address: string) => { + await user.click(screen.getByRole('button', { name: 'Add to Files' })) + await user.click(screen.getByRole('menuitem', { name: 'Add from URL…' })) + await user.type(screen.getByRole('textbox', { name: 'Address' }), address) + await user.click(screen.getByRole('button', { name: 'Add' })) + } + + await addFrom('https://github.com/sicp/book/blob/main/square.scm') + expect(await screen.findByRole('tab', { name: 'square.scm' })).toBeInTheDocument() + + await addFrom('https://github.com/sicp/book/tree/main/src') + expect(await screen.findByRole('alert')).toHaveTextContent( + '1 file added. Left out 1 file that were hidden, oversized or unreadable.', + ) + await user.click(filesList().getByRole('button', { name: 'book' })) + await user.click(filesList().getByRole('button', { name: 'src' })) + expect(filesList().getByRole('button', { name: 'eval.scm' })).toBeVisible() + expect(filesList().queryByRole('button', { name: 'README.md' })).toBeNull() + + await addFrom('https://github.com/sicp/book/blob/main/missing.scm') + expect(await screen.findByText('Nothing was found at that address.')).toBeInTheDocument() + expect(requested).toEqual([ + 'https://raw.githubusercontent.com/sicp/book/main/square.scm', + 'https://api.github.com/repos/sicp/book/git/trees/main?recursive=1', + 'https://raw.githubusercontent.com/sicp/book/main/src/eval.scm', + 'https://raw.githubusercontent.com/sicp/book/main/missing.scm', + ]) + }) + it('keeps the add-files action in the toolbar when the library is empty', async () => { await Promise.all(samples.map(file => removeStoredFiles([file.id]))) render( @@ -276,9 +331,7 @@ describe('file library', () => { ) await screen.findByText('Add a document when you are ready to read.') - const addFiles = screen.getByRole('button', { name: 'Add files' }) - expect(addFiles).toBeEnabled() - expect(addFiles).toHaveAttribute('title', 'Add files') + expect(screen.getByRole('button', { name: 'Add to Files' })).toBeEnabled() }) it('confirms new name conflicts before saving Files to a remembered folder', async () => { diff --git a/ui-packages/web/src/styles.css b/ui-packages/web/src/styles.css index cc8ce8e..5ed24ac 100644 --- a/ui-packages/web/src/styles.css +++ b/ui-packages/web/src/styles.css @@ -804,6 +804,25 @@ svg { line-height: 1.65; overflow-wrap: anywhere; } +.dialog-input { + width: 100%; + min-height: 32px; + margin-top: 14px; + padding: 5px 8px; + border: 1px solid oklch(0.84 0 0); + border-radius: 5px; + background: var(--surface); + color: inherit; + font: inherit; + font-size: 13px; +} +.dialog-input:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} +.dialog-input + p { + margin-top: 8px; +} .dialog-actions { display: flex; justify-content: flex-end; @@ -1261,7 +1280,8 @@ svg { .composer-area { padding-bottom: max(10px, env(safe-area-inset-bottom)); } - .preview-toolbar input[type="text"] { + .preview-toolbar input[type="text"], + .dialog-input { font-size: 16px; } .image-lightbox-toolbar {