Skip to content

Commit

Permalink
Update useDocuments to return map keyed by AutomergeUrl
Browse files Browse the repository at this point in the history
The recommended mechanism seems to be to store Automerge URLs when
referencing other documents, not just plain document ids, so it seems
more natural to key the map returned from useDocuments by URL rather
than by id.

See discussion in https://discord.com/channels/1200006940210757672/1202325266937159690/1277333966575374356
  • Loading branch information
msakrejda committed Aug 27, 2024
1 parent 7c486df commit 0a39b2a
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 86 deletions.
75 changes: 37 additions & 38 deletions packages/automerge-repo-react-hooks/src/useDocuments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,128 +5,127 @@ import {
DocHandleDeletePayload,
DocumentId,
isValidAutomergeUrl,
parseAutomergeUrl,
stringifyAutomergeUrl,
} from "@automerge/automerge-repo/slim"
import { useEffect, useMemo, useRef, useState } from "react"
import { useRepo } from "./useRepo.js"

/**
* Maintains a map of document states, keyed by DocumentId. Useful for collections of related
* Maintains a map of document states, keyed by AutomergeUrl. Useful for collections of related
* documents.
* Accepts either URLs or document IDs in the input array, but all get converted to IDs
* Accepts either URLs or document IDs in the input array, but all get converted to URLs
* for the output map.
*/
export const useDocuments = <T>(idsOrUrls?: DocId[]) => {
const repo = useRepo()
const ids = useMemo(
const urls = useMemo(
() =>
idsOrUrls?.map(idOrUrl => {
if (isValidAutomergeUrl(idOrUrl)) {
const { documentId } = parseAutomergeUrl(idOrUrl)
return documentId
return idOrUrl as AutomergeUrl
} else {
return idOrUrl as DocumentId
return stringifyAutomergeUrl(idOrUrl)
}
}) ?? [],
[idsOrUrls]
)
const prevIds = useRef<DocumentId[]>([])
const prevUrls = useRef<AutomergeUrl[]>([])
const [documents, setDocuments] = useState(() => {
return ids.reduce((docs, id) => {
const handle = repo.find<T>(id)
return urls.reduce((docs, url) => {
const handle = repo.find<T>(url)
const doc = handle.docSync()
if (doc) {
docs[id] = doc
docs[url] = doc
}
return docs
}, {} as Record<DocumentId, T>)
}, {} as Record<AutomergeUrl, T>)
})

useEffect(() => {
// These listeners will live for the lifetime of this useEffect
// and be torn down when the useEffect is rerun.
const listeners = {} as Record<DocumentId, Listeners<T>>
const updateDocument = (id: DocId, doc?: T) => {
if (doc) setDocuments(docs => ({ ...docs, [id]: doc }))
const listeners = {} as Record<AutomergeUrl, Listeners<T>>
const updateDocument = (url: AutomergeUrl, doc?: T) => {
if (doc) setDocuments(docs => ({ ...docs, [url]: doc }))
}
const addListener = (handle: DocHandle<T>) => {
const id = handle.documentId
const url = stringifyAutomergeUrl(handle.documentId);

// whenever a document changes, update our map
const listenersForDoc: Listeners<T> = {
change: ({ doc }) => updateDocument(id, doc),
delete: () => removeDocument(id),
change: ({ doc }) => updateDocument(url, doc),
delete: () => removeDocument(url),
}
handle.on("change", listenersForDoc.change)
handle.on("delete", listenersForDoc.delete)

// store the listener so we can remove it later
listeners[id] = listenersForDoc
listeners[url] = listenersForDoc
}

const removeDocument = (id: DocumentId) => {
const removeDocument = (url: AutomergeUrl) => {
// remove the document from the document map
setDocuments(docs => {
const { [id]: _removedDoc, ...remainingDocs } = docs
const { [url]: _removedDoc, ...remainingDocs } = docs
return remainingDocs
})
}

// Add a new document to our map
const addNewDocument = (id: DocumentId) => {
const handle = repo.find<T>(id)
const addNewDocument = (url: AutomergeUrl) => {
const handle = repo.find<T>(url)
if (handle.docSync()) {
updateDocument(id, handle.docSync())
updateDocument(url, handle.docSync())
addListener(handle)
} else {
// As each document loads, update our map
handle
.doc()
.then(doc => {
updateDocument(id, doc)
updateDocument(url, doc)
addListener(handle)
})
.catch(err => {
console.error(`Error loading document ${id} in useDocuments: `, err)
console.error(`Error loading document ${url} in useDocuments: `, err)
})
}
}

const teardown = () => {
Object.entries(listeners).forEach(([id, listeners]) => {
const handle = repo.find<T>(id as DocId)
Object.entries(listeners).forEach(([url, listeners]) => {
const handle = repo.find<T>(url as AutomergeUrl)
handle.off("change", listeners.change)
handle.off("delete", listeners.delete)
})
}

if (!ids) {
if (!urls) {
return teardown
}

for (const id of ids) {
const handle = repo.find<T>(id)
if (prevIds.current.includes(id)) {
for (const url of urls) {
const handle = repo.find<T>(url)
if (prevUrls.current.includes(url)) {
// the document was already in our list before.
// we only need to register new listeners.
addListener(handle)
} else {
// This is a new document that was not in our list before.
// We need to update its state in the documents array and register
// new listeners.
addNewDocument(id)
addNewDocument(url)
}
}

// remove any documents that are no longer in the list
const removedIds = prevIds.current.filter(id => !ids.includes(id))
removedIds.forEach(removeDocument)
const removedUrls = prevUrls.current.filter(url => !urls.includes(url))
removedUrls.forEach(removeDocument)

// Update the ref so we remember the old IDs for next time
prevIds.current = ids
// Update the ref so we remember the old URLs for next time
prevUrls.current = urls

return teardown
}, [ids, repo])
}, [urls, repo])

return documents
}
Expand Down
Loading

0 comments on commit 0a39b2a

Please sign in to comment.