pythonreact-typescriptpyscriptpyodide

how to get active REPL block in PyScript and copy whatever code written in it?


I have multiple code blocks in pyscript repl which were created dynamically on button click. I want to know which code block is active. I know library adds cm-activeLine class when line is active but that changes when I click some other button to get the class.. I want to change order of code blocks on button click. what I am thinking is I will copy all code inside editor and Swap it with other code block but I dont know how to get the code inside editor. library has no documentation.


Solution

  • My scenario was to add new repl tag on a button click inside a div as child and then determine which repl tag is active to perform further operations. The workaround I used was to enclose all of <py-repl /> tags inside <div /> and added an event listener onClick on the div. Inside event I am searching for div with cm-focused class.

    const selectActiveCodeBlock = useCallback(() => {
     let div: any = document.querySelector("div.cm-focused");
      if (!div) {
       selectedCodeBlock.current = null;
       return;
      }
    
      selectedCodeBlock.current = div.closest("py-repl");
     }, []);
    

    Now I have reference of active repl in selectedCodeBlock if it was clicked else it will be null.

    To get the code written inside repl as a string:

    let code = selectedCodeBlock.current.editor.state.doc.toString();