Skip to content

Instantly share code, notes, and snippets.

@juliankrispel
Last active October 3, 2017 10:26
Show Gist options
  • Save juliankrispel/cabe533c20e47ec8b652b784490a3dbc to your computer and use it in GitHub Desktop.
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.
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
Copy link

mxstbr commented Oct 3, 2017

import createAutocompletePlugin, { Autocomplete } from 'draft-js-autocomplete-plugin';

const plugins = [
  createAutocompletePlugin({ /*...options...*/})
];

<Autocomplete>
  {style => (
    <div style={position}>
      {this.state.suggestions.map(suggestion => <div>{suggestion.name}</div>
    </div>
  )}
</Autocomplete>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment