From 44cd6273bad5d8cc1242c1f609648f24eb4966f9 Mon Sep 17 00:00:00 2001 From: Andrea Giammarchi Date: Fri, 12 Apr 2024 15:44:20 +0200 Subject: [PATCH] PyTerminal .process(code) utility (#2026) * PyTerminal .process(code) utility * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- pyscript.core/package-lock.json | 4 ++-- pyscript.core/package.json | 2 +- pyscript.core/src/plugins/py-terminal.js | 22 ++++++++++++++++++++-- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/pyscript.core/package-lock.json b/pyscript.core/package-lock.json index b18c5741..1e8c9fd3 100644 --- a/pyscript.core/package-lock.json +++ b/pyscript.core/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pyscript/core", - "version": "0.4.18", + "version": "0.4.20", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pyscript/core", - "version": "0.4.18", + "version": "0.4.20", "license": "APACHE-2.0", "dependencies": { "@ungap/with-resolvers": "^0.1.0", diff --git a/pyscript.core/package.json b/pyscript.core/package.json index 548d2dc4..17d6ab8a 100644 --- a/pyscript.core/package.json +++ b/pyscript.core/package.json @@ -1,6 +1,6 @@ { "name": "@pyscript/core", - "version": "0.4.18", + "version": "0.4.20", "type": "module", "description": "PyScript", "module": "./index.js", diff --git a/pyscript.core/src/plugins/py-terminal.js b/pyscript.core/src/plugins/py-terminal.js index 721fef77..6bc26a48 100644 --- a/pyscript.core/src/plugins/py-terminal.js +++ b/pyscript.core/src/plugins/py-terminal.js @@ -1,7 +1,7 @@ // PyScript py-terminal plugin import { TYPES, hooks } from "../core.js"; import { notify } from "./error.js"; -import { customObserver, defineProperty } from "polyscript/exports"; +import { customObserver, defineProperties } from "polyscript/exports"; // will contain all valid selectors const SELECTORS = []; @@ -170,7 +170,25 @@ const pyTerminal = async (element) => { terminal.open(target); fitAddon.fit(); terminal.focus(); - defineProperty(element, "terminal", { value: terminal }); + defineProperties(element, { + terminal: { value: terminal }, + process: { + value: async (code) => { + // this loop is the only way I could find to actually simulate + // the user input char after char in a way that works in both + // MicroPython and Pyodide + for (const line of code.split(/(?:\r|\n|\r\n)/)) { + terminal.paste(`${line}\n`); + do { + await new Promise((resolve) => + setTimeout(resolve, 0), + ); + } while (!readline.activeRead?.resolve); + readline.activeRead.resolve(line); + } + }, + }, + }); return terminal; };