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
15 changes: 10 additions & 5 deletions ui-packages/web/src/core/folder-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<File, 'size' | 'type'> }
export type FolderSelection<T extends FolderListing = ImportSource> =
| { 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
Expand All @@ -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 = <T extends FolderListing>(
entries: readonly T[],
): FolderSelection<T> => {
const sources = entries.filter(isFolderFileWanted).sort(byPath)
return sources.length > maximumFolderFiles
? { status: 'too-many' }
Expand Down
68 changes: 68 additions & 0 deletions ui-packages/web/src/core/url-import.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
})
81 changes: 81 additions & 0 deletions ui-packages/web/src/core/url-import.ts
Original file line number Diff line number Diff line change
@@ -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)
}
102 changes: 102 additions & 0 deletions ui-packages/web/src/data/remote-files.ts
Original file line number Diff line number Diff line change
@@ -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<ImportTarget, { kind: 'file' }>) => {
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 <T, R>(
items: readonly T[],
limit: number,
map: (item: T) => Promise<R>,
) => {
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<ImportTarget, { kind: 'repository' }>,
onProgress: (done: number, total: number) => void,
): Promise<FolderSelection> => {
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<ImportSource> => {
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 }
}
58 changes: 58 additions & 0 deletions ui-packages/web/src/features/resources/add-from-url-dialog.tsx
Original file line number Diff line number Diff line change
@@ -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<HTMLInputElement>(null)
useEffect(() => inputRef.current?.focus(), [])
return (
<Modal label="Add from URL" onCancel={onCancel}>
<form
onSubmit={event => {
event.preventDefault()
const target = resolveImportUrl(text)
if (target) onAdd(target)
else setInvalid(true)
}}
>
<h2>Add from URL</h2>
<p>
An arXiv paper, a GitHub repository, folder or file, or a link to any file its site lets
web pages download.
</p>
<input
ref={inputRef}
className="dialog-input"
type="url"
aria-label="Address"
placeholder="https://arxiv.org/abs/1706.03762"
value={text}
aria-invalid={invalid}
onChange={event => {
setText(event.target.value)
setInvalid(false)
}}
/>
{invalid && (
<p role="alert">Paste an https address, such as an arXiv paper or a GitHub repository.</p>
)}
<div className="dialog-actions">
<button type="button" className="text-button" onClick={onCancel}>
Cancel
</button>
<button type="submit" className="primary-button" disabled={!text.trim()}>
Add
</button>
</div>
</form>
</Modal>
)
}
Loading