forked from vueComponent/ant-design-vue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextArea.tsx
318 lines (297 loc) · 10.2 KB
/
TextArea.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
import type { CSSProperties } from 'vue';
import {
computed,
defineComponent,
getCurrentInstance,
nextTick,
shallowRef,
watch,
watchEffect,
} from 'vue';
import ClearableLabeledInput from './ClearableLabeledInput';
import ResizableTextArea from './ResizableTextArea';
import { textAreaProps } from './inputProps';
import type { InputFocusOptions } from '../vc-input/utils/commonUtils';
import { fixControlledValue, resolveOnChange, triggerFocus } from '../vc-input/utils/commonUtils';
import classNames from '../_util/classNames';
import { FormItemInputContext, useInjectFormItemContext } from '../form/FormItemContext';
import type { FocusEventHandler } from '../_util/EventInterface';
import useConfigInject from '../config-provider/hooks/useConfigInject';
import omit from '../_util/omit';
import type { VueNode } from '../_util/type';
import { getMergedStatus, getStatusClassNames } from '../_util/statusUtils';
// CSSINJS
import useStyle from './style';
import { useInjectDisabled } from '../config-provider/DisabledContext';
function fixEmojiLength(value: string, maxLength: number) {
return [...(value || '')].slice(0, maxLength).join('');
}
function setTriggerValue(
isCursorInEnd: boolean,
preValue: string,
triggerValue: string,
maxLength: number,
) {
let newTriggerValue = triggerValue;
if (isCursorInEnd) {
// 光标在尾部,直接截断
newTriggerValue = fixEmojiLength(triggerValue, maxLength!);
} else if (
[...(preValue || '')].length < triggerValue.length &&
[...(triggerValue || '')].length > maxLength!
) {
// 光标在中间,如果最后的值超过最大值,则采用原先的值
newTriggerValue = preValue;
}
return newTriggerValue;
}
export default defineComponent({
compatConfig: { MODE: 3 },
name: 'ATextarea',
inheritAttrs: false,
props: textAreaProps(),
setup(props, { attrs, expose, emit }) {
const formItemContext = useInjectFormItemContext();
const formItemInputContext = FormItemInputContext.useInject();
const mergedStatus = computed(() => getMergedStatus(formItemInputContext.status, props.status));
const stateValue = shallowRef(props.value === undefined ? props.defaultValue : props.value);
const resizableTextArea = shallowRef();
const mergedValue = shallowRef('');
const { prefixCls, size, direction } = useConfigInject('input', props);
// Style
const [wrapSSR, hashId] = useStyle(prefixCls);
const disabled = useInjectDisabled();
const showCount = computed(() => {
return (props.showCount as any) === '' || props.showCount || false;
});
// Max length value
const hasMaxLength = computed(() => Number(props.maxlength) > 0);
const compositing = shallowRef(false);
const oldCompositionValueRef = shallowRef<string>();
const oldSelectionStartRef = shallowRef<number>(0);
const onInternalCompositionStart = (e: CompositionEvent) => {
compositing.value = true;
// 拼音输入前保存一份旧值
oldCompositionValueRef.value = mergedValue.value as string;
// 保存旧的光标位置
oldSelectionStartRef.value = (e.currentTarget as any).selectionStart;
emit('compositionstart', e);
};
const onInternalCompositionEnd = (e: CompositionEvent) => {
compositing.value = false;
let triggerValue = (e.currentTarget as any).value;
if (hasMaxLength.value) {
const isCursorInEnd =
oldSelectionStartRef.value >= props.maxlength + 1 ||
oldSelectionStartRef.value === oldCompositionValueRef.value?.length;
triggerValue = setTriggerValue(
isCursorInEnd,
oldCompositionValueRef.value as string,
triggerValue,
props.maxlength,
);
}
// Patch composition onChange when value changed
if (triggerValue !== mergedValue.value) {
setValue(triggerValue);
resolveOnChange(e.currentTarget as any, e, triggerChange, triggerValue);
}
emit('compositionend', e);
};
const instance = getCurrentInstance();
watch(
() => props.value,
() => {
if ('value' in instance.vnode.props || {}) {
stateValue.value = props.value ?? '';
}
},
);
const focus = (option?: InputFocusOptions) => {
triggerFocus(resizableTextArea.value?.textArea, option);
};
const blur = () => {
resizableTextArea.value?.textArea?.blur();
};
const setValue = (value: string | number, callback?: Function) => {
if (stateValue.value === value) {
return;
}
if (props.value === undefined) {
stateValue.value = value;
} else {
nextTick(() => {
if (resizableTextArea.value.textArea.value !== mergedValue.value) {
resizableTextArea.value?.instance.update?.();
}
});
}
nextTick(() => {
callback && callback();
});
};
const handleKeyDown = (e: KeyboardEvent) => {
if (e.keyCode === 13) {
emit('pressEnter', e);
}
emit('keydown', e);
};
const onBlur: FocusEventHandler = e => {
const { onBlur } = props;
onBlur?.(e);
formItemContext.onFieldBlur();
};
const triggerChange = (e: Event) => {
emit('update:value', (e.target as HTMLInputElement).value);
emit('change', e);
emit('input', e);
formItemContext.onFieldChange();
};
const handleReset = (e: MouseEvent) => {
resolveOnChange(resizableTextArea.value.textArea, e, triggerChange);
setValue('', () => {
focus();
});
};
const handleChange = (e: Event) => {
const { composing } = e.target as any;
let triggerValue = (e.target as any).value;
compositing.value = !!((e as any).isComposing && composing);
if (stateValue.value === triggerValue) return;
if (hasMaxLength.value) {
// 1. 复制粘贴超过maxlength的情况 2.未超过maxlength的情况
const target = e.target as any;
const isCursorInEnd =
target.selectionStart >= props.maxlength! + 1 ||
target.selectionStart === triggerValue.length ||
!target.selectionStart;
triggerValue = setTriggerValue(
isCursorInEnd,
mergedValue.value as string,
triggerValue,
props.maxlength!,
);
}
resolveOnChange(e.currentTarget as any, e, triggerChange, triggerValue);
setValue(triggerValue);
};
const renderTextArea = () => {
const { class: customClass } = attrs;
const { bordered = true } = props;
const resizeProps = {
...omit(props, ['allowClear']),
...attrs,
class: [
{
[`${prefixCls.value}-borderless`]: !bordered,
[`${customClass}`]: customClass && !showCount.value,
[`${prefixCls.value}-sm`]: size.value === 'small',
[`${prefixCls.value}-lg`]: size.value === 'large',
},
getStatusClassNames(prefixCls.value, mergedStatus.value),
hashId.value,
],
disabled: disabled.value,
showCount: null,
prefixCls: prefixCls.value,
onInput: handleChange,
onChange: handleChange,
onBlur,
onKeydown: handleKeyDown,
onCompositionstart: onInternalCompositionStart,
onCompositionend: onInternalCompositionEnd,
};
if (props.valueModifiers?.lazy) {
delete resizeProps.onInput;
}
return (
<ResizableTextArea
{...resizeProps}
id={resizeProps?.id ?? formItemContext.id.value}
ref={resizableTextArea}
maxlength={props.maxlength}
/>
);
};
expose({
focus,
blur,
resizableTextArea,
});
watchEffect(() => {
let val = fixControlledValue(stateValue.value) as string;
if (
!compositing.value &&
hasMaxLength.value &&
(props.value === null || props.value === undefined)
) {
// fix #27612 将value转为数组进行截取,解决 '😂'.length === 2 等emoji表情导致的截取乱码的问题
val = fixEmojiLength(val, props.maxlength);
}
mergedValue.value = val;
});
return () => {
const { maxlength, bordered = true, hidden } = props;
const { style, class: customClass } = attrs;
const inputProps: any = {
...props,
...attrs,
prefixCls: prefixCls.value,
inputType: 'text',
handleReset,
direction: direction.value,
bordered,
style: showCount.value ? undefined : style,
hashId: hashId.value,
disabled: props.disabled ?? disabled.value,
};
let textareaNode = (
<ClearableLabeledInput
{...inputProps}
value={mergedValue.value}
v-slots={{ element: renderTextArea }}
status={props.status}
/>
);
if (showCount.value || formItemInputContext.hasFeedback) {
const valueLength = [...mergedValue.value].length;
let dataCount: VueNode = '';
if (typeof showCount.value === 'object') {
dataCount = showCount.value.formatter({
value: mergedValue.value,
count: valueLength,
maxlength,
});
} else {
dataCount = `${valueLength}${hasMaxLength.value ? ` / ${maxlength}` : ''}`;
}
textareaNode = (
<div
hidden={hidden}
class={classNames(
`${prefixCls.value}-textarea`,
{
[`${prefixCls.value}-textarea-rtl`]: direction.value === 'rtl',
[`${prefixCls.value}-textarea-show-count`]: showCount.value,
[`${prefixCls.value}-textarea-in-form-item`]: formItemInputContext.isFormItemInput,
},
`${prefixCls.value}-textarea-show-count`,
customClass,
hashId.value,
)}
style={style as CSSProperties}
data-count={typeof dataCount !== 'object' ? dataCount : undefined}
>
{textareaNode}
{formItemInputContext.hasFeedback && (
<span class={`${prefixCls.value}-textarea-suffix`}>
{formItemInputContext.feedbackIcon}
</span>
)}
</div>
);
}
return wrapSSR(textareaNode);
};
},
});