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
8 changes: 8 additions & 0 deletions ui-packages/web/src/core/projects.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
// A remote source the project's library is kept in step with, named by the deployment.
export type ProjectSource = { name: string; url: string }

export type Project = {
id: string
name: string
databaseName: string
createdAt: number
lastActiveAt: number
source?: ProjectSource
}

// The library that existed before projects keeps its name, so upgrading moves no data.
Expand All @@ -12,6 +16,10 @@ export const defaultProjectName = 'My reading'

export const projectPath = (projectId: string) => `/p/${projectId}`

// One project per source, found again by its name on every visit.
export const sourceProjectId = (source: ProjectSource) =>
`source-${encodeURIComponent(source.name.toLowerCase())}`

export const projectDeletionPath = (projectId: string) =>
`/?delete=${encodeURIComponent(projectId)}`

Expand Down
20 changes: 18 additions & 2 deletions ui-packages/web/src/data/project-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
legacyDatabaseName,
normalizeProjectName,
type Project,
type ProjectSource,
sourceProjectId,
} from '../core/projects'
import {
deleteIndexedDatabase,
Expand All @@ -19,8 +21,7 @@ type ProjectDatabase = DBSchema & {
const registryName = 'gamma-reader-projects'
let registryPromise: Promise<IDBPDatabase<ProjectDatabase>> | undefined

const newProject = (name: string, databaseName?: string): Project => {
const id = nanoid(10)
const newProject = (name: string, databaseName?: string, id = nanoid(10)): Project => {
const now = Date.now()
return {
id,
Expand Down Expand Up @@ -66,6 +67,21 @@ export const createProject = async (name: string) => {
return project
}

// The deployment's source decides the project, so a visit always lands in the same library, and
// the address it records follows the deployment if that changes.
export const openSourceProject = async (source: ProjectSource) => {
const database = await openRegistry()
const id = sourceProjectId(source)
const existing = await database.get('projects', id)
const project = {
...(existing ?? newProject(source.name, undefined, id)),
source,
lastActiveAt: Date.now(),
}
await database.put('projects', project)
return project
}

export const renameProject = async (id: string, name: string) => {
const database = await openRegistry()
const project = await database.get('projects', id)
Expand Down
1 change: 1 addition & 0 deletions ui-packages/web/src/data/workspace-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const setWorkspaceDatabaseName = (name: string) => {
export const workspaceStorageBases = {
workspace: 'gamma-reader.workspace',
activeConversation: 'gamma-reader.active-conversation',
sourceSync: 'gamma-reader.source-sync',
} as const

// Settings saved before projects existed belong to the legacy library and keep their keys.
Expand Down
2 changes: 2 additions & 0 deletions ui-packages/web/src/features/resources/resource-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ 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 { SourceSyncStatus } from '../source/sync-status'
import { AddFromUrlDialog } from './add-from-url-dialog'
import { AddMenu } from './add-menu'
import { DuplicateFilesDialog, RemoveFileDialog, RemoveFolderDialog } from './file-dialogs'
Expand Down Expand Up @@ -163,6 +164,7 @@ export const ResourcePanel = ({
}}
/>
</div>
{project.source && <SourceSyncStatus source={project.source} reload={library.reload} />}
{library.progress && (
<p className="file-progress" role="status">
{library.progress}
Expand Down
1 change: 1 addition & 0 deletions ui-packages/web/src/features/resources/use-file-library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ export const useFileLibrary = (prepareFile: (file: File) => File = keepFile) =>
updateTextFile,
resolveDuplicates,
removeFiles,
reload,
retry: () => {
setLoading(true)
void reload()
Expand Down
15 changes: 15 additions & 0 deletions ui-packages/web/src/features/source/load-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { ProjectSource } from '../../core/projects'
import { isProjectSource } from './protocol'

// Most deployments have no source and answer 404; one that cannot be asked opens as they do.
export const loadProjectSource = async (): Promise<ProjectSource | null> => {
try {
const response = await fetch('/api/source', { cache: 'no-store' })
if (!response.ok) return null
const body: unknown = await response.json()
return isProjectSource(body) ? body : null
} catch (cause) {
console.error('Unable to read the source configuration', cause)
return null
}
}
61 changes: 61 additions & 0 deletions ui-packages/web/src/features/source/plan.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest'
import { planSync, type SyncSnapshot, snapshotAfter } from './plan'

const listing = (files: Record<string, string>) => ({
version: Object.values(files).join('-'),
files: Object.entries(files).map(([path, version]) => ({ path, version, size: 1 })),
})

const previous: SyncSnapshot = {
version: 'old',
files: {
'notes/same.md': { version: 'a', revision: 1 },
'notes/changed.md': { version: 'b', revision: 1 },
'notes/edited.md': { version: 'c', revision: 1 },
'notes/gone.md': { version: 'd', revision: 1 },
'notes/gone-edited.md': { version: 'e', revision: 1 },
},
}
const local = [
{ id: 'same', path: 'notes/same.md', revision: 1 },
{ id: 'changed', path: 'notes/changed.md', revision: 1 },
{ id: 'edited', path: 'notes/edited.md', revision: 2 },
{ id: 'gone', path: 'notes/gone.md', revision: 1 },
{ id: 'gone-edited', path: 'notes/gone-edited.md', revision: 3 },
{ id: 'mine', path: 'notes/mine.md', revision: 1 },
]

describe('source sync plan', () => {
it('brings in changes, removes what left the source and keeps edits made here', () => {
const next = listing({
'notes/same.md': 'a',
'notes/changed.md': 'b2',
'notes/edited.md': 'c2',
'notes/new.md': 'f',
})

const plan = planSync(previous, next, local)

expect(plan.download.map(file => file.path)).toEqual(['notes/changed.md', 'notes/new.md'])
expect(plan.remove).toEqual(['gone'])
expect(plan.kept).toEqual(['notes/edited.md', 'notes/gone-edited.md'])
})

it('adds everything to an empty library and keeps a file it already holds', () => {
const plan = planSync(null, listing({ 'a.md': '1', 'notes/mine.md': '2' }), local)

expect(plan.download.map(file => file.path)).toEqual(['a.md'])
expect(plan.kept).toEqual(['notes/mine.md'])
})

it('records kept edits as synced so the next version of them arrives', () => {
const next = listing({ 'notes/edited.md': 'c2' })
const snapshot = snapshotAfter(next, local)

expect(snapshot).toEqual({
version: next.version,
files: { 'notes/edited.md': { version: 'c2', revision: 2 } },
})
expect(planSync(snapshot, listing({ 'notes/edited.md': 'c3' }), local).download).toHaveLength(1)
})
})
63 changes: 63 additions & 0 deletions ui-packages/web/src/features/source/plan.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type { SourceFile, SourceListing } from './protocol'

// What the library held after the last sync: each source file's version, and the revision the
// library gave it, so a later edit in the library can be told apart from the copy that arrived.
export type SyncSnapshot = {
version: string
files: Record<string, { version: string; revision: number }>
}

type LocalFile = { id: string; path: string; revision: number }

export type SyncPlan = {
download: SourceFile[]
remove: string[]
// Edited here since the last sync, so the library keeps its own copy.
kept: string[]
}

// Paths in the library are matched without regard to case, as the store matches them.
const byPath = (files: readonly LocalFile[]) =>
new Map(files.map(file => [file.path.toLowerCase(), file]))

export const planSync = (
previous: SyncSnapshot | null,
listing: SourceListing,
local: readonly LocalFile[],
): SyncPlan => {
const here = byPath(local)
const edited = (path: string) => {
const file = here.get(path.toLowerCase())
const synced = previous?.files[path]
return file !== undefined && file.revision !== synced?.revision
}
const changed = listing.files.filter(file => previous?.files[file.path]?.version !== file.version)
const listed = new Set(listing.files.map(file => file.path))
const gone = Object.keys(previous?.files ?? {}).filter(path => !listed.has(path))
return {
download: changed.filter(file => !edited(file.path)),
remove: gone.flatMap(path => {
const file = here.get(path.toLowerCase())
return file && !edited(path) ? [file.id] : []
}),
kept: [...changed, ...gone.map(path => ({ path }))].map(file => file.path).filter(edited),
}
}

// Every listed file the library now holds counts as synced at its current revision, including a
// kept edit: once that edit is pushed to the source, its next version arrives as usual.
export const snapshotAfter = (
listing: SourceListing,
local: readonly LocalFile[],
): SyncSnapshot => {
const here = byPath(local)
return {
version: listing.version,
files: Object.fromEntries(
listing.files.flatMap(file => {
const held = here.get(file.path.toLowerCase())
return held ? [[file.path, { version: file.version, revision: held.revision }]] : []
}),
),
}
}
36 changes: 36 additions & 0 deletions ui-packages/web/src/features/source/protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { ProjectSource } from '../../core/projects'

// What a remote source serves: one listing, and each file under its path. Versions are opaque;
// they only have to change when the content does.
export type SourceFile = { path: string; version: string; size: number }
export type SourceListing = { version: string; files: SourceFile[] }

const isSourceFile = (value: unknown): value is SourceFile =>
typeof value === 'object' &&
value !== null &&
'path' in value &&
typeof value.path === 'string' &&
'version' in value &&
typeof value.version === 'string' &&
'size' in value &&
typeof value.size === 'number'

export const isSourceListing = (value: unknown): value is SourceListing =>
typeof value === 'object' &&
value !== null &&
'version' in value &&
typeof value.version === 'string' &&
'files' in value &&
Array.isArray(value.files) &&
value.files.every(isSourceFile)

export const isProjectSource = (value: unknown): value is ProjectSource =>
typeof value === 'object' &&
value !== null &&
'name' in value &&
typeof value.name === 'string' &&
'url' in value &&
typeof value.url === 'string'

export const sourceFileUrl = (source: ProjectSource, path: string) =>
`${source.url.replace(/\/$/, '')}/files/${path.split('/').map(encodeURIComponent).join('/')}`
50 changes: 50 additions & 0 deletions ui-packages/web/src/features/source/sync-status.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { RefreshCw } from 'lucide-react'
import type { ProjectSource } from '../../core/projects'
import { useSourceSync } from './use-source-sync'

const fileCount = (count: number) => `${count.toLocaleString()} ${count === 1 ? 'file' : 'files'}`

// One line under the toolbar: whether the source has changed, and the action that brings it in.
export const SourceSyncStatus = ({
source,
reload,
}: {
source: ProjectSource
reload: () => Promise<void>
}) => {
const { state, sync } = useSourceSync(source, reload)
const message =
state.kind === 'checking'
? `Checking ${source.name}…`
: state.kind === 'current'
? `${source.name} is up to date.`
: state.kind === 'available'
? `${source.name} has changes.`
: state.kind === 'syncing'
? `Syncing ${source.name}… ${state.done.toLocaleString()} of ${fileCount(state.total)}`
: state.kind === 'synced'
? [
`${source.name} is up to date.`,
state.kept.length
? `Kept your edits to ${fileCount(state.kept.length)}: ${state.kept.join(', ')}.`
: '',
state.refused
? `${fileCount(state.refused)} did not fit the library limits.`
: '',
]
.filter(Boolean)
.join(' ')
: state.message
const actionable = state.kind === 'available' || state.kind === 'failed'
return (
<div className="source-sync" role="status">
<span>{message}</span>
{actionable && (
<button type="button" className="text-button" onClick={() => void sync()}>
<RefreshCw size={12} aria-hidden="true" />
Sync
</button>
)}
</div>
)
}
Loading