1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00

JS style updates [skip ci]

This commit is contained in:
checktheroads
2020-10-07 09:41:58 -07:00
parent 3743f1a4c5
commit 5e61e097a2
73 changed files with 995 additions and 1385 deletions

9
hyperglass/ui/.eslintrc Normal file
View File

@@ -0,0 +1,9 @@
{
"extends": "@upstatement/eslint-config/react",
"plugins": ["react-hooks"],
"settings": { "import/resolver": { "typescript": {} } },
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": ["warn"]
}
}

View File

@@ -1,4 +1,4 @@
import * as React from "react";
import * as React from 'react';
import {
Flex,
Icon,
@@ -8,39 +8,39 @@ import {
PopoverTrigger,
Text,
Tooltip,
useColorMode
} from "@chakra-ui/core";
import { MdLastPage } from "@meronex/icons/md";
import dayjs from "dayjs";
import relativeTimePlugin from "dayjs/plugin/relativeTime";
import utcPlugin from "dayjs/plugin/utc";
import { useConfig } from "app/context";
import { Table } from "app/components";
useColorMode,
} from '@chakra-ui/core';
import { MdLastPage } from '@meronex/icons/md';
import dayjs from 'dayjs';
import relativeTimePlugin from 'dayjs/plugin/relativeTime';
import utcPlugin from 'dayjs/plugin/utc';
import { useConfig } from 'app/context';
import { Table } from 'app/components';
dayjs.extend(relativeTimePlugin);
dayjs.extend(utcPlugin);
const isActiveColor = {
true: { dark: "green.300", light: "green.500" },
false: { dark: "gray.300", light: "gray.500" }
true: { dark: 'green.300', light: 'green.500' },
false: { dark: 'gray.300', light: 'gray.500' },
};
const arrowColor = {
true: { dark: "blackAlpha.500", light: "blackAlpha.500" },
false: { dark: "whiteAlpha.300", light: "blackAlpha.500" }
true: { dark: 'blackAlpha.500', light: 'blackAlpha.500' },
false: { dark: 'whiteAlpha.300', light: 'blackAlpha.500' },
};
const rpkiIcon = ["not-allowed", "check-circle", "warning", "question"];
const rpkiIcon = ['not-allowed', 'check-circle', 'warning', 'question'];
const rpkiColor = {
true: {
dark: ["red.500", "green.600", "yellow.500", "gray.800"],
light: ["red.500", "green.500", "yellow.500", "gray.600"]
dark: ['red.500', 'green.600', 'yellow.500', 'gray.800'],
light: ['red.500', 'green.500', 'yellow.500', 'gray.600'],
},
false: {
dark: ["red.300", "green.300", "yellow.300", "gray.300"],
light: ["red.400", "green.500", "yellow.400", "gray.500"]
}
dark: ['red.300', 'green.300', 'yellow.300', 'gray.300'],
light: ['red.400', 'green.500', 'yellow.400', 'gray.500'],
},
};
const makeColumns = fields => {
@@ -50,7 +50,7 @@ const makeColumns = fields => {
Header: header,
accessor: accessor,
align: align,
hidden: false
hidden: false,
};
if (align === null) {
columnConfig.hidden = true;
@@ -68,22 +68,15 @@ const MonoField = ({ v, ...props }) => (
const Active = ({ isActive }) => {
const { colorMode } = useColorMode();
return (
<Icon
name={isActive ? "check-circle" : "warning"}
color={isActiveColor[isActive][colorMode]}
/>
<Icon name={isActive ? 'check-circle' : 'warning'} color={isActiveColor[isActive][colorMode]} />
);
};
const Age = ({ inSeconds }) => {
const now = dayjs.utc();
const then = now.subtract(inSeconds, "seconds");
const then = now.subtract(inSeconds, 'seconds');
return (
<Tooltip
hasArrow
label={then.toString().replace("GMT", "UTC")}
placement="right"
>
<Tooltip hasArrow label={then.toString().replace('GMT', 'UTC')} placement="right">
<Text fontSize="sm">{now.to(then, true)}</Text>
</Tooltip>
);
@@ -91,9 +84,7 @@ const Age = ({ inSeconds }) => {
const Weight = ({ weight, winningWeight }) => {
const fixMeText =
winningWeight === "low"
? "Lower Weight is Preferred"
: "Higher Weight is Preferred";
winningWeight === 'low' ? 'Lower Weight is Preferred' : 'Higher Weight is Preferred';
return (
<Tooltip hasArrow label={fixMeText} placement="right">
<Text fontSize="sm" fontFamily="mono">
@@ -113,22 +104,12 @@ const ASPath = ({ path, active }) => {
const asnStr = String(asn);
i !== 0 &&
paths.push(
<Icon
name="chevron-right"
key={`separator-${i}`}
color={arrowColor[active][colorMode]}
/>
<Icon name="chevron-right" key={`separator-${i}`} color={arrowColor[active][colorMode]} />,
);
paths.push(
<Text
fontSize="sm"
as="span"
whiteSpace="pre"
fontFamily="mono"
key={`as-${asnStr}-${i}`}
>
<Text fontSize="sm" as="span" whiteSpace="pre" fontFamily="mono" key={`as-${asnStr}-${i}`}>
{asnStr}
</Text>
</Text>,
);
});
return paths;
@@ -152,13 +133,12 @@ const Communities = ({ communities }) => {
textAlign="left"
p={4}
width="unset"
color={colorMode === "dark" ? "white" : "black"}
color={colorMode === 'dark' ? 'white' : 'black'}
fontFamily="mono"
fontWeight="normal"
whiteSpace="pre-wrap"
>
whiteSpace="pre-wrap">
<PopoverArrow />
{communities.join("\n")}
{communities.join('\n')}
</PopoverContent>
</Popover>
));
@@ -172,18 +152,11 @@ const RPKIState = ({ state, active }) => {
web.text.rpki_invalid,
web.text.rpki_valid,
web.text.rpki_unknown,
web.text.rpki_unverified
web.text.rpki_unverified,
];
return (
<Tooltip
hasArrow
placement="right"
label={stateText[state] ?? stateText[3]}
>
<Icon
name={rpkiIcon[state]}
color={rpkiColor[active][colorMode][state]}
/>
<Tooltip hasArrow placement="right" label={stateText[state] ?? stateText[3]}>
<Icon name={rpkiIcon[state]} color={rpkiColor[active][colorMode][state]} />
</Tooltip>
);
};
@@ -193,24 +166,16 @@ const Cell = ({ data, rawData, longestASN }) => {
prefix: <MonoField v={data.value} />,
active: <Active isActive={data.value} />,
age: <Age inSeconds={data.value} />,
weight: (
<Weight weight={data.value} winningWeight={rawData.winning_weight} />
),
weight: <Weight weight={data.value} winningWeight={rawData.winning_weight} />,
med: <MonoField v={data.value} />,
local_preference: <MonoField v={data.value} />,
as_path: (
<ASPath
path={data.value}
active={data.row.values.active}
longestASN={longestASN}
/>
),
as_path: <ASPath path={data.value} active={data.row.values.active} longestASN={longestASN} />,
communities: <Communities communities={data.value} />,
next_hop: <MonoField v={data.value} />,
source_as: <MonoField v={data.value} />,
source_rid: <MonoField v={data.value} />,
peer_rid: <MonoField v={data.value} />,
rpki_state: <RPKIState state={data.value} active={data.row.values.active} />
rpki_state: <RPKIState state={data.value} active={data.row.values.active} />,
};
return component[data.column.id] ?? <> </>;
};
@@ -220,7 +185,7 @@ export const BGPTable = ({ children: data, ...props }) => {
const columns = makeColumns(config.parsed_data_fields);
return (
<Flex my={8} maxW={["100%", "100%", "100%", "100%"]} w="100%" {...props}>
<Flex my={8} maxW={['100%', '100%', '100%', '100%']} w="100%" {...props}>
<Table
columns={columns}
data={data.routes}

View File

@@ -1,8 +1,8 @@
import * as React from "react";
import Countdown, { zeroPad } from "react-countdown";
import { Text, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import Countdown, { zeroPad } from 'react-countdown';
import { Text, useColorMode } from '@chakra-ui/core';
const bg = { dark: "white", light: "black" };
const bg = { dark: 'white', light: 'black' };
const Renderer = ({ hours, minutes, seconds, completed, props }) => {
if (completed) {
@@ -15,7 +15,7 @@ const Renderer = ({ hours, minutes, seconds, completed, props }) => {
<Text fontSize="xs" color="gray.500">
{props.text}
<Text as="span" fontSize="xs" color={bg[props.colorMode]}>
{time.join(":")}
{time.join(':')}
</Text>
</Text>
);

View File

@@ -1,8 +1,8 @@
import * as React from "react";
import { Flex, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Flex, useColorMode } from '@chakra-ui/core';
const bg = { light: "white", dark: "original.dark" };
const color = { light: "original.dark", dark: "white" };
const bg = { light: 'white', dark: 'original.dark' };
const color = { light: 'original.dark', dark: 'white' };
export const CardBody = ({ onClick = () => false, children, ...props }) => {
const { colorMode } = useColorMode();
@@ -17,8 +17,7 @@ export const CardBody = ({ onClick = () => false, children, ...props }) => {
bg={bg[colorMode]}
color={color[colorMode]}
overflow="hidden"
{...props}
>
{...props}>
{children}
</Flex>
);

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { Flex } from "@chakra-ui/core";
import * as React from 'react';
import { Flex } from '@chakra-ui/core';
export const CardFooter = ({ children, ...props }) => (
<Flex
@@ -12,8 +12,7 @@ export const CardFooter = ({ children, ...props }) => (
overflowY="hidden"
flexDirection="row"
justifyContent="space-between"
{...props}
>
{...props}>
{children}
</Flex>
);

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { Flex, Text, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Flex, Text, useColorMode } from '@chakra-ui/core';
const bg = { light: "blackAlpha.50", dark: "whiteAlpha.100" };
const bg = { light: 'blackAlpha.50', dark: 'whiteAlpha.100' };
export const CardHeader = ({ children, ...props }) => {
const { colorMode } = useColorMode();
@@ -13,8 +13,7 @@ export const CardHeader = ({ children, ...props }) => {
roundedTopLeft={4}
roundedTopRight={4}
borderBottomWidth="1px"
{...props}
>
{...props}>
<Text fontWeight="bold">{children}</Text>
</Flex>
);

View File

@@ -1,3 +1,3 @@
export * from "./CardBody";
export * from "./CardFooter";
export * from "./CardHeader";
export * from './CardBody';
export * from './CardFooter';
export * from './CardHeader';

View File

@@ -1,85 +1,76 @@
import * as React from "react";
import { Text, useColorMode, useTheme } from "@chakra-ui/core";
import Select from "react-select";
import { opposingColor } from "app/util";
import * as React from 'react';
import { Text, useColorMode, useTheme } from '@chakra-ui/core';
import Select from 'react-select';
import { opposingColor } from 'app/util';
export const ChakraSelect = React.forwardRef(
(
{ placeholder = "Select...", isFullWidth, size, children, ...props },
ref
) => {
({ placeholder = 'Select...', isFullWidth, size, children, ...props }, ref) => {
const theme = useTheme();
const { colorMode } = useColorMode();
const sizeMap = {
lg: { height: theme.space[12] },
md: { height: theme.space[10] },
sm: { height: theme.space[8] }
sm: { height: theme.space[8] },
};
const colorSetPrimaryBg = {
dark: theme.colors.primary[300],
light: theme.colors.primary[500]
light: theme.colors.primary[500],
};
const colorSetPrimaryColor = opposingColor(
theme,
colorSetPrimaryBg[colorMode]
);
const colorSetPrimaryColor = opposingColor(theme, colorSetPrimaryBg[colorMode]);
const bg = {
dark: theme.colors.whiteAlpha[100],
light: theme.colors.white
light: theme.colors.white,
};
const color = {
dark: theme.colors.whiteAlpha[800],
light: theme.colors.black
light: theme.colors.black,
};
const borderFocused = theme.colors.secondary[500];
const borderDisabled = theme.colors.whiteAlpha[100];
const border = {
dark: theme.colors.whiteAlpha[50],
light: theme.colors.gray[100]
light: theme.colors.gray[100],
};
const borderRadius = theme.space[1];
const hoverColor = {
dark: theme.colors.whiteAlpha[200],
light: theme.colors.gray[300]
light: theme.colors.gray[300],
};
const { height } = sizeMap[size];
const optionBgActive = {
dark: theme.colors.primary[400],
light: theme.colors.primary[600]
light: theme.colors.primary[600],
};
const optionBgColor = opposingColor(theme, optionBgActive[colorMode]);
const optionSelectedBg = {
dark: theme.colors.whiteAlpha[400],
light: theme.colors.blackAlpha[400]
light: theme.colors.blackAlpha[400],
};
const optionSelectedColor = opposingColor(
theme,
optionSelectedBg[colorMode]
);
const optionSelectedColor = opposingColor(theme, optionSelectedBg[colorMode]);
const selectedDisabled = theme.colors.whiteAlpha[400];
const placeholderColor = {
dark: theme.colors.whiteAlpha[700],
light: theme.colors.gray[600]
light: theme.colors.gray[600],
};
const menuBg = {
dark: theme.colors.blackFaded[800],
light: theme.colors.whiteFaded[50]
light: theme.colors.whiteFaded[50],
};
const menuColor = {
dark: theme.colors.white,
light: theme.colors.blackAlpha[800]
light: theme.colors.blackAlpha[800],
};
const scrollbar = {
dark: theme.colors.whiteAlpha[300],
light: theme.colors.blackAlpha[300]
light: theme.colors.blackAlpha[300],
};
const scrollbarHover = {
dark: theme.colors.whiteAlpha[400],
light: theme.colors.blackAlpha[400]
light: theme.colors.blackAlpha[400],
};
const scrollbarBg = {
dark: theme.colors.whiteAlpha[50],
light: theme.colors.blackAlpha[50]
light: theme.colors.blackAlpha[50],
};
return (
<Select
@@ -89,7 +80,7 @@ export const ChakraSelect = React.forwardRef(
...base,
minHeight: height,
borderRadius: borderRadius,
width: "100%"
width: '100%',
}),
control: (base, state) => ({
...base,
@@ -102,29 +93,29 @@ export const ChakraSelect = React.forwardRef(
? borderFocused
: border[colorMode],
borderRadius: borderRadius,
"&:hover": {
borderColor: hoverColor[colorMode]
}
'&:hover': {
borderColor: hoverColor[colorMode],
},
}),
menu: base => ({
...base,
backgroundColor: menuBg[colorMode],
borderRadius: borderRadius
borderRadius: borderRadius,
}),
menuList: base => ({
...base,
"&::-webkit-scrollbar": { width: "5px" },
"&::-webkit-scrollbar-track": {
backgroundColor: scrollbarBg[colorMode]
'&::-webkit-scrollbar': { width: '5px' },
'&::-webkit-scrollbar-track': {
backgroundColor: scrollbarBg[colorMode],
},
"&::-webkit-scrollbar-thumb": {
backgroundColor: scrollbar[colorMode]
'&::-webkit-scrollbar-thumb': {
backgroundColor: scrollbar[colorMode],
},
"&::-webkit-scrollbar-thumb:hover": {
backgroundColor: scrollbarHover[colorMode]
'&::-webkit-scrollbar-thumb:hover': {
backgroundColor: scrollbarHover[colorMode],
},
"-ms-overflow-style": { display: "none" }
'-ms-overflow-style': { display: 'none' },
}),
option: (base, state) => ({
...base,
@@ -134,7 +125,7 @@ export const ChakraSelect = React.forwardRef(
? optionSelectedBg[colorMode]
: state.isFocused
? colorSetPrimaryBg[colorMode]
: "transparent",
: 'transparent',
color: state.isDisabled
? selectedDisabled
: state.isFocused
@@ -143,62 +134,57 @@ export const ChakraSelect = React.forwardRef(
? optionSelectedColor
: menuColor[colorMode],
fontSize: theme.fontSizes[size],
"&:active": {
'&:active': {
backgroundColor: optionBgActive[colorMode],
color: optionBgColor
}
color: optionBgColor,
},
}),
indicatorSeparator: base => ({
...base,
backgroundColor: placeholderColor[colorMode]
backgroundColor: placeholderColor[colorMode],
}),
dropdownIndicator: base => ({
...base,
color: placeholderColor[colorMode],
"&:hover": {
color: color[colorMode]
}
'&:hover': {
color: color[colorMode],
},
}),
valueContainer: base => ({
...base,
paddingLeft: theme.space[4],
paddingRight: theme.space[4]
paddingRight: theme.space[4],
}),
multiValue: base => ({
...base,
backgroundColor: colorSetPrimaryBg[colorMode]
backgroundColor: colorSetPrimaryBg[colorMode],
}),
multiValueLabel: base => ({
...base,
color: colorSetPrimaryColor
color: colorSetPrimaryColor,
}),
multiValueRemove: base => ({
...base,
color: colorSetPrimaryColor,
"&:hover": {
'&:hover': {
color: colorSetPrimaryColor,
backgroundColor: "inherit"
}
backgroundColor: 'inherit',
},
}),
singleValue: base => ({
...base,
color: color[colorMode],
fontSize: theme.fontSizes[size]
})
fontSize: theme.fontSizes[size],
}),
}}
placeholder={
<Text
color={placeholderColor[colorMode]}
fontSize={size}
fontFamily={theme.fonts.body}
>
<Text color={placeholderColor[colorMode]} fontSize={size} fontFamily={theme.fonts.body}>
{placeholder}
</Text>
}
{...props}
>
{...props}>
{children}
</Select>
);
}
},
);

View File

@@ -1,10 +1,10 @@
import * as React from "react";
import { Box, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Box, useColorMode } from '@chakra-ui/core';
export const CodeBlock = ({ children }) => {
const { colorMode } = useColorMode();
const bg = { dark: "gray.800", light: "blackAlpha.100" };
const color = { dark: "white", light: "black" };
const bg = { dark: 'gray.800', light: 'blackAlpha.100' };
const color = { dark: 'white', light: 'black' };
return (
<Box
fontFamily="mono"
@@ -17,8 +17,7 @@ export const CodeBlock = ({ children }) => {
color={color[colorMode]}
fontSize="sm"
whiteSpace="pre-wrap"
as="pre"
>
as="pre">
{children}
</Box>
);

View File

@@ -1,43 +1,41 @@
import * as React from "react";
import { forwardRef } from "react";
import { Button, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { forwardRef } from 'react';
import { Button, useColorMode } from '@chakra-ui/core';
const Sun = ({ color, size = "1.5rem", ...props }) => (
const Sun = ({ color, size = '1.5rem', ...props }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
style={{
height: size,
width: size
width: size,
}}
strokeWidth={0}
stroke="currentColor"
fill="currentColor"
{...props}
>
{...props}>
<path
d="M256 32a224 224 0 00-161.393 69.035h323.045A224 224 0 00256 32zM79.148 118.965a224 224 0 00-16.976 25.16H449.74a224 224 0 00-16.699-25.16H79.148zm-27.222 45.16A224 224 0 0043.3 186.25h425.271a224 224 0 00-8.586-22.125H51.926zM36.783 210.25a224 224 0 00-3.02 19.125h444.368a224 224 0 00-3.113-19.125H36.783zm-4.752 45.125A224 224 0 0032 256a224 224 0 00.64 16.5h446.534A224 224 0 00480 256a224 224 0 00-.021-.625H32.03zm4.67 45.125a224 224 0 003.395 15.125h431.578a224 224 0 003.861-15.125H36.701zm14.307 45.125a224 224 0 006.017 13.125H454.82a224 224 0 006.342-13.125H51.008zm26.316 45.125a224 224 0 009.04 11.125H425.86a224 224 0 008.727-11.125H77.324zm45.62 45.125A224 224 0 00136.247 445h239.89a224 224 0 0012.936-9.125h-266.13z"
fill={color || "currentColor"}
fill={color || 'currentColor'}
/>
</svg>
);
const Moon = ({ color, size = "1.5rem", ...props }) => (
const Moon = ({ color, size = '1.5rem', ...props }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
style={{
height: size,
width: size
width: size,
}}
strokeWidth={0}
stroke="currentColor"
fill="currentColor"
{...props}
>
{...props}>
<path
d="M14.53 10.53a7 7 0 01-9.058-9.058A7.003 7.003 0 008 15a7.002 7.002 0 006.53-4.47z"
fill={color || "currentColor"}
fill={color || 'currentColor'}
fillRule="evenodd"
clipRule="evenodd"
/>
@@ -45,13 +43,13 @@ const Moon = ({ color, size = "1.5rem", ...props }) => (
);
const iconMap = { dark: Moon, light: Sun };
const outlineColor = { dark: "primary.300", light: "primary.600" };
const outlineColor = { dark: 'primary.300', light: 'primary.600' };
export const ColorModeToggle = forwardRef((props, ref) => {
const { colorMode, toggleColorMode } = useColorMode();
const Icon = iconMap[colorMode];
const label = `Switch to ${colorMode === "light" ? "dark" : "light"} mode`;
const label = `Switch to ${colorMode === 'light' ? 'dark' : 'light'} mode`;
return (
<Button
@@ -63,13 +61,12 @@ export const ColorModeToggle = forwardRef((props, ref) => {
borderWidth="1px"
borderColor="transparent"
_hover={{
backgroundColor: "unset",
borderColor: outlineColor[colorMode]
backgroundColor: 'unset',
borderColor: outlineColor[colorMode],
}}
color="current"
px={4}
{...props}
>
{...props}>
<Icon />
</Button>
);

View File

@@ -1,21 +1,15 @@
import * as React from "react";
import { useEffect } from "react";
import { Text } from "@chakra-ui/core";
import { components } from "react-select";
import { ChakraSelect } from "app/components";
import * as React from 'react';
import { useEffect } from 'react';
import { Text } from '@chakra-ui/core';
import { components } from 'react-select';
import { ChakraSelect } from 'app/components';
export const CommunitySelect = ({
name,
communities,
onChange,
register,
unregister
}) => {
export const CommunitySelect = ({ name, communities, onChange, register, unregister }) => {
const communitySelections = communities.map(c => {
return {
value: c.community,
label: c.display_name,
description: c.description
description: c.description,
};
});
const Option = ({ label, data, ...props }) => {
@@ -38,7 +32,7 @@ export const CommunitySelect = ({
size="lg"
name={name}
onChange={e => {
onChange({ field: name, value: e.value || "" });
onChange({ field: name, value: e.value || '' });
}}
options={communitySelections}
components={{ Option }}

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { Button, Icon, Tooltip, useClipboard } from "@chakra-ui/core";
import * as React from 'react';
import { Button, Icon, Tooltip, useClipboard } from '@chakra-ui/core';
export const CopyButton = ({ bg = "secondary", copyValue, ...props }) => {
export const CopyButton = ({ bg = 'secondary', copyValue, ...props }) => {
const { onCopy, hasCopied } = useClipboard(copyValue);
return (
<Tooltip hasArrow label="Copy Output" placement="top">
@@ -12,13 +12,8 @@ export const CopyButton = ({ bg = "secondary", copyValue, ...props }) => {
zIndex="dropdown"
onClick={onCopy}
mx={1}
{...props}
>
{hasCopied ? (
<Icon name="check" size="16px" />
) : (
<Icon name="copy" size="16px" />
)}
{...props}>
{hasCopied ? <Icon name="check" size="16px" /> : <Icon name="copy" size="16px" />}
</Button>
</Tooltip>
);

View File

@@ -1,4 +1,4 @@
import * as React from "react";
import * as React from 'react';
import {
Button,
Modal,
@@ -11,36 +11,28 @@ import {
Tag,
useDisclosure,
useColorMode,
useTheme
} from "@chakra-ui/core";
import { useConfig, useMedia } from "app/context";
import { CodeBlock } from "app/components";
useTheme,
} from '@chakra-ui/core';
import { useConfig, useMedia } from 'app/context';
import { CodeBlock } from 'app/components';
const prettyMediaSize = {
sm: "SMALL",
md: "MEDIUM",
lg: "LARGE",
xl: "X-LARGE"
sm: 'SMALL',
md: 'MEDIUM',
lg: 'LARGE',
xl: 'X-LARGE',
};
export const Debugger = () => {
const {
isOpen: configOpen,
onOpen: onConfigOpen,
onClose: configClose
} = useDisclosure();
const {
isOpen: themeOpen,
onOpen: onThemeOpen,
onClose: themeClose
} = useDisclosure();
const { isOpen: configOpen, onOpen: onConfigOpen, onClose: configClose } = useDisclosure();
const { isOpen: themeOpen, onOpen: onThemeOpen, onClose: themeClose } = useDisclosure();
const config = useConfig();
const theme = useTheme();
const bg = { light: "white", dark: "black" };
const color = { light: "black", dark: "white" };
const bg = { light: 'white', dark: 'black' };
const color = { light: 'black', dark: 'white' };
const { colorMode } = useColorMode();
const { mediaSize } = useMedia();
const borderColor = { light: "gray.100", dark: "gray.600" };
const borderColor = { light: 'gray.100', dark: 'gray.600' };
return (
<>
<Stack
@@ -55,8 +47,7 @@ export const Debugger = () => {
bottom={0}
justifyContent="center"
zIndex={1000}
maxW="100%"
>
maxW="100%">
<Tag variantColor="gray">{colorMode.toUpperCase()}</Tag>
<Tag variantColor="teal">{prettyMediaSize[mediaSize]}</Tag>
<Button size="sm" variantColor="cyan" onClick={onConfigOpen}>
@@ -73,8 +64,7 @@ export const Debugger = () => {
color={color[colorMode]}
py={4}
borderRadius="md"
maxW="90%"
>
maxW="90%">
<ModalHeader>Loaded Configuration</ModalHeader>
<ModalCloseButton />
<ModalBody>
@@ -89,8 +79,7 @@ export const Debugger = () => {
color={color[colorMode]}
py={4}
borderRadius="md"
maxW="90%"
>
maxW="90%">
<ModalHeader>Loaded Theme</ModalHeader>
<ModalCloseButton />
<ModalBody>

View File

@@ -1,18 +1,18 @@
import * as React from "react";
import { useState } from "react";
import { Flex, useColorMode } from "@chakra-ui/core";
import { FiCode } from "@meronex/icons/fi";
import { GoLinkExternal } from "@meronex/icons/go";
import format from "string-format";
import { useConfig } from "app/context";
import { FooterButton } from "./FooterButton";
import { FooterContent } from "./FooterContent";
import * as React from 'react';
import { useState } from 'react';
import { Flex, useColorMode } from '@chakra-ui/core';
import { FiCode } from '@meronex/icons/fi';
import { GoLinkExternal } from '@meronex/icons/go';
import format from 'string-format';
import { useConfig } from 'app/context';
import { FooterButton } from './FooterButton';
import { FooterContent } from './FooterContent';
format.extend(String.prototype, {});
const footerBg = { light: "blackAlpha.50", dark: "whiteAlpha.100" };
const footerColor = { light: "black", dark: "white" };
const contentBorder = { light: "blackAlpha.100", dark: "whiteAlpha.200" };
const footerBg = { light: 'blackAlpha.50', dark: 'whiteAlpha.100' };
const footerColor = { light: 'black', dark: 'white' };
const contentBorder = { light: 'blackAlpha.100', dark: 'whiteAlpha.200' };
export const Footer = () => {
const config = useConfig();
@@ -21,23 +21,23 @@ export const Footer = () => {
const [termsVisible, showTerms] = useState(false);
const [creditVisible, showCredit] = useState(false);
const handleCollapse = i => {
if (i === "help") {
if (i === 'help') {
showTerms(false);
showCredit(false);
showHelp(!helpVisible);
} else if (i === "credit") {
} else if (i === 'credit') {
showTerms(false);
showHelp(false);
showCredit(!creditVisible);
} else if (i === "terms") {
} else if (i === 'terms') {
showHelp(false);
showCredit(false);
showTerms(!termsVisible);
}
};
const extUrl = config.web.external_link.url.includes("{primary_asn}")
const extUrl = config.web.external_link.url.includes('{primary_asn}')
? config.web.external_link.url.format({ primary_asn: config.primary_asn })
: config.web.external_link.url || "/";
: config.web.external_link.url || '/';
return (
<>
{config.web.help_menu.enable && (
@@ -80,23 +80,20 @@ export const Footer = () => {
alignItems="center"
bg={footerBg[colorMode]}
color={footerColor[colorMode]}
justifyContent="space-between"
>
justifyContent="space-between">
{config.web.terms.enable && (
<FooterButton
side="left"
onClick={() => handleCollapse("terms")}
aria-label={config.web.terms.title}
>
onClick={() => handleCollapse('terms')}
aria-label={config.web.terms.title}>
{config.web.terms.title}
</FooterButton>
)}
{config.web.help_menu.enable && (
<FooterButton
side="left"
onClick={() => handleCollapse("help")}
aria-label={config.web.help_menu.title}
>
onClick={() => handleCollapse('help')}
aria-label={config.web.help_menu.title}>
{config.web.help_menu.title}
</FooterButton>
)}
@@ -111,9 +108,8 @@ export const Footer = () => {
{config.web.credit.enable && (
<FooterButton
side="right"
onClick={() => handleCollapse("credit")}
aria-label="Powered by hyperglass"
>
onClick={() => handleCollapse('credit')}
aria-label="Powered by hyperglass">
<FiCode />
</FooterButton>
)}
@@ -126,8 +122,7 @@ export const Footer = () => {
rel="noopener noreferrer"
variant="ghost"
rightIcon={GoLinkExternal}
size="xs"
>
size="xs">
{config.web.external_link.title}
</FooterButton>
)}

View File

@@ -1,29 +1,26 @@
import * as React from "react";
import { Button, Flex } from "@chakra-ui/core";
import { motion } from "framer-motion";
import * as React from 'react';
import { Button, Flex } from '@chakra-ui/core';
import { motion } from 'framer-motion';
const AnimatedFlex = motion.custom(Flex);
export const FooterButton = React.forwardRef(
({ onClick, side, children, ...props }, ref) => {
return (
<AnimatedFlex
p={0}
w="auto"
ref={ref}
flexGrow={0}
float={side}
flexShrink={0}
maxWidth="100%"
flexBasis="auto"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.6 }}
>
<Button size="xs" variant="ghost" onClick={onClick} {...props}>
{children}
</Button>
</AnimatedFlex>
);
}
);
export const FooterButton = React.forwardRef(({ onClick, side, children, ...props }, ref) => {
return (
<AnimatedFlex
p={0}
w="auto"
ref={ref}
flexGrow={0}
float={side}
flexShrink={0}
maxWidth="100%"
flexBasis="auto"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.6 }}>
<Button size="xs" variant="ghost" onClick={onClick} {...props}>
{children}
</Button>
</AnimatedFlex>
);
});

View File

@@ -1,10 +1,10 @@
import * as React from "react";
import { forwardRef } from "react";
import { Box, Collapse } from "@chakra-ui/core";
import { Markdown } from "app/components/Markdown";
import * as React from 'react';
import { forwardRef } from 'react';
import { Box, Collapse } from '@chakra-ui/core';
import { Markdown } from 'app/components/Markdown';
export const FooterContent = forwardRef(
({ isOpen = false, content, side = "left", title, ...props }, ref) => {
({ isOpen = false, content, side = 'left', title, ...props }, ref) => {
return (
<Collapse
px={6}
@@ -16,13 +16,12 @@ export const FooterContent = forwardRef(
maxWidth="100%"
isOpen={isOpen}
flexBasis="auto"
justifyContent={side === "left" ? "flex-start" : "flex-end"}
{...props}
>
justifyContent={side === 'left' ? 'flex-start' : 'flex-end'}
{...props}>
<Box textAlign={side}>
<Markdown content={content} />
</Box>
</Collapse>
);
}
},
);

View File

@@ -1 +1 @@
export * from "./Footer";
export * from './Footer';

View File

@@ -1,13 +1,7 @@
import * as React from "react";
import {
Flex,
FormControl,
FormLabel,
FormErrorMessage,
useColorMode
} from "@chakra-ui/core";
import * as React from 'react';
import { Flex, FormControl, FormLabel, FormErrorMessage, useColorMode } from '@chakra-ui/core';
const labelColor = { dark: "whiteAlpha.700", light: "blackAlpha.700" };
const labelColor = { dark: 'whiteAlpha.700', light: 'blackAlpha.700' };
export const FormField = ({
label,
@@ -28,14 +22,13 @@ export const FormField = ({
<FormControl
as={Flex}
flexDirection="column"
flex={["1 0 100%", "1 0 100%", "1 0 33.33%", "1 0 33.33%"]}
flex={['1 0 100%', '1 0 100%', '1 0 33.33%', '1 0 33.33%']}
w="100%"
maxW="100%"
mx={2}
my={[2, 2, 4, 4]}
isInvalid={error && error.message}
{...props}
>
{...props}>
<FormLabel
htmlFor={name}
color={labelColor[colorMode]}
@@ -44,8 +37,7 @@ export const FormField = ({
display="flex"
alignItems="center"
justifyContent="space-between"
pr={0}
>
pr={0}>
{label}
{labelAddOn || null}
</FormLabel>

View File

@@ -1,4 +1,4 @@
import * as React from "react";
import * as React from 'react';
import {
Button,
Modal,
@@ -9,13 +9,13 @@ import {
ModalBody,
ModalCloseButton,
useColorMode,
useDisclosure
} from "@chakra-ui/core";
import { Markdown } from "app/components";
import { motion } from "framer-motion";
useDisclosure,
} from '@chakra-ui/core';
import { Markdown } from 'app/components';
import { motion } from 'framer-motion';
const bg = { light: "white", dark: "black" };
const color = { light: "black", dark: "white" };
const bg = { light: 'white', dark: 'black' };
const color = { light: 'black', dark: 'white' };
const AnimatedModalContent = motion.custom(ModalContent);
const AnimatedModalOverlay = motion.custom(ModalOverlay);
@@ -36,8 +36,7 @@ export const Greeting = ({ greetingConfig, content, onClickThrough }) => {
size="full"
isCentered
closeOnOverlayClick={!greetingConfig.required}
closeOnEsc={!greetingConfig.required}
>
closeOnEsc={!greetingConfig.required}>
<AnimatedModalOverlay
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -51,8 +50,7 @@ export const Greeting = ({ greetingConfig, content, onClickThrough }) => {
color={color[colorMode]}
py={4}
borderRadius="md"
maxW={["95%", "75%", "75%", "75%"]}
>
maxW={['95%', '75%', '75%', '75%']}>
<ModalHeader>{greetingConfig.title}</ModalHeader>
{!greetingConfig.required && <ModalCloseButton />}
<ModalBody>

View File

@@ -1,54 +1,54 @@
import * as React from "react";
import { Flex, useColorMode } from "@chakra-ui/core";
import { motion, AnimatePresence } from "framer-motion";
import { useConfig, useHyperglassState, useMedia } from "app/context";
import { Title, ResetButton, ColorModeToggle } from "app/components";
import * as React from 'react';
import { Flex, useColorMode } from '@chakra-ui/core';
import { motion, AnimatePresence } from 'framer-motion';
import { useConfig, useHyperglassState, useMedia } from 'app/context';
import { Title, ResetButton, ColorModeToggle } from 'app/components';
const titleVariants = {
sm: {
fullSize: { scale: 1, marginLeft: 0 },
smallLogo: { marginLeft: "auto" },
smallText: { marginLeft: "auto" }
smallLogo: { marginLeft: 'auto' },
smallText: { marginLeft: 'auto' },
},
md: {
fullSize: { scale: 1 },
smallLogo: { scale: 0.5 },
smallText: { scale: 0.8 }
smallText: { scale: 0.8 },
},
lg: {
fullSize: { scale: 1 },
smallLogo: { scale: 0.5 },
smallText: { scale: 0.8 }
smallText: { scale: 0.8 },
},
xl: {
fullSize: { scale: 1 },
smallLogo: { scale: 0.5 },
smallText: { scale: 0.8 }
}
smallText: { scale: 0.8 },
},
};
const bg = { light: "white", dark: "black" };
const bg = { light: 'white', dark: 'black' };
const headerTransition = {
type: "spring",
ease: "anticipate",
type: 'spring',
ease: 'anticipate',
damping: 15,
stiffness: 100
stiffness: 100,
};
const titleJustify = {
true: ["flex-end", "flex-end", "center", "center"],
false: ["flex-start", "flex-start", "center", "center"]
true: ['flex-end', 'flex-end', 'center', 'center'],
false: ['flex-start', 'flex-start', 'center', 'center'],
};
const titleHeight = {
true: null,
false: [null, "20vh", "20vh", "20vh"]
false: [null, '20vh', '20vh', '20vh'],
};
const resetButtonMl = { true: [null, 2, 2, 2], false: null };
const widthMap = {
text_only: "100%",
logo_only: ["90%", "90%", "50%", "50%"],
logo_subtitle: ["90%", "90%", "50%", "50%"],
all: ["90%", "90%", "50%", "50%"]
text_only: '100%',
logo_only: ['90%', '90%', '50%', '50%'],
logo_subtitle: ['90%', '90%', '50%', '50%'],
all: ['90%', '90%', '50%', '50%'],
};
export const Header = ({ layoutRef, ...props }) => {
@@ -66,17 +66,13 @@ export const Header = ({ layoutRef, ...props }) => {
<AnimatedFlex
layoutTransition={headerTransition}
initial={{ opacity: 0, x: -50 }}
animate={{ opacity: 1, x: 0, width: "unset" }}
animate={{ opacity: 1, x: 0, width: 'unset' }}
exit={{ opacity: 0, x: -50 }}
alignItems="center"
mb={[null, "auto"]}
mb={[null, 'auto']}
ml={resetButtonMl[isSubmitting]}
display={isSubmitting ? "flex" : "none"}
>
<AnimatedResetButton
isSubmitting={isSubmitting}
onClick={handleFormReset}
/>
display={isSubmitting ? 'flex' : 'none'}>
<AnimatedResetButton isSubmitting={isSubmitting} onClick={handleFormReset} />
</AnimatedFlex>
</AnimatePresence>
);
@@ -84,25 +80,22 @@ export const Header = ({ layoutRef, ...props }) => {
<AnimatedFlex
key="title"
px={1}
alignItems={
isSubmitting ? "center" : ["center", "center", "flex-end", "flex-end"]
}
alignItems={isSubmitting ? 'center' : ['center', 'center', 'flex-end', 'flex-end']}
positionTransition={headerTransition}
initial={{ scale: 0.5 }}
animate={
isSubmitting && web.text.title_mode === "text_only"
? "smallText"
: isSubmitting && web.text.title_mode !== "text_only"
? "smallLogo"
: "fullSize"
isSubmitting && web.text.title_mode === 'text_only'
? 'smallText'
: isSubmitting && web.text.title_mode !== 'text_only'
? 'smallLogo'
: 'fullSize'
}
variants={titleVariants[mediaSize]}
justifyContent={titleJustify[isSubmitting]}
mt={[null, isSubmitting ? null : "auto"]}
mt={[null, isSubmitting ? null : 'auto']}
maxW={widthMap[web.text.title_mode]}
flex="1 0 0"
minH={titleHeight[isSubmitting]}
>
minH={titleHeight[isSubmitting]}>
<Title isSubmitting={isSubmitting} onClick={handleFormReset} />
</AnimatedFlex>
);
@@ -113,9 +106,8 @@ export const Header = ({ layoutRef, ...props }) => {
alignItems="center"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
mb={[null, "auto"]}
mr={isSubmitting ? null : 2}
>
mb={[null, 'auto']}
mr={isSubmitting ? null : 2}>
<ColorModeToggle />
</AnimatedFlex>
);
@@ -124,14 +116,14 @@ export const Header = ({ layoutRef, ...props }) => {
sm: [title, resetButton, colorModeToggle],
md: [resetButton, title, colorModeToggle],
lg: [resetButton, title, colorModeToggle],
xl: [resetButton, title, colorModeToggle]
xl: [resetButton, title, colorModeToggle],
},
true: {
sm: [resetButton, colorModeToggle, title],
md: [resetButton, title, colorModeToggle],
lg: [resetButton, title, colorModeToggle],
xl: [resetButton, title, colorModeToggle]
}
xl: [resetButton, title, colorModeToggle],
},
};
return (
<Flex
@@ -142,16 +134,14 @@ export const Header = ({ layoutRef, ...props }) => {
flex="0 1 auto"
bg={bg[colorMode]}
color="gray.500"
{...props}
>
{...props}>
<Flex
w="100%"
mx="auto"
pt={6}
justify="space-between"
flex="1 0 auto"
alignItems={isSubmitting ? "center" : "flex-start"}
>
alignItems={isSubmitting ? 'center' : 'flex-start'}>
{layout[isSubmitting][mediaSize]}
</Flex>
</Flex>

View File

@@ -1,4 +1,4 @@
import * as React from "react";
import * as React from 'react';
import {
IconButton,
Modal,
@@ -9,10 +9,10 @@ import {
ModalCloseButton,
useDisclosure,
useColorMode,
useTheme
} from "@chakra-ui/core";
import { motion, AnimatePresence } from "framer-motion";
import { Markdown } from "app/components";
useTheme,
} from '@chakra-ui/core';
import { motion, AnimatePresence } from 'framer-motion';
import { Markdown } from 'app/components';
const AnimatedIcon = motion.custom(IconButton);
@@ -20,11 +20,11 @@ export const HelpModal = ({ item, name }) => {
const { isOpen, onOpen, onClose } = useDisclosure();
const { colors } = useTheme();
const { colorMode } = useColorMode();
const bg = { light: "whiteFaded.50", dark: "blackFaded.800" };
const color = { light: "black", dark: "white" };
const bg = { light: 'whiteFaded.50', dark: 'blackFaded.800' };
const color = { light: 'black', dark: 'white' };
const iconColor = {
light: colors.primary[500],
dark: colors.primary[300]
dark: colors.primary[300],
};
return (
<>
@@ -53,12 +53,7 @@ export const HelpModal = ({ item, name }) => {
</AnimatePresence>
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalOverlay />
<ModalContent
bg={bg[colorMode]}
color={color[colorMode]}
py={4}
borderRadius="md"
>
<ModalContent bg={bg[colorMode]} color={color[colorMode]} py={4} borderRadius="md">
<ModalHeader>{item.params.title}</ModalHeader>
<ModalCloseButton />
<ModalBody>

View File

@@ -1,10 +1,10 @@
import * as React from "react";
import { forwardRef, useState, useEffect } from "react";
import { Box, Flex } from "@chakra-ui/core";
import { useForm } from "react-hook-form";
import { intersectionWith, isEqual } from "lodash";
import * as yup from "yup";
import format from "string-format";
import * as React from 'react';
import { forwardRef, useState, useEffect } from 'react';
import { Box, Flex } from '@chakra-ui/core';
import { useForm } from 'react-hook-form';
import { intersectionWith, isEqual } from 'lodash';
import * as yup from 'yup';
import format from 'string-format';
import {
FormField,
HelpModal,
@@ -14,9 +14,9 @@ import {
CommunitySelect,
QueryVrf,
ResolvedTarget,
SubmitButton
} from "app/components";
import { useConfig } from "app/context";
SubmitButton,
} from 'app/components';
import { useConfig } from 'app/context';
format.extend(String.prototype, {});
@@ -27,20 +27,16 @@ const formSchema = config =>
.of(yup.string())
.required(
config.messages.no_input.format({
field: config.web.text.query_location
})
field: config.web.text.query_location,
}),
),
query_type: yup
.string()
.required(
config.messages.no_input.format({ field: config.web.text.query_type })
),
.required(config.messages.no_input.format({ field: config.web.text.query_type })),
query_vrf: yup.string(),
query_target: yup
.string()
.required(
config.messages.no_input.format({ field: config.web.text.query_target })
)
.required(config.messages.no_input.format({ field: config.web.text.query_target })),
});
const FormRow = ({ children, ...props }) => (
@@ -48,38 +44,27 @@ const FormRow = ({ children, ...props }) => (
flexDirection="row"
flexWrap="wrap"
w="100%"
justifyContent={["center", "center", "space-between", "space-between"]}
{...props}
>
justifyContent={['center', 'center', 'space-between', 'space-between']}
{...props}>
{children}
</Flex>
);
export const HyperglassForm = forwardRef(
(
{
isSubmitting,
setSubmitting,
setFormData,
greetingAck,
setGreetingAck,
...props
},
ref
) => {
({ isSubmitting, setSubmitting, setFormData, greetingAck, setGreetingAck, ...props }, ref) => {
const config = useConfig();
const { handleSubmit, register, unregister, setValue, errors } = useForm({
validationSchema: formSchema(config),
defaultValues: { query_vrf: "default", query_target: "" }
defaultValues: { query_vrf: 'default', query_target: '' },
});
const [queryLocation, setQueryLocation] = useState([]);
const [queryType, setQueryType] = useState("");
const [queryVrf, setQueryVrf] = useState("");
const [queryTarget, setQueryTarget] = useState("");
const [queryType, setQueryType] = useState('');
const [queryVrf, setQueryVrf] = useState('');
const [queryTarget, setQueryTarget] = useState('');
const [availVrfs, setAvailVrfs] = useState([]);
const [fqdnTarget, setFqdnTarget] = useState("");
const [displayTarget, setDisplayTarget] = useState("");
const [fqdnTarget, setFqdnTarget] = useState('');
const [displayTarget, setDisplayTarget] = useState('');
const [families, setFamilies] = useState([]);
const onSubmit = values => {
if (!greetingAck && config.web.greeting.required) {
@@ -100,7 +85,7 @@ export const HyperglassForm = forwardRef(
config.devices[loc].vrfs.map(vrf => {
locVrfs.push({
label: vrf.display_name,
value: vrf.id
value: vrf.id,
});
deviceVrfs.push([{ id: vrf.id, ipv4: vrf.ipv4, ipv6: vrf.ipv6 }]);
});
@@ -109,9 +94,7 @@ export const HyperglassForm = forwardRef(
const intersecting = intersectionWith(...allVrfs, isEqual);
setAvailVrfs(intersecting);
!intersecting.includes(queryVrf) &&
queryVrf !== "default" &&
setQueryVrf("default");
!intersecting.includes(queryVrf) && queryVrf !== 'default' && setQueryVrf('default');
let ipv4 = 0;
let ipv6 = 0;
@@ -120,7 +103,7 @@ export const HyperglassForm = forwardRef(
deviceVrfs
.filter(v => intersecting.every(i => i.id === v.id))
.reduce((a, b) => a.concat(b))
.filter(v => v.id === "default")
.filter(v => v.id === 'default')
.map(v => {
v.ipv4 === true && ipv4++;
v.ipv6 === true && ipv6++;
@@ -138,13 +121,13 @@ export const HyperglassForm = forwardRef(
const handleChange = e => {
setValue(e.field, e.value);
e.field === "query_location"
e.field === 'query_location'
? handleLocChange(e)
: e.field === "query_type"
: e.field === 'query_type'
? setQueryType(e.value)
: e.field === "query_vrf"
: e.field === 'query_vrf'
? setQueryVrf(e.value)
: e.field === "query_target"
: e.field === 'query_target'
? setQueryTarget(e.value)
: null;
};
@@ -152,37 +135,35 @@ export const HyperglassForm = forwardRef(
const vrfContent = config.content.vrf[queryVrf]?.[queryType];
const validFqdnQueryType =
["ping", "traceroute", "bgp_route"].includes(queryType) &&
['ping', 'traceroute', 'bgp_route'].includes(queryType) &&
fqdnTarget &&
queryVrf === "default"
queryVrf === 'default'
? fqdnTarget
: null;
useEffect(() => {
register({ name: "query_location" });
register({ name: "query_type" });
register({ name: "query_vrf" });
register({ name: 'query_location' });
register({ name: 'query_type' });
register({ name: 'query_vrf' });
}, [register]);
Object.keys(errors).length >= 1 && console.error(errors);
return (
<Box
as="form"
onSubmit={handleSubmit(onSubmit)}
maxW={["100%", "100%", "75%", "75%"]}
maxW={['100%', '100%', '75%', '75%']}
w="100%"
p={0}
mx="auto"
my={4}
textAlign="left"
ref={ref}
{...props}
>
{...props}>
<FormRow>
<FormField
label={config.web.text.query_location}
name="query_location"
error={errors.query_location}
>
error={errors.query_location}>
<QueryLocation
onChange={handleChange}
locations={config.networks}
@@ -193,10 +174,7 @@ export const HyperglassForm = forwardRef(
label={config.web.text.query_type}
name="query_type"
error={errors.query_type}
labelAddOn={
vrfContent && <HelpModal item={vrfContent} name="query_type" />
}
>
labelAddOn={vrfContent && <HelpModal item={vrfContent} name="query_type" />}>
<QueryType
onChange={handleChange}
queryTypes={config.queries.list}
@@ -206,11 +184,7 @@ export const HyperglassForm = forwardRef(
</FormRow>
<FormRow>
{availVrfs.length > 1 && (
<FormField
label={config.web.text.query_vrf}
name="query_vrf"
error={errors.query_vrf}
>
<FormField label={config.web.text.query_vrf} name="query_vrf" error={errors.query_vrf}>
<QueryVrf
label={config.web.text.query_vrf}
vrfs={availVrfs}
@@ -233,10 +207,8 @@ export const HyperglassForm = forwardRef(
availVrfs={availVrfs}
/>
)
}
>
{queryType === "bgp_community" &&
config.queries.bgp_community.mode === "select" ? (
}>
{queryType === 'bgp_community' && config.queries.bgp_community.mode === 'select' ? (
<CommunitySelect
label={config.queries.bgp_community.display_name}
name="query_target"
@@ -251,9 +223,7 @@ export const HyperglassForm = forwardRef(
placeholder={config.web.text.query_target}
register={register}
unregister={unregister}
resolveTarget={["ping", "traceroute", "bgp_route"].includes(
queryType
)}
resolveTarget={['ping', 'traceroute', 'bgp_route'].includes(queryType)}
value={queryTarget}
setFqdn={setFqdnTarget}
setTarget={handleChange}
@@ -271,12 +241,11 @@ export const HyperglassForm = forwardRef(
my={2}
mr={[0, 0, 2, 2]}
flexDirection="column"
flex="0 0 0"
>
flex="0 0 0">
<SubmitButton isLoading={isSubmitting} />
</Flex>
</FormRow>
</Box>
);
}
},
);

View File

@@ -1,11 +1,11 @@
import * as React from "react";
import { forwardRef } from "react";
import { Flex, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { forwardRef } from 'react';
import { Flex, useColorMode } from '@chakra-ui/core';
export const Label = forwardRef(
({ value, label, labelColor, valueBg, valueColor, ...props }, ref) => {
const { colorMode } = useColorMode();
const _labelColor = { dark: "whiteAlpha.700", light: "blackAlpha.700" };
const _labelColor = { dark: 'whiteAlpha.700', light: 'blackAlpha.700' };
return (
<Flex
ref={ref}
@@ -14,8 +14,7 @@ export const Label = forwardRef(
justifyContent="flex-start"
mx={[1, 2, 2, 2]}
my={2}
{...props}
>
{...props}>
<Flex
display="inline-flex"
justifyContent="center"
@@ -24,15 +23,14 @@ export const Label = forwardRef(
whiteSpace="nowrap"
mb={2}
mr={0}
bg={valueBg || "primary.600"}
color={valueColor || "white"}
bg={valueBg || 'primary.600'}
color={valueColor || 'white'}
borderBottomLeftRadius={4}
borderTopLeftRadius={4}
borderBottomRightRadius={0}
borderTopRightRadius={0}
fontWeight="bold"
fontSize={["xs", "sm", "sm", "sm"]}
>
fontSize={['xs', 'sm', 'sm', 'sm']}>
{value}
</Flex>
<Flex
@@ -44,17 +42,16 @@ export const Label = forwardRef(
mb={2}
ml={0}
mr={0}
boxShadow={`inset 0px 0px 0px 1px ${valueBg || "primary.600"}`}
boxShadow={`inset 0px 0px 0px 1px ${valueBg || 'primary.600'}`}
color={labelColor || _labelColor[colorMode]}
borderBottomRightRadius={4}
borderTopRightRadius={4}
borderBottomLeftRadius={0}
borderTopLeftRadius={0}
fontSize={["xs", "sm", "sm", "sm"]}
>
fontSize={['xs', 'sm', 'sm', 'sm']}>
{label}
</Flex>
</Flex>
);
}
},
);

View File

@@ -1,11 +1,11 @@
import * as React from "react";
import { useRef } from "react";
import { Flex, useColorMode } from "@chakra-ui/core";
import { useConfig, useHyperglassState } from "app/context";
import { Debugger, Greeting, Footer, Header } from "app/components";
import * as React from 'react';
import { useRef } from 'react';
import { Flex, useColorMode } from '@chakra-ui/core';
import { useConfig, useHyperglassState } from 'app/context';
import { Debugger, Greeting, Footer, Header } from 'app/components';
const bg = { light: "white", dark: "black" };
const color = { light: "black", dark: "white" };
const bg = { light: 'white', dark: 'black' };
const color = { light: 'black', dark: 'white' };
export const Layout = ({ children }) => {
const config = useConfig();
@@ -21,8 +21,7 @@ export const Layout = ({ children }) => {
minHeight="100vh"
bg={bg[colorMode]}
flexDirection="column"
color={color[colorMode]}
>
color={color[colorMode]}>
<Flex px={2} flex="0 1 auto" flexDirection="column">
<Header layoutRef={containerRef} />
</Flex>
@@ -35,8 +34,7 @@ export const Layout = ({ children }) => {
textAlign="center"
alignItems="center"
justifyContent="start"
flexDirection="column"
>
flexDirection="column">
{children}
</Flex>
<Footer />

View File

@@ -1,18 +1,17 @@
import * as React from "react";
import { Flex, Spinner, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Flex, Spinner, useColorMode } from '@chakra-ui/core';
export const Loading = () => {
const { colorMode } = useColorMode();
const bg = { light: "white", dark: "black" };
const color = { light: "black", dark: "white" };
const bg = { light: 'white', dark: 'black' };
const color = { light: 'black', dark: 'white' };
return (
<Flex
flexDirection="column"
minHeight="100vh"
w="100%"
bg={bg[colorMode]}
color={color[colorMode]}
>
color={color[colorMode]}>
<Flex
as="main"
w="100%"
@@ -25,8 +24,7 @@ export const Loading = () => {
flexDirection="column"
px={2}
py={0}
mt={["50%", "50%", "50%", "25%"]}
>
mt={['50%', '50%', '50%', '25%']}>
<Spinner color="primary.500" w="6rem" h="6rem" />
</Flex>
</Flex>

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Layout, HyperglassForm, Results } from "app/components";
import { useHyperglassState } from "app/context";
import * as React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Layout, HyperglassForm, Results } from 'app/components';
import { useHyperglassState } from 'app/context';
const AnimatedForm = motion.custom(HyperglassForm);
@@ -12,7 +12,7 @@ export const LookingGlass = () => {
formData,
setFormData,
greetingAck,
setGreetingAck
setGreetingAck,
} = useHyperglassState();
return (

View File

@@ -1,4 +1,4 @@
import * as React from "react";
import * as React from 'react';
import {
Checkbox as ChakraCheckbox,
Divider as ChakraDivider,
@@ -7,19 +7,19 @@ import {
Link as ChakraLink,
List as ChakraList,
ListItem as ChakraListItem,
Text as ChakraText
} from "@chakra-ui/core";
Text as ChakraText,
} from '@chakra-ui/core';
import { TableCell, TableHeader, Table as ChakraTable } from "./MDTable";
import { TableCell, TableHeader, Table as ChakraTable } from './MDTable';
import { CodeBlock as CustomCodeBlock } from "app/components";
import { CodeBlock as CustomCodeBlock } from 'app/components';
export const Checkbox = ({ checked, children }) => (
<ChakraCheckbox isChecked={checked}>{children}</ChakraCheckbox>
);
export const List = ({ ordered, children }) => (
<ChakraList as={ordered ? "ol" : "ul"}>{children}</ChakraList>
<ChakraList as={ordered ? 'ol' : 'ul'}>{children}</ChakraList>
);
export const ListItem = ({ checked, children }) =>
@@ -31,12 +31,12 @@ export const ListItem = ({ checked, children }) =>
export const Heading = ({ level, children }) => {
const levelMap = {
1: { as: "h1", size: "lg", fontWeight: "bold" },
2: { as: "h2", size: "lg", fontWeight: "normal" },
3: { as: "h3", size: "lg", fontWeight: "bold" },
4: { as: "h4", size: "md", fontWeight: "normal" },
5: { as: "h5", size: "md", fontWeight: "bold" },
6: { as: "h6", size: "sm", fontWeight: "bold" }
1: { as: 'h1', size: 'lg', fontWeight: 'bold' },
2: { as: 'h2', size: 'lg', fontWeight: 'normal' },
3: { as: 'h3', size: 'lg', fontWeight: 'bold' },
4: { as: 'h4', size: 'md', fontWeight: 'normal' },
5: { as: 'h5', size: 'md', fontWeight: 'bold' },
6: { as: 'h6', size: 'sm', fontWeight: 'bold' },
};
return <ChakraHeading {...levelMap[level]}>{children}</ChakraHeading>;
};
@@ -47,9 +47,7 @@ export const Link = ({ children, ...props }) => (
</ChakraLink>
);
export const CodeBlock = ({ value }) => (
<CustomCodeBlock>{value}</CustomCodeBlock>
);
export const CodeBlock = ({ value }) => <CustomCodeBlock>{value}</CustomCodeBlock>;
export const TableData = ({ isHeader, children, ...props }) => {
const Component = isHeader ? TableHeader : TableCell;

View File

@@ -1,30 +1,19 @@
import * as React from "react";
import { Box, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Box, useColorMode } from '@chakra-ui/core';
export const Table = props => (
<Box as="table" textAlign="left" mt={4} width="full" {...props} />
);
export const Table = props => <Box as="table" textAlign="left" mt={4} width="full" {...props} />;
const bg = { light: "blackAlpha.50", dark: "whiteAlpha.50" };
const bg = { light: 'blackAlpha.50', dark: 'whiteAlpha.50' };
export const TableHeader = props => {
const { colorMode } = useColorMode();
return (
<Box
as="th"
bg={bg[colorMode]}
fontWeight="semibold"
p={2}
fontSize="sm"
{...props}
/>
);
return <Box as="th" bg={bg[colorMode]} fontWeight="semibold" p={2} fontSize="sm" {...props} />;
};
export const TableCell = ({ isHeader = false, ...props }) => (
<Box
as={isHeader ? "th" : "td"}
as={isHeader ? 'th' : 'td'}
p={2}
borderTopWidth="1px"
borderColor="inherit"

View File

@@ -1,6 +1,6 @@
import * as React from "react";
import { forwardRef } from "react";
import ReactMarkdown from "react-markdown";
import * as React from 'react';
import { forwardRef } from 'react';
import ReactMarkdown from 'react-markdown';
import {
List,
ListItem,
@@ -11,8 +11,8 @@ import {
Paragraph,
InlineCode,
Divider,
Table
} from "./MDComponents";
Table,
} from './MDComponents';
const mdComponents = {
paragraph: Paragraph,
@@ -24,7 +24,7 @@ const mdComponents = {
thematicBreak: Divider,
code: CodeBlock,
table: Table,
tableCell: TableData
tableCell: TableData,
};
export const Markdown = forwardRef(({ content }, ref) => (

View File

@@ -1 +1 @@
export * from "./Markdown";
export * from './Markdown';

View File

@@ -1,38 +1,38 @@
import * as React from "react";
import { useEffect, useState } from "react";
import Head from "next/head";
import { useTheme } from "@chakra-ui/core";
import { useConfig } from "app/context";
import { googleFontUrl } from "app/util";
import * as React from 'react';
import { useEffect, useState } from 'react';
import Head from 'next/head';
import { useTheme } from '@chakra-ui/core';
import { useConfig } from 'app/context';
import { googleFontUrl } from 'app/util';
export const Meta = () => {
const config = useConfig();
const theme = useTheme();
const [location, setLocation] = useState({});
const title = config?.site_title || "hyperglass";
const description = config?.site_description || "Network Looking Glass";
const title = config?.site_title || 'hyperglass';
const description = config?.site_description || 'Network Looking Glass';
const siteName = `${title} - ${description}`;
const keywords = config?.site_keywords || [
"hyperglass",
"looking glass",
"lg",
"peer",
"peering",
"ipv4",
"ipv6",
"transit",
"community",
"communities",
"bgp",
"routing",
"network",
"isp"
'hyperglass',
'looking glass',
'lg',
'peer',
'peering',
'ipv4',
'ipv6',
'transit',
'community',
'communities',
'bgp',
'routing',
'network',
'isp',
];
const language = config?.language ?? "en";
const language = config?.language ?? 'en';
const primaryFont = googleFontUrl(theme.fonts.body);
const monoFont = googleFontUrl(theme.fonts.mono);
useEffect(() => {
if (typeof window !== "undefined" && location === {}) {
if (typeof window !== 'undefined' && location === {}) {
setLocation(window.location);
}
}, [location]);
@@ -41,7 +41,7 @@ export const Meta = () => {
<title>{title}</title>
<meta name="hg-version" content={config.hyperglass_version} />
<meta name="description" content={description} />
<meta name="keywords" content={keywords.join(", ")} />
<meta name="keywords" content={keywords.join(', ')} />
<meta name="language" content={language} />
<meta name="url" content={location.href} />
<meta name="og:title" content={title} />

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { ChakraSelect } from "app/components";
import * as React from 'react';
import { ChakraSelect } from 'app/components';
const buildLocations = networks => {
const locations = [];
@@ -9,7 +9,7 @@ const buildLocations = networks => {
netLocations.push({
label: loc.display_name,
value: loc.name,
group: net.display_name
group: net.display_name,
});
});
locations.push({ label: net.display_name, options: netLocations });
@@ -25,7 +25,7 @@ export const QueryLocation = ({ locations, onChange, label }) => {
e.map(sel => {
selected.push(sel.value);
});
onChange({ field: "query_location", value: selected });
onChange({ field: 'query_location', value: selected });
};
return (
<ChakraSelect

View File

@@ -1,13 +1,13 @@
import * as React from "react";
import { useEffect } from "react";
import { Input, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { useEffect } from 'react';
import { Input, useColorMode } from '@chakra-ui/core';
const fqdnPattern = /^(?!:\/\/)([a-zA-Z0-9-]+\.)?[a-zA-Z0-9-][a-zA-Z0-9-]+\.[a-zA-Z-]{2,6}?$/gim;
const bg = { dark: "whiteAlpha.100", light: "white" };
const color = { dark: "whiteAlpha.800", light: "gray.400" };
const border = { dark: "whiteAlpha.50", light: "gray.100" };
const placeholderColor = { dark: "whiteAlpha.700", light: "gray.600" };
const bg = { dark: 'whiteAlpha.100', light: 'white' };
const color = { dark: 'whiteAlpha.800', light: 'gray.400' };
const border = { dark: 'whiteAlpha.50', light: 'gray.100' };
const placeholderColor = { dark: 'whiteAlpha.700', light: 'gray.600' };
export const QueryTarget = ({
placeholder,
@@ -19,7 +19,7 @@ export const QueryTarget = ({
setTarget,
resolveTarget,
displayValue,
setDisplayValue
setDisplayValue,
}) => {
const { colorMode } = useColorMode();
@@ -61,7 +61,7 @@ export const QueryTarget = ({
placeholder={placeholder}
borderColor={border[colorMode]}
_placeholder={{
color: placeholderColor[colorMode]
color: placeholderColor[colorMode],
}}
/>
</>

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { ChakraSelect } from "app/components";
import * as React from 'react';
import { ChakraSelect } from 'app/components';
export const QueryType = ({ queryTypes, onChange, label }) => {
const queries = queryTypes
@@ -11,7 +11,7 @@ export const QueryType = ({ queryTypes, onChange, label }) => {
<ChakraSelect
size="lg"
name="query_type"
onChange={e => onChange({ field: "query_type", value: e.value })}
onChange={e => onChange({ field: 'query_type', value: e.value })}
options={queries}
aria-label={label}
/>

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { ChakraSelect } from "app/components";
import * as React from 'react';
import { ChakraSelect } from 'app/components';
export const QueryVrf = ({ vrfs, onChange, label }) => (
<ChakraSelect
@@ -7,6 +7,6 @@ export const QueryVrf = ({ vrfs, onChange, label }) => (
options={vrfs}
name="query_vrf"
aria-label={label}
onChange={e => onChange({ field: "query_vrf", value: e.value })}
onChange={e => onChange({ field: 'query_vrf', value: e.value })}
/>
);

View File

@@ -1,17 +1,9 @@
import * as React from "react";
import { Button, Icon, Tooltip } from "@chakra-ui/core";
import * as React from 'react';
import { Button, Icon, Tooltip } from '@chakra-ui/core';
export const RequeryButton = ({ requery, bg = "secondary", ...props }) => (
export const RequeryButton = ({ requery, bg = 'secondary', ...props }) => (
<Tooltip hasArrow label="Reload Query" placement="top">
<Button
mx={1}
as="a"
size="sm"
zIndex="1"
variantColor={bg}
onClick={requery}
{...props}
>
<Button mx={1} as="a" size="sm" zIndex="1" variantColor={bg} onClick={requery} {...props}>
<Icon size="16px" name="repeat" />
</Button>
</Tooltip>

View File

@@ -1,18 +1,15 @@
import * as React from "react";
import { Button } from "@chakra-ui/core";
import { FiChevronLeft } from "@meronex/icons/fi";
import * as React from 'react';
import { Button } from '@chakra-ui/core';
import { FiChevronLeft } from '@meronex/icons/fi';
export const ResetButton = React.forwardRef(
({ isSubmitting, onClick }, ref) => (
<Button
ref={ref}
color="current"
variant="ghost"
onClick={onClick}
aria-label="Reset Form"
opacity={isSubmitting ? 1 : 0}
>
<FiChevronLeft size={24} />
</Button>
)
);
export const ResetButton = React.forwardRef(({ isSubmitting, onClick }, ref) => (
<Button
ref={ref}
color="current"
variant="ghost"
onClick={onClick}
aria-label="Reset Form"
opacity={isSubmitting ? 1 : 0}>
<FiChevronLeft size={24} />
</Button>
));

View File

@@ -1,23 +1,14 @@
import * as React from "react";
import { forwardRef, useEffect } from "react";
import {
Button,
Icon,
Spinner,
Stack,
Tag,
Text,
Tooltip,
useColorMode
} from "@chakra-ui/core";
import useAxios from "axios-hooks";
import format from "string-format";
import { useConfig } from "app/context";
import * as React from 'react';
import { forwardRef, useEffect } from 'react';
import { Button, Icon, Spinner, Stack, Tag, Text, Tooltip, useColorMode } from '@chakra-ui/core';
import useAxios from 'axios-hooks';
import format from 'string-format';
import { useConfig } from 'app/context';
format.extend(String.prototype, {});
const labelBg = { dark: "secondary", light: "secondary" };
const labelBgSuccess = { dark: "success", light: "success" };
const labelBg = { dark: 'secondary', light: 'secondary' };
const labelBgSuccess = { dark: 'success', light: 'success' };
export const ResolvedTarget = forwardRef(
({ fqdnTarget, setTarget, queryTarget, families, availVrfs }, ref) => {
@@ -25,7 +16,7 @@ export const ResolvedTarget = forwardRef(
const config = useConfig();
const labelBgStatus = {
true: labelBgSuccess[colorMode],
false: labelBg[colorMode]
false: labelBg[colorMode],
};
const dnsUrl = config.web.dns_provider.url;
const query4 = families.includes(4);
@@ -33,30 +24,26 @@ export const ResolvedTarget = forwardRef(
const params = {
4: {
url: dnsUrl,
params: { name: fqdnTarget, type: "A" },
headers: { accept: "application/dns-json" },
params: { name: fqdnTarget, type: 'A' },
headers: { accept: 'application/dns-json' },
crossdomain: true,
timeout: 1000
timeout: 1000,
},
6: {
url: dnsUrl,
params: { name: fqdnTarget, type: "AAAA" },
headers: { accept: "application/dns-json" },
params: { name: fqdnTarget, type: 'AAAA' },
headers: { accept: 'application/dns-json' },
crossdomain: true,
timeout: 1000
}
timeout: 1000,
},
};
const [{ data: data4, loading: loading4, error: error4 }] = useAxios(
params[4]
);
const [{ data: data4, loading: loading4, error: error4 }] = useAxios(params[4]);
const [{ data: data6, loading: loading6, error: error6 }] = useAxios(
params[6]
);
const [{ data: data6, loading: loading6, error: error6 }] = useAxios(params[6]);
const handleOverride = overridden => {
setTarget({ field: "query_target", value: overridden });
setTarget({ field: 'query_target', value: overridden });
};
const isSelected = value => {
@@ -64,9 +51,8 @@ export const ResolvedTarget = forwardRef(
};
const findAnswer = data => {
return data?.Answer?.filter(
answerData => answerData.type === data?.Question[0]?.type
)[0]?.data;
return data?.Answer?.filter(answerData => answerData.type === data?.Question[0]?.type)[0]
?.data;
};
useEffect(() => {
@@ -84,16 +70,11 @@ export const ResolvedTarget = forwardRef(
isInline
w="100%"
justifyContent={
query4 &&
data4?.Answer &&
query6 &&
data6?.Answer &&
availVrfs.length > 1
? "space-between"
: "flex-end"
query4 && data4?.Answer && query6 && data6?.Answer && availVrfs.length > 1
? 'space-between'
: 'flex-end'
}
flexWrap="wrap"
>
flexWrap="wrap">
{loading4 ||
error4 ||
(query4 && findAnswer(data4) && (
@@ -101,10 +82,9 @@ export const ResolvedTarget = forwardRef(
<Tooltip
hasArrow
label={config.web.text.fqdn_tooltip.format({
protocol: "IPv4"
protocol: 'IPv4',
})}
placement="bottom"
>
placement="bottom">
<Button
height="unset"
minW="unset"
@@ -112,24 +92,16 @@ export const ResolvedTarget = forwardRef(
py="0.1rem"
px={2}
mr={2}
variantColor={
labelBgStatus[findAnswer(data4) === queryTarget]
}
variantColor={labelBgStatus[findAnswer(data4) === queryTarget]}
borderRadius="md"
onClick={() => handleOverride(findAnswer(data4))}
>
onClick={() => handleOverride(findAnswer(data4))}>
IPv4
</Button>
</Tooltip>
{loading4 && <Spinner />}
{error4 && <Icon name="warning" />}
{findAnswer(data4) && (
<Text
fontSize="xs"
fontFamily="mono"
as="span"
fontWeight={400}
>
<Text fontSize="xs" fontFamily="mono" as="span" fontWeight={400}>
{findAnswer(data4)}
</Text>
)}
@@ -142,10 +114,9 @@ export const ResolvedTarget = forwardRef(
<Tooltip
hasArrow
label={config.web.text.fqdn_tooltip.format({
protocol: "IPv6"
protocol: 'IPv6',
})}
placement="bottom"
>
placement="bottom">
<Button
height="unset"
minW="unset"
@@ -155,20 +126,14 @@ export const ResolvedTarget = forwardRef(
mr={2}
variantColor={isSelected(findAnswer(data6))}
borderRadius="md"
onClick={() => handleOverride(findAnswer(data6))}
>
onClick={() => handleOverride(findAnswer(data6))}>
IPv6
</Button>
</Tooltip>
{loading6 && <Spinner />}
{error6 && <Icon name="warning" />}
{findAnswer(data6) && (
<Text
fontSize="xs"
fontFamily="mono"
as="span"
fontWeight={400}
>
<Text fontSize="xs" fontFamily="mono" as="span" fontWeight={400}>
{findAnswer(data6)}
</Text>
)}
@@ -176,5 +141,5 @@ export const ResolvedTarget = forwardRef(
))}
</Stack>
);
}
},
);

View File

@@ -1,6 +1,6 @@
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { forwardRef, useEffect, useState } from "react";
import { jsx } from '@emotion/core';
import { forwardRef, useEffect, useState } from 'react';
import {
AccordionItem,
AccordionHeader,
@@ -13,30 +13,30 @@ import {
Tooltip,
Text,
useColorMode,
useTheme
} from "@chakra-ui/core";
import { BsLightningFill } from "@meronex/icons/bs";
import styled from "@emotion/styled";
import useAxios from "axios-hooks";
import strReplace from "react-string-replace";
import format from "string-format";
import { startCase } from "lodash";
import { useConfig, useMedia } from "app/context";
useTheme,
} from '@chakra-ui/core';
import { BsLightningFill } from '@meronex/icons/bs';
import styled from '@emotion/styled';
import useAxios from 'axios-hooks';
import strReplace from 'react-string-replace';
import format from 'string-format';
import { startCase } from 'lodash';
import { useConfig, useMedia } from 'app/context';
import {
BGPTable,
CacheTimeout,
CopyButton,
RequeryButton,
ResultHeader,
TextOutput
} from "app/components";
import { tableToString } from "app/util";
TextOutput,
} from 'app/components';
import { tableToString } from 'app/util';
format.extend(String.prototype, {});
const FormattedError = ({ keywords, message }) => {
const patternStr = keywords.map(kw => `(${kw})`).join("|");
const pattern = new RegExp(patternStr, "gi");
const patternStr = keywords.map(kw => `(${kw})`).join('|');
const pattern = new RegExp(patternStr, 'gi');
let errorFmt;
try {
errorFmt = strReplace(message, pattern, match => (
@@ -56,21 +56,21 @@ const AccordionHeaderWrapper = styled(Flex)`
background-color: ${props => props.hoverBg};
}
&:focus {
box-shadow: "outline";
box-shadow: 'outline';
}
`;
const statusMap = {
success: "success",
warning: "warning",
error: "warning",
danger: "error"
success: 'success',
warning: 'warning',
error: 'warning',
danger: 'error',
};
const color = { dark: "white", light: "black" };
const scrollbar = { dark: "whiteAlpha.300", light: "blackAlpha.300" };
const scrollbarHover = { dark: "whiteAlpha.400", light: "blackAlpha.400" };
const scrollbarBg = { dark: "whiteAlpha.50", light: "blackAlpha.50" };
const color = { dark: 'white', light: 'black' };
const scrollbar = { dark: 'whiteAlpha.300', light: 'blackAlpha.300' };
const scrollbarHover = { dark: 'whiteAlpha.400', light: 'blackAlpha.400' };
const scrollbarBg = { dark: 'whiteAlpha.50', light: 'blackAlpha.50' };
export const Result = forwardRef(
(
@@ -83,25 +83,25 @@ export const Result = forwardRef(
queryTarget,
index,
resultsComplete,
setComplete
setComplete,
},
ref
ref,
) => {
const config = useConfig();
const theme = useTheme();
const { isSm } = useMedia();
const { colorMode } = useColorMode();
let [{ data, loading, error }, refetch] = useAxios({
url: "/api/query/",
method: "post",
url: '/api/query/',
method: 'post',
data: {
query_location: queryLocation,
query_type: queryType,
query_vrf: queryVrf,
query_target: queryTarget
query_target: queryTarget,
},
timeout: timeout,
useCache: false
useCache: false,
});
const [isOpen, setOpen] = useState(false);
@@ -117,7 +117,7 @@ export const Result = forwardRef(
let errorMsg;
if (error && error.response?.data?.output) {
errorMsg = error.response.data.output;
} else if (error && error.message.startsWith("timeout")) {
} else if (error && error.message.startsWith('timeout')) {
errorMsg = config.messages.request_timeout;
} else if (error?.response?.statusText) {
errorMsg = startCase(error.response.statusText);
@@ -130,22 +130,20 @@ export const Result = forwardRef(
error && console.error(error);
const errorLevel =
(error?.response?.data?.level &&
statusMap[error.response?.data?.level]) ??
"error";
(error?.response?.data?.level && statusMap[error.response?.data?.level]) ?? 'error';
const structuredDataComponent = {
bgp_route: BGPTable,
bgp_aspath: BGPTable,
bgp_community: BGPTable,
ping: TextOutput,
traceroute: TextOutput
traceroute: TextOutput,
};
let Output = TextOutput;
let copyValue = data?.output;
if (data?.format === "application/json") {
if (data?.format === 'application/json') {
Output = structuredDataComponent[queryType];
copyValue = tableToString(queryTarget, data, config);
}
@@ -168,10 +166,9 @@ export const Result = forwardRef(
isDisabled={loading}
ref={ref}
css={css({
"&:last-of-type": { borderBottom: "none" },
"&:first-of-type": { borderTop: "none" }
})(theme)}
>
'&:last-of-type': { borderBottom: 'none' },
'&:first-of-type': { borderTop: 'none' },
})(theme)}>
<AccordionHeaderWrapper hoverBg="blackAlpha.50">
<AccordionHeader
flex="1 0 auto"
@@ -179,8 +176,7 @@ export const Result = forwardRef(
_hover={{}}
_focus={{}}
w="unset"
onClick={handleToggle}
>
onClick={handleToggle}>
<ResultHeader
title={device.display_name}
loading={loading}
@@ -191,43 +187,30 @@ export const Result = forwardRef(
/>
</AccordionHeader>
<ButtonGroup px={[1, 1, 3, 3]} py={2}>
<CopyButton
copyValue={copyValue}
variant="ghost"
isDisabled={loading}
/>
<RequeryButton
requery={refetch}
variant="ghost"
isDisabled={loading}
/>
<CopyButton copyValue={copyValue} variant="ghost" isDisabled={loading} />
<RequeryButton requery={refetch} variant="ghost" isDisabled={loading} />
</ButtonGroup>
</AccordionHeaderWrapper>
<AccordionPanel
pb={4}
overflowX="auto"
css={css({
WebkitOverflowScrolling: "touch",
"&::-webkit-scrollbar": { height: "5px" },
"&::-webkit-scrollbar-track": {
backgroundColor: scrollbarBg[colorMode]
WebkitOverflowScrolling: 'touch',
'&::-webkit-scrollbar': { height: '5px' },
'&::-webkit-scrollbar-track': {
backgroundColor: scrollbarBg[colorMode],
},
"&::-webkit-scrollbar-thumb": {
backgroundColor: scrollbar[colorMode]
'&::-webkit-scrollbar-thumb': {
backgroundColor: scrollbar[colorMode],
},
"&::-webkit-scrollbar-thumb:hover": {
backgroundColor: scrollbarHover[colorMode]
'&::-webkit-scrollbar-thumb:hover': {
backgroundColor: scrollbarHover[colorMode],
},
"-ms-overflow-style": { display: "none" }
})(theme)}
>
'-ms-overflow-style': { display: 'none' },
})(theme)}>
<Flex direction="column" flexWrap="wrap">
<Flex
direction="column"
flex="1 0 auto"
maxW={error ? "100%" : null}
>
<Flex direction="column" flex="1 0 auto" maxW={error ? '100%' : null}>
{!error && data && <Output>{data?.output}</Output>}
{error && (
<Alert rounded="lg" my={2} py={4} status={errorLevel}>
@@ -241,14 +224,8 @@ export const Result = forwardRef(
<Flex
px={3}
mt={2}
justifyContent={[
"flex-start",
"flex-start",
"flex-end",
"flex-end"
]}
flex="1 0 auto"
>
justifyContent={['flex-start', 'flex-start', 'flex-end', 'flex-end']}
flex="1 0 auto">
{config.cache.show_text && data && !error && (
<>
{!isSm && (
@@ -258,14 +235,13 @@ export const Result = forwardRef(
/>
)}
<Tooltip
display={data?.cached ? null : "none"}
display={data?.cached ? null : 'none'}
hasArrow
label={config.web.text.cache_icon.format({
time: data?.timestamp
time: data?.timestamp,
})}
placement="top"
>
<Box ml={1} display={data?.cached ? "block" : "none"}>
placement="top">
<Box ml={1} display={data?.cached ? 'block' : 'none'}>
<BsLightningFill color={color[colorMode]} />
</Box>
</Tooltip>
@@ -282,5 +258,5 @@ export const Result = forwardRef(
</AccordionPanel>
</AccordionItem>
);
}
},
);

View File

@@ -1,35 +1,27 @@
import * as React from "react";
import { forwardRef } from "react";
import {
AccordionIcon,
Icon,
Spinner,
Stack,
Text,
Tooltip,
useColorMode
} from "@chakra-ui/core";
import format from "string-format";
import { useConfig } from "app/context";
import * as React from 'react';
import { forwardRef } from 'react';
import { AccordionIcon, Icon, Spinner, Stack, Text, Tooltip, useColorMode } from '@chakra-ui/core';
import format from 'string-format';
import { useConfig } from 'app/context';
format.extend(String.prototype, {});
const runtimeText = (runtime, text) => {
let unit;
if (runtime === 1) {
unit = "second";
unit = 'second';
} else {
unit = "seconds";
unit = 'seconds';
}
const fmt = text.format({ seconds: runtime });
return `${fmt} ${unit}`;
};
const statusColor = { dark: "primary.300", light: "primary.500" };
const statusColor = { dark: 'primary.300', light: 'primary.500' };
const warningColor = { dark: 300, light: 500 };
const defaultStatusColor = {
dark: "success.300",
light: "success.500"
dark: 'success.300',
light: 'success.500',
};
export const ResultHeader = forwardRef(
@@ -53,19 +45,13 @@ export const ResultHeader = forwardRef(
<Tooltip
hasArrow
label={runtimeText(runtime, config.web.text.complete_time)}
placement="top"
>
<Icon
name="check"
color={defaultStatusColor[colorMode]}
mr={4}
size={6}
/>
placement="top">
<Icon name="check" color={defaultStatusColor[colorMode]} mr={4} size={6} />
</Tooltip>
)}
<Text fontSize="lg">{title}</Text>
<AccordionIcon ml="auto" />
</Stack>
);
}
},
);

View File

@@ -1,9 +1,9 @@
import * as React from "react";
import { useState } from "react";
import { Accordion, Box, Stack, useTheme } from "@chakra-ui/core";
import { motion, AnimatePresence } from "framer-motion";
import { Label, Result } from "app/components";
import { useConfig, useMedia } from "app/context";
import * as React from 'react';
import { useState } from 'react';
import { Accordion, Box, Stack, useTheme } from '@chakra-ui/core';
import { motion, AnimatePresence } from 'framer-motion';
import { Label, Result } from 'app/components';
import { useConfig, useMedia } from 'app/context';
const AnimatedResult = motion.custom(Result);
const AnimatedLabel = motion.custom(Label);
@@ -13,40 +13,40 @@ const labelInitial = {
sm: { opacity: 0, x: -100 },
md: { opacity: 0, x: -100 },
lg: { opacity: 0, x: -100 },
xl: { opacity: 0, x: -100 }
xl: { opacity: 0, x: -100 },
},
center: {
sm: { opacity: 0 },
md: { opacity: 0 },
lg: { opacity: 0 },
xl: { opacity: 0 }
xl: { opacity: 0 },
},
right: {
sm: { opacity: 0, x: 100 },
md: { opacity: 0, x: 100 },
lg: { opacity: 0, x: 100 },
xl: { opacity: 0, x: 100 }
}
xl: { opacity: 0, x: 100 },
},
};
const labelAnimate = {
left: {
sm: { opacity: 1, x: 0 },
md: { opacity: 1, x: 0 },
lg: { opacity: 1, x: 0 },
xl: { opacity: 1, x: 0 }
xl: { opacity: 1, x: 0 },
},
center: {
sm: { opacity: 1 },
md: { opacity: 1 },
lg: { opacity: 1 },
xl: { opacity: 1 }
xl: { opacity: 1 },
},
right: {
sm: { opacity: 1, x: 0 },
md: { opacity: 1, x: 0 },
lg: { opacity: 1, x: 0 },
xl: { opacity: 1, x: 0 }
}
xl: { opacity: 1, x: 0 },
},
};
export const Results = ({
@@ -61,20 +61,18 @@ export const Results = ({
const theme = useTheme();
const { mediaSize } = useMedia();
const matchedVrf =
config.vrfs.filter(v => v.id === queryVrf)[0] ??
config.vrfs.filter(v => v.id === "default")[0];
config.vrfs.filter(v => v.id === queryVrf)[0] ?? config.vrfs.filter(v => v.id === 'default')[0];
const [resultsComplete, setComplete] = useState(null);
return (
<>
<Box
maxW={["100%", "100%", "75%", "50%"]}
maxW={['100%', '100%', '75%', '50%']}
w="100%"
p={0}
mx="auto"
my={4}
textAlign="left"
{...props}
>
{...props}>
<Stack isInline align="center" justify="center" mt={4} flexWrap="wrap">
<AnimatePresence>
{queryLocation && (
@@ -87,7 +85,7 @@ export const Results = ({
label={config.web.text.query_type}
value={config.queries[queryType].display_name}
valueBg={theme.colors.cyan[500]}
fontSize={["xs", "sm", "sm", "sm"]}
fontSize={['xs', 'sm', 'sm', 'sm']}
/>
<AnimatedLabel
initial={labelInitial.center[mediaSize]}
@@ -97,7 +95,7 @@ export const Results = ({
label={config.web.text.query_target}
value={queryTarget}
valueBg={theme.colors.teal[600]}
fontSize={["xs", "sm", "sm", "sm"]}
fontSize={['xs', 'sm', 'sm', 'sm']}
/>
<AnimatedLabel
initial={labelInitial.right[mediaSize]}
@@ -107,7 +105,7 @@ export const Results = ({
label={config.web.text.query_vrf}
value={matchedVrf.display_name}
valueBg={theme.colors.blue[500]}
fontSize={["xs", "sm", "sm", "sm"]}
fontSize={['xs', 'sm', 'sm', 'sm']}
/>
</>
)}
@@ -115,7 +113,7 @@ export const Results = ({
</Stack>
</Box>
<Box
maxW={["100%", "100%", "75%", "75%"]}
maxW={['100%', '100%', '75%', '75%']}
w="100%"
p={0}
mx="auto"
@@ -123,15 +121,13 @@ export const Results = ({
textAlign="left"
borderWidth="1px"
rounded="lg"
overflow="hidden"
>
overflow="hidden">
<Accordion
allowMultiple
initial={{ opacity: 1 }}
transition={{ duration: 0.3 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 300 }}
>
exit={{ opacity: 0, y: 300 }}>
<AnimatePresence>
{queryLocation &&
queryLocation.map((loc, i) => (

View File

@@ -1,63 +1,57 @@
import * as React from "react";
import { forwardRef } from "react";
import {
Box,
PseudoBox,
Spinner,
useColorMode,
useTheme
} from "@chakra-ui/core";
import { FiSearch } from "@meronex/icons/fi";
import { opposingColor } from "app/util";
import * as React from 'react';
import { forwardRef } from 'react';
import { Box, PseudoBox, Spinner, useColorMode, useTheme } from '@chakra-ui/core';
import { FiSearch } from '@meronex/icons/fi';
import { opposingColor } from 'app/util';
const btnProps = {
display: "inline-flex",
appearance: "none",
alignItems: "center",
justifyContent: "center",
transition: "all 250ms",
userSelect: "none",
position: "relative",
whiteSpace: "nowrap",
verticalAlign: "middle",
lineHeight: "1.2",
outline: "none",
as: "button",
type: "submit",
borderRadius: "md",
fontWeight: "semibold"
display: 'inline-flex',
appearance: 'none',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 250ms',
userSelect: 'none',
position: 'relative',
whiteSpace: 'nowrap',
verticalAlign: 'middle',
lineHeight: '1.2',
outline: 'none',
as: 'button',
type: 'submit',
borderRadius: 'md',
fontWeight: 'semibold',
};
const btnSizeMap = {
lg: {
height: 12,
minWidth: 12,
fontSize: "lg",
px: 6
fontSize: 'lg',
px: 6,
},
md: {
height: 10,
minWidth: 10,
fontSize: "md",
px: 4
fontSize: 'md',
px: 4,
},
sm: {
height: 8,
minWidth: 8,
fontSize: "sm",
px: 3
fontSize: 'sm',
px: 3,
},
xs: {
height: 6,
minWidth: 6,
fontSize: "xs",
px: 2
}
fontSize: 'xs',
px: 2,
},
};
const btnBg = { dark: "primary.300", light: "primary.500" };
const btnBgActive = { dark: "primary.400", light: "primary.600" };
const btnBgHover = { dark: "primary.200", light: "primary.400" };
const btnBg = { dark: 'primary.300', light: 'primary.500' };
const btnBgActive = { dark: 'primary.400', light: 'primary.600' };
const btnBgHover = { dark: 'primary.200', light: 'primary.400' };
export const SubmitButton = forwardRef(
(
@@ -66,12 +60,12 @@ export const SubmitButton = forwardRef(
isDisabled = false,
isActive = false,
isFullWidth = false,
size = "lg",
size = 'lg',
loadingText,
children,
...props
},
ref
ref,
) => {
const _isDisabled = isDisabled || isLoading;
const { colorMode } = useColorMode();
@@ -86,8 +80,8 @@ export const SubmitButton = forwardRef(
disabled={_isDisabled}
aria-disabled={_isDisabled}
aria-label="Submit Query"
width={isFullWidth ? "full" : undefined}
data-active={isActive ? "true" : undefined}
width={isFullWidth ? 'full' : undefined}
data-active={isActive ? 'true' : undefined}
bg={btnBg[colorMode]}
color={btnColor}
_active={{ bg: btnBgActive[colorMode], color: btnColorActive }}
@@ -95,11 +89,10 @@ export const SubmitButton = forwardRef(
_focus={{ boxShadow: theme.shadows.outline }}
{...btnProps}
{...btnSize}
{...props}
>
{...props}>
{isLoading ? (
<Spinner
position={loadingText ? "relative" : "absolute"}
position={loadingText ? 'relative' : 'absolute'}
mr={loadingText ? 2 : 0}
color="currentColor"
size="1em"
@@ -116,5 +109,5 @@ export const SubmitButton = forwardRef(
: children}
</PseudoBox>
);
}
},
);

View File

@@ -1,16 +1,16 @@
import * as React from "react";
import { useMemo } from "react";
import { Flex, Icon, Text } from "@chakra-ui/core";
import { usePagination, useSortBy, useTable } from "react-table";
import { useMedia } from "app/context";
import { CardBody, CardFooter, CardHeader } from "app/components";
import { TableMain } from "./TableMain";
import { TableCell } from "./TableCell";
import { TableHead } from "./TableHead";
import { TableRow } from "./TableRow";
import { TableBody } from "./TableBody";
import { TableIconButton } from "./TableIconButton";
import { TableSelectShow } from "./TableSelectShow";
import * as React from 'react';
import { useMemo } from 'react';
import { Flex, Icon, Text } from '@chakra-ui/core';
import { usePagination, useSortBy, useTable } from 'react-table';
import { useMedia } from 'app/context';
import { CardBody, CardFooter, CardHeader } from 'app/components';
import { TableMain } from './TableMain';
import { TableCell } from './TableCell';
import { TableHead } from './TableHead';
import { TableRow } from './TableRow';
import { TableBody } from './TableBody';
import { TableIconButton } from './TableIconButton';
import { TableSelectShow } from './TableSelectShow';
export const Table = ({
columns,
@@ -24,7 +24,7 @@ export const Table = ({
cellRender = null,
rowHighlightProp,
rowHighlightBg,
rowHighlightColor
rowHighlightColor,
}) => {
const tableColumns = useMemo(() => columns, [columns]);
@@ -34,9 +34,9 @@ export const Table = ({
() => ({
minWidth: 100,
width: 150,
maxWidth: 300
maxWidth: 300,
}),
[]
[],
);
let hiddenColumns = [];
@@ -60,7 +60,7 @@ export const Table = ({
nextPage,
previousPage,
setPageSize,
state: { pageIndex, pageSize }
state: { pageIndex, pageSize },
} = useTable(
{
columns: tableColumns,
@@ -69,11 +69,11 @@ export const Table = ({
initialState: {
pageIndex: 0,
pageSize: initialPageSize,
hiddenColumns: hiddenColumns
}
hiddenColumns: hiddenColumns,
},
},
useSortBy,
usePagination
usePagination,
);
return (
@@ -82,20 +82,16 @@ export const Table = ({
<TableMain {...getTableProps()}>
<TableHead>
{headerGroups.map(headerGroup => (
<TableRow
key={headerGroup.id}
{...headerGroup.getHeaderGroupProps()}
>
<TableRow key={headerGroup.id} {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableCell
as="th"
align={column.align}
key={column.id}
{...column.getHeaderProps()}
{...column.getSortByToggleProps()}
>
{...column.getSortByToggleProps()}>
<Text fontSize="sm" fontWeight="bold" display="inline-block">
{column.render("Header")}
{column.render('Header')}
</Text>
{column.isSorted ? (
column.isSortedDesc ? (
@@ -104,7 +100,7 @@ export const Table = ({
<Icon name="chevron-up" size={4} ml={1} />
)
) : (
""
''
)}
</TableCell>
))}
@@ -124,8 +120,7 @@ export const Table = ({
highlight={row.values[rowHighlightProp] ?? false}
highlightBg={rowHighlightBg}
highlightColor={rowHighlightColor}
{...row.getRowProps()}
>
{...row.getRowProps()}>
{row.cells.map((cell, i) => {
return (
<TableCell
@@ -133,14 +128,13 @@ export const Table = ({
cell={cell}
bordersVertical={[bordersVertical, i]}
key={cell.row.index}
{...cell.getCellProps()}
>
{cell.render(cellRender ?? "Cell")}
{...cell.getCellProps()}>
{cell.render(cellRender ?? 'Cell')}
</TableCell>
);
})}
</TableRow>
)
),
)}
</TableBody>
</TableMain>
@@ -161,10 +155,10 @@ export const Table = ({
</Flex>
<Flex justifyContent="center" alignItems="center">
<Text fontSize="sm" mr={4} whiteSpace="nowrap">
Page{" "}
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{" "}
</strong>{' '}
</Text>
{!(isSm || isMd) && (
<TableSelectShow

View File

@@ -1,18 +1,17 @@
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { Box, css } from "@chakra-ui/core";
import { jsx } from '@emotion/core';
import { Box, css } from '@chakra-ui/core';
export const TableBody = ({ children, ...props }) => (
<Box
as="tbody"
overflowY="scroll"
css={css({
"&::-webkit-scrollbar": { display: "none" },
"&": { msOverflowStyle: "none" }
'&::-webkit-scrollbar': { display: 'none' },
'&': { msOverflowStyle: 'none' },
})}
overflowX="hidden"
{...props}
>
{...props}>
{children}
</Box>
);

View File

@@ -1,18 +1,12 @@
import * as React from "react";
import { Box, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Box, useColorMode } from '@chakra-ui/core';
const cellBorder = {
dark: { borderLeft: "1px", borderLeftColor: "whiteAlpha.100" },
light: { borderLeft: "1px", borderLeftColor: "blackAlpha.100" }
dark: { borderLeft: '1px', borderLeftColor: 'whiteAlpha.100' },
light: { borderLeft: '1px', borderLeftColor: 'blackAlpha.100' },
};
export const TableCell = ({
bordersVertical = [false, 0, 0],
align,
cell,
children,
...props
}) => {
export const TableCell = ({ bordersVertical = [false, 0, 0], align, cell, children, ...props }) => {
const { colorMode } = useColorMode();
const [doVerticalBorders, index] = bordersVertical;
let borderProps = {};
@@ -28,8 +22,7 @@ export const TableCell = ({
whiteSpace="nowrap"
textAlign={align}
{...borderProps}
{...props}
>
{...props}>
{children}
</Box>
);

View File

@@ -1,18 +1,12 @@
import * as React from "react";
import { Box, useColorMode } from "@chakra-ui/core";
import * as React from 'react';
import { Box, useColorMode } from '@chakra-ui/core';
const bg = { dark: "whiteAlpha.100", light: "blackAlpha.100" };
const bg = { dark: 'whiteAlpha.100', light: 'blackAlpha.100' };
export const TableHead = ({ children, ...props }) => {
const { colorMode } = useColorMode();
return (
<Box
as="thead"
overflowX="hidden"
overflowY="auto"
bg={bg[colorMode]}
{...props}
>
<Box as="thead" overflowX="hidden" overflowY="auto" bg={bg[colorMode]} {...props}>
{children}
</Box>
);

View File

@@ -1,14 +1,7 @@
import * as React from "react";
import { IconButton } from "@chakra-ui/core";
import * as React from 'react';
import { IconButton } from '@chakra-ui/core';
export const TableIconButton = ({
icon,
onClick,
isDisabled,
color,
children,
...props
}) => (
export const TableIconButton = ({ icon, onClick, isDisabled, color, children, ...props }) => (
<IconButton
size="sm"
icon={icon}
@@ -17,8 +10,7 @@ export const TableIconButton = ({
variantColor={color}
isDisabled={isDisabled}
aria-label="Table Icon Button"
{...props}
>
{...props}>
{children}
</IconButton>
);

View File

@@ -1,10 +1,10 @@
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { Box, css, useTheme, useColorMode } from "@chakra-ui/core";
import { jsx } from '@emotion/core';
import { Box, css, useTheme, useColorMode } from '@chakra-ui/core';
const scrollbar = { dark: "whiteAlpha.300", light: "blackAlpha.300" };
const scrollbarHover = { dark: "whiteAlpha.400", light: "blackAlpha.400" };
const scrollbarBg = { dark: "whiteAlpha.50", light: "blackAlpha.50" };
const scrollbar = { dark: 'whiteAlpha.300', light: 'blackAlpha.300' };
const scrollbarHover = { dark: 'whiteAlpha.400', light: 'blackAlpha.400' };
const scrollbarBg = { dark: 'whiteAlpha.50', light: 'blackAlpha.50' };
export const TableMain = ({ children, ...props }) => {
const theme = useTheme();
@@ -14,24 +14,23 @@ export const TableMain = ({ children, ...props }) => {
as="table"
display="block"
css={css({
"&::-webkit-scrollbar": { height: "5px" },
"&::-webkit-scrollbar-track": {
backgroundColor: scrollbarBg[colorMode]
'&::-webkit-scrollbar': { height: '5px' },
'&::-webkit-scrollbar-track': {
backgroundColor: scrollbarBg[colorMode],
},
"&::-webkit-scrollbar-thumb": {
backgroundColor: scrollbar[colorMode]
'&::-webkit-scrollbar-thumb': {
backgroundColor: scrollbar[colorMode],
},
"&::-webkit-scrollbar-thumb:hover": {
backgroundColor: scrollbarHover[colorMode]
'&::-webkit-scrollbar-thumb:hover': {
backgroundColor: scrollbarHover[colorMode],
},
"-ms-overflow-style": { display: "none" }
'-ms-overflow-style': { display: 'none' },
})(theme)}
overflowX="auto"
borderRadius="md"
boxSizing="border-box"
{...props}
>
{...props}>
{children}
</Box>
);

View File

@@ -1,19 +1,19 @@
import * as React from "react";
import { PseudoBox, useColorMode, useTheme } from "@chakra-ui/core";
import { opposingColor } from "app/util";
import * as React from 'react';
import { PseudoBox, useColorMode, useTheme } from '@chakra-ui/core';
import { opposingColor } from 'app/util';
const hoverBg = { dark: "whiteAlpha.50", light: "blackAlpha.50" };
const bgStripe = { dark: "whiteAlpha.50", light: "blackAlpha.50" };
const hoverBg = { dark: 'whiteAlpha.50', light: 'blackAlpha.50' };
const bgStripe = { dark: 'whiteAlpha.50', light: 'blackAlpha.50' };
const rowBorder = {
dark: { borderTop: "1px", borderTopColor: "whiteAlpha.100" },
light: { borderTop: "1px", borderTopColor: "blackAlpha.100" }
dark: { borderTop: '1px', borderTopColor: 'whiteAlpha.100' },
light: { borderTop: '1px', borderTopColor: 'blackAlpha.100' },
};
const alphaMap = { dark: "200", light: "100" };
const alphaMapHover = { dark: "100", light: "200" };
const alphaMap = { dark: '200', light: '100' };
const alphaMapHover = { dark: '100', light: '200' };
export const TableRow = ({
highlight = false,
highlightBg = "primary",
highlightBg = 'primary',
doStripe = false,
doHorizontalBorders = false,
index = 0,
@@ -31,23 +31,21 @@ export const TableRow = ({
}
const color = highlight ? opposingColor(theme, bg) : null;
const borderProps =
doHorizontalBorders && index !== 0 ? rowBorder[colorMode] : {};
const borderProps = doHorizontalBorders && index !== 0 ? rowBorder[colorMode] : {};
return (
<PseudoBox
as="tr"
_hover={{
cursor: "pointer",
cursor: 'pointer',
backgroundColor: highlight
? `${highlightBg}.${alphaMapHover[colorMode]}`
: hoverBg[colorMode]
: hoverBg[colorMode],
}}
bg={bg}
color={color}
fontWeight={highlight ? "bold" : null}
fontWeight={highlight ? 'bold' : null}
{...borderProps}
{...props}
>
{...props}>
{children}
</PseudoBox>
);

View File

@@ -1,5 +1,5 @@
import * as React from "react";
import { Select } from "@chakra-ui/core";
import * as React from 'react';
import { Select } from '@chakra-ui/core';
export const TableSelectShow = ({ value, onChange, children, ...props }) => (
<Select size="sm" onChange={onChange} {...props}>

View File

@@ -1,8 +1,8 @@
export * from "./Table";
export * from "./TableBody";
export * from "./TableCell";
export * from "./TableHead";
export * from "./TableIconButton";
export * from "./TableMain";
export * from "./TableRow";
export * from "./TableSelectShow";
export * from './Table';
export * from './TableBody';
export * from './TableCell';
export * from './TableHead';
export * from './TableIconButton';
export * from './TableMain';
export * from './TableRow';
export * from './TableSelectShow';

View File

@@ -1,11 +1,11 @@
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { Box, css, useColorMode } from "@chakra-ui/core";
import { jsx } from '@emotion/core';
import { Box, css, useColorMode } from '@chakra-ui/core';
const bg = { dark: "gray.800", light: "blackAlpha.100" };
const color = { dark: "white", light: "black" };
const selectionBg = { dark: "white", light: "black" };
const selectionColor = { dark: "black", light: "white" };
const bg = { dark: 'gray.800', light: 'blackAlpha.100' };
const color = { dark: 'white', light: 'black' };
const selectionBg = { dark: 'white', light: 'black' };
const selectionColor = { dark: 'black', light: 'white' };
export const TextOutput = ({ children, ...props }) => {
const { colorMode } = useColorMode();
@@ -25,17 +25,16 @@ export const TextOutput = ({ children, ...props }) => {
whiteSpace="pre-wrap"
as="pre"
css={css({
"&::selection": {
'&::selection': {
backgroundColor: selectionBg[colorMode],
color: selectionColor[colorMode]
}
color: selectionColor[colorMode],
},
})}
{...props}
>
{...props}>
{children
.split("\\n")
.join("\n")
.replace(/\n\n/g, "\n")}
.split('\\n')
.join('\n')
.replace(/\n\n/g, '\n')}
</Box>
);
};

View File

@@ -1,31 +1,25 @@
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { forwardRef } from "react";
import { Button, Heading, Image, Stack, useColorMode } from "@chakra-ui/core";
import { useConfig, useMedia } from "app/context";
import { jsx } from '@emotion/core';
import { forwardRef } from 'react';
import { Button, Heading, Image, Stack, useColorMode } from '@chakra-ui/core';
import { useConfig, useMedia } from 'app/context';
const titleSize = { true: ["2xl", "2xl", "5xl", "5xl"], false: "2xl" };
const titleSize = { true: ['2xl', '2xl', '5xl', '5xl'], false: '2xl' };
const titleMargin = { true: 2, false: 0 };
const textAlignment = { false: ["right", "center"], true: ["left", "center"] };
const logoName = { light: "dark", dark: "light" };
const textAlignment = { false: ['right', 'center'], true: ['left', 'center'] };
const logoName = { light: 'dark', dark: 'light' };
const justifyMap = {
true: ["flex-end", "center", "center", "center"],
false: ["flex-start", "center", "center", "center"]
true: ['flex-end', 'center', 'center', 'center'],
false: ['flex-start', 'center', 'center', 'center'],
};
const logoFallback = {
light:
"https://res.cloudinary.com/hyperglass/image/upload/v1593916013/logo-dark.svg",
dark:
"https://res.cloudinary.com/hyperglass/image/upload/v1593916013/logo-light.svg"
light: 'https://res.cloudinary.com/hyperglass/image/upload/v1593916013/logo-dark.svg',
dark: 'https://res.cloudinary.com/hyperglass/image/upload/v1593916013/logo-light.svg',
};
const TitleOnly = ({ text, showSubtitle }) => (
<Heading
as="h1"
mb={titleMargin[showSubtitle]}
fontSize={titleSize[showSubtitle]}
>
<Heading as="h1" mb={titleMargin[showSubtitle]} fontSize={titleSize[showSubtitle]}>
{text}
</Heading>
);
@@ -33,26 +27,18 @@ const TitleOnly = ({ text, showSubtitle }) => (
const SubtitleOnly = ({ text, mediaSize, ...props }) => (
<Heading
as="h3"
fontSize={["md", "md", "xl", "xl"]}
fontSize={['md', 'md', 'xl', 'xl']}
whiteSpace="break-spaces"
textAlign={["left", "left", "center", "center"]}
{...props}
>
textAlign={['left', 'left', 'center', 'center']}
{...props}>
{text}
</Heading>
);
const TextOnly = ({ text, mediaSize, showSubtitle, ...props }) => (
<Stack
spacing={2}
maxW="100%"
textAlign={textAlignment[showSubtitle]}
{...props}
>
<Stack spacing={2} maxW="100%" textAlign={textAlignment[showSubtitle]} {...props}>
<TitleOnly text={text.title} showSubtitle={showSubtitle} />
{showSubtitle && (
<SubtitleOnly text={text.subtitle} mediaSize={mediaSize} />
)}
{showSubtitle && <SubtitleOnly text={text.subtitle} mediaSize={mediaSize} />}
</Stack>
);
@@ -63,15 +49,15 @@ const Logo = ({ text, logo }) => {
return (
<Image
css={{
userDrag: "none",
userSelect: "none",
msUserSelect: "none",
MozUserSelect: "none",
WebkitUserDrag: "none",
WebkitUserSelect: "none"
userDrag: 'none',
userSelect: 'none',
msUserSelect: 'none',
MozUserSelect: 'none',
WebkitUserDrag: 'none',
WebkitUserSelect: 'none',
}}
alt={text.title}
width={width ?? "auto"}
width={width ?? 'auto'}
fallbackSrc={logoFallback[colorMode]}
src={`/images/${logoName[colorMode]}${logoExt[colorMode]}`}
/>
@@ -88,12 +74,7 @@ const LogoSubtitle = ({ text, logo, mediaSize }) => (
const All = ({ text, logo, mediaSize, showSubtitle }) => (
<>
<Logo text={text} logo={logo} />
<TextOnly
mediaSize={mediaSize}
showSubtitle={showSubtitle}
mt={2}
text={text}
/>
<TextOnly mediaSize={mediaSize} showSubtitle={showSubtitle} mt={2} text={text} />
</>
);
@@ -101,7 +82,7 @@ const modeMap = {
text_only: TextOnly,
logo_only: Logo,
logo_subtitle: LogoSubtitle,
all: All
all: All,
};
export const Title = forwardRef(({ onClick, isSubmitting, ...props }, ref) => {
@@ -118,12 +99,11 @@ export const Title = forwardRef(({ onClick, isSubmitting, ...props }, ref) => {
flexWrap="wrap"
flexDir="column"
onClick={onClick}
_focus={{ boxShadow: "none" }}
_hover={{ textDecoration: "none" }}
_focus={{ boxShadow: 'none' }}
_hover={{ textDecoration: 'none' }}
justifyContent={justifyMap[isSubmitting]}
alignItems={["flex-start", "flex-start", "center"]}
{...props}
>
alignItems={['flex-start', 'flex-start', 'center']}
{...props}>
<MatchedMode
mediaSize={mediaSize}
showSubtitle={!isSubmitting}

View File

@@ -1,35 +1,35 @@
export * from "./BGPTable";
export * from "./CacheTimeout";
export * from "./Card";
export * from "./ChakraSelect";
export * from "./CodeBlock";
export * from "./ColorModeToggle";
export * from "./CommunitySelect";
export * from "./CopyButton";
export * from "./Debugger";
export * from "./Footer";
export * from "./FormField";
export * from "./Greeting";
export * from "./Header";
export * from "./HelpModal";
export * from "./HyperglassForm";
export * from "./Label";
export * from "./Layout";
export * from "./Loading";
export * from "./LookingGlass";
export * from "./Markdown";
export * from "./Meta";
export * from "./QueryLocation";
export * from "./QueryTarget";
export * from "./QueryType";
export * from "./QueryVrf";
export * from "./RequeryButton";
export * from "./ResetButton";
export * from "./ResolvedTarget";
export * from "./Result";
export * from "./ResultHeader";
export * from "./Results";
export * from "./SubmitButton";
export * from "./Table";
export * from "./TextOutput";
export * from "./Title";
export * from './BGPTable';
export * from './CacheTimeout';
export * from './Card';
export * from './ChakraSelect';
export * from './CodeBlock';
export * from './ColorModeToggle';
export * from './CommunitySelect';
export * from './CopyButton';
export * from './Debugger';
export * from './Footer';
export * from './FormField';
export * from './Greeting';
export * from './Header';
export * from './HelpModal';
export * from './HyperglassForm';
export * from './Label';
export * from './Layout';
export * from './Loading';
export * from './LookingGlass';
export * from './Markdown';
export * from './Meta';
export * from './QueryLocation';
export * from './QueryTarget';
export * from './QueryType';
export * from './QueryVrf';
export * from './RequeryButton';
export * from './ResetButton';
export * from './ResolvedTarget';
export * from './Result';
export * from './ResultHeader';
export * from './Results';
export * from './SubmitButton';
export * from './Table';
export * from './TextOutput';
export * from './Title';

View File

@@ -1,15 +1,15 @@
import * as React from "react";
import { createContext, useContext, useMemo } from "react";
import dynamic from "next/dynamic";
import { CSSReset, ThemeProvider } from "@chakra-ui/core";
import { MediaProvider } from "./MediaProvider";
import { StateProvider } from "./StateProvider";
import { makeTheme, defaultTheme } from "app/util";
import * as React from 'react';
import { createContext, useContext, useMemo } from 'react';
import dynamic from 'next/dynamic';
import { CSSReset, ThemeProvider } from '@chakra-ui/core';
import { MediaProvider } from './MediaProvider';
import { StateProvider } from './StateProvider';
import { makeTheme, defaultTheme } from 'app/util';
// Disable SSR for ColorModeProvider
const ColorModeProvider = dynamic(
() => import("@chakra-ui/core").then(mod => mod.ColorModeProvider),
{ ssr: false }
() => import('@chakra-ui/core').then(mod => mod.ColorModeProvider),
{ ssr: false },
);
const HyperglassContext = createContext(null);

View File

@@ -1,6 +1,6 @@
import * as React from "react";
import { createContext, useContext, useMemo } from "react";
import { useMediaLayout } from "use-media";
import * as React from 'react';
import { createContext, useContext, useMemo } from 'react';
import { useMediaLayout } from 'use-media';
const MediaContext = createContext(null);
@@ -13,16 +13,16 @@ export const MediaProvider = ({ theme, children }) => {
let mediaSize = false;
switch (true) {
case isSm:
mediaSize = "sm";
mediaSize = 'sm';
break;
case isMd:
mediaSize = "md";
mediaSize = 'md';
break;
case isLg:
mediaSize = "lg";
mediaSize = 'lg';
break;
case isXl:
mediaSize = "xl";
mediaSize = 'xl';
break;
}
const value = useMemo(
@@ -31,13 +31,11 @@ export const MediaProvider = ({ theme, children }) => {
isMd: isMd,
isLg: isLg,
isXl: isXl,
mediaSize: mediaSize
mediaSize: mediaSize,
}),
[isSm, isMd, isLg, isXl, mediaSize]
);
return (
<MediaContext.Provider value={value}>{children}</MediaContext.Provider>
[isSm, isMd, isLg, isXl, mediaSize],
);
return <MediaContext.Provider value={value}>{children}</MediaContext.Provider>;
};
export const useMedia = () => useContext(MediaContext);

View File

@@ -1,18 +1,15 @@
import * as React from "react";
import { createContext, useContext, useMemo, useState } from "react";
import { useSessionStorage } from "app/hooks";
import * as React from 'react';
import { createContext, useContext, useMemo, useState } from 'react';
import { useSessionStorage } from 'app/hooks';
const StateContext = createContext(null);
export const StateProvider = ({ children }) => {
const [isSubmitting, setSubmitting] = useState(false);
const [formData, setFormData] = useState({});
const [greetingAck, setGreetingAck] = useSessionStorage(
"hyperglass-greeting-ack",
false
);
const [greetingAck, setGreetingAck] = useSessionStorage('hyperglass-greeting-ack', false);
const resetForm = layoutRef => {
layoutRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
layoutRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
setSubmitting(false);
setFormData({});
};
@@ -23,11 +20,9 @@ export const StateProvider = ({ children }) => {
setFormData,
greetingAck,
setGreetingAck,
resetForm
resetForm,
}));
return (
<StateContext.Provider value={value}>{children}</StateContext.Provider>
);
return <StateContext.Provider value={value}>{children}</StateContext.Provider>;
};
export const useHyperglassState = () => useContext(StateContext);

View File

@@ -1,3 +1,3 @@
export * from "./HyperglassProvider";
export * from "./MediaProvider";
export * from "./StateProvider";
export * from './HyperglassProvider';
export * from './MediaProvider';
export * from './StateProvider';

View File

@@ -1 +1 @@
export * from "./useSessionStorage";
export * from './useSessionStorage';

View File

@@ -3,10 +3,10 @@ react-use: useSessionStorage
https://github.com/streamich/react-use/blob/master/src/useSessionStorage.ts
*/
import { useEffect, useState } from "react";
import { useEffect, useState } from 'react';
export const useSessionStorage = (key, initialValue, raw) => {
const isClient = typeof window === "object";
const isClient = typeof window === 'object';
if (!isClient) {
return [initialValue, () => {}];
}
@@ -14,16 +14,11 @@ export const useSessionStorage = (key, initialValue, raw) => {
const [state, setState] = useState(() => {
try {
const sessionStorageValue = sessionStorage.getItem(key);
if (typeof sessionStorageValue !== "string") {
sessionStorage.setItem(
key,
raw ? String(initialValue) : JSON.stringify(initialValue)
);
if (typeof sessionStorageValue !== 'string') {
sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
return initialValue;
} else {
return raw
? sessionStorageValue
: JSON.parse(sessionStorageValue || "null");
return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
}
} catch {
// If user is in private mode or has storage restriction

View File

@@ -1,5 +1,5 @@
// const aliases = require("./.alias");
const envVars = require("/tmp/hyperglass.env.json");
const envVars = require('/tmp/hyperglass.env.json');
const { configFile } = envVars;
const config = require(String(configFile));
@@ -18,6 +18,6 @@ module.exports = {
_NODE_ENV_: config.NODE_ENV,
_HYPERGLASS_URL_: config._HYPERGLASS_URL_,
_HYPERGLASS_CONFIG_: config._HYPERGLASS_CONFIG_,
_HYPERGLASS_FAVICONS_: config._HYPERGLASS_FAVICONS_
}
_HYPERGLASS_FAVICONS_: config._HYPERGLASS_FAVICONS_,
},
};

View File

@@ -1,51 +1,52 @@
/* eslint-disable no-console */
const express = require("express");
const proxyMiddleware = require("http-proxy-middleware");
const next = require("next");
const envVars = require("/tmp/hyperglass.env.json");
const express = require('express');
const proxyMiddleware = require('http-proxy-middleware');
const next = require('next');
const envVars = require('/tmp/hyperglass.env.json');
const { configFile } = envVars;
const config = require(String(configFile));
const { NODE_ENV: env, _HYPERGLASS_URL_: envUrl } = config;
const devProxy = {
"/api/query/": { target: envUrl + "api/query/", pathRewrite: { "^/api/query/": "" } },
"/images": { target: envUrl + "images", pathRewrite: { "^/images": "" } },
"/custom": { target: envUrl + "custom", pathRewrite: { "^/custom": "" } }
'/api/query/': { target: envUrl + 'api/query/', pathRewrite: { '^/api/query/': '' } },
'/images': { target: envUrl + 'images', pathRewrite: { '^/images': '' } },
'/custom': { target: envUrl + 'custom', pathRewrite: { '^/custom': '' } },
};
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = env !== "production";
const dev = env !== 'production';
const app = next({
dir: ".", // base directory where everything is, could move to src later
dev
dir: '.', // base directory where everything is, could move to src later
dev,
});
const handle = app.getRequestHandler();
let server;
app.prepare()
.then(() => {
server = express();
app
.prepare()
.then(() => {
server = express();
// Set up the proxy.
if (dev && devProxy) {
Object.keys(devProxy).forEach(function(context) {
server.use(proxyMiddleware(context, devProxy[context]));
});
}
// Set up the proxy.
if (dev && devProxy) {
Object.keys(devProxy).forEach(function(context) {
server.use(proxyMiddleware(context, devProxy[context]));
});
}
// Default catch-all handler to allow Next.js to handle all other routes
server.all("*", (req, res) => handle(req, res));
// Default catch-all handler to allow Next.js to handle all other routes
server.all('*', (req, res) => handle(req, res));
server.listen(port, err => {
if (err) {
throw err;
}
console.log(`> Ready on port ${port} [${env}]`);
});
})
.catch(err => {
console.log("An error occurred, unable to start the server");
console.log(err);
server.listen(port, err => {
if (err) {
throw err;
}
console.log(`> Ready on port ${port} [${env}]`);
});
})
.catch(err => {
console.log('An error occurred, unable to start the server');
console.log(err);
});

View File

@@ -45,17 +45,15 @@
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.24.0",
"@typescript-eslint/parser": "^2.24.0",
"@upstatement/eslint-config": "^0.4.3",
"@upstatement/prettier-config": "^0.3.0",
"babel-eslint": "^10.1.0",
"es-check": "^5.1.0",
"eslint": "^6.8.0",
"eslint-config-airbnb": "^18.1.0",
"eslint-config-prettier": "^6.10.0",
"eslint-config-react-app": "^5.2.0",
"eslint-import-resolver-webpack": "^0.13.0",
"eslint-plugin-flowtype": "^4.6.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^2.3.0",
"express": "^4.17.1",

View File

@@ -1,7 +1,7 @@
import * as React from "react";
import Head from "next/head";
import * as React from 'react';
import Head from 'next/head';
// import { useRouter } from "next/router";
import { HyperglassProvider } from "app/context";
import { HyperglassProvider } from 'app/context';
// import Error from "./_error";
const config = process.env._HYPERGLASS_CONFIG_;

View File

@@ -1,5 +1,5 @@
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
static async getInitialProps(ctx) {
@@ -13,11 +13,7 @@ class MyDocument extends Document {
<Head>
<link rel="dns-prefetch" href="//fonts.googleapis.com" />
<link rel="dns-prefetch" href="//fonts.gstatic.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin="true"
/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="true" />
<link rel="preconnect" href="https://www.google-analytics.com" />
</Head>
<body>

View File

@@ -1,6 +1,6 @@
import React from "react";
import dynamic from "next/dynamic";
import { useRouter } from "next/router";
import React from 'react';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import {
Button,
CSSReset,
@@ -9,42 +9,37 @@ import {
Text,
ThemeProvider,
useColorMode,
theme as defaultTheme
} from "@chakra-ui/core";
import { inRange } from "lodash";
theme as defaultTheme,
} from '@chakra-ui/core';
import { inRange } from 'lodash';
const ColorModeProvider = dynamic(
() => import("@chakra-ui/core").then(mod => mod.ColorModeProvider),
{ ssr: false }
() => import('@chakra-ui/core').then(mod => mod.ColorModeProvider),
{ ssr: false },
);
const ErrorContent = ({ msg, statusCode }) => {
const { colorMode } = useColorMode();
const bg = { light: "white", dark: "black" };
const baseCode = inRange(statusCode, 400, 500)
? 400
: inRange(statusCode, 500, 600)
? 500
: 400;
const bg = { light: 'white', dark: 'black' };
const baseCode = inRange(statusCode, 400, 500) ? 400 : inRange(statusCode, 500, 600) ? 500 : 400;
const errorColor = {
400: { light: "error.500", dark: "error.300" },
500: { light: "danger.500", dark: "danger.300" }
400: { light: 'error.500', dark: 'error.300' },
500: { light: 'danger.500', dark: 'danger.300' },
};
const variantColor = {
400: "error",
500: "danger"
400: 'error',
500: 'danger',
};
const color = { light: "black", dark: "white" };
const color = { light: 'black', dark: 'white' };
const { push } = useRouter();
const handleClick = () => push("/");
const handleClick = () => push('/');
return (
<Flex
w="100%"
minHeight="100vh"
bg={bg[colorMode]}
flexDirection="column"
color={color[colorMode]}
>
color={color[colorMode]}>
<Flex
px={2}
py={0}
@@ -57,8 +52,7 @@ const ErrorContent = ({ msg, statusCode }) => {
alignItems="center"
flexDirection="column"
justifyContent="start"
mt={["50%", "50%", "50%", "25%"]}
>
mt={['50%', '50%', '50%', '25%']}>
<Heading mb={4} as="h1" fontSize="2xl">
<Text as="span" color={errorColor[baseCode][colorMode]}>
{msg}
@@ -66,11 +60,7 @@ const ErrorContent = ({ msg, statusCode }) => {
{statusCode === 404 && <Text as="span"> isn't a thing...</Text>}
</Heading>
<Button
variant="outline"
onClick={handleClick}
variantColor={variantColor[baseCode]}
>
<Button variant="outline" onClick={handleClick} variantColor={variantColor[baseCode]}>
Home
</Button>
</Flex>
@@ -91,7 +81,7 @@ const ErrorPage = ({ msg, statusCode }) => {
ErrorPage.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
const msg = err ? err.message : res.req?.url || "Error";
const msg = err ? err.message : res.req?.url || 'Error';
return { msg, statusCode };
};

View File

@@ -1,12 +1,12 @@
import * as React from "react";
import Head from "next/head";
import dynamic from "next/dynamic";
import { Meta, Loading } from "app/components";
import * as React from 'react';
import Head from 'next/head';
import dynamic from 'next/dynamic';
import { Meta, Loading } from 'app/components';
const LookingGlass = dynamic(
() => import("app/components/LookingGlass").then(i => i.LookingGlass),
() => import('app/components/LookingGlass').then(i => i.LookingGlass),
{
loading: Loading
}
loading: Loading,
},
);
const Index = ({ faviconComponents }) => {
@@ -31,8 +31,8 @@ export async function getStaticProps(context) {
});
return {
props: {
faviconComponents: components
}
faviconComponents: components,
},
};
}

View File

@@ -0,0 +1 @@
module.exports = require("@upstatement/prettier-config");

View File

@@ -2,39 +2,39 @@
// This will help to prevent a flash if dark mode is the default.
(function() {
// Change these if you use something different in your hook.
var storageKey = "darkMode";
var classNameDark = "dark-mode";
var classNameLight = "light-mode";
// Change these if you use something different in your hook.
var storageKey = 'darkMode';
var classNameDark = 'dark-mode';
var classNameLight = 'light-mode';
function setClassOnDocumentBody(darkMode) {
document.body.classList.add(darkMode ? classNameDark : classNameLight);
document.body.classList.remove(darkMode ? classNameLight : classNameDark);
}
function setClassOnDocumentBody(darkMode) {
document.body.classList.add(darkMode ? classNameDark : classNameLight);
document.body.classList.remove(darkMode ? classNameLight : classNameDark);
}
var preferDarkQuery = "(prefers-color-scheme: dark)";
var mql = window.matchMedia(preferDarkQuery);
var supportsColorSchemeQuery = mql.media === preferDarkQuery;
var localStorageTheme = null;
try {
localStorageTheme = localStorage.getItem(storageKey);
} catch (err) {}
var localStorageExists = localStorageTheme !== null;
if (localStorageExists) {
localStorageTheme = JSON.parse(localStorageTheme);
}
var preferDarkQuery = '(prefers-color-scheme: dark)';
var mql = window.matchMedia(preferDarkQuery);
var supportsColorSchemeQuery = mql.media === preferDarkQuery;
var localStorageTheme = null;
try {
localStorageTheme = localStorage.getItem(storageKey);
} catch (err) {}
var localStorageExists = localStorageTheme !== null;
if (localStorageExists) {
localStorageTheme = JSON.parse(localStorageTheme);
}
// Determine the source of truth
if (localStorageExists) {
// source of truth from localStorage
setClassOnDocumentBody(localStorageTheme);
} else if (supportsColorSchemeQuery) {
// source of truth from system
setClassOnDocumentBody(mql.matches);
localStorage.setItem(storageKey, mql.matches);
} else {
// source of truth from document.body
var isDarkMode = document.body.classList.contains(classNameDark);
localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
}
// Determine the source of truth
if (localStorageExists) {
// source of truth from localStorage
setClassOnDocumentBody(localStorageTheme);
} else if (supportsColorSchemeQuery) {
// source of truth from system
setClassOnDocumentBody(mql.matches);
localStorage.setItem(storageKey, mql.matches);
} else {
// source of truth from document.body
var isDarkMode = document.body.classList.contains(classNameDark);
localStorage.setItem(storageKey, JSON.stringify(isDarkMode));
}
})();

View File

@@ -1,33 +1,33 @@
import dayjs from "dayjs";
import relativeTimePlugin from "dayjs/plugin/relativeTime";
import utcPlugin from "dayjs/plugin/utc";
import dayjs from 'dayjs';
import relativeTimePlugin from 'dayjs/plugin/relativeTime';
import utcPlugin from 'dayjs/plugin/utc';
dayjs.extend(relativeTimePlugin);
dayjs.extend(utcPlugin);
const formatAsPath = path => {
return path.join("");
return path.join('');
};
const formatCommunities = comms => {
const commsStr = comms.map(c => ` - ${c}`);
return "\n" + commsStr.join("\n");
return '\n' + commsStr.join('\n');
};
const formatBool = val => {
let fmt = "";
let fmt = '';
if (val === true) {
fmt = "yes";
fmt = 'yes';
} else if (val === false) {
fmt = "no";
fmt = 'no';
}
return fmt;
};
const formatTime = val => {
const now = dayjs.utc();
const then = now.subtract(val, "seconds");
const timestamp = then.toString().replace("GMT", "UTC");
const then = now.subtract(val, 'seconds');
const timestamp = then.toString().replace('GMT', 'UTC');
const relative = now.to(then, true);
return `${relative} (${timestamp})`;
};
@@ -39,7 +39,7 @@ export const tableToString = (target, data, config) => {
config.web.text.rpki_invalid,
config.web.text.rpki_valid,
config.web.text.rpki_unknown,
config.web.text.rpki_unverified
config.web.text.rpki_unverified,
];
return rpkiStateNames[val];
};
@@ -49,13 +49,10 @@ export const tableToString = (target, data, config) => {
active: formatBool,
as_path: formatAsPath,
communities: formatCommunities,
rpki_state: formatRpkiState
rpki_state: formatRpkiState,
};
let tableStringParts = [
`Routes For: ${target}`,
`Timestamp: ${data.timestamp} UTC`
];
let tableStringParts = [`Routes For: ${target}`, `Timestamp: ${data.timestamp} UTC`];
data.output.routes.map(route => {
config.parsed_data_fields.map(field => {
@@ -64,7 +61,7 @@ export const tableToString = (target, data, config) => {
let value = route[accessor];
const fmtFunc = tableFormatMap[accessor] ?? String;
value = fmtFunc(value);
if (accessor === "prefix") {
if (accessor === 'prefix') {
tableStringParts.push(` - ${header}: ${value}`);
} else {
tableStringParts.push(` - ${header}: ${value}`);
@@ -72,7 +69,7 @@ export const tableToString = (target, data, config) => {
}
});
});
return tableStringParts.join("\n");
return tableStringParts.join('\n');
} catch (err) {
console.error(err);
return `An error occurred while parsing the output: '${err.message}'`;

View File

@@ -1,2 +1,2 @@
export * from "./theme";
export * from "./formatters";
export * from './formatters';
export * from './theme';

View File

@@ -1,5 +1,5 @@
import { theme as chakraTheme } from "@chakra-ui/core";
import chroma from "chroma-js";
import { theme as chakraTheme } from '@chakra-ui/core';
import chroma from 'chroma-js';
const alphaColors = color => ({
900: chroma(color)
@@ -31,41 +31,26 @@ const alphaColors = color => ({
.css(),
50: chroma(color)
.alpha(0.04)
.css()
.css(),
});
const generateColors = colorInput => {
const colorMap = {};
const lightnessMap = [
0.95,
0.85,
0.75,
0.65,
0.55,
0.45,
0.35,
0.25,
0.15,
0.05
];
const lightnessMap = [0.95, 0.85, 0.75, 0.65, 0.55, 0.45, 0.35, 0.25, 0.15, 0.05];
const saturationMap = [0.32, 0.16, 0.08, 0.04, 0, 0, 0.04, 0.08, 0.16, 0.32];
const validColor = chroma.valid(colorInput.trim())
? chroma(colorInput.trim())
: chroma("#000");
const validColor = chroma.valid(colorInput.trim()) ? chroma(colorInput.trim()) : chroma('#000');
const lightnessGoal = validColor.get("hsl.l");
const lightnessGoal = validColor.get('hsl.l');
const closestLightness = lightnessMap.reduce((prev, curr) =>
Math.abs(curr - lightnessGoal) < Math.abs(prev - lightnessGoal)
? curr
: prev
Math.abs(curr - lightnessGoal) < Math.abs(prev - lightnessGoal) ? curr : prev,
);
const baseColorIndex = lightnessMap.findIndex(l => l === closestLightness);
const colors = lightnessMap
.map(l => validColor.set("hsl.l", l))
.map(l => validColor.set('hsl.l', l))
.map(color => chroma(color))
.map((color, i) => {
const saturationDelta = saturationMap[i] - saturationMap[baseColorIndex];
@@ -84,31 +69,31 @@ const generateColors = colorInput => {
};
const defaultBodyFonts = [
"-apple-system",
"BlinkMacSystemFont",
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
"Helvetica",
"Arial",
"sans-serif",
'Helvetica',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"'
'"Segoe UI Symbol"',
];
const defaultMonoFonts = [
"SFMono-Regular",
"Melno",
"Monaco",
"Consolas",
'SFMono-Regular',
'Melno',
'Monaco',
'Consolas',
'"Liberation Mono"',
'"Courier New"',
"monospace"
'monospace',
];
const generatePalette = palette => {
const generatedPalette = {};
Object.keys(palette).map(color => {
if (!["black", "white"].includes(color)) {
if (!['black', 'white'].includes(color)) {
generatedPalette[color] = generateColors(palette[color]);
} else {
generatedPalette[color] = palette[color];
@@ -120,9 +105,8 @@ const generatePalette = palette => {
};
const formatFont = font => {
const fontList = font.split(" ");
const fontFmt =
fontList.length >= 2 ? `'${fontList.join(" ")}'` : fontList.join(" ");
const fontList = font.split(' ');
const fontFmt = fontList.length >= 2 ? `'${fontList.join(' ')}'` : fontList.join(' ');
return fontFmt;
};
@@ -137,25 +121,25 @@ const importFonts = userFonts => {
mono.unshift(monoFmt);
}
return {
body: body.join(", "),
heading: body.join(", "),
mono: mono.join(", ")
body: body.join(', '),
heading: body.join(', '),
mono: mono.join(', '),
};
};
const importColors = (userColors = {}) => {
const generatedColors = generatePalette(userColors);
return {
transparent: "transparent",
current: "currentColor",
...generatedColors
transparent: 'transparent',
current: 'currentColor',
...generatedColors,
};
};
export const makeTheme = userTheme => ({
...chakraTheme,
colors: importColors(userTheme.colors),
fonts: importFonts(userTheme.fonts)
fonts: importFonts(userTheme.fonts),
});
export const isDark = color => {
@@ -169,7 +153,7 @@ export const isLight = color => isDark(color);
export const opposingColor = (theme, color) => {
if (color.match(/^\w+\.\d+$/m)) {
const colorParts = color.split(".");
const colorParts = color.split('.');
if (colorParts.length !== 2) {
throw Error(`Color is improperly formatted. Got '${color}'`);
}
@@ -181,14 +165,14 @@ export const opposingColor = (theme, color) => {
};
export const googleFontUrl = (fontFamily, weights = [300, 400, 700]) => {
const urlWeights = weights.join(",");
const urlWeights = weights.join(',');
const fontName = fontFamily
.split(/, /)[0]
.trim()
.replace(/'|"/g, "");
const urlFont = fontName.split(/ /).join("+");
.replace(/'|"/g, '');
const urlFont = fontName.split(/ /).join('+');
const urlBase = `https://fonts.googleapis.com/css?family=${urlFont}:${urlWeights}&display=swap`;
return urlBase;
};
export { theme as defaultTheme } from "@chakra-ui/core";
export { theme as defaultTheme } from '@chakra-ui/core';

View File

@@ -1432,6 +1432,18 @@
semver "^7.3.2"
tsutils "^3.17.1"
"@upstatement/eslint-config@^0.4.3":
version "0.4.3"
resolved "https://registry.yarnpkg.com/@upstatement/eslint-config/-/eslint-config-0.4.3.tgz#9cfbe22d15c0fee2f7154e9f61455c4e53718027"
integrity sha512-I5wYURRsCUpYyTkyq/AOF+aNglJAde2Kzlq297pQ2r61AatUgn84Jw4CsYR6rgQNmTinpLtb8uwi12mOIaM8zg==
"@upstatement/prettier-config@^0.3.0":
version "0.3.0"
resolved "https://registry.yarnpkg.com/@upstatement/prettier-config/-/prettier-config-0.3.0.tgz#cf34332dfba90c7586cd0bde134b7fc771163323"
integrity sha512-/DCKpd5tsgZ7Mshb7MSLdFkPRXHxZhzEKJP9ZW58ix0ARw1nbrcdbyiovHEutiQqmh4OjdLJjIAJ2MVUiEaB+Q==
dependencies:
prettier "^1.x.x"
"@use-it/event-listener@^0.1.2":
version "0.1.5"
resolved "https://registry.yarnpkg.com/@use-it/event-listener/-/event-listener-0.1.5.tgz#870456241bfef66acea6395c69b66fe516bee3cd"
@@ -3336,31 +3348,6 @@ escape-string-regexp@^1.0.2, escape-string-regexp@^1.0.5:
resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4"
integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=
eslint-config-airbnb-base@^14.2.0:
version "14.2.0"
resolved "https://registry.yarnpkg.com/eslint-config-airbnb-base/-/eslint-config-airbnb-base-14.2.0.tgz#fe89c24b3f9dc8008c9c0d0d88c28f95ed65e9c4"
integrity sha512-Snswd5oC6nJaevs3nZoLSTvGJBvzTfnBqOIArkf3cbyTyq9UD79wOk8s+RiL6bhca0p/eRO6veczhf6A/7Jy8Q==
dependencies:
confusing-browser-globals "^1.0.9"
object.assign "^4.1.0"
object.entries "^1.1.2"
eslint-config-airbnb@^18.1.0:
version "18.2.0"
resolved "https://registry.yarnpkg.com/eslint-config-airbnb/-/eslint-config-airbnb-18.2.0.tgz#8a82168713effce8fc08e10896a63f1235499dcd"
integrity sha512-Fz4JIUKkrhO0du2cg5opdyPKQXOI2MvF8KUvN2710nJMT6jaRUpRE2swrJftAjVGL7T1otLM5ieo5RqS1v9Udg==
dependencies:
eslint-config-airbnb-base "^14.2.0"
object.assign "^4.1.0"
object.entries "^1.1.2"
eslint-config-prettier@^6.10.0:
version "6.12.0"
resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-6.12.0.tgz#9eb2bccff727db1c52104f0b49e87ea46605a0d2"
integrity sha512-9jWPlFlgNwRUYVoujvWTQ1aMO8o6648r+K7qU7K5Jmkbyqav1fuEZC0COYpGBxyiAJb65Ra9hrmFx19xRGwXWw==
dependencies:
get-stdin "^6.0.0"
eslint-config-react-app@^5.2.0:
version "5.2.1"
resolved "https://registry.yarnpkg.com/eslint-config-react-app/-/eslint-config-react-app-5.2.1.tgz#698bf7aeee27f0cea0139eaef261c7bf7dd623df"
@@ -3400,13 +3387,6 @@ eslint-module-utils@^2.6.0:
debug "^2.6.9"
pkg-dir "^2.0.0"
eslint-plugin-flowtype@^4.6.0:
version "4.7.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-flowtype/-/eslint-plugin-flowtype-4.7.0.tgz#903a6ea3eb5cbf4c7ba7fa73cc43fc39ab7e4a70"
integrity sha512-M+hxhSCk5QBEValO5/UqrS4UunT+MgplIJK5wA1sCtXjzBcZkpTGRwxmLHhGpbHcrmQecgt6ZL/KDdXWqGB7VA==
dependencies:
lodash "^4.17.15"
eslint-plugin-import@^2.20.1:
version "2.22.1"
resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.22.1.tgz#0896c7e6a0cf44109a2d97b95903c2bb689d7702"
@@ -3443,13 +3423,6 @@ eslint-plugin-jsx-a11y@^6.2.3:
jsx-ast-utils "^2.4.1"
language-tags "^1.0.5"
eslint-plugin-prettier@^3.1.2:
version "3.1.4"
resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.1.4.tgz#168ab43154e2ea57db992a2cd097c828171f75c2"
integrity sha512-jZDa8z76klRqo+TdGDTFJSavwbnWK2ZpqGKNZ+VvweMW516pDUMmQ2koXvxEE4JhzNvTv+radye/bWGBmA6jmg==
dependencies:
prettier-linter-helpers "^1.0.0"
eslint-plugin-react-hooks@^2.3.0:
version "2.5.1"
resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-2.5.1.tgz#4ef5930592588ce171abeb26f400c7fbcbc23cd0"
@@ -3749,11 +3722,6 @@ fast-deep-equal@^3.1.1:
resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"
integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==
fast-diff@^1.1.2:
version "1.2.0"
resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.2.0.tgz#73ee11982d86caaf7959828d519cfe927fac5f03"
integrity sha512-xJuoT5+L99XlZ8twedaRf6Ax2TgQVxvgZOYoPKqZufmJib0tL2tegPBOZb1pVNgIhlqDlA0eO0c3wBvQcmzx4w==
fast-json-stable-stringify@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633"
@@ -4024,11 +3992,6 @@ gauge@~1.2.5:
lodash.padend "^4.1.0"
lodash.padstart "^4.1.0"
get-stdin@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-6.0.0.tgz#9e09bf712b360ab9225e812048f71fde9c89657b"
integrity sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==
get-value@^2.0.3, get-value@^2.0.6:
version "2.0.6"
resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28"
@@ -5935,14 +5898,7 @@ prelude-ls@~1.1.2:
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"
integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=
prettier-linter-helpers@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b"
integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w==
dependencies:
fast-diff "^1.1.2"
prettier@^1.19.1:
prettier@^1.19.1, prettier@^1.x.x:
version "1.19.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"
integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==