Apply $set-style spec commands to update state immutably
A design tool keeps its document in immutable state, so the renderer can skip any layer whose reference did not change. Writing nested spreads for every edit is noisy, so the team describes each edit as a spec: an object shaped like the part of the state it changes, with a command at each place that changes.
Implement applySpec(state, spec). It returns the next state and never touches the current one.
applySpec(state, spec) // => next state
A spec is a plain object. If it has a key starting with $, it is a command and applies to the current value. Otherwise each key names a child of the current value (an object key, or an array index such as '2' or 2), and its value is the spec for that child.
{ $set: value }: replace the current value with value. The key does not need to exist yet.{ $apply: fn }: replace the current value with fn(current). current is undefined if the key is missing.{ $push: items }: the current value must be an array, and items an array. Append every element of items, in order.{ $merge: partial }: the current value and partial must be plain objects. Shallow-merge partial in: its keys overwrite or add keys.{ $unset: keys }: the current value must be a plain object, and keys an array of strings. Remove those keys.state, anything inside it, or any value in the spec. The state may be deeply frozen.Object.is), nothing is copied. This covers $set of the current value, $apply returning its input, $push of [], a $merge whose keys already hold those exact values, and an $unset of keys that do not exist. If the whole spec changes nothing, return state itself.TypeError when:
$push on something that is not an array, or $apply with something that is not a function);null, or a missing key).const state = {
title: 'Landing page',
layers: [
{ id: 'hero', visible: true, tags: ['top'] },
{ id: 'footer', visible: true, tags: [] },
],
view: { zoom: 1, grid: true },
};
const next = applySpec(state, {
title: { $set: 'Landing v2' },
layers: { 0: { visible: { $set: false }, tags: { $push: ['draft'] } } },
view: { $merge: { zoom: 2 } },
});
next.title; // => 'Landing v2'
next.layers[0]; // => { id: 'hero', visible: false, tags: ['top', 'draft'] }
next.layers[1] === state.layers[1]; // => true (untouched, shared)
next.view; // => { zoom: 2, grid: true }
state.layers[0].visible; // => true (state is unchanged)
applySpec(state, { view: { $apply: (view) => ({ ...view, zoom: view.zoom * 4 }) } }).view.zoom; // => 4
applySpec(state, { view: { $unset: ['grid'] } }).view; // => { zoom: 1 }
applySpec(state, { view: { zoom: { $set: 1 } } }) === state; // => true (nothing changed)
applySpec(state, { title: { $push: ['x'] } }); // throws TypeError
applySpec(state, { view: { $toggle: 'grid' } }); // throws TypeError
applySpec(state, { owner: { name: { $set: 'Ana' } } }); // throws TypeError (owner is missing)