ViewState API: personal block state
Personal state for a block that belongs to this browser, not to the document. The toggle keeps its open state here under the key 'open'. Inside a tool it is api.viewState.
Values are stored as JSON in localStorage, under the document's id. They are never saved in the document and never sent to collaborators. An entry not written for 90 days is removed.
Without localStorage, values live in memory for this tab only.
Reaching the editor instance
The methods below run on the editor you created with new Blok(). They are available once editor.isReady resolves.
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;
// Call any API method on it.
editor.caret.setToLastBlock('end');Methods
viewState.get(blockId, key)
unknownThis browser's value for a block under key, or undefined when none is set.
const open = editor.viewState.get(blockId, 'open') === true;viewState.set(blockId, key, value)
voidStores a value for a block in this browser. Use a value JSON can hold. It works in read-only mode and never enters the undo history.
editor.viewState.set(blockId, 'open', true);viewState.onChange(blockId, key, listener)
() => voidCalls listener with the new value when this tab or another tab of this browser sets it. The other tab must show the same document. Returns a function that unsubscribes.
const unsubscribe = editor.viewState.onChange(blockId, 'open', (value) => {
setOpen(value === true);
});
// Later
unsubscribe();viewState.isCreatedHere(blockId)
booleantrue for a block this tab created after the document rendered: from the toolbox, a shortcut, paste, convert or split. false for blocks from the saved document, another tab, a collaborator, or undo and redo. Use it to open a new block for the person who made it.
// In a block tool
constructor({ api, block }) {
this.api = api;
this.block = block;
}
rendered() {
const { viewState } = this.api;
const id = this.block.id;
if (viewState.get(id, 'open') === undefined && viewState.isCreatedHere(id)) {
viewState.set(id, 'open', true);
}
}