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

fix: fixed TextArea autoSize is not work when textarea resize #2026 #2028

Merged
merged 1 commit into from
Jan 19, 2024
Merged
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
11 changes: 11 additions & 0 deletions cypress/e2e/textarea.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,15 @@ describe('textarea', () => {
});
});
});

it('autosize + textarea resize', () => {
cy.visit('http://localhost:6006/iframe.html?id=input--text-auto-size-resize&viewMode=story');
cy.get('button').contains('width=100').trigger('click');
cy.wait(100);
cy.document().then(document => {
const textAreaDOM = document.querySelector(".semi-input-textarea");
const { scrollHeight, clientHeight } = textAreaDOM;
expect(scrollHeight).eq(clientHeight);
});
});
});
5 changes: 1 addition & 4 deletions packages/semi-foundation/input/textareaFoundation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,14 +193,13 @@ export default class TextAreaFoundation extends BaseFoundation<TextAreaAdapter>
}
}

resizeTextarea = (cb?: any) => {
resizeTextarea = () => {
const { height } = this.getStates();
const { rows, autosize } = this.getProps();
const node = this._adapter.getRef();
const nodeSizingData = getSizingData(node);

if (!nodeSizingData) {
cb && cb();
return;
}

Expand All @@ -221,8 +220,6 @@ export default class TextAreaFoundation extends BaseFoundation<TextAreaAdapter>
node.style.height = `${newHeight}px`;
return;
}

cb && cb();
};

// e: MouseEvent
Expand Down
16 changes: 16 additions & 0 deletions packages/semi-ui/input/_story/input.stories.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -1015,3 +1015,19 @@ export const forwardRefFocus = () => {
</div>
</>
)};

export const TextAutoSizeResize = () => {
const [width, setWidth] = useState(800);

return (
<div>
<Space style={{ marginBottom: 20 }}>
<Button onClick={() => setWidth(100)}>width=100</Button>
<Button onClick={() => setWidth(1000)}>width=1000</Button>
</Space>
<div style={{ width, maxWidth: '100%' }}>
<TextArea autosize defaultValue='semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design semi design ' />
</div>
</div>
)
};
133 changes: 55 additions & 78 deletions packages/semi-ui/input/textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import TextAreaFoundation from '@douyinfe/semi-foundation/input/textareaFoundati
import { cssClasses } from '@douyinfe/semi-foundation/input/constants';
import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
import '@douyinfe/semi-foundation/input/textarea.scss';
import { noop, omit, isFunction, isUndefined, isObject } from 'lodash';
import { noop, omit, isFunction, isUndefined, isObject, throttle, DebouncedFunc } from 'lodash';
import { IconClear } from '@douyinfe/semi-icons';
import ResizeObserver from '../resizeObserver';

const prefixCls = cssClasses.PREFIX;

Expand All @@ -20,15 +21,14 @@ type OmitTextareaAttr =
| 'onKeyDown'
| 'onKeyPress'
| 'onKeyUp'
| 'onResize'
| 'onResize';

export type AutosizeRow = {
minRows?: number;
maxRows?: number
}
};

export interface TextAreaProps extends
Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, OmitTextareaAttr> {
export interface TextAreaProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, OmitTextareaAttr> {
autosize?: boolean | AutosizeRow;
borderless?: boolean;
placeholder?: string;
Expand All @@ -53,7 +53,7 @@ export interface TextAreaProps extends
onKeyPress?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
onEnterPress?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
onPressEnter?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
onResize?: (data: {height: number}) => void;
onResize?: (data: { height: number }) => void;
getValueLength?: (value: string) => number;
forwardRef?: ((instance: HTMLTextAreaElement) => void) | React.MutableRefObject<HTMLTextAreaElement> | null
}
Expand Down Expand Up @@ -107,9 +107,8 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {

focusing: boolean;
libRef: React.RefObject<HTMLInputElement>;
_resizeLock: boolean;
_resizeListener: any;
foundation: TextAreaFoundation;
throttledResizeTextarea: DebouncedFunc<typeof this.foundation.resizeTextarea>;

constructor(props: TextAreaProps) {
super(props);
Expand All @@ -124,17 +123,18 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
this.foundation = new TextAreaFoundation(this.adapter);

this.libRef = React.createRef<HTMLInputElement>();
this._resizeLock = false;
this.throttledResizeTextarea = throttle(this.foundation.resizeTextarea, 10);
}

get adapter() {
return {
...super.adapter,
setValue: (value: string) => this.setState({ value }, () => {
if (this.props.autosize) {
this.foundation.resizeTextarea();
}
}),
setValue: (value: string) =>
this.setState({ value }, () => {
if (this.props.autosize) {
this.foundation.resizeTextarea();
}
}),
getRef: () => this.libRef.current,
toggleFocusing: (focusing: boolean) => this.setState({ isFocus: focusing }),
toggleHovering: (hovering: boolean) => this.setState({ isHover: hovering }),
Expand Down Expand Up @@ -169,35 +169,18 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
return willUpdateStates;
}

componentDidMount() {
this.foundation.init();
this._resizeListener = null;
if (this.props.autosize) {
// Working around Firefox bug which runs resize listeners even when other JS is running at the same moment
// causing competing rerenders (due to setState in the listener) in React.
// More can be found here - facebook/react#6324
// // Reference to https://github.com/andreypopp/react-textarea-autosize/
this._resizeListener = () => {
if (this._resizeLock) {
return;
}
this._resizeLock = true;
this.foundation.resizeTextarea(() => {
this._resizeLock = false;
});
};
window.addEventListener('resize', this._resizeListener);
componentWillUnmount(): void {
if (this.throttledResizeTextarea) {
this.throttledResizeTextarea?.cancel?.();
this.throttledResizeTextarea = null;
}
}

componentWillUnmount() {
this.foundation.destroy();
this._resizeListener && window.removeEventListener('resize', this._resizeListener);
}

componentDidUpdate(prevProps: TextAreaProps, prevState: TextAreaState) {

if ((this.props.value !== prevProps.value || this.props.placeholder !== prevProps.placeholder) && this.props.autosize) {
if (
(this.props.value !== prevProps.value || this.props.placeholder !== prevProps.placeholder) &&
this.props.autosize
) {
this.foundation.resizeTextarea();
}
}
Expand All @@ -215,10 +198,7 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
if (showClear) {
return (
// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
<div
className={clearCls}
onClick={this.handleClear}
>
<div className={clearCls} onClick={this.handleClear}>
<IconClear />
</div>
);
Expand All @@ -227,25 +207,21 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
}

renderCounter() {
let counter: React.ReactNode,
current: number,
total: number,
countCls: string;
let counter: React.ReactNode, current: number, total: number, countCls: string;
const { showCounter, maxCount, getValueLength } = this.props;
if (showCounter || maxCount) {
const { value } = this.state;
// eslint-disable-next-line no-nested-ternary
current = value ? isFunction(getValueLength) ? getValueLength(value) : value.length : 0;
current = value ? (isFunction(getValueLength) ? getValueLength(value) : value.length) : 0;
total = maxCount || null;
countCls = cls(
`${prefixCls}-textarea-counter`,
{
[`${prefixCls}-textarea-counter-exceed`]: current > total
}
);
countCls = cls(`${prefixCls}-textarea-counter`, {
[`${prefixCls}-textarea-counter-exceed`]: current > total,
});
counter = (
<div className={countCls}>
{current}{total ? '/' : null}{total}
{current}
{total ? '/' : null}
{total}
</div>
);
} else {
Expand Down Expand Up @@ -289,28 +265,21 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
...rest
} = this.props;
const { isFocus, value, minLength: stateMinLength } = this.state;
const wrapperCls = cls(
className,
`${prefixCls}-textarea-wrapper`,
{
[`${prefixCls}-textarea-borderless`]: borderless,
[`${prefixCls}-textarea-wrapper-disabled`]: disabled,
[`${prefixCls}-textarea-wrapper-readonly`]: readonly,
[`${prefixCls}-textarea-wrapper-${validateStatus}`]: Boolean(validateStatus),
[`${prefixCls}-textarea-wrapper-focus`]: isFocus,
// [`${prefixCls}-textarea-wrapper-resize`]: !autosize && resize,
}
);
const wrapperCls = cls(className, `${prefixCls}-textarea-wrapper`, {
[`${prefixCls}-textarea-borderless`]: borderless,
[`${prefixCls}-textarea-wrapper-disabled`]: disabled,
[`${prefixCls}-textarea-wrapper-readonly`]: readonly,
[`${prefixCls}-textarea-wrapper-${validateStatus}`]: Boolean(validateStatus),
[`${prefixCls}-textarea-wrapper-focus`]: isFocus,
// [`${prefixCls}-textarea-wrapper-resize`]: !autosize && resize,
});
// const ref = this.props.forwardRef || this.textAreaRef;
const itemCls = cls(
`${prefixCls}-textarea`,
{
[`${prefixCls}-textarea-disabled`]: disabled,
[`${prefixCls}-textarea-readonly`]: readonly,
[`${prefixCls}-textarea-autosize`]: isObject(autosize) ? isUndefined(autosize?.maxRows) : autosize,
[`${prefixCls}-textarea-showClear`]: showClear,
}
);
const itemCls = cls(`${prefixCls}-textarea`, {
[`${prefixCls}-textarea-disabled`]: disabled,
[`${prefixCls}-textarea-readonly`]: readonly,
[`${prefixCls}-textarea-autosize`]: isObject(autosize) ? isUndefined(autosize?.maxRows) : autosize,
[`${prefixCls}-textarea-showClear`]: showClear,
});
const itemProps = {
...omit(rest, 'insetLabel', 'insetLabelId', 'getValueLength', 'onClear', 'showClear'),
autoFocus: autoFocus || this.props['autofocus'],
Expand Down Expand Up @@ -338,14 +307,22 @@ class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
onMouseEnter={e => this.foundation.handleMouseEnter(e)}
onMouseLeave={e => this.foundation.handleMouseLeave(e)}
>
<textarea {...itemProps} ref={this.setRef} />
{autosize ? (
<ResizeObserver onResize={this.throttledResizeTextarea}>
<textarea {...itemProps} ref={this.setRef} />
</ResizeObserver>
) : (
<textarea {...itemProps} ref={this.setRef} />
)}
{this.renderClearBtn()}
{this.renderCounter()}
</div>
);
}
}

const ForwardTextarea = React.forwardRef<HTMLTextAreaElement, Omit<TextAreaProps, 'forwardRef'>>((props, ref) => <TextArea {...props} forwardRef={ref} />);
const ForwardTextarea = React.forwardRef<HTMLTextAreaElement, Omit<TextAreaProps, 'forwardRef'>>((props, ref) => (
<TextArea {...props} forwardRef={ref} />
));

export default ForwardTextarea;
Loading