Skip to content

Instantly share code, notes, and snippets.

@pmrt
Last active March 10, 2019 21:48
Show Gist options
  • Save pmrt/47466d3435f54dcd5f114620b01d2f73 to your computer and use it in GitHub Desktop.
Save pmrt/47466d3435f54dcd5f114620b01d2f73 to your computer and use it in GitHub Desktop.
find surrounding block ranges
function areSameBlock(a, b) {
a.getType() === b.getType()
}
function findBlockRange(contentState, areEqualFn, startBlock) {
const after = block => contentState.getBlockAfter(block.getKey())
const before = block => contentState.getBlockBefore(block.getKey())
const find = (block, nextBlock, directionFn) => {
if (!nextBlock || !areEqualFn(block, nextBlock)) {
return block
}
return find(nextBlock, directionFn(nextBlock), directionFn)
}
return [
find(startBlock, before(startBlock), before),
find(startBlock, after(startBlock), after)
]
}
// Usage
findBlockRange(contentState, areSameBlock, getCurrentBlock(editorState))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment