4.9.2 • Published 2 years ago

@webscopeio/react-textarea-autocomplete v4.9.2

Weekly downloads
20,395
License
MIT
Repository
github
Last release
2 years ago

MIT License PRs Welcome All Contributors npm

This package provides React Component to achieve GitHub's like functionality in comments regarding the textarea autocomplete. It can be used for example for emoji autocomplete or for @mentions. The render function (for displaying text enhanced by this textarea) is beyond the scope of this package and it should be solved separately.

Browsers support

IE / EdgeFirefoxChromeSafariiOS SafariSamsungOpera
IE11, Edgelast 2 versionslast 2 versionslast 2 versionslast 2 versionslast 2 versionslast 2 versions

Installation

This module is distributed via npm and should be installed as one of your project's dependencies:

yarn add @webscopeio/react-textarea-autocomplete

or there is UMD build available. Check out this pen as example.

This package also depends on react and prop-types. Please make sure you have those installed as well.

Props

☝️ Note: Every other props than the mentioned below will be propagated to the textarea itself

PropsTypeDescription
trigger*Object: Trigger typeDefine triggers and their corresponding behavior
loadingComponent*React ComponentGets data props which is already fetched (and displayed) suggestion
innerRefFunction: (HTMLTextAreaElement) => void)Allows you to get React ref of the underlying textarea
scrollToItemboolean | (container: HTMLDivElement, item: HTMLDivElement) => void)Defaults to true. With default implementation it will scroll the dropdown every time when the item gets out of the view.
minCharNumberNumber of characters that user should type for trigger a suggestion. Defaults to 1.
onCaretPositionChangeFunction: (number) => voidListener called every time the textarea's caret position is changed. The listener is called with one attribute - caret position denoted by an integer number.
movePopupAsYouTypebooleanWhen it's true the textarea will move along with a caret as a user continues to type. Defaults to false.
boundariesElementstring | HTMLElementElement which should prevent autocomplete to overflow. Defaults to body.
textAreaComponentReact.Component | {component: React.Component, ref: string}What component use for as textarea. Default is textarea. (You can combine this with react-autosize-textarea for instance)
renderToBodybooleanWhen set to true the autocomplete will be rendered at the end of the <body>. Default is false.
onItemHighlighted({currentTrigger: string | null, item: string | Object | null}) => voidCallback get called everytime item is highlighted in the list
onItemSelected({currentTrigger: string, item: string | Object}) => voidCallback get called everytime item is selected
styleStyle ObjectStyle's of textarea
listStyleStyle ObjectStyles of list's wrapper
itemStyleStyle ObjectStyles of item's wrapper
loaderStyleStyle ObjectStyles of loader's wrapper
containerStyleStyle ObjectStyles of textarea's container
dropdownStyleStyle ObjectStyles of dropdown's wrapper
classNamestringClassNames of the textarea
containerClassNamestringClassNames of the textarea's container
listClassNamestringClassNames of list's wrapper
itemClassNamestringClassNames of item's wrapper
loaderClassNamestringClassNames of loader's wrapper
dropdownClassNamestringClassNames of dropdown's wrapper

*are mandatory

Methods

The methods below can be called on the React component's ref (see: React Docs)

MethodsDescription
getCaretPosition() : numberGets the current caret position in the textarea
setCaretPosition(position : number) : voidSets the caret position to the integer value passed as the argument
getSelectionPosition(): {selectionStart: number, selectionEnd: number}Returns selectionStart and selectionEnd of the textarea
getSelectedText(): ?stringReturns currently selected word

Example:

import React, { Component } from "react";
import ReactTextareaAutocomplete from "@webscopeio/react-textarea-autocomplete";

class App extends Component {
  onCaretPositionChange = (position) => {
    console.log(`Caret position is equal to ${position}`);
  }

  resetCaretPosition = () => {
    this.rta.setCaretPosition(0);
  }

  printCurrentCaretPosition = () => {
    const caretPosition = this.rta.getCaretPosition();
    console.log(`Caret position is equal to ${caretPosition}`);
  }

  render() {
    return (
      <div className="app">
        <div className="controls">
            <button onClick={this.resetCaretPosition}>Reset caret position</button>
            <button onClick={this.printCurrentCaretPosition}>Print current caret position to the console</button>
        </div>
        <ReactTextareaAutocomplete
          className="my-textarea"
          loadingComponent={() => <span>Loading</span>}
          trigger={{ ... }}
          ref={(rta) => { this.rta = rta; } }
          onCaretPositionChange={this.onCaretPositionChange}
        />
      </div>
    );
  }
}

export default App;

Trigger type

{
    [triggerChar: string]: {|
      output?: (
        item: Object | string,
        trigger?: string
      ) =>
        | {|
            key?: ?string,
            text: string,
            caretPosition: "start" | "end" | "next" | number
          |}
        | string | null,
      dataProvider: (
        token: string
      ) => Promise<Array<Object | string>> | Array<Object | string>,
      allowWhitespace?: boolean,
      afterWhitespace?: boolean,
      component: ReactClass<*>
    |},
}
  • dataProvider is called after each keystroke to get data what the suggestion list should display (array or promise resolving array)
  • component is the component for render the item in suggestion list. It has selected and entity props provided by React Textarea Autocomplete
  • allowWhitespace (Optional; defaults to false) Set this to true if you want to provide autocomplete for words (tokens) containing whitespace
  • afterWhitespace (Optional; defaults to false) Show autocomplete only if it's preceded by whitespace. Cannot be combined with allowWhitespace
  • output (Optional for string based item. If the item is an object this method is required) This function defines text which will be placed into textarea after the user makes a selection.

    You can also specify the behavior of caret if you return object {text: "item", caretPosition: "start"} the caret will be before the word once the user confirms his selection. Other possible value are "next", "end" and number, which is absolute number in contex of textarea (0 is equal position before the first char). Defaults to "next" which is space after the injected word.

    The default behavior for string based item is a string: <TRIGGER><ITEM><TRIGGER>). This method should always return a unique string, otherwise, you have to use object notation and specify your own key or return object from dataProvider with key property.

    In order to skip the text replace phase let's return null.

Example of usage

create-react-app example && cd example && yarn add @jukben/emoji-search @webscopeio/react-textarea-autocomplete

There is also UMD build available, check this CodePen for a proof.💪

App.js

import React, { Component } from "react";
import ReactTextareaAutocomplete from "@webscopeio/react-textarea-autocomplete";
import emoji from "@jukben/emoji-search";

import logo from "./logo.svg";
import "./App.css";
import "@webscopeio/react-textarea-autocomplete/style.css";

const Item = ({ entity: { name, char } }) => <div>{`${name}: ${char}`}</div>;
const Loading = ({ data }) => <div>Loading</div>;

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>

        <ReactTextareaAutocomplete
          className="my-textarea"
          loadingComponent={Loading}
          style={{
            fontSize: "18px",
            lineHeight: "20px",
            padding: 5
          }}
          ref={rta => {
            this.rta = rta;
          }}
          innerRef={textarea => {
            this.textarea = textarea;
          }}
          containerStyle={{
            marginTop: 20,
            width: 400,
            height: 100,
            margin: "20px auto"
          }}
          minChar={0}
          trigger={{
            ":": {
              dataProvider: token => {
                return emoji(token)
                  .slice(0, 10)
                  .map(({ name, char }) => ({ name, char }));
              },
              component: Item,
              output: (item, trigger) => item.char
            }
          }}
        />
      </div>
    );
  }
}

export default App;

Development

Run yarn to fetch dependencies.

Run yarn lint check ESlint check (yarn lint:fix for quick fix)

Run yarn flow for flow check

Run yarn test to run unit-tests powered by Jest

Dev playground (recommended)

Run yarn dev and open http://localhost:8080 for the playground

Run yarn cypress:open for open Cypress for E2E testing

Build and link

Run yarn build and yarn link then in your project folder (you have to use the same version of React e.g 15.6.1) yarn link react-textarea-autocomplete to link together.

Your PR's are welcomed! ❤️

Contributors

Maintainer
Jakub Beneš

Currently, I'm the only maintainer of this project. All related work I'm doing for is in my free time. If you like what I'm doing consider buy me a ☕. I'd appreciated! ❤️

ko-fi

Also, I'd love to thank these wonderful people for their contribution (emoji key). You rock! 💪

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT

4.9.2

2 years ago

4.9.0

2 years ago

4.9.1

2 years ago

4.8.1

3 years ago

4.8.0

3 years ago

4.7.3

3 years ago

4.7.2

4 years ago

4.7.1

4 years ago

4.7.0

4 years ago

4.6.3

4 years ago

4.6.2

4 years ago

4.6.1

5 years ago

4.6.0

5 years ago

4.5.0

5 years ago

4.4.0

5 years ago

4.3.5

5 years ago

4.3.4

5 years ago

4.3.3

5 years ago

4.3.2

5 years ago

4.3.1

5 years ago

4.3.0

5 years ago

4.2.4

5 years ago

4.2.3

5 years ago

4.2.2

5 years ago

4.2.1

5 years ago

4.2.0

5 years ago

4.1.0

5 years ago

4.0.0

5 years ago

3.1.5

5 years ago

3.1.4

5 years ago

3.1.3

5 years ago

3.1.2

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.3.5

6 years ago

2.3.4

6 years ago

2.3.3

6 years ago

2.3.2

6 years ago

2.3.1

6 years ago

2.3.0

6 years ago

2.2.3

6 years ago

2.2.2

6 years ago

2.2.1

6 years ago

2.2.0

6 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.5.3

6 years ago

1.5.2

6 years ago

1.5.1

6 years ago

1.5.0

6 years ago

1.4.2

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.3

6 years ago

1.3.2

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.4

7 years ago

1.1.3

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.0

7 years ago