File size: 8,717 Bytes
3206347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import PropTypes from 'prop-types';
import * as React from 'react';
import { useController, useFormContext } from 'react-hook-form';
import { IconButton } from '@mui/material';
import FormHelperText from '@mui/material/FormHelperText';
import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';
import ClearIcon from '@mui/icons-material/Clear';
import { ActionButtonsWrapper } from './style';
import ClickAwayListener from '@mui/base/ClickAwayListener';
import InputLabel from '@mui/material/InputLabel';
import { createEditor } from 'slate';
import { Editable, ReactEditor } from 'slate-react';
import Slate from 'components/Slate';
import Element from 'components/Slate/Element';
import {
  serialize,
  deserialize,
  insertVariable,
  customizeEditor,
  resetEditor,
  overrideEditorValue,
  focusEditor,
} from 'components/Slate/utils';
import {
  FakeInput,
  InputLabelWrapper,
  ChildrenWrapper,
} from 'components/PowerInput/style';
import CustomOptions from './CustomOptions';
import { processStepWithExecutions } from 'components/PowerInput/data';
import { StepExecutionsContext } from 'contexts/StepExecutions';

function ControlledCustomAutocomplete(props) {
  const {
    defaultValue = '',
    name,
    label,
    required,
    options = [],
    dependsOn = [],
    description,
    loading,
    disabled,
    shouldUnregister,
  } = props;
  const { control, watch } = useFormContext();
  const { field, fieldState } = useController({
    control,
    name,
    defaultValue,
    rules: { required },
    shouldUnregister,
  });
  const {
    value,
    onChange: controllerOnChange,
    onBlur: controllerOnBlur,
  } = field;
  const [, forceUpdate] = React.useReducer((x) => x + 1, 0);
  const [isInitialValueSet, setInitialValue] = React.useState(false);
  const [isSingleChoice, setSingleChoice] = React.useState(undefined);
  const priorStepsWithExecutions = React.useContext(StepExecutionsContext);
  const editorRef = React.useRef(null);

  const renderElement = React.useCallback(
    (props) => <Element {...props} disabled={disabled} />,
    [disabled],
  );

  const [editor] = React.useState(() => customizeEditor(createEditor()));

  const [showVariableSuggestions, setShowVariableSuggestions] =
    React.useState(false);
  let dependsOnValues = [];
  if (dependsOn?.length) {
    dependsOnValues = watch(dependsOn);
  }

  React.useEffect(() => {
    const ref = ReactEditor.toDOMNode(editor, editor);
    resizeObserver.observe(ref);
    return () => resizeObserver.unobserve(ref);
  }, []);

  const promoteValue = () => {
    const serializedValue = serialize(editor.children);
    controllerOnChange(serializedValue);
  };

  const resizeObserver = React.useMemo(function syncCustomOptionsPosition() {
    return new ResizeObserver(() => {
      forceUpdate();
    });
  }, []);

  React.useEffect(() => {
    const hasDependencies = dependsOnValues.length;
    if (hasDependencies) {
      // Reset the field when a dependent has been updated
      resetEditor(editor);
    }
  }, dependsOnValues);

  React.useEffect(
    function updateInitialValue() {
      const hasOptions = options.length;
      const isOptionsLoaded = loading === false;
      if (!isInitialValueSet && hasOptions && isOptionsLoaded) {
        setInitialValue(true);
        const option = options.find((option) => option.value === value);
        if (option) {
          overrideEditorValue(editor, { option, focus: false });
          setSingleChoice(true);
        } else if (value) {
          setSingleChoice(false);
        }
      }
    },
    [isInitialValueSet, options, loading],
  );

  React.useEffect(() => {
    if (!showVariableSuggestions && value !== serialize(editor.children)) {
      promoteValue();
    }
  }, [showVariableSuggestions]);

  const hideSuggestionsOnShift = (event) => {
    if (event.code === 'Tab') {
      setShowVariableSuggestions(false);
    }
  };

  const handleKeyDown = (event) => {
    hideSuggestionsOnShift(event);
    if (event.code === 'Tab') {
      promoteValue();
    }
    if (isSingleChoice && event.code !== 'Tab') {
      event.preventDefault();
    }
  };

  const stepsWithVariables = React.useMemo(() => {
    return processStepWithExecutions(priorStepsWithExecutions);
  }, [priorStepsWithExecutions]);

  const handleVariableSuggestionClick = React.useCallback(
    (variable) => {
      insertVariable(editor, variable, stepsWithVariables);
    },
    [stepsWithVariables],
  );

  const handleOptionClick = React.useCallback(
    (event, option) => {
      event.stopPropagation();
      overrideEditorValue(editor, { option, focus: false });
      setShowVariableSuggestions(false);
      setSingleChoice(true);
    },
    [stepsWithVariables],
  );

  const handleClearButtonClick = (event) => {
    event.stopPropagation();
    resetEditor(editor);
    promoteValue();
    setSingleChoice(undefined);
  };

  const reset = (tabIndex) => {
    const isOptions = tabIndex === 0;
    setSingleChoice(isOptions);
    resetEditor(editor, { focus: true });
  };

  return (
    <Slate
      editor={editor}
      value={deserialize(value, options, stepsWithVariables)}
    >
      <ClickAwayListener
        mouseEvent="onMouseDown"
        onClickAway={() => setShowVariableSuggestions(false)}
      >
        {/* ref-able single child for ClickAwayListener */}
        <ChildrenWrapper style={{ width: '100%' }} data-test="power-input">
          <FakeInput
            disabled={disabled}
            tabIndex={-1}
            onClick={() => {
              focusEditor(editor);
            }}
          >
            <InputLabelWrapper>
              <InputLabel
                shrink={true}
                disabled={disabled}
                variant="outlined"
                sx={{ bgcolor: 'white', display: 'inline-block', px: 0.75 }}
              >
                {`${label}${required ? ' *' : ''}`}
              </InputLabel>
            </InputLabelWrapper>

            <Editable
              readOnly={disabled}
              style={{ width: '100%' }}
              renderElement={renderElement}
              onKeyDown={handleKeyDown}
              onFocus={() => {
                setShowVariableSuggestions(true);
              }}
              onBlur={() => {
                controllerOnBlur();
              }}
            />

            <ActionButtonsWrapper direction="row" mr={1.5}>
              {isSingleChoice && serialize(editor.children) !== '' && (
                <IconButton
                  disabled={disabled}
                  edge="end"
                  size="small"
                  tabIndex={-1}
                  onClick={handleClearButtonClick}
                >
                  <ClearIcon />
                </IconButton>
              )}
              <IconButton
                disabled={disabled}
                edge="end"
                size="small"
                tabIndex={-1}
              >
                <ArrowDropDownIcon />
              </IconButton>
            </ActionButtonsWrapper>
          </FakeInput>
          {/* ghost placer for the variables popover */}
          <div
            ref={editorRef}
            style={{
              position: 'absolute',
              right: 16,
              left: 16,
            }}
          />

          <CustomOptions
            label={label}
            open={showVariableSuggestions}
            initialTabIndex={
              isSingleChoice === undefined ? undefined : isSingleChoice ? 0 : 1
            }
            anchorEl={editorRef.current}
            data={stepsWithVariables}
            options={options}
            onSuggestionClick={handleVariableSuggestionClick}
            onOptionClick={handleOptionClick}
            onTabChange={reset}
          />

          <FormHelperText
            variant="outlined"
            error={Boolean(fieldState.isTouched && fieldState.error)}
          >
            {fieldState.isTouched
              ? fieldState.error?.message || description
              : description}
          </FormHelperText>
        </ChildrenWrapper>
      </ClickAwayListener>
    </Slate>
  );
}

ControlledCustomAutocomplete.propTypes = {
  options: PropTypes.array,
  loading: PropTypes.bool.isRequired,
  showOptionValue: PropTypes.bool,
  dependsOn: PropTypes.arrayOf(PropTypes.string),
  defaultValue: PropTypes.string,
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  type: PropTypes.string,
  required: PropTypes.bool,
  readOnly: PropTypes.bool,
  description: PropTypes.string,
  docUrl: PropTypes.string,
  clickToCopy: PropTypes.bool,
  disabled: PropTypes.bool,
  shouldUnregister: PropTypes.bool,
};

export default ControlledCustomAutocomplete;