0.1.2 โ€ข Published 4 months ago

mobx-wormhole v0.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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

  1. 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
  2. Source: Deep observes MobX store using mobx-utils and sends changes as patches with a unique channel ID

  3. Message: Changes are sent via postMessage with channel ID to filter recipients

  4. Target: 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

0.1.2

4 months ago

0.1.1

4 months ago