rspace-online/modules/rdocs/local-first-client.ts

56 lines
2.6 KiB
TypeScript

/**
* rDocs Local-First Client — syncs linked Docmost documents.
*/
import { DocumentManager } from '../../shared/local-first/document';
import type { DocumentId } from '../../shared/local-first/document';
import { EncryptedDocStore } from '../../shared/local-first/storage';
import { DocSyncManager } from '../../shared/local-first/sync';
import { DocCrypto } from '../../shared/local-first/crypto';
import { docsSchema, docsDocId } from './schemas';
import type { DocsDoc, LinkedDocument } from './schemas';
export class DocsLocalFirstClient {
#space: string; #documents: DocumentManager; #store: EncryptedDocStore; #sync: DocSyncManager; #initialized = false;
constructor(space: string, docCrypto?: DocCrypto) {
this.#space = space; this.#documents = new DocumentManager();
this.#store = new EncryptedDocStore(space, docCrypto);
this.#sync = new DocSyncManager({ documents: this.#documents, store: this.#store });
this.#documents.registerSchema(docsSchema);
}
get isConnected(): boolean { return this.#sync.isConnected; }
async init(): Promise<void> {
if (this.#initialized) return;
await this.#store.open();
const cachedIds = await this.#store.listByModule('docs', 'links');
const cached = await this.#store.loadMany(cachedIds);
for (const [docId, binary] of cached) this.#documents.open<DocsDoc>(docId, docsSchema, binary);
await this.#sync.preloadSyncStates(cachedIds);
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
try { await this.#sync.connect(`${proto}//${location.host}/ws/${this.#space}`, this.#space); } catch {}
this.#initialized = true;
}
async subscribe(): Promise<DocsDoc | null> {
const docId = docsDocId(this.#space) as DocumentId;
let doc = this.#documents.get<DocsDoc>(docId);
if (!doc) { const b = await this.#store.load(docId); doc = b ? this.#documents.open<DocsDoc>(docId, docsSchema, b) : this.#documents.open<DocsDoc>(docId, docsSchema); }
await this.#sync.subscribe([docId]); return doc ?? null;
}
getDoc(): DocsDoc | undefined { return this.#documents.get<DocsDoc>(docsDocId(this.#space) as DocumentId); }
onChange(cb: (doc: DocsDoc) => void): () => void { return this.#sync.onChange(docsDocId(this.#space) as DocumentId, cb as (doc: any) => void); }
linkDocument(doc: LinkedDocument): void {
this.#sync.change<DocsDoc>(docsDocId(this.#space) as DocumentId, `Link ${doc.title}`, (d) => { d.linkedDocuments[doc.id] = doc; });
}
unlinkDocument(id: string): void {
this.#sync.change<DocsDoc>(docsDocId(this.#space) as DocumentId, `Unlink document`, (d) => { delete d.linkedDocuments[id]; });
}
async disconnect(): Promise<void> { await this.#sync.flush(); this.#sync.disconnect(); }
}