Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

16.0 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { FocusEvent, InputHTMLAttributes, KeyboardEvent } from 'react';
import { forwardRef, useContext, useEffect, useRef, useState } from 'react';
import type { IInputProps } from '../input/Input';
import { borderLeftClassName, borderLeftRTLClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
import { ConfigContext } from '../config-provider/ConfigProvider';
import { Input } from '../input/Input';

export interface IInputNumberProps
    extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value' | 'defaultValue' | 'size'> {
    value?: number | null;
    defaultValue?: number;
    size?: IInputProps['size'];
    min?: number;
    max?: number;
    step?: number;
    precision?: number;
    formatter?: (value: string | number | undefined) => string;
    parser?: (displayValue: string | undefined) => string;
    controls?: boolean;
    className?: string;
    inputClassName?: string;
    controlsClassName?: string;
    onChange?: (value: number | null) => void;
    onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void;
    onPressEnter?: (e: KeyboardEvent<HTMLInputElement>) => void;
    allowEmpty?: boolean;
    allowClear?: boolean;
}

export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
    (
        {
            value,
            defaultValue,
            size,
            min = Number.MIN_SAFE_INTEGER,
            max = Number.MAX_SAFE_INTEGER,
            step = 1,
            precision,
            formatter,
            parser,
            controls = true,
            className,
            inputClassName,
            controlsClassName,
            disabled,
            onChange,
            onKeyDown,
            onPressEnter,
            onFocus,
            onBlur,
            allowEmpty = false,
            allowClear = false,
            ...inputProps
        },
        ref
    ) => {
        const { locale } = useContext(ConfigContext);
        const [internalValue, setInternalValue] = useState<number | null>(
            () => {
                if (value !== undefined) {
                    return value;
                }
                return defaultValue ?? null;
            }
        );
        const lastValidValueRef = useRef<number | null>(internalValue);
        const [inputValue, setInputValue] = useState<string>(() => formatValue(internalValue));
        const inputRef = useRef<HTMLInputElement>(null);

        const mergedRef = (node: HTMLInputElement | null) => {
            if (ref) {
                if (typeof ref === 'function') {
                    ref(node);
                } else {
                    ref.current = node;
                }
            }
            inputRef.current = node;
        };

        // Update internal value when value prop changes
        useEffect(() => {
            if (value !== undefined && value !== internalValue) {
                setInternalValue(value);
                lastValidValueRef.current = value;
                setInputValue(formatValue(value));
            }
        }, [value]);

        // When the internal value changes, if it's a valid value, update lastValidValue
        useEffect(() => {
            if (internalValue !== null) {
                lastValidValueRef.current = internalValue;
            }
        }, [internalValue]);

        function formatValue(val: number | null): string {
            if (val === null || val === undefined) {
                return '';
            }

            let formattedValue: string | number = val;

            // Apply precision
            if (precision !== undefined) {
                formattedValue = Number(val).toFixed(precision);
            }

            // Apply custom formatter
            if (formatter) {
                return formatter(formattedValue);
            }

            return String(formattedValue);
        }

        function parseNumberValue(val: string): number | null {
            if (!val) {
                return null;
            }

            let parsedValue = val;

            if (parser) {
                parsedValue = parser(val);
            }

            try {
                const cleanedValue = parsedValue.replace(/[^\d.-]/g, '');

                const parts = cleanedValue.split('.');
                const firstPart = parts[0];
                const secondPart = parts.length > 1 ? parts.slice(1).join('') : '';

                const normalizedValue =
                    firstPart + (secondPart ? `.${secondPart}` : '');

                const num = Number(normalizedValue);

                if (Number.isNaN(num)) {
                    return null;
                }

                let result: number;
                if (precision !== undefined) {
                    const factor = 10 ** precision;
                    const roundedNum = Math.round(num * factor) / factor;

                    const numStr = roundedNum.toString();
                    if (numStr.includes('e')) {
                        result = Number.parseFloat(roundedNum.toFixed(precision));
                    } else {
                        result = roundedNum;
                    }
                } else {
                    const numStr = num.toString();
                    if (numStr.includes('e')) {
                        result = Number.parseFloat(num.toFixed(16).replace(/\.?0+$/, ''));
                    } else {
                        result = num;
                    }
                }

                return result;
            } catch {
                return null;
            }
        }

        function clampValue(val: number | null): number | null {
            if (val === null) {
                return null;
            }

            if (max !== undefined && val > max) {
                return max;
            }
            if (min !== undefined && val < min) {
                return min;
            }

            return val;
        }

        function handleInputChange(value: string) {
            if (allowEmpty && value === '') {
                setInputValue(value);
                setInternalValue(null);
                onChange?.(null);
                return;
            }

            const parsedNumber = parseNumberValue(value);
            const parsedValue = clampValue(parsedNumber);
            const isOutOfRange = parsedNumber !== null && parsedValue !== parsedNumber;

            setInputValue(isOutOfRange ? formatValue(parsedValue) : value);
            setInternalValue(parsedValue);

            onChange?.(parsedValue);
        }

        function handleBlur(e: FocusEvent<HTMLInputElement>) {
            // Focus can move before the controlled-value effect has rendered its state updates.
            const currentValue = value !== undefined ? value : internalValue;
            // If allowEmpty is true and input is empty, do not restore the last valid value
            if (currentValue === null) {
                if (inputValue === '' && allowEmpty) {
                    // Keep the input empty
                    if (onChange) {
                        onChange(null);
                    }
                } else {
                    // If the input is not empty, restore the last valid value
                    const valueToRestore = lastValidValueRef.current;
                    setInternalValue(valueToRestore);
                    setInputValue(formatValue(valueToRestore));

                    if (onChange) {
                        onChange(valueToRestore);
                    }
                }
                onBlur?.(e);
                return;
            }

            // When blurring, format the value properly
            let valueInRange = currentValue;

            // Apply min/max constraints
            if (max !== undefined && valueInRange > max) {
                valueInRange = max;
            }
            if (min !== undefined && valueInRange < min) {
                valueInRange = min;
            }

            if (valueInRange !== currentValue) {
                setInternalValue(valueInRange);
                setInputValue(formatValue(valueInRange));

                onChange?.(valueInRange);
            } else {
                // Just ensure the display is formatted correctly
                setInternalValue(currentValue);
                setInputValue(formatValue(currentValue));
            }

            onBlur?.(e);
        }

        function handleStep(isUp: boolean) {
            if (disabled) {
                return;
            }

            const stepValue = isUp ? step : -step;

            // When internalValue is null, use 0 as the base value or the last valid value
            let currentValue: number;

            if (internalValue !== null) {
                currentValue = internalValue;
            } else if (lastValidValueRef.current !== null) {
                currentValue = lastValidValueRef.current;
            } else {
                // If there's no valid previous value, start from 0 or the minimum value
                currentValue = (min > 0) ? min : 0;
            }

            let newValue = currentValue + stepValue;

            // Apply min/max constraints
            if (max !== undefined && newValue > max) {
                newValue = max;
            }
            if (min !== undefined && newValue < min) {
                newValue = min;
            }
            // If we've hit a limit, don't change the value
            if (newValue === currentValue) {
                return;
            }
            setInternalValue(newValue);
            lastValidValueRef.current = newValue;
            setInputValue(formatValue(newValue));

            onChange?.(newValue);
        }

        // Handle key down events for arrow keys
        function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
            if (disabled) {
                return;
            }

            onKeyDown?.(e);

            if (e.key === 'ArrowUp') {
                e.preventDefault();
                handleStep(true);
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                handleStep(false);
            } else if (e.key === 'Enter') {
                onPressEnter?.(e);
            }
        }

        function handleClick(isUp: boolean) {
            if (disabled) {
                return;
            }

            handleStep(isUp);

            inputRef.current?.focus();
        }

        const incrementDisabled = disabled || (max !== undefined && internalValue !== null && internalValue >= max);
        const decrementDisabled = disabled || (min !== undefined && internalValue !== null && internalValue <= min);

        return (
            <div className={clsx('univer-inline-block', className)}>
                <div className="univer-relative univer-w-full">
                    <Input
                        inputMode={min < 0 ? 'text' : 'decimal'}
                        {...inputProps}
                        ref={mergedRef}
                        className={clsx('univer-box-border', inputClassName)}
                        size={size}
                        value={inputValue}
                        allowClear={allowClear}
                        disabled={disabled}
                        onChange={handleInputChange}
                        onFocus={onFocus}
                        onBlur={handleBlur}
                        onKeyDown={handleKeyDown}
                    />

                    {controls && (
                        <div
                            className={clsx(
                                `
                                  univer-absolute univer-right-px univer-top-px univer-flex univer-h-[calc(100%-2px)]
                                  univer-flex-col univer-overflow-hidden univer-rounded-r-md
                                  before:univer-absolute before:univer-top-1/2 before:univer-block before:univer-h-px
                                  before:univer-w-full before:-univer-translate-y-1/2 before:univer-bg-gray-200
                                  before:univer-content-[""]
                                  rtl:univer-left-px rtl:univer-right-auto rtl:univer-rounded-l-md
                                  rtl:univer-rounded-r-none
                                  dark:before:!univer-bg-gray-600
                                `,
                                borderLeftClassName,
                                borderLeftRTLClassName,
                                controlsClassName
                            )}
                        >
                            <span
                                className={clsx(
                                    `
                                      univer-box-border univer-flex univer-h-1/2 univer-w-5 univer-cursor-pointer
                                      univer-items-center univer-justify-center univer-border-none univer-bg-transparent
                                      univer-p-0 univer-transition-colors
                                      hover:univer-bg-gray-100
                                      dark:!univer-text-gray-0
                                      dark:hover:!univer-bg-gray-600
                                    `,
                                    incrementDisabled && 'univer-cursor-not-allowed univer-opacity-60'
                                )}
                                role="button"
                                aria-label={locale?.Accessibility.increment}
                                aria-disabled={incrementDisabled}
                                tabIndex={-1}
                                onMouseDown={(e) => e.preventDefault()}
                                onClick={() => {
                                    if (incrementDisabled) {
                                        return;
                                    }

                                    handleClick(true);
                                }}
                            >
                                +
                            </span>
                            <span
                                className={clsx(
                                    `
                                      univer-box-border univer-flex univer-h-1/2 univer-w-5 univer-cursor-pointer
                                      univer-items-center univer-justify-center univer-border-none univer-bg-transparent
                                      univer-p-0 univer-transition-colors
                                      hover:univer-bg-gray-100
                                      dark:!univer-text-gray-0
                                      dark:hover:!univer-bg-gray-600
                                    `,
                                    decrementDisabled && 'univer-cursor-not-allowed univer-opacity-60'
                                )}
                                role="button"
                                aria-label={locale?.Accessibility.decrement}
                                aria-disabled={decrementDisabled}
                                tabIndex={-1}
                                onMouseDown={(e) => e.preventDefault()}
                                onClick={() => {
                                    if (decrementDisabled) {
                                        return;
                                    }

                                    handleClick(false);
                                }}
                            >
                                -
                            </span>
                        </div>
                    )}
                </div>
            </div>
        );
    }
);