All files / src/complex SpectrumArrayControlGrid.tsx

94.64% Statements 53/56
79.17% Branches 38/48
81.82% Functions 9/11
94.34% Lines 50/53

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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280                                                      19x 19x 19x                     19x 19x                       19x 19x             19x     19x 19x 19x 19x 19x     19x 76x   19x               19x 19x             19x       21x 21x 21x 21x 21x 21x 21x 21x 21x 21x     21x 36x           21x   21x 21x 21x 21x   21x             2x                             31x                             19x 19x   34x   34x         34x 34x                                                                                                                 19x                                             19x 19x         19x                                               19x  
/*
  The MIT License
 
  Copyright (c) 2017-2019 EclipseSource Munich
  https://github.com/eclipsesource/jsonforms
 
  Copyright (c) 2020 headwire.com, Inc
  https://github.com/headwirecom/jsonforms-react-spectrum-renderers
 
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
 
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
 
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/
import React from 'react';
import startCase from 'lodash/startCase';
import {
  ArrayControlProps,
  ControlElement,
  createDefaultValue,
  Helpers,
  isPlainLabel,
  Paths,
  RankedTester,
  Resolve,
  Test,
} from '@jsonforms/core';
import { DispatchCell, withJsonFormsArrayControlProps } from '@jsonforms/react';
import {
  ActionButton,
  AlertDialog,
  DialogTrigger,
  Flex,
  Text,
  Tooltip,
  TooltipTrigger,
  View,
  Grid,
} from '@adobe/react-spectrum';
 
import Delete from '@spectrum-icons/workflow/Delete';
import {
  getUIOptions,
  getChildError,
  ArrayHeader,
  ArrayFooter,
} from './array/utils';
 
const { createLabelDescriptionFrom } = Helpers;
 
const {
  or,
  isObjectArrayControl,
  isPrimitiveArrayControl,
  rankWith,
  and,
} = Test;
 
const isTableOptionNotTrue: Test.Tester = (uischema) =>
  !uischema.options?.table;
 
export const spectrumArrayControlGridTester: RankedTester = rankWith(
  3,
  or(
    and(isObjectArrayControl, isTableOptionNotTrue),
    and(isPrimitiveArrayControl, isTableOptionNotTrue)
  )
);
 
const errorFontSize = 0.8;
const errorStyle = {
  color: 'var(--spectrum-semantic-negative-color-default)',
  lineHeight: 1.3,
  fontSize: `${errorFontSize * 100}%`,
};
 
// Calculate minimum row height so that it does not change no matter if a call has an error message or not
const rowMinHeight = `calc(var(--spectrum-alias-font-size-default) * ${errorFontSize} * ${errorStyle.lineHeight} + var(--spectrum-alias-single-line-height))`;
 
function SpectrumArrayControlGrid(props: ArrayControlProps) {
  const {
    addItem,
    uischema,
    schema,
    rootSchema,
    path,
    data,
    visible,
    label,
    childErrors,
    removeItems,
  } = props;
 
  const controlElement = uischema as ControlElement;
  const createControlElement = (key?: string): ControlElement => ({
    type: 'Control',
    label: false,
    scope: schema.type === 'object' ? `#/properties/${key}` : '#',
  });
 
  const labelObject = createLabelDescriptionFrom(controlElement, schema);
 
  const uioptions = getUIOptions(uischema, labelObject.text);
  const spacing: number[] = uischema.options?.spacing ?? [];
  const add = addItem(path, createDefaultValue(schema));
  const fields = schema.properties ? Object.keys(schema.properties) : ['items'];
 
  return (
    <View
      isHidden={visible === undefined || visible === null ? false : !visible}
    >
      <ArrayHeader
        {...uioptions}
        add={add}
        allErrorsMessages={childErrors.map((e) => e.message)}
        labelText={isPlainLabel(label) ? label : label.default}
      />
      {data && Array.isArray(data) && data.length > 0 && (
        <Grid
          columns={
            spacing.length
              ? `${fields.map((_, i) => `${spacing[i] || 1}fr`).join(' ')} 0fr`
              : `repeat(${fields.length}, 1fr) 0fr`
          }
          rows='auto'
          autoRows={`minmax(${rowMinHeight}, auto)`}
          columnGap='size-100'
        >
          {fields
            .map((prop) => (
              <View
                paddingBottom='size-50'
                justifySelf={
                  schema.properties?.[prop]?.type === 'boolean'
                    ? 'center'
                    : undefined
                }
                key={prop}
              >
                {startCase(prop)}
              </View>
            ))
            .concat(<View key='spacer' />)}
          {data.map((_, index) => {
            const childPath = Paths.compose(path, `${index}`);
            const rowCells: JSX.Element[] = schema.properties
              ? fields
                  .filter((prop) => schema.properties[prop].type !== 'array')
                  .map((prop) => {
                    const childPropPath = Paths.compose(
                      childPath,
                      prop.toString()
                    );
                    const isCheckbox =
                      schema.properties[prop].type === 'boolean';
                    return (
                      <View
                        key={childPropPath}
                        paddingStart={isCheckbox ? 'size-200' : undefined}
                      >
                        <Flex
                          direction='column'
                          width='100%'
                          alignItems={isCheckbox ? 'center' : 'start'}
                        >
                          <DispatchCell
                            schema={Resolve.schema(
                              schema,
                              `#/properties/${prop}`,
                              rootSchema
                            )}
                            uischema={
                              isCheckbox
                                ? {
                                    ...createControlElement(prop),
                                    options: { trim: true },
                                  }
                                : createControlElement(prop)
                            }
                            path={childPath + '.' + prop}
                          />
                          <View
                            UNSAFE_style={errorStyle}
                            isHidden={
                              getChildError(childErrors, childPropPath) === ''
                            }
                          >
                            <Text>
                              {getChildError(childErrors, childPropPath)}
                            </Text>
                          </View>
                        </Flex>
                      </View>
                    );
                  })
              : [
                  <View key={Paths.compose(childPath, index.toString())}>
                    <Flex direction='column' width='100%'>
                      <DispatchCell
                        schema={schema}
                        uischema={createControlElement()}
                        path={childPath}
                      />
                      <View
                        UNSAFE_style={errorStyle}
                        isHidden={getChildError(childErrors, childPath) === ''}
                      >
                        <Text>{getChildError(childErrors, childPath)}</Text>
                      </View>
                    </Flex>
                  </View>,
                ];
            return (
              <React.Fragment key={index}>
                {rowCells}
                <DeleteButton
                  index={index}
                  path={childPath}
                  removeItems={removeItems}
                />
              </React.Fragment>
            );
          })}
        </Grid>
      )}
      <ArrayFooter {...uioptions} add={add} />
    </View>
  );
}
 
function DeleteButton(props: {
  removeItems: ArrayControlProps['removeItems'];
  index: number;
  path: string;
}) {
  const { removeItems, path, index } = props;
  const remove = React.useCallback(() => {
    const p = path.substring(0, path.lastIndexOf('.'));
    removeItems(p, [index])();
  }, [removeItems, path, index]);
 
  return (
    <View key={`delete-row-${index}`}>
      <DialogTrigger>
        <TooltipTrigger delay={0}>
          <ActionButton aria-label={`Delete row at ${index}`}>
            <Delete />
          </ActionButton>
          <Tooltip>Delete</Tooltip>
        </TooltipTrigger>
        <AlertDialog
          variant='confirmation'
          title='Delete'
          primaryActionLabel='Delete'
          cancelLabel='Cancel'
          autoFocusButton='primary'
          onPrimaryAction={remove}
        >
          Are you sure you wish to delete this item?
        </AlertDialog>
      </DialogTrigger>
    </View>
  );
}
 
export default withJsonFormsArrayControlProps(SpectrumArrayControlGrid);