styled-components#ThemeContext JavaScript Examples

The following examples show how to use styled-components#ThemeContext. 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: EmptyTableIndicator.js    From dexwebapp with Apache License 2.0 6 votes vote down vote up
EmptyTableIndicator = ({ text, ...props }) => {
  const theme = useContext(ThemeContext);
  if (props.loading) {
    return <div />;
  }

  return (
    <EmptyTableIndicatorWrapper>
      <img
        style={{
          marginTop: props.marginTop,
          width: '68px',
          height: 'auto',
          userSelect: 'none',
          opacity: '1',
        }}
        src={`/assets/images/${theme.imgDir}/no-data.svg`}
        alt="No Data"
        draggable="false"
      />
      <div
        style={{
          paddingTop: '2px',
          fontSize: '0.85rem',
          marginBottom: props.marginTop,
        }}
      >
        <I s={text} />
      </div>
    </EmptyTableIndicatorWrapper>
  );
}
Example #2
Source File: ThemeContext.js    From VTour with MIT License 6 votes vote down vote up
ThemeContext.Extend = function (_ref) {
  var children = _ref.children,
      value = _ref.value;
  return React.createElement(ThemeContext.Consumer, null, function (theme) {
    return React.createElement(ThemeContext.Provider, {
      value: deepMerge(theme, value)
    }, children);
  });
};
Example #3
Source File: VetoedProposals.jsx    From cosmoscan-front with Apache License 2.0 6 votes vote down vote up
VetoedProposals = ({ isLoading, data }) => {
  const theme = useContext(ThemeContext);

  return (
    <ChartContainer
      title={chartName}
      titleTooltip={tooltipTxt}
      chart={(
        <BarChart
          isLoading={isLoading}
          data={data}
          yAxisWidth={yAxisWidth}
          yAxisTickCount={yAxisTickCount}
          yAxisLabelsFormatter={formatPercentValue}
          xAxisTickFormatter={formatId}
          tooltipLabelFormatter={tooltipLabelFormatter}
          tooltipFormatter={formatPercentValue}
          barColor={theme.burgundy}
          barName={barName}
        />
      )}
    />
  );
}
Example #4
Source File: Header.js    From gitpedia with MIT License 6 votes vote down vote up
Header = () => {
    const { id, setTheme } = useContext(ThemeContext);

    return (
        <StyledHeader>
            <Link to="/">
                <Logo width='180px' />
            </Link>
            <Form displaySpan={false} />
            <Toggle isDark={id === 'dark'} onToggle={setTheme} />
        </StyledHeader>
    );
}
Example #5
Source File: EmptyTableIndicator.js    From loopring-pay with Apache License 2.0 6 votes vote down vote up
EmptyTableIndicator = ({ text, ...props }) => {
  const theme = useContext(ThemeContext);
  if (props.loading) {
    return <div />;
  }

  return (
    <EmptyTableIndicatorWrapper>
      <img
        style={{
          marginTop: props.marginTop,
          width: "68px",
          height: "auto",
          userSelect: "none",
          opacity: "1",
        }}
        src={`assets/images/${theme.imgDir}/no-data.svg`}
        alt="No Data"
        draggable="false"
      />
      <div
        style={{
          paddingTop: "2px",
          fontSize: "0.85rem",
          marginBottom: props.marginTop,
        }}
      >
        <I s={text} />
      </div>
    </EmptyTableIndicatorWrapper>
  );
}
Example #6
Source File: SideBarDrawer.js    From dexwebapp with Apache License 2.0 5 votes vote down vote up
SideBarDrawer = ({ header, body, footer, onClose, visible }) => {
  const theme = useContext(ThemeContext);
  return (
    <Drawer
      width={241}
      placement="right"
      closable={false}
      onClose={onClose}
      visible={visible}
      drawerStyle={{
        fontSize: '0.85rem',
        background: theme.sidePanelBackground,
      }}
      bodyStyle={{
        padding: '0',
      }}
      headerStyle={{
        height: 0,
      }}
    >
      <Layout
        onMouseLeave={onClose}
        style={{
          background: 'transparent',
          height: '100vh',
        }}
      >
        <div
          style={{
            background: theme.popupHeaderBackground,
            textAlign: 'center',
            width: '100%',
            height: AppLayout.topNavBarHeight,
            lineHeight: AppLayout.topNavBarHeight,
          }}
        >
          {header}
        </div>
        <Content>{body}</Content>
      </Layout>
    </Drawer>
  );
}
Example #7
Source File: Anchor.js    From VTour with MIT License 5 votes vote down vote up
Anchor = forwardRef(function (_ref, ref) {
  var a11yTitle = _ref.a11yTitle,
      children = _ref.children,
      color = _ref.color,
      disabled = _ref.disabled,
      href = _ref.href,
      icon = _ref.icon,
      label = _ref.label,
      _onBlur = _ref.onBlur,
      onClick = _ref.onClick,
      _onFocus = _ref.onFocus,
      reverse = _ref.reverse,
      rest = _objectWithoutPropertiesLoose(_ref, ["a11yTitle", "children", "color", "disabled", "href", "icon", "label", "onBlur", "onClick", "onFocus", "reverse"]);

  var theme = useContext(ThemeContext) || defaultProps.theme;

  var _useState = useState(),
      focus = _useState[0],
      setFocus = _useState[1];

  useEffect(function () {
    if ((icon || label) && children) {
      console.warn('Anchor should not have children if icon or label is provided');
    }
  }, [children, icon, label]);
  var coloredIcon = icon;

  if (icon && !icon.props.color) {
    coloredIcon = cloneElement(icon, {
      color: normalizeColor(color || theme.anchor.color, theme)
    });
  }

  var first = reverse ? label : coloredIcon;
  var second = reverse ? coloredIcon : label;
  return React.createElement(StyledAnchor, _extends({}, rest, {
    ref: ref,
    "aria-label": a11yTitle,
    colorProp: color,
    disabled: disabled,
    hasIcon: !!icon,
    focus: focus,
    hasLabel: label,
    reverse: reverse,
    href: !disabled ? href : undefined,
    onClick: !disabled ? onClick : undefined,
    onFocus: function onFocus(event) {
      setFocus(true);
      if (_onFocus) _onFocus(event);
    },
    onBlur: function onBlur(event) {
      setFocus(false);
      if (_onBlur) _onBlur(event);
    }
  }), first && second ? React.createElement(Box, {
    as: "span",
    direction: "row",
    align: "center",
    gap: "small",
    style: {
      display: 'inline-flex'
    }
  }, first, second) : first || second || children);
})
Example #8
Source File: index.js    From code-resume with MIT License 5 votes vote down vote up
Editor = (props) => {  
    const theme = useContext(ThemeContext);        
    const tab = props.path;
    const fTabName = tab.charAt(0).toUpperCase();
    const rTabName = tab.slice(1);
    const content = props.data && props.data[tab];       
    const head = `import ${fTabName}${rTabName} from '${fTabName}${rTabName}'`;
    
    let count = 0, color = '';
    
    const header = head.split(' ').map((str, index) => {
        return (
            <Span 
                initial={{ y: -50 }}
                animate={{y: 0}}
                transition={{ duration: .3 }}  
                key={str} color={theme.headerColor[`color${index}`]}>
                {str} 
                </Span>
            )
    });

    const detail = content.split("\n").map((str, index) => {
        if (count >= 6) count = 0;
        if (index >= 6) {
            color = theme.contentColor[`color${count}`];
            count++;
        } else {
            color = theme.contentColor[`color${index}`]
        }      
        
        let renderPre = (
            <Pre 
                initial={{ x: 10 }}
                animate={{x: 0}}
                whileHover={{ x: 5 }} 
                transition={{ duration: .2 }} 
                key={`${str + index}-detail`} 
                color={color}
            >{str}</Pre>
        );

        if (str.includes('href=')) {
            renderPre = (
                <Pre 
                    initial={{ x: 10 }}
                    animate={{x: 0}}
                    whileHover={{ x: 5 }} 
                    transition={{ duration: .2 }} 
                    key={`${str + index}-detail`} 
                    color={color}
                    dangerouslySetInnerHTML={{__html: str}}></Pre>
            )
        } 

        return (
            <PageWrap key={index}>
                <LineNo>{index + 2}</LineNo>
                {renderPre}
            </PageWrap>
        )
    });
    
    return (
        <Wrapper>
            <FirstLineNo>1</FirstLineNo>
            {header}
            {detail}
        </Wrapper>
    )
}
Example #9
Source File: ProposalTurnout.jsx    From cosmoscan-front with Apache License 2.0 5 votes vote down vote up
ProposalTurnout = ({ isLoading, data }) => {
  const theme = useContext(ThemeContext);
  const [proposals, setProposals] = useState(data);
  useEffect(() => {
    setProposals(data);
  }, [data]);
  const handleChange = (opt) => {
    switch (opt.value) {
      case 3:
        setProposals(data.slice(-3));
        break;
      case 10:
        setProposals(data.slice(-10));
        break;
      default:
        setProposals(data);
        break;
    }
  };

  return (
    <ChartContainer
      title={chartName}
      titleTooltip={tooltipTxt}
      select={(
        <SelectCustom
          opts={numsOfProposals}
          defaultOpt={numsOfProposals[2]}
          onChange={handleChange}
        />
          )}
      chart={(
        <BarChart
          isLoading={isLoading}
          data={proposals}
          yAxisWidth={yAxisWidth}
          yAxisTickCount={yAxisTickCount}
          yAxisLabelsFormatter={formatPercentValue}
          xAxisTickFormatter={formatId}
          tooltipLabelFormatter={tooltipLabelFormatter}
          tooltipFormatter={formatPercentValue}
          barColor={theme.blue}
          barName={barName}
        />
          )}
    />
  );
}
Example #10
Source File: Chart.js    From gitpedia with MIT License 5 votes vote down vote up
DoughnutChart = () => {
    const themeContext = useContext(ThemeContext);

    const data = {
        labels: [],
        datasets: [
            {
                label: "",
                data: [],
                backgroundColor: bgColor,
                borderWidth: 0,
            },
        ],
    };

    return (
        <LanguageContext.Consumer>
            {(context) => {
                const LIMIT = 10;
                let labels = context.map((obj) => obj.label);

                // If more than LIMIT languages then reduce it to the limit
                if (labels.length >= LIMIT) {
                    labels = labels.slice(0, LIMIT);
                }
                const value = context.map((obj) => obj.value).slice(0, LIMIT);
                data.labels = labels;
                data.datasets[0].data = value;

                return (
                    <Doughnut
                        data={data}
                        options={{
                            maintainAspectRatio: false,
                            responsive: true,
                            title: {
                                display: false,
                            },
                            legend: {
                                // display: false,
                                position: "bottom",
                                labels: {
                                    fontColor: themeContext.textColor,
                                }
                            },
                        }}
                    />
                );
            }}
        </LanguageContext.Consumer>
    );
}
Example #11
Source File: PayTable.js    From loopring-pay with Apache License 2.0 5 votes vote down vote up
PayTable = ({
  columnBuilders,
  rowData,
  emptyText,
  margin,
  loading,
}) => {
  const theme = useContext(ThemeContext);
  const _rowData = rowData || [];
  const customizeRenderEmpty = () => <EmptyTableIndicator text={emptyText} />;

  const columns = columnBuilders.map((builder, j) => ({
    ...builder,
    dataIndex: "col_" + j,
  }));

  const dataSource = _rowData.map((row, i) => {
    var rowValue = { key: i };

    columnBuilders.forEach((builder, j) => {
      rowValue["col_" + j] = (
        <Cell margin={margin}>{builder.getColValue(row)}</Cell>
      );
    });

    return rowValue;
  });

  return (
    <SimpleTableContainer>
      <ConfigProvider
        renderEmpty={dataSource.length === 0 && customizeRenderEmpty}
      >
        <TableLoadingSpin loading={loading}>
          <Table
            showHeader={false}
            tableLayout="auto"
            dataSource={dataSource}
            columns={columns}
            pagination={false}
          />
        </TableLoadingSpin>
        {/* {dataSource.length > 10 ? (
          <Pagination
            style={{
              padding: '30px 0px',
              background: theme.background,
              textAlign: 'center',
            }}
            size=""
            total={dataSource.length}
            pageSize={10}
          />
        ) : (
          <div />
        )} */}
      </ConfigProvider>
    </SimpleTableContainer>
  );
}
Example #12
Source File: useTheme.js    From plataforma-sabia with MIT License 5 votes vote down vote up
function useTheme() {
	const themeContext = useContext(ThemeContext);

	return themeContext;
}
Example #13
Source File: index.js    From covidzero-frontend with Apache License 2.0 4 votes vote down vote up
MapArea = ({ userLat, userLng, initialZoom, citiesCases, error }) => {

    const themeContext = useContext(ThemeContext);

    const defaultOptions = {
				zoom: initialZoom,
				gestureHandling: 'greedy',
        /*limites mapa*/
        southAmericaBounds: {
            west: -103.8386805338,
            south: -43.054008204,
            east: -15.3869376826,
            north: 16.2780526563,
        },
    }

    const mapRef = useRef();
    const mapsRef = useRef();
    const [zoom, setZoom] = useState(defaultOptions.zoom);
    const [bounds, setBounds] = useState(null);
    const [markersHospital, setMarkersHospital] = useState([]);
    const [circleSize, setCircleSize] = useState(80);

    const getCityCases = () => {
        let cityCases = [];

        citiesCases.map(cases => {
            if (cases.ibge_id && cityCases.indexOf(cases.ibge_id) === -1) {
                cityCases.push(cases);
            }
        });

        return cityCases;
    }

    const getCasesCity = () => {
        let cityCases = [];

        const _getCityCases = getCityCases();
        const cityProp = BrAll.objects.BR_LEVE.geometries;

        _getCityCases.map(city => {
            for (let _key in cityProp) {
                if (city.ibge_id === cityProp[_key].properties.id) {
                    let { id, centroide, NM_MUNICIP: cityName } = cityProp[
                        _key
                    ].properties;

                    centroide = centroideFormat(centroide);
                    cityCases.push({
                        id,
                        cityName,
                        totalCases: city.totalcases,
                        longitude: centroide[0],
                        latitude: centroide[1]
                    });
                }
            }
        });

        return cityCases;
    }

    const centroideFormat = value => {
        return value
            .replace("(", "")
            .replace(")", "")
            .split(",");
    }

    let confirmed = getCasesCity()

    confirmed.map(item => {
        item['type'] = 'confirmed'
    })

    const markers = [...confirmed, ...suspect, ...recovered]

    const points = markers.map((marker, index) => ({
        type: "Feature",
        properties: { cluster: false, category: marker.type, id: index, totalCases: marker.totalCases, cityName: marker.cityName },
        geometry: {
            type: "Point",
            coordinates: [
                marker.longitude,
                marker.latitude
            ]
        }
    }))

    const { clusters, supercluster } = useSupercluster({
        points,
        bounds,
        zoom,
        options: { radius: 150, maxZoom: 20 }
    });
    

    const createRoute = (map, maps, placeId) => {

        var directionsService = new maps.DirectionsService();
        var directionsRenderer = new maps.DirectionsRenderer();
        directionsRenderer.setMap(map);

        let origin = new maps.LatLng(userLat, userLng);

        directionsService.route(
            {
                origin,
                destination: { placeId },
                travelMode: 'DRIVING'
            },
            function (response, status) {
                if (status === 'OK') {
                    directionsRenderer.setDirections(response);
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });

    }

    const getHospitals = () => {

        const map = mapRef.current;
        const maps = mapsRef.current;

        if (!map || !maps) return
        //let bounds = map.getBounds()

        let pyrmont = new maps.LatLng(map.getCenter().lat(), map.getCenter().lng());
        let places = new maps.places.PlacesService(map);

        var request = {
            location: pyrmont,
            //bounds,
            radius: '5000',
            type: ['hospital'],
        };

        places.nearbySearch(
            request,
            function (results, status, pagination) {
                if (status !== 'OK') return;
                setMarkersHospital(results)
            });

    }

    useEffect(() => {
        if (zoom <= 10) {
            setMarkersHospital([])
        } else {
            getHospitals();
        }

        let minPixelSize = 80;
        let maxPixelSize = 350;

        let relativePixelSize = Math.round(Math.pow(zoom, 2.1));

        if (relativePixelSize > maxPixelSize)
            relativePixelSize = maxPixelSize;

        if (relativePixelSize < minPixelSize)
            relativePixelSize = minPixelSize;

        setCircleSize(relativePixelSize)

    }, [bounds, zoom]);

    const isOpen = async (placeId) => {

        const maps = mapsRef.current
        const map = mapRef.current

        let request = {
            placeId,
        }

        let places = new maps.places.PlacesService(map);

        let isOpen = await places.getDetails(request, (place, status) => {
            if (status === maps.places.PlacesServiceStatus.OK) {
                return (place.opening_hours && place.opening_hours.isOpen())
            } else {
                return false
            }
        });

        return isOpen

    }

    const _onChange = ({ zoom, bounds }) => {
        setZoom(zoom);
        setBounds([
            bounds.nw.lng,
            bounds.se.lat,
            bounds.se.lng,
            bounds.nw.lat
        ])
    }

    const _youClick = () => {
        const map = mapRef.current
        map.setZoom(14);
        map.panTo({ lat: userLat, lng: userLng })
    }

    const _apiIsLoaded = (map, maps) => {
        mapRef.current = map;
        mapsRef.current = maps;
        getHospitals()
        //createRoute(map, maps, 'ChIJC_-xjJ-QyJQR1yqVAokq4GY')

        /* */
        const legendsDiv = document.createElement('div');
        ReactDOM.render(
            <Styled.ContainerChips>
                <Chips height={10} onClick={_youClick} theme={themeContext} text="VocĂȘ" type="you" />
                <Chips height={10} theme={themeContext} text="Confirmados" type="confirmed" />
            </Styled.ContainerChips>
            , legendsDiv);
        map.controls[maps.ControlPosition.BOTTOM_CENTER].push(legendsDiv);
        /**/

    };

    const _createMapOptions = (maps) => {
        // next props are exposed at maps
        // "Animation", "ControlPosition", "MapTypeControlStyle", "MapTypeId",
        // "NavigationControlStyle", "ScaleControlStyle", "StrokePosition", "SymbolPath", "ZoomControlStyle",
        // "DirectionsStatus", "DirectionsTravelMode", "DirectionsUnitSystem", "DistanceMatrixStatus",
        // "DistanceMatrixElementStatus", "ElevationStatus", "GeocoderLocationType", "GeocoderStatus", "KmlLayerStatus",
        // "MaxZoomStatus", "StreetViewStatus", "TransitMode", "TransitRoutePreference", "TravelMode", "UnitSystem"
        return {
            zoomControlOptions: {
                position: maps.ControlPosition.RIGHT_BOTTOM,
                style: maps.ZoomControlStyle.SMALL
            },
            mapTypeControlOptions: {
                position: maps.ControlPosition.TOP_RIGHT
            },
            mapTypeControl: true,
            fullscreenControl: false,
            restriction: {
                latLngBounds: defaultOptions.southAmericaBounds,
                strictBounds: false
            },
            minZoom: 4,
            maxZoom: 16
        };
    }

    const _onChildClick = () => {
        
    }

    return (
        <GoogleMapReact
            bootstrapURLKeys={{ key: GMAP_KEY, libraries: ['places'] }}
            defaultCenter={[userLat, userLng]}
            defaultZoom={defaultOptions.zoom}
            yesIWantToUseGoogleMapApiInternals
            onGoogleApiLoaded={({ map, maps }) => _apiIsLoaded(map, maps)}
            onChange={_onChange}
            options={_createMapOptions}
            onChildClick={_onChildClick}
        >

            {clusters.map(cluster => {
                const [longitude, latitude] = cluster.geometry.coordinates;
                const { cluster: isCluster, point_count: pointCount, category, id, cityName, totalCases } = cluster.properties

                if (isCluster) {
                    return (
                        <Circle key={cluster.id} width={circleSize} height={circleSize} isCluster={isCluster} pointCount={pointCount} type="confirmed"
                            lat={latitude}
                            lng={longitude}
                            onClick={() => {
                                const expansionZoom = Math.min(
                                    supercluster.getClusterExpansionZoom(cluster.id), 20
                                );
                                mapRef.current.setZoom(expansionZoom);
                                mapRef.current.panTo({ lat: latitude, lng: longitude })
                            }}
                        />
                    )
                }

                return (

                    <Styled.ContainerMarker
                        lat={latitude}
                        lng={longitude}
                        key={id}
                        data-tip={`
                        <strong>Cidade:</strong> ${cityName} <br>
                        <strong>Casos:</strong> ${totalCases} <br>
                        `}
                    >
                        <Circle width={circleSize} height={circleSize} type={category} />
                        <ReactTooltip html={true} />
                    </Styled.ContainerMarker>

                )

            })}

            {userLat && userLng && !error &&
                <Styled.ContainerMarker
                    lat={userLat}
                    lng={userLng}
                    key={-1}
                    data-tip='VocĂȘ'
                >
                    <Circle type='you' />
                    <ReactTooltip />
                </Styled.ContainerMarker>
            }

            {markersHospital.map((hospital) => {
                const { lat, lng } = hospital.geometry.location;
                return (
                    <Styled.ContainerMarker
                        lat={lat()}
                        lng={lng()}
                        key={hospital.id}
                        data-tip={`
                        ${hospital.name} </br>
                        ${hospital.opening_hours && hospital.opening_hours.open_now ? "Aberto" : ''} <!-- deprecated -->
                        `}
                    >
                        <Marker type='hospital' />
                        <ReactTooltip html={true} />
                    </Styled.ContainerMarker>

                )
            })}

        </GoogleMapReact>
    );
}
Example #14
Source File: NumericInput.js    From dexwebapp with Apache License 2.0 4 votes vote down vote up
NumericInput = ({
  decimals,
  onChange,
  value,
  onBlur,
  suffix,
  fontSize,
  onClick,
  color,
  onKeyDown,
  disabled,
}) => {
  function inputOnChange(e) {
    // Avoid invalid input that may cause crash
    try {
      const { value } = e.target;
      if (typeof decimals === 'undefined') decimals = 100;
      const reg = new RegExp(
        '^-?(0|[1-9][0-9]*)(\\.[0-9]{0,' + decimals + '})?$'
      );
      if (
        (!Number.isNaN(value) && reg.test(value)) ||
        value === '' ||
        value === '-'
      ) {
        onChange(value);
      } else if (!isNaN(value) && value.toString().indexOf('.') !== -1) {
        // If string contains only one .
        const valueInFloat = parseFloat(value);
        if (valueInFloat === 0) {
          // 00000
          // 000.00 => 0.00
          onChange('0' + value.replace(/^0+/, ''));
        } else if (valueInFloat > 0) {
          // input has too many decimals. This will be caught in the parent component.
          onChange(value);
        }
      } else if (/^0*$/.test(value)) {
        // If string contains only 0
        onChange(value);
      } else if (value === '.') {
        // . => 0.
        onChange('0.');
      } else {
        // 0000000
        // 00001000 => 1000
        const removedFirstZerosValue = value.replace(/^0+/, '');
        if (
          !Number.isNaN(removedFirstZerosValue) &&
          reg.test(removedFirstZerosValue)
        ) {
          onChange(removedFirstZerosValue);
        }
      }
    } catch (error) {}
  }

  // '.' at the end or only '-' in the input box.
  function inputOnBlur() {
    try {
      if (value && (value.charAt(value.length - 1) === '.' || value === '-')) {
        onChange(value.slice(0, -1));
      }
      if (onBlur) {
        onBlur();
      }
    } catch (error) {}
  }

  function defaultOnKeyDown() {}

  if (fontSize) {
  } else {
    fontSize = '0.9em';
  }

  const theme = useContext(ThemeContext);
  return (
    <Input
      autoComplete={'off'}
      value={value}
      onChange={inputOnChange}
      onClick={onClick}
      onBlur={inputOnBlur}
      placeholder={Number(0).toFixed(decimals)}
      maxLength={25}
      style={{
        width: '100%',
        background: 'transparent',
        color: color ? color : theme.textWhite,
      }}
      suffix={
        <div
          style={{
            color: color ? color : theme.textWhite,
            fontSize: fontSize,
            userSelect: 'none',
            lineHeight: '40px',
          }}
        >
          {suffix}
        </div>
      }
      onKeyDown={onKeyDown}
      disabled={disabled}
    />
  );
}
Example #15
Source File: Box.js    From VTour with MIT License 4 votes vote down vote up
Box = forwardRef(function (_ref, ref) {
  var a11yTitle = _ref.a11yTitle,
      background = _ref.background,
      border = _ref.border,
      children = _ref.children,
      _ref$direction = _ref.direction,
      direction = _ref$direction === void 0 ? 'column' : _ref$direction,
      elevation = _ref.elevation,
      fill = _ref.fill,
      gap = _ref.gap,
      _onBlur = _ref.onBlur,
      onClick = _ref.onClick,
      _onFocus = _ref.onFocus,
      overflow = _ref.overflow,
      _ref$responsive = _ref.responsive,
      responsive = _ref$responsive === void 0 ? true : _ref$responsive,
      tag = _ref.tag,
      as = _ref.as,
      wrap = _ref.wrap,
      width = _ref.width,
      height = _ref.height,
      tabIndex = _ref.tabIndex,
      rest = _objectWithoutPropertiesLoose(_ref, ["a11yTitle", "background", "border", "children", "direction", "elevation", "fill", "gap", "onBlur", "onClick", "onFocus", "overflow", "responsive", "tag", "as", "wrap", "width", "height", "tabIndex"]);

  var theme = useContext(ThemeContext) || defaultProps.theme;
  var focusable = useMemo(function () {
    return onClick && !(tabIndex < 0);
  }, [onClick, tabIndex]);

  var _useState = useState(),
      focus = _useState[0],
      setFocus = _useState[1];

  var clickProps = useMemo(function () {
    if (focusable) {
      return {
        onClick: onClick,
        onFocus: function onFocus(event) {
          setFocus(true);
          if (_onFocus) _onFocus(event);
        },
        onBlur: function onBlur(event) {
          setFocus(false);
          if (_onBlur) _onBlur(event);
        }
      };
    }

    var result = {};
    if (_onBlur) result.onBlur = _onBlur;
    if (onClick) result.onClick = onClick;
    if (_onFocus) result.onFocus = _onFocus;
    return result;
  }, [focusable, onClick, _onFocus, _onBlur]);
  var adjustedTabIndex = useMemo(function () {
    if (tabIndex !== undefined) return tabIndex;
    if (focusable) return 0;
    return undefined;
  }, [focusable, tabIndex]);

  if ((border === 'between' || border && border.side === 'between') && !gap) {
    console.warn('Box must have a gap to use border between');
  }

  var contents = children;

  if (gap) {
    contents = [];
    var firstIndex;
    Children.forEach(children, function (child, index) {
      if (child) {
        if (firstIndex === undefined) {
          firstIndex = index;
        } else {
          contents.push(React.createElement(StyledBoxGap // eslint-disable-next-line react/no-array-index-key
          , {
            key: "gap-" + index,
            gap: gap,
            directionProp: direction,
            responsive: responsive,
            border: border
          }));
        }
      }

      contents.push(child);
    });
  }

  if (background || theme.darkChanged) {
    var dark = backgroundIsDark(background, theme);
    var darkChanged = dark !== undefined && dark !== theme.dark;

    if (darkChanged || theme.darkChanged) {
      dark = dark === undefined ? theme.dark : dark;
      contents = React.createElement(ThemeContext.Provider, {
        value: _extends({}, theme, {
          dark: dark
        })
      }, contents);
    }
  }

  var content = React.createElement(StyledBox, _extends({
    as: !as && tag ? tag : as,
    "aria-label": a11yTitle,
    background: background,
    border: border,
    ref: ref,
    directionProp: direction,
    elevationProp: elevation,
    fillProp: fill,
    focus: focus,
    overflowProp: overflow,
    wrapProp: wrap,
    widthProp: width,
    heightProp: height,
    responsive: responsive,
    tabIndex: adjustedTabIndex
  }, clickProps, rest), contents);

  if (onClick) {
    content = React.createElement(Keyboard, {
      onEnter: onClick
    }, content);
  }

  return content;
})
Example #16
Source File: index.js    From Agaave-frontend with MIT License 4 votes vote down vote up
Button = ({
  children,
  disabled,
  href,
  onClick,
  size,
  text,
  to,
  variant,
}) => {
  const { color } = useContext(ThemeContext);

  let buttonColor;
  let borderColor;
  let backgroundColor;
  let boxShadow;
  let opacity;
  switch (variant) {
    case 'secondary':
      buttonColor = color.white;
      borderColor = 'transparent';
      backgroundColor = color.pink;
      boxShadow = `${color.pink} 0px 1px 3px 0px;`;
      opacity = '1';
      break;
    case 'outline':
      buttonColor = color.grey[200];
      borderColor = 'transparent';
      backgroundColor = 'transparent';
      boxShadow = `none`;
      opacity = '0.8';
      break;
    case 'primary':
    default:
      buttonColor = color.white;
      borderColor = 'transparent';
      backgroundColor = color.grey[100];
      boxShadow = `${color.grey[200]} 0px 1px 3px 0px;`;
      opacity = '1';
  }

  let width;
  let height;
  let fontSize;
  switch (size) {
    case 'sm':
      width = 70;
      height = 24;
      fontSize = 10;
      break
    case 'lg':
      width = 120;
      height = 36;
      fontSize = 16;
      break
    case 'md':
    default:
      width = 100;
      height = 32;
      fontSize = 12;
  }

  const ButtonChild = useMemo(() => {
    if (to) {
      return <StyledLink to={to}>{text}</StyledLink>
    } else if (href) {
      return <StyledExternalLink href={href} target="__blank">{text}</StyledExternalLink>
    } else {
      return text
    }
  }, [href, text, to])

  return (
    <StyledButton
      boxShadow={boxShadow}
      color={buttonColor}
      borderColor={borderColor}
      backgroundColor={backgroundColor}
      disabled={disabled}
      fontSize={fontSize}
      onClick={onClick}
      height={height}
      width={width}
      opacity={opacity}
    >
      {children}
      {ButtonChild}
    </StyledButton>
  )
}
Example #17
Source File: AreaChart.jsx    From cosmoscan-front with Apache License 2.0 4 votes vote down vote up
AreaChart = ({
  isLoading,
  data,
  yAxisLabelsFormatter,
  yAxisWidth,
  yTickCount,
  xAxisTickFormatter,
  yAxisDomain,
  yAllowDecimals,
  tooltipFormatter,
  tooltipLabelFormatter,
  areaName,
  areaUnit,
  color,
  onDotClick,
  isDotClickable,
}) => {
  const theme = useContext(ThemeContext);

  return (
    <div style={{ width: '100%', height: '400px' }}>
      {/* eslint-disable-next-line no-nested-ternary */}
      {isLoading ? (
        <div className="d-flex justify-content-center align-items-center h-100">
          <Spinner />
        </div>
      ) : data && data.length ? (
        <ResponsiveContainer>
          <AreaChartStyled data={data}>
            <XAxis
              dataKey="x"
              tickLine={false}
              tick={{ fill: theme.gray }}
              axisLine={false}
              tickFormatter={xAxisTickFormatter}
            />
            <YAxis
              tickLine={false}
              tick={{ fill: theme.gray }}
              tickFormatter={yAxisLabelsFormatter}
              width={yAxisWidth}
              tickCount={yTickCount}
              axisLine={false}
              type="number"
              domain={yAxisDomain}
              allowDecimals={yAllowDecimals}
            />
            <CartesianGrid
              strokeDasharray="3 3"
              stroke="#e2e2e9"
              vertical={false}
            />
            <Tooltip
              cursor={{ strokeDasharray: '3 3', stroke: color }}
              formatter={tooltipFormatter}
              labelFormatter={tooltipLabelFormatter}
            />
            <Legend
              align="left"
              iconType="circle"
              verticalAlign="top"
              height={50}
              wrapperStyle={{
                fontWeight: 700,
                textTransform: 'uppercase',
              }}
            />
            <Area
              type="monotone"
              dataKey="y"
              stroke={color}
              fill={color}
              fillOpacity={0.3}
              activeDot={{
                r: 6,
                onClick: onDotClick,
                cursor: isDotClickable ? 'pointer' : 'initial',
              }}
              strokeWidth={2}
              connectNulls
              unit={areaUnit}
              name={areaName}
            />
          </AreaChartStyled>
        </ResponsiveContainer>
      ) : (
        <div className="d-flex justify-content-center align-items-center h-100">
          No data
        </div>
      )}
    </div>
  );
}
Example #18
Source File: ModalIndicator.js    From loopring-pay with Apache License 2.0 4 votes vote down vote up
ModalIndicator = ({
  title,
  tipIcons,
  tips,
  marginTop,
  imageUrl,
  textAlign,
}) => {
  const theme = useContext(ThemeContext);
  const tips_ = tips || [];
  const marginTop_ = marginTop || "80px";
  const textAlign_ = textAlign || "left";

  let tipsDiv;
  if (tipIcons && tips && tipIcons.length === tips.length) {
    tipsDiv = tips_.map((tip, i) => (
      <div
        style={{
          textAlign: textAlign_,
          margin: "16px",
        }}
        key={i}
      >
        <Row>
          <Col span={2}>{tipIcons[i]}</Col>
          <Col span={22}>{tip}</Col>
        </Row>
      </div>
    ));
  } else {
    tipsDiv = tips_.map((tip, i) => (
      <div
        style={{
          textAlign: textAlign_,
          margin: "16px",
        }}
        key={i}
      >
        {tip}
      </div>
    ));
  }

  return (
    <div>
      <FontAwesomeIcon
        icon={faCircleNotch}
        size="2x"
        spin
        style={{ margin: "20px", marginTop: marginTop_ }}
      />

      <div
        style={{
          margin: "16px",
          paddingLeft: "20px",
          paddingRight: "20px",
          color: theme.primary,
          fontSize: "1rem",
        }}
      >
        <I s={title} />
      </div>

      <div
        style={{
          fontSize: "0.85rem",
          color: theme.textWhite,
        }}
      >
        {tipsDiv}
      </div>

      {imageUrl ? (
        <div>
          <img
            alt="check metamask plugin icon"
            style={{
              userSelect: "none",
              height: "80px",
              marginTop: "16px",
              filter: "drop-shadow(0 10px 10px rgba(0, 0, 0, 0.2)",
            }}
            src={imageUrl}
          />
        </div>
      ) : (
        <span />
      )}
    </div>
  );
}
Example #19
Source File: zoom.js    From orangutan-monorepo with MIT License 4 votes vote down vote up
Zoom = props => {
  const themeContext = useContext(ThemeContext)
  const { zoomOptions } = themeContext
  const animate = animations[themeContext.caption.side] || animations.default
  const overlayRef = useRef(null)
  const originalRef = useRef(null)
  const zoomedRef = useRef(null)
  const containerRef = useRef(null)
  const captionRef = useRef(null)

  let isAnimating = false
  const setAnimating = bool => {
    isAnimating = bool
  }

  let isZoomed = false
  const setZoom = bool => {
    isZoomed = bool
  }

  const getCaptionHeight = captionLength => {
    const { fontSize, letterSpacing, width, lineHeight } = themeContext.caption
    const height =
      Math.ceil((captionLength * (fontSize + letterSpacing)) / width) *
      lineHeight
    return height
  }

  const handleOpenEnd = () => {
    if (!isAnimating) return
    if (!captionRef.current) return

    setAnimating(false)
    captionRef.current.style.opacity = 1
  }

  const handleCloseEnd = () => {
    if (!containerRef.current || !overlayRef.current || !zoomedRef.current)
      return

    overlayRef.current.style.cursor = ''
    zoomedRef.current.setAttribute(
      'style',
      `position: absolute;
		   left: 0;
       top: 0;
       cursor: pointer;
       cursor: zoom-in;`
    )
    setAnimating(false)
    containerRef.current.style.zIndex = '0'
    overlayRef.current.style.display = 'none'
  }

  const handleTransitionEnd = () =>
    isZoomed ? handleOpenEnd() : handleCloseEnd()

  let scrollTop = 0

  const open = ({ target } = {}) => {
    if (!target) return
    if (isZoomed) return
    if (!containerRef.current || !overlayRef.current || !zoomedRef.current)
      return

    const { overlay } = themeContext
    const { width: clientWidth, height: clientHeight } = getViewportSize()

    scrollTop =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop ||
      0

    setAnimating(true)
    setZoom(true)

    containerRef.current.style.zIndex = overlay.zIndex
    overlayRef.current.style.display = 'block'

    overlayRef.current.setAttribute(
      'style',
      `cursor: pointer;
      cursor: zoom-out;`
    )
    zoomedRef.current.setAttribute(
      'style',
      `cursor: pointer;
      cursor: zoom-out;`
    )

    animate({
      originalNode: originalRef.current,
      zoomedNode: zoomedRef.current,
      captionNode: captionRef.current,
      themeContext,
      captionHeight: getCaptionHeight(props.caption.length),
      clientWidth,
      clientHeight,
    })

    overlayRef.current.style.opacity = overlay.opacity
  }

  const close = () => {
    if (isAnimating || !isZoomed) return
    if (
      !overlayRef.current ||
      !zoomedRef.current ||
      !captionRef.current ||
      !originalRef.current
    )
      return

    setAnimating(true)
    setZoom(false)

    overlayRef.current.style.opacity = '0'
    zoomedRef.current.style.transform = ''

    captionRef.current.setAttribute(
      'style',
      `position: absolute;
       top: 0;
       left: 0;
       opacity: 0;
       visibility: hidden;`
    )
    originalRef.current.setAttribute(
      'style',
      `visibility: hidden;
       position: relative;`
    )
  }

  const toggle = ({ target } = {}) => {
    if (isZoomed) {
      return close()
    }
    if (target) {
      return open({ target })
    }
  }

  const handleScroll = () => {
    if (isAnimating || !isZoomed) return

    const currentScroll =
      window.pageYOffset ||
      document.documentElement.scrollTop ||
      document.body.scrollTop ||
      0

    if (Math.abs(scrollTop - currentScroll) > zoomOptions.scrollOffset) {
      setTimeout(close, 50)
    }
  }

  const handleKeyUp = event => {
    const key = event.key || event.keyCode

    // Close if escape key is pressed
    if (key === 'Escape' || key === 'Esc' || key === 27) {
      close()
    }
  }

  useEffect(() => {
    if (!originalRef.current || !zoomedRef.current) return
    originalRef.current.style.width = '100%'
    zoomedRef.current.style.width = '100%'
    overlayRef.current.style.display = 'none'
  }, [])
  useEventListener(document, 'keyup', handleKeyUp)
  useEventListener(document, 'scroll', handleScroll)
  useEventListener(window, 'resize', close)
  useEventListener(zoomedRef, 'transitionend', handleTransitionEnd)

  if (Children.count(props.children) !== 1) {
    console.error(`
      Error: Adjacent JSX elements must be wrapped in an enclosing tag. 
      Did you want a <div>...</div>?
    `)
    return null
  }

  const { overlay, caption } = themeContext

  return (
    <Container ref={containerRef}>
      <Original ref={originalRef} onClick={toggle}>
        {props.children}
      </Original>
      <Overlay
        ref={overlayRef}
        background={overlay.background}
        onClick={close}
        transitionDuration={zoomOptions.transitionDuration}
      />
      <Zoomable ref={zoomedRef} onClick={toggle}>
        {props.children}
      </Zoomable>
      <Caption
        ref={captionRef}
        fontSize={caption.fontSize}
        lineHeight={caption.lineHeight}
        letterSpacing={caption.letterSpacing}
        color={caption.color}
        fontFamily={caption.fontFamily}
      >
        {props.caption}
      </Caption>
    </Container>
  )
}
Example #20
Source File: BarChart.jsx    From cosmoscan-front with Apache License 2.0 3 votes vote down vote up
BarChart = ({
  isLoading,
  data,
  yAxisWidth,
  yAxisTickCount,
  yAxisLabelsFormatter,
  xAxisTickFormatter,
  xAxisTickCount,
  xAxisTickInterval,
  yAxisDomain,
  tooltipFormatter,
  tooltipLabelFormatter,
  barName,
  barColor,
  noLegend,
  customTooltip,
  isBrush,
}) => {
  const theme = useContext(ThemeContext);

  return (
    <div style={{ width: '100%', height: '400px' }}>
      {/* eslint-disable-next-line no-nested-ternary */}
      {isLoading ? (
        <div className="d-flex justify-content-center align-items-center h-100">
          <Spinner />
        </div>
      ) : data && data.length ? (
        <ResponsiveContainer>
          <BarChartStyled data={data}>
            <CartesianGrid
              strokeDasharray="3 3"
              stroke="#e2e2e9"
              vertical={false}
            />
            <XAxis
              dataKey="name"
              tickLine={false}
              tick={{ fill: theme.gray }}
              tickCount={xAxisTickCount}
              axisLine={false}
              tickFormatter={xAxisTickFormatter}
              interval={xAxisTickInterval}
              minTickGap={0}
            />
            <YAxis
              axisLine={false}
              tickLine={false}
              tick={{ fill: theme.gray }}
              width={yAxisWidth}
              tickCount={yAxisTickCount}
              tickFormatter={yAxisLabelsFormatter}
              type="number"
              domain={yAxisDomain}
            />
            <Tooltip
              formatter={tooltipFormatter}
              labelFormatter={tooltipLabelFormatter}
              content={customTooltip || null}
            />
            {!noLegend && (
              <Legend
                align="left"
                iconType="circle"
                verticalAlign="top"
                height={50}
                wrapperStyle={{
                  fontWeight: 700,
                  textTransform: 'uppercase',
                }}
              />
            )}
            {isBrush && (
              <Brush
                dataKey="name"
                height={15}
                stroke={barColor}
                gap={10}
                startIndex={data.length - 20}
                travellerWidth={8}
                className="mt-5"
              />
            )}
            <Bar
              dataKey="dataPiece"
              fill={barColor}
              name={barName}
              minPointSize={1}
            />
          </BarChartStyled>
        </ResponsiveContainer>
      ) : (
        <div className="d-flex justify-content-center align-items-center h-100">
          No data
        </div>
      )}
    </div>
  );
}