@chakra-ui/icons#DeleteIcon TypeScript Examples

The following examples show how to use @chakra-ui/icons#DeleteIcon. 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: UserListItem.tsx    From next-crud with MIT License 6 votes vote down vote up
UserListItem = ({ id, username, onEdit, onDelete }: IProps) => {
  return (
    <Flex
      direction="row"
      align="center"
      justify="space-between"
      py={2}
      width="100%"
    >
      <HStack spacing={8} align="center">
        <Text>#{id}</Text>
        <Text>{username}</Text>
      </HStack>
      <ButtonGroup spacing={2}>
        <IconButton
          aria-label="Edit"
          icon={<EditIcon color="white" />}
          colorScheme="blue"
          onClick={() => onEdit(id)}
          size="sm"
        />
        <IconButton
          aria-label="Delete"
          icon={<DeleteIcon color="white" />}
          colorScheme="red"
          onClick={() => onDelete(id)}
          size="sm"
        />
      </ButtonGroup>
    </Flex>
  )
}
Example #2
Source File: DeleteButton.tsx    From coindrop with GNU General Public License v3.0 5 votes vote down vote up
DeleteButton: FunctionComponent<Props> = ({ piggybankName }) => {
    const { push } = useRouter();
    const [awaitingDeleteConfirmation, setAwaitingDeleteConfirmation] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);
    const {
        piggybankDbData: {
            avatar_storage_id,
            owner_uid: ownerUid,
        },
    } = useContext(PublicPiggybankDataContext);
    async function handleDelete() {
        if (!awaitingDeleteConfirmation) {
            return setAwaitingDeleteConfirmation(true);
        }
        try {
            setIsDeleting(true);
            await Promise.all([
                deleteImage({
                    storageId: avatar_storage_id,
                    ownerUid,
                    piggybankName,
                }),
                db.collection('piggybanks').doc(piggybankName).delete(),
            ]);
            fetch(`/${piggybankName}`, { headers: { isToForceStaticRegeneration: "true" }});
            push('/dashboard');
        } catch (err) {
            setAwaitingDeleteConfirmation(false);
        }
        return undefined;
    }
    useEffect(() => {
        if (awaitingDeleteConfirmation) {
            setTimeout(() => {
                if (awaitingDeleteConfirmation) {
                    setAwaitingDeleteConfirmation(false);
                }
            }, 3000);
        }
    });
    return (
        <Button
            id="delete-coindrop-button"
            leftIcon={<DeleteIcon />}
            colorScheme={awaitingDeleteConfirmation ? "red" : undefined}
            onClick={handleDelete}
            isLoading={isDeleting}
            loadingText="Deleting"
        >
            {awaitingDeleteConfirmation ? "Confirm" : "Delete"}
        </Button>
    );
}
Example #3
Source File: TunnelInfo.tsx    From wiregui with MIT License 4 votes vote down vote up
export default function TunnelInfo() {
  const history = useHistory();
  const dispatch = useDispatch();
  const [wgConfigFile, setWgConfigFile] = useState<WgConfigFile>();
  const [fileName, setFileName] = useState<string>("");
  const [interfaceText, setInterfaceText] = useState<string>("");
  const [originalInterfaceText, setOriginalInterfaceText] = useState<string>(
    ""
  );
  const { name } = useParams<TunnelParam>();
  const { files } = useSelector<StoreState, WgConfigState>(
    (state) => state.wgConfig
  );
  const { userDataPath } = useSelector<StoreState, AppState>(
    (state) => state.app
  );

  useEffect(() => {
    const filePath = path.join(userDataPath, "configurations", `${name}.conf`);

    const data = fs.readFileSync(filePath, "utf-8");
    const config = new WgConfig({});
    config.parse(data);

    setFileName(name);
    setInterfaceText(config.toString());
    setOriginalInterfaceText(config.toString());
    setWgConfigFile(files.find((f) => f.name === name));
  }, [name]);

  useEffect(() => {
    setWgConfigFile(files.find((f) => f.name === name));
  }, [files]);

  async function toggleActive() {
    if (!wgConfigFile) {
      toast("Could not load 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 handleDelete() {
    if (!wgConfigFile) {
      toast(`Could not find config for ${name}`, { type: "error" });
      return;
    }

    if (wgConfigFile.active) {
      toast("Stop the tunnel before deleting", { type: "error" });
      return;
    }

    try {
      dispatch(deleteFile(wgConfigFile, userDataPath));
      history.push("/");
    } catch (e) {
      toast(e.message, { type: "error" });
    }
  }

  async function handleSave(): Promise<void> {
    if (files.some((f) => f.name === fileName && fileName !== name)) {
      toast(`A tunnel named ${fileName} already exists`, { type: "error" });
      return;
    }

    if (fileName.length > 15) {
      toast("Filename is too long, maximum 15 characters", { type: "error" });
      return;
    }

    try {
      if (wgConfigFile) {
        if (wgConfigFile.active) {
          toast("Stop the tunnel before updating", { type: "error" });
          return;
        }
        dispatch(deleteFile(wgConfigFile, userDataPath));
      }
      dispatch(addFile(`${fileName}.conf`, interfaceText, userDataPath));

      if (fileName !== name) {
        const lastConnectAt = localStorage.getItem(name);
        if (lastConnectAt) {
          localStorage.setItem(fileName, lastConnectAt);
          localStorage.removeItem(name);
        }
        history.push(`/tunnel/${fileName}`);
      }

      setOriginalInterfaceText(interfaceText);
      dispatch(fetchFiles(userDataPath));
    } catch (e) {
      toast(e.message, { type: "error" });
    }
  }

  function isAllowedToSave(): boolean {
    return (
      (fileName !== name || interfaceText !== originalInterfaceText) &&
      fileName.length > 0 &&
      interfaceText.length > 0
    );
  }

  function onNameChange(event: React.ChangeEvent<HTMLInputElement>): void {
    setFileName(event.target.value);
  }

  function onInterfaceTextChange(
    event: React.ChangeEvent<HTMLTextAreaElement>
  ): void {
    setInterfaceText(event.target.value);
  }

  function handleCancel() {
    history.push("/");
  }

  return (
    <Content>
      <Flex
        bg="gray.200"
        borderRadius="4"
        color="whiteAlpha.700"
        direction="column"
        p="4"
        w="575px"
        h="auto"
        mx="auto"
        my="10"
      >
        <Flex justify="space-between" w="100%">
          <Text color="whiteAlpha.800" fontSize="lg" fontWeight="bold">
            {name}
          </Text>
          <DialogButton
            title="Delete"
            color="whiteAlpha.800"
            colorScheme="red"
            header="Are you sure?"
            body="You cannot recover this file after deleting."
            onConfirm={handleDelete}
            launchButtonText={<DeleteIcon />}
          />
        </Flex>
        <Flex align="center" mt="4" w="100%">
          <Text>Name:</Text>
          <Input
            bg="gray.300"
            borderColor="transparent"
            size="xs"
            w="50%"
            ml="2"
            value={fileName}
            onChange={onNameChange}
          />
        </Flex>
        <Flex direction="column" mt="4" w="100%" h="100%">
          <Text fontWeight="medium">Interface:&nbsp;</Text>
          <Textarea
            bg="gray.300"
            borderColor="transparent"
            size="xs"
            resize="none"
            mt="2"
            w="100%"
            h="100%"
            value={interfaceText}
            onChange={onInterfaceTextChange}
          />
        </Flex>
        <Flex justify="flex-end" mt="4">
          <Button size="sm" onClick={handleCancel}>
            Cancel
          </Button>
          <Button colorScheme="orange" color="whiteAlpha.800" size="sm" ml="4" onClick={toggleActive}>
            {wgConfigFile && wgConfigFile.active ? "Deactivate" : "Activate"}
          </Button>
          {isAllowedToSave() && (
            <Button colorScheme="green" color="blackAlpha.800" size="sm" ml="4" onClick={handleSave}>
              Save
            </Button>
          )}
        </Flex>
      </Flex>
    </Content>
  );
}
Example #4
Source File: notes-list.tsx    From notebook with MIT License 4 votes vote down vote up
NotesList: React.SFC<NotesListProps> = ({
  notes,
  handleClick,
  setNotes
}) => {
  const bg = useColorModeValue("white", "#2f3244");
  const [selectedNote, setSelectedNote] = React.useState<note>();
  const toast = useToast();
  const { isOpen, onOpen, onClose } = useDisclosure();

  const onDelete = (
    id: string,
    e: React.MouseEvent<SVGElement, MouseEvent>
  ) => {
    const newNotes: note[] = notes.filter((note: note) => note.id !== id);
    setNotes(newNotes);
    showToast();
    e.stopPropagation();
  };

  const onClick = (id: string, e: React.MouseEvent<SVGElement, MouseEvent>) => {
    handleClick(id);
    e.stopPropagation();
  };

  const handleSelectedNote = (note: note) => {
    setSelectedNote(note);
    onOpen();
  };

  const showToast = () => {
    toast({
      title: "Note deleted.",
      status: "success",
      position: "top",
      duration: 2000,
      isClosable: true
    });
  };

  return (
    <>
      <AnimateSharedLayout type="crossfade">
        <Box minH={"50vh"}>
          {/* <SimpleGrid
            columns={[1, 2, 2, 3]}
            mt="40px"
            gridGap="10px"
            position="relative"
            overflow="hidden"
          > */}
          <StackGrid columnWidth={330}>
            {notes.map(note => (
              <Fade in={true}>
                <motion.div
                  whileHover={{ y: -10 }}
                  layoutId={note.id}
                  onClick={() => handleSelectedNote(note)}
                >
                  <Center py={2} px={2} key={note.id}>
                    <Box
                      maxH={"400px"}
                      w="100%"
                      boxShadow={"lg"}
                      rounded={"md"}
                      p={6}
                      overflow={"hidden"}
                      cursor="pointer"
                      _hover={{ boxShadow: "xl" }}
                      bg={bg}
                      role="group"
                      // onClick={() => handleClick(note.id, true)}
                    >
                      <Stack>
                        <Flex
                          _groupHover={{ justifyContent: "space-between" }}
                          justifyContent="center"
                          align="center"
                        >
                          <Box>
                            <Text
                              color={"green.500"}
                              textTransform={"uppercase"}
                              fontWeight={800}
                              fontSize={"sm"}
                              letterSpacing={1.1}
                            >
                              Note
                            </Text>
                          </Box>
                          <Box
                            _groupHover={{ display: "block" }}
                            display="none"
                          >
                            <HStack spacing="2">
                              <Icon
                                color={"green.500"}
                                _hover={{ color: "green.600" }}
                                _groupHover={{ display: "block" }}
                                as={EditIcon}
                                w={4}
                                h={4}
                                onClick={e => onClick(note.id, e)}
                              />
                              <Icon
                                color={"green.500"}
                                _hover={{ color: "#ca364a" }}
                                _groupHover={{ display: "block" }}
                                as={DeleteIcon}
                                w={4}
                                h={4}
                                onClick={e => onDelete(note.id, e)}
                              />
                            </HStack>
                          </Box>
                        </Flex>
                        <Heading
                          fontSize={"xl"}
                          fontFamily={"body"}
                          textTransform="capitalize"
                          noOfLines={2}
                        >
                          {note.title}
                        </Heading>

                        <Text
                          color={"gray.500"}
                          fontSize="md"
                          noOfLines={{ base: 3, md: 4 }}
                        >
                          {note.body}
                        </Text>
                      </Stack>
                    </Box>
                  </Center>
                </motion.div>
              </Fade>
            ))}
          </StackGrid>
          {/* </SimpleGrid> */}
        </Box>
        {isOpen ? (
          <NoteModal
            isOpen={isOpen}
            onClose={onClose}
            selectedNote={selectedNote}
          />
        ) : (
          ""
        )}
      </AnimateSharedLayout>
    </>
  );
}
Example #5
Source File: FuseTabBar.tsx    From rari-dApp with GNU Affero General Public License v3.0 4 votes vote down vote up
FuseTabBar = () => {
  const isMobile = useIsSmallScreen();

  const { t } = useTranslation();

  let { poolId } = useParams();

  let navigate = useNavigate();

  const filter = useFilter();
  const location = useLocation();

  const hasCreatedPools = useHasCreatedPools();

  return (
    <DashboardBox width="100%" mt={4} height={isMobile ? "auto" : "65px"}>
      <RowOrColumn
        isRow={!isMobile}
        expand
        mainAxisAlignment="flex-start"
        crossAxisAlignment="center"
        p={4}
      >
        {!poolId ? (
          <ButtonGroup
            mr={4}
            size="sm"
            isAttached
            variant="outline"
            height="35px"
          >
            <DashboardBox height="35px">
              <Row
                pl={2}
                expand
                crossAxisAlignment="center"
                mainAxisAlignment="flex-start"
                fontWeight="bold"
              >
                <Text flexShrink={0}>{t("Search:")}</Text>

                <Input
                  value={filter ?? ""}
                  onChange={(event) => {
                    const value = encodeURIComponent(event.target.value);

                    if (value) {
                      navigate("?filter=" + value);
                    } else {
                      navigate("");
                    }
                  }}
                  width="100px"
                  height="100%"
                  ml={2}
                  placeholder={t("USDC, DAI")}
                  variant="filled"
                  size="sm"
                  _placeholder={{ color: "#e0e0e0" }}
                  _focus={{ bg: "#282727" }}
                  _hover={{ bg: "#282727" }}
                  bg="#282727"
                  borderRadius={filter ? "0px" : "0px 9px 9px 0px"}
                />
              </Row>
            </DashboardBox>
            {filter ? (
              <DashboardBox bg="#282727" ml={-1}>
                <Link
                  /* @ts-ignore */
                  as={RouterLink}
                  to=""
                >
                  <Center expand pr={2} fontWeight="bold">
                    <DeleteIcon mb="2px" />
                  </Center>
                </Link>
              </DashboardBox>
            ) : null}
          </ButtonGroup>
        ) : null}

        <TabLink ml={0} route="/fuse?filter=my-pools" text={t("My Pools")} />

        <TabLink route="/fuse" text={t("Verified Pools")} />

        <TabLink
          route="/fuse?filter=unverified-pools"
          text={t("Unverified Pools")}
        />

        {hasCreatedPools && (
          <TabLink
            route="/fuse?filter=created-pools"
            text={t("Created Pools")}
          />
        )}

        <TabExternalLink
          route="https://metrics.rari.capital"
          text={t("Metrics")}
        />

        <TabLink route="/fuse/liquidations" text={t("Liquidations")} />

        {poolId ? (
          <>
            <DashboardBox
              {...(!location.pathname.includes("info") ? activeStyle : {})}
              ml={isMobile ? 0 : 4}
              mt={isMobile ? 4 : 0}
              height="35px"
            >
              <Link
                /* @ts-ignore */
                as={RouterLink}
                to={`/fuse/pool/${poolId}`}
                className="no-underline"
              >
                <Center expand px={2} fontWeight="bold">
                  {t("Pool #{{poolId}}", { poolId })}
                </Center>
              </Link>
            </DashboardBox>

            <DashboardBox
              {...(location.pathname.includes("info") ? activeStyle : {})}
              ml={isMobile ? 0 : 4}
              mt={isMobile ? 4 : 0}
              height="35px"
            >
              <Link
                /* @ts-ignore */
                as={RouterLink}
                to={`/fuse/pool/${poolId}/info`}
                className="no-underline"
              >
                <Center expand px={2} fontWeight="bold">
                  {t("Pool #{{poolId}} Info", { poolId })}
                </Center>
              </Link>
            </DashboardBox>
          </>
        ) : null}

        <NewPoolButton />
      </RowOrColumn>
    </DashboardBox>
  );
}
Example #6
Source File: AvatarInput.tsx    From coindrop with GNU General Public License v3.0 4 votes vote down vote up
AvatarInput: FunctionComponent = () => {
    const inputRef = useRef<FileInputRef>(null);
    const { piggybankDbData } = useContext(PublicPiggybankDataContext);
    const currentAvatarStorageId = piggybankDbData.avatar_storage_id;
    const { query: { piggybankName: piggybankNameQuery } } = useRouter();
    const piggybankName = typeof piggybankNameQuery === 'string' ? piggybankNameQuery : piggybankNameQuery[0];
    const { user } = useUser();
    const uid = user?.id;
    const piggybankRef = db.collection('piggybanks').doc(piggybankName);
    const fileSizeError = "Image too large";
    const contentTypeError = "Only images are accepted";
    const imageDimensionsError = "Image height and width must be >= 250px";
    const [fileSelectErrorMessage, setFileSelectErrorMessage] = useState("");
    function clearInput() { inputRef.current.value = null; }
    const setAvatar = async (newAvatarStorageId) => {
      Promise.all([
        piggybankRef.set({ avatar_storage_id: newAvatarStorageId }, { merge: true }),
        deleteImage({
          storageId: currentAvatarStorageId,
          ownerUid: uid,
          piggybankName,
        }),
      ]);
      mutate(['publicPiggybankData', piggybankName], { ...piggybankDbData, avatar_storage_id: newAvatarStorageId });
    };
    const onInputChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
      setFileSelectErrorMessage(null);
      const file = event?.target?.files?.[0];
      const storageRef = storage.ref();
      const newAvatarStorageId = uuidV4();
      const newAvatarPath = piggybankImageStoragePath({ ownerUid: uid, piggybankName, imageAs: "avatar", imageStorageId: newAvatarStorageId });
      const newAvatarRef = storageRef.child(newAvatarPath);
      if (file) {
        try {
          const contentType = file.type;
          if (!contentType.startsWith("image/")) {
            throw new Error(contentTypeError);
          }
          if (file.size > 1000000) {
            throw new Error(fileSizeError);
          }
          const { width, height } = await getImageDimensions(file);
          if (width < 250 || height < 250) {
            throw new Error(imageDimensionsError);
          }
          await newAvatarRef.put(file);
          clearInput();
          setAvatar(newAvatarStorageId);
        } catch (err) {
          const { message } = err;
          if (message === fileSizeError) {
            setFileSelectErrorMessage("Image too large. Please resize image to < 1MB.");
          } else if (message === contentTypeError) {
            setFileSelectErrorMessage("Only .jpg, .png, and .webp images are accepted.");
          } else if (message === imageDimensionsError) {
            setFileSelectErrorMessage("Width and height must be at least 250px");
          } else {
            setFileSelectErrorMessage("Error during upload. Please try again.");
          }
          clearInput();
        }
      }
    };
    return (
      <>
        <FormLabel htmlFor="avatar-input">Image</FormLabel>
        <Stack id="avatar-input-container">
          <Box mx="auto">
            {
              currentAvatarStorageId
              ? <Avatar />
              : (
                <NextImage
                  id="avatar-img"
                  width={200}
                  height={200}
                  src="/avatar-placeholder.png"
                  alt="avatar placeholder"
                  data-cy="avatar-placeholder"
                />
              )
            }
          </Box>
          <Center>
            <Flex wrap="wrap" justify="center">
              <Box mt={1}>
                <FileInput
                  text={currentAvatarStorageId ? "Upload new image" : "Upload image"}
                  id="avatar-input"
                  ref={inputRef}
                  accept="image/png, image/jpeg, image/webp"
                  onChange={onInputChange}
                />
              </Box>
              {currentAvatarStorageId && (
                <Box ml={2} mt={1}>
                  <Button
                    onClick={() => {
                      setAvatar(null);
                    }}
                    colorScheme="red"
                    size="sm"
                    leftIcon={<DeleteIcon />}
                    data-cy="remove-image-btn"
                  >
                    Remove image
                  </Button>
                </Box>
              )}
            </Flex>
          </Center>
          {fileSelectErrorMessage && (
            <Text textAlign="center" color="red.500">
              <WarningIcon mr={2} />
              {fileSelectErrorMessage}
            </Text>
          )}
        </Stack>
      </>
    );
}