0.0.9 • Published 5 years ago

slate-autocomplete v0.0.9

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

A Slate plugin to suggestion replacements or actions based on input. Useful for implementing autocomplete suggestions by node type.


Install

With npm:

npm install --save slate-autocomplete

With yarn:

yarn add slate-autocomplete

You will need to have installed slate as a dependency already.


Usage

Define your custom plugin:

With static suggestions:

import autoCompletePlugin from 'slate-autocomplete'

const suggestions = [
  "Afganistán",
  "Albania",
  "Argentina",
  ...
]

export default autoCompletePlugin({
  suggestions,
  resultSize: 5,
  totalText: true,
  shouldHandleNode: (editor, currentNode) => true,
  onEnter: (suggestion, editor) => {
    replaceCurrentText(editor, suggestion)
  }
})

With dynamic suggestions:

import autoCompletePlugin from 'slate-autocomplete'

export default autoCompletePlugin({
  renderPortal: (Portal, props) => (
    <YourDynamicComp>
      {names => (<Portal {...props} suggestions={names} />)}
    </YourDynamicComp>
  ),
  shouldHandleNode: (editor, currentNode) => true,
  totalText: false,
  onEnter: (suggestion, editor) => {
    replaceCurrentText(editor, suggestion)
  }
})

In this case, you need define renderPortal instead of suggestions.

import customPlugin from 'your_plugin_path'
import { Editor } from 'slate-react'

const Example = ({ value, onChange, renderNode }) => (
  <React.Fragment>
    <Editor
      value={value}
      plugins={[customPlugin]}
      onChange={onChange}
      renderNode={renderNode}
    />
    {plugins.filter(({ component }) => !!component).map(({ component: Comp }, index) => <Comp key={index} />)}
  </React.Fragment>
)
OptionTypeOptionalDescription
suggestionsArrayYesAn array of suggestions.
totalTextBooleanYesA boolean used to kwow if the suggestions should be applied to complete node text or only to the current word.
resultSizeNumberYesAn optional number use to set size of suggestion result.
renderPortalFunctionYesA function use to wrap the portal component with dynamics suggestions.
onEnterFunctionNoA function use to handle return/enter keypress to append suggestion into editor.
shouldHandleNodeFunctionNoA function use to know if the current slate node should be handled.

Development

Clone the repository and then run:

yarn
yarn storybook

You should see something like:

Collaboration

If you have some idea/suggestion or you found an error, please, let me know sending me an email: federico.lochbaum@gmail.com or creating a new issue.