theme-ui#Text JavaScript Examples

The following examples show how to use theme-ui#Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BreadCrumbs.js    From developer-portal with Apache License 2.0 6 votes vote down vote up
BreadCrumbs = ({ contentType, group, parent, title }) => {
  return (
    <Flex sx={{ pt: 3, flexWrap: 'wrap' }}>
      <Crumb url="/" text="Home" />
      <Crumb url={`/${contentType}`} text={capitalize(contentType)} />
      {group && <Crumb url={`${group.url}`} text={group.name} />}
      {parent && <Crumb url={`${parent.slug}`} text={parent.title} />}
      <Text variant="caps" sx={{ color: 'textMuted' }}>
        {title}
      </Text>
    </Flex>
  );
}
Example #2
Source File: index.js    From medusa with MIT License 6 votes vote down vote up
StyledTooltip = ({id, text}) => {
  const StyledTooltip = styled(ReactTooltip)`
      box-shadow: 0px 5px 15px 0px rgba(0, 0, 0, 0.08),
        0px 0px 0px 1px rgba(136, 152, 170, 0.1),
        0px 4px 4px 0px rgba(136, 152, 170, 0.1) !important;
      padding: 8px 12px;
      &:after {
        margin-right: 4px;
      }
      &.show {
        opacity: 1;
      }
    `
  return(
    <StyledTooltip
      place="top"
      backgroundColor='#FFF'
      textColor='black'
      effect="solid"
      id={id}
      sx={{ boxShadow: `0px 5px 15px 0px rgba(0, 0, 0, 0.08),
      0px 0px 0px 1px rgba(136, 152, 170, 0.1),
      0px 4px 4px 0px rgba(136, 152, 170, 0.1) !important`,
      padding: `8px 12px`
    }}
    >
        <Text>{text}</Text>
    </StyledTooltip>
  )
}
Example #3
Source File: CodeContainer.js    From developer-portal with Apache License 2.0 6 votes vote down vote up
CodeContainer = ({ value, language }) => {
  return (
    <Box sx={{}}>
      <Flex
        sx={{
          ml: 3,
          borderRadius: '4px 4px 0px 0px',
          py: 2,
          bg: 'surface',
          width: 6,
        }}
      >
        <Text sx={{ mx: 'auto' }}>{capitalize(language || 'code')}</Text>
      </Flex>
      <CodeWrapper
        sx={{ p: 3, maxHeight: 8, borderRadius: 'small' }}
        value={value}
        language={language}
      />
    </Box>
  );
}
Example #4
Source File: endpoint-container.js    From medusa with MIT License 6 votes vote down vote up
EndpointContainer = ({ endpoints }) => {
  if (!endpoints) return null

  return (
    <CodeBox header="ENDPOINTS">
      <Flex
        py={2}
        sx={{
          flexDirection: "column",
        }}
      >
        {endpoints.map((e, i) => {
          const method = e.method.toUpperCase()
          const endpoint = e.endpoint
          return (
            <Flex
              key={i}
              sx={{ fontSize: "0", fontFamily: "monospace", px: "3", py: "2" }}
            >
              <Text
                variant={`labels.${method}`}
                sx={{
                  width: "55px",
                  textAlign: "right",
                }}
                mr={2}
              >
                {method}
              </Text>
              <Text sx={{ color: "dark" }}>
                {endpoint.replace(/{(.*?)}/g, ":$1")}
              </Text>
            </Flex>
          )
        })}
      </Flex>
    </CodeBox>
  )
}
Example #5
Source File: Infobar.js    From developer-portal with Apache License 2.0 6 votes vote down vote up
Infobar = ({ resourcePath, slug, toc }) => {
  return (
    <Box>
      <Box
        sx={{
          alignItems: 'center',
          justifyContent: 'center',
          border: 'solid',
          borderColor: 'muted',
          borderWidth: '0 0 1px 0',
          width: '100%',
          p: 3,
        }}
      >
        <Text sx={{ fontFamily: 'FT Base', pl: 3 }} variant="microText">
          Contents
        </Text>
      </Box>
      <Box sx={{ pl: 0, pr: 3, pt: 3 }}>
        <Text sx={{ pl: [2, 2, 2, 4], pt: 0, pb: 2, color: 'textMuted' }} variant="caps">
          On This Page
        </Text>
        <FileContents resourcePath={resourcePath} slug={slug} toc={toc} />
      </Box>
    </Box>
  );
}
Example #6
Source File: route.js    From medusa with MIT License 6 votes vote down vote up
Route = ({ method, path }) => {
  const fixedMethod = method.toUpperCase()
  return (
    <Flex sx={{ fontFamily: "monospace" }}>
      <Text variant={`labels.${fixedMethod}`} mr={1}>
        {fixedMethod}
      </Text>
      <Text>{formatRoute(path)}</Text>
    </Flex>
  )
}
Example #7
Source File: 404.js    From github-covid-finder with MIT License 6 votes vote down vote up
NotFound = () => {
  return (
    <Layout>
      <SEO />
      <Container
        sx={{
          backgroundColor: 'background',
          padding: 16,
          borderRadius: '3px',
          marginTop: '80px',
          letterSpacing: '4px',
          fontSize: '56px',
          color: '#FF4136',
          fontFamily: 'inter',
          textAlign: 'center',
          fontWeight: 700,
        }}
      >
        <Text>#STAY THE FUCK HOME</Text>
      </Container>
      <Container
        sx={{
          fontFamily: 'inter',
          textAlign: 'center',
          backgroundColor: 'background',
          color: 'text',
          borderRadius: '3px',
        }}
      >
        <p>Not sure if the page you are searching exist!</p>
        <p>While I check feel free to navigate to the Home page</p>
      </Container>
    </Layout>
  )
}
Example #8
Source File: lighthouse.js    From cards with MIT License 6 votes vote down vote up
Lighthouse = ({ value, label, theme }) => {
  return (
    <Flex
      sx={{
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
      }}
    >
      <Progress value={value} {...getColors(value, theme)} />
      <Text
        sx={{
          mt: '10px',
          fontWeight: 300,
          fontFamily: 'Roboto, Helvetica, Arial, sans-serif',
          color: theme === 'dark' ? '#F5F5F5' : '#212121',
          fontSize: '24px'
        }}
      >
        {label}
      </Text>
    </Flex>
  )
}
Example #9
Source File: RelatedResources.js    From developer-portal with Apache License 2.0 6 votes vote down vote up
RelatedResources = ({ resources = [], contentType, show = 3 }) => {
  const nextType = contentType === ContentTypes.GUIDES ? 'relatedGuides' : 'relatedDocs';
  return (
    <Box>
      <Heading variant="mediumHeading" sx={{ my: 4 }}>
        <InlineText name={nextType} />
      </Heading>
      {resources.slice(0, show).map(({ data }, i) => {
        return (
          <Link key={data.frontmatter.slug} href={`/${nextType}/${data.frontmatter.slug}`} passHref>
            <Flex
              sx={{
                alignItems: 'center',
                py: 3,
                px: 0,
                border: 'light',
                borderColor: 'muted',
                borderWidth: '0 0 1px 0',
                cursor: 'pointer',
              }}
            >
              <Icon sx={{ size: 4, minWidth: 32 }} name={`num_${i + 1}`} />
              <Text variant="largeText" sx={{ pl: 3 }}>
                {data.frontmatter.title}
              </Text>
              <Icon sx={{ ml: 'auto', minWidth: 16 }} color="primary" name={'arrow_right'}></Icon>
            </Flex>
          </Link>
        );
      })}
    </Box>
  );
}
Example #10
Source File: searchable-select.js    From cards with MIT License 6 votes vote down vote up
Option = ({ innerRef, innerProps, children, value, ...props }) => (
  <components.Option {...props}>
    <Flex
      ref={innerRef}
      sx={{
        alignItems: 'center',
        justifyContent: 'space-between'
      }}
      {...innerProps}
    >
      <Text
        sx={{
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
          pr: 3,
          flex: 1
        }}
        title={children}
      >
        {children}
      </Text>
      <Box>
        <Image
          placeholder='blur'
          src={previews[value]}
          width={128}
          height={72}
        />
      </Box>
    </Flex>
  </components.Option>
)
Example #11
Source File: MarkdownWrapper.js    From developer-portal with Apache License 2.0 5 votes vote down vote up
ListItem = ({ children, index, ordered }) => {
  return ordered ? (
    $(
      Grid,
      { columns: ['64px auto'], gap: 3, sx: { mb: 3 } },
      $(
        Flex,
        {
          sx: {
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center',
            bg: 'onBackground',
            color: 'primary',
            size: 4,
            borderRadius: 'round',
            fontFamily: 'heading',
            fontSize: 3,
            mx: 'auto',
          },
        },
        $(Text, null, `${index + 1}`)
      ),
      $(
        Text,
        {
          sx: {
            my: 0,
            p: 0,
            '& > p': {
              m: 0,
            },
            '& > ul': {
              mt: 1,
              mb: 0,
            },
          },
        },
        children
      )
    )
  ) : (
    <li>{children}</li>
  );
}
Example #12
Source File: footer.js    From github-covid-finder with MIT License 5 votes vote down vote up
Footer = () => {
  return (
    <Box
      sx={{
        borderTop: '1px solid',
        borderColor: 'cardBorder',
        py: '5px',
      }}
    >
      <Flex
        as="footer"
        sx={{
          flexDirection: ['column', 'row'],
          alignItems: 'center',
          justifyContent: 'space-between',
          maxWidth: ['100%', '768px', '992px', '1400px'],
          py: '15px',
          margin: '0 auto',
        }}
      >
        <Text
          sx={{
            fontSize: '12px',
            color: 'text',
            fontFamily: 'inter',
            textAlign: 'center',
          }}
        >
          <a href="https://www.netlify.com">This site is powered by Netlify</a>
        </Text>
        <a
          href="https://www.helpfulengineering.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          <Text
            sx={{
              letterSpacing: '2px',
              fontSize: '14px',
              color: 'text',
              fontFamily: 'inter',
              textAlign: 'center',
              my: 10,
            }}
          >
            Get involved
          </Text>
        </a>
        <Text
          sx={{
            fontSize: '12px',
            color: 'text',
            fontFamily: 'inter',
            textAlign: 'center',
          }}
        >
          <a href="https://twitter.com/_luisFilipePT">@_luisFilipePT</a>
          &nbsp;|&nbsp;
          <a href="https://github.com/luisFilipePT/github-covid-finder/blob/master/CODE_OF_CONDUCT.md">
            Code of Conduct
          </a>
        </Text>
      </Flex>
    </Box>
  )
}
Example #13
Source File: SidebarDocumentation.js    From developer-portal with Apache License 2.0 5 votes vote down vote up
Sidebar = ({ resources, resourcePath, activeSlug, mobile, router }) => {
  const activeGroup = useStore((state) => state.activeGroup);
  const [name, setName] = useState(null);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    setName(navItems.find((ni) => ni.slug === activeGroup)?.name);
  }, [activeGroup]);

  useEffect(() => {
    if (mobile) {
      setMobileOpen(false);
    }
  }, [mobile, router?.asPath]);

  return (
    <>
      {mobile && <MobileSidebar open={mobileOpen} onClick={setMobileOpen} />}
      {mobileOpen || !mobile ? (
        <Flex
          sx={{
            p: 0,
            pl: [0, 0, 0, 4],
            pb: [3, 0],
            flexDirection: 'column',
            border: 'light',
            borderColor: 'muted',
            borderWidth: mobile ? '0 0 1px 0' : '0 1px 0 0',
            minWidth: '200px',
          }}
        >
          <Text sx={{ px: 2, pt: 3, color: 'textMuted' }} variant="caps">
            {name}
          </Text>
          {resources.map((resource, i) => (
            <List
              key={i}
              items={resource}
              resourcePath={resourcePath}
              activeSlug={activeSlug}
              mobile={mobile}
            />
          ))}
        </Flex>
      ) : null}
    </>
  );
}
Example #14
Source File: code-box.js    From medusa with MIT License 5 votes vote down vote up
CodeBox = ({ header, children, shell, content, allowCopy }) => {
  return (
    <Box
      sx={{
        background: "fadedContrast",
        borderRadius: "small",
        boxShadow: "0 0 0 1px var(--theme-ui-colors-primaryLight)",
        alignSelf: "flex-start",
        marginLeft: "auto",
        marginRight: "auto",
        width: "100%",
        mb: "4",
      }}
    >
      <Box
        sx={{
          bg: "primary",
          p: "8px 10px",
          letterSpacing: "0.01em",
          borderRadius: "8px 8px 0 0",
        }}
      >
        <Flex
          sx={{
            height: "100%",
            justifyContent: "space-between",
            alignItems: "baseline",
          }}
        >
          <Text variant="small" sx={{ fontWeight: "400", color: "light" }}>
            {header.toUpperCase()}
          </Text>
          {allowCopy ? (
            <CopyToClipboard
              copyText={content}
              tooltipText={"Copy to clipboard"}
            />
          ) : (
            <></>
          )}
        </Flex>
      </Box>
      <Box
        sx={{
          position: "relative",
          boxSizing: "content-box",
          maxHeight: "calc(90vh - 20px)",
          minHeight: "10px",
        }}
      >
        <Flex
          sx={{
            flexDirection: "column",
            position: "relative",
            minHeight: "inherit",
            maxHeight: "inherit",
            overflowY: "auto",
          }}
        >
          {children}
        </Flex>
      </Box>
    </Box>
  )
}
Example #15
Source File: live-editor.js    From cards with MIT License 5 votes vote down vote up
Loading = () => (
  <Text sx={{ fontFamily: 'mono', color: theme.color }}>Loading...</Text>
)
Example #16
Source File: IntroText.js    From developer-portal with Apache License 2.0 5 votes vote down vote up
IntroText = ({ mobile }) => {
  return (
    <Container>
      <Flex
        sx={{
          alignItems: 'center',
          flexWrap: mobile ? 'wrap' : 'nowrap',
        }}
      >
        <Flex pb="4" sx={{ width: '100%', flexDirection: 'column', minWidth: ['50vw', 600] }}>
          <Heading variant="megaHeading">About</Heading>
          <Heading
            variant="megaHeading"
            sx={{
              color: 'onBackgroundMuted',
            }}
          >
            The Protocol
          </Heading>
        </Flex>

        <Heading
          sx={{
            pb: 4,
            color: 'onBackgroundMuted',
          }}
        >
          <InlineTextarea name="aboutSubheading" />
        </Heading>
      </Flex>
      <Grid columns={[1, 2]}>
        <Flex sx={{ flexDirection: 'column', width: '100%' }}>
          <Text
            sx={{
              pb: 4,
              color: 'onBackgroundMuted',
            }}
          >
            <InlineTextarea name="aboutMakerProtocol" />
          </Text>
          <Link href="/documentation/introduction-to-the-maker-protocol">
            <Flex sx={{ alignItems: 'center', pb: [5, 0] }}>
              <Icon sx={{ mr: 2 }} color="primary" name={'arrow_right'}></Icon>
              <ThemeLink>Learn more about the Maker Protocol.</ThemeLink>
            </Flex>
          </Link>
        </Flex>
        <Flex sx={{ px: 4, flexDirection: 'column' }}>
          <Heading sx={{ pb: 3, pr: [0, 0, 6] }}>
            <InlineText name="devUpdates1" />
          </Heading>
          <EmailSignup sx={{ fontSize: 5 }} placeholder="We saved a slot for your email" />
        </Flex>
      </Grid>
    </Container>
  );
}
Example #17
Source File: pagination.js    From github-covid-finder with MIT License 5 votes vote down vote up
Pagination = ({ pageUp, pageDown, currentPage, totalResults }) => {
  const ButtonStyle = {
    cursor: 'pointer',
    width: 36,
    height: 36,
    padding: 0,
    borderRadius: 4,
    border: '1px solid',
    borderColor: 'cardBorder',
    backgroundColor: 'cardBackground',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontSize: 18,
    color: 'text',
  }

  return (
    <Flex
      sx={{
        fontSize: [16, 26],
        color: 'textRreverse',
        textAlign: 'center',
        fontFamily: 'inter',
        padding: '8px',
        mt: '30px',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      {currentPage !== 1 && (
        <Button
          sx={{
            ...ButtonStyle,
          }}
          onClick={pageDown}
        >
          &#8592;
        </Button>
      )}
      <Text sx={{ color: 'text', px: 32, fontSize: 14 }}>
        Page {currentPage} ({totalResults} results)
      </Text>
      <Button
        sx={{
          ...ButtonStyle,
        }}
        onClick={pageUp}
      >
        &#8594;
      </Button>
    </Flex>
  )
}
Example #18
Source File: CodeBox.js    From developer-portal with Apache License 2.0 5 votes vote down vote up
CodeBox = ({ cta, sections }) => {
  const [activeTool, setActiveTool] = useState(0);

  return (
    <Container>
      <Heading sx={{ pb: [3, 4] }} variant="mediumHeading">
        {cta}
      </Heading>
      <Grid
        columns={[1, '1fr auto']}
        sx={{
          columnGap: 4,
        }}
      >
        <Box>
          <Card
            sx={{
              height: '500px',
              width: '100%',
              bg: 'background',
            }}
          >
            <CodeWrapper
              value={sections[activeTool].code}
              language={sections[activeTool].language}
            />
          </Card>
        </Box>
        <Box>
          <Grid
            sx={{
              rowGap: 4,
            }}
          >
            {sections.map((tool, i) => {
              const { title, des, link } = tool;
              const isActive = i === activeTool;
              return (
                <Box key={tool.title}>
                  <Heading
                    variant="microHeading"
                    onClick={() => {
                      setActiveTool(i);
                    }}
                    sx={{ cursor: 'pointer' }}
                  >
                    {title}
                  </Heading>
                  {!isActive ? null : (
                    <Grid
                      sx={{
                        rowGap: 2,
                        pt: 2,
                      }}
                    >
                      <Text>{des}</Text>
                      <Link href={link} passHref>
                        <Flex sx={{ alignItems: 'center' }}>
                          <Icon sx={{ mr: 2 }} name={'arrow_right'}></Icon>
                          <ThemeLink sx={{ color: 'text', cursor: 'pointer' }}>Read More</ThemeLink>
                        </Flex>
                      </Link>
                    </Grid>
                  )}
                </Box>
              );
            })}
          </Grid>
        </Box>
      </Grid>
    </Container>
  );
}
Example #19
Source File: about.js    From github-covid-finder with MIT License 5 votes vote down vote up
About = () => {
  return (
    <Layout>
      <SEO />
      <Container
        sx={{
          padding: 4,
          color: 'text',
          fontFamily: 'inter',
          textAlign: 'center',
          backgroundColor: 'cardBackground',
          borderRadius: '8px',
          borderWidth: 1,
          borderStyle: 'solid',
          borderColor: 'cardBorder',
          lineHeight: '24px',
        }}
      >
        <Box p={4}>
          <h3>
            "Opportunity 3 - Start <em>contributing</em> immediately
          </h3>
          <Text>
            It would be great if any software engineer with spare time can just
            peruse open Github issues across all OpenAir [Covid-19] projects,
            filter for their area of expertise and just submit little PRs within
            their specific time constraints. You shouldn’t even need to engage
            too deeply with the wider project organisation; just see a list of
            valuable quickwins that you can tackle rapidly to add value to any
            team that needs it."
          </Text>
        </Box>
        <p>
          This project was inspired by the above excerpt from
          <Link
            href="https://jonnyparris.github.io/COVID-helping"
            sx={{ color: 'secondary' }}
            target="_blank"
            rel="noopener noreferrer"
          >
            &nbsp;this blogpost.
          </Link>
        </p>
      </Container>
    </Layout>
  )
}
Example #20
Source File: collapsible.js    From medusa with MIT License 4 votes vote down vote up
NestedCollapsible = ({ properties, title }) => {
  const [isOpen, setIsOpen] = useState(false)
  return (
    <Box
      mt={2}
      sx={{
        "& .child-attrs": {
          cursor: "pointer",
          fontSize: "12px",
          p: "6px 10px",
          boxSizing: "border-box",
          width: "max-content",
          borderRadius: "small",
          border: "1px solid",
          borderColor: "faded",
        },

        "& .child-attrs.is-open": {
          width: "100%",
          borderBottom: "none",
          borderBottomLeftRadius: "0",
          borderBottomRightRadius: "0",
        },
      }}
    >
      <Collapsible
        transitionTime={50}
        triggerClassName={"child-attrs"}
        triggerOpenedClassName={"child-attrs"}
        triggerTagName="div"
        trigger={
          <Flex
            sx={{
              alignItems: "baseline",
              fontSize: "13px",
              fontWeight: "400",
            }}
          >
            <Box
              mr={1}
              className={isOpen ? "rotated" : null}
              sx={{
                userSelect: "none",
                transition: "all 0.2s ease",
                transform: "rotate(45deg)",
                "&.rotated": {
                  transform: "rotate(0deg)",
                },
              }}
            >
              &times;
            </Box>{" "}
            <Text
              sx={{ fontSize: "0", fontFamily: "body", userSelect: "none" }}
            >{`${isOpen ? "Hide" : "Show"} child attributes`}</Text>
          </Flex>
        }
        onTriggerOpening={() => setIsOpen(true)}
        onTriggerClosing={() => setIsOpen(false)}
      >
        <Box
          sx={{
            padding: "2",
            borderRadius: "small",
            borderTopLeftRadius: 0,
            borderTopRightRadius: 0,
            border: "hairline",
            borderColor: "faded",
          }}
          mb="2"
        >
          <Heading as="h3" p={2} sx={{ fontFamily: "body", fontWeight: "500" }}>
            {title}
          </Heading>
          {properties.map((param, i) => {
            return (
              <Box
                p={2}
                sx={{
                  borderTop: "hairline",
                }}
                key={i}
              >
                <Flex
                  sx={{
                    fontSize: "0",
                    alignItems: "baseline",
                    pb: "1",
                    fontFamily: "monospace",
                  }}
                >
                  <Box mr={2} fontSize={"12px"}>
                    {param.property}
                  </Box>
                  <Text color={"gray"} fontSize={"10px"}>
                    {param.type}
                  </Text>
                  {param.required && (
                    <Text ml={1} fontSize={"10px"} variant="labels.required">
                      required
                    </Text>
                  )}
                </Flex>
                <Description>
                  <Text
                    sx={{
                      fontSize: "0",
                      lineHeight: "26px",
                      fontFamily: "body",
                    }}
                  >
                    <Markdown>{param.description}</Markdown>
                  </Text>
                </Description>
              </Box>
            )
          })}
        </Box>
      </Collapsible>
    </Box>
  )
}
Example #21
Source File: overlay-preview.js    From cards with MIT License 4 votes vote down vote up
export default function OverlayPreview () {
  const { query, screenshotUrl, theme } = useContext(AppContext)
  const { borderColor, color, contrast } = theme

  return (
    <>
      <Box as='header'>
        <AspectRatio ratio='16/9'>
          <LivePreview
            shadow
            css={`
              zoom: 0.6;
              cursor: pointer;
            `}
            onClick={() => toClipboard(screenshotUrl, 'URL')}
          />
        </AspectRatio>
      </Box>

      <Text sx={{ color, mt: 4, mb: 3, fontSize: 2, fontWeight: 'normal' }}>
        Add it to your website by copying the code below
      </Text>

      <Box as='section' sx={{ overflow: 'scroll' }}>
        <Tabs theme={theme}>
          <TabList>
            <Tab>SEO tags</Tab>
            <Tab>HTML</Tab>
            <Tab>Markdown</Tab>
            <Tab>Javascript</Tab>
            <Tab>Direct URL</Tab>
          </TabList>

          <TabPanel>
            <Code
              sx={{
                borderColor,
                color: contrast
              }}
              onClick={e => toClipboard(e.target.textContent, 'SEO Tags')}
            >
              {shareCode.seo(screenshotUrl)}
            </Code>
          </TabPanel>
          <TabPanel>
            <Code
              sx={{
                borderColor,
                color: contrast
              }}
              onClick={e => toClipboard(e.target.textContent, 'HTML')}
            >
              {shareCode.html(screenshotUrl)}
            </Code>
          </TabPanel>
          <TabPanel>
            <Code
              sx={{
                borderColor,
                color: contrast
              }}
              onClick={e => toClipboard(e.target.textContent, 'Markdown')}
            >
              {shareCode.markdown(screenshotUrl)}
            </Code>
          </TabPanel>
          <TabPanel>
            <Code
              sx={{
                borderColor,
                color: contrast
              }}
              onClick={e => toClipboard(e.target.textContent, 'Javascript')}
            >
              {shareCode.javascript(query)}
            </Code>
          </TabPanel>
          <TabPanel>
            <Code
              sx={{
                borderColor,
                color: contrast
              }}
              onClick={e => toClipboard(e.target.textContent, 'URL')}
            >
              {screenshotUrl}
            </Code>
          </TabPanel>
        </Tabs>
      </Box>
    </>
  )
}
Example #22
Source File: PreferencesRoute.js    From NoteMaster with GNU General Public License v3.0 4 votes vote down vote up
PreferencesRoute = ({ preferences, updatePreferences }) => {
  const history = useHistory();

  const fontFamilyChange = e => {
    updatePreferences({
      fontFamily: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const fontSizeChange = e => {
    updatePreferences({
      fontSize: Number(e.target.value),
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const fontWeightChange = e => {
    updatePreferences({
      fontWeight: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const lineHeightChange = e => {
    updatePreferences({
      lineHeight: Number(e.target.value),
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const lineNumbersChange = e => {
    updatePreferences({
      lineNumbers: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const autoLaunchChange = e => {
    updatePreferences({
      autoLaunch: e.target.value === 'true',
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const nmlEnabledChange = e => {
    updatePreferences({
      nmlEnabled: e.target.value === 'true',
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const fontLigaturesChange = e => {
    updatePreferences({
      fontLigatures: e.target.value === 'true',
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const nmlBaseCurrencyChange = e => {
    updatePreferences({
      nmlBaseCurrency: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const wrappingIndentChange = e => {
    updatePreferences({
      wrappingIndent: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const editorThemeChange = e => {
    updatePreferences({
      editorTheme: e.target.value,
      // HACK: If the initial content is updated to match the existing autosaveContent then the user will lose all changes
      // since the file was read from the disk into memory.
      editorContent: preferences.autosaveContent
    });
  };

  const navigateToNotes = e => {
    updatePreferences({
      editorContent: preferences.autosaveContent
    });

    history.push('/');
  };

  const {
    editorTheme,
    fontFamily,
    fontSize,
    fontWeight,
    lineNumbers,
    lineHeight,
    fontLigatures,
    autoLaunch,
    nmlEnabled,
    nmlBaseCurrency,
    wrappingIndent
  } = preferences;

  const renderNmlOptions = () => {
    return (
      <Box
        className={
          nmlEnabled ? styles.smartOptionsActive : styles.smartOptionsHidden
        }
        mb="2"
      >
        <Flex mt="3">
          <Box sx={{ flex: '1 1 auto' }}>
            <TooltipComponent content="Set this value to your most commonly used currency. The default is: USD.">
              <Label mt="2" variant="labelTooltip">
                Base Currency
              </Label>
            </TooltipComponent>
          </Box>
          <Box>
            <Select
              disabled={!nmlEnabled}
              defaultValue={nmlBaseCurrency}
              onChange={nmlBaseCurrencyChange}
            >
              <option value="USD">USD</option>
              <option value="GBP">GBP</option>
              <option value="EUR">EUR</option>
            </Select>
          </Box>
        </Flex>
      </Box>
    );
  };

  return (
    <div className={styles.container} data-tid="container">
      <div className={styles.header}>
        <TitlebarComponent />
      </div>
      <div className={styles.preferences}>
        <ContainerComponent padding="0 8px 0 0">
          <Button variant="linkUpper" mb="0" onClick={navigateToNotes}>
            <i className="ri-arrow-left-line" /> Return to Notes
          </Button>
        </ContainerComponent>
        <ScrollableContentComponent>
          <ContainerComponent padding="0 8px 0 0">
            <Heading mt="0" as="h1">
              Preferences
            </Heading>
            <Text mt="1" mb="3" variant="muted">
              Customize NoteMaster to your desire. You can request features on{' '}
              <Link
                href="https://github.com/LiamRiddell/NoteMaster"
                target="_blank"
                rel="noreferer"
              >
                NoteMaster GitHub
              </Link>
              .
            </Text>

            {/* Editor */}
            <Box mb="4">
              <Text mb="2" variant="group">
                Editor
              </Text>

              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="When enabled, NoteMaster Smart Mode automatically recognizes keywords, and intelligently provides results as you type. The default is: Enabled.">
                    <Label mt="2" variant="labelTooltip">
                      Smart Mode
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select
                    defaultValue={nmlEnabled ? 'true' : 'false'}
                    onChange={nmlEnabledChange}
                  >
                    <option value="true">Enabled</option>
                    <option value="false">Disabled</option>
                  </Select>
                </Box>
              </Flex>

              {/* NoteMaster Language */}
              {renderNmlOptions()}

              {/* Line Numbers */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="When enabled, line numbers will be displayed on the left side of the editor. The default is: Off.">
                    <Label mt="2" variant="labelTooltip">
                      Line Numbers
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select
                    defaultValue={lineNumbers}
                    onChange={lineNumbersChange}
                  >
                    <option value="off">Off</option>
                    <option value="on">On</option>
                    <option value="relative">Relative</option>
                    <option value="interval">Interval</option>
                  </Select>
                </Box>
              </Flex>

              {/* Text Wrap Indentation */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="This effects how long sentences wrap onto a new line. The default is: Same.">
                    <Label mt="2" variant="labelTooltip">
                      Text Wrap Indent
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select
                    defaultValue={wrappingIndent}
                    onChange={wrappingIndentChange}
                  >
                    <option value="same">Same</option>
                    <option value="indent">Indent</option>
                    <option value="deepIndent">Deep Indent</option>
                    <option value="none">None</option>
                  </Select>
                </Box>
              </Flex>

              {/* Editor Theme */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="Using the Dark theme will enable rich text highlighting, which compliments Smart Mode. Use Dark Basic, if you find the rich text highlighting distrating. The default is: Dark.">
                    <Label mt="2" variant="labelTooltip">
                      Theme
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select
                    defaultValue={editorTheme}
                    onChange={editorThemeChange}
                  >
                    <option value="notemaster-dark-nml-enabled">Dark</option>
                    <option value="notemaster-dark-nml-disabled">
                      Dark Basic
                    </option>
                  </Select>
                </Box>
              </Flex>
            </Box>

            {/* Typography Settings */}
            <Box mb="4">
              <Text mb="2" variant="group">
                Typography
              </Text>

              {/* Font */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="Changes the font within the editor. The default is: Roboto.">
                    <Label mt="2" variant="labelTooltip">
                      Font
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select defaultValue={fontFamily} onChange={fontFamilyChange}>
                    <option value="Roboto">Roboto</option>
                    <option value="Arial">Arial</option>
                    <option value="Helvetica Neue">Helvetica Neue</option>
                    <option value="Monospace">Monospace</option>
                    <option value="Ubuntu">Ubuntu</option>
                    <option value="Segoe UI">Segoe UI</option>
                  </Select>
                </Box>
              </Flex>

              {/* Font Size */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="You can adjust the font size within the editor. The default is: 16.">
                    <Label mt="2" variant="labelTooltip">
                      Font Size
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Input
                    type="number"
                    defaultValue={fontSize}
                    onChange={fontSizeChange}
                    sx={{ width: '72px' }}
                  />
                </Box>
              </Flex>

              {/* Font Weight */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="Changes the font thickness within the editor. The default is: Regular.">
                    <Label mt="2" variant="labelTooltip">
                      Font Weight
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select defaultValue={fontWeight} onChange={fontWeightChange}>
                    <option value="100">Thin</option>
                    <option value="200">Extra Light</option>
                    <option value="300">Light</option>
                    <option value="400">Regular</option>
                    <option value="500">Medium</option>
                    <option value="600">Semi-Bold</option>
                    <option value="700">Bold</option>
                    <option value="800">Extra Bold</option>
                    <option value="900">Black</option>
                  </Select>
                </Box>
              </Flex>

              {/* Line Height */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="Change the line height within the editor. The default is: 24.">
                    <Label mt="2" variant="labelTooltip">
                      Line Height
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Input
                    type="number"
                    defaultValue={lineHeight}
                    onChange={lineHeightChange}
                    sx={{ width: '72px' }}
                  />
                </Box>
              </Flex>

              {/*
              <Label mt="2" mb="1">
                Font Ligatures
              </Label>
              <Select
                defaultValue={fontLigatures ? 'true' : 'false'}
                onChange={fontLigaturesChange}
              >
                <option value="true">On</option>
                <option value="false">Off</option>
              </Select> */}
            </Box>

            {/* System */}
            <Box mb="4">
              <Text mb="2" variant="group">
                SYSTEM
              </Text>

              {/* Auto Launch */}
              <Flex mt="3">
                <Box sx={{ flex: '1 1 auto' }}>
                  <TooltipComponent content="When enabled, NoteMaster will be launched on startup. The default is: On.">
                    <Label mt="2" variant="labelTooltip">
                      Auto Launch
                    </Label>
                  </TooltipComponent>
                </Box>
                <Box>
                  <Select
                    defaultValue={autoLaunch ? 'true' : 'false'}
                    onChange={autoLaunchChange}
                  >
                    <option value="false">Off</option>
                    <option value="true">On</option>
                  </Select>
                </Box>
              </Flex>
            </Box>

            {/* Creation Rights */}
            <Box
              p={3}
              color="text"
              bg="#27292C"
              mb="1"
              sx={{ borderRadius: 3 }}
            >
              Thank you for downloading NoteMaster, an open-source project
              created and maintained by{' '}
              <Link href="https://github.com/LiamRiddell" target="_blank">
                Liam Riddell
              </Link>{' '}
              ❤️
            </Box>
          </ContainerComponent>
        </ScrollableContentComponent>
      </div>
    </div>
  );
}
Example #23
Source File: header.js    From github-covid-finder with MIT License 4 votes vote down vote up
Header = ({ isShowSearch, searchCompProps, toggleModal }) => {
  const [colorMode, setColorMode] = useColorMode()
  return (
    <Box
      sx={{
        borderBottom: "1px solid",
        borderColor: 'cardBorder',
        marginBottom: '24px'
      }}>
      <Flex
        as="header"
        sx={{
          height: '120px',
          alignItems: 'center',
          justifyContent: 'space-between',
          margin: '0 auto',
          maxWidth: ['100%', '768px', '992px', '1400px'],
          px: '15px',
        }}
      >
        <Flex
          sx={{
            flex: 1,
            alignItems: 'center',
          }}
        >
          <Text
            sx={{
              fontSize: '24px',
              color: 'white',
              fontFamily: 'inter',
              textAlign: 'center',
            }}
          >
            <Link to="/" style={{ display: 'block', lineHeight: 0 }} >
              <Image style={{ fill: '#FF4136', width: 180 }} src={colorMode === 'dark' ? logoWhite : logoBlack} />
            </Link>
          </Text>
          { isShowSearch &&
            <Box
              sx={{
                width: '76%',
                margin: '16px 16px 0px 16px',
                '@media only screen and (max-width: 916px)': {
                  marginTop: 0,
                  width: 'auto',
                  display: 'flex',
                  justifyContent: 'flex-end',
                  margin: '0px 16px 0px auto',
                },
                '@media only screen and (max-width: 320px)': {
                  margin: '0px 6px',
                },
              }}
            >
              <Box
                sx={{
                  '@media only screen and (max-width: 916px)': {
                    display: 'none',
                  },
                }}
              >
                <Search {...searchCompProps}/>
              </Box>
              <Button
                name="toggle-modal-with-search"
                onClick={toggleModal}
                backgroundColor="rgb(157, 31, 30)"
                sx={{
                  padding: '6px 12px',
                  '@media only screen and (min-width: 916px)': {
                    display: 'none',
                  },
                }}
              >
                <SearchIcon
                  style={{
                    width: 16,
                    height: 16,
                  }}
                />
              </Button>
            </Box>
          }
        </Flex>
        <Flex
          sx={{
            alignItems: 'center',
            justifyContent: 'space-between',
            '@media only screen and (min-width: 916px)': {
              marginBottom: 9,
            },
          }}
        >
          <Link to="/about">
            <Text
              sx={{
                fontSize: '16px',
                color: 'text',
                fontFamily: 'inter',
                textAlign: 'center',
                mr: '1em'
              }}
            >
              About
          </Text>
          </Link>
          <a href="https://github.com/luisFilipePT/github-covid-finder" target="_blank" rel="noopener noreferrer">
            <Text sx={{color: 'text', marginTop: '4px'}}>
              <GithubIcon />
            </Text>
          </a>
          <Button sx={{
            fontFamily: 'inter',
            marginLeft: '24px',
            cursor: 'pointer'
          }} 
          variant='selectTheme'
          onClick={e => {
            setColorMode(colorMode === 'default' ? 'dark' : 'default')
          }}>
            {colorMode === 'default' ? 'Dark' : 'Light'}
          </Button>
        </Flex>
      </Flex>
    </Box>
  )
}
Example #24
Source File: sidebar-item.js    From medusa with MIT License 4 votes vote down vote up
SideBarItem = ({ item }) => {
  const {
    openSection,
    openSections,
    currentHash,
    currentSection,
    goTo,
  } = useContext(NavigationContext)
  const [isOpen, setIsOpen] = useState(false);
  const { section } = item
  const subItems = section.paths
    .map(p => {
      return p.methods
    })
    .reduce((pre, cur) => {
      return pre.concat(cur)
    })
    .map(m => {
      return {
        title: m.summary,
        path: convertToKebabCase(m.summary),
      }
    })

  const handleClick = () => {
    const id = convertToKebabCase(section.section_name)
    const element = document.querySelector(`#${id}`)
    if (element) {
      element.scrollIntoView()
      if (!openSections.includes(id)) {
        openSection({id, section})
      }
    }
  }

  const handleSubClick = path => {
    const id = convertToKebabCase(section.section_name)
    goTo({ section: id, method: path, sectionObj: section })
  }

  useEffect(() => {
    setIsOpen(currentSection === convertToKebabCase(section.section_name) ||
    openSections.includes(convertToKebabCase(section.section_name)));
  }, [section.section_name, currentSection, openSections])

  return (
    <Container id={`nav-${convertToKebabCase(section.section_name)}`}>
      <StyledCollapsible
        trigger={
          <Flex
            sx={{
              fontSize: "1",
              pl: "16px",
              pr: "10px",
              alignItems: "center",
              borderRadius: "small",
              cursor: "pointer",
              mr: "4px",
              mb: "5px",
              height: "25px",
              justifyContent: "space-between",
              "&:hover, &.active": {
                backgroundColor: "primary",
                color: "light"
              },
              "&:hover svg, &.active svg": {
                color: "light"
              }
            }}
            className={
              currentSection === convertToKebabCase(section.section_name)
                ? "active"
                : null
            }
          >
            {section.section_name} <ChevronDown fill={"light"} />
          </Flex>
        }
        open={isOpen}
        onTriggerOpening={handleClick}
        transitionTime={1}
      >
        {subItems.map((si, i) => {
          const path = convertToKebabCase(si.path)
          return (
            <Flex
              key={i}
              className={currentHash === path ? "active" : null}
              onClick={() => handleSubClick(path)}
              id={`nav-${path}`}
              sx={{
                ml: "10px",
                pl: "10px",
                pr: "10px",
                alignItems: "center",
                borderRadius: "small",
                cursor: "pointer",
                mb: "8px",
                textDecoration: "none",
                color: "text",
                height: "25px",
                "&:hover": {
                  backgroundColor: "primary",
                  color: "light"
                },
                "&.active": {
                  backgroundColor: "primary",
                  color: "light"
                },
              }}
            >
              <Text
                sx={{
                  fontSize: "0",
                }}
              >
                {si.title}
              </Text>
            </Flex>
          )
        })}
      </StyledCollapsible>
    </Container>
  )
}
Example #25
Source File: index.js    From github-covid-finder with MIT License 4 votes vote down vote up
Index = () => {
  const refSearch = useRef(null)
  const [repos, setRepos] = useState(null)
  const [totalResults, setTotalResults] = useState(null)
  const [isFetchingData, setIsFetchingData] = useState(true)
  const [isShowModal, setIsShowModal] = useState(false)
  const [searchState, dispatch] = useReducer(reducer, INITIAL_STATE)
  const previousSearchState = usePrevious({ ...searchState })
  const [colorMode, _setColorMode] = useColorMode()

  useEffect(() => {
    const fetchDataAndSetState = async () => {
      const data = await fetchData(searchState)

      if (data) {
        setRepos(data)
        setTotalResults(data.total_count)
      }

      setIsFetchingData(false)
    }

    // Avoid request while developing
    if (process.env.NODE_ENV === 'development') {
      setRepos(mockRepos)
      setIsFetchingData(false)
      return
    }

    fetchDataAndSetState()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchState])

  const onSearchChange = field => e => {
    if (searchState.page * 30 < totalResults && field === 'pageUp') {
      scrollTo('#wrapper')
      dispatch({ type: field, payload: searchState.page + 1 })
      return
    }

    if (searchState.page > 1 && field === 'pageDown') {
      scrollTo('#wrapper')
      dispatch({ type: field, payload: searchState.page - 1 })
      return
    }
  }

  const onSearchIconClick = async (input, stars, language) => {
    dispatch({ type: 'search', payload: input })
    dispatch({ type: 'sort', payload: stars })
    dispatch({ type: 'filter', payload: language })

    if (
      previousSearchState.term === searchState.term &&
      previousSearchState.sort === searchState.sort &&
      previousSearchState.filter === searchState.filter
    ) {
      return
    }

    setIsFetchingData(true)

    if (isShowModal) {
      setIsShowModal(false)
    }

    const data = await fetchData(searchState)

    if (data) {
      setRepos(data)
      setTotalResults(data.total_count)
    }

    setIsFetchingData(false)
  }

  const toggleModal = () => {
    setIsShowModal(!isShowModal)
  }

  const searchCompProps = {
    searchState,
    onSearchIconClick,
    onSortChange: onSearchChange('sort'),
    onSearchChange: onSearchChange('search'),
    onFilterChange: onSearchChange('filter'),
  }

  return (
    <>
      <Layout
        isShowSearch
        isShowModal={isShowModal}
        toggleModal={toggleModal}
        searchCompProps={searchCompProps}
      >
        <SEO />
        <span id="wrapper" ref={refSearch} />
        {isFetchingData ? (
          <Spinner
            color="rgb(255, 65, 54)"
            sx={{
              top: '50%',
              left: '50%',
              position: 'absolute',
              transform: 'translate(-50%, -50%)',
            }}
          />
        ) : repos.items.length > 0 ? (
          <>
            <Grid columns={[1, 1, 1, 3]}>
              {repos.items.map(repo => (
                <RepoCard key={repo.id} repo={repo} />
              ))}
            </Grid>
            <Pagination
              pageUp={onSearchChange('pageUp')}
              pageDown={onSearchChange('pageDown')}
              currentPage={searchState.page}
              totalResults={totalResults}
            />
          </>
        ) : (
          <Box
            sx={{
              top: '50%',
              left: '50%',
              position: 'absolute',
              transform: 'translate(-50%, -50%)',
            }}
          >
            <Text
              sx={{
                fontSize: 22,
                fontFamily: 'inter',
              }}
            >
              No result found
            </Text>
          </Box>
        )}
      </Layout>
      <Flex id="modal" className={isShowModal ? 'active' : null}>
        <Flex
          p="16px"
          bg={
            colorMode === 'dark'
              ? 'rgba(64,64,64,0.9)'
              : 'rgba(255,255,255,0.7)'
          }
          sx={{
            maxWidth: 660,
            margin: 'auto',
            borderRadius: 6,
            alignItems: 'flex-end',
            flexDirection: 'column',
            '@media only screen and (max-width: 425px)': {
              width: 360,
            },
            '@media only screen and (max-width: 320px)': {
              width: 300,
            },
          }}
        >
          <Search {...searchCompProps} />
          <Button
            mt="8px"
            backgroundColor="rgb(186, 65, 54)"
            onClick={toggleModal}
            sx={{
              fontFamily: 'inter',
            }}
          >
            Close
          </Button>
        </Flex>
      </Flex>
    </>
  )
}
Example #26
Source File: method.js    From medusa with MIT License 4 votes vote down vote up
Method = ({ data, section, sectionData, pathname, api }) => {
  const { parameters, requestBody, description, method, summary } = data
  const jsonResponse = data.responses[0].content?.[0].json
  const { updateHash, updateMetadata } = useContext(NavigationContext)
  const methodRef = useRef(null)
  const [containerRef, isInView] = useInView({
    root: null,
    rootMargin: "0px 0px -80% 0px",
    threshold: 0,
  })
  const formattedParameters = formatMethodParams({ parameters, requestBody })

  useEffect(() => {
    if (isInView) {
      updateHash(section, convertToKebabCase(summary), sectionData)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isInView])

  const handleMetaChange = () => {
    updateMetadata({
      title: summary,
      description: description,
    })
    if (methodRef.current) {
      methodRef.current.scrollIntoView({
        behavior: "smooth",
      })
    }
  }

  const getExampleValues = (type, defaultExample) => {
    switch (type) {
      case "integer":
        return 1000
      case "boolean":
        return false
      case "object":
        return {}
      default:
        return defaultExample
    }
  }

  // extract required properties or a non-required property from a json object
  // based on the extraction method "getPropertyFromObject"
  const getPropertiesFromObject = (
    requiredProperties,
    properties,
    obj,
    res,
    getPropertyFromObject
  ) => {
    for (const element of requiredProperties) {
      try {
        res[element.property] = getPropertyFromObject(obj, element.property)
      } catch (err) {}
    }

    // if (Object.keys(res) === requiredProperties.map((p) => p.property)) {
    //   return res
    // }

    for (const element of properties) {
      try {
        res[element.property] = getPropertyFromObject(obj, element.property)
        break
      } catch (err) {}
    }

    return res
  }

  const getCurlJson = (properties, prefix, bodyParameters) => {
    if (!properties[0] || !jsonResponse) {
      return
    }
    const jsonObject = JSON.parse(jsonResponse)
    const pathParts = pathname.split("/")
    const requiredProperties = bodyParameters.filter((p) => p.required)

    let res = {}

    // if the endpoint is for a relation i.e. /orders/:id/shipment drill down into the properties of the json object
    if (pathParts.length > 3) {
      const propertyIndex = pathParts[2].match(/{[A-Za-z_]+}/) ? 3 : 2

      try {
        const obj =
          jsonObject[pathParts[propertyIndex].replace("-", "_")] ||
          jsonObject[Object.keys(jsonObject)[0]][
            pathParts[propertyIndex].replace("-", "_")
          ]

        res = getPropertiesFromObject(
          requiredProperties,
          properties,
          obj,
          res,
          (obj, property) =>
            Array.isArray(obj)
              ? obj.find((o) => o[property])[property]
              : obj[property]
        )
      } catch (err) {}
    }

    // if nothing was found drilling down look at the top level properties
    if (JSON.stringify(res) === "{}") {
      res = getPropertiesFromObject(
        requiredProperties,
        properties,
        jsonObject,
        res,
        (jsonObject, property) =>
          jsonObject[property] ||
          jsonObject[Object.keys(jsonObject)[0]][property]
      )
    }

    // Last resort, set the first property to an example
    if (JSON.stringify(res) === "{}") {
      res[properties[0].property] = getExampleValues(properties[0].type, `${prefix}_${properties[0].property}`)
    }

    // Add values to 'undefined' properties before returning due to JSON.stringify removing 'undefined' but not 'null'
    return requiredProperties.reduce((prev, curr) => {
        if(prev[curr.property] === undefined){
          prev[curr.property] = getExampleValues(curr.type, `${prefix}_${curr.property}`)
        }
        return prev
      }, res)
  }

  const getCurlCommand = (requestBody) => {
    const body = JSON.stringify(
      getCurlJson(
        requestBody.properties,
        `example_${section}`,
        formattedParameters.body
      )
    )
    return `curl -X ${data.method.toUpperCase()} https://medusa-url.com/${api}${formatRoute(
      pathname
    )} \\
  --header "Authorization: Bearer <ACCESS TOKEN>" ${
    data.method.toUpperCase() === "POST" && requestBody.properties?.length > 0
      ? `\\
  --header "content-type: application/json" \\
  --data '${body}'`
      : ""
  }`
  }

  return (
    <Flex
      py={"5vw"}
      sx={{
        borderTop: "hairline",
        flexDirection: "column",
      }}
      id={convertToKebabCase(summary)}
      ref={methodRef}
    >
      <Flex>
        <Heading
          as="h2"
          mb={4}
          sx={{
            fontSize: "4",
            fontWeight: "500",
            cursor: "pointer",
          }}
          ref={containerRef}
          onClick={() => handleMetaChange()}
        >
          {summary}
        </Heading>
      </Flex>
      <ResponsiveContainer>
        <Flex
          className="info"
          sx={{
            flexDirection: "column",
            pr: "5",
            "@media screen and (max-width: 848px)": {
              pr: "0",
            },
          }}
        >
          <Route path={pathname} method={method} />
          <Description>
            <Text
              sx={{
                lineHeight: "26px",
              }}
              mt={3}
            >
              <Markdown>{description}</Markdown>
            </Text>
          </Description>
          <Box mt={2}>
            <Parameters params={formattedParameters} type={"Parameters"} />
          </Box>
        </Flex>
        <Box className="code">
          <Box>
            <JsonContainer
              json={getCurlCommand(requestBody)}
              header={"cURL Example"}
              language={"shell"}
              allowCopy={true}
              method={convertToKebabCase(summary)}
            />
          </Box>
          <Box>
            <JsonContainer
              json={jsonResponse}
              header={"RESPONSE"}
              method={convertToKebabCase(summary)}
            />
          </Box>
        </Box>
      </ResponsiveContainer>
    </Flex>
  )
}
Example #27
Source File: LibrariesSdks.js    From developer-portal with Apache License 2.0 4 votes vote down vote up
LibrariesSdks = () => {
  const daijsCode = `import Maker from '@makerdao/dai';

  const maker = 
    await Maker.create('http', {
    url: myRpcUrl,
    privateKey: myPrivateKey
  });

  const vault = 
    await maker
      .service('mcd:cdpManager')
      .openLockAndDraw(
        'ETH-A', ETH(50), DAI(1000)
      );`;
  return (
    <Container>
      <Heading variant="largeHeading" pb={3}>
        Libraries
      </Heading>
      <Grid columns={[1, '1fr auto']} sx={{ gridColumnGap: 4, gridRowGap: [4, 'auto'] }}>
        <CodeWindow code={daijsCode} />
        <Grid columns={[1, 'auto', 2]} sx={{ gridRowGap: 3, gridTemplateRows: '2em' }}>
          <Heading variant="smallHeading">Dai.js</Heading>
          <Flex
            sx={{
              flexDirection: 'column',
              gridRowStart: 2,
              justifyContent: 'space-between',
              pb: [4, 0],
            }}
          >
            <Flex sx={{ flexDirection: 'column', color: 'onBackgroundMuted' }}>
              <Text
                variant="plainText"
                sx={{
                  pb: 2,
                }}
              >
                <InlineTextarea name="sdksAndToolsHeading" />
              </Text>
              <Text>
                <InlineTextarea name="sdksAndToolsText" />
              </Text>
            </Flex>
            <Link href="/documentation/introduction-to-dai-js">
              <Flex sx={{ alignItems: 'center', py: [3, 3, 0] }}>
                <Icon sx={{ mr: 2 }} color="primary" name={'arrow_right'}></Icon>
                <ThemeLink>View Dai.js docs</ThemeLink>
              </Flex>
            </Link>
          </Flex>
          <Flex
            sx={{
              flexDirection: 'column',
              gridRowStart: ['auto', 4, 2],
              gridColumnStart: [1, 1, 2],
            }}
          >
            <Flex
              sx={{
                flexDirection: 'column',
                color: 'onBackgroundMuted',
              }}
            >
              <Text sx={{ pb: 2, fontSize: [4, 5] }}>
                <InlineTextarea name="pyMakerHeading" />
              </Text>
              <Text>
                <InlineTextarea name="pyMakerSubtext" />
              </Text>
            </Flex>
            <Link href="/documentation/pymaker">
              <Flex sx={{ alignItems: 'center', py: [3, 3, 4] }}>
                <Icon sx={{ mr: 2 }} color="primary" name={'arrow_right'}></Icon>
                <ThemeLink>View pyMaker docs</ThemeLink>
              </Flex>
            </Link>
          </Flex>
        </Grid>
      </Grid>

      <Grid
        columns={[1, 'auto', 3]}
        sx={{
          pt: 4,
        }}
      >
        <Heading
          variant="largeHeading"
          sx={{ py: 4, gridColumnStart: [1, 2], gridColumnEnd: [2, 4] }}
        >
          <InlineTextarea name="toolsHeading" />
        </Heading>
        <Flex
          sx={{
            flexDirection: 'column',
            gridColumnStart: [1, 2],
          }}
        >
          <Icon name="keeper" color="textMuted" sx={{ width: '164px', height: '164px', mb: 4 }} />
          <Heading>Keepers</Heading>
          <Text sx={{ py: 3, color: 'onBackgroundMuted' }}>
            <InlineTextarea name="keepersSubtext" />
          </Text>
          <Link href="/documentation/introduction-to-auction-keepers">
            <Flex sx={{ alignItems: 'center' }}>
              <Icon sx={{ mr: 2 }} color="primary" name={'arrow_right'}></Icon>
              <ThemeLink>Learn more about Maker Keepers</ThemeLink>
            </Flex>
          </Link>
        </Flex>
        <Flex
          sx={{
            flexDirection: 'column',
            gridColumnStart: [1, 3],
            mt: [4, 0],
          }}
        >
          <Icon
            name="wireframeGlobe"
            color="textMuted"
            sx={{ width: '164px', height: '164px', mb: 4 }}
          />
          <Heading>CLIs</Heading>
          <Text sx={{ py: 3, color: 'onBackgroundMuted' }}>
            <InlineTextarea name="CLIsSubtext" />
          </Text>
          <Link href="/documentation/mcd-cli">
            <Flex sx={{ alignItems: 'center', mt: 'auto' }}>
              <Icon sx={{ mr: 2 }} color="primary" name={'arrow_right'}></Icon>
              <ThemeLink>Learn more about the CLIs</ThemeLink>
            </Flex>
          </Link>
        </Flex>
      </Grid>
    </Container>
  );
}