All files / CustomProperties/Edit CustomPropertiesListField.js

83.33% Statements 45/54
68.75% Branches 22/32
88.88% Functions 16/18
84.31% Lines 43/51

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251                  26x                           15x   15x 15x   15x                     10x 10x 120x         15x                                 15x   30x 30x 220x 220x   110x   110x                                         220x     15x     15x                           180x                           180x                                   26x               10x 10x     10x 120x 120x   40x 40x                       120x                     10x 10x 10x 10x 120x     110x         60x 5x       5x     10x         10x                               26x               26x                                
import { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import orderBy from 'lodash/orderBy';
import { Field, useFormState } from 'react-final-form';
 
import { Button, Headline, KeyValue } from '@folio/stripes/components';
import { useKintIntl } from '../../hooks';
import CustomPropertyFormCard from './CustomPropertyFormCard';
 
const CustomPropertiesList = ({
  availableCustomProperties = [],
  input: {
    name,
    onChange,
    value
  },
  intlKey: passedIntlKey,
  intlNS: passedIntlNS,
  labelOverrides = {},
  meta: {
    pristine
  },
}) => {
  const kintIntl = useKintIntl(passedIntlKey, passedIntlNS);
 
  const [customProperties, setCustomProperties] = useState([]); // This is the list of customProperties we're currently displaying for edit.
  const [dirtying, setDirtying] = useState(false);
 
  useEffect(() => {
    // When the user loads this form, we want to init the list of customProperties
    // we're displaying (state.customProperties) with the list of customProperties that have been set
    // either via defaults or previously-saved data. Since that data may come in
    // _after_ we have mounted this component, we need to check if new data has come in
    // while the form is still marked as pristine.
    //
    // final-form unsets `pristine` after its `onChange` is called, but we also dirty
    // the component when we add/remove rows. That happens _before_ `onChange` is called,
    // so internally we use `state.dirtying` to show that we just initiated an action
    // that will result in a dirty component.
    Eif (pristine && !dirtying) {
      setCustomProperties(availableCustomProperties.filter(
        customProperty => value[customProperty.value] !== undefined
      ));
    }
  }, [availableCustomProperties, dirtying, pristine, value]);
 
  const handleDeleteCustomProperty = (customProperty, i) => {
    const currentValue = value[customProperty.value]?.[0] ?? {};
 
    const newCustomProperties = [...customProperties];
    newCustomProperties.splice(i, 1);
    setCustomProperties(newCustomProperties);
    setDirtying(true);
 
    onChange({
      ...value,
      [customProperty.value]: [{
        ...currentValue,
        _delete: true,
      }],
    });
  };
 
  const renderCustomProperties = (customPropertyType) => {
    // This is necessary to track individually since "index" will span primary/optional for a given set
    let internalPropertyCounter = 0;
    return customProperties.map((customProperty, index) => {
      Iif (customPropertyType === 'primary' && !customProperty.primary) return undefined;
      if (customPropertyType === 'optional' && customProperty.primary) return undefined;
 
      internalPropertyCounter += 1;
 
      return (
        <CustomPropertyFormCard
          key={`customPropertyField-${customProperty.value}`}
          {...{
            availableCustomProperties,
            customProperty,
            customPropertyType,
            customProperties,
            handleDeleteCustomProperty,
            index,
            internalPropertyCounter,
            intlKey: passedIntlKey,
            intlNS: passedIntlNS,
            labelOverrides,
            name,
            onChange,
            setCustomProperties,
            value
          }}
        />
      );
    }).filter(cp => cp !== undefined);
  };
 
  return (
    <>
      {
        availableCustomProperties.some((customProperty = {}) => customProperty.primary) &&
          <KeyValue
            label={
              <Headline margin="x-small" size="large" tag="h4">
                {kintIntl.formatKintMessage({
                  id: 'customProperties.primaryProperties',
                  overrideValue: labelOverrides.primaryProperties
                })}
              </Headline>
            }
            value={renderCustomProperties('primary')}
          />
      }
      {
        availableCustomProperties.some((customProperty = {}) => !customProperty.primary) &&
          <KeyValue
            label={
              <Headline margin="x-small" size="large" tag="h4">
                {kintIntl.formatKintMessage({
                  id: 'customProperties.optionalProperties',
                  overrideValue: labelOverrides.optionalProperties
                })}
              </Headline>
            }
            value={renderCustomProperties('optional')}
          />
      }
      {
        availableCustomProperties.some((customProperty = {}) => !customProperty.primary) &&
        <Button
          id="add-customproperty-btn"
          onClick={() => {
            setCustomProperties([...customProperties, {}]);
            setDirtying(true);
          }}
        >
          {kintIntl.formatKintMessage({
            id: 'customProperties.addProperty',
            overrideValue: labelOverrides.addProperty
          })}
        </Button>
      }
    </>
  );
};
 
const CustomPropertiesListField = ({
  ctx,
  customProperties,
  intlKey: passedIntlKey,
  intlNS: passedIntlNS,
  labelOverrides = {},
  ...fieldProps
}) => {
  const fieldRef = useRef();
  const kintIntl = useKintIntl(passedIntlKey, passedIntlNS);
 
  // Map customProperties to bring together the options and the definition values
  const availableCustomProperties = customProperties?.map(customProperty => {
    let options = customProperty?.category?.values;
    if (options) {
      // order by label, add notSet option afterwards
      options = orderBy(options, 'label');
      options = [
        {
          label: kintIntl.formatKintMessage({
            id: 'notSet',
            overrideValue: labelOverrides.notSet
          }),
          value: '',
        },
        ...options,
      ];
    }
 
    return {
      description: customProperty.description,
      label: customProperty.label,
      primary: customProperty.primary,
      type: customProperty.type,
      options,
      value: customProperty.name,
      defaultInternal: customProperty.defaultInternal,
    };
  });
 
  const { initialValues } = useFormState();
  const getInitialValue = () => {
    const cps = {};
    (customProperties || [])
      .filter(cp => cp.primary)
      // Change default to be an ignored customProperty.
      // This means any changes without setting the value will be ignored
      .forEach(cp => { cps[cp.name] = [{ _delete: true }]; });
 
    // IMPORTANT -- All customproperty ctx sections are adding to the same "initialValue" field
    // Ensure that we don't already have initialValues for this particular set before setting them,
    // to ensure no looping behaviour
    if (Object.keys(cps).every(key => initialValues.customProperties?.[key] !== undefined)) {
      return initialValues.customProperties;
    }
 
    // Ensure that if we already had these values in initialvalues they're not overwritten
    return ({ ...cps, ...initialValues.customProperties });
  };
 
  return (
    <Field
      {...fieldProps}
      initialValue={getInitialValue()}
      render={p => {
        return (
          <CustomPropertiesList
            ref={fieldRef}
            availableCustomProperties={availableCustomProperties}
            ctx={ctx}
            intlKey={passedIntlKey}
            intlNS={passedIntlNS}
            labelOverrides={labelOverrides}
            {...p}
          />
        );
      }}
    />
  );
};
 
CustomPropertiesListField.propTypes = {
  ctx: PropTypes.string,
  customProperties: PropTypes.arrayOf(PropTypes.object),
  intlKey: PropTypes.string,
  intlNS: PropTypes.string,
  labelOverrides: PropTypes.object,
};
 
CustomPropertiesList.propTypes = {
  availableCustomProperties: PropTypes.arrayOf(PropTypes.object),
  ctx: PropTypes.string,
  input: PropTypes.shape({
    name: PropTypes.string,
    value: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    onChange: PropTypes.func,
  }),
  intlKey: PropTypes.string,
  intlNS: PropTypes.string,
  labelOverrides: PropTypes.object,
  meta: PropTypes.object,
};
 
 
export default CustomPropertiesListField;