What is the best approach for adding a checklist block to Draft?
I want to extend Draft to accept a checklist/todo block. The block will have a checkbox at the left edge and can be toggled on/off to represent a complete/pending state respectively. The checkbox cannot be moved around the editor (you can’t copy/paste it into the middle of a text block).
I feel like there are a few approaches I can take, so I was wondering if I could get an opinion.
- Create a custom block type by extending
DraftEditorBlock. I would need to overriderender()and tuck the checkbox into the component before the children are rendered.- One issue with this approach is that Draft does not publicly expose this component. Not a dealbreaker, but I’m assuming there was some thought behind excluding
DraftEditorBlock.
- One issue with this approach is that Draft does not publicly expose this component. Not a dealbreaker, but I’m assuming there was some thought behind excluding
- Wrap the internal block text in an
Entitythat injects the checkbox.- I tried out this approach using the link example. One side-effect is that you can’t delete all text within the block and have the Entity remain. These concerns were raised in #129, e.g. using a zero-width character.
- A better alternative?
Thanks again for continuously improving Draft.
Can you create a custom block component that includes your checkbox and composes a DraftEditorBlock? (We should never ever extend React components.)
You can pass along props that track the state of the checkbox.
class MyCheckboxEditor extends React.Component {
constructor(props) {
this._blockRenderer = (block) => {
if (block.getType() === 'checkable') {
return {
component: CheckableBlock,
props: {
checkedState: this.state.checkedState[block.getKey()],
onCheckedChange: (...) => /* update value in `checkedState` */
},
};
}
}
}
// etc.
}
Thanks for the quick reply. Let me take a shot at your suggestion and I will get back to you.
@hellendag Can you create a custom block component that includes your checkbox and composes a DraftEditorBlock?
I noticed that DraftEditorBlock requires props to be passed in. As a result, I ended up with:
this._blockRenderer = (block) => {
const type = block.getType()
if (type !== 'taskPending' && type !== 'taskComplete') {
return // render the default DraftEditorBlock
}
return {
component: CheckableBlock,
props: {
checked: type === 'taskComplete',
...getDraftEditorBlockProps(this.state.editorState, block),
},
}
}
where getDraftEditorBlockProps() derives the required props.
My component looks like
export default class CheckableBlock extends React.Component {
static propTypes = {
blockProps: PropTypes.object.isRequired,
}
render() {
const {checked} = this.props.blockProps
return (
<div>
<input type="checkbox" checked={checked} />
<DraftEditorBlock {...this.props.blockProps}/>
</div>
)
}
}
This renders as expected and the text contents of the block are editable! Nice. However, using the keyboard to move the insertion cursor over to the input results in an error:
Uncaught Invariant Violation: Unknown node in selection range.
This makes sense. I don’t expect Draft to understand how to handle insertion outside of the DraftEditorBlock. Is there a way to tell Draft “just ignore the <input>” (while still allowing it to be toggled with a mouse/keyboard)?
(I don’t have my heart set on <input type="checkbox">, but I assume I will need a proper React element of some kind to handle events, e.g. toggle the state on/off.)
I don’t believe generated content (:before, :after) or list-image-style will offer me the control to toggle the state.
Any suggestions would be much appreciated.
where getDraftEditorBlockProps() derives the required props.
The same props should be passed to your block component as to DraftEditorBlock: CustomComponent and DraftEditorBlock.
So I believe you should have access to all the necessary props, and can propagate them through to your DraftEditorBlock using {...this.props}.
Uncaught Invariant Violation: Unknown node in selection range. ... Is there a way to tell Draft “just ignore the ” (while still allowing it to be toggle with a mouse/keyboard)?
Ah, I should have realized that might cause trouble. Does it work if you make the <input> contentEditable={false}?
So I believe you should have access to all the necessary props, and can propagate them through to your
DraftEditorBlockusing{...this.props}.
Sweet!
Does it work if you make the
<input> contentEditable={false}?
Unfortunately not. It exhibits the same error when I change the <input> to a <span contentEditable="false">
Did you should set data-offset-key={this.props.offsetKey} on your root div? This is how our selection logic figures out where it is within the editor. (Not that you would have known to do that, since I probably didn't document it well. :))
Thanks for the help. data-offset-key worked!
Alright…making some progress. No more Uncaught Invariant Violations.
Is it possible to special case the selection to “skip” the inline <input> altogether? It would be ideal if the insertion cursor left the current custom block text and landed at the end of the previous block when pressing ←.
Awesome!
Is it possible to special case the selection to “skip” the inline altogether?
Not exactly. It's one of the drawbacks of depending on the browser for selection behavior -- it sometimes puts the cursor in awkward places, especially around contentEditable={false} elements.
What does your current SelectionState look like when the cursor is before/after the <input>?
It is consistent when moving the cursor before/after the <input>:
anchorKey: "erh0g"
anchorOffset: 0
focusKey: "erh0g"
focusOffset: 0
hasFocus: false
isBackward: false
(I pulled these values from the React Dev Tools.)
If I apply certain styles to the <input>, (e.g. position: absolute, float: left) selection behavior changes a little. Going “forward” → moves the selection from the end of the current block to the beginning of the next block. Going “backward” ← from the first character of the current block moves the cursor around the input before placing it at the end previous block.
I haven’t dug through the code enough, but it seems Draft knows how to solve the “forward” case (because it can put the cursor at offset: 0 of the next block). It’s the “backward” case where Draft “loses track” of the selection.
Would a ← handler do the job? For instance, you could use a key binding function that maps the key to a command, then in handleKeyCommand, logic for that command that:
- Checks for the current
SelectionState, and whether it is collapsed - If so, checks whether it is within a "checkable"-type block, and at offset
0 - If so:
- If there is a previous block, use
EditorState.forceSelectionto throw the cursor up to the end of it - If not, kill everything and don't allow an
onChange
- If there is a previous block, use
We could also expose leftArrow and rightArrow as first-class keydown handler citizens, too.
You could probably still end up in a weird cursor state at times, but that could help.
We could also expose leftArrow and rightArrow as first-class keydown handler citizens, too.
I think custom key bindings and handleKeyCommand will get me to a workable solution. But exposing onLeftArrow could be a nice API enhancement for the future. :space_invader:
Would a ← handler do the job?
Yes, I think so. However, I’m confused about the interplay between the method assigned to the keyBindingFn prop and handleKeyCommand.
If I pass a ← command to handleKeyCommand and the left keypress is not inside a checkable block, then I will have lost the chance to call getDefaultKeyBinding appropriately (handleKeyCommand doesn’t have access to event, right?)
Currently I have:
// some pseudocode for brevity
myKeyBinder = (event) => {
// if key isnt ArrowLeft return getDefaultKeyBinding(event)
// if selection isnt collapsed return getDefaultKeyBinding(event)
// if focus offset isnt 0 return getDefaultKeyBinding(event)
// if block type isnt checkable return getDefaultKeyBinding(event)
// if prev block doesn’t exist return getDefaultKeyBinding(event)
const prevBlock = contentState.getBlockBefore(startKey)
const prevLength = prevBlock.getLength()
const nextSelection = new SelectionState({
anchorKey: prevKey,
anchorOffset: prevLength,
focusKey: prevKey,
focusOffset: prevLength,
isBackward: false,
hasFocus: false,
})
// move to end of previous block
const selectionState = EditorState.forceSelection(editorState, nextSelection)
const nextState = EditorState.push(selectionState, contentState, 'move-selection-to-end-of-block')
this.handleChange(nextState)
return event.key
}
FWIW, this solves my needs, but I imaging I may be missing something.
http://facebook.github.io/draft-js/docs/advanced-topics-key-bindings.html#customization
Your key binding function should fall through to return getDefaultKeyBinding(event);. :)
Your key binding function should fall through to return getDefaultKeyBinding(event);. :)
It does. :wink: That is all the pseudocode at the top. I return getDefaultKeyBinding(event) for each non-relevant condition before I generate a new EditorState. My code seems similar to the example you referenced:
function myKeyBindingFn(e: SyntheticKeyboardEvent): string {
if (e.keyCode === 83 /* `S` key */ && hasCommandModifier(e)) {
return 'myeditor-save';
}
return getDefaultKeyBinding(e);
}
However, if I don’t respect the default key binding for ← I would have to manually move the selection one character left each time inside handleKeyCommand, right?
Oh ha, I just totally ignored that since it was commented out! My fault. :)
I think I see what the issue is here. There are actually two things you need to implement.
- Your key binding function, which should return a string like
'move-selection-up'in your left-arrow case. - A
handleKeyCommandfunction, which receives the command string and consumes it accordingly.
Both should be provided as props to Editor.
class MyEditor extends React.Component {
constructor(props) {
...
this.handleKeyCommand = (command) => {
if (command === 'move-selection-left') {
// do stuff to this.state.editorState, call this.setState(), return true
}
return false;
}
}
render() {
return (
<Editor
handleKeyCommand={this.handleKeyCommand}
keyBindingFn={myKeyBindingFn}
...
/>
);
}
}
function myKeyBinding(event) {
if (/* left key and other stuff */) {
return 'move-selection-left';
}
return getDefaultKeyBinding(event);
}
So you're defining a command, then separately consuming and handling that command. Does that make sense?
Yes. I think my hangup is that I have to duplicate much of the EditorState/ContentState/SelectionState introspection in both methods. However, my issue has been solved and that is the important part.
I just wanted to throw out a huge THANK YOU for taking the time to respond thoroughly (and thoughtfully) to all of my questions and comments. Your help was immensely valuable. :gem:
I think my hangup is that I have to duplicate much of the EditorState/ContentState/SelectionState introspection in both methods.
Ah, true. That's kind of annoying. Are there any top-level API methods that you think might help streamline this? I'm going to go ahead and close this issue for queue maintenance, but we can continue discussing on the thread.
I just wanted to throw out a huge THANK YOU for taking the time to respond thoroughly (and thoughtfully) to all of my questions and comments. Your help was immensely valuable. :gem:
You're welcome! :)
Are there any top-level API methods that you think might help streamline this?
Hmm. Good question. Off the top of my head:
EditorState::getBlockAtSelectionStart()::getBlockAtSelectionEnd()::getBlockBeforeSelectionStart()::getBlockAfterSelectionEnd()
That would save me a small amount of code here and there, but it might not be worth the API bloat.
I’ll keep my eyes open for common patterns as I continue to build with Draft.
These would generally be wrappers like this, right?:
static function getBlockBeforeSelectionStart(editorState) {
const selection = editorState.getSelection();
const content = editorState.getCurrentContent();
return content.getBlockMap().getBlockForKey(selection.getStartKey());
}
Plucking information off an EditorState can be a little boilerplate-y and tedious, I know. :)
It might be useful to have a bag of shortcut utilities like these, perhaps not on EditorState itself, but either available within the Draft repo or in a utility repo.
Yes, these would probably be better suited as a set of utility functions, similar to RichUtils. Thanks for following up.