@emotion/react#useTheme TypeScript Examples

The following examples show how to use @emotion/react#useTheme. 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: FilterButton.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
FilterButton = ({
  value,
  label,
  index,
  count,
  filterCategoryIndex,
  handleFilterChange,
}: FilterButtonProps) => {
  const [selected, setSelected] = useState(value)
  const handleFilterSelect = () => {
    setSelected(!selected)
    handleFilterChange(filterCategoryIndex, index, !selected)
  }
  const theme = useTheme()

  return (
    <ToggleButton
      theme={theme}
      filterCategoryIndex={filterCategoryIndex}
      variant="contained"
      selected={value}
      disabled={count === 0}
      onClick={() => handleFilterSelect()}
    >
      {label} ({count})
    </ToggleButton>
  )
}
Example #2
Source File: TourHost.tsx    From lightning-terminal with MIT License 6 votes vote down vote up
TourHost: React.FC = () => {
  const { appView } = useStore();
  const theme = useTheme();

  const { Tour } = Styled;
  return (
    <Tour
      steps={tourSteps}
      isOpen={appView.tourVisible}
      onRequestClose={appView.closeTour}
      accentColor={theme.colors.pink}
      goToStep={appView.tourActiveStep}
      getCurrentStep={appView.setTourActiveStep}
      showNavigation={false}
      showButtons={false}
      closeWithMask={false}
      disableKeyboardNavigation={true}
      badgeContent={(curr, tot) => `${curr} of ${tot}`}
      startAt={0}
    />
  );
}
Example #3
Source File: Stat.tsx    From lightning-terminal with MIT License 6 votes vote down vote up
Stat: React.FC<Props> = ({
  label,
  value,
  positive,
  negative,
  warn,
  className,
  tip,
  tipPlacement,
  tipCapitalize,
}) => {
  const theme = useTheme();

  let color = '';
  if (negative) color = theme.colors.pink;
  if (warn) color = theme.colors.gold;
  if (positive) color = theme.colors.green;

  const { Wrapper, Value } = Styled;
  let cmp = (
    <Wrapper className={className}>
      <Value color={color}>{value}</Value>
      <HeaderFour>{label}</HeaderFour>
    </Wrapper>
  );

  if (tip) {
    cmp = (
      <Tip overlay={tip} placement={tipPlacement} capitalize={tipCapitalize}>
        {cmp}
      </Tip>
    );
  }

  return cmp;
}
Example #4
Source File: MiscPage.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
MiscPage = () => {
  const { palette } = useTheme()
  return (
    <div>
      <PageTitle title={"Misc"} className={""} />
      <span
        css={css`
          color: ${palette.headerTextColor};
          padding: 8px;
        `}
      >
        Loading Spinner
      </span>
      <SpinningLoader />
    </div>
  )
}
Example #5
Source File: Matches.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
Matches = ({ doc, onScoreClick, height }: MatchesProps) => {
  const { palette } = useTheme()
  const [elements, setElements] = useState<any[]>([])

  useEffect(() => {
    const newElements = getChartElements(doc, palette, onScoreClick)
    setElements(newElements)
  }, [doc, palette, onScoreClick])

  return (
    <div style={{ height, background: "white" }}>
      <ReactFlow
        elements={elements}
        nodeTypes={nodeTypes}
        minZoom={0.2}
        defaultZoom={0.25}
        defaultPosition={[10, 10]}
      >
        <Controls />
      </ReactFlow>
    </div>
  )
}
Example #6
Source File: DocumentTabs.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
DocumentTabs = ({
  docs,
  docIndex,
  height,
  setDocIndex,
}: TabProps) => {
  const { palette } = useTheme()
  return (
    <Tabs
      style={{ height, width: "12em" }}
      orientation="vertical"
      variant="scrollable"
      value={docIndex}
      onChange={(e, newIndex) => setDocIndex(newIndex)}
      scrollButtons="auto"
    >
      {docs.map(({ text, uri }, idx) => {
        return (
          <Tab
            style={{ borderBottom: `1px solid ${palette.grey[300]}` }}
            label={
              <DocumentTabLabel
                text={text}
                uri={uri}
                idx={idx}
                selectedIndex={docIndex}
              />
            }
            value={idx}
            key={idx}
          />
        )
      })}
    </Tabs>
  )
}
Example #7
Source File: Scores.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
Scores = ({ score, nested }: ScoreProps) => {
  const [show, setShow] = useState(false)
  const { palette } = useTheme()

  let { op_name, operands, value, ref_id, description } = score
  if (!op_name && !operands && !value) {
    return <></>
  }

  const toggleShow = () => {
    setShow((prev) => !prev)
  }

  const canToggle = operands && operands.length > 0

  return (
    <div style={{ paddingLeft: nested ? "10px" : "0px" }}>
      <ListItem button={canToggle} onClick={toggleShow}>
        <Grid container>
          <Grid item xs={4}>
            <Box paddingTop="0.75rem">
              <Typography noWrap fontSize="1.25rem">
                {score.value || "0.12341234"}
              </Typography>
            </Box>
          </Grid>
          <Grid item xs={7}>
            <Box>
              <Typography noWrap>{op_name}</Typography>
              <Typography noWrap color={palette.grey[500]}>
                {description}
              </Typography>
            </Box>
          </Grid>
        </Grid>
        {canToggle && (
          <ListItemSecondaryAction>
            ({operands?.length}){show ? <ExpandLess /> : <ExpandMore />}
          </ListItemSecondaryAction>
        )}
      </ListItem>
      {operands && (
        <div>
          <Collapse in={show}>
            <List>
              {operands.map((operand, index) => (
                <Scores score={operand} key={`${index}-${ref_id}`} nested />
              ))}
            </List>
          </Collapse>
        </div>
      )}
    </div>
  )
}
Example #8
Source File: ChartNode.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
function NodePort({ type, portDataLabel }: NodePortProps) {
  const theme = useTheme()
  const NodePortTop = styled(Handle)`
    margin-top: -0.2rem;
    background-color: white;
    width: 1rem;
    height: 1rem;
    border-radius: 0.5rem;
    border: 1px solid ${theme.palette.primary.main};
    display: flex;
    align-items: center;
    justify-content: center;

    &:after {
      display: block;

      content: "";
      background-color: #099;
      color: white;
      border-radius: 0.25rem;
      width: 0.5rem;
      height: 0.5rem;
    }
  `

  const NodePortBottom = styled(NodePortTop)`
    bottom: -0.45rem;
  `
  switch (type) {
    case "source":
      return (
        <NodePortBottom
          data-name={`NodePortBottom-${portDataLabel}`}
          type={type}
          position={Position.Bottom}
        />
      )
    case "target":
      return (
        <NodePortTop
          data-name={`NodePortTop-${portDataLabel}`}
          type={type}
          position={Position.Top}
        />
      )
  }
}
Example #9
Source File: ChartNode.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
export default function ChartNode(props: ChartNodeProps) {
  const flowType = useSelector(selectSelectedFlow).type
  const dispatch = useDispatch()
  const theme = useTheme()

  const ChartNodeElement = styled.div`
    min-width: 16rem;
    cursor: move;
    text-align: center;
    font-size: 14px;
    font-weight: 500;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 0.25em;
    transition: 0.2s;
    border: 1px solid ${theme.palette.primary.main};
  `

  function _isFlowNode(prop: ChartNodeProps): prop is FlowNode {
    return (prop as FlowNode).id !== undefined
  }

  if (_isFlowNode(props)) {
    const node = props
    return (
      <ChartNodeElement
        data-name={`chart-node-${node?.data?.label}`}
        onDoubleClick={() => {
          flowType === "user-generated" &&
            dispatch(showModal("podEdit", { nodeId: node?.id }))
        }}
      >
        {node.id !== "gateway" && (
          <NodePort
            portDataLabel={node?.data?.label || node.id}
            type="target"
          />
        )}
        <div id={`chart-node-${node?.data?.label}`}>
          <div className="node-header">
            <div className={`p-1`}>
              <p className="m-1">
                <span className="text-bold">
                  {node?.data?.label || (
                    <span className="text-warning">Empty Pod</span>
                  )}
                </span>
              </p>
            </div>
          </div>
        </div>{" "}
        <NodePort type="source" portDataLabel={node?.data?.label || node.id} />
      </ChartNodeElement>
    )
  } else
    return (
      <ChartNodeElement id={`chart-node-${props.label}`}>
        <div className="node-header">
          <div className={`p-1`}>
            <p className="m-1">
              <span className="text-bold">
                {props.label || <span className="text-warning">Empty Pod</span>}
              </span>
            </p>
          </div>
        </div>
      </ChartNodeElement>
    )
}
Example #10
Source File: index.tsx    From houston with MIT License 5 votes vote down vote up
export default function useHoustonTheme(): IHoustonTheme {
  return useTheme();
}
Example #11
Source File: ImageDetails.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
export default function ImageDetails({ image }: Props) {
  const theme = useTheme()
  let { keywords, platform, author, version } = image
  let dockerCommand = image["docker-command"]
  let dockerName = image["docker-name"]
  return (
    <>
      <DetailCard>
        <CardContent>
          <DetailsSection>
            <SectionHeading>Docker Command</SectionHeading>
            <CodeSnippetWithCopy codeSnippet={dockerCommand} />
            <SectionHeading>Python Usage</SectionHeading>
            <CodeSnippetWithCopy
              codeSnippet={getPythonUsage(dockerName, version)}
            />
            <SectionHeading>In a Flow</SectionHeading>
            <CodeSnippetWithCopy
              codeSnippet={getUsageInFlow(dockerName, version)}
            />
          </DetailsSection>
        </CardContent>
      </DetailCard>
      <DetailCard>
        <CardContent>
          <DetailsSection>
            <SectionHeading>Tags</SectionHeading>
            <div>
              {keywords.map((keyword, index) => (
                <Tag
                  data-name="hubImageTags"
                  key={index}
                  filterColorIndex={index}
                  theme={theme}
                >
                  {keyword}
                </Tag>
              ))}
            </div>
          </DetailsSection>
          <DetailsSection>
            <SectionHeading>Platform</SectionHeading>
            <div>
              {platform.map((p, index) => (
                <Tag
                  data-name="hubImageTags"
                  key={index}
                  filterColorIndex={3}
                  theme={theme}
                >
                  {p}
                </Tag>
              ))}
            </div>
            <DetailsSection>
              <SectionHeading>Owner</SectionHeading>
              <div>{author}</div>
            </DetailsSection>
          </DetailsSection>
        </CardContent>
      </DetailCard>
    </>
  )
}
Example #12
Source File: PieChartBase.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
function PieChartBase({ width, height, data }: Props) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const [chartInstance, setChartInstance] = useState<ChartElement | null>(null)
  const theme = useTheme()

  const getColor = useCallback(
    (key: string) => {
      return getLevelPalette(theme)[key]
    },
    [theme]
  )

  useEffect(() => {
    if (!canvasRef.current) return
    const names = Object.keys(data)
    const chartOptions: ChartOptions = {
      animation: { duration: 0 },
      legend: {
        display: false,
        position: "bottom",
        labels: {
          padding: 25,
          boxWidth: 20,
        },
      },
      tooltips: {
        mode: "index",
        position: "nearest",
      },
    }

    const chartConfig: ChartConfiguration = {
      type: "pie",
      data: {
        datasets: [
          {
            borderWidth: 1,
            data: Object.values(data),
            borderColor: names.map((name) => getColor(name).borderColor),
            backgroundColor: names.map(
              (name) => getColor(name).backgroundColor
            ),
          },
        ],
      },
      options: chartOptions,
    }

    const newChartInstance = new ChartElement(canvasRef.current, chartConfig)
    setChartInstance(newChartInstance)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!chartInstance) return
    const names = Object.keys(data)
    const chartData: ChartData = {
      labels: names,
      datasets: [
        {
          borderWidth: 1,
          data: Object.values(data),
          borderColor: names.map((name) => getColor(name).borderColor),
          backgroundColor: names.map((name) => getColor(name).backgroundColor),
        },
      ],
    }
    chartInstance.data = chartData
    chartInstance.update()
  }, [data, chartInstance, getColor])

  return (
    <canvas
      height={height || DEFAULT_HEIGHT}
      width={width || DEFAULT_WIDTH}
      ref={canvasRef}
    />
  )
}
Example #13
Source File: FlowChartNodes.tsx    From dashboard with Apache License 2.0 5 votes vote down vote up
ChartNode = ({
  data,
  selected,
  isDragging,
  type,
}: ChartNodeProps) => {
  const { palette } = useTheme()
  const { item, onScoreClick, hasInput = true, hasOutput = true, name } = data
  const parentId = "parent_id" in item ? item.parent_id : undefined
  const score = "score" in item ? item.score : undefined
  const { id: itemId, uri, mime_type, text } = item
  const elevation = isDragging ? 20 : selected ? 10 : 2

  let style = {}

  if (type === "match")
    style = {
      backgroundColor: palette.filters[0].main,
    }
  else if (type === "chunk")
    style = {
      backgroundColor: palette.filters[3].main,
    }

  return (
    <div>
      {hasInput && <Handle type="source" position={Position.Left}></Handle>}
      <Card elevation={elevation} color="red" style={style}>
        <CardHeader
          style={{ paddingBottom: ".5em" }}
          action={
            score && (
              <Button size="large" onClick={() => onScoreClick(score as Score)}>
                score: {score.value || "0.0"}
              </Button>
            )
          }
        />
        <Box maxWidth="30rem" padding="1em" paddingTop="0em">
          {text && <NodeBigText>"{text}"</NodeBigText>}
          {uri && mimeTypeFromDataURI(uri) && <NodeMediaPreview uri={uri} />}
          <Grid container>
            <Grid item xs={6}>
              {mime_type && (
                <Typography color="textSecondary" gutterBottom>
                  {mime_type}
                </Typography>
              )}
            </Grid>

            <Grid item xs={6}>
              <Box textAlign="right"></Box>
            </Grid>
          </Grid>
          <div style={{ backgroundColor: "#ffffff80" }}>
            <PropertyList data={item} key="main table" />
          </div>

          {parentId && (
            <Box marginTop="0.5rem">
              <Typography color="textSecondary">
                ParentId: {parentId}
              </Typography>
            </Box>
          )}
        </Box>
      </Card>
      {hasOutput && <Handle type="target" position={Position.Right}></Handle>}
    </div>
  )
}
Example #14
Source File: WorkspaceSelection.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
export default function WorkspaceSelection() {
  const workspaces = useSelector(selectWorkspaces)
  const selectedWorkspaceId = useSelector(selectSelectedWorkspaceId)
  const connected = useSelector(selectConnectionStatus)
  const { palette } = useTheme()

  const dispatch = useDispatch()

  const uploadSelectedFiles = (selectorFiles: FileList | null) => {
    if (selectorFiles) {
      const filesArray = Array.from(selectorFiles) as Blob[]
      return dispatch(uploadFilesToWorkspace(filesArray))
    }
  }

  const WorkspaceSelectionMenu = styled.div`
    font-family: "Montserrat", serif;
    width: 12rem;
    margin-right: 1.5rem;
  `

  const SelectedWorkspaceHeader = styled.div`
    position: relative;
    font-weight: 600;
    font-size: 1.25em;
    color: ${palette.headerTextColor};
    margin-bottom: 1rem;
    white-space: nowrap;
    overflow: hidden;
  `

  type WorkspaceTabProps = {
    selected: boolean
  }

  const WorkspaceTab = styled.div`
    cursor: pointer;
    font-weight: ${(props: WorkspaceTabProps) =>
      props.selected ? "bold" : 500};
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left: 1rem;
    margin-bottom: 1rem;
    white-space: nowrap;
    overflow: hidden;
    position: relative;
    padding-top: 0.15rem;
    padding-bottom: 0.15rem;
  `

  const WorkspaceTabOverflowHider = styled.div`
    position: absolute;
    height: 1.75rem;
    width: 2rem;
    top: 0;
    right: 0;
    background: linear-gradient(
      to right,
      transparent 0%,
      ${palette.bodyBackground} 40%
    );
  `

  const WorkspaceHeader = styled.div`
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 1rem;
    color: ${palette.headerTextColor};
  `

  const SubHeader = styled.div`
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 0.5rem;
    color: ${palette.headerTextColor};
  `

  const AddButton = styled.span`
    float: right;
    cursor: pointer;
  `

  const FilesList = styled.div`
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    margin-bottom: 1rem;
    height: 10rem;
    overflow-y: auto;
    overflow-x: hidden;
  `

  const FileItem = styled.div`
    font-weight: 400;
    font-size: 0.85rem;
    padding-top: 0.15rem;
    padding-bottom: 0.15rem;
    margin-top: 0.15rem;
    margin-bottom: 0.15rem;
    position: relative;
    white-space: nowrap;
  `

  const FileIcon = styled.span`
    opacity: 0.5;
    margin-right: 0.25em;
  `

  const userWorkspaces = Object.entries(workspaces).filter(
    ([id, workspace]) => workspace.type !== "example"
  )

  const exampleWorkspaces = Object.entries(workspaces).filter(
    ([id, workspace]) => workspace.type === "example"
  )

  const FileSelector = () => {
    const FileLabel = styled.label`
      float: right;
      cursor: pointer;
    `
    const FileInput = styled.input`
      display: none;
    `

    return (
      <>
        <FileLabel htmlFor="workspace-file-select">
          <i className="material-icons">attach_file</i>
        </FileLabel>
        <FileInput
          id="workspace-file-select"
          type="file"
          multiple
          onChange={(e) => uploadSelectedFiles(e.target.files)}
        />
      </>
    )
  }

  const currentWorkspace = workspaces[selectedWorkspaceId]

  const FilesListComponent = () => (
    <FilesList>
      {currentWorkspace.files.length ? (
        currentWorkspace.files.map((filename, idx) => (
          <FileItem key={idx}>
            <FileIcon>
              <i className="material-icons">file_present</i>
            </FileIcon>
            <span>{filename}</span>
            <WorkspaceTabOverflowHider />
          </FileItem>
        ))
      ) : (
        <span>
          <i>none</i>
        </span>
      )}
    </FilesList>
  )

  return (
    <WorkspaceSelectionMenu>
      <SelectedWorkspaceHeader>
        {currentWorkspace.name || <i>{FALLBACK_WORKSPACE_NAME}</i>}
        <TitleConnectionIndicator
          show={currentWorkspace.type === "remote"}
          connected={connected}
        />
      </SelectedWorkspaceHeader>

      <SubHeader>
        Files <FileSelector />
      </SubHeader>
      {isFeatureEnabled("FILES") && <FilesListComponent />}
      <WorkspaceHeader>
        My Workspaces
        <AddButton
          data-name={"newWorkspaceButton"}
          onClick={() => dispatch(createNewWorkspace())}
        >
          <i className="material-icons">add</i>
        </AddButton>
      </WorkspaceHeader>

      {userWorkspaces.map(([workspaceId, workspace], idx) => (
        <WorkspaceTab
          data-name={`${workspace.name.replaceAll(" ", "")}`}
          selected={selectedWorkspaceId === workspaceId}
          key={idx}
        >
          <span onClick={() => dispatch(loadWorkspace(workspaceId))}>
            {workspace.name || FALLBACK_WORKSPACE_NAME}
          </span>
          <ConnectionIndicator
            show={workspace.type === "remote"}
            connected={connected}
          />
          <WorkspaceTabOverflowHider />
          <DeleteButton
            idx={idx}
            onClick={() => dispatch(deleteWorkspace(workspaceId))}
          />
        </WorkspaceTab>
      ))}
      <WorkspaceHeader>Example Workspaces</WorkspaceHeader>
      {exampleWorkspaces.map(([workspaceId, workspace], idx) => (
        <WorkspaceTab
          data-name={`exampleWorkspaceButton-${idx}`}
          selected={selectedWorkspaceId === workspaceId}
          onClick={() => dispatch(loadWorkspace(workspaceId))}
          key={idx}
        >
          {workspace.name}
        </WorkspaceTab>
      ))}
      <WorkspaceTab selected={false} onClick={multiModalScript}>
        Multi-Modal-Example
      </WorkspaceTab>
    </WorkspaceSelectionMenu>
  )
}
Example #15
Source File: BarChartBase.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
function ChartBase({
  width,
  height,
  data,
  numTicks,
  onClick,
  timeLabels,
}: Props) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const [chartInstance, setChartInstance] = useState<ChartElement | null>(null)
  // Get theme from ThemeProvider (for usecases like dark mode)
  const theme = useTheme()

  function onClickChart(e: MouseEvent) {
    if (!chartInstance) return
    const activePoints = chartInstance.getElementsAtEvent(e)
    onClick(activePoints)
  }

  const getXAxisLabel = useCallback(
    (value, index, values) => {
      if (index === 0) return timeLabels[0]
      else if (index === Math.floor(values.length / 2)) return timeLabels[1]
      return
    },
    [timeLabels]
  )

  function getYAxisLabel(value: number) {
    if (Number.isInteger(value)) {
      return value
    }
  }

  function ChartLegend() {
    return (
      <div
        className="chart-legend mt-1 mb-3"
        data-name="logOccurencesChartLegend"
      >
        {Object.entries(getLevelPalette(theme)).map(
          ([level, style]: [string, LevelColor]) => (
            <div className="chart-legend-item" key={level}>
              <div
                className={`chart-legend-indicator mr-1 ${level.toLowerCase()}`}
                style={{ backgroundColor: style.borderColor }}
              />
              <span className="chart-legend-caption mr-2">{level}</span>
            </div>
          )
        )}
      </div>
    )
  }

  useEffect(() => {
    if (!canvasRef.current) return
    const chartOptions: ChartOptions = {
      animation: { duration: 0 },
      events: ["click"],
      onClick: onClickChart,
      maintainAspectRatio: true,
      responsive: true,
      legend: {
        display: false,
      },
      tooltips: {
        enabled: false,
      },
      elements: {
        point: {
          radius: 0,
          hitRadius: 20,
        },
      },
      scales: {
        xAxes: [
          {
            stacked: true,
            ticks: {
              padding: 5,
              maxRotation: 0,
              autoSkip: false,
              callback: getXAxisLabel,
            },
            gridLines: {
              zeroLineColor: "#cfd8dc",
              color: "#cfd8dc",
            },
          },
        ],
        yAxes: [
          {
            stacked: true,
            scaleLabel: {
              display: false,
            },
            gridLines: {
              borderDash: [5, 5],
              zeroLineColor: "#cfd8dc",
              drawBorder: false,
              color: "#cfd8dc",
            },
            ticks: {
              padding: 5,
              suggestedMin: 0,
              autoSkip: true,
              maxTicksLimit: 4,
              callback: getYAxisLabel,
            },
          },
        ],
      },
    }

    const chartConfig: ChartConfiguration = {
      type: "bar",
      data: {
        datasets: getParsedDatasets(data, theme),
      },
      options: chartOptions,
    }

    const newChartInstance = new ChartElement(canvasRef.current, chartConfig)
    setChartInstance(newChartInstance)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!chartInstance) return
    const chartData: ChartData = {
      labels: getLabels(numTicks),
      datasets: getParsedDatasets(data, theme),
    }
    chartInstance.data = chartData
    chartInstance.update()
  }, [data, chartInstance, numTicks, theme])

  useEffect(() => {
    if (
      chartInstance &&
      chartInstance.options.scales &&
      chartInstance.options.scales.xAxes &&
      chartInstance.options.scales.xAxes[0].ticks
    ) {
      chartInstance.options.scales.xAxes[0].ticks.callback = getXAxisLabel
      chartInstance.update()
    }
  }, [getXAxisLabel, chartInstance])

  return (
    <>
      <ChartLegend />
      <canvas
        height={height || DEFAULT_HEIGHT}
        width={width || DEFAULT_WIDTH}
        ref={canvasRef}
      />
    </>
  )
}
Example #16
Source File: FlowChartNodes.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
PropertyListItem = ({
  itemKey,
  itemValue,
  nested,
}: {
  itemKey: string
  itemValue: any
  nested?: boolean
}) => {
  const [show, setShow] = useState(false)
  const { palette } = useTheme()

  const toggleShow = () => {
    setShow((prev) => !prev)
  }

  let isObject = false
  if (typeof itemValue === "object" && itemValue !== null) {
    isObject = true
  }

  if (isObject && isEmpty(itemValue)) return null
  if (
    itemValue === 0 ||
    itemValue === "unset" ||
    itemValue === null ||
    itemValue === "" ||
    itemValue === {}
  )
    return null

  return (
    <div
      style={{
        marginLeft: nested ? "2em" : "0px",
        borderLeft: `1px solid ${palette.grey[500]}`,
        backgroundColor: show
          ? isObject
            ? `${palette.grey[100]}80`
            : palette.grey[200]
          : "inherit",
      }}
    >
      <ListItem button onClick={toggleShow} style={{ paddingLeft: "0px" }}>
        <Grid container>
          <Grid item xs={6}>
            <Typography noWrap>
              <ListMarker color={palette.grey[500]} />
              {itemKey}
            </Typography>
          </Grid>
          <Grid item xs={6}>
            <Typography noWrap>
              {isObject ? (
                <LightText color={palette.grey[500]}>Object</LightText>
              ) : (
                String(itemValue)
              )}
            </Typography>
          </Grid>
        </Grid>
        <ListItemSecondaryAction>
          {isObject && <>({Object.keys(itemValue).length})</>}
          {show ? <ExpandLess /> : <ExpandMore />}
        </ListItemSecondaryAction>
      </ListItem>
      <Collapse in={show}>
        {isObject ? (
          Object.keys(itemValue).length ? (
            show && <PropertyList data={itemValue} nested />
          ) : (
            <ListItem>
              <WrappedText>This Object is empty</WrappedText>
            </ListItem>
          )
        ) : (
          <ListItem>
            <WrappedText>
              <div>
                <b>key: </b>
                {itemKey}
              </div>
              <div>
                <b>value: </b>
                {itemValue}
              </div>
            </WrappedText>
          </ListItem>
        )}
      </Collapse>
    </div>
  )
}
Example #17
Source File: BarChartCard.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
function BarChartCard(props: Props) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const [chartInstance, setChartInstance] = useState<ChartElement | null>(null)
  const [currentTab, setCurrentTab] = useState<keyof Props>("messages")
  const { palette } = useTheme()

  const chartData = props[currentTab]

  const getChartOptions = useCallback((): ChartOptions => {
    return {
      animation: { duration: 0 },
      tooltips: {
        callbacks: {
          title: function (tooltipItem: any) {
            return `Pod: ${tooltipItem[0].xLabel}`
          },
          label: (tooltipItem: any, data: any) => {
            let label = `${data.datasets[tooltipItem.datasetIndex].label}: ${
              currentTab === "bytes"
                ? formatBytes(tooltipItem.value)
                : tooltipItem.value
            }`
            return label
          },
          afterLabel: (tooltipItem: any) => {
            let text = "\nProcess ID: " + chartData[tooltipItem.index].process
            return text
          },
        },
      },
      scales: {
        xAxes: [
          {
            stacked: true,
          },
        ],
        yAxes: [
          {
            stacked: true,
            ticks: {
              callback: (label: number) => {
                if (currentTab === "bytes") return formatBytes(label)
                return label > 999 ? `${(label / 1000).toFixed(0)}k` : label
              },
            },
          },
        ],
      },
      maintainAspectRatio: false,
    }
  }, [chartData, currentTab])

  const getChartConfig = useCallback(
    (chartOptions: ChartOptions): ChartConfiguration => {
      return {
        type: "bar",
        options: chartOptions,
        data: {
          labels: chartData.map((d: any) => d.node),
          datasets: [
            {
              label: "msg sent",
              fill: "start",
              data: chartData.map((d: any) => d.sent),
              backgroundColor: palette.primary,
              borderColor: palette.primary,
              pointBackgroundColor: palette.background,
              pointHoverBackgroundColor: palette.primary,
              borderWidth: 1.5,
            },
            {
              label: "msg received",
              fill: "start",
              data: chartData.map((d: any) => d.received),
              backgroundColor: palette.success,
              borderColor: palette.success,
              pointBackgroundColor: palette.background,
              pointHoverBackgroundColor: palette.success,
              borderWidth: 1.5,
            },
          ],
        },
      }
    },
    [chartData, palette.success, palette.primary, palette.background]
  )

  const getChartData = useCallback(() => {
    return {
      labels: chartData.map((d: any) => d.node),
      datasets: [
        {
          label: `${currentTab} sent`,
          fill: "start",
          data: chartData.map((d: any) => d.sent),
          backgroundColor: palette.primary,
          borderColor: palette.primary,
          pointBackgroundColor: palette.background,
          pointHoverBackgroundColor: palette.primary,
          borderWidth: 1.5,
        },
        {
          label: `${currentTab} received`,
          fill: "start",
          data: chartData.map((d: any) => d.received),
          backgroundColor: palette.success,
          borderColor: palette.success,
          pointBackgroundColor: palette.background,
          pointHoverBackgroundColor: palette.success,
          borderWidth: 1.5,
        },
      ],
    }
  }, [
    chartData,
    currentTab,
    palette.success,
    palette.primary,
    palette.background,
  ])

  useEffect(() => {
    if (!canvasRef.current) return
    const chartOptions: ChartOptions = getChartOptions()
    const chartConfig: ChartConfiguration = getChartConfig(chartOptions)
    const newChartInstance = new ChartElement(canvasRef.current, chartConfig)
    setChartInstance(newChartInstance)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!chartInstance) return
    const newData: ChartData = getChartData()
    const newOptions: ChartOptions = getChartOptions()
    chartInstance.options = newOptions
    chartInstance.data = newData
    chartInstance.update()
  }, [chartData, chartInstance, currentTab, getChartData, getChartOptions])

  return (
    <div className="mb-4">
      <div>
        <h6 className="m-0">Network Load</h6>
      </div>

      <div className="pt-0">
        <div className="py-2">
          <div className="mb-2">
            <div>
              <div
                theme="white"
                active={currentTab === "messages"}
                onClick={() => setCurrentTab("messages")}
              >
                Messages
              </div>
              <div
                theme="white"
                active={currentTab === "bytes"}
                onClick={() => setCurrentTab("bytes")}
              >
                Bytes
              </div>
            </div>
          </div>
        </div>
        <div style={{ position: "relative", height: 300 }}>
          <canvas ref={canvasRef} />
        </div>
      </div>
    </div>
  )
}
Example #18
Source File: SpeedCard.tsx    From dashboard with Apache License 2.0 4 votes vote down vote up
function SpeedCard({ speed }: Props) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const [chartInstance, setChartInstance] = useState<ChartElement | null>(null)
  const { history } = speed
  const { palette } = useTheme()

  let maxValue = Math.max(...history)
  let minValue = Math.min(...history)

  const getChartOptions = useCallback((): ChartOptions => {
    const difference = maxValue - minValue
    return {
      maintainAspectRatio: true,
      responsive: true,
      animation: { duration: 0 },
      legend: {
        display: false,
      },
      tooltips: {
        enabled: false,
      },
      layout: {
        padding: {
          bottom: -10,
          left: -10,
        },
      },
      elements: {
        point: {
          radius: 0,
        },
        line: {
          tension: 0.33,
        },
      },
      scales: {
        xAxes: [
          {
            gridLines: {
              display: false,
            },
            ticks: {
              display: false,
            },
          },
        ],
        yAxes: [
          {
            gridLines: {
              display: false,
            },
            scaleLabel: {
              padding: 0,
              display: false,
            },
            ticks: {
              display: false,
              // Avoid getting the graph line cut of at the top of the canvas.
              // Chart.js bug link: https://github.com/chartjs/Chart.js/issues/4790
              suggestedMax: maxValue + difference * 0.1,
              suggestedMin: minValue - difference * 0.1,
            },
          },
        ],
      },
    }
  }, [maxValue, minValue])

  const getChartConfig = useCallback(
    (chartOptions) => {
      return {
        type: "line",
        data: {
          labels: new Array(history.length).fill(null),
          datasets: [
            {
              label: "Today",
              fill: "start",
              borderWidth: 1.5,
              backgroundColor: "rgba(0, 153, 153, 0.25)",
              borderColor: palette.primary,
              data: history,
            },
          ],
        },
        options: chartOptions,
      }
    },
    [history, palette.primary]
  )

  useEffect(() => {
    if (!canvasRef.current) return
    const chartOptions = getChartOptions()
    const chartConfig = getChartConfig(chartOptions)
    const newChartInstance = new ChartElement(canvasRef.current, chartConfig)
    setChartInstance(newChartInstance)
  }, []) // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!chartInstance) return
    let newChartData = {
      ...chartInstance.data,
      ...{
        datasets: [
          {
            label: "Today",
            fill: "start",
            borderWidth: 1.5,
            backgroundColor: "rgba(0, 153, 153, 0.25)",
            borderColor: palette.primary,
            data: history,
          },
        ],
      },
    }
    chartInstance.options = getChartOptions()
    chartInstance.data = newChartData
    chartInstance.update()
  }, [history, chartInstance, getChartOptions, getChartConfig, palette.primary])

  return (
    <div className="pt-0 h-100 stats-small">
      <div className="stats-small__data mx-auto">
        <h6 className="stats-small__label text-uppercase text-center mb-0 pt-0 mt-0">
          <b>Speed</b>
        </h6>
        <h2 className="my-3 mx-auto">{speed.current}</h2>
        <h6 className="stats-small__label under text-uppercase text-center">
          {speed.unit}/Second
        </h6>
      </div>
      <canvas height="100" ref={canvasRef} className="stats-small-1" />
    </div>
  )
}