Last active
October 3, 2017 10:26
-
-
Save juliankrispel/cabe533c20e47ec8b652b784490a3dbc to your computer and use it in GitHub Desktop.
Pseudo-code Example for a mention plugin implementation with a new draft js plugins api.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { EditorState } from 'draft-js-plugins'; | |
import Editor from 'djsp.editor'; | |
import autocompletePlugin from 'djsp.autocomplete'; | |
import selectionPositionPlugin from 'djsp.selection-position'; | |
import entityDecoratorPlugin from 'djsp.entity-decorator'; | |
import Popover from 'djsp.popover'; | |
import ListBox from 'djsp.listbox'; | |
import addEntity from 'djsp.add-entity'; | |
const ListItem = ({ item }) => ( | |
<div className="my-list-item"> | |
{item.firstName} {item.lastName} | |
</div> | |
); | |
const MentionEntity = ({ entity, children }) => (<span className="mention-entity"> | |
@{children} | |
</span>); | |
// Example of Mentions plugin | |
const entityType = { | |
name: 'MENTION', | |
mutability: 'IMMUTABLE', | |
} | |
const plugins = [ | |
autoCompletePlugin({ trigger: '@', type: entityType }), // trigger could be char, regex or function that returns a string as a match | |
selectionPositionPlugin(), | |
entityDecoratorPlugin({ | |
type: entityType, | |
component: MentionEntity | |
}) | |
]; | |
class MyApp extends Component { | |
state = { | |
editorState: EditorState.createEmpty(), | |
selectionPosition: false, | |
suggestions: [], | |
}; | |
onChange = editorState => this.setState({ editorState }); | |
onAutocomplete = string => http.get('/my-endpoint').then(suggestions => this.setState({ suggestions })) | |
addEntity = entity => this.onChange(addEntity( | |
this.state.editorState, | |
{ | |
...entityType, | |
data: entity, | |
} | |
)); | |
changeSelectionPosition = selectionPosition => this.setState({ selectionPosition }); | |
render() { | |
return (<div> | |
<Editor | |
onAutocomplete={this.onAutocomplete} | |
onSelectionPositionChange={this.changeSelectionPosition} | |
onChange={this.onChange} | |
plugins={plugins} | |
/> | |
<Popover | |
selectionPosition={this.state.selectionPosition} | |
> | |
<ListBox | |
list={this.state.suggestions} | |
onChange={this.addEntity} | |
listComponent={ListItem} | |
/> | |
</Popover> | |
</div>); | |
} | |
}; |
mxstbr
commented
Oct 3, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment