UNPKG

collaborative-ui

Version:

React component library for building real-time collaborative editing applications.

64 lines (63 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.JsonCrdtDemosState = void 0; const json_crdt_1 = require("json-joy/lib/json-crdt"); const json_crdt_repo_1 = require("json-crdt-repo"); const rxjs_1 = require("rxjs"); class JsonCrdtDemosState { constructor(opts) { this.opts = opts; this.file$ = new rxjs_1.BehaviorSubject(null); this.sid = json_crdt_1.Model.sid(); this.selected$ = new rxjs_1.BehaviorSubject(''); this.select = (id) => { this.opts.nav.navigate('/' + [...this.opts.basePath, 'live', id].join('/')); }; this.create = (definition) => { const schema = definition.schema; const id = 'demo_' + (Date.now() % 1728578450000).toString(36) + Math.round(Math.random() * 0xffffffff).toString(36); const { session } = this.repo.sessions.make({ id: ['demo', id], schema }); const file = { id: id, session, }; this.file$.next(file); this.select(file.id); }; this.repo = new json_crdt_repo_1.JsonCrdtRepo({ wsUrl: opts.wsApi || 'wss://api.jsonjoy.org/rx', }); const basePathLength = this.opts.basePath.length; this.steps$ = new rxjs_1.BehaviorSubject(this.opts.nav.steps$.getValue().slice(basePathLength)); this.opts.nav.steps$.pipe((0, rxjs_1.map)((steps) => steps.slice(basePathLength))).subscribe(this.steps$); this.steps$ .pipe((0, rxjs_1.map)((steps) => (steps[0] === 'live' && typeof steps[1] === 'string' ? steps[1] : ''))) .subscribe(this.selected$); this.selected$.subscribe(async (id) => { if (!id) { this.file$.next(null); return; } const file = this.file$.getValue(); if (file && file.id === id) return; this.file$.next(null); try { const session = await this.repo.sessions.load({ id: ['demo', id], remote: { timeout: 10000, throwIf: 'missing' } }); const file = { id, session, }; this.file$.next(file); } catch (error) { console.error('Could not open file', id); console.error(error); } }); } url(id) { return `${window.location.protocol}//${window.location.host}${this.opts.basePath.length ? '/' + this.opts.basePath.join('/') : ''}/live/${id}`; } } exports.JsonCrdtDemosState = JsonCrdtDemosState;