diff --git a/examples/timers.php b/examples/timers.php index 6f644c1..940ce3e 100644 --- a/examples/timers.php +++ b/examples/timers.php @@ -6,16 +6,22 @@ require_once __DIR__."/../vendor/autoload.php"; $shell = new NoccyLabs\React\Shell\Shell(); +// The prompt event is invoked before every full redraw. Call redrawPrompt() +// to trigger it manually. Set the prompt or the style here. $shell->on('prompt', function ($shell) { $shell->setPrompt(date("H:i:s> ")); }); + +// Input handler, parse the commands. $shell->on('input', function (array $input) use ($shell) { $shell->write("You entered: ".join(" ", $input)."\n"); }); -// The shell is an OutputStream +// The shell is an OutputStream, and writing to it will handle hiding the prompt +// and redrawing it afterwards! $shell->write("Hello World!\n\n"); +// So output can be writen while you are typing! Loop::addPeriodicTimer(5, function () use ($shell) { $shell->write(date(DATE_ATOM)."\n"); }); \ No newline at end of file diff --git a/src/Shell.php b/src/Shell.php index 5101d7c..b7eec6c 100644 --- a/src/Shell.php +++ b/src/Shell.php @@ -82,7 +82,7 @@ class Shell implements WritableStreamInterface, EventEmitterInterface public function setPrompt(string $prompt): void { $this->prompt = $prompt; - $this->promptWidth = mb_strlen($this->prompt); + $this->promptWidth = mb_strlen(preg_replace('<(\e\[[0-9;]+?m)>m', '', $this->prompt)); } private function handleInput($v) { @@ -99,6 +99,7 @@ class Shell implements WritableStreamInterface, EventEmitterInterface // Update the history array_unshift($this->history, $this->buffer); while (count($this->history) > $this->maxHistory) array_pop($this->history); + $this->historyIndex = 0; // Parse and empty the buffer $buffer = str_getcsv(trim($this->buffer), " "); $this->buffer = ''; @@ -128,12 +129,12 @@ class Shell implements WritableStreamInterface, EventEmitterInterface if ($this->historyIndex === null && count($this->history) > 0) { $this->historyCache = $this->buffer; $this->historyIndex = 0; - $this->buffer = $this->history[$this->historyIndex]; + $this->buffer = $this->history[$this->historyIndex]??''; } elseif ($this->historyIndex < count($this->history) - 1) { $this->historyIndex++; - $this->buffer = $this->history[$this->historyIndex]; + $this->buffer = $this->history[$this->historyIndex]??''; } - $this->cursorPos = min(strlen($this->buffer), $this->cursorPos) - $this->scrollOffset; + $this->cursorPos = mb_strlen($this->buffer); break; case "\e[B": // down if ($this->historyIndex === null) { @@ -144,9 +145,9 @@ class Shell implements WritableStreamInterface, EventEmitterInterface $this->historyCache = null; } else { $this->historyIndex--; - $this->buffer = $this->history[$this->historyIndex]; + $this->buffer = $this->history[$this->historyIndex]??''; } - $this->cursorPos = min(strlen($this->buffer), $this->cursorPos) - $this->scrollOffset; + $this->cursorPos = mb_strlen($this->buffer); break; case "\e[H": // home