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

56 lines
2.7 KiB
TypeScript

/**
* rDesign Local-First Client — syncs linked Affine projects.
*/
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 { designSchema, designDocId } from './schemas';
import type { DesignDoc, LinkedProject } from './schemas';
export class DesignLocalFirstClient {
#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(designSchema);
}
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('design', 'projects');
const cached = await this.#store.loadMany(cachedIds);
for (const [docId, binary] of cached) this.#documents.open<DesignDoc>(docId, designSchema, 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<DesignDoc | null> {
const docId = designDocId(this.#space) as DocumentId;
let doc = this.#documents.get<DesignDoc>(docId);
if (!doc) { const b = await this.#store.load(docId); doc = b ? this.#documents.open<DesignDoc>(docId, designSchema, b) : this.#documents.open<DesignDoc>(docId, designSchema); }
await this.#sync.subscribe([docId]); return doc ?? null;
}
getDoc(): DesignDoc | undefined { return this.#documents.get<DesignDoc>(designDocId(this.#space) as DocumentId); }
onChange(cb: (doc: DesignDoc) => void): () => void { return this.#sync.onChange(designDocId(this.#space) as DocumentId, cb as (doc: any) => void); }
linkProject(project: LinkedProject): void {
this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Link ${project.name}`, (d) => { d.linkedProjects[project.id] = project; });
}
unlinkProject(id: string): void {
this.#sync.change<DesignDoc>(designDocId(this.#space) as DocumentId, `Unlink project`, (d) => { delete d.linkedProjects[id]; });
}
async disconnect(): Promise<void> { await this.#sync.flush(); this.#sync.disconnect(); }
}