uiwjs / react-textarea-code-editor

A simple code editor with syntax highlighting.
https://uiwjs.github.io/react-textarea-code-editor/
MIT License
476 stars 22 forks source link

Add the ability to highlight individual lines #151

Open lucgagan opened 1 year ago

lucgagan commented 1 year ago

I am trying to add regex tester to https://ray.run/tools similar to https://regex101.com/.

The main requirement is that I want to highlight matching parts of the code.

The other use case for this would be to develop a text diff similar to https://ray.run/tools/json-diff-analyzer

jaywcjlove commented 1 year ago

@lucgagan https://codesandbox.io/embed/https-github-com-uiwjs-react-textarea-code-editor-issues-151-nsm7qp?fontsize=14&hidenavigation=1&theme=dark

import React, { useEffect } from "react";
import CodeEditor, { SelectionText } from "@uiw/react-textarea-code-editor";
import rehypePrism from "rehype-prism-plus";
import rehypeRewrite from "rehype-rewrite";
import "./styles.css";

export default function App() {
  const textRef = React.useRef();
  const [code, setCode] = React.useState(
    `function add(a, b) {\n  return a + b;\n}`
  );
  useEffect(() => {
    if (textRef.current) {
      const obj = new SelectionText(textRef.current);
      console.log("obj:", obj);
    }
  }, []);
  return (
    <CodeEditor
      value={code}
      ref={textRef}
      language="js"
      rehypePlugins={[
        [rehypePrism, { ignoreMissing: true }],
        [
          rehypeRewrite,
          {
            rewrite: (node, index, parent) => {
              if (node.properties?.className?.includes("code-line")) {
                if (index === 0 && node.properties?.className) {
                  node.properties.className.push("demo01");
                  console.log("~~~", index, node.properties?.className);
                }
              }
              if (node.type === "text") {
                if (node.value === "return" && parent.children.length === 1) {
                  parent.properties.className.push("demo123");
                  // console.log("node123", node.value);
                  // console.log("node111.properties.className", parent);
                }
              }
            }
          }
        ]
      ]}
      placeholder="Please enter JS code."
      onChange={(evn) => setCode(evn.target.value)}
      padding={15}
      style={{
        fontFamily:
          "ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace",
        fontSize: 12
      }}
    />
  );
}
jaywcjlove commented 1 year ago
image

@lucgagan