summaryrefslogtreecommitdiffhomepage
path: root/gui/src/renderer/components/ScopeBar.tsx
blob: dbc5739b2cfd52c5604c11e36d1ee36fd1d362e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';
import { colors } from '../../config.json';
import { smallText } from './common-styles';

const StyledScopeBar = styled.div({
  display: 'flex',
  flexDirection: 'row',
  backgroundColor: colors.blue40,
  borderRadius: '13px',
  overflow: 'hidden',
});

interface IScopeBarProps {
  defaultSelectedIndex?: number;
  onChange?: (selectedIndex: number) => void;
  className?: string;
  children: React.ReactNode;
}

export function ScopeBar(props: IScopeBarProps) {
  const [selectedIndex, setSelectedIndex] = useState(props.defaultSelectedIndex ?? 0);

  const onClick = useCallback((index: number) => setSelectedIndex(index), []);
  useEffect(() => {
    props.onChange?.(selectedIndex);
  }, [selectedIndex]);

  const children = React.Children.map(props.children, (child, index) => {
    if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        selected: index === selectedIndex,
        onClick,
        index,
      });
    } else {
      return undefined;
    }
  });

  return <StyledScopeBar className={props.className}>{children}</StyledScopeBar>;
}

const StyledScopeBarItem = styled.button(smallText, (props: { selected?: boolean }) => ({
  cursor: 'default',
  flex: 1,
  flexBasis: 0,
  padding: '4px 8px',
  color: colors.white,
  textAlign: 'center',
  border: 'none',
  backgroundColor: props.selected ? colors.green : 'transparent',
  ':hover': {
    backgroundColor: props.selected ? colors.green : colors.blue40,
  },
}));

interface IScopeBarItemProps {
  index?: number;
  selected?: boolean;
  onClick?: (index: number) => void;
  children?: React.ReactNode;
}

export function ScopeBarItem(props: IScopeBarItemProps) {
  const onClick = useCallback(() => {
    if (props.index !== undefined) {
      props.onClick?.(props.index);
    }
  }, [props.onClick, props.index]);

  return props.index !== undefined ? (
    <StyledScopeBarItem selected={props.selected} onClick={onClick}>
      {props.children}
    </StyledScopeBarItem>
  ) : null;
}