-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathMentions.tsx
399 lines (353 loc) · 10.7 KB
/
Mentions.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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 { polyfill } from 'react-lifecycles-compat';
import KeywordTrigger from './KeywordTrigger';
import { MentionsContextProvider } from './MentionsContext';
import Option, { OptionProps } from './Option';
import {
filterOption as defaultFilterOption,
getBeforeSelectionText,
getLastMeasureIndex,
omit,
Omit,
replaceWithMeasure,
setInputSelection,
validateSearch as defaultValidateSearch,
} from './util';
type BaseTextareaAttrs = Omit<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
'prefix' | 'onChange' | 'onSelect'
>;
export type Placement = 'top' | 'bottom';
export interface MentionsProps extends BaseTextareaAttrs {
autoFocus?: boolean;
className?: string;
defaultValue?: string;
notFoundContent?: React.ReactNode;
split?: string;
style?: React.CSSProperties;
transitionName?: string;
placement?: Placement;
prefix?: string | string[];
prefixCls?: string;
value?: string;
filterOption?: false | typeof defaultFilterOption;
validateSearch?: typeof defaultValidateSearch;
onChange?: (text: string) => void;
onSelect?: (option: OptionProps, prefix: string) => void;
onSearch?: (text: string, prefix: string) => void;
onFocus?: React.FocusEventHandler<HTMLTextAreaElement>;
onBlur?: React.FocusEventHandler<HTMLTextAreaElement>;
getPopupContainer?: () => HTMLElement;
}
interface MentionsState {
value: string;
measuring: boolean;
measureText: string | null;
measurePrefix: string;
measureLocation: number;
activeIndex: number;
isFocus: boolean;
}
class Mentions extends React.Component<MentionsProps, MentionsState> {
public static Option = Option;
public static defaultProps = {
prefixCls: 'rc-mentions',
prefix: '@',
split: ' ',
validateSearch: defaultValidateSearch,
filterOption: defaultFilterOption,
notFoundContent: 'Not Found',
rows: 1,
};
public static getDerivedStateFromProps(props: MentionsProps, prevState: MentionsState) {
const newState: Partial<MentionsState> = {};
if ('value' in props && props.value !== prevState.value) {
newState.value = props.value;
}
return newState;
}
public textarea?: HTMLTextAreaElement;
public measure?: HTMLDivElement;
public focusId: number | undefined = undefined;
constructor(props: MentionsProps) {
super(props);
this.state = {
value: props.defaultValue || props.value || '',
measuring: false,
measureLocation: 0,
measureText: null,
measurePrefix: '',
activeIndex: 0,
isFocus: false,
};
}
public componentDidUpdate() {
const { measuring } = this.state;
// Sync measure div top with textarea for rc-trigger usage
if (measuring) {
this.measure.scrollTop = this.textarea.scrollTop;
}
}
public triggerChange = (value: string) => {
const { onChange } = this.props;
if (!('value' in this.props)) {
this.setState({ value });
}
if (onChange) {
onChange(value);
}
};
public onChange: React.ChangeEventHandler<HTMLTextAreaElement> = ({ target: { value } }) => {
this.triggerChange(value);
};
// Check if hit the measure keyword
public onKeyDown: React.KeyboardEventHandler<HTMLTextAreaElement> = event => {
const { which } = event;
const { activeIndex, measuring } = this.state;
// Skip if not measuring
if (!measuring) {
return;
}
if (which === KeyCode.UP || which === KeyCode.DOWN) {
// Control arrow function
const optionLen = this.getOptions().length;
const offset = which === KeyCode.UP ? -1 : 1;
const newActiveIndex = (activeIndex + offset + optionLen) % optionLen;
this.setState({
activeIndex: newActiveIndex,
});
event.preventDefault();
} else if (which === KeyCode.ESC) {
this.stopMeasure();
} else if (which === KeyCode.ENTER) {
// Measure hit
const option = this.getOptions()[activeIndex];
this.selectOption(option);
event.preventDefault();
}
};
/**
* When to start measure:
* 1. When user press `prefix`
* 2. When measureText !== prevMeasureText
* - If measure hit
* - If measuring
*
* When to stop measure:
* 1. Selection is out of range
* 2. Contains `space`
* 3. ESC or select one
*/
public onKeyUp: React.KeyboardEventHandler<HTMLTextAreaElement> = event => {
const { key, which } = event;
const { measureText: prevMeasureText, measuring } = this.state;
const { prefix = '', onSearch, validateSearch } = this.props;
const target = event.target as HTMLTextAreaElement;
const selectionStartText = getBeforeSelectionText(target);
const { location: measureIndex, prefix: measurePrefix } = getLastMeasureIndex(
selectionStartText,
prefix,
);
// Skip if match the white key list
if ([KeyCode.ESC, KeyCode.UP, KeyCode.DOWN, KeyCode.ENTER].indexOf(which) !== -1) {
return;
}
if (measureIndex !== -1) {
const measureText = selectionStartText.slice(measureIndex + measurePrefix.length);
const validateMeasure: boolean = validateSearch(measureText, this.props);
const matchOption = !!this.getOptions(measureText).length;
if (validateMeasure) {
if (
key === measurePrefix ||
measuring ||
(measureText !== prevMeasureText && matchOption)
) {
this.startMeasure(measureText, measurePrefix, measureIndex);
}
} else if (measuring) {
// Stop if measureText is invalidate
this.stopMeasure();
}
/**
* We will trigger `onSearch` to developer since they may use for async update.
* If met `space` means user finished searching.
*/
if (onSearch && validateMeasure) {
onSearch(measureText, measurePrefix);
}
} else if (measuring) {
this.stopMeasure();
}
};
public onInputFocus: React.FocusEventHandler<HTMLTextAreaElement> = event => {
this.onFocus(event);
};
public onInputBlur: React.FocusEventHandler<HTMLTextAreaElement> = event => {
this.onBlur(event);
};
public onDropdownFocus = () => {
this.onFocus();
};
public onFocus = (event?: React.FocusEvent<HTMLTextAreaElement>) => {
window.clearTimeout(this.focusId);
const { isFocus } = this.state;
const { onFocus } = this.props;
if (!isFocus && event && onFocus) {
onFocus(event);
}
this.setState({ isFocus: true });
};
public onBlur = (event: React.FocusEvent<HTMLTextAreaElement>) => {
this.focusId = window.setTimeout(() => {
const { onBlur } = this.props;
this.setState({ isFocus: false });
this.stopMeasure();
if (onBlur) {
onBlur(event);
}
}, 0);
};
public selectOption = (option: OptionProps) => {
const { value, measureLocation, measurePrefix } = this.state;
const { split, onSelect } = this.props;
const { value: mentionValue = '' } = option;
const { text, selectionLocation } = replaceWithMeasure(value, {
measureLocation,
targetText: mentionValue,
prefix: measurePrefix,
selectionStart: this.textarea.selectionStart,
split,
});
this.triggerChange(text);
this.stopMeasure(() => {
// We need restore the selection position
setInputSelection(this.textarea, selectionLocation);
});
if (onSelect) {
onSelect(option, measurePrefix);
}
};
public setActiveIndex = (activeIndex: number) => {
this.setState({
activeIndex,
});
};
public setTextAreaRef = (element: HTMLTextAreaElement) => {
this.textarea = element;
};
public setMeasureRef = (element: HTMLDivElement) => {
this.measure = element;
};
public getOptions = (measureText?: string): OptionProps[] => {
const targetMeasureText = measureText || this.state.measureText || '';
const { children, filterOption } = this.props;
const list = toArray(children)
.map(({ props }: { props: OptionProps }) => props)
.filter((option: OptionProps) => {
/** Return all result if `filterOption` is false. */
if (filterOption === false) {
return true;
}
return filterOption(targetMeasureText, option);
});
return list;
};
public startMeasure(measureText: string, measurePrefix: string, measureLocation: number) {
this.setState({
measuring: true,
measureText,
measurePrefix,
measureLocation,
activeIndex: 0,
});
}
public stopMeasure(callback?: () => void) {
this.setState(
{
measuring: false,
measureLocation: 0,
measureText: null,
},
callback,
);
}
public focus() {
this.textarea.focus();
}
public blur() {
this.textarea.blur();
}
public render() {
const { value, measureLocation, measurePrefix, measuring, activeIndex } = this.state;
const {
prefixCls,
placement,
transitionName,
className,
style,
autoFocus,
notFoundContent,
getPopupContainer,
...restProps
} = this.props;
const inputProps = omit(
restProps,
'value',
'defaultValue',
'prefix',
'split',
'children',
'validateSearch',
'filterOption',
'onSelect',
'onSearch',
);
const options = measuring ? this.getOptions() : [];
return (
<div className={classNames(prefixCls, className)} style={style}>
<textarea
autoFocus={autoFocus}
ref={this.setTextAreaRef}
value={value}
{...inputProps}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={this.onKeyUp}
onFocus={this.onInputFocus}
onBlur={this.onInputBlur}
/>
{measuring && (
<div ref={this.setMeasureRef} className={`${prefixCls}-measure`}>
{value.slice(0, measureLocation)}
<MentionsContextProvider
value={{
notFoundContent,
activeIndex,
setActiveIndex: this.setActiveIndex,
selectOption: this.selectOption,
onFocus: this.onDropdownFocus,
}}
>
<KeywordTrigger
prefixCls={prefixCls}
transitionName={transitionName}
placement={placement}
options={options}
visible
getPopupContainer={getPopupContainer}
>
<span>{measurePrefix}</span>
</KeywordTrigger>
</MentionsContextProvider>
{value.slice(measureLocation + measurePrefix.length)}
</div>
)}
</div>
);
}
}
polyfill(Mentions);
export default Mentions;