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(stepper): 对齐 mobile-vue (#518) #524

Closed
wants to merge 5 commits into from
Closed
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
2 changes: 1 addition & 1 deletion site/mobile/mobile.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export default {
{
title: 'Stepper 步进器',
name: 'Stepper',
component: () => import('tdesign-mobile-react/stepper/_example/index.jsx'),
component: () => import('tdesign-mobile-react/stepper/_example/index.tsx'),
},
{
title: 'PullDownRefresh 下拉刷新',
Expand Down
30 changes: 30 additions & 0 deletions src/_util/formatNumber.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* 格式化数字
* @param value 传入的数字字符串
* @param allowDecimal 是否允许小数,默认为 true
* @param allowNegative 是否允许负数,默认为 true
* @returns 返回格式化后的数字字符串
*/
export const formatNumber = (value: string, allowDecimal = true, allowNegative = true) => {
let resultValue = value;
if (allowDecimal) {
const index = value.indexOf('.');
if (index !== -1) {
resultValue = `${value.slice(0, index + 1)}${value.slice(index).replace(/\./g, '')}`;
}
} else {
const [splitValue = ''] = value.split('.');
resultValue = splitValue;
}

if (allowNegative) {
const index = value.indexOf('-');
if (index !== -1) {
resultValue = `${value.slice(0, index + 1)}${value.slice(index).replace(/-/g, '')}`;
}
} else {
resultValue = value.replace(/-/g, '');
}

return resultValue.replace(/[^\d.-]/g, '');
};
146 changes: 81 additions & 65 deletions src/stepper/Stepper.tsx
Original file line number Diff line number Diff line change
@@ -1,135 +1,151 @@
import React, { FC } from 'react';
import React, { FormEvent, forwardRef, memo } from 'react';
import classNames from 'classnames';
import identity from 'lodash/identity';
import { AddIcon, RemoveIcon } from 'tdesign-icons-react';
import useDefaultProps from 'tdesign-mobile-react/hooks/useDefaultProps';
import useDefault from 'tdesign-mobile-react/_util/useDefault';
import { formatNumber } from 'tdesign-mobile-react/_util/formatNumber';
import useConfig from '../_util/useConfig';
import useDefault from '../_util/useDefault';
import { TdStepperProps } from './type';
import withNativeProps, { NativeProps } from '../_util/withNativeProps';
import { stepperDefaultProps } from './defaultProps';

export interface StepperProps extends TdStepperProps, NativeProps {}

const defaultProps = {
disabled: false,
disableInput: false,
max: 100,
min: 0,
step: 1,
theme: 'normal',
defaultValue: 0,
onBlur: identity,
onChange: identity,
onOverlimit: identity,
};

const Stepper: FC<StepperProps> = (props) => {
const Stepper = forwardRef<HTMLDivElement, StepperProps>((originProps, ref) => {
const props = useDefaultProps(originProps, stepperDefaultProps);
const {
disabled,
className,
style,
disableInput,
disabled,
inputWidth,
integer,
max,
size,
min,
step,
theme,
value,
defaultValue,
onBlur,
onChange,
onFocus,
onOverlimit,
...otherProps
} = props;

const [currentValue, setCurrentValue] = useDefault(value, defaultValue, onChange);
const { classPrefix } = useConfig();
const name = `${classPrefix}-stepper`;
const baseClass = `${classPrefix}-stepper`;
const inputStyle = inputWidth ? { width: `${props.inputWidth}px` } : {};

const isDisabled = (type: 'minus' | 'plus') => {
if (disabled) return true;
if (type === 'minus' && currentValue <= min) {
if (type === 'minus' && Number(currentValue) <= min) {
return true;
}
if (type === 'plus' && currentValue >= max) {
if (type === 'plus' && Number(currentValue) >= max) {
return true;
}
return false;
};

const getLen = (num: number) => {
const numStr = num.toString();
return numStr.indexOf('.') === -1 ? 0 : numStr.split('.')[1].length;
};

/**
* 精确加法
*/
const add = (a: number, b: number) => {
const maxLen = Math.max(getLen(a), getLen(b));
const base = 10 ** maxLen;
return Math.round(a * base + b * base) / base;
};

const formatValue = (value: number) =>
Math.max(Math.min(max, value, Number.MAX_SAFE_INTEGER), min, Number.MIN_SAFE_INTEGER);
Math.max(Math.min(max, value, Number.MAX_SAFE_INTEGER), min, Number.MIN_SAFE_INTEGER).toFixed(
Math.max(getLen(step), getLen(value)),
);

const updateValue = (value: number) => {
setCurrentValue(formatValue(value));
onChange(value);
const updateValue = (value: TdStepperProps['value']) => {
setCurrentValue(formatNumber(`${value}`, !integer));
};

const minusValue = () => {
if (isDisabled('minus')) {
onOverlimit('minus');
const plusValue = () => {
if (isDisabled('plus')) {
onOverlimit?.('plus');
return;
}
updateValue(Number(currentValue) - step);
updateValue(formatValue(add(Number(currentValue), step)));
};

const plusValue = () => {
if (isDisabled('plus')) {
onOverlimit('plus');
const minusValue = () => {
if (isDisabled('minus')) {
onOverlimit?.('minus');
return;
}
updateValue(Number(currentValue) + step);
updateValue(formatValue(add(Number(currentValue), -step)));
};

const handleInput = (e: FormEvent<HTMLInputElement>) => {
const value = formatNumber((e.target as HTMLInputElement).value, !integer);
setCurrentValue(value);
};

const handleChange = (e: React.FocusEvent<HTMLInputElement, Element>) => {
const { value } = e.currentTarget;
if (isNaN(Number(value))) return;
const formattedValue = formatValue(Number(value));
setCurrentValue(formattedValue);
onChange(formattedValue);
const handleChange = () => {
const formattedValue = formatValue(Number(currentValue));
updateValue(formattedValue);
};

const handleBlur = (e: React.FocusEvent<HTMLInputElement, Element>) => {
const { value } = e.currentTarget;
if (isNaN(Number(value))) return;
const formattedValue = formatValue(Number(value));
setCurrentValue(formattedValue);
onBlur(formattedValue);
const handleFocus = () => {
onFocus(Number(currentValue));
};

const handleBlur = () => {
onBlur(Number(currentValue));
};

return withNativeProps(
props,
<div
className={classNames(name, {
[`${classPrefix}-is-disabled`]: disabled,
[`${name}__pure`]: theme === 'grey',
[`${name}__normal`]: theme !== 'grey',
})}
>
<div className={classNames(baseClass, `${baseClass}--${size}`, className)} style={style} {...otherProps} ref={ref}>
<div
className={classNames(`${name}__minus`, {
[`${classPrefix}-is-disabled`]: currentValue <= min,
className={classNames(`${baseClass}__minus`, `${baseClass}__minus--${theme}`, `${baseClass}__icon--${size}`, {
[`${baseClass}--${theme}-disabled`]: disabled || Number(currentValue) <= props.min,
})}
onClick={minusValue}
>
<RemoveIcon className={`${name}__icon`} />
<RemoveIcon className={`${baseClass}__minus-icon`} />
</div>
<input
className={`${name}__input`}
style={{ width: inputWidth || 50 }}
value={currentValue}
onChange={handleChange}
className={classNames(`${baseClass}__input`, `${baseClass}__input--${theme}`, `${baseClass}__input--${size}`, {
[`${baseClass}--${theme}-disabled`]: disabled,
})}
type={integer ? 'tel' : 'text'}
inputMode={integer ? 'numeric' : 'decimal'}
style={inputStyle}
disabled={disableInput || disabled}
readOnly={disableInput}
onFocus={handleFocus}
onBlur={handleBlur}
disabled={disabled || disableInput}
onInput={handleInput}
onChange={handleChange}
/>
<div
className={classNames(`${name}__plus`, {
[`${classPrefix}-is-disabled`]: currentValue >= max,
className={classNames(`${baseClass}__plus`, `${baseClass}__plus--${theme}`, `${baseClass}__icon--${size}`, {
[`${baseClass}--${theme}-disabled`]: disabled || Number(currentValue) >= max,
})}
onClick={plusValue}
>
<AddIcon className={`${name}__icon`} />
<AddIcon className={`${baseClass}__plus-icon`} />
</div>
</div>,
);
};
});

Stepper.defaultProps = defaultProps as StepperProps;
Stepper.defaultProps = stepperDefaultProps as StepperProps;
Stepper.displayName = 'Stepper';

export default Stepper;
export default memo(Stepper);
120 changes: 120 additions & 0 deletions src/stepper/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { describe, vi } from '@test/utils';
import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import { Stepper } from '../index';

const prefix = 't';
const baseClass = `.${prefix}-stepper`;

describe('tag', () => {
describe('props', () => {
it(': disableInput', () => {
const { container } = render(<Stepper disableInput></Stepper>);
const $stepperItem = container.querySelector('.t-stepper__input') as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--disabled`));
});

it(': disabled', () => {
const { container } = render(<Stepper disabled></Stepper>);
const $stepperItem = container.querySelector('.t-stepper__input') as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--disabled`));
});

it(': inputWidth', () => {
const { container } = render(<Stepper inputWidth={100}></Stepper>);
const $stepperItem = container.querySelector('.t-stepper__input') as HTMLElement;
expect($stepperItem.style.width).toBe('100px');
});

it(': integer', () => {
const { container } = render(<Stepper integer={false} value={0.5}></Stepper>);
const $stepperItem = container.querySelector('.t-stepper__input') as HTMLElement;
expect($stepperItem.getAttribute('value')).toBe('0.5');
});

it(': max', () => {
const { container } = render(<Stepper max={10} value={10}></Stepper>);
const $stepperItem = container.querySelector('.t-stepper__plus') as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--filled-disabled`));
});

it(': min', () => {
const { container } = render(<Stepper min={1} value={1}></Stepper>);
const $stepperItem = container.querySelector(`${baseClass}__minus`) as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--filled-disabled`));
});

it(': size', () => {
const size = ['small', 'medium', 'large'] as ('small' | 'medium' | 'large')[];
size.forEach((s) => {
const { container } = render(<Stepper size={s}></Stepper>);
const $stepperItem = container.querySelector(`${baseClass}`) as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--${s}`));
});
});

it(': step', () => {
const { container } = render(<Stepper theme="filled" defaultValue={0.5} integer={false} step={0.5}></Stepper>);
const $stepperPlus = container.querySelector('.t-stepper__plus') as HTMLElement;
const $stepperItem = container.querySelector('.t-stepper__input') as HTMLElement;
fireEvent.click($stepperPlus);
expect($stepperItem.getAttribute('value')).toBe('1.0');
});

it(': theme', () => {
const theme = ['normal', 'filled', 'outline'] as ('normal' | 'filled' | 'outline')[];
theme.forEach((t) => {
const { container } = render(<Stepper theme={t}></Stepper>);
const $stepperItem = container.querySelector(`${baseClass}`) as HTMLElement;
expect($stepperItem.classList.contains(`${baseClass}--${t}`));
});
});

it(': value', () => {
const { container } = render(<Stepper value={10}></Stepper>);
const $stepperItem = container.querySelector(`${baseClass}__input`) as HTMLElement;
expect($stepperItem.getAttribute('value')).toBe('10');
});

it(': defaultValue', () => {
const { container } = render(<Stepper defaultValue={10}></Stepper>);
const $stepperItem = container.querySelector(`${baseClass}__input`) as HTMLElement;
expect($stepperItem.getAttribute('value')).toBe('10');
});
});

describe('event', () => {
it(': blur', async () => {
const onChange = vi.fn();
const onBlur = vi.fn();
const { container } = render(<Stepper defaultValue={99} onBlur={onBlur} onChange={onChange} />);
const $input = container.querySelector(`${baseClass}__input`) as HTMLElement;
fireEvent.blur($input);
expect(onBlur).toHaveBeenCalled();
});

it(': change', async () => {
const onChange = vi.fn();
const { container } = render(<Stepper defaultValue={99} onChange={onChange} />);
const $minusBtn = container.querySelector(`${baseClass}__minus`) as HTMLElement;
fireEvent.click($minusBtn);
expect(onChange).toHaveBeenCalled();
});

it(': overlimit', async () => {
const onOverlimit = vi.fn();
const { container } = render(<Stepper defaultValue={10} max={10} onOverlimit={onOverlimit} />);
const $plusBtn = container.querySelector(`${baseClass}__plus`) as HTMLElement;
fireEvent.click($plusBtn);
expect(onOverlimit).toHaveBeenCalled();
});

it(': focus', async () => {
const onFocus = vi.fn();
const { container } = render(<Stepper defaultValue={10} max={10} onFocus={onFocus} />);
const $input = container.querySelector(`${baseClass}__input`) as HTMLElement;
fireEvent.focus($input);
expect(onFocus).toHaveBeenCalled();
});
});
});
6 changes: 0 additions & 6 deletions src/stepper/_example/base.jsx

This file was deleted.

11 changes: 11 additions & 0 deletions src/stepper/_example/base.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react';
import { Stepper } from 'tdesign-mobile-react';

export default function Base() {
return (
<div className="stepper-example">
<Stepper theme="filled" defaultValue={3}></Stepper>
<Stepper theme="filled" defaultValue={3.5} integer={false} step={0.5}></Stepper>
</div>
);
}
Loading
Loading