diff options
author | 2021-12-23 15:48:58 +0100 | |
---|---|---|
committer | 2021-12-23 15:48:58 +0100 | |
commit | b5d16a8068ed55b784f8e10f19a99cc7f11b8bc7 (patch) | |
tree | d819b4bb607f5b046451e15385c16804d5f43fcf /packages/renderer/src/stores/RootStore.ts | |
parent | feat: Main to renderer store synchronization (diff) | |
download | sophie-b5d16a8068ed55b784f8e10f19a99cc7f11b8bc7.tar.gz sophie-b5d16a8068ed55b784f8e10f19a99cc7f11b8bc7.tar.zst sophie-b5d16a8068ed55b784f8e10f19a99cc7f11b8bc7.zip |
feat: Add react and mobx integration
Diffstat (limited to 'packages/renderer/src/stores/RootStore.ts')
-rw-r--r-- | packages/renderer/src/stores/RootStore.ts | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/packages/renderer/src/stores/RootStore.ts b/packages/renderer/src/stores/RootStore.ts new file mode 100644 index 0000000..86efac6 --- /dev/null +++ b/packages/renderer/src/stores/RootStore.ts | |||
@@ -0,0 +1,61 @@ | |||
1 | import { | ||
2 | applySnapshot, | ||
3 | applyPatch, | ||
4 | getEnv as getAnyEnv, | ||
5 | IAnyStateTreeNode, | ||
6 | Instance, | ||
7 | types | ||
8 | } from 'mobx-state-tree'; | ||
9 | import { sharedStore, SophieRenderer } from '@sophie/shared'; | ||
10 | |||
11 | export interface RootEnv { | ||
12 | ipc: SophieRenderer; | ||
13 | } | ||
14 | |||
15 | /** | ||
16 | * Gets a well-typed environment from `model`. | ||
17 | * | ||
18 | * Only useable inside state trees created by `createAndConnectRootStore`. | ||
19 | * | ||
20 | * @param model The state tree node. | ||
21 | */ | ||
22 | export function getEnv(model: IAnyStateTreeNode): RootEnv { | ||
23 | return getAnyEnv<RootEnv>(model); | ||
24 | } | ||
25 | |||
26 | export const rootStore = types.model('RootStore', { | ||
27 | shared: sharedStore, | ||
28 | }).actions((self) => ({ | ||
29 | buttonClick() { | ||
30 | getEnv(self).ipc.buttonClick(); | ||
31 | }, | ||
32 | })); | ||
33 | |||
34 | export interface RootStore extends Instance<typeof rootStore> {} | ||
35 | |||
36 | /** | ||
37 | * Creates a new `RootStore` with a new environment and connects it to `ipc`. | ||
38 | * | ||
39 | * Changes to the `shared` store in the main process will be propagated to | ||
40 | * the newly created store via `ipc`. | ||
41 | * | ||
42 | * @param ipc The `sophieRenderer` context bridge. | ||
43 | */ | ||
44 | export function createAndConnectRootStore(ipc: SophieRenderer): RootStore { | ||
45 | const store = rootStore.create({ | ||
46 | shared: {}, | ||
47 | }, { | ||
48 | ipc, | ||
49 | }); | ||
50 | |||
51 | ipc.setSharedStoreListener({ | ||
52 | onSnapshot(snapshot) { | ||
53 | applySnapshot(store.shared, snapshot); | ||
54 | }, | ||
55 | onPatch(patch) { | ||
56 | applyPatch(store.shared, patch); | ||
57 | }, | ||
58 | }); | ||
59 | |||
60 | return store; | ||
61 | } | ||