@marlinjai/block-editor-react
v0.2.0
Published
Generic parts of a block editor for React: a snapshot undo history, inspector field primitives and a sortable, keyboard-operable outline. No document model and no state library.
Maintainers
Readme
@marlinjai/block-editor-react
The generic parts of a block editor, for React: an undo history of document
snapshots, the property inspector's field primitives, and a sortable outline
that works by pointer and by keyboard. It knows no document model, no output
format and no state library. The email editor (@marlinjai/email-editor) is
built on it, and the Books template composer in framer-clone is the second
consumer.
pnpm add @marlinjai/block-editor-reactWhat is in it
| Part | Exports | Needs |
|---|---|---|
| Undo history | SnapshotHistory, also from @marlinjai/block-editor-react/history | nothing (no React) |
| History for a plain JSON document | useUndoableState (Immer recipes) | React |
| Inspector fields | TextField, ColorField, SelectField, AlignmentField, CheckboxField, SpacingField, RangeField, ButtonGroupField, normalizeSpacingValue | React |
| Sortable outline, from @marlinjai/block-editor-react/outline | SortableOutline, useOutlineSensors, outlineCollision, flattenOutline, planOutlineDrop, outlineEndRowId | React, dnd-kit |
No state library, so no MobX-State-Tree version is forced
The history stores whatever snapshots the host gives it. The email editor keeps
its document in MobX-State-Tree 6 and records getSnapshot(template) after
every change; a host on MobX-State-Tree 7, or one holding plain JSON in React
state, uses the same class. Nothing in this package imports mobx or
mobx-state-tree.
Peer dependencies
react, react-dom and the three @dnd-kit packages are peer dependencies,
all marked optional. The main entry needs React only; dnd-kit is needed only
by the /outline entry, and the /history entry imports none of them, so a
server-side consumer (the email editor's core, which the mail service imports)
never loads React, and npm does not install optional peers for it. (A
pnpm deploy of a workspace that holds this package as a workspace link does
copy them, about 8 MB in the mail service image, unused at run time.) A host using the fields needs React; a host using
the outline also needs @dnd-kit/core 6, @dnd-kit/sortable 8 and
@dnd-kit/utilities 3. They are peers rather than dependencies because dnd-kit
works through React context: a second copy next to the host's own would break
dragging between the two.
Undo history
import { SnapshotHistory } from '@marlinjai/block-editor-react/history';
const history = new SnapshotHistory(initialSnapshot, { limit: 100 });
store.onChange((snapshot) => history.record(snapshot));
const previous = history.undo(); // the snapshot to apply, or undefined
if (previous !== undefined) store.apply(previous);record(snapshot)adds a step and drops the redo future. After anundoorredo, the nextrecordof an equal snapshot is taken as the echo of what was just applied and ignored, so a store that reports every change (an undo included) never cuts off its own redo.markApplied(snapshot)replaces the remembered snapshot with the host's normalised reading of it.limit(default 100) keeps the newest snapshots.equals(default: equal JSON) decides what counts as the echo.coalesceMs(default 0, off) merges records with the samecoalesceKeyarriving within that many milliseconds into one step: typing in one field is then one undo step. The first edit after the initial snapshot is always its own step.reset(snapshot)starts over (a document was opened) and, like an undo, ignores the echo of that snapshot, so a store that reports the load adds no step;replaceCurrentchanges the current step without adding one;subscribeandrevisionnotify a view.
useUndoableState(initial, options) holds a plain JSON document in React with
the same history: update(draft => { ... }, { coalesceKey }) applies an Immer
recipe as one step (a recipe that changes nothing adds none), plus undo,
redo, canUndo, canRedo and reset. Keyboard shortcuts stay with the
host, which knows when a key press belongs to a text field.
Inspector fields
Controlled inputs with a visible label tied to the control, hint and error
lines linked by aria-describedby, and toggle groups that report their state
with aria-pressed. Every visible word can be replaced through props
(label, options, sideLabels, pickerLabel, clearLabel), so a German
interface needs no fork; option labels the host supplies are shown as given,
bare string options are capitalised. SpacingField normalises bare numbers to pixels by
default; pass normalize for another unit system.
Styling: Tailwind utility classes
The fields carry Tailwind utility classes (text-gray-600, border-gray-300,
focus:ring-blue-500, ...). A host's Tailwind has to scan this package's build
output, or those classes are not generated:
- Tailwind 3: add
node_modules/@marlinjai/block-editor-react/dist/**/*.{js,mjs}tocontent(the email editor resolves the path withrequire.resolve). - Tailwind 4:
@source "../node_modules/@marlinjai/block-editor-react/dist";in the stylesheet that imports Tailwind (the path relative to that file).
Besides the default palette, the classes use one theme colour the host
defines: accent (ColorField's swatch hover ring, hover:ring-accent/40).
Sortable outline
An outline is leaves and groups holding leaves, one level deep (the email
editor: sections and the wrappers that group them). SortableOutline draws it
as one flat list with a closing row after each group, so a drop just above the
closing row lands inside the group and a drop below it lands after the group.
Every drop is planned by planOutlineDrop, which the host can also call
itself, and reaches the host as an OutlineMove:
import { SortableOutline } from '@marlinjai/block-editor-react/outline';
<SortableOutline
entries={[{ id: 'a', type: 'leaf' }, { id: 'g', type: 'group', children: ['b'] }]}
collapsed={collapsedGroupIds}
label="Document structure"
onMove={(move) => {
if (move.kind === 'move-top') moveEntry(move.entryId, move.index);
else moveLeaf(move.leafId, move.groupId, move.index);
}}
renderRow={({ row, setNodeRef, style, dragHandleProps, isOver }) => (
<div ref={setNodeRef} style={style}>
{row.kind !== 'end' && <button {...dragHandleProps} aria-label={`Drag ${row.id}`}>⠿</button>}
{row.kind === 'end' ? (isOver ? 'Drop here' : null) : row.id}
</div>
)}
/>renderRow is called inside the outline's own row components. A host on
MobX reads its observables either in its own observer component that renders
SortableOutline, or inside an observer row component it returns from
renderRow (the email editor does both), never in the bare callback.
Keyboard: the drag handle takes focus; Space or Enter picks the row up, the
arrow keys move it, Space or Enter drops it and Escape cancels. dnd-kit
describes this to screen readers and announces each step. A test that drives
the keyboard has to let one macrotask pass after the pick-up (for example
await page.evaluate(() => new Promise((r) => setTimeout(r, 0))) in
Playwright): dnd-kit adds its keydown listener in a setTimeout, and an arrow
key sent before that timer has run is dropped. Groups move only at
the top level. A pointer drag starts after 5 pixels, so a click still selects.
Sensors: a host's own pointer rule
By default any pointer (mouse, pen or finger) and the keyboard can drag a row.
A host whose pointer drags must follow its own rule passes its sensors, made
with useOutlineSensors({ pointer }), where pointer is a dnd-kit
PointerSensor subclass. The email editor leaves a finger to scroll the list:
import { PointerSensor } from '@dnd-kit/core';
import { SortableOutline, useOutlineSensors } from '@marlinjai/block-editor-react/outline';
class PointerNotTouchSensor extends PointerSensor {
static activators = [
{
eventName: 'onPointerDown' as const,
handler: ({ nativeEvent }: { nativeEvent: PointerEvent }) => nativeEvent.pointerType !== 'touch' && nativeEvent.button === 0,
},
];
}
function Outline(props: OutlineProps) {
const sensors = useOutlineSensors({ pointer: PointerNotTouchSensor });
return <SortableOutline {...props} sensors={sensors} />;
}| API | What it does |
| --- | --- |
| useOutlineSensors(options?) | The outline's sensors: options.pointer (default dnd-kit's PointerSensor) with the 5 pixel start, and the keyboard sensor with the outline's own coordinates. A hook: call it in a component. |
| SortableOutline sensors prop | The sensors to drag with. Without it the outline uses useOutlineSensors(). |
Since 0.2.0; an older release ignores the sensors prop.
License
MIT
