@chakra-ui/react#Link TypeScript Examples

The following examples show how to use @chakra-ui/react#Link. 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: CourseCard.tsx    From fresh-coupons with GNU General Public License v3.0 6 votes vote down vote up
function CourseInstructors({instructors, ...props}: CourseInstructorsProps) {
  if (!instructors) {
    return <></>
  }

  return (
    <HStack mt="4" spacing={3} {...props}>
      {instructors && instructors.map(instructor => (
        <HStack spacing={1} key={instructor.url}>
          <Icon as={BsPersonSquare} color="gray.400"/>
          <Link
            href={`https://${instructor.url}`}
            isExternal
            fontSize="sm"
            fontWeight="medium"
            _visited={{
              color: "cadetblue"
            }}
            color={useColorModeValue('gray.600', 'gray.300')}
          >
            {instructor.name}
            <ExternalLinkIcon mx="2"/>
          </Link>
        </HStack>
      ))}
    </HStack>
  )
}
Example #2
Source File: achievements.tsx    From portfolio with MIT License 6 votes vote down vote up
ExternalLink: React.FC<ExternalLinkProps> = ({
  url,
  linkProps,
  text,
  ...props
}) => {
  return (
    <Link href={url} {...linkProps} {...props}>
      {text}
    </Link>
  );
}
Example #3
Source File: ErrorPage.tsx    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
ErrorPage: React.FC<FallbackProps> = ({ error }) => {
  const { t } = useTranslation();

  return (
    <Box color="white">
      <Box bg="red.600" width="100%" p={4}>
        <Heading>{t("Whoops! Looks like something went wrong!")}</Heading>
        <Text>
          {t(
            "You can either reload the page, or report this error to us on our"
          )}{" "}
          <Link isExternal href="https://github.com/Rari-Capital/rari-dApp">
            <u>GitHub</u>
            <ExternalLinkIcon mx="2px" />
          </Link>
        </Text>
      </Box>

      <Code colorScheme="red">{error.toString()}</Code>
    </Box>
  );
}
Example #4
Source File: FilesList.tsx    From ke with MIT License 6 votes vote down vote up
export function FilesList({
  value,
  onChange,
  listItemIcon = Paperclip,
  linkProps,
}: FilesListProps): ReactElement<FilesListProps> {
  const deleteFile = (file: FileDescriptor): void => {
    const restFiles = value.filter((f) => f.uuid !== file.uuid)
    onChange(restFiles)
  }

  return (
    <List>
      {value.map((file) => (
        <ListItem display="flex" alignItems="center" className={listItemCss} key={file.uuid}>
          <ListIcon as={listItemIcon} />
          {file?.url ? (
            <Link href={file.url} isExternal {...linkProps}>
              {file.name}
            </Link>
          ) : (
            file.name
          )}
          <IconButton
            aria-label="Удалить"
            variant="unstyled"
            size="xs"
            icon={<X color="red" size={16} />}
            ml={2}
            onClick={() => deleteFile(file)}
          />
        </ListItem>
      ))}
    </List>
  )
}
Example #5
Source File: TabNav.tsx    From ledokku with MIT License 6 votes vote down vote up
TabNavLink = ({
  selected,
  ...props
}: TabNavLinkProps & BoxProps) => (
  <Link
    as={ReactRouterLink}
    py="3"
    px="0.5"
    color="gray.500"
    _hover={{
      textDecoration: 'none',
      color: 'black',
    }}
    {...(selected
      ? {
          borderBottom: '2px',
          borderColor: 'black',
          color: 'black',
          mb: '-1px',
        }
      : {})}
    {...props}
  />
)
Example #6
Source File: HeadingAnchored.tsx    From lucide with ISC License 6 votes vote down vote up
HeadingAnchored = ({ children, as: headingLevel, ...restProps }) => {
  const { addHeading } = useHeadingNavigationContext();
  const headingText = typeof children === 'string' ? children : children[0];

  const anchor = getAnchor(headingText);
  const link = `#${anchor}`;
  const hoverStyling = {
    textDecoration: 'none',
    _before: {
      content: '"#"',
      color: '#F56565',
      fontWeight: 'bold',
      position: 'absolute',
      left: 0,
      transform: 'translateX(-100%)',
      paddingX: 2,
    },
  };
  const focusStyling = {
    outline: 'none',
  };

  useEffect(() => {
    addHeading({
      anchor,
      label: headingText,
      headingLevel,
    });
  }, [anchor, headingText]);

  return (
    <Heading id={anchor} as={headingLevel} position="relative" {...restProps}>
      <Link href={link} className="anchor-link" _hover={hoverStyling} _focus={focusStyling}>
        {children}
      </Link>
    </Heading>
  );
}
Example #7
Source File: Footer.tsx    From website with MIT License 6 votes vote down vote up
Footer: React.FC<FooterProps> = ({ className }) => (
  <Grid
    as="footer"
    px="24px"
    py="36px"
    color="gray.300"
    bg="gray.900"
    templateColumns="1fr 1fr minmax(auto, 1140px) 1fr 1fr"
    className={className}
  >
    <Stack align="center" justify="center" gridColumn="3/4" textAlign="center">
      <section>
        <Text margin="0" lineHeight="20px" fontSize="12px">
          &copy; 2020 ReactJS ID.
        </Text>
        <Text margin="0" lineHeight="20px" fontSize="12px">
          Kode sumber situs ini tersedia di{' '}
          <Link href="https://github.com/reactjs-id/website" isExternal color="#fff" rel="noopener noreferrer">
            GitHub
          </Link>
          . Gambar latar disediakan oleh{' '}
          <Link href="https://www.transparenttextures.com/" isExternal color="#fff" rel="noopener noreferrer">
            Transparent Textures
          </Link>
          .
        </Text>
      </section>
    </Stack>
  </Grid>
)
Example #8
Source File: ComponentMapping.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
components = {
    h1: ({ children }) => <Heading as="h1" my="1.5rem" size="2xl">{children}</Heading>,
    h2: ({ children }) => <Heading as="h2" my="1.5rem" size="xl">{children}</Heading>,
    h3: ({ children }) => <Heading as="h3" my="1.5rem" size="lg">{children}</Heading>,
    h4: ({ children }) => <Heading as="h4" my="1.5rem" size="md">{children}</Heading>,
    p: ({ children }) => <Text mb="1.5rem" fontSize="lg">{children}</Text>,
    Center,
    ul: ({ children }) => <UnorderedList mb="1.5rem">{children}</UnorderedList>,
    ol: ({ children }) => <OrderedList mb="1.5rem">{children}</OrderedList>,
    li: ({ children }) => <ListItem fontSize="lg">{children}</ListItem>,
    Image,
    ImageBorder,
    code: Code,
    CodeBlock,
    a: ({ children, href }) => <u><Link href={href} isExternal>{children}</Link></u>,
    NextLink: ({ children, href }) => <u><NextLink href={href}>{children}</NextLink></u>,
}
Example #9
Source File: AppVersionAlert.tsx    From takeout-app with MIT License 6 votes vote down vote up
AppVersionAlert: React.FC = () => {
  const { data: appVersion } = Api.useAppVersion();
  return appVersion && appVersion.commit !== COMMIT ? (
    <Alert status="info" mt={1}>
      <AlertIcon />
      New app version available;
      <Link textDecoration="underline" onClick={() => window.location.reload()} ml={1}>
        Reload?
      </Link>
    </Alert>
  ) : null;
}
Example #10
Source File: Footer.tsx    From calories-in with MIT License 6 votes vote down vote up
function Footer({ onAbout, ...rest }: Props) {
  return (
    <Box {...rest}>
      <Divider />
      <HStack height="50px" spacing={3}>
        <Button
          variant="link"
          color="gray.500"
          fontWeight="thin"
          py={0.5}
          onClick={onAbout}
        >
          About
        </Button>

        <Link
          color="gray.500"
          target="_blank"
          href="https://www.termsfeed.com/live/7e9b9ec6-aca7-4c99-a987-feb8b535a8e9"
        >
          Terms
        </Link>

        <Link
          color="gray.500"
          target="_blank"
          href="https://www.termsfeed.com/live/ff5061b9-09e0-4fae-a8e9-010274f2085c"
        >
          Disclaimer
        </Link>
      </HStack>
    </Box>
  )
}
Example #11
Source File: Setup.tsx    From bluebubbles-server with Apache License 2.0 5 votes vote down vote up
NavBar = (): JSX.Element => {
    const { colorMode, toggleColorMode } = useColorMode();

    return (
        <Flex
            height="20"
            alignItems="center"
            borderBottomWidth="1px"
            borderBottomColor={useColorModeValue('gray.200', 'gray.700')}
            justifyContent='space-between'
            p={4}
            pl={6}
        >
            <Flex alignItems="center" justifyContent='flex-start'>
                <img src={logo} className="logo" alt="logo" height={48} />
                <Text fontSize="1xl" ml={2}>BlueBubbles</Text>
            </Flex>
            <Flex justifyContent='flex-end'>
                <HStack spacing={{ base: '0', md: '1' }}>
                    <Tooltip label="Website Home" aria-label="website-tip">
                        <Link href="https://bluebubbles.app" style={{ textDecoration: 'none' }} target="_blank">
                            <IconButton size="lg" variant="ghost" aria-label="website" icon={<AiOutlineHome />} />
                        </Link>
                    </Tooltip>
                    <Tooltip label="BlueBubbles Web" aria-label="website-tip">
                        <Link href="https://bluebubbles.app/web" style={{ textDecoration: 'none' }} target="_blank">
                            <IconButton size="lg" variant="ghost" aria-label="bluebubbles web" icon={<FiMessageCircle />} />
                        </Link>
                    </Tooltip>
                    <Tooltip label="Support Us" aria-label="donate-tip">
                        <Link href="https://bluebubbles.app/donate" style={{ textDecoration: 'none' }} target="_blank">
                            <IconButton size="lg" variant="ghost" aria-label="donate" icon={<MdOutlineAttachMoney />} />
                        </Link>
                    </Tooltip>
                    <Tooltip label="Join our Discord" aria-label="discord-tip">
                        <Link href="https://discord.gg/yC4wr38" style={{ textDecoration: 'none' }} target="_blank">
                            <IconButton size="lg" variant="ghost" aria-label="discord" icon={<FaDiscord />} />
                        </Link>
                    </Tooltip>
                    <Tooltip label="Read our Source Code" aria-label="github-tip">
                        <Link href="https://github.com/BlueBubblesApp" style={{ textDecoration: 'none' }} target="_blank">
                            <IconButton size="lg" variant="ghost" aria-label="github" icon={<FiGithub />} />
                        </Link>
                    </Tooltip>
                    <Spacer />
                    <Divider orientation="vertical" width={1} height={15} borderColor='gray' />
                    <Spacer />
                    <Spacer />
                    <Spacer />
                    <FormControl display='flex' alignItems='center'>
                        <Box mr={2}><MdOutlineDarkMode size={20} /></Box>
                        <Switch id='theme-mode-toggle' onChange={toggleColorMode} isChecked={colorMode === 'light'} />
                        <Box ml={2}><MdOutlineLightMode size={20} /></Box>
                    </FormControl>
                </HStack>
            </Flex>
        </Flex>
    );
}
Example #12
Source File: footer.tsx    From portfolio with MIT License 5 votes vote down vote up
Footer = () => {
  return (
    <Stack
      as="footer"
      isInline
      spacing={[1, 2]}
      p={4}
      justifyContent="space-between"
      alignItems="center"
      w={["100%", "85%", "80%"]}
      maxW={800}
      mx="auto"
    >
      <Flex
        flexDirection={["column", "column", "row"]}
        flexFlow={["column-reverse", "column-reverse"]}
        justifyContent={["center", "space-between"]}
        alignItems="center"
        w="100%"
        ju
      >
        {/* <HStack> */}
        <Text
          textAlign="center"
          fontSize="sm"
          color={useColorModeValue("gray.500", "gray.200")}
        >
          © {new Date().getFullYear()} Muhammad Ahmad{" "}
        </Text>
        {/* <Box fontSize="md" textAlign="left">
        Website built with
        <Box
          as="span"
          mx="2"
          _before={{
            cursor: "default",
            content: '"❤️"'
          }}
          _hover={{
            _before: {
              content: '"☕️"'
            }
          }}
        />
        in Pakistan{"  "}??
      </Box> */}
        {/* </HStack> */}
        <Box textAlign="center">
          {siteConfig.author.accounts.map((sc, index) => (
            <IconButton
              key={index}
              as={Link}
              isExternal
              href={sc.url}
              aria-label={sc.label}
              size="lg"
              colorScheme={sc.type}
              icon={sc.icon}
              {...iconProps}
            />
          ))}
        </Box>
      </Flex>
    </Stack>
  );
}
Example #13
Source File: OraclesTable.tsx    From rari-dApp with GNU Affero General Public License v3.0 5 votes vote down vote up
OracleRow = ({
  oracle,
  underlyings,
  isDefault = false,
}: {
  oracle: string;
  underlyings: string[];
  isDefault?: boolean;
}) => {
  const oracleIdentity = useIdentifyOracle(oracle);

  const displayedOracle = !!oracleIdentity
    ? oracleIdentity
    : shortAddress(oracle);

  return (
    <>
      <Tr>
        <Td>
          <Link
            href={`https://etherscan.io/address/${oracle}`}
            isExternal
            _hover={{ pointer: "cursor", color: "#21C35E" }}
          >
            <Text fontWeight="bold">{displayedOracle}</Text>
          </Link>
        </Td>
        <Td>
          {isDefault ? (
            <span style={{ fontWeight: "bold" }}>DEFAULT</span>
          ) : (
            <AvatarGroup size="xs" max={30} mr={2}>
              {underlyings.map((underlying) => {
                return <CTokenIcon key={underlying} address={underlying} />;
              })}
            </AvatarGroup>
          )}
        </Td>
      </Tr>
    </>
  );
}
Example #14
Source File: LinkWidget.test.tsx    From ke with MIT License 5 votes vote down vote up
test('Link widget properly rendered', () => {
  const component = shallow(getComponent())

  expect(component.find(Link).length).toEqual(1)
  expect(component.find(StyledWidgetWrapper).length).toEqual(1)
})
Example #15
Source File: index.tsx    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function Home() {
  const { isError, gardens, error } = useDendronGardens();
  if (isError) return <div>failed to load: {JSON.stringify(error)}</div>;
  let extra: any;
  // if (_.isEmpty(gardens)) {
  //   extra = <Button>New Garden from Git</Button>;
  // }
  if (_.isEmpty(gardens)) {
    extra = (
      <Box maxW="32rem">
        <VStack spacing={4} align="stretch">
          <Center>
            <Heading mb={4}>Welcome to Dendron</Heading>
          </Center>
          <Text fontSize="xl">
            If you haven&apos;t already done so, you can install Dendron by following
            the instructions &nbsp;
            <Link
              href="https://dendron.so/notes/678c77d9-ef2c-4537-97b5-64556d6337f1.html"
              isExternal
            >
              here
            </Link>
          </Text>
          <Button>Publish a new site from Git (coming soon) </Button>
        </VStack>
      </Box>
    );
  }
  return (
    <>
      <Head>
        <title>Dendron</title>
        <link rel="icon" href="/favicon.ico" />
        <script type="text/javascript" src="/static/memberful.js" />
      </Head>

      <Grid justifyContent="center">{extra}</Grid>
    </>
  );
}
Example #16
Source File: DocsMenu.tsx    From lucide with ISC License 5 votes vote down vote up
DocsMenu = (props: BoxProps) => {
  const router = useRouter();
  const linkIsActive = (currentPath, href) => currentPath === `/docs/${href}`;
  return (
    <Box {...props}>
      <Box paddingY={4}>
        {docsMenuTree.map(({ section, items }) => (
          <Box key={section}>
            <Text fontSize={19} fontWeight="bold" marginBottom={2}>
              {section}
            </Text>
            <Box as="ul" style={{ listStyle: 'none' }} marginBottom={6}>
              {items.map(({ href, title }) => (
                <Box as="li" key={title}>
                  <NextLink href={`/docs/${href}`} passHref>
                    <Link
                      _hover={{ opacity: linkIsActive(router.asPath, href) ? 1 : 0.8 }}
                      display="block"
                      color={linkIsActive(router.asPath, href) ? 'brand.500' : 'inherit'}
                    >
                      <Text
                        fontSize={16}
                        lineHeight={1.8}
                        opacity={linkIsActive(router.asPath, href) ? 1 : 0.5}
                        as="p"
                        width="100%"
                        display="block"
                      >
                        {title}
                      </Text>
                    </Link>
                  </NextLink>
                </Box>
              ))}
            </Box>
          </Box>
        ))}
      </Box>
    </Box>
  );
}
Example #17
Source File: SharePopover.tsx    From ksana.in with Apache License 2.0 5 votes vote down vote up
SharePopover = ({ url }: SharePopoverProps) => {
  const [isLoadingShare, setLoadingShare] = useState<boolean>(false)
  const [showShare, setShowShare] = useState<boolean>(false)
  const [text, setText] = useState<string>('')
  const parsedUrl = encodeURIComponent(url)

  const handleShare = async (url: string) => {
    setLoadingShare(true)
    const d = await getMeta(url)
    setText(encodeURIComponent(d.description))
    setShowShare(true)
    setLoadingShare(false)
  }

  return (
    <Popover
      isOpen={showShare}
      onClose={() => {
        setShowShare(false)
      }}
      isLazy
      placement="bottom"
    >
      <PopoverTrigger>
        <IconButton
          onClick={() => {
            handleShare(url)
          }}
          aria-label="Share url"
          fontSize="20px"
          variant="ghost"
          borderRadius="md"
          isLoading={isLoadingShare}
          icon={<HiShare color="#ED8936" />}
        />
      </PopoverTrigger>
      <PopoverContent>
        <PopoverArrow />
        <PopoverCloseButton />
        <PopoverHeader>Bagikan tautan anda</PopoverHeader>
        <PopoverBody>
          <Stack direction="row" justifyContent="center">
            <Link isExternal href={`https://api.whatsapp.com/send?text=${text}+%0A+${parsedUrl}`}>
              <IconButton
                borderRadius="md"
                colorScheme="green"
                aria-label="Share whatsapp"
                icon={<FaWhatsapp />}
              />
            </Link>
            <Link
              isExternal
              href={`https://twitter.com/intent/tweet?text=${text}+%0A+${parsedUrl}`}
            >
              <IconButton
                borderRadius="md"
                colorScheme="twitter"
                aria-label="Share twitter"
                icon={<FaTwitter />}
              />
            </Link>
            <Link
              isExternal
              href={`https://www.facebook.com/sharer/sharer.php?quote=${text}&u=${parsedUrl}`}
            >
              <IconButton
                borderRadius="md"
                colorScheme="facebook"
                aria-label="Share Facebook"
                icon={<FaFacebook />}
              />
            </Link>
          </Stack>
        </PopoverBody>
      </PopoverContent>
    </Popover>
  )
}
Example #18
Source File: LearningCard.tsx    From website with MIT License 5 votes vote down vote up
LearningCard: React.FC<LearningCardProps> = ({ heading, title, href, desc }) => {
  return (
    <Flex
      flexDirection="column"
      role="group"
      backgroundColor="white"
      position="relative"
      border="none"
      boxShadow="rgba(0, 0, 0, 0.25) 0px 2px 4px"
      minHeight="320px"
      borderRadius="8px"
      p={4}
      textAlign="left"
      cursor="pointer"
      _hover={{ boxShadow: 'rgba(0, 0, 0, 0.25) 0px 6px 8px' }}
    >
      <Heading color="astronautBlue" as="h4" mb="4px" size="sm" fontWeight={300} textTransform="uppercase">
        {heading}
      </Heading>
      <Heading textAlign="left" color="gray08" as="h5" size="md" fontWeight={600}>
        <Link
          href={href}
          isExternal
          _focus={{ boxShadow: 'rgba(26, 255, 214, 0.6) 0px 0px 0px 3px' }}
          css={css`
            &::after {
              position: absolute;
              top: 0;
              bottom: 0;
              left: 0;
              right: 0;
              content: '';
            }
          `}
        >
          {title}
        </Link>
      </Heading>
      <Text textAlign="left" as="p" mt="0.5em" mb="1.3em">
        {desc}
      </Text>
      <LinkButton
        _hover={undefined}
        _groupHover={{ backgroundColor: 'reactBlue.900' }}
        as="span"
        mt="auto"
        backgroundColor="reactBlue.800"
        color="white"
      >
        Kunjungi Situs
      </LinkButton>
    </Flex>
  )
}
Example #19
Source File: AuthModal.tsx    From coindrop with GNU General Public License v3.0 5 votes vote down vote up
AuthModal: FunctionComponent<Props> = ({ isOpen }) => {
    const router = useRouter();
    const onClose = () => router.push('/', undefined, { shallow: true });
    return (
        <Modal
            id="auth-modal"
            isOpen={isOpen}
            onClose={onClose}
        >
            <ModalOverlay />
            <ModalContent>
                <ModalHeader textAlign="center" mb={-3}>Sign in to continue</ModalHeader>
                <ModalCloseButton />
                <ModalBody>
                    <FirebaseAuth />
                    <Text textAlign="center" fontSize="xs" mb={2}>
                        {'If you\'re having trouble logging in, please try again with '}
                        <Link
                            href="https://www.google.com/chrome/"
                            target="_blank"
                            rel="noreferrer"
                            textDecoration="underline"
                        >
                            Chrome
                        </Link>
                        {' or '}
                        <Link
                            href="https://www.mozilla.org/firefox"
                            target="_blank"
                            rel="noreferrer"
                            textDecoration="underline"
                        >
                            Firefox
                        </Link>
                        .
                    </Text>
                </ModalBody>
            </ModalContent>
        </Modal>
    );
}
Example #20
Source File: ControlAttendeeEdit.tsx    From takeout-app with MIT License 5 votes vote down vote up
ControlAttendeeEdit: React.FC<Props> = () => {
  const match = useRouteMatch<{ id: string }>();
  const id = parseInt(match.params.id, 10);
  const { data } = ControlApi.useAttendee(id);
  const [errorAlert, setErrorAlert] = React.useState<JSX.Element | null>(null);
  const [isRequesting, setIsRequesting] = React.useState<boolean>(false);
  const { register, handleSubmit, reset } = useForm<ControlUpdateAttendeeRequestAttendee>({
    defaultValues: {
      name: React.useMemo(() => data?.attendee?.name, [data]),
      is_staff: React.useMemo(() => data?.attendee?.is_staff, [data]),
      is_speaker: React.useMemo(() => data?.attendee?.is_speaker, [data]),
      is_committer: React.useMemo(() => data?.attendee?.is_committer, [data]),
      presentation_slugs: React.useMemo(() => data?.attendee?.presentation_slugs || [], [data]),
    },
  });

  const onSubmit = handleSubmit(async (data) => {
    if (isRequesting) return;
    setIsRequesting(true);
    try {
      await ControlApi.updateAttendee(id, data);
      setErrorAlert(null);
    } catch (e) {
      setErrorAlert(
        <Box my={2}>
          <ErrorAlert error={e} />
        </Box>,
      );
    }
    setIsRequesting(false);
  });

  React.useEffect(() => {
    if (data) reset(data.attendee);
  }, [data]);

  if (!data) return <p>Loading</p>;

  // TODO: link to registration page and support email
  return (
    <>
      {errorAlert}
      <Container mt="20px">
        <form onSubmit={onSubmit}>
          <Text>
            <Link href={data.ticket.admin_url} isExternal textDecoration="underline">
              {data.ticket.reference}
            </Link>
          </Text>
          <FormControl mt={4} id="attendee__name" isRequired>
            <FormLabel>Name</FormLabel>
            <Input {...register("name")} />
          </FormControl>
          <FormControl mt={4} id="attendee__staff" isRequired>
            <FormLabel>Staff</FormLabel>
            <Checkbox {...register("is_staff")} />
          </FormControl>
          <FormControl mt={4} id="attendee__speaker" isRequired>
            <FormLabel>Speaker</FormLabel>
            <Checkbox {...register("is_speaker")} />
          </FormControl>
          <FormControl mt={4} id="attendee__committer" isRequired>
            <FormLabel>Committer</FormLabel>
            <Checkbox {...register("is_committer")} />
          </FormControl>
          <FormControl mt={4} id="attendee__presentation_slugs">
            <FormLabel>Presentation Slugs</FormLabel>
            <Input {...register("presentation_slugs.0")} />
          </FormControl>

          <Button mt={4} size="lg" type="submit" isLoading={isRequesting}>
            Save
          </Button>
        </form>
      </Container>
    </>
  );
}
Example #21
Source File: NgrokAuthTokenField.tsx    From bluebubbles-server with Apache License 2.0 4 votes vote down vote up
NgrokAuthTokenField = ({ helpText }: NgrokAuthTokenFieldProps): JSX.Element => {
    const dispatch = useAppDispatch();
    const ngrokToken: string = (useAppSelector(state => state.config.ngrok_key) ?? '');
    const [showNgrokToken, setShowNgrokToken] = useBoolean();
    const [newNgrokToken, setNewNgrokToken] = useState(ngrokToken);
    const [ngrokTokenError, setNgrokTokenError] = useState('');
    const hasNgrokTokenError: boolean = (ngrokTokenError ?? '').length > 0;

    useEffect(() => { setNewNgrokToken(ngrokToken); }, [ngrokToken]);

    /**
     * A handler & validator for saving a new Ngrok auth token.
     *
     * @param theNewNgrokToken - The new auth token to save
     */
    const saveNgrokToken = (theNewNgrokToken: string): void => {
        theNewNgrokToken = theNewNgrokToken.trim();

        // Validate the port
        if (theNewNgrokToken === ngrokToken) {
            setNgrokTokenError('You have not changed the token since your last save!');
            return;
        } else if (theNewNgrokToken.includes(' ')) {
            setNgrokTokenError('Invalid Ngrok Auth Token! Please check that you have copied it correctly.');
            return;
        }

        dispatch(setConfig({ name: 'ngrok_key', value: theNewNgrokToken }));
        setNgrokTokenError('');
        showSuccessToast({
            id: 'settings',
            duration: 4000,
            description: 'Successfully saved new Ngrok Auth Token! Restarting Proxy service...'
        });
    };

    return (
        <FormControl isInvalid={hasNgrokTokenError}>
            <FormLabel htmlFor='ngrok_key'>Ngrok Auth Token (Optional)</FormLabel>
            <Input
                id='password'
                type={showNgrokToken ? 'text' : 'password'}
                maxWidth="20em"
                value={newNgrokToken}
                onChange={(e) => {
                    if (hasNgrokTokenError) setNgrokTokenError('');
                    setNewNgrokToken(e.target.value);
                }}
            />
            <IconButton
                ml={3}
                verticalAlign='top'
                aria-label='View Ngrok token'
                icon={showNgrokToken ? <AiFillEye /> : <AiFillEyeInvisible />}
                onClick={() => setShowNgrokToken.toggle()}
            />
            <IconButton
                ml={3}
                verticalAlign='top'
                aria-label='Save Ngrok token'
                icon={<AiOutlineSave />}
                onClick={() => saveNgrokToken(newNgrokToken)}
            />
            {!hasNgrokTokenError ? (
                <FormHelperText>
                    {helpText ?? (
                        <Text>
                            Using an Auth Token will allow you to use the benefits of the upgraded Ngrok
                            service. This can improve connection stability and reliability. If you do not have
                            an Ngrok Account, sign up for free here:&nbsp;
                            <Box as='span' color={baseTheme.colors.brand.primary}>
                                <Link href='https://dashboard.ngrok.com/get-started/your-authtoken' target='_blank'>ngrok.com</Link>
                            </Box>
                        </Text>
                    )}
                </FormHelperText>
            ) : (
                <FormErrorMessage>{ngrokTokenError}</FormErrorMessage>
            )}
        </FormControl>
    );
}
Example #22
Source File: index.tsx    From wiregui with MIT License 4 votes vote down vote up
export default function Sidebar() {
  const history = useHistory();
  const location = useLocation();
  const dispatch = useDispatch();

  const [isDialogOpen, setDialogOpen] = useState<boolean>(false);
  const [nameToDelete, setNameToDelete] = useState<string>();

  const { files } = useSelector<StoreState, WgConfigState>(
    (state) => state.wgConfig
  );
  const { userDataPath } = useSelector<StoreState, AppState>(
    (state) => state.app
  );

  function handleRedirect(param: string): void {
    const newPath = `/tunnel/${param}`;
    if (location.pathname === newPath) {
      return;
    }
    history.push(newPath);
  }

  function getWgConfigFile(name: string): WgConfigFile | undefined {
    return files.find((f) => f.name === name);
  }

  function isSelected(name: string): boolean {
    return location.pathname.split("/tunnel/")[1] === name;
  }

  function isActive(name: string): boolean {
    const wgConfigFile = getWgConfigFile(name);

    if (!wgConfigFile) {
      return false;
    }

    return wgConfigFile.active;
  }

  function handleDelete() {
    if (!nameToDelete) {
      toast("Could not find config file", { type: "error" });
      return;
    }

    try {
      const wgConfigFile = getWgConfigFile(nameToDelete);
      if (!wgConfigFile) {
        toast("Could not find config file", { type: "error" });
        return;
      }

      dispatch(deleteFile(wgConfigFile, userDataPath));

      if (isSelected(nameToDelete)) {
        history.push("/");
      }
    } catch (e) {
      toast(e.message, { type: "error" });
    }
  }

  function handleDeleteDialog(name: string) {
    setNameToDelete(name);
    setDialogOpen(true);
  }

  function cancelDialog(): void {
    setDialogOpen(false);
  }

  async function handleToggle(name: string) {
    const wgConfigFile = getWgConfigFile(name);
    if (!wgConfigFile) {
      toast("Could not find config file", { type: "error" });
      return;
    }

    try {
      const started = await WireGuard.toggle(wgConfigFile.path);
      const message = started ? "Activated" : "Deactivated";
      toast(`${message} ${wgConfigFile.name}`, { type: "success" });
      dispatch(updateStatus(started ? wgConfigFile.name : ""));
    } catch (e) {
      try {
        await checkWgIsInstalled();
      } catch (e) {
        toast("Wireguard was not detected on the system. If you just installed it, try restarting wiregui.", { type: "error" });
        return;
      }
      toast(e.message, { type: "error" });
    }
  }

  async function handleCopy(name: string) {
    const wgConfigFile = getWgConfigFile(name);
    if (!wgConfigFile) {
      toast("Could not find config file", { type: "error" });
      return;
    }

    const filePath = path.join(userDataPath, "configurations", `${name}.conf`);
    const data = fs.readFileSync(filePath, "utf-8");
    const config = new WgConfig({});
    config.parse(data);

    try {
      await navigator.clipboard.writeText(config.toString());
      toast(`${name} copied to clipboard`, { type: "success" });
    } catch (e) {
      toast(`Could not copy ${name} to clipboard`, { type: "error" });
    }
  }

  return (
    <Flex bg="gray.200" direction="column" w="350px" position="relative">
      <Box px="4" pt="4" w="100%">
        <Flex justify="center">
          <NewTunnelButton />
        </Flex>
        <Text color="whiteAlpha.700" fontWeight="bold" mt="8">
          TUNNELS
        </Text>
      </Box>
      <Flex direction="column" overflowY="auto" maxH="calc(100vh - 96px - 19px)" className="sidebar__list__container">
        {files.map((file) => (
          <div key={file.name}>
            <Link
              onClick={() => handleRedirect(file.name)}
              _hover={{ textDecoration: "none" }}
            >
              <SidebarItem
                name={file.name}
                path={file.path}
                address={file.address}
                lastConnectAt={file.lastConnectAt}
                active={file.active}
                selected={isSelected(file.name)}
              />
            </Link>
            <ContextMenuList menuId={`menu-${file.name}`}>
              <ContextMenuItem
                color="whiteAlpha.700"
                onClick={({ passData }) => handleToggle(passData.name as string)}
              >
                {isActive(file.name) ? "Deactivate" : "Activate" }
              </ContextMenuItem>
              <ContextMenuItem
                color="whiteAlpha.700"
                onClick={({ passData }) => handleCopy(passData.name as string)}
              >
                Copy
              </ContextMenuItem>
              <hr/>
              <ContextMenuItem
                color="red"
                onClick={({ passData }) => handleDeleteDialog(passData.name as string)}
              >
                Delete
              </ContextMenuItem>
            </ContextMenuList>
          </div>
        ))}
      </Flex>
      <Text
          position="absolute"
          bottom="0"
          w="100%"
          textAlign="center"
          fontSize="smaller"
          color="whiteAlpha.500"
        >
          v{version}
        </Text>
        <Dialog
          isOpen={isDialogOpen}
          header="Are you sure?"
          body="You cannot recover this file after deleting."
          onConfirm={handleDelete}
          onCancel={cancelDialog}
          onClose={cancelDialog}
        />
    </Flex>
  );
}
Example #23
Source File: repositories-list-item.tsx    From notebook with MIT License 4 votes vote down vote up
RepositoriesListItem: React.SFC<RepositoriesListItemProps> = ({
  repo
}) => {
  const [repoId, setRepoId] = React.useState<number>(0);
  const bg = useColorModeValue("white", "#2f3244");
  const textColor = useColorModeValue("gray.600", "#b5b1b1");
  const { isOpen, onOpen, onClose } = useDisclosure();

  const handleClick = (id: number) => {
    setRepoId(id);
    onOpen();
  };

  return (
    <>
      <Center>
        <Box
          maxW="sm"
          height="fit-content"
          borderWidth="1px"
          borderRadius="lg"
          overflow="hidden"
          boxShadow="md"
          mx="5px"
          mb="10px"
          mt="10px"
          _hover={{ boxShadow: "lg" }}
        >
          {/* <Image
          height={{ base: "28vh", lg: "32vh" }}
          cursor={repo.coverImage ? "pointer" : "auto"}
          width={"100%"}
          src={repo.coverImage}
          objectFit="cover"
          alt="cover image"
          fallbackSrc="https://via.placeholder.com/320x216/DCDFDF/ffffff/?text=CoverImage"
          fallbackSrc={placeholder}
          onClick={() => handleClick(repo.coverImage)}
        /> */}
          <LazyImage
            id={repo.id}
            src={repo.coverImage}
            blurHash={repo.blurHash}
            handleClick={handleClick}
          />

          <Box p="5" bg={bg}>
            <Flex justifyContent="space-between" alignItems="center">
              <Box
                mt="1"
                fontWeight="semibold"
                as="h6"
                fontSize="md"
                lineHeight="tight"
                textAlign="left"
                isTruncated
              >
                <Link
                  href={repo.liveLink || repo.githubLink}
                  textDecoration={"none !important"}
                  isExternal
                >
                  {repo.title}
                  <ExternalLinkIcon mx="3px" />
                </Link>
              </Box>
              <Box mt="1">
                {repo.stars ? (
                  <Link
                    href={repo.githubLink}
                    textDecoration={"none !important"}
                    isExternal
                  >
                    <Tooltip hasArrow label="Github stars" placement="top-end">
                      <Box>
                        <StarIcon color="teal.300" fontSize="sm" />
                        <Box as="span" ml="2" color={textColor} fontSize="sm">
                          {repo.stars}
                        </Box>
                      </Box>
                    </Tooltip>
                  </Link>
                ) : (
                  ""
                )}
              </Box>
            </Flex>
            <Box textAlign="left">
              <HStack spacing="1" mt="2" mb="2">
                {repo.technologies.map((tech, index) => (
                  <Badge
                    borderRadius="full"
                    px="1"
                    colorScheme={tech.color}
                    textTransform="lowercase"
                    key={index}
                  >
                    {tech.name}
                  </Badge>
                ))}
              </HStack>
            </Box>
            <Box color={textColor} fontSize="md" textAlign="left">
              {repo.desc}
            </Box>
          </Box>
        </Box>
      </Center>
      <Carousel
        repoId={repoId}
        onOpen={onOpen}
        onClose={onClose}
        isOpen={isOpen}
      />
    </>
  );
}
Example #24
Source File: notebook-post.tsx    From portfolio with MIT License 4 votes vote down vote up
NotebookPost: React.SFC<PostProps> = () => {
  const textColor = useColorModeValue("gray.500", "gray.200");
  const post = articles[4];

  return (
    <>
      <VStack mt={0} mb={6} spacing={1} align="start">
        <Heading as="h1" fontSize="3xl" lineHeight="shorter" fontWeight="bold">
          {post.title}
        </Heading>
        <Divider
          orientation="horizontal"
          opacity={1}
          borderBottomWidth={0}
          height={"1px"}
          bg={"gray.200"}
        />
      </VStack>
      <Flex
        justifyContent={"space-between"}
        flexDirection={["column", "row", "row"]}
      >
        <HStack spacing={2} isInline>
          <Text fontSize="sm" fontWeight="400" color={textColor}>
            {post.published}
          </Text>
          <Text fontSize="sm" fontWeight="400" color={textColor}>
            •
          </Text>
          <Tooltip hasArrow label="Views" placement="top">
            <Flex alignItems="center">
              <Text
                fontSize="sm"
                noOfLines={1}
                fontWeight="400"
                align="left"
                color={textColor}
              >
                {post.views}
              </Text>
              <Icon as={FaEye} ml={1} color={textColor} />
            </Flex>
          </Tooltip>

          <Text fontSize="sm" fontWeight="600" color={textColor}>
            •
          </Text>
          <Tooltip hasArrow label="Read time" placement="top">
            <Text
              fontSize="sm"
              noOfLines={1}
              fontWeight="400"
              align="left"
              color={textColor}
            >
              {post.readTime}
            </Text>
          </Tooltip>
        </HStack>
        <HStack spacing={1} alignItems="center">
          {post.tags.map(tag => (
            <Tag
              size="sm"
              padding="0 3px"
              key={tag}
              colorScheme={getTagColor(tag)}
            >
              {tag}
            </Tag>
          ))}
        </HStack>
      </Flex>
      <HStack align="end" mt={5}>
        <Link href={post.live} isExternal>
          <Button
            ml={2}
            variant="outline"
            size={["sm"]}
            color={useColorModeValue("green.600", "green.200")}
            bg={useColorModeValue("white", "gray.800")}
            leftIcon={<BiLinkExternal size={18} />}
          >
            Demo
          </Button>
        </Link>
        <Link href={post.github_url} isExternal>
          <Button
            ml={2}
            variant="outline"
            size={["sm"]}
            color={useColorModeValue("green.600", "green.200")}
            bg={useColorModeValue("white", "gray.800")}
            leftIcon={<FiGithub size={18} />}
          >
            Github link
          </Button>
        </Link>
      </HStack>

      <Box height={["35vh", "45vh", "55vh", "70vh"]} marginTop={5}>
        <Carousel images={post.images} />
      </Box>
      <VStack spacing={5} align={"start"} mt={6}>
        <Header fontSize={"xl"} mt={0} mb={0}>
          What will you learn?
        </Header>
        <Box fontSize="md">
          <UnorderedList textAlign="left" paddingLeft={5} m={0}>
            <ListItem>How to create a CRUD app with react</ListItem>
            <ListItem>How to create a responsive app using ChakraUi</ListItem>
            <ListItem>How to use animations with framer-motion</ListItem>
            <ListItem>How to create slider with framer-motion</ListItem>
          </UnorderedList>
        </Box>
      </VStack>
      <VStack spacing={5} align={"start"} mt={6}>
        <Header fontSize={"xl"} mt={0} mb={0}>
          Built with
        </Header>
        <Box fontSize="md">
          <UnorderedList textAlign="left" paddingLeft={5} m={0}>
            <ListItem>
              Programming language -{" "}
              <Link
                href="https://www.typescriptlang.org/"
                isExternal
                color={"blue.500"}
              >
                Typescript
              </Link>
            </ListItem>
            <ListItem>
              Front-end library -{" "}
              <Link
                href="https://github.com/facebook/react/"
                isExternal
                color={"blue.500"}
              >
                React
              </Link>
            </ListItem>
            <ListItem>
              UI components -{" "}
              <Link href="https://chakra-ui.com/" isExternal color={"blue.500"}>
                Chakra-ui
              </Link>
            </ListItem>
            <ListItem>
              Animation library -{" "}
              <Link
                href="https://www.framer.com/motion/"
                isExternal
                color={"blue.500"}
              >
                Framer motion
              </Link>
            </ListItem>
            <ListItem>
              Notes display -{" "}
              <Link
                href="https://github.com/tsuyoshiwada/react-stack-grid"
                isExternal
                color={"blue.500"}
              >
                react-stack-grid
              </Link>
            </ListItem>
            <ListItem>
              Forms Validation -{" "}
              <Link
                href="https://react-hook-form.com/"
                isExternal
                color={"blue.500"}
              >
                React hook form
              </Link>
            </ListItem>
            <ListItem>
              Icons -{" "}
              <Link
                href="https://react-icons.github.io/react-icons/"
                isExternal
                color={"blue.500"}
              >
                React icons
              </Link>
            </ListItem>
            <ListItem>
              Images placeholder -{" "}
              <Link href="https://blurha.sh/" isExternal color={"blue.500"}>
                blurhash
              </Link>
            </ListItem>
            <ListItem>
              Progressive image loading -{" "}
              <Link
                href="https://github.com/FormidableLabs/react-progressive-image"
                isExternal
                color={"blue.500"}
              >
                react-progressive-image
              </Link>
            </ListItem>
          </UnorderedList>
        </Box>
      </VStack>
    </>
  );
}
Example #25
Source File: FuseLiquidationsPage.tsx    From rari-dApp with GNU Affero General Public License v3.0 4 votes vote down vote up
LiquidationRow = ({
  noBottomDivider,
  liquidation,
}: {
  noBottomDivider?: boolean;
  liquidation: LiquidationEvent;
}) => {
  const isMobile = useIsMobile();

  const { t } = useTranslation();

  const date = new Date(liquidation.timestamp * 1000);
  return (
    <>
      <Link
        isExternal
        width="100%"
        className="no-underline"
        href={"https://etherscan.io/tx/" + liquidation.transactionHash}
      >
        <Row
          mainAxisAlignment="flex-start"
          crossAxisAlignment="center"
          width="100%"
          height="100px"
          className="hover-row"
          pl={4}
          pr={1}
        >
          <Column
            width={isMobile ? "100%" : "30%"}
            height="100%"
            mainAxisAlignment="center"
            crossAxisAlignment="flex-start"
          >
            <Row mainAxisAlignment="flex-start" crossAxisAlignment="center">
              <Box boxSize="23px">
                <Jazzicon
                  diameter={23}
                  seed={jsNumberForAddress(liquidation.liquidator)}
                />
              </Box>

              <Text ml={2} mr={2} fontWeight="bold">
                <Text as="span" color="#EE1E45">
                  {" → "}
                </Text>
                {t("Liquidated")}
                <Text as="span" color="#73BF69">
                  {" → "}
                </Text>
              </Text>

              <Box boxSize="23px">
                <Jazzicon
                  diameter={23}
                  seed={jsNumberForAddress(liquidation.borrower)}
                />
              </Box>

              <Text ml={3} mr={2} fontWeight="bold">
                (Pool #{liquidation.poolID})
              </Text>
            </Row>

            <Text mt={2} fontSize="11px" color="#EE1E45">
              {liquidation.liquidator}
            </Text>
            <Text mt={1} fontSize="11px" color="#73BF69">
              {liquidation.borrower}
            </Text>
          </Column>

          {isMobile ? null : (
            <>
              <Column
                mainAxisAlignment="center"
                crossAxisAlignment="center"
                height="100%"
                width="23%"
              >
                <CTokenIcon
                  size="md"
                  mb={2}
                  address={liquidation.suppliedTokenAddress}
                />
              </Column>

              <Column
                mainAxisAlignment="center"
                crossAxisAlignment="center"
                height="100%"
                width="23%"
                fontWeight="bold"
              >
                <CTokenIcon
                  size="sm"
                  mb={2}
                  address={liquidation.borrowedTokenAddress}
                />
                {smallUsdFormatter(
                  liquidation.repayAmount /
                    10 ** liquidation.borrowedTokenUnderlyingDecimals
                ).replace("$", "")}{" "}
                {liquidation.borrowedTokenUnderlyingSymbol}
              </Column>

              <Column
                mainAxisAlignment="center"
                crossAxisAlignment="center"
                height="100%"
                width="25%"
              >
                <Text fontWeight="bold">{date.toLocaleTimeString()}</Text>

                <Text mt={1}>{date.toLocaleDateString()}</Text>
              </Column>
            </>
          )}
        </Row>
      </Link>

      {noBottomDivider ? null : <ModalDivider />}
    </>
  );
}
Example #26
Source File: AboutWindow.tsx    From dope-monorepo with GNU General Public License v3.0 4 votes vote down vote up
AboutWindow = ({ ...props }) => {
  return (
    <DesktopWindow
      title="ABOUT DOPE WARS"
      background="#efefee"
      width="800px"
      hideWalletAddress
      {...props}
    >
      <div
        css={css`
          overflow-y: auto;
          overflow-x: hidden;
          display: flex;
          flex-direction: column;
          justify-content: stretch;
        `}
      >
        <div
          css={css`
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
            .react-player__preview {
              background-size: 80% 80% !important;
              background-repeat: no-repeat;
              align-items: end !important;
              padding: 32px;
            }
          `}
        >
          <ReactPlayer
            // If we want a cover image
            // light="/images/Logo-Plain.svg"
            //
            // To auto-play uncomment this
            // playing
            //
            url={VIDEOS}
            width="100%"
            controls
            css={css`
              background: black;
            `}
            playIcon={
              <Button
                variant="cny"
                css={css`
                  width: auto;
                `}
              >
                Enter the murderverse
              </Button>
            }
          />
          <ContentIntro />
          <ContentHustlers />
          <ContentRoadmap />
          <ContentFooter />
        </div>
        <PanelFooter
          css={css`
            position: sticky;
            bottom: 0;
            padding-right: 16px;
          `}
        >
          <div></div>
          <Link href="/news" passHref>
            <Button>Latest Announcements</Button>
          </Link>
          {/* <Link href="/mint" passHref>
            <Button variant="primary">Mint a Hustler</Button>
          </Link> */}
        </PanelFooter>
      </div>
    </DesktopWindow>
  );
}
Example #27
Source File: index.tsx    From formik-chakra-ui with MIT License 4 votes vote down vote up
App = () => {
  return (
    <ChakraProvider>
      <Heading as="h1" size="xl" textAlign="center">
        Formik Chakra UI
      </Heading>
      <Box as="p" textAlign="center">
        Example using{' '}
        <Link href="https://github.com/kgnugur/formik-chakra-ui" isExternal>
          Formik Chakra UI{' '}
        </Link>
      </Box>

      <Formik
        initialValues={initialValues}
        onSubmit={onSubmit}
        validationSchema={validationSchema}
      >
        {({ handleSubmit, values, errors }) => (
          <Stack
            spacing={5}
            borderWidth="1px"
            rounded="lg"
            shadow="1px 1px 3px rgba(0,0,0,0.3)"
            maxWidth={800}
            p={6}
            m="10px auto"
            as="form"
            onSubmit={handleSubmit as any}
          >
            <InputControl name="firstName" label="First Name" />
            <InputControl name="lastName" label="Last Name" />
            <NumberInputControl
              name="age"
              label="Age"
              helperText="Helper text"
            />
            <CheckboxSingleControl name="employed">
              Employed
            </CheckboxSingleControl>
            <RadioGroupControl name="favoriteColor" label="Favorite Color">
              <Radio value="#ff0000">Red</Radio>
              <Radio value="#00ff00">Green</Radio>
              <Radio value="#0000ff">Blue</Radio>
            </RadioGroupControl>
            <CheckboxContainer name="toppings" label="Toppings">
              <CheckboxControl name="toppings1" value="chicken">
                Chicken
              </CheckboxControl>
              <CheckboxControl name="toppings" value="ham">
                Ham
              </CheckboxControl>
              <CheckboxControl name="toppings" value="mushrooms">
                Mushrooms
              </CheckboxControl>
              <CheckboxControl name="toppings" value="cheese">
                Cheese
              </CheckboxControl>
              <CheckboxControl name="toppings" value="tuna">
                Tuna
              </CheckboxControl>
              <CheckboxControl name="toppings" value="pineapple">
                Pineapple
              </CheckboxControl>
            </CheckboxContainer>
            <TextareaControl name="notes" label="Notes" />
            <SwitchControl name="employedd" label="Employed" />
            <SelectControl
              label="Select label"
              name="select"
              selectProps={{ placeholder: 'Select option' }}
            >
              <option value="option1">Option 1</option>
              <option value="option2">Option 2</option>
              <option value="option3">Option 3</option>
            </SelectControl>
            <SliderControl name="foo" sliderProps={{ max: 40 }} />
            <PinInputControl
              name="bar"
              pinAmount={4}
              pinInputProps={{ size: 'sm' }}
            />

            <PercentComplete />
            <FormControl
              name="customField"
              label="Custom FormControl"
              helperText="Helper text"
            >
              <Field
                as={Input}
                name="customField"
                placeholder="A custom field"
              />
            </FormControl>
            <InputControl
              name="customElements"
              label="Custom elements"
              labelProps={{ color: 'blue' }}
              errorMessageProps={{ fontWeight: 'bold' }}
              helperText="Helper text"
              helperTextProps={{ fontStyle: 'italic' }}
            />
            <ButtonGroup>
              <SubmitButton>Submit</SubmitButton>
              <ResetButton>Reset</ResetButton>
            </ButtonGroup>

            <Box as="pre" marginY={10}>
              {JSON.stringify(values, null, 2)}
              <br />
              {JSON.stringify(errors, null, 2)}
            </Box>
          </Stack>
        )}
      </Formik>
    </ChakraProvider>
  );
}
Example #28
Source File: AppDomains.tsx    From ledokku with MIT License 4 votes vote down vote up
AppDomains = ({ appId }: AppDomainProps) => {
  const toast = useToast();
  const { data, loading /* error */ } = useAppByIdQuery({
    variables: {
      appId,
    },
    ssr: false,
    skip: !appId,
  });

  const {
    data: domainsData,
    loading: domainsDataLoading,
    refetch: appDomainsRefetch,
  } = useDomainsQuery({
    variables: {
      appId,
    },
  });

  const [
    removeDomainMutation,
    { loading: removeDomainMutationLoading },
  ] = useRemoveDomainMutation();

  const handleRemoveDomain = async (domain: string) => {
    try {
      await removeDomainMutation({
        variables: {
          input: {
            appId,
            domainName: domain,
          },
        },
        refetchQueries: [{ query: DomainsDocument, variables: { appId } }],
      });
      toast.success('Domain removed successfully');
    } catch (error) {
      toast.error(error.message);
    }
  };

  if (!data) {
    return null;
  }

  // // TODO display error

  if (loading) {
    // TODO nice loading
    return <p>Loading...</p>;
  }

  const { app } = data;

  if (!app) {
    // TODO nice 404
    return <p>App not found.</p>;
  }

  return (
    <>
      <Box py="5">
        <Heading as="h2" size="md">
          Domain management
        </Heading>
        <Text fontSize="sm" color="gray.400">
          List of domains you have added to {app.name} app
        </Text>
      </Box>

      <Grid templateColumns={{ sm: 'repeat(1, 1fr)', md: 'repeat(3, 1fr)' }}>
        <GridItem colSpan={2}>
          <Box mb="8">
            {domainsDataLoading ? <Spinner /> : null}
            {domainsData?.domains.domains.length === 0 ? (
              <Text fontSize="sm" color="gray.400">
                Currently you haven't added any custom domains to your app
              </Text>
            ) : null}
            {domainsData?.domains.domains.map((domain: any) => (
              <Flex
                key={domain}
                justifyContent="space-between"
                alignItems="center"
              >
                <Link
                  href={`http://${domain}`}
                  isExternal
                  display="flex"
                  alignItems="center"
                >
                  {domain} <Icon as={FiExternalLink} mx="2" />
                </Link>

                <IconButton
                  aria-label="Delete"
                  variant="ghost"
                  colorScheme="red"
                  icon={<FiTrash2 />}
                  disabled={removeDomainMutationLoading}
                  onClick={() => handleRemoveDomain(domain)}
                />
              </Flex>
            ))}
          </Box>

          <AddAppDomain appId={appId} appDomainsRefetch={appDomainsRefetch} />
        </GridItem>
      </Grid>
    </>
  );
}
Example #29
Source File: AccountModal.tsx    From eth-dapps-nextjs-boiletplate with MIT License 4 votes vote down vote up
export default function AccountModal({ isOpen, onClose }: Props) {
  const { globalState, dispatch } = useContext(globalContext)
  const { account, provider } = globalState
  const chainIdPaths = {
    1: '', // mainnet
    42: 'kovan.',
    3: 'ropsten.',
    4: 'rinkeby.',
    5: 'goerli.',
  }
  const chainPath = provider && chainIdPaths[parseInt(provider.chainId)]

  async function handleDeactivateAccount() {
    //deactivate();
    if (provider && !provider.isMetaMask) { // isWalletConnect then
      await provider.disconnect()
    }
    dispatch({ type: 'CLEAR_STATE'})
    onClose();
  }

  return (
    <Modal isOpen={isOpen} onClose={onClose} isCentered size="md">
      <ModalOverlay />
      <ModalContent
        background="gray.900"
        border="1px"
        borderStyle="solid"
        borderColor="gray.700"
        borderRadius="3xl"
      >
        <ModalHeader color="white" px={4} fontSize="lg" fontWeight="medium">
          Account
        </ModalHeader>
        <ModalCloseButton
          color="white"
          fontSize="sm"
          _hover={{
            color: "whiteAlpha.700",
          }}
        />
        <ModalBody pt={0} px={4}>
          <Box
            borderRadius="3xl"
            border="1px"
            borderStyle="solid"
            borderColor="gray.600"
            px={5}
            pt={4}
            pb={2}
            mb={3}
          >
            <Flex justifyContent="space-between" alignItems="center" mb={3}>
              <Text color="gray.400" fontSize="sm">
                Connected with {provider?.isMetaMask ? 'MetaMask' : 'WalletConnect'}
              </Text>
              <Button
                variant="outline"
                size="sm"
                borderColor="blue.800"
                borderRadius="3xl"
                color="blue.500"
                fontSize="13px"
                fontWeight="normal"
                px={2}
                height="26px"
                _hover={{
                  background: "none",
                  borderColor: "blue.300",
                  textDecoration: "underline",
                }}
                onClick={handleDeactivateAccount}
              >
                Disconnect
              </Button>
            </Flex>
            <Flex alignItems="center" mt={2} mb={4} lineHeight={1}>
              <Identicon />
              <Text
                color="white"
                fontSize="xl"
                fontWeight="semibold"
                ml="2"
                lineHeight="1.1"
              >
                {account &&
                  `${account.slice(0, 6)}...${account.slice(
                    account.length - 4,
                    account.length
                  )}`}
              </Text>
            </Flex>
            <Flex alignContent="center" m={3}>
              <Button
                variant="link"
                color="gray.400"
                fontWeight="normal"
                fontSize="sm"
                _hover={{
                  textDecoration: "none",
                  color: "whiteAlpha.800",
                }}
              >
                <CopyIcon mr={1} />
                Copy Address
              </Button>
              {
              chainPath?
              <Link
                fontSize="sm"
                display="flex"
                alignItems="center"
                href={`https://${chainPath}etherscan.io/address/${account}`}
                isExternal
                color="gray.400"
                ml={6}
                _hover={{
                  color: "whiteAlpha.800",
                  textDecoration: "underline",
                }}
              >  
                <ExternalLinkIcon mr={1} />
                View on Explorer
              </Link>:''
              }
            </Flex>
          </Box>
        </ModalBody>

        <ModalFooter
          justifyContent="end"
          background="gray.700"
          borderBottomLeftRadius="3xl"
          borderBottomRightRadius="3xl"
          p={6}
        >
          <Text
            color="white"
            textAlign="left"
            fontWeight="medium"
            fontSize="md"
          >
            Your transactions will appear here...
          </Text>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
}