forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextareaAutosize.tsx
321 lines (283 loc) · 9.1 KB
/
TextareaAutosize.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
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import * as ReactDOM from 'react-dom';
import {
unstable_debounce as debounce,
unstable_useForkRef as useForkRef,
unstable_useEnhancedEffect as useEnhancedEffect,
unstable_ownerWindow as ownerWindow,
} from '@mui/utils';
import { TextareaAutosizeProps } from './TextareaAutosize.types';
type State = {
outerHeightStyle: number;
overflow?: boolean | undefined;
};
function getStyleValue(value: string) {
return parseInt(value, 10) || 0;
}
const styles: {
shadow: React.CSSProperties;
} = {
shadow: {
// Visibility needed to hide the extra text area on iPads
visibility: 'hidden',
// Remove from the content flow
position: 'absolute',
// Ignore the scrollbar width
overflow: 'hidden',
height: 0,
top: 0,
left: 0,
// Create a new layer, increase the isolation of the computed values
transform: 'translateZ(0)',
},
};
function isEmpty(obj: State) {
return (
obj === undefined ||
obj === null ||
Object.keys(obj).length === 0 ||
(obj.outerHeightStyle === 0 && !obj.overflow)
);
}
/**
*
* Demos:
*
* - [Textarea Autosize](https://mui.com/base-ui/react-textarea-autosize/)
* - [Textarea Autosize](https://mui.com/material-ui/react-textarea-autosize/)
*
* API:
*
* - [TextareaAutosize API](https://mui.com/base-ui/react-textarea-autosize/components-api/#textarea-autosize)
*/
const TextareaAutosize = React.forwardRef(function TextareaAutosize(
props: TextareaAutosizeProps,
forwardedRef: React.ForwardedRef<Element>,
) {
const { onChange, maxRows, minRows = 1, style, value, ...other } = props;
const { current: isControlled } = React.useRef(value != null);
const inputRef = React.useRef<HTMLInputElement>(null);
const handleRef = useForkRef(forwardedRef, inputRef);
const shadowRef = React.useRef<HTMLTextAreaElement>(null);
const renders = React.useRef(0);
const [state, setState] = React.useState<State>({
outerHeightStyle: 0,
});
const getUpdatedState = React.useCallback(() => {
const input = inputRef.current!;
const containerWindow = ownerWindow(input);
const computedStyle = containerWindow.getComputedStyle(input);
// If input's width is shrunk and it's not visible, don't sync height.
if (computedStyle.width === '0px') {
return {
outerHeightStyle: 0,
};
}
const inputShallow = shadowRef.current!;
inputShallow.style.width = computedStyle.width;
inputShallow.value = input.value || props.placeholder || 'x';
if (inputShallow.value.slice(-1) === '\n') {
// Certain fonts which overflow the line height will cause the textarea
// to report a different scrollHeight depending on whether the last line
// is empty. Make it non-empty to avoid this issue.
inputShallow.value += ' ';
}
const boxSizing = computedStyle.boxSizing;
const padding =
getStyleValue(computedStyle.paddingBottom) + getStyleValue(computedStyle.paddingTop);
const border =
getStyleValue(computedStyle.borderBottomWidth) + getStyleValue(computedStyle.borderTopWidth);
// The height of the inner content
const innerHeight = inputShallow.scrollHeight;
// Measure height of a textarea with a single row
inputShallow.value = 'x';
const singleRowHeight = inputShallow.scrollHeight;
// The height of the outer content
let outerHeight = innerHeight;
if (minRows) {
outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);
}
if (maxRows) {
outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);
}
outerHeight = Math.max(outerHeight, singleRowHeight);
// Take the box sizing into account for applying this value as a style.
const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
const overflow = Math.abs(outerHeight - innerHeight) <= 1;
return { outerHeightStyle, overflow };
}, [maxRows, minRows, props.placeholder]);
const updateState = (prevState: State, newState: State) => {
const { outerHeightStyle, overflow } = newState;
// Need a large enough difference to update the height.
// This prevents infinite rendering loop.
if (
renders.current < 20 &&
((outerHeightStyle > 0 &&
Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1) ||
prevState.overflow !== overflow)
) {
renders.current += 1;
return {
overflow,
outerHeightStyle,
};
}
if (process.env.NODE_ENV !== 'production') {
if (renders.current === 20) {
console.error(
[
'MUI: Too many re-renders. The layout is unstable.',
'TextareaAutosize limits the number of renders to prevent an infinite loop.',
].join('\n'),
);
}
}
return prevState;
};
const syncHeight = React.useCallback(() => {
const newState = getUpdatedState();
if (isEmpty(newState)) {
return;
}
setState((prevState) => updateState(prevState, newState));
}, [getUpdatedState]);
useEnhancedEffect(() => {
const syncHeightWithFlushSync = () => {
const newState = getUpdatedState();
if (isEmpty(newState)) {
return;
}
// In React 18, state updates in a ResizeObserver's callback are happening after
// the paint, this leads to an infinite rendering.
//
// Using flushSync ensures that the states is updated before the next pain.
// Related issue - https://github.com/facebook/react/issues/24331
ReactDOM.flushSync(() => {
setState((prevState) => updateState(prevState, newState));
});
};
const handleResize = () => {
renders.current = 0;
syncHeightWithFlushSync();
};
// Workaround a "ResizeObserver loop completed with undelivered notifications" error
// in test.
// Note that we might need to use this logic in production per https://github.com/WICG/resize-observer/issues/38
// Also see https://github.com/mui/mui-x/issues/8733
let rAF: any;
const rAFHandleResize = () => {
cancelAnimationFrame(rAF);
rAF = requestAnimationFrame(() => {
handleResize();
});
};
const debounceHandleResize = debounce(handleResize);
const input = inputRef.current!;
const containerWindow = ownerWindow(input);
containerWindow.addEventListener('resize', debounceHandleResize);
let resizeObserver: ResizeObserver;
if (typeof ResizeObserver !== 'undefined') {
resizeObserver = new ResizeObserver(
process.env.NODE_ENV === 'test' ? rAFHandleResize : handleResize,
);
resizeObserver.observe(input);
}
return () => {
debounceHandleResize.clear();
cancelAnimationFrame(rAF);
containerWindow.removeEventListener('resize', debounceHandleResize);
if (resizeObserver) {
resizeObserver.disconnect();
}
};
}, [getUpdatedState]);
useEnhancedEffect(() => {
syncHeight();
});
React.useEffect(() => {
renders.current = 0;
}, [value]);
const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
renders.current = 0;
if (!isControlled) {
syncHeight();
}
if (onChange) {
onChange(event);
}
};
return (
<React.Fragment>
<textarea
value={value}
onChange={handleChange}
ref={handleRef}
// Apply the rows prop to get a "correct" first SSR paint
rows={minRows as number}
style={{
height: state.outerHeightStyle,
// Need a large enough difference to allow scrolling.
// This prevents infinite rendering loop.
overflow: state.overflow ? 'hidden' : undefined,
...style,
}}
{...other}
/>
<textarea
aria-hidden
className={props.className}
readOnly
ref={shadowRef}
tabIndex={-1}
style={{
...styles.shadow,
...style,
paddingTop: 0,
paddingBottom: 0,
}}
/>
</React.Fragment>
);
}) as React.ForwardRefExoticComponent<TextareaAutosizeProps & React.RefAttributes<Element>>;
TextareaAutosize.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
className: PropTypes.string,
/**
* Maximum number of rows to display.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display.
* @default 1
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
placeholder: PropTypes.string,
/**
* @ignore
*/
style: PropTypes.object,
/**
* @ignore
*/
value: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.number,
PropTypes.string,
]),
} as any;
export { TextareaAutosize };