elf-sync-state-yomo
Version:
Syncs elf store state across tabs
14 lines (10 loc) • 1.51 kB
JavaScript
import { pipe, BehaviorSubject, skip, distinctUntilChanged, tap, finalize } from 'rxjs';
import { map } from 'rxjs/operators';
import { isEqual } from 'lodash-es';
import Presence from '@yomo/presencejs';
function includeKeys(a){return pipe(map(b=>Object.keys(b).reduce((c,d)=>(a.includes(d)&&(c[d]=b[d]),c),{})))}
function syncState(a,b){const c={channel:`${a.name}@store`,source:a=>a.asObservable(),preUpdate:a=>a.data,runGuard:()=>"undefined"!=typeof window&&"undefined"!=typeof window.BroadcastChannel},d=Object.assign(Object.assign({},c),b);if(!d.runGuard())return;let e;const f=()=>e.asObservable(),g=a=>{console.log("setValue: ",a),e.next(a);};// const stateChannel = new BroadcastChannel(merged.channel);
let i=null;return null===i&&(console.log("girdim"),e=new BehaviorSubject({}),i=new Presence("https://prsc.yomo.dev",{auth:{// Certification Type
type:"token",// Api for getting access token
endpoint:"https://ae59-159-146-14-53.ngrok.io/api/presence-auth"}}),i.on("connected",()=>{console.log("Connected to server: ",i.host);})),i.on("connected",()=>{i.on("updateData",b=>{console.log("data :",b),a.update(a=>Object.assign(Object.assign({},a),b));});}),i.on("connected",()=>{f().subscribe(a=>{console.log("getValue: ",a),i.send("updateData",a);});}),d.source(a).pipe(skip(1),distinctUntilChanged(isEqual),tap(a=>{(console.log("PostMessage: ",a),g(a));}),finalize(()=>{i.close(),i.on("closed",()=>{console.log("Closed the connection");});})).subscribe(),i}
export { includeKeys, syncState };