react-live#LivePreview JavaScript Examples

The following examples show how to use react-live#LivePreview. 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: ComponentPreview.js    From basis with MIT License 6 votes vote down vote up
function ComponentPreviewContent({
  window,
  document,
  hasBodyMargin,
  bg,
  setDocument,
  containerRef,
  highlightedComponents,
}) {
  useEffect(() => {
    if (setDocument) {
      setDocument(document);
    }
  }, [setDocument, document]);

  return (
    <BasisProvider theme={defaultTheme} window={window}>
      {!hasBodyMargin && (
        <Global
          styles={{
            body: {
              margin: 0,
            },
          }}
        />
      )}
      <BackgroundProvider value={bg ?? null}>
        <LivePreview
          Component={LivePreviewWrapper}
          containerRef={containerRef}
          highlightedComponents={highlightedComponents}
        />
      </BackgroundProvider>
    </BasisProvider>
  );
}
Example #2
Source File: LiveProvider.js    From cardano-documentation with MIT License 6 votes vote down vote up
ReactLiveProvider = ({ code }) => {
  return (
    <LiveProvider code={code}>
      <LiveEditor />
      <LiveError />
      <LivePreview />
    </LiveProvider>
  )
}
Example #3
Source File: LiveProvider.js    From learningHub with MIT License 6 votes vote down vote up
ReactLiveProvider = ({ code }) => {
  return (
    <LiveProvider code={code}>
      <LiveEditor />
      <LiveError />
      <LivePreview />
    </LiveProvider>
  );
}
Example #4
Source File: CodeBlock.jsx    From tonic-ui with MIT License 6 votes vote down vote up
LiveCodePreview = props => {
  const [colorMode] = useColorMode();
  const borderColor = {
    light: 'gray:30',
    dark: 'gray:70',
  }[colorMode];

  return (
    <Box
      border={1}
      borderColor={borderColor}
      borderRadius="sm"
      p="4x"
    >
      <Box
        as={LivePreview}
        fontFamily="base"
        fontSize="sm"
        lineHeight="sm"
        whiteSpace="normal"
        {...props}
      />
    </Box>
  );
}
Example #5
Source File: ExampleItem.js    From Lambda with MIT License 5 votes vote down vote up
render() {
    const { editorOpen } = this.state;
    const editorClassNames = classNames('live-editor', {
      'live-editor--visible': editorOpen,
    });
    const formId = `editorOpen${this.props.label.replace(' ', '_')}`;

    return (
      <div className="section">
        <h3 className="section__heading">
          {this.props.label}{' '}
          <label className="source-checkbox-label" htmlFor={formId}>
            <input
              type="checkbox"
              id={formId}
              name={formId}
              checked={editorOpen}
              onChange={this.handleEditSourceChange}
            />
            View source
          </label>
        </h3>
        {this.renderHint()}
        <LiveProvider
          scope={scope}
          code={this.props.code}
          theme={dracula}
          noInline
        >
          <LiveError />
          <div className="live-preview">
            <div className={editorClassNames}>
              <LiveEditor />
            </div>
            <LivePreview
              className="react-live-preview"
              style={{ dir: this.props.direction === 'rtl' ? 'rtl' : 'ltr' }}
            />
          </div>
        </LiveProvider>
      </div>
    );
  }
Example #6
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 #7
Source File: index.js    From mds-docs with MIT License 4 votes vote down vote up
StoryComp = ({
  componentData,
  showArgsTable = true,
  htmlData,
  propData = {},
}) => {
  const testRef = useRef(null);
  const [zoom, setZoom] = useState(1);
  const [activeTab, setActiveTab] = React.useState(0);

  const [jsxCode, setJsxCode] = React.useState(
    getRawPreviewCode(componentData)
  );

  const html = beautifyHTML(htmlData,
    beautifyHTMLOptions
  );
  const [htmlCode, setHtmlCode] = useState(html);
  const [isExpanded, setIsExpanded] = useState(false);
  const [activeButton, setActiveButton] = useState('React');

  const renderHTMLTab = () => {
    return (
      <Tab label={<Button>HTML</Button>}>
        {renderCodeBlock(htmlCode)}
      </Tab>
    );
  };

  const renderCodeBlock = (val) => (
    <div>
      <style>
        {`pre {
        margin: 0;
        text-align: left;

      }`}
      </style>
      <SyntaxHighlighter
        language='javascript'
        style={vs2015}
        showLineNumbers={true}
      >
        {val}
      </SyntaxHighlighter>
    </div>
  );

  const copyCode = (val) =>
    navigator.clipboard.writeText(val);

  const CopyCode = (props) => {
    const { onClick } = props;
    return (
      <div className='ml-auto d-flex'>
        <img
          src={logo}
          className='codesandBox-icon mr-6 align-self-center'
          onClick={(e) => {
            e.preventDefault();
            openSandbox(jsxCode);
          }}
        />
        <Icon
          name='content_copy'
          size={20}
          appearance='white'
          onClick={onClick}
          className='align-self-center cursor-pointer'
        />
      </div>
    );
  };

  const handleZoomIn = () => {
    setZoom(zoom + 0.5);
  };

  const handleZoomOut = () => {
    setZoom(zoom - 0.5);
  };

  const showLiveEditorContent = () => {
    if (activeButton === 'React') {
      return (
        <div>
          <LiveEditor theme={vsDark} />
        </div>
      );
    } else {
      return renderCodeBlock(htmlCode);
    }
  };

  const imports = React.useMemo(() => ({ ...DS }), []);

  return (
    <>
      <div className='pt-8 pb-8 d-flex w-100 m-auto flex-column align-items-center'>
        <LiveProvider code={jsxCode} scope={imports}>
          <Card
            shadow='light'
            className='w-100 overflow-hidden'
          >
            <CardHeader>
              <div className='d-flex justify-content-end'>
                <Button
                  onClick={() => handleZoomIn()}
                  icon='zoom_in'
                  appearance='transparent'
                  largeIcon
                  className='transformation-button'
                ></Button>
                <Button
                  onClick={() => handleZoomOut()}
                  icon='zoom_out'
                  appearance='transparent'
                  largeIcon
                  className='transformation-button'
                ></Button>
              </div>
            </CardHeader>
            <CardBody className='d-flex flex-column align-items-center'>
              <div ref={testRef}>
                <LivePreview
                  className='p-8 live-preview'
                  style={{ zoom: zoom }}
                />
                <LiveError />
              </div>
              <div className='d-flex flex-row-reverse w-100 mb-6'>
                <Button
                  appearance='basic'
                  className='action-button'
                  onClick={() => setIsExpanded(!isExpanded)}
                >
                  {isExpanded ? 'Hide code' : 'Show code'}
                </Button>
              </div>
            </CardBody>
          </Card>

          {isExpanded && (
            <Card
              shadow='light'
              className='w-100 overflow-hidden mt-6 live-editor-card'
            >
              <div>
                <div className='d-flex px-4 pt-6'>
                  <Button
                    appearance='basic'
                    onClick={() => setActiveButton('React')}
                    selected={
                      activeButton === 'React'
                        ? true
                        : false
                    }
                    className='mr-3'
                  >
                    React
                  </Button>
                  <Button
                    appearance='basic'
                    onClick={() => setActiveButton('HTML')}
                    selected={
                      activeButton === 'HTML' ? true : false
                    }
                  >
                    HTML
                  </Button>
                  {activeButton === 'React' && (
                    <CopyCode
                      onClick={() => {
                        const editor =
                          document.querySelector(
                            '.npm__react-simple-code-editor__textarea'
                          );
                        if (editor) copyCode(editor.value);
                      }}
                    />
                  )}
                </div>
              </div>

              {showLiveEditorContent()}
            </Card>
          )}
        </LiveProvider>
        {showArgsTable && (
          <>
            <Heading className='mt-10 align-self-start'>
              Props
            </Heading>
            <ArgsTable rows={propData} />
          </>
        )}
      </div>
    </>
  );
}
Example #8
Source File: playground.js    From r3f-website with MIT License 4 votes vote down vote up
Playground = () => {
  const [activeGeometry, setActiveGeometry] = useState(box);
  const [color, setColor] = useState("#ccc");
  const [numberOfGeometry, setNumberOfGeometry] = useState(1);
  const [picker, showPicker] = useState(false);
  const pickerButton = useRef();
  useClickOutside(pickerButton, () => showPicker(false));
  return (
    <section
      css={`
        padding: 60px 0;
      `}
    >
      <h2>Try it yourself</h2>
      <p
        css={`
          position: relative;
          display: flex;
          align-items: center;
        `}
      >
        I want to render a{" "}
        <select
          css={`
            margin: 0 5px;
          `}
          onChange={(e) => setActiveGeometry(e.target.value)}
          onBlur={(e) => setActiveGeometry(e.target.value)}
        >
          <option value={box}>Box</option>
          <option value={sphere}>Sphere</option>
          <option value={cone}>Cone</option>
          <option value={dodecahedron}>Dodecahedron</option>
        </select>{" "}
        in a{" "}
        <span
          ref={pickerButton}
          css={`
            display: inherit;
          `}
        >
          <button
            aria-label="Show color picker"
            onClick={() => showPicker((s) => !s)}
            css={`
              width: 23px;
              height: 23px;
              margin: 0 5px;
              background: ${color};
              border: 1px solid #ffffff;
            `}
          />
          {picker && (
            <ChromePicker
              css={`
                position: absolute;
                top: 40px;
                z-index: 99;
                left: 180px;
              `}
              color={color}
              onChange={(color) => setColor(color.hex)}
            />
          )}{" "}
        </span>
        color
      </p>
      I want to show{" "}
      <input
        aria-label="How many geometry to show"
        type="number"
        max="6"
        min="1"
        value={numberOfGeometry}
        onChange={(e) => setNumberOfGeometry(e.target.value)}
      ></input>{" "}
      geometry
      <LiveProvider
        theme={nightOwl}
        scope={scope}
        noInline
        code={code(activeGeometry, color, numberOfGeometry)}
      >
        <div
          css={`
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-gap: 40px;

            @media screen and (max-width: 900px) {
              grid-template-columns: 1fr;
            }
          `}
        >
          <LiveEditor
            css={`
              margin-top: 40px;
            `}
          />
          <div
            css={`
              height: 100%;
              > div {
                height: 100%;
                min-height: 400px;
              }
            `}
          >
            <LiveError />
            <LivePreview />
          </div>
        </div>
      </LiveProvider>
    </section>
  );
}