@chakra-ui/react#Select TypeScript Examples

The following examples show how to use @chakra-ui/react#Select. 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: InputPanel.tsx    From openchakra with MIT License 6 votes vote down vote up
InputPanel = () => {
  const { setValueFromEvent } = useForm()

  const size = usePropsSelector('size')
  const variant = usePropsSelector('variant')

  return (
    <>
      <SizeControl label="Size" options={['sm', 'md', 'lg']} value={size} />
      <TextControl label="Value" name="value" />
      <TextControl label="Placeholder" name="placeholder" />

      <FormControl htmlFor="variant" label="Variant">
        <Select
          id="variant"
          onChange={setValueFromEvent}
          name="variant"
          size="sm"
          value={variant || ''}
        >
          <option>outline</option>
          <option>unstyled</option>
          <option>flushed</option>
          <option>filled</option>
        </Select>
      </FormControl>

      <SwitchControl label="Invalid" name="isInvalid" />
      <SwitchControl label="Read Only" name="isReadOnly" />
      <SwitchControl label="Full width" name="isFullWidth" />
    </>
  )
}
Example #2
Source File: index.tsx    From formik-chakra-ui with MIT License 6 votes vote down vote up
SelectControl: FC<SelectControlProps> = React.forwardRef(
  (props: SelectControlProps, ref: React.ForwardedRef<HTMLSelectElement>) => {
    const { name, label, selectProps, children, ...rest } = props;
    const [field] = useField(name);

    return (
      <FormControl name={name} label={label} {...rest}>
        <Select {...field} id={name} ref={ref} {...selectProps}>
          {children}
        </Select>
      </FormControl>
    );
  }
)
Example #3
Source File: ButtonPanel.tsx    From openchakra with MIT License 6 votes vote down vote up
ButtonPanel = () => {
  const { setValueFromEvent } = useForm()

  const size = usePropsSelector('size')
  const variant = usePropsSelector('variant')

  return (
    <>
      <ChildrenControl />

      <SizeControl name="size" label="Size" value={size} />

      <FormControl htmlFor="variant" label="Variant">
        <Select
          id="variant"
          onChange={setValueFromEvent}
          name="variant"
          size="sm"
          value={variant || ''}
        >
          <option>outline</option>
          <option>ghost</option>
          <option>unstyled</option>
          <option>link</option>
          <option>solid</option>
        </Select>
      </FormControl>

      <ColorsControl label="Color Scheme" name="colorScheme" />
      <IconControl label="Left icon" name="leftIcon" />
      <IconControl label="Right icon" name="rightIcon" />
    </>
  )
}
Example #4
Source File: TranslateButton.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
LanguageSelect = (extraProps: SelectProps) => {
  const { i18n } = useTranslation();

  return (
    <Select
      value={i18n.language}
      onChange={(event) => {
        i18n.changeLanguage(event.target.value);
        localStorage.setItem("rariLang", event.target.value);
      }}
      fontWeight="bold"
      width="100%"
      {...extraProps}
    >
      <option className="black-bg-option" value="en">
        English
      </option>
      <option className="black-bg-option" value="zh-CN">
        简体中文
      </option>
      <option className="black-bg-option" value="zh-TW">
        中國傳統的
      </option>
    </Select>
  );
}
Example #5
Source File: ListPanel.tsx    From openchakra with MIT License 6 votes vote down vote up
CodePanel = () => {
  const { setValueFromEvent } = useForm()
  const styleType = usePropsSelector('styleType')

  return (
    <>
      <FormControl label="Style type" htmlFor="styleType">
        <Select
          name="styleType"
          id="styleType"
          size="sm"
          value={styleType || 'md'}
          onChange={setValueFromEvent}
        >
          <option>none</option>
          <option>disc</option>
          <option>circle</option>
          <option>square</option>
          <option>decimal</option>
          <option>georgian</option>
          <option>cjk-ideographic</option>
          <option>kannada</option>
        </Select>
      </FormControl>
    </>
  )
}
Example #6
Source File: NgrokRegionField.tsx    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
NgrokRegionField = ({ helpText }: NgrokRegionFieldProps): JSX.Element => {
    const ngrokRegion: string = (useAppSelector(state => state.config.ngrok_region) ?? '');
    return (
        <FormControl>
            <FormLabel htmlFor='ngrok_region'>Ngrok Region</FormLabel>
            <Flex flexDirection='row' justifyContent='flex-start' alignItems='center'>
                <Select
                    id='ngrok_region'
                    placeholder='Select your Ngrok Region'
                    maxWidth="15em"
                    mr={3}
                    value={ngrokRegion}
                    onChange={(e) => {
                        if (!e.target.value || e.target.value.length === 0) return;
                        onSelectChange(e);
                    }}
                >
                    <option value='us'>North America</option>
                    <option value='eu'>Europe</option>
                    <option value='ap'>Asia/Pacific</option>
                    <option value='au'>Australia</option>
                    <option value='sa'>South America</option>
                    <option value='jp'>Japan</option>
                    <option value='in'>India</option>
                </Select>
            </Flex>
            <FormHelperText>
                {helpText ?? 'Select the region closest to you. This will ensure latency is at its lowest when connecting to the server.'}
            </FormHelperText>
        </FormControl>
    );
}
Example #7
Source File: Phone.tsx    From phonepare with MIT License 5 votes vote down vote up
Phone: FC<{
  index: number
  mobile?: boolean
  select?: boolean
}> = ({ index, mobile=false, select=true } ) => {
  const [ manufacturer, setManufacturer ] = useState<Manufacturer>()
  const [ selectedPhones, setSelectedPhones ] = useRecoilState(selectedPhonesState)
  const selectedPhonesData = useRecoilValue(selectedPhonesDataState)

  function updatePhoneIndex(value: string): void {
    setSelectedPhones(v => {
      const copied = [ ...v ]
      copied[index] = value
      return copied as [ string, string, string ]
    })
  }
  return <Box textAlign='left' {...( mobile ? { display: { base: 'none', lg: 'block' } } : {} )}>
    {
      select && <>
        <Text>제조사</Text>
        <Select mb={2} placeholder='선택 안함' onChange={(e) => {
          updatePhoneIndex('')
          setManufacturer(e.target.value as Manufacturer)
        }}>
          {
            Manufacturers.map((m: Manufacturer) => <option key={m} value={m}>{ManufacturersName[m]}</option>)
          }
        </Select>
        <Text>기종</Text>
        <Select placeholder='선택해주세요' value={selectedPhones[index]} onChange={(e) => updatePhoneIndex(e.target.value)}>
          {
            Phones.filter(el => manufacturer ? el.data.manufacturer === manufacturer : true).map(phone => <option key={phone.data.id} value={phone.data.id}>{!manufacturer && `[${ManufacturersName[phone.data.manufacturer]}] `}{phone.data.name}</option>)
          }
        </Select>
      </>
    }
    {
      selectedPhonesData[index] ? <Box mt={10} textAlign='center'>
        <Image mx='auto' src={selectedPhonesData[index]?.image} alt={selectedPhonesData[index]?.data.name} width={{ base: '150px', md: '350px' }} height={{ base: '200px', md: '450px' }} />
        <Text fontSize='3xl' fontWeight='bold'>{selectedPhonesData[index]?.data.name}</Text>
        <Text mt={2}>색상</Text>
        <Flex wrap='wrap' justifyContent='center'>
          {
            selectedPhonesData[index]?.colors.map(color => <ColorLabel color={color} key={color.id} />)
          }
        </Flex>
      </Box> : <Box mt={10} width={{ base: '150px', md: '350px' }} height={{ base: '200px', md: '450px' }} />
    } 
  </Box>
}
Example #8
Source File: SelectPanel.tsx    From openchakra with MIT License 5 votes vote down vote up
SelectPanel = () => {
  const { setValueFromEvent } = useForm()

  const size = usePropsSelector('size')
  const variant = usePropsSelector('variant')

  return (
    <>
      <FormControl label="Size" htmlFor="size">
        <Select
          name="size"
          id="size"
          size="sm"
          value={size || ''}
          onChange={setValueFromEvent}
        >
          <option>sm</option>
          <option>md</option>
          <option>lg</option>
        </Select>
      </FormControl>

      <IconControl label="Icon" name="icon" />
      <TextControl label="Icon size" name="iconSize" />

      <FormControl label="variant" htmlFor="variant">
        <Select
          name="variant"
          id="variant"
          size="sm"
          value={variant}
          onChange={setValueFromEvent}
        >
          <option>outline</option>
          <option>unstyled</option>
          <option>flushed</option>
          <option>filled</option>
        </Select>
      </FormControl>

      <SwitchControl label="Invalid" name="isInvalid" />
      <SwitchControl label="Read Only" name="isReadOnly" />
    </>
  )
}
Example #9
Source File: shop.tsx    From coindrop with GNU General Public License v3.0 5 votes vote down vote up
Shop: FC = () => {
    const [selectedTipCard, setSelectedTipCard] = useState("tip500");
    const green = useColorModeValue("green.500", "green.300");
    return (
        <Box>
            <NextSeo
                title="Tip Donation Payment Cards | Zero Fees | Coindrop Shop"
                description="Buy physical cards that can be used for tipping. Cards link to your Coindrop page where you can receive payments, donations, and tips with zero fees."
            />
            <Heading
                as="h1"
                size="2xl"
                textAlign="center"
                my={6}
            >
                Shop
            </Heading>
            <Box>
                <Flex
                    direction={["column", "row"]}
                    align={["center", "start"]}
                >
                    <Flex>
                        <Image src="/shop/tip-card.png" height="300" width="300" />
                    </Flex>
                    <Box ml={4}>
                        <Heading
                            my={4}
                        >
                            Tip Cards
                        </Heading>
                        <Text>
                            Accept donations and tips in the real world.
                            <br />
                            <br />
                            Cards measure 3 inches x 3 inches. Text and design can be customized.
                            <br />
                            <br />
                        </Text>
                        <Flex wrap="wrap" justify="space-around">
                            <Flex mt={2} direction="row" wrap="wrap" align="center">
                                <Text>Quantity:</Text>
                                <Box ml={2}>
                                    <Select
                                        value={selectedTipCard}
                                        onChange={(event) => {
                                            setSelectedTipCard(event.target.value);
                                        }}
                                    >
                                        <option value="tip500">500</option>
                                        <option value="tip1000">1,000</option>
                                        <option value="tip2500">2,500</option>
                                        <option value="tip5000">5,000</option>
                                        <option value="tip10000">10,000</option>
                                        <option value="tip25000">25,000</option>
                                    </Select>
                                </Box>
                            </Flex>
                            <Box>
                                <Flex mt={3} direction="row" wrap="wrap" align="center">
                                    <Text fontSize="3xl" fontWeight="bold" color={green}>
                                        ${products[selectedTipCard].price}
                                    </Text>
                                    <Text fontSize="sm" ml={2}>
                                        {` (${products[selectedTipCard].pricePer} per card)`}
                                    </Text>
                                </Flex>
                                <TipCardBuyButtons selectedId={selectedTipCard} />
                            </Box>
                        </Flex>
                    </Box>
                </Flex>
            </Box>
        </Box>
    );
}
Example #10
Source File: IntroStepper.tsx    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
HasHustler = (props: Props) => {
    const [ page, setPage ] = useState(0);
    const [ hustlerIndex, setHustlerIndex ] = useState(0);

    useEffect(() => {
        localStorage.setItem(`gameSelectedHustler_${(window.ethereum as any).selectedAddress}`, props.hustlerData[hustlerIndex].id);
    }, [hustlerIndex, props.hustlerData]);

    const pages: Array<Page> = [
        {
            heading: "Hey, seems like it's your first time here! Let's get you up and running with the basics.",
            text: `Cool, you seem to already have a hustler, let's get you and your hustler set up.
            Which hustler do you wanna play with?`,
            children: <>
                <Select onChange={(e) => setHustlerIndex(Number.parseInt(e.target.value))}>
                    {props.hustlerData.map((hustler: any, i: number) => <option key={i} value={i}>{hustler.id} {hustler.name ? " - " + hustler.name : ""}</option>)}
                </Select><br /><object type="image/svg+xml" data={props.hustlerData[hustlerIndex].svg} />
            </>,
        },
        // {
        //     heading: "Where do you wanna start out your journey?",
        //     text: `There are many cities available in the game, you can visit 'em all whenever you want but you can
        //     choose one to start with.`
        // }
    ]

    const handleNext = () => {
        pages[page].onNext && pages[page].onNext!();
        if (page === pages.length - 1)
        {
            props.manager.events.emit('game');
            return;
        }

        setPage(page + 1);
    }

    return (
        <VStack>
            <Heading>
                {pages[page].heading}
            </Heading>
            <br />
            <Text>
                {pages[page].text}
            </Text>
            {pages[page].children}
            <HStack style={footerButtonsStyle}>
                <Button onClick={() => props.manager.events.emit('game')}>
                    {page === pages.length - 1 ? "Finish" : "DGAF"}
                </Button>
                {page > 0 ? <Button onClick={() => setPage(page - 1)}>
                    Go back
                </Button> : undefined}
                {page < pages.length - 1 ? <Button onClick={handleNext}>
                    Next
                </Button> : undefined}
            </HStack>
        </VStack>
    );
}
Example #11
Source File: index.tsx    From jsonschema-editor-react with Apache License 2.0 5 votes vote down vote up
AdvancedBoolean: React.FunctionComponent<AdvancedItemStateProps> = (
	props: React.PropsWithChildren<AdvancedItemStateProps>
) => {
	const { itemStateProp } = props;

	const item = useState(itemStateProp);

	return (
		<Flex direction="column" wrap="nowrap">
			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2} htmlFor="default">
					Default:{" "}
				</FormLabel>
				<Select
					variant="outline"
					value={(item.default.value as string) ?? ""}
					size="sm"
					margin={2}
					placeholder="Choose data type"
					onChange={(evt: React.ChangeEvent<HTMLSelectElement>) => {
						item.default.set(evt.target.value);
					}}
				>
					<option key="true" value="true">
						true
					</option>
					<option key="false" value="false">
						false
					</option>
				</Select>
			</Stack>
		</Flex>
	);
}
Example #12
Source File: index.tsx    From engine with MIT License 5 votes vote down vote up
Details = () => (
  <AccordionItem>
    <h2>
      <AccordionButton _expanded={{ bg: "gray.300", color: "white" }}>
        <Box flex="1" textAlign="left">
          Details
        </Box>
        <AccordionIcon />
      </AccordionButton>
    </h2>
    <AccordionPanel pb={4}>
      <InputGroup size="sm">
        <InputLeftAddon children="Name" w="24" />
        <Input defaultValue="DoThingsFoo" />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="File path" w="24" />
        <Input defaultValue="src/producers/domain/computation.ts" />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Author" w="24" />
        <Input defaultValue="John Doe" isReadOnly />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Created on" w="24" />
        <Input defaultValue="19/02/2022" isReadOnly />
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Version" w="24" />
        <Select placeholder="Select a version">
          <option value="option1" selected>
            V2 22/02/2022 14:23 - John a2a2b227a7 (latest)
          </option>
          <option value="option2">V1 20/02/2022 13:23 Jane 9c32e516af</option>
        </Select>
      </InputGroup>
      <InputGroup size="sm">
        <InputLeftAddon children="Description" w="24" />
        <Textarea defaultValue="Does what it needs to do in terms of computation"></Textarea>
      </InputGroup>
    </AccordionPanel>
  </AccordionItem>
)
Example #13
Source File: AvatarGroupPanel.tsx    From openchakra with MIT License 5 votes vote down vote up
AvatarGroupPanel = () => {
  const { setValue, setValueFromEvent } = useForm()

  const size = usePropsSelector('size')
  const spacing = usePropsSelector('spacing')
  const max = usePropsSelector('max')

  return (
    <>
      <FormControl label="Size" htmlFor="size">
        <Select
          name="size"
          id="size"
          size="sm"
          value={size || ''}
          onChange={setValueFromEvent}
        >
          <option>2xs</option>
          <option>xs</option>
          <option>sm</option>
          <option>md</option>
          <option>lg</option>
          <option>xl</option>
          <option>2xl</option>
        </Select>
      </FormControl>

      <FormControl label="Spacing">
        <Slider
          onChange={value => setValue('spacing', value)}
          min={-3}
          max={6}
          step={1}
          defaultValue={spacing}
        >
          <SliderTrack>
            <SliderFilledTrack />
          </SliderTrack>
          <SliderThumb />
        </Slider>
      </FormControl>

      <FormControl label="max">
        <NumberInput
          size="sm"
          onChange={value => setValue('max', value)}
          value={max}
          min={1}
        >
          <NumberInputField />
          <NumberInputStepper>
            <NumberIncrementStepper />
            <NumberDecrementStepper />
          </NumberInputStepper>
        </NumberInput>
      </FormControl>
    </>
  )
}
Example #14
Source File: BaseTokenOracleConfig.tsx    From rari-dApp with GNU Affero General Public License v3.0 4 votes vote down vote up
BaseTokenOracleConfig = () => {
  const { t } = useTranslation();

  const { address } = useRari();

  const {
    mode,
    oracleData,
    uniV3BaseTokenAddress,
    uniV3BaseTokenOracle,
    setUniV3BaseTokenOracle,
    baseTokenActiveOracleName,
    setBaseTokenActiveOracleName,
  } = useAddAssetContext();

  const isUserAdmin = address === oracleData?.admin ?? false;

  // We get all oracle options.
  const options = useGetOracleOptions(oracleData, uniV3BaseTokenAddress);

  console.log("helo there", { options });
  // If we're editing the asset, show master price oracle as a default.
  // Should run only once, when component renders.
  useEffect(() => {
    if (
      mode === "Editing" &&
      baseTokenActiveOracleName === "" &&
      options &&
      options["Current_Price_Oracle"]
    )
      setBaseTokenActiveOracleName("Current_Price_Oracle");
  }, [mode, baseTokenActiveOracleName, options, setBaseTokenActiveOracleName]);

  // This will update the oracle address, after user chooses which options they want to use.
  // If option is Custom_Oracle oracle address is typed in by user, so we dont trigger this.
  useEffect(() => {
    if (
      !!baseTokenActiveOracleName &&
      baseTokenActiveOracleName !== "Custom_Oracle" &&
      options
    )
      setUniV3BaseTokenOracle(options[baseTokenActiveOracleName]);
  }, [baseTokenActiveOracleName, options, setUniV3BaseTokenOracle]);

  return (
    <>
      <Row
        crossAxisAlignment="center"
        mainAxisAlignment="center"
        width="100%"
        my={2}
      >
        <Alert status="info" width="80%" height="50px" borderRadius={5} my={1}>
          <AlertIcon />
          <Text fontSize="sm" align="center" color="black">
            {"This Uniswap V3 TWAP Oracle needs an oracle for the BaseToken."}
          </Text>
        </Alert>
      </Row>
      <Column
        mainAxisAlignment="flex-start"
        crossAxisAlignment="center"
        w="100%"
        h="100%"
      >
        <Column
          my={4}
          width="100%"
          crossAxisAlignment="center"
          mainAxisAlignment="space-between"
        >
          <Column
            mainAxisAlignment="center"
            crossAxisAlignment="center"
            height="50%"
            justifyContent="space-around"
          >
            <CTokenIcon address={uniV3BaseTokenAddress} boxSize={"50px"} />
            <SimpleTooltip
              label={t("Choose the best price oracle for this BaseToken.")}
            >
              <Text fontWeight="bold" fontSize="sm" align="center">
                {t("BaseToken Price Oracle")} <QuestionIcon ml={1} mb="4px" />
              </Text>
            </SimpleTooltip>
          </Column>

          {options ? (
            <Box alignItems="center" height="50%">
              <Select
                {...DASHBOARD_BOX_PROPS}
                ml="auto"
                my={2}
                borderRadius="7px"
                _focus={{ outline: "none" }}
                width="260px"
                placeholder={
                  baseTokenActiveOracleName.length === 0
                    ? t("Choose Oracle")
                    : baseTokenActiveOracleName.replaceAll("_", " ")
                }
                value={baseTokenActiveOracleName.toLowerCase()}
                disabled={
                  !isUserAdmin ||
                  (!oracleData?.adminOverwrite &&
                    !options.Current_Price_Oracle === null)
                }
                onChange={(event) =>
                  setBaseTokenActiveOracleName(event.target.value)
                }
              >
                {Object.entries(options).map(([key, value]) =>
                  value !== null &&
                  value !== undefined &&
                  key !== "Uniswap_V3_Oracle" &&
                  key !== "Uniswap_V2_Oracle" ? (
                    <option className="black-bg-option" value={key} key={key}>
                      {key.replaceAll("_", " ")}
                    </option>
                  ) : null
                )}
              </Select>

              {baseTokenActiveOracleName.length > 0 ? (
                <Input
                  width="100%"
                  textAlign="center"
                  height="40px"
                  variant="filled"
                  size="sm"
                  mt={2}
                  mb={2}
                  value={uniV3BaseTokenOracle}
                  onChange={(event) => {
                    const address = event.target.value;
                    setUniV3BaseTokenOracle(address);
                  }}
                  disabled={
                    baseTokenActiveOracleName === "Custom_Oracle" ? false : true
                  }
                  {...DASHBOARD_BOX_PROPS}
                  _placeholder={{ color: "#e0e0e0" }}
                  _focus={{ bg: "#121212" }}
                  _hover={{ bg: "#282727" }}
                  bg="#282727"
                />
              ) : null}
            </Box>
          ) : null}
        </Column>
      </Column>
    </>
  );
}
Example #15
Source File: ProxyServiceField.tsx    From bluebubbles-server with Apache License 2.0 4 votes vote down vote up
ProxyServiceField = ({ helpText, showAddress = true }: ProxyServiceFieldProps): JSX.Element => {
    const dispatch = useAppDispatch();
    const dnsRef = useRef(null);
    const alertRef = useRef(null);
    const proxyService: string = (useAppSelector(state => state.config.proxy_service) ?? '').toLowerCase().replace(' ', '-');
    const address: string = useAppSelector(state => state.config.server_address) ?? '';
    const port: number = useAppSelector(state => state.config.socket_port) ?? 1234;
    const [dnsModalOpen, setDnsModalOpen] = useBoolean();
    const [requiresConfirmation, confirm] = useState((): string | null => {
        return null;
    });
    return (
        <FormControl>
            <FormLabel htmlFor='proxy_service'>Proxy Service</FormLabel>
            <Flex flexDirection='row' justifyContent='flex-start' alignItems='center'>
                <Select
                    id='proxy_service'
                    placeholder='Select Proxy Service'
                    maxWidth="15em"
                    mr={3}
                    value={proxyService}
                    onChange={(e) => {
                        if (!e.target.value || e.target.value.length === 0) return;
                        onSelectChange(e);
                        if (e.target.value === 'dynamic-dns') {
                            setDnsModalOpen.on();
                        } else if (e.target.value === 'cloudflare') {
                            confirm('confirmation');
                        }
                    }}
                >
                    <option value='ngrok'>Ngrok</option>
                    <option value='cloudflare'>Cloudflare</option>
                    <option value='dynamic-dns'>Dynamic DNS</option>
                </Select>
                {(proxyService === 'dynamic-dns')
                    ? (
                        <IconButton
                            mr={3}
                            aria-label='Set address'
                            icon={<AiOutlineEdit />}
                            onClick={() => setDnsModalOpen.on()}
                        />
                    ) : null}
                {(showAddress) ? (
                    <>
                        <Text fontSize="md" color="grey">Address: {address}</Text>
                        <IconButton
                            ml={3}
                            aria-label='Copy address'
                            icon={<BiCopy />}
                            onClick={() => copyToClipboard(address)}
                        />
                    </>
                ) : null}
            </Flex>
            <FormHelperText>
                {helpText ?? 'Select a proxy service to use to make your server internet-accessible. Without one selected, your server will only be accessible on your local network'}
            </FormHelperText>

            <DynamicDnsDialog
                modalRef={dnsRef}
                onConfirm={(address) => dispatch(setConfig({ name: 'server_address', value: address }))}
                isOpen={dnsModalOpen}
                port={port as number}
                onClose={() => setDnsModalOpen.off()}
            />

            <ConfirmationDialog
                title="Notice"
                modalRef={alertRef}
                onClose={() => confirm(null)}
                body={confirmationActions[requiresConfirmation as string]?.message}
                acceptText="OK"
                declineText={null}
                onAccept={() => {
                    confirmationActions[requiresConfirmation as string].func();
                }}
                isOpen={requiresConfirmation !== null}
            />
        </FormControl>
    );
}
Example #16
Source File: FormFields.tsx    From calories-in with MIT License 4 votes vote down vote up
function FormFields({
  canEdit,
  variantsForms,
  initialVariantForm,

  dietFormStatsTree,
  ...rest
}: Props) {
  const variantFormEvents = useVariantFormEvents({ dietFormStatsTree })
  const { variantStats } = variantFormEvents
  function onSelectChange(event: ChangeEvent<HTMLSelectElement>) {
    const { value } = event.target
    variantFormEvents.onVariantFormFieldIdChange(value)
  }

  const { proteinPercent, carbsPercent, fatPercent } = useMemo(
    () => roundMacrosPercents(getMacrosPercents(variantStats)),
    [variantStats]
  )

  const screenSize = useScreenSize()
  const isLarge = screenSize >= ScreenSize.Medium

  return (
    <Box {...rest} p={4}>
      <VStack spacing={6} alignItems="stretch">
        {variantsForms.length > 1 && (
          <Select
            focusBorderColor="teal.500"
            size="md"
            defaultValue={initialVariantForm.fieldId}
            onChange={onSelectChange}
          >
            <option key="avg" value={''}>
              Average across all days
            </option>
            {variantsForms.map(variantForm => (
              <option key={variantForm.fieldId} value={variantForm.fieldId}>
                {variantForm.name}
              </option>
            ))}
          </Select>
        )}

        <Flex width="97%" justifyContent="space-between">
          <Box>
            <Stat
              type="dietEnergy"
              label="Calories"
              value={variantStats.energy}
              isLarge={isLarge}
              justifyContent="flex-start"
            />
          </Box>

          <Box>
            <Stat
              type="diet"
              label="Protein"
              value={variantStats.protein}
              isLarge={isLarge}
              justifyContent="flex-start"
              valueDetailElement={
                <StatValueDetail
                  label={`${proteinPercent}%`}
                  tooltipLabel={'% energy from protein'}
                />
              }
            />
          </Box>

          <Box>
            <Stat
              justifyContent="flex-start"
              type="diet"
              label="Carbs"
              value={variantStats.carbs}
              isLarge={isLarge}
              valueDetailElement={
                <StatValueDetail
                  label={`${carbsPercent}%`}
                  tooltipLabel={'% energy from carbs'}
                />
              }
            />
          </Box>

          <Box>
            <Stat
              justifyContent="flex-start"
              type="diet"
              label="Fat"
              value={variantStats.fat}
              isLarge={isLarge}
              valueDetailElement={
                <StatValueDetail
                  label={`${fatPercent}%`}
                  tooltipLabel={'% energy from fats'}
                />
              }
            />
          </Box>
        </Flex>

        <StatsFormFields canEdit={canEdit} showsEnergyPrecentFromFat={true} />
      </VStack>
    </Box>
  )
}
Example #17
Source File: PaymentMethodsInput.tsx    From coindrop with GNU General Public License v3.0 4 votes vote down vote up
PaymentMethodsInput: FC<Props> = ({ fieldArrayName, fields, control, register, remove, append }) => {
    const { colors } = useTheme();
    const paymentMethodsDataWatch: PaymentMethod[] = useWatch({
        control,
        name: fieldArrayName,
    });
    const [openAccordionItemIndex, setOpenAccordionItemIndex] = useState(-1);
    useEffect(() => {
        if (
            paymentMethodsDataWatch[paymentMethodsDataWatch.length - 1]?.paymentMethodId === "default-blank"
            || paymentMethodsDataWatch[paymentMethodsDataWatch.length - 1]?.address === ""
        ) {
            setOpenAccordionItemIndex(paymentMethodsDataWatch.length - 1);
        }
    }, [paymentMethodsDataWatch]);
    const containsInvalidAddress = paymentMethodsDataWatch.some(paymentMethod => !paymentMethod.address);
    const { isAddressTouched, setIsAddressTouched } = useContext(AdditionalValidation);
    // optgroup not compatible with Chakra dark mode: https://github.com/chakra-ui/chakra-ui/issues/2853
        // const optionsGroup = (category: Category) => {
        //     const optgroupLabels: Record<Category, string> = {
        //         "digital-wallet": 'Digital Wallets',
        //         "digital-asset": "Digital Assets",
        //         "subscription-platform": "Subscription Platforms",
        //     };
        //     return (
        //         <optgroup label={optgroupLabels[category]}>
        //             {paymentMethods
        //             .filter(paymentMethod => paymentMethod.category === category)
        //             .sort((a, b) => (a.id < b.id ? -1 : 1))
        //             .map(({ id, displayName }) => (
        //                 <option
        //                     key={id}
        //                     value={id}
        //                     style={{display: paymentMethodsDataWatch.map(paymentMethodDataWatch => paymentMethodDataWatch.paymentMethodId).includes(id) ? "none" : undefined }}
        //                 >
        //                     {displayName}
        //                 </option>
        //             ))}
        //         </optgroup>
        //     );
        // };
    return (
        <>
        {fields.length < 1
            ? 'No payment methods defined yet.'
        : (
            <Accordion
                allowToggle
                defaultIndex={-1}
                index={openAccordionItemIndex}
            >
                {
                fields
                    .map((item, index) => {
                    const watchedData = paymentMethodsDataWatch.find(watchedPaymentMethod => watchedPaymentMethod.id === item.id);
                    const PaymentMethodIcon = paymentMethodIcons[watchedData?.paymentMethodId];
                    return (
                        <AccordionItem
                            key={item.id}
                        >
                            <AccordionButton
                                onClick={() => {
                                    setIsAddressTouched(true);
                                    if (openAccordionItemIndex !== index && !paymentMethodsDataWatch.find(paymentMethod => paymentMethod.address === "")) {
                                        setOpenAccordionItemIndex(index);
                                    } else {
                                        setOpenAccordionItemIndex(undefined);
                                    }
                                }}
                            >
                                <Flex flex="1" textAlign="left" align="center">
                                    <Flex mr={1} align="center">
                                        {PaymentMethodIcon ? <PaymentMethodIcon mr={2} /> : <QuestionOutlineIcon mr={2} />}
                                        {paymentMethodNames[watchedData?.paymentMethodId] ?? 'Add payment method'}
                                    </Flex>
                                    {watchedData?.isPreferred && (
                                        <Flex>
                                            <StarIcon
                                                ml={2}
                                                size="16px"
                                                color={colors.yellow['400']}
                                            />
                                            <Text
                                                as="span"
                                                fontSize="xs"
                                                ml={1}
                                            >
                                                <i>Preferred</i>
                                            </Text>
                                        </Flex>
                                    )}
                                </Flex>
                                <AccordionIcon />
                            </AccordionButton>
                            <AccordionPanel pb={4} id={`accordion-panel-${watchedData.paymentMethodId}`}>
                                <input
                                    ref={register()}
                                    name={`${fieldArrayName}[${index}].id`}
                                    defaultValue={item.id}
                                    style={{display: 'none'}}
                                />
                                <Box
                                    display={paymentMethodNames[watchedData?.paymentMethodId] ? "none" : "block"}
                                    data-cy={`select-payment-method-container-${watchedData.paymentMethodId}`}
                                >
                                    <Select
                                        name={`${fieldArrayName}[${index}].paymentMethodId`}
                                        ref={register()}
                                        defaultValue={paymentMethodNames[item.paymentMethodId] ? item.paymentMethodId : 'default-blank'}
                                        isInvalid={containsInvalidAddress && isAddressTouched}
                                        onChange={() => setIsAddressTouched(false)}
                                    >
                                        <option hidden disabled value="default-blank">Select...</option>
                                        {/* optgroup not compatible with Chakra dark mode: https://github.com/chakra-ui/chakra-ui/issues/2853 */}
                                        {Object.entries(paymentMethodNames)
                                            .sort((a, b) => {
                                                const [aId] = a;
                                                const [bId] = b;
                                                return aId < bId ? -1 : 1;
                                            })
                                            .map(([paymentMethodId, paymentMethodDisplayName]) => (
                                                <option
                                                    key={paymentMethodId}
                                                    value={paymentMethodId}
                                                    style={{display: paymentMethodsDataWatch.map(paymentMethod => paymentMethod.paymentMethodId).includes(paymentMethodId) ? "none" : undefined }}
                                                >
                                                    {paymentMethodDisplayName}
                                                </option>
                                            ))}
                                    </Select>
                                </Box>
                                <Box
                                    mx={3}
                                    display={paymentMethodNames[watchedData?.paymentMethodId] ? "block" : "none"}
                                >
                                    <FormControl isRequired>
                                        <FormLabel htmlFor={`${fieldArrayName}[${index}].address`}>Address</FormLabel>
                                        <Input
                                            id={`address-input-${watchedData.paymentMethodId}`}
                                            name={`${fieldArrayName}[${index}].address`}
                                            ref={register()}
                                            defaultValue={item.address}
                                            isInvalid={containsInvalidAddress && isAddressTouched}
                                        />
                                        <Box>
                                            <Checkbox
                                                name={`${fieldArrayName}[${index}].isPreferred`}
                                                ref={register()}
                                                defaultValue={item?.isPreferred ? 1 : 0}
                                                defaultIsChecked={item?.isPreferred}
                                                mt={1}
                                                colorScheme="yellow"
                                            >
                                                Preferred
                                            </Checkbox>
                                        </Box>
                                    </FormControl>
                                </Box>
                                <Flex
                                    justify={watchedData?.paymentMethodId === 'default-blank' ? 'space-between' : 'flex-end'}
                                    mt={3}
                                    wrap="wrap"
                                    align="center"
                                >
                                    {watchedData?.paymentMethodId === 'default-blank' && (
                                        <Text fontSize="xs" ml={1}>
                                            <Link href="/blog/payment-method-request" isExternal>
                                                Payment method not listed?
                                            </Link>
                                        </Text>
                                    )}
                                    <Button
                                        onClick={() => {
                                            remove(index);
                                            setIsAddressTouched(false);
                                        }}
                                        leftIcon={<MinusIcon />}
                                        size="sm"
                                    >
                                        {'Remove '}
                                        {/* {paymentMethodNames[watchedData?.paymentMethodId]} */}
                                    </Button>
                                </Flex>
                            </AccordionPanel>
                        </AccordionItem>
                    );
                })
}
            </Accordion>
        )}
        <Flex
            justify="center"
            mt={2}
        >
            <Button
                id="add-payment-method-button"
                onClick={() => {
                    append({});
                    setIsAddressTouched(false);
                }}
                leftIcon={<AddIcon />}
                variant="ghost"
                size="sm"
                isDisabled={
                    (
                        fields.length > 0
                        && !paymentMethodNames[paymentMethodsDataWatch[paymentMethodsDataWatch.length - 1]?.paymentMethodId]
                    )
                    || containsInvalidAddress
                }
            >
                Add payment method
            </Button>
        </Flex>
        </>
    );
}
Example #18
Source File: index.tsx    From jsonschema-editor-react with Apache License 2.0 4 votes vote down vote up
AdvancedString: React.FunctionComponent<AdvancedItemStateProps> = (
	props: React.PropsWithChildren<AdvancedItemStateProps>
) => {
	const { itemStateProp } = props;

	const changeEnumOtherValue = (value: string): string[] | null => {
		const array = value.split("\n");
		if (array.length === 0 || (array.length === 1 && !array[0])) {
			return null;
		}

		return array;
	};

	const itemState = useState(itemStateProp);

	const isEnumChecked = (itemState.value as JSONSchema7).enum !== undefined;
	const enumData = (itemState.value as JSONSchema7).enum
		? (itemState.enum.value as string[])
		: [];
	const enumValue = enumData?.join("\n");

	return (
		<Flex direction="column" wrap="nowrap">
			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2}>Default: </FormLabel>
				<Input
					id="default"
					placeholder="Default value"
					value={(itemState.default.value as string) ?? ""}
					onChange={(evt: React.ChangeEvent<HTMLInputElement>) => {
						itemState.default.set(evt.target.value);
					}}
				/>
			</Stack>

			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2}>Min Length: </FormLabel>
				<NumberInput
					size="sm"
					defaultValue={Number(itemState.minLength.value)}
					onChange={(value: number | string) => {
						itemState.minLength.set(Number(value));
					}}
				>
					<NumberInputField value={Number(itemState.minLength.value)} />
					<NumberInputStepper>
						<NumberIncrementStepper />
						<NumberDecrementStepper />
					</NumberInputStepper>
				</NumberInput>
				<FormLabel mr={2}>Max Length: </FormLabel>
				<NumberInput
					size="sm"
					defaultValue={Number(itemState.maxLength.value)}
					onChange={(value: number | string) => {
						itemState.maxLength.set(Number(value));
					}}
				>
					<NumberInputField value={Number(itemState.maxLength.value)} />
					<NumberInputStepper>
						<NumberIncrementStepper />
						<NumberDecrementStepper />
					</NumberInputStepper>
				</NumberInput>
			</Stack>
			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2} htmlFor="pattern">
					Pattern:{" "}
				</FormLabel>
				<Input
					id="pattern"
					placeholder="MUST be a valid regular expression."
					value={itemState.pattern.value ?? ""}
					onChange={(evt: React.ChangeEvent<HTMLInputElement>) => {
						itemState.pattern.set(evt.target.value);
					}}
				/>
			</Stack>

			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2}>Enum: </FormLabel>
				<Checkbox
					isChecked={isEnumChecked}
					onChange={(evt: React.ChangeEvent<HTMLInputElement>) => {
						if (!evt.target.checked) {
							itemState.enum.set(none);
						} else {
							itemState.enum.set(Array<string>());
						}
					}}
				/>
				<Textarea
					value={enumValue || ""}
					isDisabled={!isEnumChecked}
					placeholder="ENUM Values - One Entry Per Line"
					onChange={(evt: React.ChangeEvent<HTMLTextAreaElement>) => {
						const update = changeEnumOtherValue(evt.target.value);
						if (update === null) {
							itemState.enum.set(none);
						} else {
							itemState.enum.set(update as string[]);
						}
					}}
				/>
			</Stack>
			<Stack
				isInline
				alignItems="center"
				justifyContent="center"
				alignContent="center"
				m={1}
			>
				<FormLabel mr={2} htmlFor="format">
					Format:{" "}
				</FormLabel>
				<Select
					variant="outline"
					value={itemState.format.value ?? ""}
					size="sm"
					margin={2}
					placeholder="Choose data type"
					onChange={(evt: React.ChangeEvent<HTMLSelectElement>) => {
						if (evt.target.value === "") {
							itemState.format.set(none);
						} else {
							itemState.format.set(evt.target.value);
						}
					}}
				>
					{StringFormat.map((item, index) => {
						return (
							<option key={String(index)} value={item.name}>
								{item.name}
							</option>
						);
					})}
				</Select>
			</Stack>
		</Flex>
	);
}
Example #19
Source File: FusePoolInfoPage.tsx    From rari-dApp with GNU Affero General Public License v3.0 4 votes vote down vote up
AssetAndOtherInfo = ({
  assets,
  poolOracle,
}: {
  assets: USDPricedFuseAsset[];
  poolOracle: string;
}) => {
  let { poolId } = useParams();

  const { fuse } = useRari();

  const { t } = useTranslation();

  const [selectedAsset, setSelectedAsset] = useState(
    assets.length > 3 ? assets[2] : assets[0]
  );
  const selectedTokenData = useTokenData(selectedAsset.underlyingToken);
  const selectedAssetUtilization =
    // @ts-ignore
    selectedAsset.totalSupply === "0"
      ? 0
      : parseFloat(
        // Use Max.min() to cap util at 100%
        Math.min(
          (selectedAsset.totalBorrow / selectedAsset.totalSupply) * 100,
          100
        ).toFixed(0)
      );

  const { data: curveData } = useQuery(
    selectedAsset.cToken + " curves",
    async () => {
      const interestRateModel = await fuse.getInterestRateModel(
        selectedAsset.cToken
      );

      if (interestRateModel === null) {
        return { borrowerRates: null, supplierRates: null };
      }

      const IRMidentity = await fuse.identifyInterestRateModelName(
        interestRateModel
      );

      const curve = convertIRMtoCurve(interestRateModel, fuse);

      return { curve, IRMidentity };
    }
  );

  const { curve: data, IRMidentity } = curveData ?? {};
  console.log({ data, IRMidentity });

  const isMobile = useIsMobile();

  const oracleIdentity = useIdentifyOracle(
    selectedAsset.oracle,
    selectedAsset.underlyingToken
  );

  // Link to MPO if asset is ETH
  const oracleAddress =
    selectedAsset.underlyingToken === ETH_TOKEN_DATA.address
      ? poolOracle
      : selectedAsset.oracle;

  return (
    <Column
      mainAxisAlignment="flex-start"
      crossAxisAlignment="flex-start"
      width="100%"
      height="100%"
    >
      <Row
        mainAxisAlignment="space-between"
        crossAxisAlignment="center"
        height="60px"
        width="100%"
        px={4}
        flexShrink={0}
      >
        <Heading size="sm" py={3}>
          {t("Pool {{num}}'s {{token}} Stats", {
            num: poolId,
            token: selectedAsset.underlyingSymbol,
          })}
        </Heading>

        <Select
          {...DASHBOARD_BOX_PROPS}
          borderRadius="7px"
          fontWeight="bold"
          width="130px"
          _focus={{ outline: "none" }}
          color={selectedTokenData?.color ?? "#FFF"}
          onChange={(event) =>
            setSelectedAsset(
              assets.find((asset) => asset.cToken === event.target.value)!
            )
          }
          value={selectedAsset.cToken}
        >
          {assets.map((asset) => (
            <option
              className="black-bg-option"
              value={asset.cToken}
              key={asset.cToken}
            >
              {asset.underlyingSymbol}
            </option>
          ))}
        </Select>
      </Row>

      <ModalDivider />

      <Box
        height="200px"
        width="100%"
        color="#000000"
        overflow="hidden"
        px={3}
        className="hide-bottom-tooltip"
        flexShrink={0}
      // bg="red"
      >
        {data ? (
          data.supplierRates === null ? (
            <Center expand color="#FFFFFF">
              <Text>
                {t("No graph is available for this asset's interest curves.")}
              </Text>
            </Center>
          ) : (
            <>
              <Chart
                options={
                  {
                    ...FuseUtilizationChartOptions,
                    annotations: {
                      points: [
                        {
                          x: selectedAssetUtilization,
                          y: data.borrowerRates[selectedAssetUtilization].y,
                          marker: {
                            size: 6,
                            fillColor: "#FFF",
                            strokeColor: "#DDDCDC",
                          },
                        },
                        {
                          x: selectedAssetUtilization,
                          y: data.supplierRates[selectedAssetUtilization].y,
                          marker: {
                            size: 6,
                            fillColor: selectedTokenData?.color ?? "#A6A6A6",
                            strokeColor: "#FFF",
                          },
                        },
                      ],
                      xaxis: [
                        {
                          x: selectedAssetUtilization,
                          label: {
                            text: t("Current Utilization"),
                            orientation: "horizontal",
                            style: {
                              background: "#121212",
                              color: "#FFF",
                            },
                          },
                        },
                      ],
                    },

                    colors: ["#FFFFFF", selectedTokenData?.color ?? "#A6A6A6"],
                  } as any
                }
                type="line"
                width="100%"
                height="100%"
                series={[
                  {
                    name: "Borrow Rate",
                    data: data.borrowerRates,
                  },
                  {
                    name: "Deposit Rate",
                    data: data.supplierRates,
                  },
                ]}
              />
              <Text
                position="absolute"
                zIndex={4}
                top={4}
                left={4}
                color="white"
              >
                {" "}
                {IRMidentity?.replace("_", " ") ?? ""}
              </Text>
            </>
          )
        ) : (
          <Center expand color="#FFFFFF">
            <Spinner />
          </Center>
        )}
      </Box>

      <ModalDivider />

      <Row
        mainAxisAlignment="space-around"
        crossAxisAlignment="center"
        height="100%"
        width="100%"
        pt={4}
        px={4}
        pb={2}
      >
        <CaptionedStat
          stat={(selectedAsset.collateralFactor / 1e16).toFixed(0) + "%"}
          statSize="lg"
          captionSize="xs"
          caption={t("Collateral Factor")}
          crossAxisAlignment="center"
          captionFirst={true}
        />

        <SimpleTooltip label={oracleIdentity}>
          <Link
            href={`https://etherscan.io/address/${oracleAddress}`}
            isExternal
            _hover={{ pointer: "cursor", color: "#21C35E" }}
          >
            <CaptionedStat
              stat={truncate(oracleIdentity, 20)}
              statSize="md"
              captionSize="xs"
              caption={t("Oracle")}
              crossAxisAlignment="center"
              captionFirst={true}
            />
          </Link>
        </SimpleTooltip>

        <CaptionedStat
          stat={(selectedAsset.reserveFactor / 1e16).toFixed(0) + "%"}
          statSize="lg"
          captionSize="xs"
          caption={t("Reserve Factor")}
          crossAxisAlignment="center"
          captionFirst={true}
        />
      </Row>

      <ModalDivider />

      <Row
        mainAxisAlignment="space-around"
        crossAxisAlignment="center"
        height="100%"
        width="100%"
        p={4}
        mt={3}
      >
          <SimpleTooltip label={`${selectedAsset.totalSupply} ${selectedAsset.underlyingSymbol}`}>
            <CaptionedStat
              stat={(selectedAsset.totalSupply / (10 ** selectedAsset.underlyingDecimals)).toFixed(2) + ` (${shortUsdFormatter(selectedAsset.totalSupplyUSD)})`}
              statSize="lg"
              captionSize="xs"
              caption={t("Total Supplied")}
              crossAxisAlignment="center"
              captionFirst={true}
            />
          </SimpleTooltip>

        {isMobile ? null : (
          <CaptionedStat
            stat={
              selectedAsset.totalSupplyUSD.toString() === "0"
                ? "0%"
                : (
                  (selectedAsset.totalBorrowUSD /
                    selectedAsset.totalSupplyUSD) *
                  100
                ).toFixed(0) + "%"
            }
            statSize="lg"
            captionSize="xs"
            caption={t("Utilization")}
            crossAxisAlignment="center"
            captionFirst={true}
          />
        )}

        <CaptionedStat
          stat={shortUsdFormatter(selectedAsset.totalBorrowUSD)}
          statSize="lg"
          captionSize="xs"
          caption={t("Total Borrowed")}
          crossAxisAlignment="center"
          captionFirst={true}
        />
      </Row>
      <ModalDivider />
    </Column>
  );
}
Example #20
Source File: InitiationFooterDopeContent.tsx    From dope-monorepo with GNU General Public License v3.0 4 votes vote down vote up
InitiationFooterDopeContent = ({
  hustlerConfig,
  setHustlerConfig,
}: InitiationFooterDopeContentProps) => {
  const { account } = useWeb3React();
  const dispatchHustler = useDispatchHustler();

  const handleDopeChange = (event: ChangeEvent<HTMLSelectElement>) => {
    const value = event.target.value;
    setHustlerConfig({ ...hustlerConfig, dopeId: value });
  };

  const getBundledDopeFromData = (data: WalletQuery) => {
    let bundledDope: Dope[] | [] = [];

    if (
      data?.wallets.edges &&
      data.wallets.edges[0]?.node?.dopes &&
      data.wallets.edges[0].node.dopes.length > 0
    ) {
      bundledDope = data.wallets.edges[0].node.dopes.filter(dopeNft => !dopeNft.opened) as Dope[];
    }
    return bundledDope;
  };

  const { data, isFetching: loading } = useWalletQuery(
    {
      where: {
        id: account,
      },
    },
    {
      enabled: !account,
      onSuccess: data => {
        const bundledDope = getBundledDopeFromData(data);
        if (bundledDope.length > 0 && isHustlerRandom()) {
          const firstDopeId = bundledDope[0].id;
          console.log(`Setting hustler ID from dope returned: ${firstDopeId}`);
          setHustlerConfig({ ...hustlerConfig, dopeId: firstDopeId });
        }
      },
    },
  );

  const goToNextStep = () => {
    dispatchHustler({
      type: 'GO_TO_APPROVE_STEP',
    });
  };

  const goToConfigureStep = () => {
    dispatchHustler({
      type: 'GO_TO_CONFIGURE_STEP',
    });
  };

  if (!account) return <NoDopeMessage />;

  if (loading) {
    return (
      <PanelFooter>
        <SpinnerMessage text="Finding DOPE in your wallet with Gear" />
      </PanelFooter>
    );
  } else if (!loading && !data?.wallets.edges![0]?.node?.dopes) {
    return <NoDopeMessage />;
  } else {
    // Prevent controls from showing if no qualified DOPE
    const bundledDope = data && getBundledDopeFromData(data);

    if (bundledDope && bundledDope.length === 0) return <NoDopeMessage />;
    return (
      <div>
        <SubPanelForm>
          <Select size="sm" onChange={handleDopeChange} value={hustlerConfig.dopeId}>
            <option disabled>YOUR DOPE</option>
            {bundledDope &&
              bundledDope.map(dopeNft => (
                <option key={dopeNft.id} value={dopeNft.id}>
                  DOPE NFT #{dopeNft.id}
                </option>
              ))}
          </Select>
        </SubPanelForm>
        <PanelFooter>
          <div>
            <Button onClick={goToConfigureStep}>Configure</Button>
            <Button
              onClick={() => randomizeHustlerAttributes(hustlerConfig.dopeId, setHustlerConfig)}
            >
              Randomize
            </Button>
          </div>
          <Button variant="primary" onClick={goToNextStep}>
            ? Next
          </Button>
        </PanelFooter>
      </div>
    );
  }
}
Example #21
Source File: GradientControl.tsx    From openchakra with MIT License 4 votes vote down vote up
GradientControl = (props: GradientControlPropsType) => {
  const { setValue } = useForm()
  const [gradientColor, setGradientColor] = useState(['green.200'])
  const [directionValue, setDirectionValue] = useState('to right')
  const gradient = usePropsSelector(props.name)

  const choices = props.options

  const updateValue = () => {
    if (
      gradientColor.length >= 2 &&
      gradient !== `linear(${directionValue}, ${gradientColor.toString()})`
    ) {
      setValue(
        props.name,
        `linear(${directionValue}, ${gradientColor.toString()})`,
      )
    }
  }

  useEffect(() => {
    updateValue()
    //eslint-disable-next-line
  }, [directionValue, gradientColor])

  useEffect(() => {
    if (gradient === '' || gradient === null) {
      setGradientColor(['green.200'])
    } else {
      try {
        let gradientValue = gradient.split('(')[1]
        let actualDirection = gradientValue.split(',')[0]
        let actualColor = gradientValue.split(',')
        let colorArray = actualColor.splice(1, actualColor.length)
        colorArray[colorArray.length - 1] = colorArray[
          colorArray.length - 1
        ].split(')')[0]
        colorArray[0] = colorArray[0].split(' ')[1]
        setDirectionValue(actualDirection)
        setGradientColor(colorArray)
      } catch (e) {
        console.log(e)
      }
    }
  }, [gradient])

  const updateGradient = async (value: string, index: number) => {
    let colorCopy = [...gradientColor]
    colorCopy[index] = value
    setGradientColor(colorCopy)
  }

  const removeGradient = async (index: number) => {
    let colorCopy = [...gradientColor]
    colorCopy.splice(index, 1)
    if (colorCopy.length >= 2) {
      setGradientColor(colorCopy)
    } else {
      setGradientColor(colorCopy)
      setValue(props.name, null)
    }
  }

  return (
    <>
      <FormControl label={props.label}>
        <Select
          size="sm"
          id={directionValue || 'direction'}
          name={directionValue || 'direction'}
          value={directionValue || ''}
          onChange={(value: React.ChangeEvent<HTMLSelectElement>) => {
            setDirectionValue(value.target.value)
            gradientColor.length >= 2 &&
              setValue(
                props.name,
                `linear(${directionValue}, ${gradientColor.toString()})`,
              )
          }}
        >
          {choices?.map((choice: string) => (
            <option key={choice}>{choice}</option>
          ))}
        </Select>
      </FormControl>

      {gradientColor.map((e, i) => (
        <Box textAlign="right" mt={3} key={i}>
          {i >= 1 && (
            <IconButton
              onClick={() => removeGradient(i)}
              variant="ghost"
              marginRight={2}
              size="xs"
              aria-label="delete"
              icon={<SmallCloseIcon path="" />}
            />
          )}

          <ColorPickerControl
            withFullColor={props.withFullColor}
            name={props.name}
            gradient={true}
            index={i}
            gradientColor={e}
            updateGradient={updateGradient}
          />
        </Box>
      ))}

      <Box textAlign="right" mt={3}>
        <Button
          variant="ghost"
          size="xs"
          onClick={() => setGradientColor([...gradientColor, 'blue.500'])}
        >
          + Add
        </Button>
      </Box>
    </>
  )
}