Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support replaceWithoutPrefix #74

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 64 additions & 34 deletions src/Mentions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,28 @@ import classNames from 'classnames';
import toArray from 'rc-util/lib/Children/toArray';
import KeyCode from 'rc-util/lib/KeyCode';
import * as React from 'react';
import TextArea, { TextAreaProps } from 'rc-textarea';
import type { TextAreaProps } from 'rc-textarea';
import TextArea from 'rc-textarea';
import KeywordTrigger from './KeywordTrigger';
import { MentionsContextProvider } from './MentionsContext';
import Option, { OptionProps } from './Option';
import type { OptionProps } from './Option';
import Option from './Option';
import type {
Omit} from './util';
import {
filterOption as defaultFilterOption,
getBeforeSelectionText,
getLastMeasureIndex,
omit,
Omit,
replaceWithMeasure,
setInputSelection,
validateSearch as defaultValidateSearch,
} from './util';

type BaseTextareaAttrs = Omit<TextAreaProps, 'prefix' | 'onChange' | 'onSelect'>;
type BaseTextareaAttrs = Omit<
TextAreaProps,
'prefix' | 'onChange' | 'onSelect'
>;

export type Placement = 'top' | 'bottom';
export type Direction = 'ltr' | 'rtl';
Expand All @@ -36,6 +42,7 @@ export interface MentionsProps extends BaseTextareaAttrs {
prefixCls?: string;
value?: string;
filterOption?: false | typeof defaultFilterOption;
replaceWithoutPrefix?: boolean;
validateSearch?: typeof defaultValidateSearch;
onChange?: (text: string) => void;
onSelect?: (option: OptionProps, prefix: string) => void;
Expand Down Expand Up @@ -72,7 +79,10 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
rows: 1,
};

public static getDerivedStateFromProps(props: MentionsProps, prevState: MentionsState) {
public static getDerivedStateFromProps(
props: MentionsProps,
prevState: MentionsState,
) {
const newState: Partial<MentionsState> = {};

if ('value' in props && props.value !== prevState.value) {
Expand Down Expand Up @@ -115,12 +125,14 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
}
};

public onChange: React.ChangeEventHandler<HTMLTextAreaElement> = ({ target: { value } }) => {
public onChange: React.ChangeEventHandler<HTMLTextAreaElement> = ({
target: { value },
}) => {
this.triggerChange(value);
};

// Check if hit the measure keyword
public onKeyDown: React.KeyboardEventHandler<HTMLTextAreaElement> = (event) => {
public onKeyDown: React.KeyboardEventHandler<HTMLTextAreaElement> = event => {
const { which } = event;
const { activeIndex, measuring } = this.state;
const { onKeyDown: clientOnKeyDown } = this.props;
Expand Down Expand Up @@ -170,29 +182,37 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
* 2. Contains `space`
* 3. ESC or select one
*/
public onKeyUp: React.KeyboardEventHandler<HTMLTextAreaElement> = (event) => {
public onKeyUp: React.KeyboardEventHandler<HTMLTextAreaElement> = event => {
const { key, which } = event;
const { measureText: prevMeasureText, measuring } = this.state;
const { prefix = '', onKeyUp: clientOnKeyUp, onSearch, validateSearch } = this.props;
const {
prefix = '',
onKeyUp: clientOnKeyUp,
onSearch,
validateSearch,
} = this.props;
const target = event.target as HTMLTextAreaElement;
const selectionStartText = getBeforeSelectionText(target);
const { location: measureIndex, prefix: measurePrefix } = getLastMeasureIndex(
selectionStartText,
prefix,
);
const { location: measureIndex, prefix: measurePrefix } =
getLastMeasureIndex(selectionStartText, prefix);

// If the client implements an onKeyUp handler, call it
if (clientOnKeyUp) {
clientOnKeyUp(event);
}

// Skip if match the white key list
if ([KeyCode.ESC, KeyCode.UP, KeyCode.DOWN, KeyCode.ENTER].indexOf(which) !== -1) {
if (
[KeyCode.ESC, KeyCode.UP, KeyCode.DOWN, KeyCode.ENTER].indexOf(which) !==
-1
) {
return;
}

if (measureIndex !== -1) {
const measureText = selectionStartText.slice(measureIndex + measurePrefix.length);
const measureText = selectionStartText.slice(
measureIndex + measurePrefix.length,
);
const validateMeasure: boolean = validateSearch(measureText, this.props);
const matchOption = !!this.getOptions(measureText).length;

Expand Down Expand Up @@ -222,19 +242,20 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
}
};

public onPressEnter: React.KeyboardEventHandler<HTMLTextAreaElement> = (event) => {
const { measuring } = this.state;
const { onPressEnter } = this.props;
if (!measuring && onPressEnter) {
onPressEnter(event);
}
};
public onPressEnter: React.KeyboardEventHandler<HTMLTextAreaElement> =
event => {
const { measuring } = this.state;
const { onPressEnter } = this.props;
if (!measuring && onPressEnter) {
onPressEnter(event);
}
};

public onInputFocus: React.FocusEventHandler<HTMLTextAreaElement> = (event) => {
public onInputFocus: React.FocusEventHandler<HTMLTextAreaElement> = event => {
this.onFocus(event);
};

public onInputBlur: React.FocusEventHandler<HTMLTextAreaElement> = (event) => {
public onInputBlur: React.FocusEventHandler<HTMLTextAreaElement> = event => {
this.onBlur(event);
};

Expand Down Expand Up @@ -269,16 +290,20 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {

public selectOption = (option: OptionProps) => {
const { value, measureLocation, measurePrefix } = this.state;
const { split, onSelect } = this.props;
const { split, onSelect, replaceWithoutPrefix } = this.props;

const { value: mentionValue = '' } = option;
const { text, selectionLocation } = replaceWithMeasure(value, {
measureLocation,
targetText: mentionValue,
prefix: measurePrefix,
selectionStart: this.textarea.selectionStart,
split,
});
const { text, selectionLocation } = replaceWithMeasure(
value,
{
measureLocation,
targetText: mentionValue,
prefix: measurePrefix,
selectionStart: this.textarea.selectionStart,
split,
},
replaceWithoutPrefix,
);
this.triggerChange(text);
this.stopMeasure(() => {
// We need restore the selection position
Expand Down Expand Up @@ -322,7 +347,11 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
return list;
};

public startMeasure(measureText: string, measurePrefix: string, measureLocation: number) {
public startMeasure(
measureText: string,
measurePrefix: string,
measureLocation: number,
) {
this.setState({
measuring: true,
measureText,
Expand Down Expand Up @@ -352,7 +381,8 @@ class Mentions extends React.Component<MentionsProps, MentionsState> {
}

public render() {
const { value, measureLocation, measurePrefix, measuring, activeIndex } = this.state;
const { value, measureLocation, measurePrefix, measuring, activeIndex } =
this.state;
const {
prefixCls,
placement,
Expand Down
37 changes: 28 additions & 9 deletions src/util.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MentionsProps } from './Mentions';
import { OptionProps } from './Option';
import type { MentionsProps } from './Mentions';
import type { OptionProps } from './Option';

export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

Expand Down Expand Up @@ -34,7 +34,10 @@ interface MeasureIndex {
/**
* Find the last match prefix index
*/
export function getLastMeasureIndex(text: string, prefix: string | string[] = ''): MeasureIndex {
export function getLastMeasureIndex(
text: string,
prefix: string | string[] = '',
): MeasureIndex {
const prefixList: string[] = Array.isArray(prefix) ? prefix : [prefix];
return prefixList.reduce(
(lastMatch: MeasureIndex, prefixStr): MeasureIndex => {
Expand Down Expand Up @@ -90,13 +93,21 @@ function reduceText(text: string, targetText: string, split: string) {
* targetText: light
* => little @light test
*/
export function replaceWithMeasure(text: string, measureConfig: MeasureConfig) {
const { measureLocation, prefix, targetText, selectionStart, split } = measureConfig;
export function replaceWithMeasure(
text: string,
measureConfig: MeasureConfig,
replaceWithoutPrefix?: boolean,
) {
const { measureLocation, prefix, targetText, selectionStart, split } =
measureConfig;

// Before text will append one space if have other text
let beforeMeasureText = text.slice(0, measureLocation);
if (beforeMeasureText[beforeMeasureText.length - split.length] === split) {
beforeMeasureText = beforeMeasureText.slice(0, beforeMeasureText.length - split.length);
beforeMeasureText = beforeMeasureText.slice(
0,
beforeMeasureText.length - split.length,
);
}
if (beforeMeasureText) {
beforeMeasureText = `${beforeMeasureText}${split}`;
Expand All @@ -112,15 +123,20 @@ export function replaceWithMeasure(text: string, measureConfig: MeasureConfig) {
restText = restText.slice(split.length);
}

const connectedStartText = `${beforeMeasureText}${prefix}${targetText}${split}`;
const connectedStartText = `${beforeMeasureText}${
replaceWithoutPrefix ? '' : prefix
}${targetText}${split}`;

return {
text: `${connectedStartText}${restText}`,
selectionLocation: connectedStartText.length,
};
}

export function setInputSelection(input: HTMLTextAreaElement, location: number) {
export function setInputSelection(
input: HTMLTextAreaElement,
location: number,
) {
input.setSelectionRange(location, location);

/**
Expand All @@ -136,7 +152,10 @@ export function validateSearch(text: string, props: MentionsProps) {
return !split || text.indexOf(split) === -1;
}

export function filterOption(input: string, { value = '' }: OptionProps): boolean {
export function filterOption(
input: string,
{ value = '' }: OptionProps,
): boolean {
const lowerCase = input.toLowerCase();
return value.toLowerCase().indexOf(lowerCase) !== -1;
}
12 changes: 12 additions & 0 deletions tests/FullProcess.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,4 +158,16 @@ describe('Full Process', () => {

expect(wrapper.state().measuring).toBe(false);
});

it('replace without prefix', () => {
const onChange = jest.fn();
const wrapper = createMentions({ onChange, replaceWithoutPrefix: true });

simulateInput(wrapper, '@b');
wrapper.find('textarea').simulate('keyDown', {
keyCode: KeyCode.ENTER,
});

expect(onChange).toBeCalledWith('bamboo ');
});
});