Misc

Reactivity and Events

How to observe and react to changes in Polotno store using MobX and event listeners

Polotno's state is an mobx-state-tree store, so every change is observable through MobX. Install the same mobx and mobx-react-lite majors polotno uses (7 and 5): two copies of mobx in one app break observation.

In React, you get automatic UI updates by wrapping your components in observer():

import { observer } from 'mobx-react-lite';

// the component will be automatically updated when number of children is changed
export const App = observer(({ store }) => (
  <div>
    <p>Elements on the current page: {store.activePage?.children.length}</p>
  </div>
));

You can also use any data from the store as dependency to react hooks:

const App = observer(({ store }) => {
  React.useEffect(() => {
    console.log('width of the store is changed');
  }, [store.width]);
  return <></>;
})

React hooks + MobX reactions

If you want logic that runs outside the render cycle, you can combine useEffect with mobx.reaction (or autorun):

import { reaction } from 'mobx';
import { useEffect } from 'react';

export function useElementCounter(store) {
  useEffect(() => {
    // fires every time the number of elements on the active page changes
    const dispose = reaction(
      () => store.activePage?.children.length,
      (length) => {
        console.log('Element count changed:', length);
      }
    );
    return dispose;          // clean-up on unmount
  }, [store]);               // deps
}

Under the hood, MobX tracks exactly what you read inside the first function and re-runs the second function only when that value changes, with no manual listeners and no polling.

Events

store.on('change', handler) observes changes to the serialized design, such as element edits, additions, deletions, undo, and redo. It does not report transient state such as selection or highlighting. Use MobX reaction or autorun to observe that state.

const unsubscribe = store.on('change', () => {
  console.log('Something in the store changed');
});

Detecting specific actions

The event does not identify the action. Compare the design state to detect the changes you need.

Example: Simple tracking of adding/removing elements

let prevCount = store.activePage?.children.length ?? 0;

const unsub = store.on('change', () => {
  const newCount = store.activePage?.children.length ?? 0;

  if (newCount > prevCount) {
    console.log('Element added');
  } else if (newCount < prevCount) {
    console.log('Element removed');
  }

  prevCount = newCount;
});

Example: deeper tracking of adding/removing elements

Track element IDs across all pages and nested groups to detect additions and removals. Save the initial IDs before subscribing.

import { forEveryChild } from 'polotno/model/group-model';

function getElementIds() {
  const ids = new Set<string>();
  store.pages.forEach((page) => {
    forEveryChild(page, (element) => {
      ids.add(element.id);
    });
  });
  return ids;
}

let lastIds = getElementIds();
const unsubscribe = store.on('change', () => {
  const newIds = getElementIds();
  for (const id of lastIds) {
    if (!newIds.has(id)) console.log(id, 'deleted');
  }
  for (const id of newIds) {
    if (!lastIds.has(id)) console.log(id, 'added');
  }
  lastIds = newIds;
});

Example: Changes on one element

import { reaction } from 'mobx';

function watchElement(element) {
  return reaction(
    () => ({
      x: element.x,
      y: element.y,
      width: element.width,
      height: element.height,
      rotation: element.rotation,
    }),
    (coords) => {
      console.log('Element changed', coords);
    }
  );
}

// later
const dispose = watchElement(store.activePage.children[0]);

Example: Page-level changes (title, background, etc.)

reaction(
  () => ({
    title: store.activePage?.name,
    bg: store.activePage?.background,
  }),
  (data) => console.log('Page updated', data)
);

Performance

change event can fire dozens of times per second during drag/resize. Avoid heavy work inside the handler - wrap it in throttle, or debounce.

// define function to save design to backend
const saveDesign = async () => {
  // export the design
  const json = store.toJSON();
  // save it to the backend
  await fetch('https://example.com/designs', {
    method: 'POST',
    body: JSON.stringify(json),
  });
}

// write a function for throttle saving
// it will call save no more then 1 time per second
let timeout = null;
const requestSave = () => {
  // if save is already requested - do nothing
  if (timeout) {
    return;
  }
  // schedule saving to the backend
  timeout = setTimeout(() => {
    // reset timeout
    timeout = null;
    saveDesign();
  }, 1000);
};

// request saving operation on any changes
store.on('change', requestSave);

On this page