Skip to content

Commit

Permalink
[form-builder] Block editor: improve block action patch functions (#1138
Browse files Browse the repository at this point in the history
)
  • Loading branch information
skogsmaskin committed Dec 21, 2018
1 parent 8db17b0 commit 30364b7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ export default class BlockExtrasOverlay extends React.Component<Props, State> {
element={element}
block={block}
value={value}
path={[{_key: block._key}]}
set={createBlockActionPatchFn('set', block, onPatch)}
unset={createBlockActionPatchFn('unset', block, onPatch)}
insert={createBlockActionPatchFn('insert', block, onPatch)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,24 @@

import type {FormBuilderValue, Block} from '../typeDefs'
import PatchEvent, {insert, unset, set} from '../../../../PatchEvent'
import {randomKey, normalizeBlock} from '@sanity/block-tools'
import {normalizeBlock} from '@sanity/block-tools'

export default function createBlockActionPatchFn(
type: string,
block: FormBuilderValue,
onPatch: PatchEvent => void
) {
let toInsert
return (givenBlock: Block) => {
switch (type) {
case 'set':
return onPatch(PatchEvent.from(set(givenBlock, [{_key: block._key}])))
return onPatch(PatchEvent.from(set(normalizeBlock(givenBlock), [{_key: block._key}])))
case 'unset':
return onPatch(PatchEvent.from(unset([{_key: block._key}])))
case 'insert':
// Make sure the given block key's are unique and normalized
givenBlock._key = randomKey(12)
if (givenBlock._type === 'block') {
normalizeBlock(givenBlock)
}
return onPatch(PatchEvent.from(insert([givenBlock], 'after', [{_key: block._key}])))
toInsert = Array.isArray(givenBlock) ? givenBlock : [givenBlock]
toInsert = toInsert.map(blk => normalizeBlock(blk))
return onPatch(PatchEvent.from(insert(toInsert, 'after', [{_key: block._key}])))
default:
throw new Error(`Patch type ${type} not supported`)
}
Expand Down

0 comments on commit 30364b7

Please sign in to comment.