All files / app/modals/upsert-stacks-node-api upsert-stacks-node-api.tsx

0% Statements 0/47
0% Branches 0/19
0% Functions 0/6
0% Lines 0/42

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                                                                                                                                                                                                                                                                                 
/* eslint-disable @typescript-eslint/no-unsafe-argument */
import { TxModalFooter } from '../send-stx/send-stx-modal-layout';
import { Api } from '@api/api';
import { ErrorLabel } from '@components/error-label';
import { ErrorText } from '@components/error-text';
import { generateRandomHexString } from '@crypto/key-generation';
import { Modal } from '@modals/components/base-modal';
import { ModalHeader } from '@modals/components/modal-header';
import { ButtonGroup, Button, Box, Text, Input, color } from '@stacks/ui';
import { StacksNode } from '@store/stacks-node';
import { capitalize } from '@utils/capitalize';
import { safeAwait } from '@utils/safe-await';
import { useFormik } from 'formik';
import React, { FC, useEffect, useRef, useState } from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import * as yup from 'yup';
 
interface AddNodeSettingsProps {
  isOpen: boolean;
  selectedNode?: StacksNode;
 
  onUpdateNode(node: StacksNode): void;
 
  onClose(): void;
}
 
export const UpsertStacksNodeSettingsModal: FC<AddNodeSettingsProps> = props => {
  const { isOpen, selectedNode, onClose, onUpdateNode } = props;
 
  const [loading, setLoading] = useState(false);
 
  useHotkeys('esc', onClose, []);
  const nameFieldRef = useRef<any>();
  const form = useFormik({
    initialValues: {
      name: '',
      url: '',
    },
    validationSchema: yup.object({
      name: yup.string().max(64).required(),
      url: yup.string().url().required(),
    }),
    async onSubmit() {
      setLoading(true);
      const [error, success] = await safeAwait(new Api(form.values.url).getNodeStatus());
      Iif (error) {
        setLoading(false);
        form.setErrors({ url: 'Unable to connect to the node' });
        return;
      }
      Iif (success && success.data.status === 'ready') {
        onUpdateNode({ id: generateRandomHexString(), ...selectedNode, ...form.values });
        onClose();
        setLoading(false);
      }
    },
  });
 
  useEffect(() => {
    Iif (!selectedNode) return form.resetForm();
    void form.setValues(selectedNode);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, selectedNode]);
 
  useEffect(() => {
    Iif (isOpen) nameFieldRef.current?.focus();
    Iif (!isOpen) return;
    return () => form.resetForm();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);
 
  const changeVerb = selectedNode ? 'Edit' : 'Add';
 
  const header = <ModalHeader onSelectClose={onClose}>{changeVerb} a node</ModalHeader>;
  const footer = (
    <TxModalFooter>
      <ButtonGroup size="md">
        <Button type="button" mode="tertiary" onClick={onClose}>
          Cancel
        </Button>
        <Button type="submit" isLoading={loading}>
          {changeVerb} node
        </Button>
      </ButtonGroup>
    </TxModalFooter>
  );
  return (
    <Modal isOpen={isOpen} minWidth={['100%', '488px']} handleClose={onClose}>
      <Box as="form" onSubmit={(e: React.FormEvent<HTMLDivElement>) => form.handleSubmit(e as any)}>
        {header}
        <Box p="extra-loose">
          <Text color={color('text-body')} textStyle="body.small" lineHeight="20px">
            Enter an address for a Stacks Blockchain API that proxies a Stacks node. Before using a
            node, make sure you review and trust the host before configuring a new API.
          </Text>
          <Box mt="loose">
            <Text textStyle="body.small.medium" as="label" {...{ htmlFor: 'name' }}>
              Name
            </Text>
            <Input
              ref={nameFieldRef}
              mt="base-tight"
              id="name"
              onChange={form.handleChange}
              value={form.values.name}
              placeholder="Some API instance"
            />
            {form.touched.name && form.errors.name && (
              <ErrorLabel>
                <ErrorText>{capitalize(form.errors.name)}</ErrorText>
              </ErrorLabel>
            )}
          </Box>
          <Box mt="loose">
            <Text textStyle="body.small.medium" as="label" {...{ htmlFor: 'url' }}>
              URL
            </Text>
            <Input
              placeholder="https://api.hiro.so"
              mt="base-tight"
              id="url"
              onChange={form.handleChange}
              value={form.values.url}
            />
            {form.touched.url && form.errors.url && (
              <ErrorLabel>
                <ErrorText>{capitalize(form.errors.url)}</ErrorText>
              </ErrorLabel>
            )}
          </Box>
        </Box>
        {footer}
      </Box>
    </Modal>
  );
};