0.1.2 โข Published 4 months ago
mobx-wormhole v0.1.2
MobX Wormhole
A lightweight library for synchronizing MobX state between windows or iframes with channel ID support.
Features
- ๐ Effortless state synchronization between parent/child windows or iframes
- ๐ Channel ID support for concurrent sync operations
- ๐งช Fully typed with TypeScript
- ๐ Deep observation to sync all nested changes
- ๐ก๏ธ Isolation between different synchronization channels
- ๐ค Reliable handshake mechanism with automatic retries
Installation
# npm
npm install mobx-wormhole mobx immer
# yarn
yarn add mobx-wormhole mobx immer
# pnpm
pnpm add mobx-wormhole mobx immer
Quick Example
// Shared interface for both windows
interface UserData {
name: string;
isActive: boolean;
preferences: {
darkMode: boolean;
};
}
// Source Window (Parent)
import { makeAutoObservable } from "mobx";
import { startDeepSourceSync } from "mobx-wormhole";
class UserStore {
data: UserData = {
name: "John",
isActive: true,
preferences: { darkMode: true },
};
constructor() {
makeAutoObservable(this);
// Start sync with target window
startDeepSourceSync({
store: this.data,
targetWindow: iframe.contentWindow, // Your iframe reference
channelId: "user-store-channel",
});
}
}
// Target Window (Child iframe)
import { TargetSync } from "mobx-wormhole";
// Create target sync with the same channel ID as source
const targetSync = new TargetSync<UserData>({
channelId: "user-store-channel", // Must match source channel ID
onStateChanged: (state) => {
console.log("State changed:", state);
},
});
// Start listening for changes
targetSync.start();
// Stop listening when done
targetSync.stop();
How It Works
Handshake: When the target starts, it sends a handshake request to get the current state from the source
- If no response is received, it automatically retries with exponential backoff
- The source responds with the complete current state
Source: Deep observes MobX store using
mobx-utils
and sends changes as patches with a unique channel IDMessage: Changes are sent via
postMessage
with channel ID to filter recipientsTarget: Receives messages, filters by channel ID, and applies patches using Immer
Development
# Install dependencies
pnpm install
# Run tests
pnpm test
# Build the library
pnpm build
License
MIT