All files / src/complex/array SpectrumArrayItem.tsx

100% Statements 52/52
68.42% Branches 13/19
100% Functions 8/8
100% Lines 45/45

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                                                        19x 19x                   19x                       19x           19x 19x 19x   19x                                           19x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x                                                                                                                                                               19x       14x 14x   14x 14x             14x 14x 14x           14x           19x     14x   19x   19x 14x 14x   14x 14x     19x     19x               6x 6x 6x           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, { ComponentType } from 'react';
import {
  Text,
  Flex,
  ActionButton,
  View,
  DialogTrigger,
  TooltipTrigger,
  Tooltip,
  AlertDialog,
} from '@adobe/react-spectrum';
import {
  composePaths,
  ControlElement,
  findUISchema,
  getData,
  JsonFormsRendererRegistryEntry,
  JsonFormsState,
  JsonSchema,
  Resolve,
  UISchemaElement,
  UISchemaTester,
} from '@jsonforms/core';
import {
  areEqual,
  JsonFormsStateContext,
  ResolvedJsonFormsDispatch,
  withJsonFormsContext,
} from '@jsonforms/react';
import Delete from '@spectrum-icons/workflow/Delete';
import ChevronDown from '@spectrum-icons/workflow/ChevronDown';
import ChevronUp from '@spectrum-icons/workflow/ChevronUp';
 
import './SpectrumArrayItem.css';
 
export interface OwnPropsOfSpectrumArrayItem {
  index: number;
  expanded: boolean;
  path: string;
  schema: JsonSchema;
  handleExpand(index: number): () => void;
  removeItem(path: string, value: number): () => void;
  uischema: ControlElement;
  renderers?: JsonFormsRendererRegistryEntry[];
  uischemas?: {
    tester: UISchemaTester;
    uischema: UISchemaElement;
  }[];
}
 
export interface StatePropsOfSpectrumArrayItem
  extends OwnPropsOfSpectrumArrayItem {
  childLabel: string;
}
 
const SpectrumArrayItem = ({
  index,
  childLabel,
  expanded,
  removeItem,
  path,
  handleExpand,
  schema,
  uischema,
  uischemas,
  renderers,
}: StatePropsOfSpectrumArrayItem) => {
  const foundUISchema = findUISchema(uischemas, schema, uischema.scope, path);
  const childPath = composePaths(path, `${index}`);
  return (
    <View
      borderWidth='thin'
      borderColor='dark'
      borderRadius='medium'
      padding='size-250'
    >
      <View aria-selected={expanded}>
        <Flex
          direction='row'
          margin='size-50'
          justifyContent='space-between'
          alignItems='center'
        >
          <View UNSAFE_className='spectrum-array-item-number'>
            <Text>{index + 1}</Text>
          </View>
          <ActionButton
            flex='auto'
            isQuiet
            onPress={handleExpand(index)}
            aria-label={`expand-item-${childLabel}`}
          >
            <Text UNSAFE_style={{ textAlign: 'left' }}>{childLabel}</Text>
          </ActionButton>
          <View>
            <ActionButton
              onPress={handleExpand(index)}
              isQuiet={true}
              aria-label={`expand-item-${childLabel}`}
            >
              {expanded ? <ChevronUp /> : <ChevronDown />}
            </ActionButton>
            <DialogTrigger>
              <TooltipTrigger delay={0}>
                <ActionButton
                  isQuiet={true}
                  aria-label={`delete-item-${childLabel}`}
                >
                  <Delete />
                </ActionButton>
                <Tooltip>Delete</Tooltip>
              </TooltipTrigger>
              <AlertDialog
                variant='confirmation'
                title='Delete'
                primaryActionLabel='Delete'
                cancelLabel='Cancel'
                autoFocusButton='primary'
                onPrimaryAction={removeItem(path, index)}
              >
                Are you sure you wish to delete this item?
              </AlertDialog>
            </DialogTrigger>
          </View>
        </Flex>
      </View>
      {expanded ? (
        <View>
          <ResolvedJsonFormsDispatch
            schema={schema}
            uischema={foundUISchema || uischema}
            path={childPath}
            key={childPath}
            renderers={renderers}
          />
        </View>
      ) : (
        ''
      )}
    </View>
  );
};
 
/**
 * Map state to control props.
 * @param state the store's state
 * @param ownProps any own props
 * @returns {StatePropsOfControl} state props for a control
 */
export const mapStateToSpectrumArrayItemProps = (
  state: JsonFormsState,
  ownProps: OwnPropsOfSpectrumArrayItem
): StatePropsOfSpectrumArrayItem => {
  const { schema, path, index, uischema } = ownProps;
  const firstPrimitiveProp = schema.properties
    ? Object.keys(schema.properties).find((propName) => {
        const prop = schema.properties[propName];
        return (
          prop.type === 'string' ||
          prop.type === 'number' ||
          prop.type === 'integer'
        );
      })
    : undefined;
  const childPath = composePaths(path, `${index}`);
  const childData = Resolve.data(getData(state), childPath);
  const childLabel = uischema.options?.elementLabelProp
    ? childData[uischema.options.elementLabelProp]
    : firstPrimitiveProp
    ? childData[firstPrimitiveProp]
    : '';
 
  return {
    ...ownProps,
    childLabel,
  };
};
 
export const ctxToSpectrumArrayItemProps = (
  ctx: JsonFormsStateContext,
  ownProps: OwnPropsOfSpectrumArrayItem
) => mapStateToSpectrumArrayItemProps({ jsonforms: { ...ctx } }, ownProps);
 
const withContextToSpectrumArrayItemProps = (
  Component: ComponentType<StatePropsOfSpectrumArrayItem>
): ComponentType<OwnPropsOfSpectrumArrayItem> => ({
  ctx,
  props,
}: JsonFormsStateContext & StatePropsOfSpectrumArrayItem) => {
  const stateProps = ctxToSpectrumArrayItemProps(ctx, props);
  return <Component {...stateProps} />;
};
 
export const withJsonFormsSpectrumArrayItemProps = (
  Component: ComponentType<StatePropsOfSpectrumArrayItem>
): ComponentType<OwnPropsOfSpectrumArrayItem> =>
  withJsonFormsContext(
    withContextToSpectrumArrayItemProps(
      React.memo(
        Component,
        (
          prevProps: StatePropsOfSpectrumArrayItem,
          nextProps: StatePropsOfSpectrumArrayItem
        ) => {
          const { handleExpand: prevHandleExpand, removeItem: prevRemoveItem, ...restPrevProps } = prevProps
          const { handleExpand: nextHandleExpand, removeItem: nextRemoveItem, ...restNextProps } = nextProps
          return areEqual(restPrevProps, restNextProps)
        }
      )
    )
  );
 
export default withJsonFormsSpectrumArrayItemProps(SpectrumArrayItem);