@material-ui/icons#Close TypeScript Examples

The following examples show how to use @material-ui/icons#Close. 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: Snackbar.stories.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
ActionSnackbar = styled(
  ({
    close,
    ...props
  }: SnackbarContentProps & {
    close?: () => void;
  }) => {
    return (
      <MuiSnackbarContent
        {...props}
        action={[
          <IconButton
            key="close"
            aria-label="close"
            color="inherit"
            onClick={close}
          >
            <Close />
          </IconButton>,
        ]}
      />
    );
  },
)``
Example #2
Source File: Summary.tsx    From UsTaxes with GNU Affero General Public License v3.0 6 votes vote down vote up
BinaryStateListItem = ({
  active,
  children
}: BinaryStateListItemProps): ReactElement => {
  return (
    <Grid container spacing={3}>
      <Grid item style={{ margin: 'auto' }}>
        <Avatar>
          {active ? (
            <Check titleAccess="Eligible" />
          ) : (
            <Close titleAccess="Ineligible" />
          )}
        </Avatar>
      </Grid>
      <Grid item xs zeroMinWidth>
        {children}
      </Grid>
    </Grid>
  )
}
Example #3
Source File: OpenOrdersDialog.tsx    From swap-ui with Apache License 2.0 6 votes vote down vote up
export default function OpenOrdersDialog({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  return (
    <Dialog
      maxWidth="lg"
      open={open}
      onClose={onClose}
      PaperProps={{
        style: {
          borderRadius: "10px",
        },
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
        }}
      >
        <IconButton
          onClick={onClose}
          style={{
            padding: 10,
          }}
        >
          <Close />
        </IconButton>
      </div>
      <DialogContent style={{ paddingTop: 0 }}>
        <OpenOrdersAccounts />
      </DialogContent>
    </Dialog>
  );
}
Example #4
Source File: Scores.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
ScoresSidebar = ({ score, close }: SidebarProps) => {
  return (
    <ScoresCard elevation={5}>
      <CardHeader
        action={
          <IconButton aria-label="close" onClick={close}>
            <Close />
          </IconButton>
        }
        title="Score"
      />
      <ScoresCardContent>
        <List>
          <Scores score={score} />
        </List>
      </ScoresCardContent>
    </ScoresCard>
  )
}
Example #5
Source File: index.tsx    From frontegg-react with MIT License 6 votes vote down vote up
iconMap: { [K in IconNames]: any } = {
  'down-arrow': KeyboardArrowDownRounded,
  'left-arrow': KeyboardArrowLeftRounded,
  'person-add': PersonAddRounded,
  'right-arrow': KeyboardArrowRightRounded,
  'sort-arrows-asc': ArrowUpward,
  'sort-arrows-desc': ArrowDownward,
  'sort-arrows': DeleteRounded,
  'up-arrow': KeyboardArrowUpRounded,
  'vertical-dots': MoreVertRounded,
  'visibility-off': VisibilityOff,
  back: ArrowBackRounded,
  checkmark: CheckRounded,
  copy: FileCopyRounded,
  delete: DeleteRounded,
  edit: Edit,
  filters: FilterList,
  image: ImageRounded,
  indeterminate: IndeterminateCheckBoxRounded,
  search: Search,
  send: SendRounded,
  refresh: Cached,
  'calendar-today': CalendarToday,
  flash: FlashOn,
  pdf: PictureAsPdf,
  csv: GridOn,
  visibility: Visibility,
  warning: WarningRounded,
  list: Subject,
  exit: ExitToAppRounded,
  swap: CachedRounded,
  profile: FaceRounded,
  globe: Language,
  close: Close,
}
Example #6
Source File: CloseButton.tsx    From bee-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export function CloseButton({ onClose }: Props): ReactElement {
  const classes = useStyles()

  return (
    <div className={classes.wrapper} onClick={onClose}>
      <Close />
    </div>
  )
}
Example #7
Source File: VestingClaimNotification.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
function VestingClaimNotificationBase(props: VestingClaimNotificationProps) {
  const { className, isMobileLayout = false, onClose } = props;
  const [ignore, setIgnore] = useState(false);
  return (
    <div
      className={className}
      data-layout={isMobileLayout ? 'mobile' : 'modal'}
    >
      <div>
        <img src={errorImage} alt="Error" />
      </div>
      <div>
        <h2>Claim ANC</h2>
        <p>
          This account has been affected by the oracle feeder issue on Dec. 9th
          and is eligible for reimbursement.
        </p>
        <Checkbox
          checked={ignore}
          onChange={() => setIgnore((value) => !value)}
        />
        <FlatButton component={Link} to="/anc/vesting/claim">
          Claim ANC
        </FlatButton>
        <IconButton
          className="close"
          size="small"
          onClick={() => onClose(ignore)}
        >
          <Close />
        </IconButton>
      </div>
    </div>
  );
}
Example #8
Source File: AirdropContent.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
function AirdropBase({
  className,
  onClose,
  isMobileLayout,
}: {
  className?: string;
  onClose: () => void;
  isMobileLayout: boolean;
}) {
  return (
    <div
      className={className}
      data-layout={isMobileLayout ? 'mobile' : 'modal'}
    >
      <div>
        <AirdropImage />
      </div>
      <div>
        <h2>Airdrop</h2>
        <p>Claim your ANC tokens</p>
        <FlatButton component={Link} to="/airdrop">
          Claim
        </FlatButton>
        <IconButton className="close" size="small" onClick={onClose}>
          <Close />
        </IconButton>
      </div>
    </div>
  );
}
Example #9
Source File: icons.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
RedClose = withStyles({
  root: {
    color: COLORS.red,
    fontSize: '16px',
  },
})(Close)
Example #10
Source File: status_icons.tsx    From jupyter-extensions with Apache License 2.0 5 votes vote down vote up
RedClose = withStyles({
  root: {
    color: COLORS.red,
    fontSize: '16px',
  },
})(Close)
Example #11
Source File: useNotification.tsx    From homebase-app with MIT License 5 votes vote down vote up
CloseIcon = styled(Close)({
  color: "#fff",
})
Example #12
Source File: MessageBox.tsx    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
function MessageBoxBase({
  className,
  icon,
  style,
  children,
  variant = 'normal',
  textAlign = 'center',
  hide,
}: MessageBoxProps) {
  const [hidden, setHidden] = useState<boolean>(() => {
    if (!hide) {
      return false;
    }

    const end = localStorage.getItem(key(hide.id));

    if (!end) {
      return false;
    }

    return +end > Date.now();
  });

  const updateHidden = useCallback(() => {
    if (!hide) {
      return;
    }

    localStorage.setItem(key(hide.id), (Date.now() + hide.period).toString());

    setHidden(true);
  }, [hide]);

  return !hidden ? (
    <article
      className={className}
      style={style}
      data-variant={variant}
      data-textalign={textAlign}
    >
      {icon}
      <p className={icon ? 'padded' : ''}>{children}</p>
      {!!hide && <Close className="close" onClick={updateHidden} />}
    </article>
  ) : null;
}
Example #13
Source File: TestDetailsModal.tsx    From frontend with Apache License 2.0 4 votes vote down vote up
TestDetailsModal: React.FunctionComponent<{
  testRun: TestRun;
  touched: boolean;
  handleClose: () => void;
}> = ({ testRun, touched, handleClose }) => {
  const classes = useStyles();
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();
  const testRunDispatch = useTestRunDispatch();

  const stageWidth = (window.innerWidth / 2) * 0.8;
  const stageHeigth = window.innerHeight * 0.6;
  const stageScaleBy = 1.2;
  const [stageScale, setStageScale] = React.useState(1);
  const [stagePos, setStagePos] = React.useState(defaultStagePos);
  const [stageInitPos, setStageInitPos] = React.useState(defaultStagePos);
  const [stageOffset, setStageOffset] = React.useState(defaultStagePos);
  const [processing, setProcessing] = React.useState(false);
  const [isDrawMode, setIsDrawMode] = useState(false);
  const [valueOfIgnoreOrCompare, setValueOfIgnoreOrCompare] = useState(
    "Ignore Areas"
  );
  const [isDiffShown, setIsDiffShown] = useState(false);
  const [selectedRectId, setSelectedRectId] = React.useState<string>();
  const [ignoreAreas, setIgnoreAreas] = React.useState<IgnoreArea[]>([]);
  const [applyIgnoreDialogOpen, setApplyIgnoreDialogOpen] = React.useState(
    false
  );

  const toggleApplyIgnoreDialogOpen = () => {
    setApplyIgnoreDialogOpen(!applyIgnoreDialogOpen);
  };

  const [image, imageStatus] = useImage(
    staticService.getImage(testRun.imageName)
  );
  const [baselineImage, baselineImageStatus] = useImage(
    staticService.getImage(testRun.baselineName)
  );
  const [diffImage, diffImageStatus] = useImage(
    staticService.getImage(testRun.diffName)
  );

  const applyIgnoreAreaText =
    "Apply selected ignore area to all images in this build.";

  React.useEffect(() => {
    fitStageToScreen();
    // eslint-disable-next-line
  }, [image]);

  React.useEffect(() => {
    setIsDiffShown(!!testRun.diffName);
  }, [testRun.diffName]);

  React.useEffect(() => {
    setIgnoreAreas(JSON.parse(testRun.ignoreAreas));
  }, [testRun]);

  const isImageSizeDiffer = React.useMemo(
    () =>
      testRun.baselineName &&
      testRun.imageName &&
      (image?.height !== baselineImage?.height ||
        image?.width !== baselineImage?.width),
    [image, baselineImage, testRun.baselineName, testRun.imageName]
  );

  const handleIgnoreAreaChange = (ignoreAreas: IgnoreArea[]) => {
    setIgnoreAreas(ignoreAreas);
    testRunDispatch({
      type: "touched",
      payload: testRun.ignoreAreas !== JSON.stringify(ignoreAreas),
    });
  };

  const removeSelection = (event: KonvaEventObject<MouseEvent>) => {
    // deselect when clicked not on Rect
    const isRectClicked = event.target.className === "Rect";
    if (!isRectClicked) {
      setSelectedRectId(undefined);
    }
  };

  const deleteIgnoreArea = (id: string) => {
    handleIgnoreAreaChange(ignoreAreas.filter((area) => area.id !== id));
    setSelectedRectId(undefined);
  };

  const saveTestRun = (ignoreAreas: IgnoreArea[], successMessage: string) => {
    testRunService
      .updateIgnoreAreas({
        ids: [testRun.id],
        ignoreAreas,
      })
      .then(() => {
        enqueueSnackbar(successMessage, {
          variant: "success",
        });
      })
      .catch((err) =>
        enqueueSnackbar(err, {
          variant: "error",
        })
      );
  };

  const saveIgnoreAreasOrCompareArea = () => {
    if (valueOfIgnoreOrCompare.includes("Ignore")) {
      saveTestRun(ignoreAreas, "Ignore areas are updated.");
    } else {
      const invertedIgnoreAreas = invertIgnoreArea(
        image!.width,
        image!.height,
        head(ignoreAreas)
      );

      handleIgnoreAreaChange(invertedIgnoreAreas);
      saveTestRun(
        invertedIgnoreAreas,
        "Selected area has been inverted to ignore areas and saved."
      );
    }
    testRunDispatch({ type: "touched", payload: false });
  };

  const onIgnoreOrCompareSelectChange = (value: string) => {
    if (value.includes("Compare")) {
      setValueOfIgnoreOrCompare("Compare Area");
    } else {
      setValueOfIgnoreOrCompare("Ignore Areas");
    }
  };

  const setOriginalSize = () => {
    setStageScale(1);
    resetPositioin();
  };

  const fitStageToScreen = () => {
    const scale = image
      ? Math.min(
          stageWidth < image.width ? stageWidth / image.width : 1,
          stageHeigth < image.height ? stageHeigth / image.height : 1
        )
      : 1;
    setStageScale(scale);
    resetPositioin();
  };

  const resetPositioin = () => {
    setStagePos(defaultStagePos);
    setStageOffset(defaultStagePos);
  };

  const applyIgnoreArea = () => {
    let newIgnoreArea = ignoreAreas.find((area) => selectedRectId! === area.id);
    if (newIgnoreArea) {
      setProcessing(true);
      testRunService
        .getList(testRun.buildId)
        .then((testRuns: TestRun[]) => {
          let allIds = testRuns.map((item) => item.id);
          let data: UpdateIgnoreAreaDto = {
            ids: allIds,
            ignoreAreas: [newIgnoreArea!],
          };
          testRunService.addIgnoreAreas(data).then(() => {
            setProcessing(false);
            setSelectedRectId(undefined);
            enqueueSnackbar(
              "Ignore areas are updated in all images in this build.",
              {
                variant: "success",
              }
            );
          });
        })
        .catch((error) => {
          enqueueSnackbar("There was an error : " + error, {
            variant: "error",
          });
          setProcessing(false);
        });
    } else {
      enqueueSnackbar(
        "There was an error determining which ignore area to apply.",
        { variant: "error" }
      );
    }
  };

  useHotkeys(
    "d",
    () => !!testRun.diffName && setIsDiffShown((isDiffShown) => !isDiffShown),
    [testRun.diffName]
  );
  useHotkeys("ESC", handleClose, [handleClose]);

  return (
    <React.Fragment>
      <AppBar position="sticky">
        <Toolbar>
          <Grid container justifyContent="space-between">
            <Grid item>
              <Typography variant="h6">{testRun.name}</Typography>
            </Grid>
            {testRun.diffName && (
              <Grid item>
                <Tooltip title={"Hotkey: D"}>
                  <Switch
                    checked={isDiffShown}
                    onChange={() => setIsDiffShown(!isDiffShown)}
                    name="Toggle diff"
                  />
                </Tooltip>
              </Grid>
            )}
            {(testRun.status === TestStatus.unresolved ||
              testRun.status === TestStatus.new) && (
              <Grid item>
                <ApproveRejectButtons testRun={testRun} />
              </Grid>
            )}
            <Grid item>
              <IconButton color="inherit" onClick={handleClose}>
                <Close />
              </IconButton>
            </Grid>
          </Grid>
        </Toolbar>
      </AppBar>
      {processing && <LinearProgress />}
      <Box m={1}>
        <Grid container alignItems="center">
          <Grid item xs={12}>
            <Grid container alignItems="center">
              <Grid item>
                <TestRunDetails testRun={testRun} />
              </Grid>
              {isImageSizeDiffer && (
                <Grid item>
                  <Tooltip
                    title={
                      "Image height/width differ from baseline! Cannot calculate diff!"
                    }
                  >
                    <IconButton>
                      <WarningRounded color="secondary" />
                    </IconButton>
                  </Tooltip>
                </Grid>
              )}
            </Grid>
          </Grid>
          <Grid item>
            <Grid container alignItems="center" spacing={2}>
              <Grid item>
                <Select
                  id="area-select"
                  labelId="areaSelect"
                  value={valueOfIgnoreOrCompare}
                  onChange={(event) =>
                    onIgnoreOrCompareSelectChange(event.target.value as string)
                  }
                >
                  {["Ignore Areas", "Compare Area"].map((eachItem) => (
                    <MenuItem key={eachItem} value={eachItem}>
                      {eachItem}
                    </MenuItem>
                  ))}
                </Select>
              </Grid>
              <Grid item>
                <ToggleButton
                  value={"drawMode"}
                  selected={isDrawMode}
                  onClick={() => {
                    setIsDrawMode(!isDrawMode);
                  }}
                >
                  <Add />
                </ToggleButton>
              </Grid>
              <Grid item>
                <IconButton
                  disabled={!selectedRectId || ignoreAreas.length === 0}
                  onClick={() =>
                    selectedRectId && deleteIgnoreArea(selectedRectId)
                  }
                >
                  <Delete />
                </IconButton>
              </Grid>
              <Tooltip title="Clears all ignore areas." aria-label="reject">
                <Grid item>
                  <IconButton
                    disabled={ignoreAreas.length === 0}
                    onClick={() => {
                      handleIgnoreAreaChange([]);
                    }}
                  >
                    <LayersClear />
                  </IconButton>
                </Grid>
              </Tooltip>
              <Tooltip
                title={applyIgnoreAreaText}
                aria-label="apply ignore area"
              >
                <Grid item>
                  <IconButton
                    disabled={!selectedRectId || ignoreAreas.length === 0}
                    onClick={() => toggleApplyIgnoreDialogOpen()}
                  >
                    <Collections />
                  </IconButton>
                </Grid>
              </Tooltip>
              <Grid item>
                <IconButton
                  disabled={!touched}
                  onClick={() => saveIgnoreAreasOrCompareArea()}
                >
                  <Save />
                </IconButton>
              </Grid>
            </Grid>
          </Grid>
          <Grid item>
            <Button
              color="primary"
              disabled={!testRun.testVariationId}
              onClick={() => {
                navigate(
                  `${routes.VARIATION_DETAILS_PAGE}/${testRun.testVariationId}`
                );
              }}
            >
              Baseline history
            </Button>
          </Grid>
          <Grid item>
            <CommentsPopper
              text={testRun.comment}
              onSave={(comment) =>
                testRunService
                  .update(testRun.id, { comment })
                  .then(() =>
                    enqueueSnackbar("Comment updated", {
                      variant: "success",
                    })
                  )
                  .catch((err) =>
                    enqueueSnackbar(err, {
                      variant: "error",
                    })
                  )
              }
            />
          </Grid>
        </Grid>
      </Box>
      <Box
        overflow="hidden"
        minHeight="65%"
        className={classes.drawAreaContainer}
      >
        <Grid container style={{ height: "100%" }}>
          <Grid item xs={6} className={classes.drawAreaItem}>
            <DrawArea
              type="Baseline"
              imageName={testRun.baselineName}
              branchName={testRun.baselineBranchName}
              imageState={[baselineImage, baselineImageStatus]}
              ignoreAreas={[]}
              tempIgnoreAreas={[]}
              setIgnoreAreas={handleIgnoreAreaChange}
              selectedRectId={selectedRectId}
              setSelectedRectId={setSelectedRectId}
              onStageClick={removeSelection}
              stageScaleState={[stageScale, setStageScale]}
              stagePosState={[stagePos, setStagePos]}
              stageInitPosState={[stageInitPos, setStageInitPos]}
              stageOffsetState={[stageOffset, setStageOffset]}
              drawModeState={[false, setIsDrawMode]}
            />
          </Grid>
          <Grid item xs={6} className={classes.drawAreaItem}>
            {isDiffShown ? (
              <DrawArea
                type="Diff"
                imageName={testRun.diffName}
                branchName={testRun.branchName}
                imageState={[diffImage, diffImageStatus]}
                ignoreAreas={ignoreAreas}
                tempIgnoreAreas={JSON.parse(testRun.tempIgnoreAreas)}
                setIgnoreAreas={handleIgnoreAreaChange}
                selectedRectId={selectedRectId}
                setSelectedRectId={setSelectedRectId}
                onStageClick={removeSelection}
                stageScaleState={[stageScale, setStageScale]}
                stagePosState={[stagePos, setStagePos]}
                stageInitPosState={[stageInitPos, setStageInitPos]}
                stageOffsetState={[stageOffset, setStageOffset]}
                drawModeState={[isDrawMode, setIsDrawMode]}
              />
            ) : (
              <DrawArea
                type="Image"
                imageName={testRun.imageName}
                branchName={testRun.branchName}
                imageState={[image, imageStatus]}
                ignoreAreas={ignoreAreas}
                tempIgnoreAreas={JSON.parse(testRun.tempIgnoreAreas)}
                setIgnoreAreas={handleIgnoreAreaChange}
                selectedRectId={selectedRectId}
                setSelectedRectId={setSelectedRectId}
                onStageClick={removeSelection}
                stageScaleState={[stageScale, setStageScale]}
                stagePosState={[stagePos, setStagePos]}
                stageInitPosState={[stageInitPos, setStageInitPos]}
                stageOffsetState={[stageOffset, setStageOffset]}
                drawModeState={[isDrawMode, setIsDrawMode]}
              />
            )}
          </Grid>
        </Grid>
      </Box>
      <ScaleActionsSpeedDial
        onZoomInClick={() => setStageScale(stageScale * stageScaleBy)}
        onZoomOutClick={() => setStageScale(stageScale / stageScaleBy)}
        onOriginalSizeClick={setOriginalSize}
        onFitIntoScreenClick={fitStageToScreen}
      />
      <BaseModal
        open={applyIgnoreDialogOpen}
        title={applyIgnoreAreaText}
        submitButtonText={"Yes"}
        onCancel={toggleApplyIgnoreDialogOpen}
        content={
          <Typography>
            {`All images in the current build will be re-compared with new ignore area taken into account. Are you sure?`}
          </Typography>
        }
        onSubmit={() => {
          toggleApplyIgnoreDialogOpen();
          applyIgnoreArea();
        }}
      />
    </React.Fragment>
  );
}
Example #14
Source File: index.tsx    From prism-frontend with MIT License 4 votes vote down vote up
function DataViewer({ classes }: DatasetProps) {
  const dispatch = useDispatch();
  const isDatasetLoading = useSelector(loadingDatasetSelector);
  const { startDate: selectedDate } = useSelector(dateRangeSelector);
  const { t } = useSafeTranslation();

  const {
    data: dataset,
    datasetParams: params,
    title,
    chartType,
  } = useSelector(datasetSelector);

  useEffect(() => {
    if (!params || !selectedDate) {
      return;
    }

    const requestParams: DatasetRequestParams = isAdminBoundary(params)
      ? {
          id: params.id,
          boundaryProps: params.boundaryProps,
          url: params.url,
          serverLayerName: params.serverLayerName,
          selectedDate,
        }
      : {
          date: selectedDate,
          externalId: params.externalId,
          triggerLevels: params.triggerLevels,
          baseUrl: params.baseUrl,
        };

    dispatch(loadDataset(requestParams));
  }, [params, dispatch, selectedDate]);

  if (!dataset || !params) {
    return null;
  }

  const category = isAdminBoundary(params) ? params.id : params.externalId;

  const config: ChartConfig = {
    type: chartType,
    stacked: false,
    fill: false,
    category,
  };

  const adminBoundaryLevelButtons = isAdminBoundary(params)
    ? Object.entries(params.boundaryProps).map(([adminId, level]) => (
        <Button
          id={adminId}
          className={classes.adminButton}
          onClick={() => dispatch(updateAdminId(adminId))}
          size="small"
          color="primary"
          variant={params.id === adminId ? 'contained' : 'text'}
        >
          {level.name}
        </Button>
      ))
    : null;

  return (
    <>
      <Grid item className={classes.container}>
        <Paper className={classes.paper}>
          <IconButton size="small" onClick={() => dispatch(clearDataset())}>
            <Close fontSize="small" />
          </IconButton>
          <Grid item className={classes.boundarySelector}>
            {adminBoundaryLevelButtons}
          </Grid>
          {isDatasetLoading ? (
            <div className={classes.loading}>
              <CircularProgress size={50} />
            </div>
          ) : (
            <Chart
              title={t(title)}
              config={config}
              data={dataset}
              xAxisLabel={
                isAdminBoundary(params)
                  ? undefined
                  : t('Timestamps reflect local time in Cambodia')
              }
            />
          )}
        </Paper>
      </Grid>
    </>
  );
}
Example #15
Source File: TxResultRenderer.tsx    From anchor-web-app with Apache License 2.0 4 votes vote down vote up
export function TxResultRenderer({
  resultRendering,
  onExit,
  minimizable,
  onMinimize,
}: TxResultRendererProps) {
  const {
    dimTextColor,
    colors: { primary },
  } = useTheme();

  const {
    phase,
    message = 'Waiting for Terra Station...',
    description = 'Transaction broadcasted. There is no need to send another until it has been complete.',
    failedReason,
  } = resultRendering;

  const handleMinimize = useCallback(() => {
    onMinimize?.();
    onExit?.();
  }, [onExit, onMinimize]);

  switch (phase) {
    case TxStreamPhase.POST:
      return (
        <Layout>
          <article>
            <figure data-state={phase}>
              <PushSpinner color={dimTextColor} />
            </figure>

            <h2>{message}</h2>

            <Receipts resultRendering={resultRendering} />

            <SubmitButton onClick={() => onExit?.()}>Stop</SubmitButton>
          </article>
        </Layout>
      );
    case TxStreamPhase.BROADCAST:
      return (
        <Layout>
          <article>
            <figure data-state={phase}>
              <GuardSpinner frontColor={primary} />
            </figure>

            <h2>
              <span>{message}</span>
              <p>{description}</p>
            </h2>

            <Receipts resultRendering={resultRendering} />
            {minimizable && (
              <Container direction="row" gap={10}>
                <ActionButton
                  className="minimize-button"
                  onClick={handleMinimize}
                >
                  Minimize
                </ActionButton>
              </Container>
            )}
          </article>
        </Layout>
      );
    case TxStreamPhase.SUCCEED:
      return (
        <Layout>
          <article>
            <figure data-state={phase}>
              <DoneIcon />
            </figure>

            <h2>Complete!</h2>

            <Receipts resultRendering={resultRendering} />

            <SubmitButton onClick={() => onExit?.()}>OK</SubmitButton>
          </article>
        </Layout>
      );
    case TxStreamPhase.FAILED:
      return (
        <Layout>
          <article>
            {failedReason?.error instanceof PollingTimeout ? (
              <figure data-state={TxStreamPhase.SUCCEED}>
                <AccessTime />
              </figure>
            ) : (
              <figure data-state={phase}>
                <Close />
              </figure>
            )}

            {failedReason && renderTxFailedReason(failedReason)}

            <Receipts resultRendering={resultRendering} />

            <SubmitButton onClick={() => onExit?.()}>OK</SubmitButton>
          </article>
        </Layout>
      );
  }
}
Example #16
Source File: Request.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
DocumentRequest = ({
  requestBody,
  defaultRequestBody,
  setRequestBody,
}: Props) => {
  const [textDocuments, setTextDocuments] = useState("")
  const [uris, setURIs] = useState<string[]>([])
  const [showCustom, setShowCustom] = useState(false)
  const [rows, setRows] = useState<string[]>([])
  const [placeholders, setPlaceholders] = useState<{ [key: string]: string }>(
    {}
  )
  const [keys, setKeys] = useState<{ [key: string]: string }>({})
  const [values, setValues] = useState<{ [key: string]: string }>({})

  const toggleShowCustom = () => setShowCustom((prev) => !prev)

  useEffect(() => {
    const {
      rows: initialRows,
      keys: initialKeys,
      values: initialValues,
      text: initialText,
      uris: initialURIs,
      placeholders: initialPlaceholders,
    } = parseDocumentRequest(requestBody, defaultRequestBody)

    setPlaceholders(initialPlaceholders)
    setTextDocuments(initialText)
    setRows(initialRows.length ? initialRows : [nanoid()])
    setValues(initialValues)
    setKeys(initialKeys)
    setURIs(initialURIs)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const handleUpdate = async () => {
      const formattedBody = await formatDocumentRequest(
        textDocuments,
        uris,
        rows,
        keys,
        values
      )
      setRequestBody(formattedBody)
    }
    handleUpdate()
  }, [textDocuments, uris, rows, keys, values, setRequestBody])

  const addRow = () => {
    const rowId = nanoid()
    setRows((prev) => {
      return [...prev, rowId]
    })
  }

  const handleFileSelect = async (files: FileList | null) => {
    const uris: string[] = []
    const filesArray = Array.from(files || [])

    for (let file of filesArray) {
      const uri = await fileToBase64(file)
      uris.push(uri)
    }

    setURIs(uris)
  }

  const removeRow = (rowId: string) => {
    if (placeholders[rowId]) return setValue(rowId, "")

    const index = rows.indexOf(rowId)
    setRows((prev) => {
      prev.splice(index, 1)
      return prev.length === 0 ? [nanoid()] : [...prev]
    })
  }

  const setKey = (rowId: string, key: string) => {
    setKeys((prev) => {
      prev[rowId] = key
      return { ...prev }
    })
  }

  const setValue = (rowId: string, value: string) => {
    setValues((prev) => {
      prev[rowId] = value
      return { ...prev }
    })
  }

  const removeFiles = () => {
    setURIs([])
  }

  const numCustomFields = reduce(
    rows,
    (acc, rowId) => {
      if (values[rowId] && keys[rowId]) return acc + 1
      return acc
    },
    0
  )

  return (
    <>
      <Box mb={2}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <TextInput
              label="Text Documents"
              placeholder="Text Documents"
              variant="outlined"
              multiline
              minRows={3}
              maxRows={25}
              type="custom-text"
              value={textDocuments}
              onChange={(e) => setTextDocuments(e.target.value)}
            />
          </Grid>
        </Grid>
      </Box>
      <Grid container>
        <Grid item xs={6}>
          <FileInput
            type="file"
            multiple
            id="attach-files-button"
            onChange={(e) => handleFileSelect(e.target.files)}
          />
          <label htmlFor="attach-files-button">
            <Button size="large" component="span">
              Select Files
            </Button>
          </label>
          {uris?.length ? (
            <Box display="inline" marginLeft={3}>
              {uris.length} files selected{" "}
              <Button onClick={removeFiles}>Remove</Button>
            </Box>
          ) : (
            ""
          )}
        </Grid>
        <Grid item xs={6}>
          <Box textAlign="right" onClick={toggleShowCustom}>
            <Button size="large">
              {showCustom ? "Hide " : "Show "}Additional Fields
              {numCustomFields ? ` (${numCustomFields})` : ""}
            </Button>
          </Box>
        </Grid>
      </Grid>
      <Collapse in={showCustom}>
        <Box width="100%">
          <Divider />
          {rows.map((id) => (
            <Grid key={id} container spacing={2} paddingTop={3}>
              <Grid item xs={4}>
                <TextInput
                  label="Key"
                  variant="outlined"
                  type="custom-input"
                  disabled={typeof placeholders[id] === "string"}
                  value={keys[id] || ""}
                  onChange={(e) => setKey(id, e.target.value)}
                />
              </Grid>
              <Grid item xs={7}>
                <TextInput
                  label="Value"
                  variant="outlined"
                  type="custom-input"
                  value={values[id] || ""}
                  placeholder={placeholders[id] || ""}
                  onChange={(e) => setValue(id, e.target.value)}
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
              </Grid>
              <Grid item xs={1}>
                {!placeholders[id] || values[id] ? (
                  <Button size="large" onClick={() => removeRow(id)}>
                    <Close />
                  </Button>
                ) : (
                  <></>
                )}
              </Grid>
            </Grid>
          ))}

          <Box paddingTop={3}>
            <Button size="large" onClick={addRow}>
              <Add /> Add Field
            </Button>
          </Box>
        </Box>
      </Collapse>
    </>
  )
}
Example #17
Source File: Snackbar.stories.tsx    From anchor-web-app with Apache License 2.0 4 votes vote down vote up
Basic = () => {
  const { addSnackbar, snackbarContainerRef } = useSnackbar();

  return (
    <Container>
      <ActionButton
        onClick={() => {
          count++;

          addSnackbar(
            <Snackbar autoClose={autoClose}>
              <SnackbarContent
                message={`${count} HELLO SNACKBAR!`}
                action={[
                  <Button key="undo" color="inherit" size="small">
                    UNDO
                  </Button>,
                  <IconButton key="close" aria-label="close" color="inherit">
                    <Close />
                  </IconButton>,
                ]}
              />
            </Snackbar>,
          );
        }}
      >
        Default
      </ActionButton>

      <ActionButton
        onClick={() => {
          count++;

          addSnackbar(
            <Snackbar autoClose={autoClose}>
              <NormalSnackbarContent
                message={`${count} HELLO SNACKBAR!`}
                action={[
                  <Button key="undo" color="inherit" size="small">
                    UNDO
                  </Button>,
                  <IconButton key="close" aria-label="close" color="inherit">
                    <Close />
                  </IconButton>,
                ]}
              />
            </Snackbar>,
          );
        }}
      >
        Normal
      </ActionButton>

      <ActionButton
        onClick={() => {
          count++;

          addSnackbar(
            <Snackbar autoClose={autoClose}>
              <SuccessSnackbarContent
                message={`${count} HELLO SNACKBAR!`}
                action={[
                  <Button key="undo" color="inherit" size="small">
                    UNDO
                  </Button>,
                  <IconButton key="close" aria-label="close" color="inherit">
                    <Close />
                  </IconButton>,
                ]}
              />
            </Snackbar>,
          );
        }}
      >
        Success
      </ActionButton>

      <ActionButton
        onClick={() => {
          count++;

          addSnackbar(
            <Snackbar autoClose={autoClose}>
              <WarningSnackbarContent
                message={`${count} HELLO SNACKBAR!`}
                action={[
                  <Button key="undo" color="inherit" size="small">
                    UNDO
                  </Button>,
                  <IconButton key="close" aria-label="close" color="inherit">
                    <Close />
                  </IconButton>,
                ]}
              />
            </Snackbar>,
          );
        }}
      >
        Warning
      </ActionButton>

      <ActionButton
        onClick={() => {
          count++;

          addSnackbar(
            <Snackbar autoClose={autoClose}>
              <ErrorSnackbarContent
                message={`${count} HELLO SNACKBAR!`}
                action={[
                  <Button key="undo" color="inherit" size="small">
                    UNDO
                  </Button>,
                  <IconButton key="close" aria-label="close" color="inherit">
                    <Close />
                  </IconButton>,
                ]}
              />
            </Snackbar>,
          );
        }}
      >
        Error
      </ActionButton>

      <SnackbarContainer ref={snackbarContainerRef} />
    </Container>
  );
}