editor.js/src/components/store/blocksReducer.ts
Ilya Moroz e6db8d5140
[Feature] Add state manager (#2018)
* add state manager with demo file

* remove initial state

* move Store type to Store.ts

* add new actions

* change store schema

* add docs

* type -> interface, add deepCopy function

* move types to the /types/ folder

* rename types files, change state type (add blocks: key)

* fix createStore.ts func

* add documentation for reducer

* use BlockMutationType instead of ActionType

* add doc

* deep copy of initial state

* add doc for createStore

* Apply suggestions from code review

Co-authored-by: Peter Savchenko <specc.dev@gmail.com>

* rename `reducer` to `blocksReducer`

* add a listener type, pass changed state to the listener

Co-authored-by: Peter Savchenko <specc.dev@gmail.com>
2022-05-05 14:26:04 +03:00

30 lines
967 B
TypeScript

import { EditorState } from '../../../types/store/editorState';
import { Action } from '../../../types/store/action';
import * as _ from '../utils';
import { BlockMutationType } from '../../../types/events/block/mutation-type';
/**
* The reducer function for Editor.js state
* This function applies the passed action to the current state and returns the new state
* This reducer is especially for working with blocks data
*
* @param state - previous state to apply action
* @param action - information about the action in the previous state
*/
export default function blocksReducer(state: EditorState, action: Action): EditorState {
const stateCopy = _.deepCopy(state);
switch (action.type) {
case BlockMutationType.Added:
case BlockMutationType.Changed:
stateCopy.blocks[action.data.id] = action.data;
break;
case BlockMutationType.Removed:
delete stateCopy.blocks[action.blockId];
break;
}
return stateCopy;
}