Added document ID in URL

This commit is contained in:
Stephan Egli 2025-01-10 11:48:34 +01:00
parent c61efa7b52
commit 2ea5f45eb9

View File

@ -1,6 +1,7 @@
// docManager.js (Automerge 2.x style)
import { Repo } from "@automerge/automerge-repo"
import { Repo, isValidAutomergeUrl } from "@automerge/automerge-repo"
import * as Automerge from "@automerge/automerge"
// For IndexedDB storage
import { IndexedDBStorageAdapter } from '@automerge/automerge-repo-storage-indexeddb'
import { BrowserWebSocketClientAdapter } from "@automerge/automerge-repo-network-websocket"
@ -9,29 +10,28 @@ let handle
export function initRepo() {
const repo = new Repo({
// Choose a network adapter or omit if youre doing pure local
network: [new BrowserWebSocketClientAdapter("wss://automerge.rheinheim.fraction.ch")],
// Use IndexedDB instead of localStorage
storage: new IndexedDBStorageAdapter({
// optionally specify a database name (defaults to "automerge")
databaseName: "myAutomergeDB"
})
network: [
new BrowserWebSocketClientAdapter("wss://sync.automerge.org")
],
storage: new IndexedDBStorageAdapter()
})
// Now create or open a document
handle = repo.create()
// Check for existing docId in URL hash
const rootDocUrl = document.location.hash.substring(1)
if (rootDocUrl && isValidAutomergeUrl(rootDocUrl)) {
handle = repo.find(rootDocUrl)
} else {
// Create new document if none exists
handle = repo.create({
shapes: []
})
// Set the URL hash to the new document's URL
document.location.hash = handle.url
}
// Listen for 'change' events
handle.on("change", ({doc}) => {
console.log("Document changed!")
// The up-to-date document is accessible via handle.doc
console.log("Current doc state:", doc)
})
// Initialize the doc with some data
handle.change(doc => {
doc.shapes = []
console.log("Document changed!", doc)
})
return handle