prism-react-renderer#defaultProps JavaScript Examples

The following examples show how to use prism-react-renderer#defaultProps. 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: object-props.jsx    From MDXP with MIT License 6 votes vote down vote up
ObjectProps = ({of: object, include, exclude, transform, pre='', post=''}) => {
  const {themeConfig} = useConfig();
  const filter = filterProperties(include, exclude);
  const code = (pre + stringifyObject(object, {indent: '  ', filter, transform}) + post).trim();

  return (
    <Highlight {...defaultProps} theme={themeConfig.prism.light} code={code} language='js'>
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <Styled.pre className={className} style={style}>
          {tokens.map((line, i) => (
            <div {...getLineProps({ line, key: i })}>
              {line.map((token, key) => (
                <span {...getTokenProps({ token, key })} />
              ))}
            </div>
          ))}
        </Styled.pre>
      )}
    </Highlight>
  );
}
Example #2
Source File: Code.jsx    From intergalactic with MIT License 6 votes vote down vote up
export default function ({ children, lang, block, ...others }) {
  return (
    <Highlight {...defaultProps} code={children} language={lang} theme={theme}>
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre
          {...others}
          className={styles.pre}
          style={{ ...style, display: block ? 'block' : 'inline-block' }}
        >
          {tokens.map((line, i) => (
            <div {...getLineProps({ line, key: i })}>
              {line.map((token, key) => {
                const { className, ...other } = getTokenProps({ token, key });
                return <span {...other} />;
              })}
            </div>
          ))}
        </pre>
      )}
    </Highlight>
  );
}
Example #3
Source File: Editor.jsx    From filbert-js with MIT License 6 votes vote down vote up
Editor = ({ code = '' }) => (
  <Highlight {...defaultProps} theme={theme} code={code.trim()} language="jsx">
    {({ className, style, tokens, getLineProps, getTokenProps }) => (
      <Pre className={className} style={style}>
        {tokens.map((line, i) => (
          <Line key={i} {...getLineProps({ line, key: i })}>
            <LineNo>{i + 1}</LineNo>
            <LineContent>
              {line.map((token, key) => (
                <span key={key} {...getTokenProps({ token, key })} />
              ))}
            </LineContent>
          </Line>
        ))}
      </Pre>
    )}
  </Highlight>
)
Example #4
Source File: explainer.js    From use-shopping-cart with MIT License 6 votes vote down vote up
Explainer = ({ title, description, code }) => {
  return (
    <div className={styles.explainerWrapper}>
      <div className={styles.explainerText}>
        <h2>{title}</h2>
        <p>{description}</p>
      </div>
      <Highlight {...defaultProps} code={code} language="jsx">
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className} style={style}>
            {tokens.map((line, i) => (
              <div {...getLineProps({ line, key: i })}>
                {line.map((token, key) => (
                  <span {...getTokenProps({ token, key })} />
                ))}
              </div>
            ))}
          </pre>
        )}
      </Highlight>
    </div>
  )
}
Example #5
Source File: Json.jsx    From api-request-builder-open-src with MIT License 6 votes vote down vote up
render () {
        let exampleCode = JSON.stringify(this.props.json, null, '  ');
        return <div id="sdk">
            <Highlight {...defaultProps} code={exampleCode} 
                theme={undefined} language="json">
                {({ className, style, tokens, getLineProps, getTokenProps }) => (
                <><pre className={className} style={style}>
                    {tokens.map((line, i) => (
                    <div {...getLineProps({ line, key: i })}>
                        {line.map((token, key) => (
                        <span {...getTokenProps({ token, key })} />
                        ))}
                    </div>
                    ))}
                </pre>
                <p><b>Note:</b> To use the JSON format, remove all <b>filename</b> attributes and replace
                with the <b>documentBase64</b> attribute. The filename attribute is only used by the
                API Request Builder application.
                </p></>
                )}
            </Highlight>
        </div>
    }
Example #6
Source File: Sdk.jsx    From api-request-builder-open-src with MIT License 6 votes vote down vote up
render () {
        /**
         * Props:   maxWidth
                    appObject
                    json
                    sdk
                    sdkLanguage
                    sdkLanguageName
         */

        if (this.props.json && this.props.json.block_error) {
            return <div id="sdk" className="Status Status_error Status_bold">
                {this.props.json.block_error}
            </div>
        } else if (this.props.sdkLanguage === this.props.appObject.langJson) {
            return <Json json={this.props.json} />
        } else if (this.props.sdk) {
            return <div id="sdk" style={{maxWidth: this.props.maxWidth}}>
                <Highlight {...defaultProps} code={this.props.sdk} 
                    theme={undefined} language="javascript">
                    {({ className, style, tokens, getLineProps, getTokenProps }) => (
                    <pre className={className} style={style}>
                        {tokens.map((line, i) => (
                        <div {...getLineProps({ line, key: i })}>
                            {line.map((token, key) => (
                            <span {...getTokenProps({ token, key })} />
                            ))}
                        </div>
                        ))}
                    </pre>
                    )}
                </Highlight>
            </div>
        } else {
            return null
        }
    }
Example #7
Source File: CodeBlock.js    From react-nice-dates with MIT License 6 votes vote down vote up
export default function CodeBlock({ code, language }) {
  return (
    <Highlight {...defaultProps} code={code.trim()} language={language} theme={theme}>
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre className={className} style={style}>
          {tokens.map((line, i) => (
            <div {...getLineProps({ line })} key={i}>
              {line.map((token, key) => (
                <span {...getTokenProps({ token })} key={key} />
              ))}
            </div>
          ))}
        </pre>
      )}
    </Highlight>
  )
}
Example #8
Source File: PrismSetup.js    From starter-project-gatsby-mdx-blog-course-project with MIT License 6 votes vote down vote up
PrismWrapper = props => {
  const className = props.children.props.className
  const language = className.split("-")[1]

  return (
    <Highlight
      {...defaultProps}
      code={props.children.props.children.trim()}
      language={language}
      theme={theme}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => {
        return (
          <Container>
            <Pre className={className} style={style}>
              <div className="code-tab">{language}</div>
              {tokens.map((line, i) => (
                <div {...getLineProps({ line, key: i })}>
                  {line.map((token, key) => (
                    <span {...getTokenProps({ token, key })} />
                  ))}
                </div>
              ))}
            </Pre>
          </Container>
        )
      }}
    </Highlight>
  )
}
Example #9
Source File: index.js    From MDXP with MIT License 6 votes vote down vote up
CodeHighlight = ({children, language, className: outerClassName}) => {
  const theme = useConfig().themeConfig.prism.light;
  
  return (
    <Highlight
      {...defaultProps}
      code={children.trim()}
      language={language}
      theme={theme}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <Styled.pre
          className={`${outerClassName || ''} ${className}`}
          style={{ ...style, overflowX: 'auto' }}
          data-testid="code"
        >
          {tokens.map((line, i) => (
            <div {...getLineProps({ line, key: i })}>
              {line.map((token, key) => (
                <span
                  {...getTokenProps({ token, key })}
                  sx={{ display: 'inline-block' }}
                />
              ))}
            </div>
          ))}
        </Styled.pre>
      )}
    </Highlight>
  );
}
Example #10
Source File: index.js    From r3f-website with MIT License 5 votes vote down vote up
export default function CodeHighlight({
  children,
  className,
  live,
  title,
  lineNumbers,
}) {
  const [copied, setCopied] = useState(false);
  const codeString = children.trim();
  const language = className.replace(/language-/, "");

  if (live) {
    return (
      <LiveProvider
        code={codeString}
        noInline
        theme={theme}
        transformCode={(code) => `/** @jsx mdx */${code}`}
        scope={{ mdx, Canvas }}
      >
        <LiveWrapper>
          <StyledEditor>
            <LiveEditor />
          </StyledEditor>
          <LivePreview />
        </LiveWrapper>

        <LiveError />
      </LiveProvider>
    );
  }

  const handleClick = () => {
    setCopied(true);
    copyToClipboard(codeString);
  };

  return (
    <>
      {title && <PreHeader>{title}</PreHeader>}
      <div className="gatsby-highlight">
        <Highlight
          {...defaultProps}
          code={codeString}
          language={language}
          theme={theme}
        >
          {({
            className: blockClassName,
            style,
            tokens,
            getLineProps,
            getTokenProps,
          }) => (
            <Pre className={blockClassName} style={style} hasTitle={title}>
              <CopyCode onClick={handleClick}>
                {copied ? "Copied!" : "Copy"}
              </CopyCode>
              <code>
                {tokens.map((line, i) => (
                  <div {...getLineProps({ line, key: i })}>
                    {lineNumbers && <LineNo>{i + 1}</LineNo>}
                    {line.map((token, key) => (
                      <span {...getTokenProps({ token, key })} />
                    ))}
                  </div>
                ))}
              </code>
            </Pre>
          )}
        </Highlight>
      </div>
    </>
  );
}
Example #11
Source File: codeBlock.js    From learningHub with MIT License 5 votes vote down vote up
CodeBlock = ({ children: exampleCode, ...props }) => {
  if (props['react-live']) {
    return <LoadableComponent code={exampleCode} />;
  } else {
    return (
      <Highlight {...defaultProps} code={exampleCode} language="javascript" theme={prismTheme}>
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className + ' pre'} style={style} p={3}>
            {cleanTokens(tokens).map((line, i) => {
              let lineClass = {};

              let isDiff = false;

              if (line[0] && line[0].content.length && line[0].content[0] === '+') {
                lineClass = { backgroundColor: 'rgba(76, 175, 80, 0.2)' };
                isDiff = true;
              } else if (line[0] && line[0].content.length && line[0].content[0] === '-') {
                lineClass = { backgroundColor: 'rgba(244, 67, 54, 0.2)' };
                isDiff = true;
              } else if (line[0] && line[0].content === '' && line[1] && line[1].content === '+') {
                lineClass = { backgroundColor: 'rgba(76, 175, 80, 0.2)' };
                isDiff = true;
              } else if (line[0] && line[0].content === '' && line[1] && line[1].content === '-') {
                lineClass = { backgroundColor: 'rgba(244, 67, 54, 0.2)' };
                isDiff = true;
              }
              const lineProps = getLineProps({ line, key: i });

              lineProps.style = lineClass;
              const diffStyle = {
                userSelect: 'none',
                MozUserSelect: '-moz-none',
                WebkitUserSelect: 'none',
              };

              let splitToken;

              return (
                <div {...lineProps} key={line + i}>
                  {line.map((token, key) => {
                    if (isDiff) {
                      if (
                        (key === 0 || key === 1) &
                        (token.content.charAt(0) === '+' || token.content.charAt(0) === '-')
                      ) {
                        if (token.content.length > 1) {
                          splitToken = {
                            types: ['template-string', 'string'],
                            content: token.content.slice(1),
                          };
                          const firstChar = {
                            types: ['operator'],
                            content: token.content.charAt(0),
                          };

                          return (
                            <React.Fragment key={token + key}>
                              <span
                                {...getTokenProps({ token: firstChar, key })}
                                style={diffStyle}
                              />
                              <span {...getTokenProps({ token: splitToken, key })} />
                            </React.Fragment>
                          );
                        } else {
                          return <span {...getTokenProps({ token, key })} style={diffStyle} />;
                        }
                      }
                    }
                    return <span {...getTokenProps({ token, key })} />;
                  })}
                </div>
              );
            })}
          </pre>
        )}
      </Highlight>
    );
  }
}
Example #12
Source File: code.jsx    From litmus-docs with Apache License 2.0 5 votes vote down vote up
CodeBlock = ({ type, code, title }) => {
  // copyToClipboard(e) {
  // 	const el = e.target.parentElement.nextElementSibling
  // 	el.focus()
  // 	let range = document.createRange()
  // 	try {
  // 		range.selectNode(el)
  // 		const sel = window.getSelection()
  // 		sel.removeAllRanges()
  // 		sel.addRange(range)
  // 		document.execCommand('copy')
  // 		if (sel.removeRange) {
  // 			sel.removeRange(range)
  // 		} else {
  // 			sel.removeAllRanges()
  // 		}
  // 	} catch (err) {
  // 		console.error('Copy to Clipboar Error:', err)
  // 	}
  // }

  // render() {
  // 	const { title, type } = this.props
  // 	const code = this.props.code || ''

  return (
    <div className="code">
      <div className="titleGroup">
        <img src="../../../static/img/code_block_header.svg" alt="hii" />
        <div className="title">Terminal</div>

        <button className="copyBtn">
          <img src="../../../static/img/copy.svg" alt="hii" />
        </button>
      </div>
      <div className="coding">
        <Highlight {...defaultProps} className="line-numbers" theme={theme} code={code.trim()} language={type || 'js'}>
          {({ className, style, tokens, getLineProps, getTokenProps }) => (
            <pre className="line-numbers">
              {tokens.map((line, i) => (
                <div {...getLineProps({ line, key: i })}>
                  {line.map((token, key) => (
                    <span {...getTokenProps({ token, key })} />
                  ))}
                </div>
              ))}
            </pre>
          )}
        </Highlight>
      </div>
    </div>
  )
}
Example #13
Source File: index.js    From usepandas with MIT License 5 votes vote down vote up
CodeHighlight.defaultProps = {
  live: false,
  title: null,
  lineNumbers: null,
};
Example #14
Source File: index.js    From r3f-website with MIT License 5 votes vote down vote up
CodeHighlight.defaultProps = {
  live: false,
  title: null,
  lineNumbers: null,
};
Example #15
Source File: CodeBlock.js    From react-nice-dates with MIT License 5 votes vote down vote up
CodeBlock.defaultProps = {
  language: 'jsx'
}
Example #16
Source File: index.js    From royalhackaway.com with MIT License 5 votes vote down vote up
SiteCodeBlock = ({ children = "", className = "" }) => {
  const [, language, paramString] = LANGUAGE_PARSER.exec(
    children.props.className
  )

  const params = paramString?.split(",") || []
  const enableLineNumbers = params.includes("number")

  return (
    <Highlight
      {...defaultProps}
      code={children.props.children}
      language={language}
      theme={vsDarkTheme}
    >
      {({ newClassName, style, tokens, getLineProps, getTokenProps }) => (
        <pre
          className={CombineStyles(
            newClassName,
            siteCodeBlockClass,
            enableLineNumbers && siteCodeBlockWithNumbersClass
          )}
          style={style}
        >
          {tokens.map((line, i) => (
            <>
              {enableLineNumbers && (
                <div className={siteCodeBlockLineNumberClass}>{i + 1}</div>
              )}
              <div className={siteCodeBlockLineContentClass}>
                {line.map((token, key) => (
                  <span key={key} {...getTokenProps({ token, key })} />
                ))}
              </div>
            </>
          ))}
        </pre>
      )}
    </Highlight>
  )
}
Example #17
Source File: Code.js    From testnets-cardano-org with MIT License 5 votes vote down vote up
Code = ({ codeString, language, theme }) => {
  const [ isCopied, setIsCopied ] = React.useState(false)

  return (
    <Wrapper>
      <Highlight
        {...defaultProps}
        code={codeString}
        language={language}
        theme={theme}
      >
        {({ className, tokens, getLineProps, getTokenProps }) => (
          <Pre
            className={className}
          >
            <CopyButton
              onClick={() => {
                copyToClipboard(codeString)
                setIsCopied(true)
                setTimeout(() => setIsCopied(false), 3000)
              }}
            >
              {isCopied ? '? Copied!' : 'Copy'}
            </CopyButton>

            {tokens.map((line, i) => (
              <div key={i} {...getLineProps({ line, key: i })}>
                {line.map((token, key) => (
                  <span key={key} {...getTokenProps({ token, key })} />
                ))}
              </div>
            ))}
          </Pre>
        )}
      </Highlight>
      <ConfettiWrapper>
        <Confetti active={isCopied} config={config} />
      </ConfettiWrapper>
    </Wrapper>
  )
}
Example #18
Source File: theme.js    From nextra-theme-docs with MIT License 5 votes vote down vote up
Code = ({ children, className, highlight, ...props }) => {
  if (!className) return <code {...props}>{children}</code>

  const highlightedLines = highlight ? highlight.split(',').map(Number) : []

  // https://mdxjs.com/guides/syntax-highlighting#all-together
  const language = className.replace(/language-/, '')
  return (
    <Highlight
      {...defaultProps}
      code={children.trim()}
      language={language}
      theme={THEME}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <code className={className} style={{ ...style }}>
          {tokens.map((line, i) => (
            <div
              key={i}
              {...getLineProps({ line, key: i })}
              style={
                highlightedLines.includes(i + 1)
                  ? {
                      background: '#cce0f5',
                      margin: '0 -1rem',
                      padding: '0 1rem',
                    }
                  : null
              }
            >
              {line.map((token, key) => (
                <span key={key} {...getTokenProps({ token, key })} />
              ))}
            </div>
          ))}
        </code>
      )}
    </Highlight>
  )
}
Example #19
Source File: controls.js    From rgm with MIT License 4 votes vote down vote up
React.memo(
  props => {
    return (
      <div
        css={css`
          pre[class*='language-'],
          code[class*='language-'] {
            color: #d4d4d4;
            font-size: 0.8rem;
            text-shadow: none;
            font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono',
              monospace;
            direction: ltr;
            text-align: left;
            white-space: pre;
            word-spacing: normal;
            word-break: normal;
            line-height: 1.5;
            -moz-tab-size: 4;
            -o-tab-size: 4;
            tab-size: 4;
            -webkit-hyphens: none;
            -moz-hyphens: none;
            -ms-hyphens: none;
            hyphens: none;
          }

          pre[class*='language-']::selection,
          code[class*='language-']::selection {
            text-shadow: none;
            background: #b3d4fc;
          }

          @media print {
            pre[class*='language-'],
            code[class*='language-'] {
              text-shadow: none;
            }
          }

          pre[class*='language-'] {
            padding: 1em;
            margin: 0;
            overflow: auto;
            background: #1e1e1e;
          }

          :not(pre) > code[class*='language-'] {
            padding: 0.1em 0.3em;
            border-radius: 0.3em;
            color: #db4c69;
            background: #f9f2f4;
          }

          .namespace {
            opacity: 0.7;
          }

          .token.comment,
          .token.prolog,
          .token.doctype,
          .token.cdata {
            color: #6a9955;
          }

          .token.punctuation {
            color: #d4d4d4;
          }

          .token.property,
          .token.tag,
          .token.boolean,
          .token.number,
          .token.constant,
          .token.symbol,
          .token.deleted {
            color: #b5cea8;
          }

          .token.selector,
          .token.attr-name,
          .token.string,
          .token.char,
          .token.builtin,
          .token.inserted {
            color: #7dd823;
          }

          .token.operator,
          .token.entity,
          .token.url,
          .language-css .token.string,
          .style .token.string {
            color: #d4d4d4;
            background: #1e1e1e;
          }

          .token.atrule,
          .token.attr-value,
          .token.keyword {
            color: #ff4d00;
          }

          .token.function {
            color: #ffe33d;
          }

          .token.regex,
          .token.important,
          .token.variable {
            color: #d16969;
          }

          .token.important,
          .token.bold {
            font-weight: bold;
          }

          .token.italic {
            font-style: italic;
          }

          .token.constant {
            color: #9cdcfe;
          }

          .token.class-name {
            color: #4ec9b0;
          }

          .token.parameter {
            color: #9cdcfe;
          }

          .token.interpolation {
            color: #9cdcfe;
          }

          .token.punctuation.interpolation-punctuation {
            color: #569cd6;
          }

          .token.boolean {
            color: #569cd6;
          }

          .token.property {
            color: #9cdcfe;
          }

          .token.selector {
            color: #d7ba7d;
          }

          .token.tag {
            color: #ff5bd7;
          }

          .token.attr-name {
            color: #9cdcfe;
          }

          .token.attr-value {
            color: #ce9178;
          }

          .token.entity {
            color: #4ec9b0;
            cursor: unset;
          }

          .token.namespace {
            color: #4ec9b0;
          }

          .token-line {
            min-height: 12px;
          }

          pre[class*='language-javascript'],
          code[class*='language-javascript'] {
            color: #4ec9b0;
          }

          pre[class*='language-css'],
          code[class*='language-css'] {
            color: #ce9178;
          }

          pre[class*='language-html'],
          code[class*='language-html'] {
            color: #d4d4d4;
          }

          .language-html .token.punctuation {
            color: #808080;
          }
          /*********************************************************
* Line highlighting
*/
          pre[data-line] {
            position: relative;
          }

          pre[class*='language-'] > code[class*='language-'] {
            position: relative;
            z-index: 1;
          }

          .line-highlight {
            position: absolute;
            left: 0;
            right: 0;
            padding: inherit 0;
            margin-top: 1em;
            background: #f7ebc6;
            box-shadow: inset 5px 0 0 #f7d87c;
            z-index: 0;
            pointer-events: none;
            line-height: inherit;
            white-space: pre;
          }
        `}
      >
        <Highlight
          {...defaultProps}
          code={props.children}
          language="jsx"
          theme={undefined}
        >
          {({ className, style, tokens, getLineProps, getTokenProps }) => (
            <pre className={className} style={style}>
              {tokens.map((line, i) => (
                <div key={i} {...getLineProps({ line, key: i })}>
                  {line.map((token, key) => (
                    <span key={key} {...getTokenProps({ token, key })} />
                  ))}
                </div>
              ))}
            </pre>
          )}
        </Highlight>
      </div>
    );
  },
);
Example #20
Source File: WTCode.js    From walkthru with MIT License 4 votes vote down vote up
function WTCode({ files, step, sameFile, config }) {
  const { focus, language, center } = step.frontmatter
  const ref = useRef()
  const active = step.frontmatter.file
  const [content, setContent] = useState('')
  const [prevScrollPos, setPrevScrollPos] = useState(0)
  const file = files.find((file) => file.path === active)
  const [activeFile, setActiveFile] = useState(file)
  const highlightedLines = focus ? getHighlightedLines(focus.toString()) : []
  useEffect(() => {
    const file = files.find((file) => file.path === active)
    setActiveFile(file)
  }, [files, step, active])
  useEffect(() => {
    let scrollPos = 0
    if (sameFile) {
      animateScroll.scrollTo(prevScrollPos, {
        containerId: 'scrollContainer',
        duration: 0,
      })
      scrollPos = ref.current.scrollTop
    }
    scrollNewCenter(center, ref.current)
    setPrevScrollPos(scrollPos)
  }, [content, center, prevScrollPos, sameFile])
  useEffect(() => {
    ref.current.scrollTo(0, 0)
  }, [])
  return (
    <>
      <WTFileBar files={files} activeFile={activeFile} config={config} />
      <Highlight
        {...defaultProps}
        theme={theme}
        code={activeFile.content}
        language={language || activeFile.path.split('.').pop()}
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => {
          return (
            <Pre
              ref={ref}
              className={`${className} ${
                highlightedLines.length ? '' : 'no-highlight'
              }`}
              id="scrollContainer"
            >
              <Code>
                <LineNumbers>
                  {tokens.map((line, i) => {
                    const lineProps = getLineProps({ line, key: i })
                    if (highlightedLines.indexOf(i + 1) > -1) {
                      lineProps.highlighted = true
                    }
                    return (
                      <div
                        style={lineProps.style}
                        key={`number-wrapper-${i.toString()}`}
                      >
                        <LineNumber
                          highlighted={lineProps.highlighted}
                          className="__line-no"
                          key={`number-${i.toString()}`}
                        >
                          {i + 1}
                        </LineNumber>
                      </div>
                    )
                  })}
                </LineNumbers>
                <Lines>
                  {tokens.map((line, i) => {
                    const lineProps = getLineProps({ line, key: i })
                    if (highlightedLines.indexOf(i + 1) > -1) {
                      lineProps.highlighted = true
                    }
                    return (
                      <Line {...lineProps} key={i.toString()}>
                        <LineContent key={`content-${i.toString()}`}>
                          {line.map((token, key) => {
                            const tokenProps = getTokenProps({ token, key })
                            if (highlightedLines.indexOf(i + 1) > -1) {
                              tokenProps.highlighted = true
                            }
                            return <Token {...tokenProps} key={`${i}-${key}`} />
                          })}
                        </LineContent>
                      </Line>
                    )
                  })}
                </Lines>
              </Code>
            </Pre>
          )
        }}
      </Highlight>
    </>
  )
}
Example #21
Source File: codeBlock.js    From cardano-documentation with MIT License 4 votes vote down vote up
CodeBlock = ({ children: exampleCode, ...props }) => {
  if (props['react-live']) {
    return <LoadableComponent code={exampleCode} />
  } else {
    return (
      <Highlight
        {...defaultProps}
        code={exampleCode}
        language="javascript"
        theme={prismTheme}
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className + ' pre'} style={style} p={3}>
            {cleanTokens(tokens).map((line, i) => {
              let lineClass = {}

              let isDiff = false

              if (
                line[0] &&
                line[0].content.length &&
                line[0].content[0] === '+'
              ) {
                lineClass = { backgroundColor: 'rgba(76, 175, 80, 0.2)' }
                isDiff = true
              } else if (
                line[0] &&
                line[0].content.length &&
                line[0].content[0] === '-'
              ) {
                lineClass = { backgroundColor: 'rgba(244, 67, 54, 0.2)' }
                isDiff = true
              } else if (
                line[0] &&
                line[0].content === '' &&
                line[1] &&
                line[1].content === '+'
              ) {
                lineClass = { backgroundColor: 'rgba(76, 175, 80, 0.2)' }
                isDiff = true
              } else if (
                line[0] &&
                line[0].content === '' &&
                line[1] &&
                line[1].content === '-'
              ) {
                lineClass = { backgroundColor: 'rgba(244, 67, 54, 0.2)' }
                isDiff = true
              }
              const lineProps = getLineProps({ line, key: i })

              lineProps.style = lineClass
              const diffStyle = {
                userSelect: 'none',
                MozUserSelect: '-moz-none',
                WebkitUserSelect: 'none',
              }

              let splitToken

              return (
                <div {...lineProps} key={line + i}>
                  {line.map((token, key) => {
                    if (isDiff) {
                      if (
                        (key === 0 || key === 1) &
                        (token.content.charAt(0) === '+' ||
                          token.content.charAt(0) === '-')
                      ) {
                        if (token.content.length > 1) {
                          splitToken = {
                            types: ['template-string', 'string'],
                            content: token.content.slice(1),
                          }
                          const firstChar = {
                            types: ['operator'],
                            content: token.content.charAt(0),
                          }

                          return (
                            <React.Fragment key={token + key}>
                              <span
                                {...getTokenProps({ token: firstChar, key })}
                                style={diffStyle}
                              />
                              <span
                                {...getTokenProps({ token: splitToken, key })}
                              />
                            </React.Fragment>
                          )
                        } else {
                          return (
                            <span
                              {...getTokenProps({ token, key })}
                              style={diffStyle}
                            />
                          )
                        }
                      }
                    }
                    return <span {...getTokenProps({ token, key })} />
                  })}
                </div>
              )
            })}
          </pre>
        )}
      </Highlight>
    )
  }
}
Example #22
Source File: index.js    From usepandas with MIT License 4 votes vote down vote up
export default function CodeHighlight({
  codeString,
  className,
  live,
  highlight,
  title,
  lineNumbers,
}) {
  const [copied, setCopied] = useState(false);
  const language = className && className.replace(/language-/, "");

  const shouldHighlightLine = calculateLinesToHighlight(highlight);

  const handleClick = () => {
    setCopied(true);
    copyToClipboard(codeString);

    setTimeout(() => {
      setCopied(false);
    }, 4000);
  };

  if (live) {
    return (
      <LiveProvider
        code={codeString}
        noInline
        theme={theme}
        transformCode={(code) => `/** @jsx mdx */${code}`}
        scope={scope}
      >
        <LiveWrapper>
          <LivePreview />

          <StyledEditor>
            <CopyCode onClick={handleClick} disabled={copied} hasTitle>
              {copied ? "Copied!" : "Copy"}
            </CopyCode>

            <LiveEditor />
          </StyledEditor>

          <LiveError />
        </LiveWrapper>
      </LiveProvider>
    );
  }

  return (
    <>
      {title && <PreHeader>{title}</PreHeader>}
      <div className="gatsby-highlight">
        <Highlight
          {...defaultProps}
          code={codeString}
          language={language}
          theme={theme}
        >
          {({
            className: blockClassName,
            style,
            tokens,
            getLineProps,
            getTokenProps,
          }) => (
            <Pre
              className={blockClassName}
              style={style}
              hasTitle={title}
              hasLanguage={!!language}
            >
              <CopyCode
                onClick={handleClick}
                disabled={copied}
                hasTitle={title}
              >
                {copied ? "Copied!" : "Copy"}
              </CopyCode>
              <code>
                {tokens.map((line, index) => {
                  const lineProps = getLineProps({ line, key: index });

                  if (shouldHighlightLine(index)) {
                    lineProps.className = `${lineProps.className} highlight-line`;
                  }

                  return (
                    <div {...lineProps}>
                      {lineNumbers && <LineNo>{index + 1}</LineNo>}
                      {line.map((token, key) => (
                        <span {...getTokenProps({ token, key })} />
                      ))}
                    </div>
                  );
                })}
              </code>
            </Pre>
          )}
        </Highlight>
      </div>
    </>
  );
}
Example #23
Source File: Code.jsx    From nextjs-prismic-blog-starter with MIT License 4 votes vote down vote up
Code = ({data: {primary}}) => {
  const {theme, colorMode} = useThemeUI()
  const [copied, setCopied] = useState(false)

  /**
   * Toast
   * language of the block copied to clipboard
   * @param {String} lang
   */
  const copyText = (lang) => {
    // remove older toast and copied state
    toast.dismiss()
    setCopied(false)

    // new toast and copied state
    toast.info(`${lang.toUpperCase()} block copied to clipboard`, {
      onOpen: () => {
        setCopied(true)
      },
      onClose: () => {
        setCopied(false)
      },
    })
  }

  const Button = styled.button`
    color: ${theme.colors.text};
    background: ${theme.colors.shade2};
    padding: 0.25rem;
    border: none;
    font-family: ${theme.fonts.body};
    letter-spacing: 1px;
    cursor: pointer;
    &:hover {
      color: ${theme.colors.accent};
      background: ${theme.colors.text};
    }
  `

  return (
    <Fragment>
      <Highlight
        {...defaultProps}
        theme={colorMode === 'light' ? light : dark}
        code={RichText.asText(primary.code)}
        language={primary.lang}>
        {({className, style, tokens, getLineProps, getTokenProps}) => (
          <pre
            className={className}
            style={{
              ...style,
              backgroundColor: theme.colors.code,
              marginLeft: primary.type === 'List' ? '2.5rem' : null,
              borderWidth: '1px',
              borderStyle: 'solid',
              borderColor: theme.colors.shade2,
              borderRadius: '0.25rem',
            }}>
            <div
              className={className}
              style={{
                ...style,
                margin: '-0.25rem auto 0.5rem auto',
                textAlign: 'right',
                color: theme.colors.accent,
                backgroundColor: theme.colors.code,
              }}>
              <span>{primary.lang.toUpperCase()}</span>
              <CopyToClipboard
                text={primary.code.text}
                onCopy={() => copyText(primary.lang)}
                style={{margin: '0 0.5rem'}}>
                {copied ? <span>Copied</span> : <Button>Copy</Button>}
              </CopyToClipboard>
            </div>
            {tokens.map((line, i) => (
              <div {...getLineProps({line, key: i})}>
                {line.map((token, key) => (
                  <span {...getTokenProps({token, key})} />
                ))}
              </div>
            ))}
          </pre>
        )}
      </Highlight>
      <ToastContainer
        autoClose={2500}
        closeOnClick
        newestOnTop
        pauseOnHover
        transition={Slide}
        draggable
        role='alert'
      />
    </Fragment>
  )
}
Example #24
Source File: code-block.js    From cloudflare-docs-engine with Apache License 2.0 4 votes vote down vote up
CodeBlock = (props) => {
  const { className, children } = props.children.props

  if (props.className) {
    return <pre {...props} />
  }

  let language = className ? className.split("-")[1] : "js"
  const mappedLanguage = languageMappings[language]
  if (mappedLanguage) language = mappedLanguage

  let code = children.trim()

  const tokenProps = ({ children, className, key }) => {
    const tokens = className.replace("token ", "").split(" ")

    className = ""

    tokens.forEach((token, i) => {
      token = transformToken({ token, children, language })
      if (token.indexOf("language-") !== 0) token = `token-${token}`
      className += ` CodeBlock--${token}`
    })

    className = className.trim()

    return {
      key,
      children,
      className,
    }
  }

  let codeFrontmatter = {}

  // For now, we don’t support code frontmatter
  // in Markdown or YAML blocks because they
  // themselves can contain frontmatter.

  // TODO: find workaround for this limitation
  if (language !== "markdown" && language !== "yaml") {
    const parsed = frontMatterParser(code)

    if (Object.keys(parsed.data).length) {
      code = parsed.content
      codeFrontmatter = parsed.data
    }
  }

  const theme = codeFrontmatter.theme || "light"

  return (
    <Highlight {...defaultProps} code={code} language={language}>
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre
          className={
            codeBlockClassName(theme) + " CodeBlock--language-" + language
          }
          language={language}
        >
          {codeFrontmatter.header && (
            <span className="CodeBlock--header">{codeFrontmatter.header}</span>
          )}
          {codeFrontmatter.filename && !codeFrontmatter.header && (
            <span className="CodeBlock--filename">
              {codeFrontmatter.filename}
            </span>
          )}
          <code>
            <span className="CodeBlock--rows">
              <span className="CodeBlock--rows-content">
                {tokens.map((line, i) => (
                  <span
                    key={i}
                    className={
                      "CodeBlock--row" +
                      (codeFrontmatter.highlight &&
                      codeFrontmatter.highlight.length &&
                      codeFrontmatter.highlight.includes(i + 1)
                        ? " CodeBlock--row-is-highlighted"
                        : "")
                    }
                  >
                    <span className="CodeBlock--row-indicator"></span>
                    <div className="CodeBlock--row-content">
                      {addNewlineToEmptyLine(line).map((token, key) => (
                        <span
                          key={key}
                          {...tokenProps(getTokenProps({ token, key }))}
                        />
                      ))}
                    </div>
                  </span>
                ))}
              </span>
            </span>
          </code>
        </pre>
      )}
    </Highlight>
  )
}
Example #25
Source File: Markdown.jsx    From xetera.dev with MIT License 4 votes vote down vote up
function Code({ children, className, metastring }) {
  // basically I want to be able to declare objects here without adding quotes to keys
  // which json5 allows me to do but json5 has a really big bundle size so I don't want to use it
  // please forgive me for my sins javascript gods
  const extraProps = eval(`(${metastring ?? "{}"})`)
  const { theme } = useContext(ThemeProvider)
  if (typeof extraProps.lang === "undefined") {
    extraProps.lang = true
  }

  const shouldHighlightLine = calculateLinesToHighlight(extraProps.h)
  const language = className?.replace(/language-/, "") || ""
  const highlighterClass = languageMappings[language]
  const isPreTitle = extraProps.title?.startsWith("/")
  const TitleType = isPreTitle ? "pre" : "div"
  const displayTop = extraProps.title || (highlighterClass && extraProps.lang)

  return (
    <Flex flexFlow="column" mb={6} lineHeight="1.8">
      {displayTop && (
        <Flex justifyContent="flex-end" alignItems="center" mb={2}>
          {extraProps.title && (
            <Box
              as={TitleType}
              width="full"
              mb={0}
              // background="bgSecondary"
              fontSize={["xs", null, "sm"]}
              borderTopRadius="2px"
              color="text.300"
            >
              {extraProps.title}
            </Box>
          )}
          {highlighterClass && extraProps.lang && (
            <Flex
              flexDirection="row"
              flexShrink={0}
              alignItems="center"
              justifySelf="flex-end"
            >
              <Text fontSize="xs" color="text.400">
                {highlighterClass.name}
              </Text>
              {highlighterClass.image && (
                <Box
                  borderRadius="sm"
                  overflow="hidden"
                  width="auto"
                  height="20px"
                  display="block"
                  ml={2}
                >
                  {highlighterClass.image}
                </Box>
              )}
            </Flex>
          )}
        </Flex>
      )}
      <Highlight
        {...defaultProps}
        code={children}
        language={language}
        theme={theme === "dark" ? Theme : ThemeLight}
      >
        {({ tokens, getLineProps, getTokenProps }) => (
          <Text
            as="pre"
            py={2}
            transition={transition}
            borderWidth={["1px"]}
            wordBreak="break-all"
            borderColor="borderSubtle"
            position="relative"
            overflowX="auto"
            fontSize={["sm", null, "md"]}
          >
            {tokens.map((line, i) => {
              // Remove the last empty line:
              let lineNumberElem
              if (
                line.length === 1 &&
                line[0].empty === true &&
                i === tokens.length - 1
              ) {
                lineNumberElem = null
              } else if (extraProps.lines) {
                lineNumberElem = (
                  <Box
                    display={{ base: "none", md: "inline" }}
                    as="span"
                    fontSize="sm"
                    mr={4}
                    userSelect="none"
                    color="text.400"
                    // className="mr-4 text-blueGray-600 select-none"
                  >
                    {i + 1}
                  </Box>
                )
              }
              // For some reason prism-react-renderer likes adding 1 extra line
              // at the end of every codeblock so we remove it here
              if (i === tokens.length - 1) {
                return null
              }
              const lineProps = getLineProps({ line, key: i })

              if (shouldHighlightLine(i)) {
                lineProps.className = `${lineProps.className} highlight-line`
              }

              return (
                <div key={i} {...lineProps}>
                  {lineNumberElem}
                  {line.map((token, key) => (
                    <span key={key} {...getTokenProps({ token, key })} />
                  ))}
                </div>
              )
            })}
          </Text>
        )}
      </Highlight>
    </Flex>
  )
}
Example #26
Source File: index.js    From gatsby-blog-mdx with MIT License 4 votes vote down vote up
Code = ({ codeString, language, metastring, ...props }) => {
  const [copyBtnText, setCopyBtnText] = useState("Copy")
  const [copyText, setCopyText] = useState("")
  const [loadingText, setLoadingText] = useState(false)

  // Set up texts to be copied on copy button
  useEffect(() => {
    let newStr = ""
    // Remove highlight comments
    let line = ""
    for (let i = 0; i < codeString.length; i++) {
      const c = codeString.charAt(i)
      if (c === "\n") {
        const result = removeHighlightComments(line)
        if (result) {
          newStr += result
          if (i !== codeString.length - 1) {
            newStr += "\n"
          }
        }
        line = ""
      } else {
        line += c
      }
    }
    // Last line
    const result = removeHighlightComments(line)
    if (result) newStr += result
    setCopyText(newStr)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // Set default language to text
  if (!language) language = "text"

  if (props["react-live"]) {
    return (
      <LiveProvider code={codeString} noInline={true} theme={undefined}>
        <LiveEditor className="live-highlight" style={undefined} />
        <LiveError className="live-error" />
        <LivePreview className="live-preview" />
      </LiveProvider>
    )
  }

  const handleCopy = () => {
    setCopyBtnText("Copied!")
    if (!loadingText) {
      setLoadingText(true)
      setTimeout(() => {
        setCopyBtnText("Copy")
        setLoadingText(false)
      }, 4000)
    }
  }

  const shouldHighlightLine = calculateLinesToHighlight(metastring)

  return (
    <Highlight
      {...defaultProps}
      code={codeString}
      language={language}
      theme={false}
    >
      {({ className, style, tokens, getLineProps, getTokenProps }) => {
        return (
          <div className="gatsby-highlight" data-language={language}>
            <div className="badge-btn-wrap">
              <div className={`language-badge language-badge-${language}`}>
                {language.toUpperCase()}
              </div>
              <CopyToClipboard text={copyText} onCopy={handleCopy}>
                <button className="btn-copy">{copyBtnText}</button>
              </CopyToClipboard>
            </div>
            <pre className={className} style={style}>
              {tokens.map((line, i) => {
                const lineProps = getLineProps({ line, key: i })
                const shouldExclude = highlightLine(line, lineProps, i)

                if (shouldHighlightLine(i)) {
                  addClassName(lineProps)
                }

                if (linesToHighlight.length > 0) {
                  if (linesToHighlight[0] === i) {
                    // Add class name & pop
                    addClassName(lineProps)
                    linesToHighlight.shift()
                  }
                }
                return !shouldExclude ? (
                  <div key={i} {...lineProps}>
                    {line.map((token, key) => (
                      <span {...getTokenProps({ token, key })} />
                    ))}
                  </div>
                ) : null
              })}
            </pre>
          </div>
        )
      }}
    </Highlight>
  )
}
Example #27
Source File: index.js    From MDXP with MIT License 4 votes vote down vote up
MDXPCodeHighlight = ({children}) => {
  const theme = useConfig().themeConfig.prism.light;
  const [showState, setShowState] = useState(false);

  const show = () => {
    document.prevScroll = document.scrollingElement.scrollTop;
    document.body.style.overflow = 'hidden';
    document.body.style.position = 'fixed';
    document.body.style.top = `-${document.prevScroll}px`;
    document.body.style.width = '100%';

    window.location.hash = '';
    setShowState(true);
  };
  const hide = () => {
    setShowState(false);

    document.body.style.removeProperty('overflow');
    document.body.style.removeProperty('position');
    document.body.style.removeProperty('top');
    document.body.style.removeProperty('width');
    window.scrollTo(0, document.prevScroll);
  };

  return (
    <React.Fragment>
      <Highlight
        {...defaultProps}
        code={children.trim()}
        language='md'
        theme={theme}
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <Styled.pre
            className={`language-md ${className}`}
            style={{ ...style, position: 'relative', overflowX: 'auto' }}
            data-testid="code"
          >
            <span
              sx={{
                fontSize: 1,
                position: 'absolute',
                top: '10px',
                right: '10px',
                color: 'rgb(249, 172, 0)',
                textTransform: 'uppercase',
                letterSpacing: 'caps',
                cursor: 'pointer',
                '&:hover': {
                  top: '11px',
                  right: '11px',
                  fontWeight: 'bold'
                },
                '&:active': {
                  top: '11px',
                  right: '11px',
                  fontWeight: 'bold'
                },
                '@media screen and (max-width: 920px)': {
                  display: 'none'
                }
              }}
              onClick={show}
            >
              Show
            </span>
            {tokens.map((line, i) => (
              <div {...getLineProps({ line, key: i })}>
                {line.map((token, key) => (
                  <span
                    {...getTokenProps({ token, key })}
                    sx={{ display: 'inline-block' }}
                  />
                ))}
              </div>
            ))}
          </Styled.pre>
        )}
      </Highlight>
      <MDXPDemo code={children} onOuterClick={hide} show={showState} />
    </React.Fragment>
  );
}