Skip to content

Commit

Permalink
auto-indenting
Browse files Browse the repository at this point in the history
  • Loading branch information
loiswells97 committed Oct 30, 2024
1 parent 3cab914 commit 7e27828
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ const PyodideRunner = (props) => {
const [visuals, setVisuals] = useState([]);
const [showRunner, setShowRunner] = useState(active);
const [inputStack, setInputStack] = useState([]);
const [indentationLevel, setIndentationLevel] = useState(0);
const [awaitingInput, setAwaitingInput] = useState(false);

const prependToInputStack = (input) => {
setInputStack((prevInputStack) => {
if (prevInputStack[0] === "") {
Expand All @@ -79,6 +82,20 @@ const PyodideRunner = (props) => {
};
const [inputStackIndex, setInputStackIndex] = useState(0);

const incrementIndentationLevel = () => {
setIndentationLevel((prevIndentationLevel) => prevIndentationLevel + 1);
};

const decrementIndentationLevel = () => {
setIndentationLevel((prevIndentationLevel) => {
return Math.max(0, prevIndentationLevel - 1);
});
};

useEffect(() => {
console.log("indentationLevel", indentationLevel);
}, [indentationLevel]);

useEffect(() => {
console.log("isOutputOnly", isOutputOnly);
});
Expand All @@ -102,6 +119,20 @@ const PyodideRunner = (props) => {
}
}, [inputStack, inputStackIndex, consoleMode]);

useEffect(() => {
if (awaitingInput && consoleMode) {
const inputElement = getInputElement();
inputElement.innerText = " ".repeat(indentationLevel * 4);
// move cursor to end of text
const range = document.createRange();
const selection = window.getSelection();
range.selectNodeContents(inputElement);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
}, [awaitingInput, indentationLevel, consoleMode]);

useEffect(() => {
console.log("inputStack", inputStack);
}, [inputStack]);
Expand Down Expand Up @@ -208,7 +239,16 @@ const PyodideRunner = (props) => {

const element = getInputElement();
const { content, ctrlD } = await getInputContent(element);
setAwaitingInput(false);

prependToInputStack(content);
if (content.trimEnd().slice(-1) === ":") {
incrementIndentationLevel();
} else if (content.trimEnd() === "") {
console.log("the content is");
console.log(content);
decrementIndentationLevel();
}

const encoder = new TextEncoder();
const bytes = encoder.encode(content + "\n");
Expand Down Expand Up @@ -310,6 +350,7 @@ const PyodideRunner = (props) => {
span.setAttribute("spellCheck", "false");
span.setAttribute("class", "pythonrunner-input");
span.setAttribute("contentEditable", "true");
setAwaitingInput(true);
return span;
};

Expand Down

0 comments on commit 7e27828

Please sign in to comment.