diff --git a/components/SelectionEditor.js b/components/SelectionEditor.js index 51a8a72..8cbb8eb 100644 --- a/components/SelectionEditor.js +++ b/components/SelectionEditor.js @@ -19,23 +19,49 @@ function ModifierButton(props) { ) } +function reducer(state, action) { + switch (action.type) { + case 'BOLD': { + return { + ...state, + bold: !state.bold + } + } + case 'ITALICS': { + return { + ...state, + italics: !state.italics + } + } + case 'UNDERLINE': { + return { + ...state, + underline: !state.underline + } + } + case 'COLOR': { + return { + ...state, + color: action.color + } + } + } + throw new Error('Invalid action') +} + function SelectionEditor({ position, onChange }) { const [open, setOpen] = React.useState(false) - const [bold, setBold] = React.useState(false) - const [italics, setItalics] = React.useState(false) - const [underline, setUnderline] = React.useState(false) - - const [color, setColor] = React.useState(null) + const [state, dispatch] = React.useReducer(reducer, { + bold: false, + italics: false, + underline: false, + color: null + }) React.useEffect(() => { - onChange({ - bold, - italics, - underline, - color - }) - }, [onChange, bold, color, italics, underline]) + onChange(state) + }, [onChange, state]) return (
- setBold(v => !v)}> + dispatch({ type: 'BOLD' })}> B - setItalics(v => !v)}> + dispatch({ type: 'ITALICS' })}> I - setUnderline(v => !v)}> + dispatch({ type: 'UNDERLINE' })} + > U