uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.69k stars 135 forks source link

Why does the autocomplete integration not work in react-codemirror? #579

Closed Time1sM0ney closed 1 year ago

Time1sM0ney commented 1 year ago

https://codesandbox.io/p/sandbox/react-codemirror-tzhnch.

 const jsonCompletion = (context: CompletionContext) => {
    const word = context.matchBefore(/\w*/);
    if (word.from == word.to && !context.explicit) return null;
    return {
      from: word.from,
      options: [
        { label: "match", type: "keyword" },
        { label: "hello", type: "variable", info: "(World)" },
        { label: "magic", type: "text", apply: "⠁⭒*.✩.*⭒⠁", detail: "macro" },
      ],
    };
  };
    <ReactCodeMirror
        className="editor"
        theme={vscodeDarkInit({
          styles: [
            {
              tag: t.comment,
              color: "#787b80",
            },
          ],
        })}
        basicSetup={{
          crosshairCursor: false,
        }}
        extensions={[
          langs.json(),
          autocompletion({ override: [jsonCompletion] }),
        ]}
        onChange={handleChange}
      />
jaywcjlove commented 1 year ago

@codercoin98 Example: https://codesandbox.io/embed/vibrant-marco-p8znlj?fontsize=14&hidenavigation=1&theme=dark

import React from "react";
import CodeMirror from "@uiw/react-codemirror";
import { autocompletion } from "@codemirror/autocomplete";

// Our list of completions (can be static, since the editor
/// will do filtering based on context).
const completions = [
  { label: "panic", type: "keyword" },
  { label: "park", type: "constant", info: "Test completion" },
  { label: "password", type: "variable" }
];

function myCompletions(context) {
  let before = context.matchBefore(/\w+/);
  // If completion wasn't explicitly started and there
  // is no word before the cursor, don't open completions.
  if (!context.explicit && !before) return null;
  return {
    from: before ? before.from : context.pos,
    options: completions,
    validFor: /^\w*$/
  };
}

function App() {
  const [value, setValue] = React.useState("// Type a 'p'\n");
  const onChange = React.useCallback((val, viewUpdate) => {
    console.log("val:", val);
    setValue(val);
  }, []);
  return (
    <CodeMirror
      value={value}
      height="200px"
      extensions={[autocompletion({ override: [myCompletions] })]}
      onChange={onChange}
    />
  );
}

export default App;
Lau08 commented 1 month ago

I'm triying using this to trigger the autocomplete: {{ but not showing the opinions. I see the variables perfectly in the console, and it triggers without problem but not opening the opinion list.


import ReactCodeMirror from "@uiw/react-codemirror";
import { markdown } from "@codemirror/lang-markdown";
import { python } from "@codemirror/lang-python";
import { json } from "@codemirror/lang-json";
import { VariableType } from "@/models/WorkflowDesignerModelConfig";
import { autocompletion } from "@codemirror/autocomplete";

function myCompletions(context: any, listOfPromptVariables: string[]) {
  let word = context.matchBefore(/\{\{\w*/);
  if (!word || (word.from === word.to && !context.explicit)) return null;

  const options = listOfPromptVariables.map((variable) => ({
    label: variable,
    type: "variable",
    apply: `{{${variable}}}`,
  }));

  return {
    from: word.from,
    options: options,
    validFor: /^\{\{\w*$/,
  };
}

function CodeEditor({
  variableType,
  listOfPromptVariables,
  editorContent,
  onEditorChange,
}: any) {
  const handleEditorChange = (content: any) => {
    onEditorChange(content);
  };
  const codeOptions = {
    lineNumbers: true,
    tabSize: 2,
    styleActiveLine: true,
    lineWrapping: true,
    foldGutter: true,
    autocompletion: true,
    drawSelection: true,
    closeBrackets: false,
  };

  return (
    <div className="px-5 h-[74%]">
      <h1 className="my-5 text-base font-medium pb-5 border-b-2 border-dashed">
        {variableType == VariableType.SwaggerDoc
          ? "SwaggerDoc"
          : variableType == VariableType.PromptTemplate
          ? "PromptTemplate"
          : variableType == VariableType.JsonSchema
          ? "JsonSchema"
          : ""}
      </h1>
      <div className="pt-3 h-full">
        <ReactCodeMirror
          value={editorContent}
          theme={"light"}
          extensions={[
            markdown(),
            python(),
            json(),
            autocompletion({
              override: [
                (context) => myCompletions(context, listOfPromptVariables),
              ],
            }),
          ]}
          height={"77vh"}
          onChange={handleEditorChange}
          basicSetup={codeOptions}
        />
      </div>
    </div>
  );
}

export default CodeEditor;