Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update useDocuments to return map keyed by AutomergeUrl #379

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
78 changes: 40 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,130 @@ 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
Loading