I have Slate editor input and Split&Add
button on react typescript.
I want the input to be split into two separate inputs from the point cursor stands. For example, if I have
"I want to split this text into two parts. Here is the first part (assume here the cursor). And here the second part." Whenever I click Split&Add
button, There should be three separate slate editor inputs:
- Input with "I want to split this text into two parts. Here is the first part" value
- Empty input with cursor
- Input with "And here the second part." value.
I was assuming I can do it by selecting cursor place, and getting/setting its value to a new variable (so that I will set it to the third new input). And deleting the value after cursor point.
My code, now, looks something like this
const [isSplit, setIsSplit] = useState(false);
// function for the button
const onSplitEditor = (): void => {
setIsSplit(true);
const { selection } = editor;
if (selection) {
// Get the point after the cursor
const pointAfterCursor = Editor.after(editor, selection.focus);
// Set the value after the cursor to a variable
if (pointAfterCursor !== undefined) {
const valueAfterCursor = Editor.string(editor, {
anchor: {
path: pointAfterCursor.path,
offset: pointAfterCursor.offset - 1,
},
focus: Editor.end(editor, []),
});
if (valueAfterCursor) {
// Delete the content after the cursor
Transforms.delete(editor, {
at: selection,
distance: 1,
unit: 'line',
});
}
// eslint-disable-next-line no-debugger
// debugger;
console.log('valueAfterCursor =>', valueAfterCursor);
}
}
};
// split and add editor input once add button is clicked
useEffect(() => {
if (isSplit) {
setIsSplit(false);
}
}, []);
return (
<>
<Slate
editor={editor}
initialValue={value}
onChange={(value: Descendant[]): void => setValue(value)}
>
<Editable
placeholder="Optional text"
renderElement={renderElement}
className="editor__input"
onKeyDown={(e): void => onKeyDown(e, editor)}
onFocus={(): void => setIsFocused(true)}
onBlur={(): void => setIsFocused(false)}
/>
</Slate>
{isSplit && (
<Slate
editor={editor}
initialValue={valueAfterCursor}
onChange={(value: Descendant[]): void => setValue(value)}
>
<Editable
placeholder="Optional text"
renderElement={renderElement}
className="editor__input"
onKeyDown={(e): void => onKeyDown(e, editor)}
onFocus={(): void => setIsFocused(true)}
onBlur={(): void => setIsFocused(false)}
/>
</Slate>
)}
</>
)