diff --git a/README.md b/README.md index e687862..dd0ea5d 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/ui-packages/web/src/core/reading-position.test.ts b/ui-packages/web/src/core/reading-position.test.ts new file mode 100644 index 0000000..ef68884 --- /dev/null +++ b/ui-packages/web/src/core/reading-position.test.ts @@ -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) + }) +}) diff --git a/ui-packages/web/src/core/reading-position.ts b/ui-packages/web/src/core/reading-position.ts new file mode 100644 index 0000000..44c5355 --- /dev/null +++ b/ui-packages/web/src/core/reading-position.ts @@ -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 + +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 +} diff --git a/ui-packages/web/src/features/reader/document-tabs.test.tsx b/ui-packages/web/src/features/reader/document-tabs.test.tsx index b0b3bc2..6203159 100644 --- a/ui-packages/web/src/features/reader/document-tabs.test.tsx +++ b/ui-packages/web/src/features/reader/document-tabs.test.tsx @@ -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() } const workspace = (activeId: string): Workspace => { const store = createWorkspaceStore(files.map(file => file.id)) @@ -63,7 +62,6 @@ const workspace = (activeId: string): Workspace => { files, filesLoading: false, activeId, - scrollPositions, openDocument: vi.fn(), closeDocument: vi.fn(), closeDocuments: vi.fn(), diff --git a/ui-packages/web/src/features/reader/document-tabs.tsx b/ui-packages/web/src/features/reader/document-tabs.tsx index 6be48ba..1cd2dc0 100644 --- a/ui-packages/web/src/features/reader/document-tabs.tsx +++ b/ui-packages/web/src/features/reader/document-tabs.tsx @@ -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)} /> diff --git a/ui-packages/web/src/features/reader/docx-reader.test.tsx b/ui-packages/web/src/features/reader/docx-reader.test.tsx index 74691b0..6bb7a24 100644 --- a/ui-packages/web/src/features/reader/docx-reader.test.tsx +++ b/ui-packages/web/src/features/reader/docx-reader.test.tsx @@ -44,7 +44,7 @@ const renderReader = () => blob={new Blob(['docx bytes'])} files={[file]} active - scrollPositions={{ current: new Map() }} + onPositionChange={() => undefined} /> , ) diff --git a/ui-packages/web/src/features/reader/docx-reader.tsx b/ui-packages/web/src/features/reader/docx-reader.tsx index 0fff5b6..5fdaaef 100644 --- a/ui-packages/web/src/features/reader/docx-reader.tsx +++ b/ui-packages/web/src/features/reader/docx-reader.tsx @@ -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 = @@ -38,7 +37,14 @@ const convertDocument = (blob: Blob, name: string): Promise => }, ) -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 }>( null, @@ -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} /> ) diff --git a/ui-packages/web/src/features/reader/file-preview.tsx b/ui-packages/web/src/features/reader/file-preview.tsx index ad4bb6c..aace32e 100644 --- a/ui-packages/web/src/features/reader/file-preview.tsx +++ b/ui-packages/web/src/features/reader/file-preview.tsx @@ -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' @@ -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> textReader?: TextReaderDefinition } @@ -33,7 +32,8 @@ export const FilePreview = ({ document, files, active, - scrollPositions, + defaultPosition, + onPositionChange, pdfSources, textReader, }: FilePreviewProps) => { @@ -106,7 +106,8 @@ export const FilePreview = ({ blob={state.blob} files={files} active={active} - scrollPositions={scrollPositions} + defaultPosition={defaultPosition} + onPositionChange={onPositionChange} textReader={textReader} /> ) @@ -119,7 +120,8 @@ export const FilePreview = ({ blob={state.blob} files={files} active={active} - scrollPositions={scrollPositions} + defaultPosition={defaultPosition} + onPositionChange={onPositionChange} /> ) @@ -130,7 +132,8 @@ export const FilePreview = ({ document={document} blob={state.blob} active={active} - scrollPositions={scrollPositions} + defaultPosition={defaultPosition} + onPositionChange={onPositionChange} /> ) @@ -145,6 +148,8 @@ export const FilePreview = ({ document={document} source={source.url} active={active} + defaultPosition={defaultPosition} + onPositionChange={onPositionChange} /> ) diff --git a/ui-packages/web/src/features/reader/markdown-reader/index.tsx b/ui-packages/web/src/features/reader/markdown-reader/index.tsx index 82c6adb..3f345de 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/index.tsx +++ b/ui-packages/web/src/features/reader/markdown-reader/index.tsx @@ -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 @@ -32,7 +33,8 @@ export const MarkdownReader = ({ content, files, active, - scrollPositions, + defaultPosition, + onPositionChange, imageResolver, markdownOptions, appearance, @@ -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 @@ -95,14 +101,8 @@ export const MarkdownReader = ({ if (!markdown) return ( -
-
{ - if (active) scrollPositions.current.set(document.id, event.currentTarget.scrollTop) - }} - > +
+
{content}
@@ -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)) }} > diff --git a/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx b/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx index 8b18180..1928bc0 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx +++ b/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx @@ -26,7 +26,7 @@ const renderReader = (content: string) => content={content} files={[document]} active - scrollPositions={{ current: new Map() }} + onPositionChange={() => undefined} />, ) @@ -75,7 +75,7 @@ describe('Markdown file reader', () => { content: '# Guide\n\nRead at your own pace.', files: [document], active: true, - scrollPositions: { current: new Map() }, + onPositionChange: () => undefined, } const base = render() expect(screen.queryByRole('button', { name: 'Reading appearance' })).not.toBeInTheDocument() diff --git a/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts b/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts new file mode 100644 index 0000000..8932286 --- /dev/null +++ b/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts @@ -0,0 +1,102 @@ +import { type RefObject, useLayoutEffect, useRef } from 'react' +import { + type BlockBox, + type FlowPosition, + flowAnchorAt, + flowScrollTop, + type ReadingPositionProps, +} from '../../../core/reading-position' + +// Rendered Markdown keeps its blocks in one container; plain text is a single
.
+const blocksOf = (content: HTMLElement) => [
+  ...(content.querySelector(':scope > .markdown-content') ?? content).children,
+]
+
+// Layout offsets ignore scrolling, so a block's place in the scrolled content is its offset from
+// the page less the scroll container's own.
+const pageTop = (element: Element) => {
+  let top = 0
+  let node: Element | null = element
+  while (node instanceof HTMLElement) {
+    top += node.offsetTop
+    node = node.offsetParent
+  }
+  return top
+}
+
+const measure = (blocks: readonly Element[], scroll: HTMLElement) => {
+  const origin = pageTop(scroll)
+  return (index: number): BlockBox => {
+    const block = blocks[index]
+    return block instanceof HTMLElement
+      ? { top: pageTop(block) - origin, height: block.offsetHeight }
+      : { top: 0, height: 0 }
+  }
+}
+
+const readerInput = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const
+
+type FlowPositionOptions = ReadingPositionProps & {
+  rootRef: RefObject
+  scrollRef: RefObject
+  contentRef: RefObject
+  active: boolean
+}
+
+export const useFlowPosition = ({
+  rootRef,
+  scrollRef,
+  contentRef,
+  active,
+  defaultPosition,
+  onPositionChange,
+}: FlowPositionOptions) => {
+  const place = useRef(
+    defaultPosition?.kind === 'flow' ? defaultPosition : null,
+  )
+  const restoring = useRef(false)
+
+  // Images, formulas and diagrams finish after the text, pushing it down, so the place is applied
+  // again whenever the content changes size — until the reader does anything, from which point
+  // the position is theirs.
+  useLayoutEffect(() => {
+    const root = rootRef.current
+    const scroll = scrollRef.current
+    const content = contentRef.current
+    if (!active || !root || !scroll || !content) return
+    const target = place.current
+    if (!target) {
+      scroll.scrollTop = 0
+      return
+    }
+    const apply = () => {
+      const blocks = blocksOf(content)
+      scroll.scrollTop = flowScrollTop(target, blocks.length, measure(blocks, scroll))
+    }
+    const observer = new ResizeObserver(apply)
+    const release = () => {
+      restoring.current = false
+      observer.disconnect()
+      readerInput.forEach(name => {
+        root.removeEventListener(name, release)
+      })
+    }
+    restoring.current = true
+    apply()
+    observer.observe(content)
+    readerInput.forEach(name => {
+      root.addEventListener(name, release, { passive: true })
+    })
+    return release
+  }, [active, contentRef, rootRef, scrollRef])
+
+  // Browsers deliver scroll at most once a frame, and finding the block takes a handful of reads.
+  return () => {
+    const scroll = scrollRef.current
+    const content = contentRef.current
+    if (!active || restoring.current || !scroll || !content) return
+    const blocks = blocksOf(content)
+    place.current = flowAnchorAt(blocks.length, measure(blocks, scroll), scroll.scrollTop)
+    onPositionChange(place.current)
+  }
+}
diff --git a/ui-packages/web/src/features/reader/pdf-reader.tsx b/ui-packages/web/src/features/reader/pdf-reader.tsx
index 9585f1c..9af4511 100644
--- a/ui-packages/web/src/features/reader/pdf-reader.tsx
+++ b/ui-packages/web/src/features/reader/pdf-reader.tsx
@@ -1,6 +1,7 @@
 import { useRef, useState } from 'react'
 import { PdfReader as DocumentPdfReader, type PdfReaderHandle } from '../../components/pdf-reader'
 import type { StoredFileMetadata } from '../../core/files'
+import type { ReadingPositionProps } from '../../core/reading-position'
 import { useReaderBinding } from '../../shell/workspace-context'
 import { usePdfReadingTheme } from './pdf-reading-preferences'
 import { readViewport } from './reader-viewport'
@@ -9,13 +10,17 @@ export const PdfReader = ({
   document,
   source,
   active,
-}: {
+  defaultPosition,
+  onPositionChange,
+}: ReadingPositionProps & {
   document: StoredFileMetadata
   source: string
   active: boolean
 }) => {
   const readerRef = useRef(null)
-  const [pageNumber, setPageNumber] = useState(1)
+  const [pageNumber, setPageNumber] = useState(
+    defaultPosition?.kind === 'page' ? defaultPosition.page : 1,
+  )
   const [theme, setTheme] = usePdfReadingTheme()
   useReaderBinding(
     {
@@ -36,7 +41,10 @@ export const PdfReader = ({
       name={document.name}
       pageNumber={pageNumber}
       theme={theme}
-      onPageChange={setPageNumber}
+      onPageChange={page => {
+        setPageNumber(page)
+        onPositionChange({ kind: 'page', page })
+      }}
       onThemeChange={setTheme}
     />
   )
diff --git a/ui-packages/web/src/features/reader/text-document-workspace/index.tsx b/ui-packages/web/src/features/reader/text-document-workspace/index.tsx
index 760e613..f5099d6 100644
--- a/ui-packages/web/src/features/reader/text-document-workspace/index.tsx
+++ b/ui-packages/web/src/features/reader/text-document-workspace/index.tsx
@@ -10,7 +10,7 @@ import {
 import { Group, Panel, Separator, usePanelRef } from 'react-resizable-panels'
 import type { SourceLanguage } from '../../../components/source-editor'
 import type { StoredFileMetadata } from '../../../core/files'
-import type { Workspace } from '../../../shell/use-workspace'
+import type { ReadingPositionProps } from '../../../core/reading-position'
 import { useWorkspaceSource, useWorkspaceSourceActions } from '../../../shell/workspace-context'
 import type { TextReaderComponent } from '../text-file-reader'
 import styles from './style.module.scss'
@@ -27,14 +27,13 @@ const subscribeNarrow = (notify: () => void) => {
 }
 const narrowSnapshot = () => matchMedia(narrowQuery).matches
 
-type TextDocumentWorkspaceProps = {
+type TextDocumentWorkspaceProps = ReadingPositionProps & {
   document: StoredFileMetadata
   persistedContent: string
   sourceLanguage: SourceLanguage
   Preview: TextReaderComponent
   files: readonly StoredFileMetadata[]
   active: boolean
-  scrollPositions: Workspace['scrollPositions']
 }
 
 export const TextDocumentWorkspace = ({
@@ -44,7 +43,8 @@ export const TextDocumentWorkspace = ({
   Preview,
   files,
   active,
-  scrollPositions,
+  defaultPosition,
+  onPositionChange,
 }: TextDocumentWorkspaceProps) => {
   const draft = useWorkspaceSource(document.id)
   const actions = useWorkspaceSourceActions()
@@ -120,7 +120,8 @@ export const TextDocumentWorkspace = ({
               content={previewContent}
               files={files}
               active={previewActive}
-              scrollPositions={scrollPositions}
+              defaultPosition={defaultPosition}
+              onPositionChange={onPositionChange}
             />
           
         
diff --git a/ui-packages/web/src/features/reader/text-document-workspace/text-document-workspace.test.tsx b/ui-packages/web/src/features/reader/text-document-workspace/text-document-workspace.test.tsx index 4e3c5cc..e1e228f 100644 --- a/ui-packages/web/src/features/reader/text-document-workspace/text-document-workspace.test.tsx +++ b/ui-packages/web/src/features/reader/text-document-workspace/text-document-workspace.test.tsx @@ -73,7 +73,7 @@ const Harness = ({ blob={blob} files={[file]} active={visible} - scrollPositions={workspace.scrollPositions} + onPositionChange={() => undefined} textReader={definition} /> diff --git a/ui-packages/web/src/features/reader/text-file-reader.tsx b/ui-packages/web/src/features/reader/text-file-reader.tsx index c5ec1ec..471d751 100644 --- a/ui-packages/web/src/features/reader/text-file-reader.tsx +++ b/ui-packages/web/src/features/reader/text-file-reader.tsx @@ -2,24 +2,22 @@ import { type ComponentType, type ReactNode, useEffect, useRef, useState } from import type { MarkdownImageResolver } from '../../components/markdown-image' import type { SourceLanguage } from '../../components/source-editor' import { maximumTextPreviewBytes, type StoredFileMetadata } from '../../core/files' -import type { Workspace } from '../../shell/use-workspace' +import type { ReadingPositionProps } from '../../core/reading-position' import { TextDocumentWorkspace } from './text-document-workspace' -type TextFileReaderProps = { +type TextFileReaderProps = ReadingPositionProps & { document: StoredFileMetadata files: readonly StoredFileMetadata[] blob: Blob active: boolean - scrollPositions: Workspace['scrollPositions'] textReader: TextReaderDefinition } -export type TextReaderProps = { +export type TextReaderProps = ReadingPositionProps & { document: StoredFileMetadata content: string files: readonly StoredFileMetadata[] active: boolean - scrollPositions: Workspace['scrollPositions'] // Formats converted to Markdown carry their own images rather than workspace files. imageResolver?: MarkdownImageResolver } @@ -41,7 +39,8 @@ export const TextFileReader = ({ files, blob, active, - scrollPositions, + defaultPosition, + onPositionChange, textReader: { Preview, sourceLanguage }, }: TextFileReaderProps) => { const processedDocument = useRef<{ id: string; revision: number }>(null) @@ -110,7 +109,8 @@ export const TextFileReader = ({ Preview={Preview} files={files} active={active} - scrollPositions={scrollPositions} + defaultPosition={defaultPosition} + onPositionChange={onPositionChange} /> ) } diff --git a/ui-packages/web/src/features/reader/xlsx-reader/index.tsx b/ui-packages/web/src/features/reader/xlsx-reader/index.tsx index 31eab9a..88935f6 100644 --- a/ui-packages/web/src/features/reader/xlsx-reader/index.tsx +++ b/ui-packages/web/src/features/reader/xlsx-reader/index.tsx @@ -1,6 +1,7 @@ import { useVirtualizer } from '@tanstack/react-virtual' import { useEffect, useMemo, useRef, useState } from 'react' import type { StoredFileMetadata } from '../../../core/files' +import type { ReadingPositionProps } from '../../../core/reading-position' import { cellText, clampColumns, @@ -8,16 +9,14 @@ import { readSpreadsheet, type Worksheet, } from '../../../core/xlsx' -import type { Workspace } from '../../../shell/use-workspace' import { useReaderBinding } from '../../../shell/workspace-context' import { readViewport } from '../reader-viewport' import styles from './style.module.scss' -type XlsxReaderProps = { +type XlsxReaderProps = ReadingPositionProps & { document: StoredFileMetadata blob: Blob active: boolean - scrollPositions: Workspace['scrollPositions'] } type SheetState = @@ -40,11 +39,21 @@ const openWorkbook = (blob: Blob): Promise => }, ) -export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxReaderProps) => { +export const XlsxReader = ({ + document, + blob, + active, + defaultPosition, + onPositionChange, +}: XlsxReaderProps) => { // Parsing is not free and both StrictMode and reopening a tab ask for the same workbook again. const workbook = useRef<{ id: string; revision: number; result: Promise }>(null) const [state, setState] = useState({ status: 'loading' }) - const [selected, setSelected] = useState(0) + const [selected, setSelected] = useState( + defaultPosition?.kind === 'sheet' ? defaultPosition.sheet : 0, + ) + // The reader's own place, kept across a hidden tab, which loses its scroll offset. + const place = useRef(defaultPosition?.kind === 'sheet' ? defaultPosition.scrollTop : 0) const scrollRef = useRef(null) const tableRef = useRef(null) @@ -57,7 +66,11 @@ export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxRead if (pending !== cached) { workbook.current = pending setState({ status: 'loading' }) - setSelected(0) + // A changed workbook starts over; the first one opens where the reader left it. + if (cached) { + setSelected(0) + place.current = 0 + } } let current = true void pending.result.then(result => { @@ -78,7 +91,9 @@ export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxRead useReaderBinding(binding, active) const sheets = state.status === 'ready' ? state.sheets : [] - const rows = sheets[selected]?.rows ?? [] + // A saved sheet the workbook no longer has falls back to the first. + const sheetIndex = sheets[selected] ? selected : 0 + const rows = sheets[sheetIndex]?.rows ?? [] const { columns, hidden } = useMemo(() => clampColumns(rows), [rows]) // A column is identified by its letter, which is also what the header shows. const labels = useMemo( @@ -99,8 +114,8 @@ export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxRead useEffect(() => { // The table only exists once the workbook has parsed, so there is nothing to scroll before. if (!active || state.status !== 'ready' || !scrollRef.current) return - scrollRef.current.scrollTop = scrollPositions.current.get(document.id) ?? 0 - }, [active, document.id, scrollPositions, state.status]) + scrollRef.current.scrollTop = place.current + }, [active, state.status]) if (state.status === 'loading') return
Opening {document.name}…
@@ -122,10 +137,12 @@ export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxRead type="button" role="tab" className={styles.tab} - aria-selected={index === selected} + aria-selected={index === sheetIndex} onClick={() => { setSelected(index) + place.current = 0 if (scrollRef.current) scrollRef.current.scrollTop = 0 + onPositionChange({ kind: 'sheet', sheet: index, scrollTop: 0 }) }} > {sheet.name} @@ -142,7 +159,9 @@ export const XlsxReader = ({ document, blob, active, scrollPositions }: XlsxRead className={styles.scroll} ref={scrollRef} onScroll={event => { - if (active) scrollPositions.current.set(document.id, event.currentTarget.scrollTop) + if (!active) return + place.current = event.currentTarget.scrollTop + onPositionChange({ kind: 'sheet', sheet: sheetIndex, scrollTop: place.current }) }} > {columns === 0 ? ( diff --git a/ui-packages/web/src/features/reader/xlsx-reader/xlsx-reader.test.tsx b/ui-packages/web/src/features/reader/xlsx-reader/xlsx-reader.test.tsx index f2dff2e..07901cd 100644 --- a/ui-packages/web/src/features/reader/xlsx-reader/xlsx-reader.test.tsx +++ b/ui-packages/web/src/features/reader/xlsx-reader/xlsx-reader.test.tsx @@ -35,7 +35,7 @@ const show = (sheets: Worksheet[]) => { document={file} blob={new Blob(['xlsx'])} active - scrollPositions={{ current: new Map() }} + onPositionChange={() => undefined} /> , ) diff --git a/ui-packages/web/src/shell/use-workspace.ts b/ui-packages/web/src/shell/use-workspace.ts index 7094571..bac83e3 100644 --- a/ui-packages/web/src/shell/use-workspace.ts +++ b/ui-packages/web/src/shell/use-workspace.ts @@ -31,11 +31,13 @@ export const useWorkspace = (files: StoredFileMetadata[], filesLoading: boolean) const routeSegment = useMatch('/files/:documentId')?.params.documentId const activeId = documentIdFor(files, routeSegment) const [initialWorkspace] = useState(readWorkspace) - const [store] = useState(() => createWorkspaceStore(initialWorkspace.tabs)) + const [store] = useState(() => + createWorkspaceStore(initialWorkspace.tabs, initialWorkspace.positions), + ) const [actions] = useState(() => createWorkspaceActions(store)) const tabs = useStore(store, state => state.tabs) - const scrollPositions = useRef(new Map()) const navigationTargetRef = useRef(activeId) + const savedActiveId = useRef(initialWorkspace.lastActiveId) useEffect(() => { if (filesLoading) return @@ -69,8 +71,35 @@ export const useWorkspace = (files: StoredFileMetadata[], filesLoading: boolean) useEffect(() => { if (filesLoading || (pathname !== '/files' && (activeId === null || !tabs.includes(activeId)))) return - writeWorkspace({ tabs, lastActiveId: activeId }) - }, [tabs, activeId, pathname, filesLoading]) + savedActiveId.current = activeId + writeWorkspace({ tabs, lastActiveId: activeId, positions: store.getState().positions }) + }, [tabs, activeId, pathname, filesLoading, store]) + + // A reader reports its position as it scrolls; storage hears about it once the reader pauses, + // and before the page goes away. + useEffect(() => { + let timer: ReturnType | undefined + const save = () => { + clearTimeout(timer) + timer = undefined + const { tabs, positions } = store.getState() + writeWorkspace({ tabs, lastActiveId: savedActiveId.current, positions }) + } + const flush = () => { + if (timer !== undefined) save() + } + const unsubscribe = store.subscribe((state, previous) => { + if (state.positions === previous.positions) return + clearTimeout(timer) + timer = setTimeout(save, 1000) + }) + window.addEventListener('pagehide', flush) + return () => { + unsubscribe() + window.removeEventListener('pagehide', flush) + flush() + } + }, [store]) const openDocument = (id: string) => { if (id === navigationTargetRef.current || !files.some(document => document.id === id)) return @@ -95,9 +124,6 @@ export const useWorkspace = (files: StoredFileMetadata[], filesLoading: boolean) void navigate(documentPath(files, next), { replace: true }) } }) - closing.forEach(id => { - scrollPositions.current.delete(id) - }) } const closeDocument = (id: string) => closeDocuments([id]) @@ -109,7 +135,6 @@ export const useWorkspace = (files: StoredFileMetadata[], filesLoading: boolean) files, filesLoading, activeId, - scrollPositions, openDocument, closeDocument, closeDocuments, diff --git a/ui-packages/web/src/shell/workspace-navigation.integration.test.tsx b/ui-packages/web/src/shell/workspace-navigation.integration.test.tsx index fb37ceb..6f1bc0d 100644 --- a/ui-packages/web/src/shell/workspace-navigation.integration.test.tsx +++ b/ui-packages/web/src/shell/workspace-navigation.integration.test.tsx @@ -67,7 +67,7 @@ describe('local workspace navigation', () => { expect(screen.getByRole('textbox', { name: 'Your question' })).toBeEnabled(), ) await user.type(screen.getByRole('textbox', { name: 'Your question' }), 'A saved question') - expect(savedWorkspace()).toEqual({ + expect(savedWorkspace()).toMatchObject({ tabs: ['getting-started', 'explore-wave', 'how-gamma-reader-works'], lastActiveId: 'how-gamma-reader-works', }) @@ -170,13 +170,15 @@ describe('local workspace navigation', () => { await waitForWorkspace() await screen.findByRole('heading', { name: 'Start with a document' }) expect(tabNames()).toEqual([]) - await waitFor(() => expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null })) + await waitFor(() => + expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null, positions: {} }), + ) await user.click(screen.getByRole('button', { name: 'Open Start here.md' })) await screen.findByRole('tab', { name: 'Start here.md' }) await user.click(screen.getByRole('button', { name: 'Close Start here.md' })) expect(screen.getByLabelText('Current route')).toHaveTextContent('/files') - expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null }) + expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null, positions: {} }) page.unmount() openReader() @@ -192,7 +194,7 @@ describe('local workspace navigation', () => { ) expect(tabNames()).toEqual([]) expect(screen.queryByRole('tabpanel')).not.toBeInTheDocument() - expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null }) + expect(savedWorkspace()).toEqual({ tabs: [], lastActiveId: null, positions: {} }) }) it('restores empty defaults and reports damaged storage', async () => { @@ -254,6 +256,22 @@ describe('local workspace navigation', () => { expect(scroll.scrollTop).toBe(180) expect(screen.queryByRole('button', { name: 'Ask AI' })).not.toBeInTheDocument() }) + it('reopens a document where the reader left it after a reload', async () => { + const scroll = () => { + const element = screen.getByRole('tabpanel').querySelector('.document-scroll') + if (!element) throw new Error('Document scroll container is missing') + return element + } + const page = openReader('/files/Start%20here.md') + await screen.findByRole('heading', { name: 'Start here' }) + fireEvent.scroll(scroll(), { target: { scrollTop: 180 } }) + page.unmount() + + openReader('/files/Start%20here.md') + await screen.findByRole('heading', { name: 'Start here' }) + await waitFor(() => expect(scroll().scrollTop).toBe(180)) + }) + it('opens a document whose name differs only in case, as a rename leaves behind', async () => { // The write tool replaces a file it matched without regard to case, so the name in an // address can fall out of step with the one on the file by exactly that much. diff --git a/ui-packages/web/src/shell/workspace-storage.ts b/ui-packages/web/src/shell/workspace-storage.ts index c7802b2..d74e826 100644 --- a/ui-packages/web/src/shell/workspace-storage.ts +++ b/ui-packages/web/src/shell/workspace-storage.ts @@ -1,12 +1,29 @@ +import { isReadingPosition, type ReadingPosition } from '../core/reading-position' import { workspaceStorageBases, workspaceStorageKey } from '../data/workspace-database' -type SavedWorkspace = { tabs: string[]; lastActiveId: string | null } +export type ReadingPositions = Record + +type SavedWorkspace = { + tabs: string[] + lastActiveId: string | null + positions: ReadingPositions +} const storageKey = workspaceStorageBases.workspace -const defaults: SavedWorkspace = { tabs: [], lastActiveId: null } +const defaults: SavedWorkspace = { tabs: [], lastActiveId: null, positions: {} } const isDocumentId = (value: unknown): value is string => typeof value === 'string' && value.length > 0 +// Positions arrived after tabs, so an absent or partly unreadable set costs only those entries. +const openPositions = (value: unknown, tabs: readonly string[]): ReadingPositions => + typeof value === 'object' && value !== null + ? Object.fromEntries( + Object.entries(value).filter( + ([id, position]) => tabs.includes(id) && isReadingPosition(position), + ), + ) + : {} + export const readWorkspace = (): SavedWorkspace => { try { const raw = localStorage.getItem(workspaceStorageKey(storageKey)) @@ -23,16 +40,25 @@ export const readWorkspace = (): SavedWorkspace => { (!isDocumentId(value.lastActiveId) || !value.tabs.includes(value.lastActiveId))) ) throw new Error('Invalid saved workspace') - return { tabs: [...new Set(value.tabs)], lastActiveId: value.lastActiveId } + const tabs = [...new Set(value.tabs)] + return { + tabs, + lastActiveId: value.lastActiveId, + positions: openPositions('positions' in value ? value.positions : undefined, tabs), + } } catch (error) { console.error('Unable to restore workspace', error) return defaults } } -export const writeWorkspace = (workspace: SavedWorkspace) => { +// A position is kept only while its document is open, so closed and removed files age out. +export const writeWorkspace = ({ tabs, lastActiveId, positions }: SavedWorkspace) => { try { - localStorage.setItem(workspaceStorageKey(storageKey), JSON.stringify(workspace)) + localStorage.setItem( + workspaceStorageKey(storageKey), + JSON.stringify({ tabs, lastActiveId, positions: openPositions(positions, tabs) }), + ) } catch (error) { console.error('Unable to save workspace', error) } diff --git a/ui-packages/web/src/shell/workspace-store.ts b/ui-packages/web/src/shell/workspace-store.ts index 46a8838..7e7656c 100644 --- a/ui-packages/web/src/shell/workspace-store.ts +++ b/ui-packages/web/src/shell/workspace-store.ts @@ -1,5 +1,6 @@ import { nanoid } from 'nanoid' import { createStore } from 'zustand/vanilla' +import type { ReadingPosition } from '../core/reading-position' export type PersistedSource = { revision: number @@ -19,6 +20,7 @@ export type SourceDraft = { export type WorkspaceState = { tabs: string[] sourceDrafts: Record + positions: Record } export type WorkspaceActions = { @@ -32,6 +34,7 @@ export type WorkspaceActions = { failSourceSave: (fileId: string, message: string, open?: boolean) => void reloadIncomingSource: (fileId: string) => void forgetSource: (fileId: string) => void + setPosition: (fileId: string, position: ReadingPosition) => void } export const sourceDirty = (draft: SourceDraft | undefined) => @@ -48,10 +51,14 @@ const updateDraft = ( return next === draft ? drafts : { ...drafts, [fileId]: next } } -export const createWorkspaceStore = (tabs: string[]) => +export const createWorkspaceStore = ( + tabs: string[], + positions: Record = {}, +) => createStore(() => ({ tabs, sourceDrafts: {}, + positions, })) export type WorkspaceStore = ReturnType @@ -68,6 +75,9 @@ export const createWorkspaceActions = (store: WorkspaceStore): WorkspaceActions sourceDrafts: Object.fromEntries( Object.entries(state.sourceDrafts).filter(([id]) => !closing.has(id)), ), + positions: Object.fromEntries( + Object.entries(state.positions).filter(([id]) => !closing.has(id)), + ), } }), setTabs: update => @@ -187,5 +197,7 @@ export const createWorkspaceActions = (store: WorkspaceStore): WorkspaceActions const { [fileId]: _removed, ...sourceDrafts } = state.sourceDrafts return { sourceDrafts } }), + setPosition: (fileId, position) => + set(state => ({ positions: { ...state.positions, [fileId]: position } })), } }