@chakra-ui/react#Popover JavaScript Examples

The following examples show how to use @chakra-ui/react#Popover. 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: onboarding.js    From idena-web with MIT License 6 votes vote down vote up
export function OnboardingPopover({children, ...props}) {
  return (
    <>
      {/* eslint-disable-next-line react/destructuring-assignment */}
      {props.isOpen && (
        <Box
          bg="xblack.080"
          position="fixed"
          top={0}
          left={0}
          right={0}
          bottom={0}
          zIndex={2}
          css={{margin: '0!important', padding: '0!important'}}
        />
      )}
      <Popover closeOnBlur={false} {...props}>
        {children}
      </Popover>
    </>
  )
}
Example #2
Source File: components.js    From idena-web with MIT License 5 votes vote down vote up
export function ProfileTagPopover(props) {
  return <Popover placement="top" arrowShadowColor="transparent" {...props} />
}
Example #3
Source File: Hint.js    From blobs.app with MIT License 5 votes vote down vote up
Hint = ({ text }) => (
  <Popover autoFocus={false}>
    <PopoverTrigger>
      <Button
        bg="transparent"
        p="0"
        h="auto"
        color="gray.400"
        _hover={{ bg: 'transparent', color: 'gray.600' }}
        _focus={{ outline: 'none' }}
      >
        <QuestionIcon />
      </Button>
    </PopoverTrigger>
    <PopoverContent>
      <PopoverArrow />
      <PopoverCloseButton />
      <PopoverBody>
        <Text variant="subtle" fontSize="sm" p="3">
          {text}
        </Text>
      </PopoverBody>
    </PopoverContent>
  </Popover>
)
Example #4
Source File: components.js    From idena-web with MIT License 4 votes vote down vote up
export function ProfileTagList() {
  const {t} = useTranslation()

  const [
    {age, penalty, totalShortFlipPoints, totalQualifiedFlips},
  ] = useIdentity()

  const epoch = useEpoch()

  const score = useTotalValidationScore()

  const inviteScore = useInviteScore()

  const formatDna = useFormatDna({maximumFractionDigits: 5})

  const [isMobile] = useMediaQuery('(max-width: 480px)')

  const hasAnyTag =
    age > 0 || penalty > 0 || Number.isFinite(score) || inviteScore > 0

  return (
    <Wrap
      spacing={[0, '1']}
      direction={['column', 'row']}
      w={['full']}
      mt={[hasAnyTag ? 4 : 0, 0]}
      mb={[hasAnyTag ? 3 : 0, 0]}
    >
      {age > 0 && (
        <WrapItem>
          <SimpleProfileTag label={t('Age')} value={age} />
        </WrapItem>
      )}

      {Number.isFinite(score) && (
        <WrapItem>
          {isMobile ? (
            <ProfileTag>
              <Flex align="center" justify="space-between">
                <ProfileTagLabel>{t('Score')}</ProfileTagLabel>
                <TextLink href="/validation-report" display="inline-flex">
                  {t('Validation report')}
                </TextLink>
              </Flex>
              <ProfileTagValue>{toPercent(score)}</ProfileTagValue>
            </ProfileTag>
          ) : (
            <Popover placement="top" arrowShadowColor="transparent">
              <PopoverTrigger>
                <Box>
                  <SimpleProfileTag
                    label={t('Score')}
                    value={toPercent(score)}
                    cursor="help"
                  />
                </Box>
              </PopoverTrigger>
              <PopoverContent border="none" fontSize="sm" w="max-content">
                <PopoverArrow bg="graphite.500" />
                <PopoverBody bg="graphite.500" borderRadius="sm" p="2" pt="1">
                  <Stack>
                    <Stack spacing="0.5">
                      <Text color="muted" lineHeight="shorter">
                        {t('Total score')}
                      </Text>
                      <Text color="white" lineHeight="4">
                        {t(
                          `{{totalShortFlipPoints}} out of {{totalQualifiedFlips}}`,
                          {
                            totalShortFlipPoints,
                            totalQualifiedFlips,
                          }
                        )}
                      </Text>
                    </Stack>
                    <Stack spacing="0.5">
                      <Text color="muted" lineHeight="shorter">
                        {t('Epoch #{{epoch}}', {epoch: epoch?.epoch})}
                      </Text>
                      <TextLink
                        href="/validation-report"
                        color="white"
                        lineHeight="4"
                      >
                        {t('Validation report')}
                        <ChevronRightIcon />
                      </TextLink>
                    </Stack>
                  </Stack>
                </PopoverBody>
              </PopoverContent>
            </Popover>
          )}
        </WrapItem>
      )}

      {penalty > 0 && (
        <WrapItem>
          <ProfileTag bg={[null, 'red.012']}>
            <ProfileTagLabel color="red.500">
              {t('Mining penalty')}
            </ProfileTagLabel>
            <ProfileTagValue color="red.500">
              {formatDna(penalty)}
            </ProfileTagValue>
          </ProfileTag>
        </WrapItem>
      )}

      {inviteScore && (
        <WrapItem>
          {isMobile ? (
            <ProfileTag>
              <Flex align="center" justify="space-between">
                <ProfileTagLabel>{t('Invitation rewards')}</ProfileTagLabel>
                <TextLink href="/contacts" display="inline-flex">
                  {t('Check invites')}
                </TextLink>
              </Flex>
              <ProfileTagValue>{toPercent(inviteScore)}</ProfileTagValue>
            </ProfileTag>
          ) : (
            <ProfileTagPopover>
              <ProfileTagPopoverTrigger>
                <ProfileTag
                  cursor="help"
                  bg={
                    // eslint-disable-next-line no-nested-ternary
                    inviteScore < 0.75
                      ? 'red.010'
                      : inviteScore < 0.99
                      ? 'orange.010'
                      : 'green.010'
                  }
                  color={
                    // eslint-disable-next-line no-nested-ternary
                    inviteScore < 0.75
                      ? 'red.500'
                      : inviteScore < 0.99
                      ? 'orange.500'
                      : 'green.500'
                  }
                >
                  <ProfileTagLabel>{t('Invitation rewards')}</ProfileTagLabel>
                  <ProfileTagValue>{toPercent(inviteScore)}</ProfileTagValue>
                </ProfileTag>
              </ProfileTagPopoverTrigger>
              <ProfileTagPopoverContent>
                <Stack spacing="2px" w={40}>
                  <Text color="xwhite.040" lineHeight="base">
                    {t(
                      'You will get {{invitationRewardRatio}} of the invitation rewards if your invite is activated now',
                      {invitationRewardRatio: toPercent(inviteScore)}
                    )}
                  </Text>
                  <TextLink href="/contacts" color="white" lineHeight="base">
                    {t('Check invites')}
                    <ChevronRightIcon />
                  </TextLink>
                </Stack>
              </ProfileTagPopoverContent>
            </ProfileTagPopover>
          )}
        </WrapItem>
      )}
    </Wrap>
  )
}
Example #5
Source File: containers.js    From idena-web with MIT License 4 votes vote down vote up
export function VotingPhase({service}) {
  const {t} = useTranslation()

  const [current] = useActor(service)

  const {
    createDate,
    startDate,
    finishDate,
    finishCountingDate,
    votes = [],
    votesCount,
    voteProofsCount,
    winnerThreshold,
    quorum,
    committeeSize,
    estimatedTerminationTime,
    finishTime,
    terminationTime,
  } = current.context

  const eitherIdleState = (...states) =>
    eitherState(current, ...states.map(s => `idle.${s}`.toLowerCase()))

  const didDetermineWinner = hasWinner({
    votes,
    votesCount: voteProofsCount,
    winnerThreshold,
    quorum,
    committeeSize,
    finishCountingDate,
  })

  const didReachQuorum = hasQuorum({votesCount, quorum, committeeSize})

  // eslint-disable-next-line no-nested-ternary
  const [nextPhaseLabel, nextPhaseDate] = eitherIdleState(
    VotingStatus.Deploying,
    VotingStatus.Pending,
    VotingStatus.Starting
  )
    ? [t('Start voting'), startDate]
    : // eslint-disable-next-line no-nested-ternary
    eitherIdleState(VotingStatus.Open, VotingStatus.Voting, VotingStatus.Voted)
    ? [t('End voting'), finishDate]
    : // eslint-disable-next-line no-nested-ternary
    eitherIdleState(
        VotingStatus.Counting,
        VotingStatus.Prolonging,
        VotingStatus.Finishing
      )
    ? // eslint-disable-next-line no-nested-ternary
      dayjs().isBefore(finishCountingDate)
      ? [
          didDetermineWinner
            ? t('Waiting for rewards distribution')
            : t('End counting'),
          finishCountingDate,
        ]
      : didReachQuorum
      ? [
          // eslint-disable-next-line no-nested-ternary
          didDetermineWinner
            ? isAllowedToTerminate({estimatedTerminationTime})
              ? t('Waiting for rewards distribution or termination')
              : t('Waiting for rewards distribution')
            : isAllowedToTerminate({estimatedTerminationTime})
            ? t('Waiting for refunds or termination')
            : t('Waiting for refunds'),
          null,
        ]
      : [
          isAllowedToTerminate({estimatedTerminationTime})
            ? t('Waiting for prolongation or termination')
            : t('Waiting for prolongation'),
          null,
        ]
    : // eslint-disable-next-line no-nested-ternary
    eitherIdleState(VotingStatus.Archived, VotingStatus.Terminating)
    ? [t('Waiting for termination'), finishTime]
    : eitherIdleState(VotingStatus.Terminated)
    ? [t('Terminated'), terminationTime]
    : []

  return (
    <Flex align="center" justify="space-between">
      <Box fontWeight={500}>
        <Text color="muted">{nextPhaseLabel}</Text>
        {nextPhaseDate && (
          <Text>
            {new Date(nextPhaseDate).toLocaleString()}
            {eitherIdleState(
              VotingStatus.Open,
              VotingStatus.Voted,
              VotingStatus.Counting
            ) && <Text as="span"> ({dayjs().to(nextPhaseDate)})</Text>}
          </Text>
        )}
      </Box>
      <Popover placement="top">
        <PopoverTrigger>
          <InfoButton display="inline-flex" p={0} />
        </PopoverTrigger>
        <PopoverContent
          bg="graphite.500"
          border="none"
          zIndex="popover"
          w="2xs"
          px={4}
          py={2}
          pb={4}
        >
          <PopoverArrow bg="graphite.500" />
          <PopoverHeader borderBottom="none" p={0} mb={3}>
            <Text color="white" fontWeight={500}>
              {t('Voting timeline')}
            </Text>
          </PopoverHeader>
          <PopoverBody p={0}>
            <Stack spacing="10px" fontSize="sm">
              <VotingPhase.ListItem
                isActive={false}
                label={t('Created')}
                value={new Date(createDate).toLocaleString()}
              />
              <VotingPhase.ListItem
                isActive={eitherIdleState(VotingStatus.Pending)}
                label={t('Start voting')}
                value={
                  eitherIdleState(VotingStatus.Pending)
                    ? '--'
                    : new Date(startDate).toLocaleString()
                }
              />
              <VotingPhase.ListItem
                isActive={eitherIdleState(
                  VotingStatus.Pending,
                  VotingStatus.Open,
                  VotingStatus.Voted
                )}
                label={t('End voting')}
                value={
                  eitherIdleState(VotingStatus.Pending)
                    ? '--'
                    : new Date(finishDate).toLocaleString()
                }
              />
              <VotingPhase.ListItem
                isActive={eitherIdleState(
                  VotingStatus.Pending,
                  VotingStatus.Open,
                  VotingStatus.Voted,
                  VotingStatus.Counting
                )}
                label={t('End counting')}
                value={
                  eitherIdleState(VotingStatus.Pending)
                    ? '--'
                    : new Date(finishCountingDate).toLocaleString()
                }
              />
            </Stack>
          </PopoverBody>
        </PopoverContent>
      </Popover>
    </Flex>
  )
}
Example #6
Source File: playlists.js    From grandcast.fm with Apache License 2.0 4 votes vote down vote up
export default function Playlists() {
  const { isSignedIn } = useAuth()
  const [selectedPlaylist, setSelectedPlaylist] = useState('')
  const [newPlaylist, setNewPlaylist] = useState('')
  const { data } = useQuery(GET_PLAYLISTS)
  const [createPlaylist] = useMutation(CREATE_PLAYLIST)

  const filteredPlaylist = data?.playlists?.filter((p) => {
    return p.name === selectedPlaylist
  })[0]

  return (
    <Container>
      {!isSignedIn() && <SignIn />}
      {isSignedIn() && (
        <div>
          <FormControl id="playlists">
            <Flex>
              <Select
                placeholder="Select playlist"
                onChange={(e) => setSelectedPlaylist(e.target.value)}
              >
                {data?.playlists?.map((p) => {
                  return (
                    <option key={p.name} value={p.value}>
                      {p.name}
                    </option>
                  )
                })}
              </Select>
              <Popover>
                <PopoverTrigger>
                  <Button ml={4}>
                    <AddIcon />
                  </Button>
                </PopoverTrigger>
                <PopoverContent>
                  <PopoverArrow />
                  <PopoverCloseButton />
                  <PopoverHeader>Create new playlist</PopoverHeader>
                  <PopoverBody>
                    <FormControl id="newplaylist">
                      <Input
                        type="text"
                        onChange={(e) => setNewPlaylist(e.target.value)}
                      />
                      <Button
                        mt={4}
                        onClick={() =>
                          createPlaylist({
                            variables: { playlistName: newPlaylist },
                            update: (proxy) => {
                              const data = proxy.readQuery({
                                query: GET_PLAYLISTS,
                              })

                              proxy.writeQuery({
                                query: GET_PLAYLISTS,
                                data: {
                                  playlists: [
                                    ...data.playlists,
                                    {
                                      __typename: 'Playlist',
                                      name: newPlaylist,
                                    },
                                  ],
                                },
                              })
                            },
                          })
                        }
                      >
                        Create
                      </Button>
                    </FormControl>
                  </PopoverBody>
                </PopoverContent>
              </Popover>
            </Flex>
          </FormControl>
          <VStack mt={4} spacing={4}>
            {filteredPlaylist?.episodes?.map((e) => {
              return (
                <Episode key={e.id} episode={e} playlists={data.playlists} />
              )
            })}
          </VStack>
        </div>
      )}
    </Container>
  )
}
Example #7
Source File: Account.jsx    From scaffold-directory with MIT License 4 votes vote down vote up
/*
  ~ What it does? ~

  Displays an Address, Balance, and Wallet as one Account component,
  also allows users to log in to existing accounts and log out

  ~ How can I use? ~

  <Account
    address={address}
    localProvider={localProvider}
    userProvider={userProvider}
    mainnetProvider={mainnetProvider}
    price={price}
    web3Modal={web3Modal}
    loadWeb3Modal={loadWeb3Modal}
    logoutOfWeb3Modal={logoutOfWeb3Modal}
    blockExplorer={blockExplorer}
  />

  ~ Features ~

  - Provide address={address} and get balance corresponding to the given address
  - Provide localProvider={localProvider} to access balance on local network
  - Provide userProvider={userProvider} to display a wallet
  - Provide mainnetProvider={mainnetProvider} and your address will be replaced by ENS name
              (ex. "0xa870" => "user.eth")
  - Provide price={price} of ether and get your balance converted to dollars
  - Provide web3Modal={web3Modal}, loadWeb3Modal={loadWeb3Modal}, logoutOfWeb3Modal={logoutOfWeb3Modal}
              to be able to log in/log out to/from existing accounts
  - Provide blockExplorer={blockExplorer}, click on address and get the link
              (ex. by default "https://etherscan.io/" or for xdai "https://blockscout.com/poa/xdai/")
*/

export default function Account({
  address,
  connectText,
  ensProvider,
  isWalletConnected,
  loadWeb3Modal,
  logoutOfWeb3Modal,
  setUserRole,
  userProvider,
  userRole,
}) {
  const ens = useDisplayAddress(ensProvider, address);
  const shortAddress = ellipsizedAddress(address);
  const toast = useToast({ position: "top", isClosable: true });
  const [isPopoverOpen, setIsPopoverOpen] = useState(true);
  const registerButtonRef = useRef();
  const openPopover = () => setIsPopoverOpen(true);
  const closePopover = () => setIsPopoverOpen(false);
  const { primaryFontColor, secondaryFontColor, dividerColor } = useCustomColorModes();

  if (!userRole && isWalletConnected) {
    return <Spinner />;
  }

  const hasEns = ens !== shortAddress;
  const isAdmin = userRole === USER_ROLES.admin;
  const isBuilder = userRole === USER_ROLES.builder;
  const isAnonymous = userRole === USER_ROLES.anonymous;

  const connectWallet = (
    <Button colorScheme="blue" key="loginbutton" onClick={loadWeb3Modal}>
      {connectText || "connect"}
    </Button>
  );

  const UserDisplayName = ({ mb, textAlign }) =>
    hasEns ? (
      <>
        <Text fontSize="md" fontWeight="bold" textAlign={textAlign} color={primaryFontColor}>
          {ens}
        </Text>
        <Text color={secondaryFontColor} fontSize="sm" fontWeight="normal" textAlign={textAlign} mb={mb}>
          {shortAddress}
        </Text>
      </>
    ) : (
      <Text fontSize="md" fontWeight="semibold" textAlign={textAlign} color={primaryFontColor} mb={mb}>
        {shortAddress}
      </Text>
    );

  const accountMenu = address && (
    <LinkBox>
      <Flex align="center">
        <LinkOverlay as={NavLink} to="/portfolio">
          <QRPunkBlockie withQr={false} address={address.toLowerCase()} w={9} borderRadius={6} />
        </LinkOverlay>
        <Box ml={4}>
          {/* ToDo. Move to Utils */}
          <UserDisplayName textAlign="left" />
        </Box>
        <Tooltip label="Disconnect wallet">
          <Button ml={4} onClick={logoutOfWeb3Modal} variant="outline" size="sm">
            X
          </Button>
        </Tooltip>
      </Flex>
    </LinkBox>
  );

  const handleSignUpSuccess = () => {
    closePopover();
    toast({
      title: "You are now registered!",
      description: (
        <>
          Visit{" "}
          <Link href="/portfolio" textDecoration="underline">
            your portfolio
          </Link>{" "}
          to start building
        </>
      ),
      status: "success",
    });
  };

  const anonymousMenu = address && (
    <Popover placement="bottom-end" initialFocusRef={registerButtonRef} isOpen={isPopoverOpen} onClose={closePopover}>
      <PopoverTrigger>
        <Button variant="ghost" _hover={{ backgroundColor: "gray.50" }} w={9} p={0} onClick={openPopover}>
          <Box>
            <Icon as={HeroIconUser} w={6} h={6} color={secondaryFontColor} />
            <AvatarBadge boxSize={2} bg="red.500" borderRadius="full" top="4px" right="4px" />
          </Box>
        </Button>
      </PopoverTrigger>
      <Tooltip label="Disconnect wallet">
        <Button ml={4} onClick={logoutOfWeb3Modal} variant="outline" size="sm">
          X
        </Button>
      </Tooltip>
      <PopoverContent w={72}>
        <PopoverBody
          as={Flex}
          direction="column"
          px={9}
          py={10}
          _focus={{ background: "none" }}
          _active={{ background: "none" }}
        >
          <Text color={primaryFontColor} fontWeight="bold" textAlign="center" mb={1}>
            Register as a builder
          </Text>
          <Text color={secondaryFontColor} fontSize="sm" fontWeight="normal" textAlign="center" mb={6}>
            Sign a message with your wallet to create a builder profile.
          </Text>
          <Box m="auto" p="px" borderWidth="1px" borderColor={dividerColor} borderRadius={8}>
            <QRPunkBlockie address={address} w={19} borderRadius={6} />
          </Box>
          <UserDisplayName textAlign="center" mb={6} />
          <SignatureSignUp
            ref={registerButtonRef}
            userProvider={userProvider}
            address={address}
            onSuccess={handleSignUpSuccess}
            setUserRole={setUserRole}
          />
        </PopoverBody>
      </PopoverContent>
    </Popover>
  );

  const userMenu = isAnonymous ? anonymousMenu : accountMenu;

  return (
    <Flex align="center">
      {isAdmin && (
        <Badge colorScheme="red" mr={4}>
          admin
        </Badge>
      )}
      {isBuilder && (
        <Badge colorScheme="green" mr={4}>
          builder
        </Badge>
      )}
      {isWalletConnected ? userMenu : connectWallet}
    </Flex>
  );
}