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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ AI inference runs at the model provider. On the free allowance, questions, conve

![Browser storage, local tools, and the two routes to a model provider](ui-packages/web/src/assets/samples/how-gamma-reader-works.svg)

Files, attachments, and conversations persist in **IndexedDB**, one database per project, with a small registry listing the projects; tabs, the last active file, and any model keys you configure use **localStorage**. Unsaved Source drafts and code execution state stay in memory. **Save** (⌘/Ctrl+S) saves a Source draft to the browser; **Save as…** and folder export write saved copies to your computer. Lab outputs are not included in the exported Markdown.
Files, attachments, and conversations persist in **IndexedDB**, one database per project, with a small registry listing the projects; tabs, the last active file, where you stopped in each open document, and any model keys you configure use **localStorage**. Unsaved Source drafts and code execution state stay in memory. **Save** (⌘/Ctrl+S) saves a Source draft to the browser; **Save as…** and folder export write saved copies to your computer. Lab outputs are not included in the exported Markdown.

Browser storage belongs to this site and browser profile. Export work you want to keep beyond it. Removing a file deletes only the browser copy, leaving your original unchanged.

Expand Down
32 changes: 32 additions & 0 deletions ui-packages/web/src/core/reading-position.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { type BlockBox, flowAnchorAt, flowScrollTop, isReadingPosition } from './reading-position'

const layout = (heights: readonly number[]) => {
const tops = heights.map((_, index) => heights.slice(0, index).reduce((sum, h) => sum + h, 0))
return (index: number): BlockBox => ({ top: tops[index] ?? 0, height: heights[index] ?? 0 })
}

describe('flow reading positions', () => {
it('returns to the same share of the same block after the text reflows', () => {
const wide = layout([100, 300, 200])
const anchor = flowAnchorAt(3, wide, 250)
expect(anchor).toEqual({ kind: 'flow', block: 1, offset: 0.5 })

// Narrower text wraps onto more lines, so every block grows and moves down.
const narrow = layout([150, 600, 400])
expect(flowScrollTop(anchor, 3, narrow)).toBe(150 + 300)
})

it('lands on the last block when the document has become shorter', () => {
const box = layout([100, 100])
expect(flowScrollTop({ kind: 'flow', block: 5, offset: 0.25 }, 2, box)).toBe(125)
})

it('rejects stored positions it could not restore', () => {
expect(isReadingPosition({ kind: 'page', page: 3 })).toBe(true)
expect(isReadingPosition({ kind: 'page', page: 0 })).toBe(false)
expect(isReadingPosition({ kind: 'flow', block: 2, offset: 1 })).toBe(false)
expect(isReadingPosition({ kind: 'sheet', sheet: 1, scrollTop: -4 })).toBe(false)
expect(isReadingPosition({ kind: 'scroll', top: 10 })).toBe(false)
})
})
74 changes: 74 additions & 0 deletions ui-packages/web/src/core/reading-position.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Where a reader stopped in a document, in the terms its format can restore: a PDF by page, text
// that reflows by block, and a sheet by tab and fixed-height rows.
export type ReadingPosition =
| { kind: 'page'; page: number }
| { kind: 'flow'; block: number; offset: number }
| { kind: 'sheet'; sheet: number; scrollTop: number }

export type FlowPosition = Extract<ReadingPosition, { kind: 'flow' }>

const isCount = (value: unknown): value is number =>
typeof value === 'number' && Number.isInteger(value) && value >= 0

export const isReadingPosition = (value: unknown): value is ReadingPosition => {
if (typeof value !== 'object' || value === null || !('kind' in value)) return false
if (value.kind === 'page') return 'page' in value && isCount(value.page) && value.page >= 1
if (value.kind === 'flow')
return (
'block' in value &&
isCount(value.block) &&
'offset' in value &&
typeof value.offset === 'number' &&
value.offset >= 0 &&
value.offset < 1
)
if (value.kind === 'sheet')
return (
'sheet' in value &&
isCount(value.sheet) &&
'scrollTop' in value &&
typeof value.scrollTop === 'number' &&
value.scrollTop >= 0
)
return false
}

export type BlockBox = { top: number; height: number }

// A pixel offset means a different paragraph once the width or text size changes. A block and
// the share of it already scrolled past survive both, so that is what a flow position keeps.
export const flowAnchorAt = (
count: number,
box: (index: number) => BlockBox,
scrollTop: number,
): FlowPosition => {
if (count === 0) return { kind: 'flow', block: 0, offset: 0 }
// Blocks are laid out in order, so the last one starting at or above the top is found by halving.
let low = 0
let high = count - 1
while (low < high) {
const middle = Math.ceil((low + high) / 2)
if (box(middle).top <= scrollTop) low = middle
else high = middle - 1
}
const { top, height } = box(low)
const offset = height > 0 ? (scrollTop - top) / height : 0
return { kind: 'flow', block: low, offset: Math.min(Math.max(offset, 0), 0.999) }
}

export const flowScrollTop = (
position: FlowPosition,
count: number,
box: (index: number) => BlockBox,
) => {
if (count === 0) return 0
const { top, height } = box(Math.min(position.block, count - 1))
return top + position.offset * height
}

// A reader takes its starting place once, when it mounts, then keeps its own and reports changes:
// the defaultValue and onChange of an uncontrolled input.
export type ReadingPositionProps = {
defaultPosition?: ReadingPosition
onPositionChange: (position: ReadingPosition) => void
}
2 changes: 0 additions & 2 deletions ui-packages/web/src/features/reader/document-tabs.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ const storedFile = (
const pdfFile = storedFile('pdf', 'Guide.pdf', 'pdf')
const imageFile = storedFile('image', 'Figure.png', 'image')
const files = [pdfFile, imageFile]
const scrollPositions = { current: new Map<string, number>() }

const workspace = (activeId: string): Workspace => {
const store = createWorkspaceStore(files.map(file => file.id))
Expand All @@ -63,7 +62,6 @@ const workspace = (activeId: string): Workspace => {
files,
filesLoading: false,
activeId,
scrollPositions,
openDocument: vi.fn(),
closeDocument: vi.fn(),
closeDocuments: vi.fn(),
Expand Down
5 changes: 4 additions & 1 deletion ui-packages/web/src/features/reader/document-tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,10 @@ export const DocumentTabs = ({
document={source}
files={workspace.files}
active={workspace.activeId === id}
scrollPositions={workspace.scrollPositions}
// Read when the reader mounts, not subscribed: a reader reports its place as it
// scrolls, and the tabs have no reason to render again for that.
defaultPosition={workspace.store.getState().positions[id]}
onPositionChange={position => workspace.actions.setPosition(id, position)}
pdfSources={pdfSources}
textReader={textReaderFor(source)}
/>
Expand Down
2 changes: 1 addition & 1 deletion ui-packages/web/src/features/reader/docx-reader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const renderReader = () =>
blob={new Blob(['docx bytes'])}
files={[file]}
active
scrollPositions={{ current: new Map() }}
onPositionChange={() => undefined}
/>
</StrictMode>,
)
Expand Down
17 changes: 12 additions & 5 deletions ui-packages/web/src/features/reader/docx-reader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import { useEffect, useRef, useState } from 'react'
import type { MarkdownImageResolver } from '../../components/markdown-image'
import { convertDocxToMarkdown, reportDocxMessages } from '../../core/docx'
import type { StoredFileMetadata } from '../../core/files'
import type { Workspace } from '../../shell/use-workspace'
import type { ReadingPositionProps } from '../../core/reading-position'
import { StandardMarkdownReader } from './markdown-reader/standard-reader'

type DocxReaderProps = {
type DocxReaderProps = ReadingPositionProps & {
document: StoredFileMetadata
blob: Blob
files: readonly StoredFileMetadata[]
active: boolean
scrollPositions: Workspace['scrollPositions']
}

type ConversionState =
Expand Down Expand Up @@ -38,7 +37,14 @@ const convertDocument = (blob: Blob, name: string): Promise<ConversionState> =>
},
)

export const DocxReader = ({ document, blob, files, active, scrollPositions }: DocxReaderProps) => {
export const DocxReader = ({
document,
blob,
files,
active,
defaultPosition,
onPositionChange,
}: DocxReaderProps) => {
// Converting is expensive, and both StrictMode and reopening a tab ask for the same document again.
const conversion = useRef<{ id: string; revision: number; result: Promise<ConversionState> }>(
null,
Expand Down Expand Up @@ -83,7 +89,8 @@ export const DocxReader = ({ document, blob, files, active, scrollPositions }: D
content={state.content}
files={files}
active={active}
scrollPositions={scrollPositions}
defaultPosition={defaultPosition}
onPositionChange={onPositionChange}
imageResolver={state.resolveImage}
/>
)
Expand Down
19 changes: 12 additions & 7 deletions ui-packages/web/src/features/reader/file-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { lazy, type RefObject, Suspense, useEffect, useState } from 'react'
import { formatBytes, type StoredFileMetadata } from '../../core/files'
import type { ReadingPositionProps } from '../../core/reading-position'
import { getStoredFile } from '../../data/file-store'
import type { Workspace } from '../../shell/use-workspace'
import { ImageReader } from './image-reader'
import { TextFileReader, type TextReaderDefinition } from './text-file-reader'

Expand All @@ -13,11 +13,10 @@ const XlsxReader = lazy(() =>
import('./xlsx-reader').then(module => ({ default: module.XlsxReader })),
)

type FilePreviewProps = {
type FilePreviewProps = ReadingPositionProps & {
document: StoredFileMetadata
files: readonly StoredFileMetadata[]
active: boolean
scrollPositions: Workspace['scrollPositions']
pdfSources: RefObject<Map<string, PdfSourceCacheEntry>>
textReader?: TextReaderDefinition
}
Expand All @@ -33,7 +32,8 @@ export const FilePreview = ({
document,
files,
active,
scrollPositions,
defaultPosition,
onPositionChange,
pdfSources,
textReader,
}: FilePreviewProps) => {
Expand Down Expand Up @@ -106,7 +106,8 @@ export const FilePreview = ({
blob={state.blob}
files={files}
active={active}
scrollPositions={scrollPositions}
defaultPosition={defaultPosition}
onPositionChange={onPositionChange}
textReader={textReader}
/>
)
Expand All @@ -119,7 +120,8 @@ export const FilePreview = ({
blob={state.blob}
files={files}
active={active}
scrollPositions={scrollPositions}
defaultPosition={defaultPosition}
onPositionChange={onPositionChange}
/>
</Suspense>
)
Expand All @@ -130,7 +132,8 @@ export const FilePreview = ({
document={document}
blob={state.blob}
active={active}
scrollPositions={scrollPositions}
defaultPosition={defaultPosition}
onPositionChange={onPositionChange}
/>
</Suspense>
)
Expand All @@ -145,6 +148,8 @@ export const FilePreview = ({
document={document}
source={source.url}
active={active}
defaultPosition={defaultPosition}
onPositionChange={onPositionChange}
/>
</Suspense>
)
Expand Down
28 changes: 14 additions & 14 deletions ui-packages/web/src/features/reader/markdown-reader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { parseMarkdownHeadings } from './heading-model'
import { MarkdownOutline } from './outline'
import type { MarkdownReadingPreferences } from './reading-preferences'
import styles from './style.module.scss'
import { useFlowPosition } from './use-flow-position'

const embeddedOutlineMinimumWidth = 640

Expand All @@ -32,7 +33,8 @@ export const MarkdownReader = ({
content,
files,
active,
scrollPositions,
defaultPosition,
onPositionChange,
imageResolver,
markdownOptions,
appearance,
Expand Down Expand Up @@ -77,10 +79,14 @@ export const MarkdownReader = ({
return () => observer.disconnect()
}, [markdown])

useLayoutEffect(() => {
if (!active || !previewScrollRef.current) return
previewScrollRef.current.scrollTop = scrollPositions.current.get(document.id) ?? 0
}, [active, document.id, scrollPositions])
const recordPosition = useFlowPosition({
rootRef,
scrollRef: previewScrollRef,
contentRef: articleRef,
active,
defaultPosition,
onPositionChange,
})

useLayoutEffect(() => {
if (!markdown || !articleRef.current || !previewScrollRef.current) return
Expand All @@ -95,14 +101,8 @@ export const MarkdownReader = ({

if (!markdown)
return (
<div className="reader-content">
<div
className="document-scroll"
ref={previewScrollRef}
onScroll={event => {
if (active) scrollPositions.current.set(document.id, event.currentTarget.scrollTop)
}}
>
<div className="reader-content" ref={rootRef}>
<div className="document-scroll" ref={previewScrollRef} onScroll={recordPosition}>
<article className="markdown-body plain-text-body" ref={articleRef}>
<pre>{content}</pre>
</article>
Expand Down Expand Up @@ -167,7 +167,7 @@ export const MarkdownReader = ({
ref={previewScrollRef}
onScroll={event => {
if (!active) return
scrollPositions.current.set(document.id, event.currentTarget.scrollTop)
recordPosition()
setActiveHeadingId(activeHeadingFrom(headingElements.current, event.currentTarget))
}}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const renderReader = (content: string) =>
content={content}
files={[document]}
active
scrollPositions={{ current: new Map() }}
onPositionChange={() => undefined}
/>,
)

Expand Down Expand Up @@ -75,7 +75,7 @@ describe('Markdown file reader', () => {
content: '# Guide\n\nRead at your own pace.',
files: [document],
active: true,
scrollPositions: { current: new Map<string, number>() },
onPositionChange: () => undefined,
}
const base = render(<MarkdownReader {...props} />)
expect(screen.queryByRole('button', { name: 'Reading appearance' })).not.toBeInTheDocument()
Expand Down
Loading