All files / src/components/lib InlineEditInputFactory.js

0% Statements 0/17
0% Branches 0/14
0% Functions 0/7
0% Lines 0/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                                                                                       
import { Input } from 'antd';
import React from 'react';
import { InputSuffix } from './InputSuffix/InputSuffix';
 
/**
 * Factory function to create an input / textarea component
 *
 * @param {String} component - 'input' or 'textarea'
 * @param {String} label - current value
 * @param {String} defaultLabel - default value
 * @param {Function} onSave - callback function to set value + close edit mode
 * @param {Function} setLabel - callback function to set value
 * @param {Function} onUndoClick - callback function to reset value to default
 * @param {Object} inputRef - ref to input
 * @param {Number} maxLength - max length of input
 * @returns {ReactDOM}
 */
export function InlineEditInputFactory({
  component = 'input', // or 'textarea',
  label = '',
  // initialLabel,
  defaultLabel,
  onSave = () => {},
  setLabel = () => {},
  onUndoClick = () => {},
  inputRef,
  maxLength = 255,
}) {
  const onInputSave = (e) => {
    const text = e.target.value;
    onSave(text || defaultLabel);
  };
 
  const isChanged = label !== defaultLabel;
 
  const onBlur = (e) => {
    // if undo button is clicked, don't blur immediately
    // isEditing will be false after undo button is clicked
    if (e.relatedTarget?.id === 'inline-edit__undo-button') { return; }
 
    onInputSave(e);
  };
 
  const commonProps = {
    ref: inputRef,
    value: label,
    onPressEnter: onInputSave,
    onBlur,
    onChange: (e) => setLabel(e.target.value),
    placeholder: defaultLabel,
    maxLength,
    // showCount
  };
  const inputProps = {
    className: 'inline-edit__input input-component',
    suffix: <InputSuffix isChanged={isChanged} onUndoClick={onUndoClick} />,
  };
  const textAreaProps = {
    className: 'inline-edit__input textarea-component',
    autoSize: { minRows: 1, maxRows: 120 },
  };
 
  if (component === 'textarea') {
    return (
      <div className="inline-edit__textarea-wrapper">
        <Input.TextArea {...commonProps} {...textAreaProps} />
        <InputSuffix component="textarea" isChanged={isChanged} onUndoClick={onUndoClick} />
      </div>
    );
  }
 
  if (component === 'input') { return <Input {...commonProps} {...inputProps} />; }
 
  return <Input {...commonProps} {...inputProps} />;
}