electron-shared-state
Version:
❤️ easily sharing state across electron main and renderer processes.
2 lines (1 loc) • 1.45 kB
JavaScript
import w,{applyPatches as S,enablePatches as R}from"immer";import{ipcMain as C,webContents as y,ipcRenderer as T}from"electron";R();function _(m,E={}){let s=m,r={patches:[]},i=[],{name:u}=E,h=new Set,l=process?.type==="renderer",a=process?.type==="browser",p=a?C:T,d=`@@ELECTRON_SHARED_STORE_IPC_CHANNEL${u?"::"+u:""}`,o=!1;p.on(d,(e,n)=>{if(a){let t=e.sender.id;h.add(t)}if(n.patches.length===0)return;o=!0;let c=S(s,n.patches);r={...n,senderId:a?e.sender.id:-1},I(),s=c,o=!1;for(let t=0;t<i.length;t++){let f=i[t];f(s,n.description)}});function I(){r.patches.length!==0&&(l?r.senderId!==-1&&p.send(d,r):a&&h.forEach(e=>{if(e===r.senderId)return;let n=y.fromId(e);n&&n.send(d,r)}))}function b(e,n){o=!0;let c=w(s,e,t=>{r={patches:t,description:n}});I(),s=c,o=!1;for(let t=0;t<i.length;t++){let f=i[t];f(s,r.description)}return c}function g(){if(o)throw new Error("You may not call store.getState() inside setState method. It has already received the state as an argument. ");return s}function v(e){if(typeof e!="function")throw new Error("Expected the listener to be a function.");if(o)throw new Error("You may not call store.subscribe() inside store.setState(). ");return i.push(e),e(s,r.description),function(){if(o)throw new Error("You may not unsubscribe from a store listener while the state is updating. ");let c=i.indexOf(e);i.splice(c,1)}}return l&&p.send(d,{patches:[]}),{setState:b,getState:g,subscribe:v}}export{_ as createSharedStore};