Лучший способ отключить редактирование строк (через ArrayInput / SimpleFormIterator)? - PullRequest
0 голосов
/ 05 мая 2020

У меня есть рабочее решение, но оно кажется немного медленным и глючным, в частности, мешает CSS анимации при отбрасывании строки. Мне интересно, есть ли у команды RA или опытных пользователей более элегантное и оптимальное решение. Я надеюсь, что в будущем компоненты ArrayInput / SimpleFormIterator смогут предоставить индекс строки и, возможно, даже опору disableEdit, чтобы упростить этот процесс.

Я понимаю, что FormDataConsumer помогает с опорой ScopedData, но это вызвало множество критических ошибок, когда было обернуто вокруг всех вводов, и обертывание по одной вокруг каждого ввода кажется плохим решением.

Вот мое усеченное решение. Любые советы приветствуются. Спасибо!

const WorkOrderLinesForm = ({ type, label = 'Items', ...props }) => {
  //...some setup with useEffects here

    return useMemo(
        () => (
            <ArrayInput
                source={type}
                label={label}
                validate={
                    ['work_order_lines_other', 'work_order_lines_suction', 'work_order_lines_discharge'].includes(type)
                        ? validateWOLines
                        : null
                }
                {...props}
            >
                <SimpleFormIterator>
                    <ConditionalLineInputs
                        type={type}
                        types={types}
                        laborItemDefault={laborItemDefault}
                        updateField={updateField}
                    />
                </SimpleFormIterator>
            </ArrayInput>
        ),
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [type, label, types, laborItemDefault, props.style]
    );
};

const getIsDisabled = ({ lines = [], id }) => {
    const currentIndex = parseInt(id.match(/[\d]/g));

    const renderDisabledInput =
        lines &&
        'undefined' !== typeof lines[currentIndex] &&
        ('undefined' !== typeof lines[currentIndex].id || 'undefined' !== typeof lines[currentIndex].original_ids);

    return renderDisabledInput;
};

const ConditionalLineInputs = ({ label, type, types, laborItemDefault, source, updateField, ...props }) => {
    const formState = useFormState();
    const { values, initialValues } = formState;
    const renderDisabledInput = useMemo(() => getIsDisabled({ lines: values[type], id: props.id }), [
        props.id,
        type,
        values,
    ]);

    const getSource = useCallback((scopedSource: string) => `${source}.${scopedSource}`, [source]);

    return useMemo(
        () => (
            <Fragment>
                <SelectInput
                    disabled={
                        renderDisabledInput
                    }
                    source={getSource('classification')}
                    label="Classification"
                    choices={classificationChoices}
                    initialValue={'work_order_lines_labor' === type ? 'Labor' : 'Part'}
                    optionValue="name"
                    validate={[required()]}
                    {...props}
                />
                <DateTimeInput
                    source={getSource('transacted_at')}
                    label="Transacted At"
                    options={{
                        format: 'MM/dd/yyyy, HH:mm',
                        clearable: true,
                    }}
                    validate={[required()]}
                    disabled={renderDisabledInput}
                    initialValue={today}
                    {...props}
                />
         // Other inputs...
                )}
            </Fragment>
        ),
        [
            getSource,
            initialValues.assigned_to_id,
            label,
            laborItemDefault,
            props,
            renderDisabledInput,
            source,
            type,
            types,
            updateField,
            values,
        ]
    );
};

1 Ответ

0 голосов
/ 07 мая 2020
• 1000 ты сделал это!
...