Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
7.9 kB
3
Indexable
Never
explain the below code and also explain what will happen when we make truncate=true.

import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { InputTextarea } from 'primereact/inputtextarea';
import PrimeWrapper from '../primeWrapper/primeWrapper';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { v4 as uuidv4 } from 'uuid';

const PrimeInputTextarea = (props) => {
    const {
        register,
        formState: { errors },
    } = useForm({
        mode: 'all',
    });
    const { id, model, validations, children, onBlur, onChange, ...rest } = props;

    const [inputValue, setInputValue] = useState(props.value || '');
    const [charsRemaining, setCharsRemaining] = useState(props.maxLength || 0);
    const [charsEntered, setCharsEntered] = useState(0);

    const calculateLength = props.calculateLength || ((str) => str.length);

    useEffect(() => {
        const initialText = props.value || '';
        const [text, remainingChars] = getStateValues(initialText);
        setInputValue(initialText); // Ensure state reflects initial value
        setCharsRemaining(remainingChars);
        setCharsEntered(text.length);
    }, [props.value]);

    const getStateValues = (text) => {
        const remainingLength = props.maxLength - calculateLength(text);
        if (remainingLength < 0 && props.truncate) {
            const truncatedText = text.slice(0, props.maxLength);
            return [truncatedText, 0]; // Return truncated text and zero remaining chars
        }
        return [text, remainingLength];
    };

    const handleInputChange = (event) => {
        const value = props.autoCapitalize ? event.target.value.toUpperCase() : event.target.value;
        const [text, remainingChars] = getStateValues(value);
        setInputValue(text); // Update component's own state
        setCharsRemaining(remainingChars);
        setCharsEntered(text.length);
        props.onChange && props.onChange({ ...event, target: { ...event.target, value: text } });
    };

    const getCharRemainingText = () => {
        const charRemainingText = props.charRemainingKey || 'You have {0} characters remaining.';
        return charRemainingText.replace(/\{0\}/g, charsRemaining);
    };

    const getCharEnteredText = () => {
        const charEnteredText = props.charEnteredKey || '{0} characters entered.';
        return charEnteredText.replace(/\{0\}/g, charsEntered);
    };

    return (
        (props.showIf !== undefined ? props.showIf : true) && (
            <span>
                <div>
                    <label className={props.labelClassName}>
                        {props.evalLangText(props.labelKey, props.label)}
                    </label>
                </div>
                <span>
                    <InputTextarea
                        id={id ? id : uuidv4() + '_inputTextarea'}
                        value={inputValue}
                        {...rest}
                        {...register(model, {
                            validate: validations,
                            onChange: (e) => {
                                handleInputChange(e);
                                if (onChange) {
                                    onChange(e);
                                }
                            },
                            onBlur: (e) => {
                                if (onBlur) {
                                    onBlur(e);
                                }
                            },
                        })}>
                        {children}
                    </InputTextarea>

                    {props.helperTextShowIf &&
                        (props.helperTextLabelKey || props.helperTextLabel) && (
                            <div>
                                <small
                                    className={classNames(
                                        'ux-input-helper-text',
                                        props.helperTextClassName,
                                    )}>
                                    {props.evalLangText(
                                        props.helperTextLabelKey,
                                        props.helperTextLabel,
                                    )}
                                </small>
                            </div>
                        )}

                    {props.showRemaining && (
                        <div>
                            <small
                                id={`${props.id}_characterRemaining`}
                                className={classNames(
                                    `noChar_${charsRemaining === 0}`,
                                    props.charRemainingClass,
                                )}>
                                {getCharRemainingText()}
                            </small>
                        </div>
                    )}

                    {props.showCurrent && (
                        <div>
                            <small
                                id={`${props.id}_charEntered`}
                                className={classNames(
                                    `noChar_${charsEntered === parseInt(props.maxLength, 10)}`,
                                    props.charEnteredClass,
                                )}>
                                {getCharEnteredText()}
                            </small>
                        </div>
                    )}

                    {errors[model]?.message && (
                        <div
                            id={`errorMessageSpanForElementWithId_${props.id}`}
                            className="p-error"
                            // role="alert"
                            //is-error="true"
                        >
                            {errors[model]?.message}
                        </div>
                    )}
                </span>
            </span>
        )
    );
};

PrimeInputTextarea.propTypes = {
    /** Define/Generate a unique id for the component */
    id: PropTypes.string,
    /** Determines if the component is hidden or shown */
    showIf: PropTypes.bool,
    /** Accepts a Content Manager key and assigns the value to the label of the input */
    label: PropTypes.string,
    labelKey: PropTypes.string,
    /** List of CSS classnames to apply on label element  */
    labelClassName: PropTypes.string,
    /** Prop that automatically capitalizes entered text */
    autoCapitalize: PropTypes.bool,
    /** Assistive component that conveys additional guidance about the field, such as how it will be used and what types in values should be provided. */
    helperTextLabel: PropTypes.string,
    /** Helper Text via Label Key for locale compatability */
    helperTextLabelKey: PropTypes.string,
    /** Helper text class name */
    helperTextClassName: PropTypes.string,
    /** Determines if helper text is hidden or shown */
    helperTextShowIf: PropTypes.bool,
    /** Determines if component truncates text to max length based on result returned by custom calculateLength function */
    truncate: PropTypes.bool,
    /** Determine whether characters remaining count will show */
    showRemaining: PropTypes.bool,
    /** Determine whether how many characters entered count will show  */
    showCurrent: PropTypes.bool,
    /** Characters Remaining WcmKey */
    charRemainingKey: PropTypes.string,
    /** Characters Entered WcmKey */
    charEnteredKey: PropTypes.string,
    /** Additional classes to add to the characters remaining text */
    charRemainingClass: PropTypes.string,
    /** Additional classes to add to the characters entered text */
    charEnteredClass: PropTypes.string,
};

PrimeInputTextarea.defaultProps = {};

export default PrimeWrapper(PrimeInputTextarea);

Leave a Comment