react-live#LiveError JavaScript Examples

The following examples show how to use react-live#LiveError. 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: PlaygroundCodeError.js    From basis with MIT License 6 votes vote down vote up
PlaygroundCodeError = withLive(({ live }) => {
  const theme = useTheme();

  if (typeof window === "undefined" || !live.error || live.code.trim() === "") {
    return null;
  }

  return (
    <div
      css={{
        position: "absolute",
        left: 0,
        right: 0,
        top: -200,
        height: 200,
        overflowY: "auto",
        boxSizing: "border-box",
        padding: `${theme.space[4]} ${theme.space[8]}`,
        backgroundColor: theme.colors.white,
        boxShadow: "0 -4px 0 0 rgba(207, 0, 14, 0.8)",
        color: theme.colors.conditional.negative.text,
        "> pre": {
          margin: 0,
        },
      }}
    >
      <LiveError />
    </div>
  );
})
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: 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 #5
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 #6
Source File: ComponentContainer.js    From basis with MIT License 4 votes vote down vote up
function ComponentContainer(props) {
  const { code, noInline = false, scope, hasBodyMargin, bg } = props;
  const theme = useTheme();
  const spaceBetween = parseInt(theme.space[11], 10);
  const spaceAroundIframe = parseInt(theme.space[5], 10);
  const borderWidthPx = theme.borderWidths[0];
  const borderWidth = parseInt(borderWidthPx, 10);
  const minWidth = 50 + 2 * spaceAroundIframe + borderWidth;
  const initialWidth = useMemo(() => {
    if (!props.width || typeof props.width === "string") {
      const initialWidthPx =
        theme.breakpoints[props.width || "xs"] || props.width;

      return parseInt(initialWidthPx, 10) + 2 * spaceAroundIframe;
    }

    return props.width + 2 * spaceAroundIframe;
  }, [props.width, theme.breakpoints, spaceAroundIframe]);
  const [resizeWidth, setResizeWidth] = useState(
    initialWidth - 2 * spaceAroundIframe
  );
  const [width, setWidth] = useState(initialWidth + borderWidth);

  return (
    <div css={{ display: "flex", flexGrow: 1, overflowY: "auto" }}>
      <LiveProvider
        code={code}
        scope={scope}
        noInline={noInline}
        theme={reactLiveEditorTheme}
      >
        <div>
          <Resizable
            style={{
              flexShrink: 0,
              marginRight: spaceBetween,
              borderRight: `${borderWidthPx} solid ${theme.colors.grey.t10}`,
            }}
            enable={rightOnly}
            minWidth={minWidth}
            size={{
              width,
              height: "100%",
            }}
            onResizeStop={(_e, _direction, _ref, d) => {
              setWidth(width + d.width);
            }}
            onResize={(_e, _direction, _ref, d) => {
              setResizeWidth(
                width + d.width - 2 * spaceAroundIframe - borderWidth
              );
            }}
          >
            <div
              css={{
                position: "absolute",
                right: 0,
                top: 0,
                backgroundColor: theme.colors.grey.t10,
                fontSize: theme.fontSizes[0],
                padding: `0 ${theme.space[1]}`,
              }}
            >
              {resizeWidth}px
            </div>
            <div
              css={{
                height: "100%",
                boxSizing: "border-box",
                padding: spaceAroundIframe,
                backgroundColor: theme.getColor(bg),
                overflowY: "auto",
              }}
            >
              <ComponentPreview hasBodyMargin={hasBodyMargin} bg={bg} />
            </div>
          </Resizable>
        </div>
        <div css={{ flexGrow: 1, overflowY: "auto" }}>
          <ComponentCode code={code} />
          <LiveError />
        </div>
      </LiveProvider>
    </div>
  );
}
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>
  );
}
Example #9
Source File: CodeBlock.jsx    From tonic-ui with MIT License 4 votes vote down vote up
CodeBlock = ({
  /**
   * Do not evaluate and mount the inline code (Default: `false`).
   */
  noInline = false,

  /**
   * Disable editing on the `<LiveEditor />` (Default: `false`)
   */
  disabled = false,

  /**
   * Preview only (Default: `false`)
   */
  previewOnly = false,

  /**
   * Default is expand or collapse (Default: `false`)
   */
  expanded: defaultExpanded = false,

  className,
  children,
  ...props
}) => {
  const [, updateState] = useState();
  const forceUpdate = useCallback(() => updateState({}), []);
  const [colorMode] = useColorMode();
  const [editorCode, setEditorCode] = useState(children.trim());
  const {
    onCopy: copySource,
    hasCopied: hasCopiedSource,
  } = useClipboard(editorCode);
  const [isLiveEditorVisible, toggleLiveEditorVisibility] = reactHooks.useToggle(defaultExpanded);
  const resetDemo = () => {
    setEditorCode(children.trim());
    toggleLiveEditorVisibility(false);
    forceUpdate();
  };
  const handleLiveEditorChange = useCallback(newCode => {
    setEditorCode(newCode.trim());
  }, []);
  const language = className && className.replace(/language-/, '');

  noInline = boolean(noInline);

  if (disabled === undefined) {
    disabled = (language !== 'jsx');
  } else {
    disabled = (language !== 'jsx') || boolean(disabled);
  }

  const liveProviderProps = {
    theme: {
      dark: codeBlockDark,
      light: codeBlockLight,
    }[colorMode],
    language,
    noInline,
    disabled,
    code: editorCode,
    transformCode: code => code,
    scope: {
      ...reactComponents,
      ...reactLabComponents,
      ...reactHooks,
      ...thirdPartyComponents,
      Code,
      FontAwesomeIcon,
      InputTag,
      Lorem,
      SkeletonBody,
      SkeletonContent,
      Global, // from '@emotion/react'
      css, // from '@emotion/react'
      mdx, // from '@mdx-js/react'
      sx, // from '@tonic-ui/styled-system'
      tmicons, // from '@trendmicro/tmicon'
    },
    mountStylesheet: false,
    ...props,
  };

  if (previewOnly) {
    return (
      <LiveProvider {...liveProviderProps}>
        <LiveCodePreview style={liveCodePreviewStyle} />
      </LiveProvider>
    );
  }

  const isEditable = !disabled;

  if (!isEditable) {
    return (
      <LiveProvider {...liveProviderProps}>
        <LiveEditor
          style={liveEditorStyle}
          css={css`
            & > textarea { outline: 0; }
          `}
        />
      </LiveProvider>
    );
  }

  return (
    <LiveProvider {...liveProviderProps}>
      <LiveCodePreview style={liveCodePreviewStyle} />
      <Box display="flex" justifyContent="flex-end">
        <IconButton onClick={toggleLiveEditorVisibility}>
          <Tooltip label={isLiveEditorVisible ? 'Hide the source' : 'Show the source'}>
            <Icon icon="code" size={{ sm: '5x', md: '4x' }} />
          </Tooltip>
        </IconButton>
        <IconButton onClick={copySource}>
          <Tooltip label={hasCopiedSource ? 'Copied' : 'Copy the source'}>
            <Icon icon="file-copy-o" size={{ sm: '5x', md: '4x' }} />
          </Tooltip>
        </IconButton>
        <IconButton onClick={resetDemo}>
          <Tooltip label="Reset the demo">
            <Icon icon="redo" size={{ sm: '5x', md: '4x' }} />
          </Tooltip>
        </IconButton>
      </Box>
      <Fade in={isLiveEditorVisible}>
        <Collapse in={isLiveEditorVisible} unmountOnExit={true}>
          <LiveEditor
            onChange={handleLiveEditorChange}
            style={liveEditorStyle}
            css={css`
              & > textarea { outline: 0; }
            `}
          />
        </Collapse>
      </Fade>
      <LiveError style={liveErrorStyle} />
    </LiveProvider>
  );
}