Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function replaceValue(snapshot: null | JSONValue, editor: SlateEditor) {
// console.log('Replacing value')
if (snapshot) {
const fragment = blocksToEditorValue(snapshot, blockContentType)
// Store the old selection
const select = createSelectionOperation(editor)
editor.value.document.nodes.forEach(node => {
editor.applyOperation({
type: 'remove_node',
path: [0],
node: node
})
})
fragment.document.nodes.reverse().forEach(node => {
editor.applyOperation({
type: 'insert_node',
path: [0],
node: node
})
})
function normalizeBlock(block) {
return blocksToEditorValue(
editorValueToBlocks(
{
document: {
nodes: [block.toJSON(VALUE_TO_JSON_OPTS)]
}
},
blockContentType
),
blockContentType
).document.nodes[0]
}
return {
function insertPatch(patch: InsertPatch, editor: SlateEditor) {
const {items, position} = patch
const blocksToInsert = blocksToEditorValue(items, blockContentType)
const posKey = findLastKey(patch.path)
let index = editor.value.document.nodes.findIndex((node, indx) => {
return posKey ? node.key === posKey : indx === patch.path[0]
})
if (position === 'before') {
index = index > 0 ? index-- : index
}
if (position === 'after') {
index++
}
blocksToInsert.document.nodes.forEach(block => {
editor.applyOperation({
type: 'insert_node',
path: [index++],
node: block
})
function setPatch(patch: Patch, change: () => void, type: Type) {
if (Array.isArray(patch.value)) {
if (patch.path.length === 0) {
return replaceValue(patch.value, change, type)
}
throw new Error(`Invalid patch, looks like it should be an insert: ${JSON.stringify(patch)}`)
}
const editorBlock = blocksToEditorValue([patch.value], type).document.nodes[0]
const key = findLastKey(patch.path)
return change.replaceNodeByKey(key, editorBlock)
}
function insertPatch(patch: Patch, change: () => void, type: Type) {
const {items, position} = patch
const fragment = blocksToEditorValue(items, type)
const posKey = findLastKey(patch.path)
let path = change.value.document.nodes.findIndex(node => {
return node.key === posKey
})
if (position === 'before') {
path = path > 0 ? path-- : path
}
if (position === 'after') {
path++
}
const operations = fragment.document.nodes.map(block => {
return Operation.create({
type: 'insert_node',
path: [path],
node: block
})
function replaceValue(snapshot: ?(Blocks[]), change: () => void, type: Type) {
if (snapshot) {
const fragment = blocksToEditorValue(snapshot, type)
if (change.value.document.nodes.size) {
change.selectAll().delete()
}
change.applyOperations(
fragment.document.nodes.reverse().map(node => {
return {
type: 'insert_node',
path: [0],
node: node
}
})
)
return change
}
throw new Error('No snapshot given!')
}