dendriform-immer-patch-optimiser
Dendriform uses Immer. Immer is wonderful, especially its ability to produce patches for implementing concurrent editing and undo & redo functionality.
But Dendriform needs to track how array elements are moved around. Luckily the RFC6902 JSON patch standard that Immer's patches are similar to describes "move" operations. Immer does not produce "move" patches, so this plugin post-processes Immer patches to infer array element movement and produce "move" patches.
When using Immer alone, certain types of changes can lead to a large number of patches because Immer's design optimises for good performance at generation time. A nice side effect of this library is that describing movements naturally reduces the number of patches.
Please note that while this library does some immer patch optimisations that could be used in any project, the main goal of this library is to solve problems for Dendriform. As such, it's API may be a little volatile, and it won't necessarily aim to please the use cases of the general public. You are welcome to use the library as is, copy the source code for your own uses, or even republish the code as a new library if you'd like to take on the responsibility of maintaining a more public-serving variant of it.
Current limitations
- Is not yet guaranteed to work with arrays containing multiple identical (strictly-equal) elements
Examples
Array optimisation
import {produceWithPatches} from 'immer';
import {optimise} from 'dendriform-immer-patch-optimiser';
const base = {foo: ['a','b','c']};
const [result, recordedPatches] = produceWithPatches(base, draft => {
draft.foo.unshift('d');
});
const optimisedPatches = optimise(base, recordedPatches);
Move patches
import {produceWithPatches} from 'immer';
import {optimise, applyPatches} from 'dendriform-immer-patch-optimiser';
const base = {foo: ['a','b','c']};
const [result, recordedPatches] = produceWithPatches(base, draft => {
draft.foo.shift();
});
const optimisedPatches = optimise(base, recordedPatches);
const result2 = applyPatches(base, optimisedPatches);
Adding, moving and removing at once
import {produceWithPatches} from 'immer';
import {optimise, applyPatches} from 'dendriform-immer-patch-optimiser';
const base = ['a','b','X','Y','c','d','e','Z'];
const [result, recordedPatches] = produceWithPatches(base, draft => {
draft.splice(2,2);
draft.pop();
draft.reverse();
draft.push('C');
draft.splice(3, 0, 'B');
draft.unshift('A');
});
const optimisedPatches = optimise(base, recordedPatches);
const result2 = applyPatches(base, optimisedPatches);