formik#useFormikContext JavaScript Examples

The following examples show how to use formik#useFormikContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UsState.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
UsState = () => {
  const showUsStates = (state) => (
    <option key={state} value={state}>
      {state}
    </option>
  );
  const UsStateSelect = (props) => <Select {...props}>{states.map(showUsStates)}</Select>;

  const [disabled, setDisabled] = useState(true);
  const {
    values: { country },
  } = useFormikContext();

  useEffect(() => {
    setDisabled(country !== 'USA');
  }, [country]);

  return (
    <Fieldset name="state" label="US State" help="Uses default select tag">
      <Field
        id="state"
        name="state"
        disabled={disabled}
        placeholder="Select your state"
        as={UsStateSelect}
      />
    </Fieldset>
  );
}
Example #2
Source File: form.js    From proof-of-humanity-web with MIT License 6 votes vote down vote up
function FocusOnFirstError({ children }) {
  const formik = useFormikContext();

  useEffect(() => {
    if (!formik.isValid && formik.submitCount > 0) {
      const firstErrorKey = getFirstErrorKey(formik.errors);
      const firstErrorElement =
        global.window.document.getElementsByName(firstErrorKey)?.[0];
      firstErrorElement?.focus();
      // The element might be visually hidden, so we scroll to its parent.
      firstErrorElement?.parentElement.scrollIntoView();
    }
  }, [formik.submitCount, formik.isValid, formik.errors]);

  return children;
}
Example #3
Source File: FileUploaderArea.js    From react-invenio-deposit with MIT License 6 votes vote down vote up
FilesListTable = ({
  isDraftRecord,
  filesList,
  deleteFile,
  decimalSizeDisplay,
}) => {
  const { setFieldValue, values: formikDraft } = useFormikContext();
  const defaultPreview = _get(formikDraft, 'files.default_preview', '');
  return (
    <Table>
      <FileTableHeader isDraftRecord={isDraftRecord} />
      <Table.Body>
        {filesList.map((file) => {
          return (
            <FileTableRow
              key={file.name}
              isDraftRecord={isDraftRecord}
              file={file}
              deleteFile={deleteFile}
              defaultPreview={defaultPreview}
              setDefaultPreview={(filename) =>
                setFieldValue('files.default_preview', filename)
              }
              decimalSizeDisplay={decimalSizeDisplay}
            />
          );
        })}
      </Table.Body>
    </Table>
  );
}
Example #4
Source File: FormField.js    From Done-With-It with MIT License 6 votes vote down vote up
function AppFormField({ name, width, ...otherProps }) {
	const {
		setFieldTouched,
		setFieldValue,
		errors,
		touched,
		values,
	} = useFormikContext();

	return (
		<>
			<TextInput
				onBlur={() => setFieldTouched(name)}
				onChangeText={(text) => setFieldValue(name, text)}
				value={values[name]}
				width={width}
				{...otherProps}
			/>
			<ErrorMessage error={errors[name]} visible={touched[name]} />
		</>
	);
}
Example #5
Source File: TermsContainer.js    From web with GNU General Public License v3.0 6 votes vote down vote up
TermsContainer = () => {
  const { setFieldValue } = useFormikContext();

  const handleClick = () => {
    setFieldValue('step', 3);
  };

  return <Terms handleClick={handleClick} />;
}
Example #6
Source File: FormikControl.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 6 votes vote down vote up
function FormikControl({
  name,
  label,
  help,
  className,
  ...params
}) {
  const {
    touched, errors, handleChange, handleBlur, setFieldError,
  } = useFormikContext();
  const fieldTouched = getIn(touched, name);
  const fieldError = getIn(errors, name);
  const handleFocus = (e) => setFieldError(e.target.name, undefined);

  return (
    <Form.Group className={className}>
      {label}
      <Form.Control
        {...params}
        name={name}
        className="pb-2"
        onChange={handleChange}
        onBlur={handleBlur}
        onFocus={handleFocus}
        isInvalid={fieldTouched && fieldError}
      />
      <FormikErrorFeedback name={name}>
        <Form.Text>{help}</Form.Text>
      </FormikErrorFeedback>
    </Form.Group>
  );
}
Example #7
Source File: FormikErrorFeedback.jsx    From frontend-app-discussions with GNU Affero General Public License v3.0 6 votes vote down vote up
function FormikErrorFeedback({ name }) {
  const {
    touched,
    errors,
  } = useFormikContext();
  const fieldTouched = getIn(touched, name);
  const fieldError = getIn(errors, name);

  return (
    <TransitionReplace>
      {fieldTouched && fieldError
        ? (
          <Form.Control.Feedback type="invalid" hasIcon={false} key={`${name}-error-feedback`}>
            {fieldError}
          </Form.Control.Feedback>
        )
        : (
          <React.Fragment key={`${name}-no-error-feedback`} />
        )}
    </TransitionReplace>
  );
}
Example #8
Source File: action-tooltip.js    From stacker.news with MIT License 6 votes vote down vote up
export default function ActionTooltip ({ children, notForm, disable, overlayText }) {
  // if we're in a form, we want to hide tooltip on submit
  let formik
  if (!notForm) {
    formik = useFormikContext()
  }
  if (disable) {
    return children
  }
  return (
    <OverlayTrigger
      placement='bottom'
      overlay={
        <Tooltip>
          {overlayText || '1 sat'}
        </Tooltip>
      }
      trigger={['hover', 'focus']}
      show={formik?.isSubmitting ? false : undefined}
    >
      {children}
    </OverlayTrigger>
  )
}
Example #9
Source File: Datepicker.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
Datepicker = ({ name, ...props }) => {
  const inputProps = { className: 'form-input w-full' };
  const { setFieldValue } = useFormikContext();

  const handleChange = (value) => {
    try {
      setFieldValue(name, dateFormat(value, 'yyyy-MM-dd'));
    } catch (err) {
      setFieldValue(name, null);
    }
  };

  return (
    <DayPickerInput
      name={name}
      inputProps={inputProps}
      onDayChange={handleChange}
      placeholder="yyyy-MM-dd"
      {...props}
    />
  );
}
Example #10
Source File: DailyData.js    From web with GNU General Public License v3.0 6 votes vote down vote up
DailyData = ({ mode, setMode }) => {
  const { dirty, submitForm, initialValues } = useFormikContext();
  const { goBack } = useNavigation();

  // Edit mode
  const handleCancel = () => setMode(MODE.VIEW);
  const handleEdit = () => setMode(MODE.EDIT);

  const createMode = useMemo(() => isCreateMode(mode), [mode]);
  const editMode = useMemo(() => isEditMode(mode), [mode]);
  const viewMode = useMemo(() => isViewMode(mode), [mode]);

  useEffect(() => {
    window.scroll(0, 0);
  }, [mode]);

  return (
    <Layout isNavigation hideBell>
      <Title>
        <T i18nKey="daily_data_text1" />
      </Title>
      {viewMode ? <Data data={initialValues} /> : <Form isEditMode={isEditMode} />}
      <TitleBox>
        <T i18nKey="daily_data_text2" />
      </TitleBox>
      <Imprint />
      <Actions>
        {(createMode || editMode) && (
          <Button onClick={submitForm} label={<T i18nKey="button_save" />} disabled={!dirty} />
        )}
        {editMode && <Button onClick={handleCancel} label={<T i18nKey="button_cancel" />} />}
        {viewMode && <Button onClick={handleEdit} label={<T i18nKey="button_edit" />} />}
        {(createMode || viewMode) && <Button onClick={() => goBack()} label={<T i18nKey="button_back" />} />}
      </Actions>
    </Layout>
  );
}
Example #11
Source File: Debug.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
Debug = () => {
  const formikContext = useFormikContext();

  return (
    <pre className="text-sm font-mono p-4 lg:px-8 bg-red-200">
      {JSON.stringify(formikContext, null, 2)}
    </pre>
  );
}
Example #12
Source File: NameContainer.js    From web with GNU General Public License v3.0 6 votes vote down vote up
NameContainer = ({ handelGoToNextStep }) => {
  const { initialValues, setFieldValue, validateForm } = useFormikContext();

  const fields = [FIELD_NAME, FIELD_TERM1];

  const handleNext = () => {
    validateForm().then(error => {
      if (!fields.some(field => Object.keys(error).includes(field))) {
        handelGoToNextStep();
      }
    });
  };

  const handleSkip = () => {
    setFieldValue(FIELD_NAME, initialValues[FIELD_NAME]);
    handelGoToNextStep();
  };

  return <Name handleNext={handleNext} handleSkip={handleSkip} />;
}
Example #13
Source File: Fieldset.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
Fieldset = ({ label, help, name, children }) => {
  const { submitCount, touched, errors } = useFormikContext();
  const hasError = get(touched, name) && get(errors, name) && submitCount > 0;

  return (
    <fieldset className={classnames(hasError && 'has-error')}>
      {label && (
        <label htmlFor={name} className="form-label w-full cursor-pointer mb-0">
          {label}
        </label>
      )}
      {children}
      <div className="form-help text-sm text-secondary first-letter">
      {hasError ? get(errors, name) : help}
      </div>
    </fieldset>
  );
}
Example #14
Source File: form.js    From stacker.news with MIT License 5 votes vote down vote up
function InputInner ({
  prepend, append, hint, showValid, onChange, overrideValue,
  innerRef, storageKeyPrefix, ...props
}) {
  const [field, meta, helpers] = props.readOnly ? [{}, {}, {}] : useField(props)
  const formik = props.readOnly ? null : useFormikContext()

  const storageKey = storageKeyPrefix ? storageKeyPrefix + '-' + props.name : undefined

  useEffect(() => {
    if (overrideValue) {
      helpers.setValue(overrideValue)
      if (storageKey) {
        localStorage.setItem(storageKey, overrideValue)
      }
    } else if (storageKey) {
      const draft = localStorage.getItem(storageKey)
      if (draft) {
        // for some reason we have to turn off validation to get formik to
        // not assume this is invalid
        helpers.setValue(draft, false)
      }
    }
  }, [overrideValue])

  return (
    <>
      <InputGroup hasValidation>
        {prepend && (
          <InputGroup.Prepend>
            {prepend}
          </InputGroup.Prepend>
        )}
        <BootstrapForm.Control
          onKeyDown={(e) => {
            if (e.keyCode === 13 && (e.metaKey || e.ctrlKey)) {
              formik?.submitForm()
            }
          }}
          ref={innerRef}
          {...field} {...props}
          onChange={(e) => {
            field.onChange(e)

            if (storageKey) {
              localStorage.setItem(storageKey, e.target.value)
            }

            if (onChange) {
              onChange(formik, e)
            }
          }}
          isInvalid={meta.touched && meta.error}
          isValid={showValid && meta.initialValue !== meta.value && meta.touched && !meta.error}
        />
        {append && (
          <InputGroup.Append>
            {append}
          </InputGroup.Append>
        )}
        <BootstrapForm.Control.Feedback type='invalid'>
          {meta.touched && meta.error}
        </BootstrapForm.Control.Feedback>
      </InputGroup>
      {hint && (
        <BootstrapForm.Text>
          {hint}
        </BootstrapForm.Text>
      )}
    </>
  )
}
Example #15
Source File: BlackoutDatesInput.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 5 votes vote down vote up
BlackoutDatesInput = ({
  value,
  type,
  label,
  fieldName,
  helpText,
  fieldClasses,
  feedbackClasses,
  formGroupClasses,
  fieldNameCommonBase,
}) => {
  const {
    handleChange, handleBlur, errors, touched,
  } = useFormikContext();

  const [inFocus, setInFocus] = useState(false);
  const fieldError = getIn(errors, `${fieldNameCommonBase}.${fieldName}`);
  const fieldTouched = getIn(touched, `${fieldNameCommonBase}.${fieldName}`);
  const isInvalidInput = Boolean(!inFocus && fieldError && fieldTouched);

  const handleFocusOut = (event) => {
    handleBlur(event);
    setInFocus(false);
  };

  return (
    <Form.Group
      controlId={`${fieldNameCommonBase}.${fieldName}`}
      className={`col ${formGroupClasses}`}
      isInvalid={isInvalidInput}
    >
      <Form.Control
        name={`${fieldNameCommonBase}.${fieldName}`}
        value={value}
        type={type}
        onChange={handleChange}
        floatingLabel={label}
        className={fieldClasses}
        onBlur={(event) => handleFocusOut(event)}
        onFocus={() => setInFocus(true)}
      />
      <FieldFeedback
        feedbackCondition={inFocus}
        errorCondition={isInvalidInput}
        errorMessage={fieldError || ''}
        feedbackMessage={helpText}
        transitionClasses="mt-1"
        feedbackClasses={feedbackClasses}
      />
    </Form.Group>
  );
}
Example #16
Source File: SubmitButton.js    From Done-With-It with MIT License 5 votes vote down vote up
function SubmitButton({ title }) {
	const { handleSubmit } = useFormikContext();

	return <Button title={title} onPress={handleSubmit} />;
}
Example #17
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
export function FormikSubmitButton(props) {
  const formik = useFormikContext();

  return <button {...props} disabled={formik.isSubmitting} type="submit" />;
}
Example #18
Source File: register-form.spec.js    From horondi_client_fe with MIT License 5 votes vote down vote up
useFormikContext.mockImplementation(() => formik);
Example #19
Source File: index.js    From realworld with MIT License 5 votes vote down vote up
export function FormikStatusErrors() {
  const formik = useFormikContext();
  return Array.isArray(formik.status) && formik.status.length
    ? formik.status.map(message => <li key={message}>{message}</li>)
    : null;
}
Example #20
Source File: FileUploaderToolbar.js    From react-invenio-deposit with MIT License 5 votes vote down vote up
FileUploaderToolbar = ({
  config,
  filesList,
  filesSize,
  filesEnabled,
  quota,
  decimalSizeDisplay,
}) => {
  const { setFieldValue } = useFormikContext();

  const handleOnChangeMetadataOnly = () => {
    setFieldValue('files.enabled', !filesEnabled)
    setFieldValue('access.files', 'public')
  }

  return (
    <>
      <Grid.Column verticalAlign="middle" floated="left" mobile={16} tablet={6} computer={6}>
        {config.canHaveMetadataOnlyRecords && (
          <List horizontal>
            <List.Item>
              <Checkbox
                label={i18next.t('Metadata-only record')}
                onChange={handleOnChangeMetadataOnly}
                disabled={filesList.length > 0}
                checked={!filesEnabled}
              />
            </List.Item>
            <List.Item>
              <Popup
                trigger={<Icon name="question circle outline" className="neutral" />}
                content={i18next.t('Disable files for this record')}
                position="top center"
              />
            </List.Item>
          </List>
        )}
      </Grid.Column>
      {filesEnabled && (
        <Grid.Column mobile={16} tablet={10} computer={10} className="storage-col">
          <Header size="tiny" className="mr-10">{i18next.t('Storage available')}</Header>
          <List horizontal floated="right">
            <List.Item>
              <Label
                {...(filesList.length === quota.maxFiles
                  ? { color: 'blue' }
                  : {})}
              >
                {i18next.t(`{{length}} out of {{maxfiles}} files`, {
                  length: filesList.length,
                  maxfiles: quota.maxFiles,
                })}
              </Label>
            </List.Item>
            <List.Item>
              <Label
                {...(humanReadableBytes(filesSize, decimalSizeDisplay) ===
                humanReadableBytes(quota.maxStorage, decimalSizeDisplay)
                  ? { color: 'blue' }
                  : {})}
              >
                {humanReadableBytes(filesSize, decimalSizeDisplay)}{' '}
                {i18next.t('out of')}{' '}
                {humanReadableBytes(quota.maxStorage, decimalSizeDisplay)}
              </Label>
            </List.Item>
          </List>
        </Grid.Column>
      )}
    </>
  );
}
Example #21
Source File: ImprintFiller.js    From web with GNU General Public License v3.0 5 votes vote down vote up
ImprintFiller = () => {
  const { goBack } = useNavigation();
  const { resetForm, values, initialValues } = useFormikContext();
  const { isCovidManual } = useHealthStats();
  const [step, setStep] = useState(1);
  const [showBackGuard, setShowBackGuard] = useState(false);

  useEffect(() => {
    if (window && window.scrollTo) {
      window.scrollTo(0, 0);
    }
  }, [step]);

  const numberOfSteps = isCovidManual ? NUMBER_OF_STEPS : NUMBER_OF_STEPS - 1;

  const processBackOnFirstStep = () => {
    if (isequal(values, initialValues)) {
      goBack();
    } else {
      setShowBackGuard(true);
    }
  };

  const onBackClick = () => {
    if (step === 1) {
      processBackOnFirstStep();
      return;
    }
    if (step === 6 && !isCovidManual) {
      setStep(prev => prev - 2);
      return;
    }
    setStep(prev => prev - 1);
  };

  const goToNextStep = () => {
    if (step === 4 && !isCovidManual) {
      setStep(prev => prev + 2);
      return;
    }
    setStep(prev => prev + 1);
  };

  const onResetForm = () => {
    resetForm();
    setStep(1);
  };

  const StepComponent = steps[step].Component;

  return (
    <>
      <Layout isGovFooter hideBell onBackClick={onBackClick}>
        <Stepper currentStep={step} numberOfSteps={numberOfSteps} />
        <StepComponent handelGoToNextStep={goToNextStep} handleResetForm={onResetForm} />
      </Layout>
      {showBackGuard && (
        <NavigationBackGuard
          title={<T i18nKey="imprint_filler_text1" />}
          description={<T i18nKey="imprint_filler_text2" />}
          handleCancel={() => setShowBackGuard(false)}
          handleConfirm={() => goBack()}
        />
      )}
    </>
  );
}
Example #22
Source File: DivisionByGroupFields.jsx    From frontend-app-course-authoring with GNU Affero General Public License v3.0 4 votes vote down vote up
DivisionByGroupFields = ({ intl }) => {
  const { validDiscussionTopics } = useContext(OpenedXConfigFormContext);
  const {
    handleChange,
    handleBlur,
    values: appConfig,
    setFieldValue,
  } = useFormikContext();
  const {
    divideDiscussionIds,
    discussionTopics,
    divideByCohorts,
    divideCourseTopicsByCohorts,
  } = appConfig;

  useEffect(() => {
    if (divideByCohorts) {
      if (!divideCourseTopicsByCohorts && _.size(discussionTopics) !== _.size(divideDiscussionIds)) {
        setFieldValue('divideDiscussionIds', discussionTopics.map(topic => topic.id));
      }
    } else {
      setFieldValue('divideDiscussionIds', []);
      setFieldValue('divideCourseTopicsByCohorts', false);
    }
  }, [
    divideByCohorts,
    divideCourseTopicsByCohorts,
  ]);

  const handleCheckBoxToggle = (event, push, remove) => {
    const { checked, value } = event.target;
    if (checked) {
      push(value);
    } else {
      remove(divideDiscussionIds.indexOf(value));
    }
  };

  const handleDivideCourseTopicsByCohortsToggle = (event) => {
    const { checked } = event.target;
    if (!checked) {
      setFieldValue('divideDiscussionIds', []);
    }
    handleChange(event);
  };

  return (
    <>
      <h5 className="text-gray-500 mb-2 mt-4">
        {intl.formatMessage(messages.divisionByGroup)}
      </h5>
      <FormSwitchGroup
        onChange={handleChange}
        className="mt-2"
        onBlur={handleBlur}
        id="divideByCohorts"
        checked={divideByCohorts}
        label={intl.formatMessage(messages.divideByCohortsLabel)}
        helpText={intl.formatMessage(messages.divideByCohortsHelp)}
      />
      <TransitionReplace>
        {divideByCohorts ? (
          <React.Fragment key="open">
            <AppConfigFormDivider />
            <FormSwitchGroup
              onChange={(event) => handleDivideCourseTopicsByCohortsToggle(event)}
              onBlur={handleBlur}
              className="ml-4 mt-3"
              id="divideCourseTopicsByCohorts"
              checked={divideCourseTopicsByCohorts}
              label={intl.formatMessage(messages.divideCourseTopicsByCohortsLabel)}
              helpText={intl.formatMessage(messages.divideCourseTopicsByCohortsHelp)}
            />
            <TransitionReplace>
              {divideCourseTopicsByCohorts ? (
                <React.Fragment key="open">
                  <FieldArray
                    name="divideDiscussionIds"
                    render={({ push, remove }) => (
                      <Form.Group className="ml-4">
                        <Form.CheckboxSet
                          name="dividedTopics"
                          onChange={(event) => handleCheckBoxToggle(event, push, remove)}
                          onBlur={handleBlur}
                          defaultValue={divideDiscussionIds}
                        >
                          {validDiscussionTopics.map((topic) => (
                            topic.name ? (
                              <Form.Checkbox
                                key={`checkbox-${topic.id}`}
                                id={`checkbox-${topic.id}`}
                                value={topic.id}
                              >
                                {topic.name}
                              </Form.Checkbox>
                            ) : null
                          ))}
                        </Form.CheckboxSet>
                      </Form.Group>
                    )}
                  />
                </React.Fragment>
              ) : (
                <React.Fragment key="closed" />
              )}
            </TransitionReplace>
          </React.Fragment>
        ) : (
          <React.Fragment key="closed" />
        )}
      </TransitionReplace>
    </>
  );
}
Example #23
Source File: GroupMultiple.js    From web with GNU General Public License v3.0 4 votes vote down vote up
GroupMultiple = ({ onBack, onNext, question }) => {
  const { setFieldValue, values } = useFormikContext();
  const [answers, setAnswers] = useState([]);

  useEffect(() => {
    const { items } = question;
    setAnswers([...items]);
  }, [question]);

  if (answers.length === 0) {
    return null;
  }

  const { text } = question;
  const otherId = `${answers[0].id}_other`;
  const answersIds = answers.map(value => value.id);

  const handleChange = itemId => {
    const current = values[itemId];
    setFieldValue(otherId, false);
    setFieldValue(itemId, current === undefined ? true : !current);
  };

  const handleSelectOther = () => {
    answersIds.forEach(value => {
      values[value] = false;
    });
    handleChange(otherId);
  };

  const someSelected = answersIds.some(value => values[value]) || values[otherId];

  const next = () => {
    const current = [...values[DIAGNOSIS_FORM_FIELDS.QUESTIONS]];
    const selectedAnswers = answersIds.map(value => {
      return {
        id: value,
        choice_id: !values[value] ? VALUE_ABSENT : VALUE_PRESENT
      };
    });
    current.push(selectedAnswers);
    setFieldValue(DIAGNOSIS_FORM_FIELDS.QUESTIONS, current);
    onNext();
  };

  const back = () => {
    answersIds.forEach(value => {
      delete values[value];
    });
    setFieldValue(otherId, undefined);
    onBack();
  };

  return (
    <Layout id="view-diagnosis" onBackClick={back} hideBell>
      <Container>
        <Title>
          <T i18nKey={text} />
        </Title>
        <FieldSet>
          {answers.map(item => {
            const { explanation, id, name } = item;
            return (
              <Checkbox
                checked={values[id]}
                content={
                  explanation && <Tooltip sticky title={<T i18nKey={name} />} content={<T i18nKey={explanation} />} />
                }
                key={id}
                label={<T i18nKey={name} />}
                name={id}
                onChange={() => handleChange(id)}
              />
            );
          })}
          <Checkbox
            checked={values[otherId]}
            label={<T i18nKey="group_multiple_text1" />}
            name={<T i18nKey="group_multiple_text1" />}
            onChange={handleSelectOther}
          />
        </FieldSet>
        <Button disabled={!someSelected} onClick={next} label={<T i18nKey="button_next" />} />
      </Container>
    </Layout>
  );
}
Example #24
Source File: Preview.js    From react-eclipsefdn-members with Eclipse Public License 2.0 4 votes vote down vote up
Preview = () => {
  const { values } = useFormikContext();

  return (
    <>
      <h1 className="fw-600 h2">
        Review and Submit your Completed Application
      </h1>
      <p>
        Please review your completed membership application form. If you would
        like to make changes to the information, please click the back button.
      </p>
      <p>
        Please click <strong>submit</strong> when ready.
      </p>
      <div className="margin-top-30">
        <h2 className="fw-600 h3">Company Information</h2>
        <div className="row">
          <div className="col-md-16">
            <div className="margin-top-25 preview-field">
              {values.organization.legalName.label}
            </div>
          </div>
          <div className="col-md-8">
            <label>twitter</label>
            <div className="preview-field">
              {values.organization.twitterHandle}
            </div>
          </div>
        </div>

        <h3 className="fw-600 h4">Address</h3>
        <div className="row margin-bottom-30">
          <div className="col-md-8">
            <label>Street</label>
            <div className="preview-field">
              {values.organization.address.street}
            </div>
          </div>
          <div className="col-md-4">
            <label>City</label>
            <div className="preview-field">
              {values.organization.address.city}
            </div>
          </div>
          <div className="col-md-4">
            <label>province/State</label>
            <div className="preview-field">
              {values.organization.address.provinceOrState}
            </div>
          </div>
          <div className="col-md-4">
            <label>Country</label>
            <div className="preview-field">
              {values.organization.address.country.label}
            </div>
          </div>
          <div className="col-md-4">
            <label>PostalCode</label>
            <div className="preview-field">
              {values.organization.address.postalCode}
            </div>
          </div>
        </div>

        <h2 className="fw-600 h3">Company Representative Contact</h2>
        <div className="row margin-bottom-30">
          <div className="col-md-6">
            <label>First Name</label>
            <div className="preview-field">
              {values.representative.company.firstName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Last Name</label>
            <div className="preview-field">
              {values.representative.company.lastName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Job Title</label>
            <div className="preview-field">
              {values.representative.company.jobtitle}
            </div>
          </div>
          <div className="col-md-6">
            <label>Email</label>
            <div className="preview-field">
              {values.representative.company.email}
            </div>
          </div>
        </div>

        <h2 className="fw-600 h3">Company Marketing Contact</h2>
        <div className="row margin-bottom-30">
          <div className="col-md-6">
            <label>First Name</label>
            <div className="preview-field">
              {values.representative.marketing.firstName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Last Name</label>
            <div className="preview-field">
              {values.representative.marketing.lastName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Job Title</label>
            <div className="preview-field">
              {values.representative.marketing.jobtitle}
            </div>
          </div>
          <div className="col-md-6">
            <label>Email</label>
            <div className="preview-field">
              {values.representative.marketing.email}
            </div>
          </div>
        </div>

        <h2 className="fw-600 h3">Company Accounting Contact</h2>
        <div className="row margin-bottom-30">
          <div className="col-md-6">
            <label>First Name</label>
            <div className="preview-field">
              {values.representative.accounting.firstName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Last Name</label>
            <div className="preview-field">
              {values.representative.accounting.lastName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Job Title</label>
            <div className="preview-field">
              {values.representative.accounting.jobtitle}
            </div>
          </div>
          <div className="col-md-6">
            <label>Email</label>
            <div className="preview-field">
              {values.representative.accounting.email}
            </div>
          </div>
        </div>

        <h2 className="fw-600 h3">Intended Membership Level</h2>
        <div className="row margin-bottom-30">
          <div className="col-md-10">
            <div className="preview-field">{values.membershipLevel.label}</div>
          </div>
        </div>

        <h2 className="fw-600 h3">Working Group(s) to Join</h2>
        {values.workingGroups.map((el, index) => (
          <React.Fragment key={index}>
            <div className="row margin-bottom-30">
              <div className="col-md-8">
                <label>Working group</label>
                <div className="preview-field">{el.workingGroup.label}</div>
              </div>
              <div className="col-md-8">
                <label>Intended Participation Level</label>
                <div className="preview-field">
                  {el.participationLevel.label}
                </div>
              </div>
              <div className="col-md-8">
                <label>Effective Date</label>
                <div className="preview-field">
                  {new Date(el.effectiveDate).toLocaleDateString()}
                </div>
              </div>

              <div className="col-md-24">
                <p className="h4 fw-600 margin-top-25">
                  The working Group Representative
                </p>
              </div>
              <div className="col-md-6">
                <label>First Name</label>
                <div className="preview-field">
                  {el.workingGroupRepresentative.firstName}
                </div>
              </div>
              <div className="col-md-6">
                <label>Last Name</label>
                <div className="preview-field">
                  {el.workingGroupRepresentative.lastName}
                </div>
              </div>
              <div className="col-md-6">
                <label>Job Title</label>
                <div className="preview-field">
                  {el.workingGroupRepresentative.jobtitle}
                </div>
              </div>
              <div className="col-md-6">
                <label>Job Title</label>
                <div className="preview-field">
                  {el.workingGroupRepresentative.email}
                </div>
              </div>
            </div>
            <hr />
          </React.Fragment>
        ))}

        <h2 className="fw-600 h3">Signing Authority</h2>
        <div className="row margin-bottom-30">
          <div className="col-md-6">
            <label>First Name</label>
            <div className="preview-field">
              {values.signingAuthorityRepresentative.firstName}
            </div>
          </div>
          <div className="col-md-6">
            <label>Last Name</label>
            <div className="preview-field">
              {values.signingAuthorityRepresentative.lastName}
            </div>
          </div>
          <div className="col-md-12">
            <label>Email</label>
            <div className="preview-field">
              {values.signingAuthorityRepresentative.email}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
Example #25
Source File: ChronicSick.js    From web with GNU General Public License v3.0 4 votes vote down vote up
ChronicSick = ({ handelGoToNextStep }) => {
  const { handleChange, setFieldValue, values } = useFormikContext();

  const handleSelectChronicSick = () => {
    setFieldValue(FIELD_IS_CHRONIC_SICK, VALUE_IS_CHRONIC_SICK_YES);
  };

  const handleSelectNoChronicSick = () => {
    setFieldValue(FIELD_IS_CHRONIC_SICK, VALUE_IS_CHRONIC_SICK_NO);
    chronicSickValues.map(field => field.field).forEach(item => setFieldValue(item, false));
  };

  const handleSetFieldValue = (field, value) => {
    setFieldValue(field, value);
  };

  const isAnyFieldSelected = () =>
    values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_NO || chronicSickValues.find(_obj => values[_obj.field]);

  const goToNextStep = () => {
    if (isAnyFieldSelected()) {
      handelGoToNextStep();
    }
  };

  const renderCheckboxes = chronicSickValues.map(({ field, description, placeholder }) => (
    <Fragment key={field}>
      <Checkbox
        checked={values[field]}
        label={
          <Label>
            <T i18nKey={field} />
          </Label>
        }
        name={field}
        onChange={() => handleSetFieldValue(field, !values[field])}
        size="big"
        value={values[field] || ''}
      />
      {values[field] && placeholder && (
        <InputWrapper>
          <TextField
            label={<T i18nKey={placeholder} />}
            name={description}
            onChange={handleChange}
            value={values[description] || ''}
          />
        </InputWrapper>
      )}
    </Fragment>
  ));

  const disabled = !isAnyFieldSelected();

  const isChronicSick = values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_YES;

  return (
    <>
      <Title>
        <T i18nKey="chronic_sick_text1" />
      </Title>
      <Wrapper>
        <FormGroup>
          <Radio
            checked={values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_NO}
            label={
              <Label>
                <T i18nKey="chronic_sick_text2" />
              </Label>
            }
            onChange={handleSelectNoChronicSick}
            name={FIELD_IS_CHRONIC_SICK}
          />
          <Radio
            checked={values[FIELD_IS_CHRONIC_SICK] === VALUE_IS_CHRONIC_SICK_YES}
            label={
              <Label>
                <T i18nKey="chronic_sick_text3" />
              </Label>
            }
            onChange={handleSelectChronicSick}
            name={FIELD_IS_CHRONIC_SICK}
          />
        </FormGroup>
      </Wrapper>

      {isChronicSick && (
        <SubContainer>
          <Description>
            <T i18nKey="chronic_sick_text4" />
          </Description>
          {renderCheckboxes}
        </SubContainer>
      )}
      <Actions>
        <Button disabled={disabled} onClick={goToNextStep} label={<T i18nKey="button_next" />} />
      </Actions>
    </>
  );
}
Example #26
Source File: FileUploader.js    From react-invenio-deposit with MIT License 4 votes vote down vote up
FileUploaderComponent = ({
  config,
  files,
  isDraftRecord,
  hasParentRecord,
  quota,
  permissions,
  record,
  uploadFiles,
  deleteFile,
  importParentFiles,
  importButtonIcon,
  importButtonText,
  isFileImportInProgress,
  decimalSizeDisplay,
  ...uiProps
}) => {
  // We extract the working copy of the draft stored as `values` in formik
  const { values: formikDraft } = useFormikContext();
  const filesEnabled = _get(formikDraft, 'files.enabled', false);
  const [warningMsg, setWarningMsg] = useState();

  const filesList = Object.values(files).map((fileState) => {
    return {
      name: fileState.name,
      size: fileState.size,
      checksum: fileState.checksum,
      links: fileState.links,
      uploadState: {
        // initial: fileState.status === UploadState.initial,
        isFailed: fileState.status === UploadState.error,
        isUploading: fileState.status === UploadState.uploading,
        isFinished: fileState.status === UploadState.finished,
        isPending: fileState.status === UploadState.pending,
      },
      progressPercentage: fileState.progressPercentage,
      cancelUploadFn: fileState.cancelUploadFn,
    };
  });

  const filesSize = filesList.reduce(
    (totalSize, file) => (totalSize += file.size),
    0
  );

  const dropzoneParams = {
    preventDropOnDocument: true,
    onDropAccepted: (acceptedFiles) => {
      const maxFileNumberReached =
        filesList.length + acceptedFiles.length > quota.maxFiles;
      const acceptedFilesSize = acceptedFiles.reduce(
        (totalSize, file) => (totalSize += file.size),
        0
      );
      const maxFileStorageReached =
        filesSize + acceptedFilesSize > quota.maxStorage;

      const filesNames = _map(filesList, 'name');
      const duplicateFiles = acceptedFiles.filter((acceptedFile) =>
        filesNames.includes(acceptedFile.name)
      );

      if (maxFileNumberReached) {
        setWarningMsg(
          <div className="content">
            <Message
              warning
              icon="warning circle"
              header="Could not upload files."
              content={`Uploading the selected files would result in ${
                filesList.length + acceptedFiles.length
              } files (max.${quota.maxFiles})`}
            />
          </div>
        );
      } else if (maxFileStorageReached) {
        setWarningMsg(
          <div className="content">
            <Message
              warning
              icon="warning circle"
              header="Could not upload files."
              content={
                <>
                  {i18next.t('Uploading the selected files would result in')}{' '}
                  {humanReadableBytes(
                    filesSize + acceptedFilesSize,
                    decimalSizeDisplay
                  )}
                  {i18next.t('but the limit is')}
                  {humanReadableBytes(quota.maxStorage, decimalSizeDisplay)}.
                </>
              }
            />
          </div>
        );
      } else if (!_isEmpty(duplicateFiles)) {
        setWarningMsg(
          <div className="content">
            <Message
              warning
              icon="warning circle"
              header={i18next.t(`The following files already exist`)}
              list={_map(duplicateFiles, 'name')}
            />
          </div>
        );
      } else {
        uploadFiles(formikDraft, acceptedFiles);
      }
    },
    multiple: true,
    noClick: true,
    noKeyboard: true,
    disabled: false,
  };

  const filesLeft = filesList.length < quota.maxFiles;
  if (!filesLeft) {
    dropzoneParams['disabled'] = true;
  }

  const displayImportBtn =
    filesEnabled && isDraftRecord && hasParentRecord && !filesList.length;

  return (
    <>
      <Grid>
        <Grid.Row className="pt-10 pb-5">
          {isDraftRecord && (
            <FileUploaderToolbar
              {...uiProps}
              config={config}
              filesEnabled={filesEnabled}
              filesList={filesList}
              filesSize={filesSize}
              isDraftRecord={isDraftRecord}
              quota={quota}
              decimalSizeDisplay={decimalSizeDisplay}
            />
          )}
        </Grid.Row>
        {displayImportBtn && (
          <Grid.Row className="pb-5 pt-5">
            <Grid.Column width={16}>
              <Message visible info>
                <div style={{ display: 'inline-block', float: 'right' }}>
                  <Button
                    type="button"
                    size="mini"
                    primary={true}
                    icon={importButtonIcon}
                    content={importButtonText}
                    onClick={() => importParentFiles()}
                    disabled={isFileImportInProgress}
                    loading={isFileImportInProgress}
                  />
                </div>
                <p style={{ marginTop: '5px', display: 'inline-block' }}>
                  <Icon name="info circle" />
                  {i18next.t('You can import files from the previous version.')}
                </p>
              </Message>
            </Grid.Column>
          </Grid.Row>
        )}
        {filesEnabled && (
          <Grid.Row className="pt-0 pb-0">
            <FileUploaderArea
              {...uiProps}
              filesList={filesList}
              dropzoneParams={dropzoneParams}
              isDraftRecord={isDraftRecord}
              filesEnabled={filesEnabled}
              deleteFile={deleteFile}
              decimalSizeDisplay={decimalSizeDisplay}
            />
          </Grid.Row>
        )}
        {isDraftRecord ? (
          <Grid.Row className="file-upload-note pt-5">
            <Grid.Column width={16}>
              <Message visible warning>
                <p>
                  <Icon name="warning sign" />
                  {i18next.t(
                    'File addition, removal or modification are not allowed after you have published your upload.'
                  )}
                </p>
              </Message>
            </Grid.Column>
          </Grid.Row>
        ) : (
          <Grid.Row className="file-upload-note pt-5">
            <Grid.Column width={16}>
              <Message info>
                <NewVersionButton
                  record={record}
                  onError={() => {}}
                  className=""
                  disabled={!permissions.can_new_version}
                  style={{ float: 'right' }}
                />
                <p style={{ marginTop: '5px', display: 'inline-block' }}>
                  <Icon name="info circle" size="large" />
                  {i18next.t(
                    'You must create a new version to add, modify or delete files.'
                  )}
                </p>
              </Message>
            </Grid.Column>
          </Grid.Row>
        )}
      </Grid>
      <Modal
        open={!!warningMsg}
        header="Warning!"
        content={warningMsg}
        onClose={() => setWarningMsg()}
        closeIcon
      />
    </>
  );
}
Example #27
Source File: TransformationBlockConfigModal.js    From kuwala with Apache License 2.0 4 votes vote down vote up
TransformationBlockConfigModal = ({isOpen}) => {
    const {toggleTransformationConfigModal} = useStoreActions(actions => actions.common);
    const {updateTransformationBlock} = useStoreActions(actions => actions.canvas);
    const {selectedElement, elements} = useStoreState(state => state.canvas);
    const [transformationBlockName, setTransformationBlockName] = useState(undefined);
    const [showToolTip, setShowToolTip] = useState(false);
    const [isTransformationBlockSaveLoading, setIsTransformationBlockSaveLoading] = useState(false);
    const [submitData, setSubmitData] = useState(null);

    useEffect( () => {
        initNodeName()
    }, [selectedElement])

    const onNameChange = (event) => {
        setTransformationBlockName(event.target.value);
    }

    const initNodeName = () => {
        if(selectedElement && selectedElement.type === TRANSFORMATION_BLOCK) {
            setTransformationBlockName(selectedElement.data.transformationBlock.name)
        }else {
            setTransformationBlockName('');
        }
    }

    const FormikWrapper = ({children}) => {
        const mapParameter = (param) => {
            let value = '';

            if (param.id === 'aggregated_columns') {
                value = [{ column: null, aggregation: null}]
            } else if (param.type === 'list[text]') {
                value = ['']
            }

            return { ...param, value }
        }
        let params = selectedElement.data.transformationCatalog.macroParameters.map(mapParameter);

        if(selectedElement.data.transformationBlock.isConfigured) {
            params = selectedElement.data.transformationBlock.macroParameters;
        }
        
        let materializeTable = selectedElement.data.transformationBlock.materializeTable;
        let tfBlockName = transformationBlockName;

        if(submitData !== null) {
            params = submitData.parameters;
            materializeTable = submitData.materializeTable;
            tfBlockName = submitData.transformationBlockName;
        }

        return (
            <Formik
                initialValues={{
                    parameters: params,
                    materializeTable: materializeTable,
                    transformationBlockName: tfBlockName,
                }}
                onSubmit={async (values)=>{
                    setSubmitData(values);
                    await upsertTransformationBlocks({ values });
                    setSubmitData(null);
                }}
                children={() => (
                    <>
                        {children}
                    </>
                )}
            />
        )
    }

    const toggleConfigModalWrapper = () => {
        toggleTransformationConfigModal();
        setSubmitData(null);
    }

    const upsertTransformationBlocks = async ({values}) => {
        setIsTransformationBlockSaveLoading(true);
        const connectedElements = getElementByIds(elements, selectedElement.data.transformationBlock.connectedSourceNodeIds);
        const connectedBlocks = connectedElements.map((el) => getEntityElementEntityBlockId(el));
        const mapParameter = (param) => {
            let value = param.value;

            if (param.type === 'date') {
                value = moment(param.value).format('YYYY-MM-DD')
            } else if (param.id === 'aggregated_columns') {
                value = param.value.map(({ column, aggregation }) => `${column}KUWALA_AGG${aggregation}`);
            }

            return { ...param, value };
        }

        if (!selectedElement.data.transformationBlock.transformationBlockEntityId) {
            const parsedValues = {
                ...values,
                parameters: values.parameters.map(mapParameter)
            }
            const data = {
                transformation_catalog_item_id: selectedElement.data.transformationCatalog.id,
                input_block_ids: connectedBlocks,
                macro_parameters: parsedValues.parameters.map((el) => {
                    return {
                        id: el.id,
                        value: el.value
                    }
                }),
                name: values.transformationBlockName,
                materialize_as_table: values.materializeTable,
                position_x: selectedElement.position.x,
                position_y: selectedElement.position.y,
            }

            try {
                const res = await createTransformationBlock(data);

                if(res.status === 200) {
                    const dto = new TransformationBlockDTO({
                        transformationCatalog: selectedElement.data.transformationCatalog,
                        name: values.transformationBlockName,
                        connectedSourceNodeIds: selectedElement.data.transformationBlock.connectedSourceNodeIds,
                        transformationBlockId: selectedElement.data.transformationBlock.transformationBlockId,
                        connectedTargetNodeIds: selectedElement.data.transformationBlock.connectedTargetNodeIds,
                        isConfigured: true,
                        macroParameters: values.parameters,
                        transformationCatalogItemId: selectedElement.data.transformationBlock.transformationCatalogItemId,
                        transformationBlockEntityId: res.data.id,
                        materializeTable: values.materializeTable,
                        columns: res.data.columns,
                        positionX: res.data.position_x,
                        positionY: res.data.position_y,
                        inputBlockIds: connectedBlocks,
                    })
                    updateTransformationBlock(dto);
                    toggleTransformationConfigModal();
                    setTransformationBlockName(values.transformationBlockName);
                }
            } catch(e){
                alert('Failed to create transformation block')
            } finally {
                setIsTransformationBlockSaveLoading(false);
            }
        } else {
            // TODO: Update data block (not implemented completely in backend)
            alert('Updating transformation blocks is currently not supported');

            setIsTransformationBlockSaveLoading(false);
        }
    }

    const ConfigBodyAndFooter = React.memo(() => {
        const { setFieldValue, submitForm, values  } = useFormikContext();

        return (
            <Fragment>
                <TransformationBlockConfigBody
                    elements={elements}
                    selectedElement={selectedElement}
                    setFieldValue={setFieldValue}
                    setShowToolTip={setShowToolTip}
                    setSubmitData={setSubmitData}
                    showToolTip={showToolTip}
                    values={values}
                />

                <TransformationBlockConfigFooter
                    isTransformationBlockSaveLoading={isTransformationBlockSaveLoading}
                    submitForm={submitForm}
                    toggleConfigModalWrapper={toggleTransformationConfigModal}
                />
            </Fragment>
        )
    });

    return (
        <Modal
            isOpen={isOpen}
            closeModalAction={toggleConfigModalWrapper}
        >
            <TransformationBlockConfigHeader
                onNameChange={onNameChange}
                selectedElement={selectedElement}
                transformationBlockName={transformationBlockName}
            />

            <FormikWrapper>
                <ConfigBodyAndFooter />
            </FormikWrapper>
        </Modal>
    )
}