@chakra-ui/react#AspectRatio TypeScript Examples

The following examples show how to use @chakra-ui/react#AspectRatio. 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: AspectRatioBoxPreview.tsx    From openchakra with MIT License 6 votes vote down vote up
AspectRatioPreview: React.FC<{ component: IComponent }> = ({
  component,
}) => {
  const { props, ref } = useInteractive(component, true)
  const { drop, isOver } = useDropComponent(
    component.id,
    undefined,
    component.children.length === 0,
  )
  const children = component.children

  const boxProps: any = {}

  if (isOver) {
    props.bg = 'teal.50'
  }

  return (
    <Box {...boxProps} ref={drop(ref)}>
      <AspectRatio {...props}>
        {!children.length ? (
          /*
           * We need at least one children because of the implementation
           * of AspectRatio
           */
          <Box />
        ) : (
          <Box>
            <ComponentPreview componentName={children[0]} />
          </Box>
        )}
      </AspectRatio>
    </Box>
  )
}
Example #2
Source File: IntermissionScreen.tsx    From takeout-app with MIT License 6 votes vote down vote up
IntermissionScreen: React.FC = () => {
  return (
    <Box w="100vw" h="auto" maxW="1920px" maxH="1080px">
      <AspectRatio ratio={16 / 9}>
        <Box bgColor="#D7D165" bgImage="/assets/screen-bg.png" bgSize="contain" w="100%" h="100%" p="2.5vw">
          <IntermissionScreenInner />
        </Box>
      </AspectRatio>
    </Box>
  );
}
Example #3
Source File: TrackPage.tsx    From takeout-app with MIT License 6 votes vote down vote up
TrackViewSkeleton: React.FC = () => {
  return (
    <Container maxW={["auto", "auto", "auto", "1700px"]} px="15px" py="22px">
      <Flex alignItems="top" justifyContent="space-between" direction={["column", "column", "column", "row"]}>
        <Box w="100%">
          <AspectRatio ratio={16 / 9}>
            <Skeleton w="100%" h="100%" />
          </AspectRatio>
        </Box>

        <Box maxW={["auto", "auto", "auto", "400px"]} minH="400px" w="100%" ml="30px"></Box>
      </Flex>
      <Flex alignItems="top" justifyContent="space-between" direction={["column", "column", "column", "row"]} mt="12px">
        <Box w="100%">
          <Skeleton w="100%" h="100px" />
        </Box>
        <Box maxW={["auto", "auto", "auto", "400px"]} w="100%" ml="30px" />
      </Flex>
    </Container>
  );
}
Example #4
Source File: TrackVideo.tsx    From takeout-app with MIT License 6 votes vote down vote up
TrackOfflineView: React.FC = () => {
  return (
    <AspectRatio ratio={16 / 9}>
      <Center w="100%" h="100%">
        <VStack>
          <Box w="95px" h="95px" css={{ filter: "grayscale(1)" }}>
            <picture>
              <source type="image/webp" srcSet="/assets/hero_hamburger.webp" />
              <Image src="/assets/hero_hamburger.svg" w="100%" h="100%" alt="" />
            </picture>
          </Box>
          <Heading as="div" color={Colors.textMuted}>
            Offline...
          </Heading>
        </VStack>
      </Center>
    </AspectRatio>
  );
}
Example #5
Source File: SpeakerAvatar.tsx    From takeout-app with MIT License 5 votes vote down vote up
SpeakerAvatar: React.FC<Props> = ({ speakers }) => {
  if (speakers.length == 0) return <></>;
  if (speakers.length == 1) {
    const speaker = speakers[0];
    return (
      <AspectRatio ratio={1}>
        <Box w="100%" h="100%">
          <Image w="100%" h="100%" alt="" src={speaker.avatar_url} fallbackSrc={DEFAULT_AVATAR_URL} />
        </Box>
      </AspectRatio>
    );
  } else {
    const speakerA = speakers[0];
    const speakerB = speakers[1];

    return (
      <AspectRatio ratio={1}>
        <Box w="100%" h="100%">
          <Box w="100%" h="100%">
            <Image
              w="60%"
              h="60%"
              position="absolute"
              bottom={0}
              right={0}
              alt=""
              src={speakerB.avatar_url}
              fallbackSrc={DEFAULT_AVATAR_URL}
            />
            <Image
              w="60%"
              position="absolute"
              top={0}
              left={0}
              h="60%"
              alt=""
              src={speakerA.avatar_url}
              fallbackSrc={DEFAULT_AVATAR_URL}
            />
          </Box>
        </Box>
      </AspectRatio>
    );
  }
}
Example #6
Source File: TrackVideo.tsx    From takeout-app with MIT License 5 votes vote down vote up
TrackVideo: React.FC<Props> = ({ track, streamOptions }) => {
  const [streamTokenNotExpired, setStreamTokenNotExpired] = React.useState(true);
  const [isPlaying, setIsPlaying] = React.useState(true);
  const streamKind = determineStreamKind(track, streamOptions.interpretation);
  const streamPresence = track.presences[streamKind];

  // TODO: handle error
  const { data: streamInfo, mutate: streamMutate } = Api.useStream(track.slug, streamKind === "interpretation");

  React.useEffect(() => {
    const now = dayjs().unix() + 180;
    if (streamInfo?.stream && streamInfo.stream.expiry <= now) {
      setStreamTokenNotExpired(false);
      console.log("TrackVideo: request streamData renew");

      const timer = setInterval(() => {
        console.log("Requesting streamData due to expiration");
        streamMutate();
      }, 1000);
      return () => clearInterval(timer);
    } else {
      setStreamTokenNotExpired(true);
    }
  }, [track.slug, streamKind, streamInfo?.stream?.expiry]);

  if (!streamPresence?.online) {
    return <TrackOfflineView />;
  }

  if (streamInfo && !streamInfo.stream) {
    return <TrackOfflineView />;
  }

  if (streamInfo?.stream && streamTokenNotExpired) {
    if (!streamInfo) throw "wut";
    return (
      <StreamView
        key={`${streamInfo.stream.slug}/${streamInfo.stream.type}`}
        playbackUrl={streamInfo.stream.url}
        shouldStartPlayback={isPlaying}
        onPlayOrStop={setIsPlaying}
      />
    );
  } else {
    return (
      <AspectRatio ratio={16 / 9}>
        <Skeleton h="100%" w="100%" />
      </AspectRatio>
    );
  }
}
Example #7
Source File: offline-data-card.tsx    From portfolio with MIT License 4 votes vote down vote up
RepositoryCard = (props: RepositoryCardProps) => {
  const {
    key,
    title,
    description,
    cover,
    blurHash,
    technologies,
    url,
    live,
    stars,
    fork,
  } = props;
  const { isOpen, onOpen, onClose } = useDisclosure();

  const handleClick = () => {
    onOpen();
    // window.open(link);
    // if (type == "link" || type == "article") {
    //   window.open(link);
    // } else {
    //   onOpen();
    // }
  };

  const handleLinkClick = (
    e: React.MouseEvent<HTMLParagraphElement, MouseEvent>,
    link: string
  ) => {
    window.open(link);
    e.stopPropagation();
  };

  const transition = { duration: 0.5, ease: [0.43, 0.13, 0.23, 0.96] };

  const thumbnailVariants = {
    initial: { scale: 0.9, opacity: 0 },
    enter: { scale: 1, opacity: 1, transition },
    exit: {
      scale: 0.5,
      opacity: 0,
      transition: { duration: 1.5, ...transition }
    }
  };

  const imageVariants = {
    hover: { scale: 1.1 }
  };

  return (
    <CardTransition>
      <Box onClick={handleClick} cursor="pointer" size="xl">
        <VStack
          //   w="100%"
          rounded="xl"
          borderWidth="1px"
          bg={useColorModeValue("white", "gray.800")}
          borderColor={useColorModeValue("gray.100", "gray.700")}
          _hover={{
            shadow: "lg",
            textDecoration: "none"
          }}
          overflow="hidden"
          align="start"
          spacing={0}
        >
          <Box position="relative" w="100%">
            <MotionBox variants={thumbnailVariants}>
              <MotionBox
                whileHover="hover"
                variants={imageVariants}
                transition={transition}
              >
                <AspectRatio
                  ratio={1.85 / 1}
                  maxW="400px"
                  w="100%"
                  borderBottomWidth="1px"
                  borderColor={useColorModeValue("gray.100", "gray.700")}
                >
                  {/* <Image
                    src={cover}
                    fallback={<Skeleton />}
                    objectFit="cover"
                  /> */}
                  <LazyImage
                    src={cover}
                    blurHash={blurHash}
                  />
                </AspectRatio>
              </MotionBox>
            </MotionBox>
          </Box>

          <VStack py={2} px={[2, 4]} spacing={1} align="start" w="100%">
            <Flex justifyContent={"space-between"} width="100%">
              <Tooltip hasArrow label="Github link" placement="top">
                <HStack>
                  <Icon as={FiGithub} boxSize="0.9em" mt={"1px"} />
                  {/* <Link href={url} isExternal> */}
                  <Text
                    fontSize="sm"
                    noOfLines={1}
                    fontWeight="600"
                    align="left"
                    onClick={e => handleLinkClick(e, url)}
                  >
                    {title}
                  </Text>
                </HStack>
              </Tooltip>
              {/* </Link> */}
              <Flex>
                <Icon as={AiOutlineStar} boxSize="0.9em" mt={"1px"} />
                <Box as="span" ml="1" fontSize="sm">
                  {stars}
                </Box>
              </Flex>
            </Flex>
            <Flex justifyContent={"space-between"} width="100%">
              <Box>
                <HStack spacing="1">
                  {technologies.map(tech => (
                    <Tag size="sm" colorScheme={getTagColor(tech)}>
                      <Text fontSize={["0.55rem", "inherit", "inherit"]}>
                        {tech}
                      </Text>
                    </Tag>
                  ))}
                </HStack>
              </Box>
            </Flex>
            {/* <Flex justifyContent={"space-between"} width="100%">
              <Flex>
                <AiOutlineStar color="teal.300" />
                <Box as="span" ml="1" fontSize="sm">
                  {stars}
                </Box>
              </Flex>
              <Box >
              <Text
                fontSize="xs"
                fontWeight="400"
                color={useColorModeValue("gray.400", "gray.500")}
              >
                {created}
              </Text>
            </Box>
            </Flex> */}
          </VStack>
        </VStack>
        <Modal isOpen={isOpen} onClose={onClose} isCentered allowPinchZoom>
          <ModalOverlay />
          <ModalContent bg="none" maxW={"28rem"} w="auto">
            <ModalBody p={0} rounded="lg" overflow="hidden" bg="none">
              <Center>
                <Image src={cover} rounded="lg" />
                {/* {type == "image" ? (
                <Image src={cover} rounded="lg" />
              ) : (
                <ReactPlayer url={link} controls playing />
              )} */}
              </Center>
            </ModalBody>
          </ModalContent>
        </Modal>
      </Box>
    </CardTransition>
  );
}
Example #8
Source File: TrackVideo.tsx    From takeout-app with MIT License 4 votes vote down vote up
StreamView: React.FC<StreamViewProps> = ({ playbackUrl, shouldStartPlayback, onPlayOrStop }) => {
  const [_session, setSession] = React.useState<StreamPlaybackSession | null>(null);
  const elem = React.useRef<HTMLDivElement>(null);

  const volumeStorageKey = "rk-takeout-app--DefaultVolume";
  const { volume: defaultVolume, muted: defaultMuted } = ((): { volume: number; muted: boolean } => {
    try {
      return JSON.parse(window.localStorage?.getItem(volumeStorageKey) || '{"volume": 0.5, "muted": false}');
    } catch (e) {
      console.warn(e);
      return { volume: 0.5, muted: false };
    }
  })();

  React.useEffect(() => {
    if (!elem.current) return; // TODO: これほんとにだいじょうぶ?? でも elem.current を dep にいれると2回 useEffect 発火するんだよな
    console.log("StreamView: initializing", playbackUrl, elem.current);

    const root = document.createElement("div");
    root.dataset.vjsPlayer = "true";
    const video = document.createElement("video");
    video.playsInline = true;
    video.classList.add("video-js");

    root.appendChild(video);
    elem.current.appendChild(root);

    const player = videojs(
      video,
      {
        techOrder: ["AmazonIVS"],
        autoplay: shouldStartPlayback,
        controls: true,
        fill: true,
      },
      () => {
        console.log("player is ready");
      },
    ) as videojs.Player & VideoJSIVSTech & VideoJSQualityPlugin;

    player.enableIVSQualityPlugin();
    player.src(playbackUrl);

    player.volume(defaultVolume);
    player.muted(!!defaultMuted);

    player.on("play", () => {
      onPlayOrStop(true);
    });
    player.on("pause", () => {
      onPlayOrStop(false);
    });

    player.on("volumechange", () => {
      const volume = player.volume();
      const muted = player.muted();
      try {
        window.localStorage?.setItem(volumeStorageKey, JSON.stringify({ volume, muted }));
      } catch (e) {
        console.warn(e);
      }
    });

    const events: VideoJSIVSEvents = player.getIVSEvents();
    const ivsPlayer = player.getIVSPlayer();

    ivsPlayer.addEventListener(events.PlayerEventType.TEXT_METADATA_CUE, (cue) => {
      const payload: IvsMetadata = JSON.parse(cue.text);
      console.log("Incoming IVS Metadata", payload);
      try {
        consumeIvsMetadata(payload);
      } catch (e) {
        console.error("IVS metadata error", e);
      }
    });

    ivsPlayer.addEventListener(events.PlayerState.PLAYING, () => {
      console.log("IVS Player is playing");
    });

    setSession({
      url: playbackUrl,
      player,
      root,
    });

    return () => {
      console.log("StreamView: dispose", playbackUrl);
      player.dispose();
      root.remove();
    };
  }, [playbackUrl]);

  return (
    <AspectRatio ratio={16 / 9}>
      <Box w="100%" h="100%" ref={elem} />
    </AspectRatio>
  );
}
Example #9
Source File: TrackView.tsx    From takeout-app with MIT License 4 votes vote down vote up
TrackView: React.FC<Props> = ({ track, streamOptionsState }) => {
  const [streamOptions, setStreamOptions] = streamOptionsState;
  const trackOptionsSelector = (instance: string) => (
    <TrackStreamOptionsSelector track={track} streamOptionsState={streamOptionsState} instance={instance} />
  );

  // Preload candidate speaker images
  React.useEffect(() => {
    if (!track.card_candidate) return;
    if (!track.card_candidate.speakers) return;

    track.card_candidate.speakers.forEach((s) => {
      const i = new Image();
      i.onload = () => console.log("Preloaded", s.avatar_url);
      i.src = s.avatar_url;
    });
  }, [track.card_candidate]);

  // TODO: Chakra 側のブレークポイントの調整
  // TODO: hide chat button
  return (
    <Container maxW={["auto", "auto", "auto", "1700px"]} px="15px" py="22px">
      <Flex alignItems="top" justifyContent="space-between" direction={["column", "column", "column", "row"]}>
        <Box w="100%">
          <React.Suspense
            fallback={
              <AspectRatio ratio={16 / 9}>
                <Skeleton w="100%" h="100%" />
              </AspectRatio>
            }
          >
            <TrackVideo track={track} streamOptions={streamOptionsState[0]} />
          </React.Suspense>
          {streamOptions.caption ? (
            <React.Suspense fallback={<Skeleton w="100%" h="80px" />}>
              <TrackCaption
                track={track}
                onUnsubscribe={() => {
                  setStreamOptions({ ...streamOptions, caption: false });
                }}
              />
            </React.Suspense>
          ) : null}

          <Box display={["flex", "flex", "none", "none"]} justifyContent="end" my={2}>
            <Box w="150px">{trackOptionsSelector("1")}</Box>
          </Box>
        </Box>

        {streamOptions.chat && track.chat ? (
          <Box
            maxW={["auto", "auto", "auto", "400px"]}
            h={["480px", "480px", "480px", "auto"]}
            w="100%"
            ml={["0", "0", "0", "30px"]}
          >
            <React.Suspense fallback={<Skeleton w="100%" h="100%" />}>
              <TrackChat track={track} />
            </React.Suspense>
          </Box>
        ) : null}
      </Flex>

      <Flex alignItems="top" justifyContent="space-between" direction={["column", "column", "column", "row"]} mt="12px">
        <Box w="100%">
          <TrackCardView
            card={track.card}
            nav={
              <HStack alignItems="flex-start" spacing="20px">
                {track.viewerCount ? <TrackViewerCount count={track.viewerCount} /> : null}
                <Box display={["none", "none", "block", "block"]}>{trackOptionsSelector("2")}</Box>
              </HStack>
            }
          />
        </Box>
        <Box maxW={["auto", "auto", "auto", "400px"]} w="100%" ml="30px">
          <AppVersionAlert />
        </Box>
      </Flex>
    </Container>
  );
}