diff --git a/CHANGELOG.md b/CHANGELOG.md index d75f2aa8..d1746f54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Release Notes -## [Unreleased](https://github.com/laravel/prompts/compare/v0.1.13...main) +## [Unreleased](https://github.com/laravel/prompts/compare/v0.1.14...main) + +## [v0.1.14](https://github.com/laravel/prompts/compare/v0.1.13...v0.1.14) - 2023-12-27 + +* Ignore new PHPStan error by [@jessarcher](https://github.com/jessarcher) in https://github.com/laravel/prompts/pull/103 ## [v0.1.13](https://github.com/laravel/prompts/compare/v0.1.12...v0.1.13) - 2023-10-27 diff --git a/src/Prompt.php b/src/Prompt.php index ea4e99ae..1f50b102 100644 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -49,6 +49,11 @@ abstract class Prompt */ public mixed $validate; + /** + * The cancellation callback. + */ + protected static Closure $cancelUsing; + /** * Indicates if the prompt has been validated. */ @@ -113,7 +118,11 @@ public function prompt(): mixed if ($continue === false || $key === Key::CTRL_C) { if ($key === Key::CTRL_C) { - static::terminal()->exit(); + if (isset(static::$cancelUsing)) { + return (static::$cancelUsing)(); + } else { + static::terminal()->exit(); + } } return $this->value(); @@ -124,6 +133,14 @@ public function prompt(): mixed } } + /** + * Register a callback to be invoked when a user cancels a prompt. + */ + public static function cancelUsing(Closure $callback): void + { + static::$cancelUsing = $callback; + } + /** * How many new lines were written by the last output. */ diff --git a/tests/Feature/TextPromptTest.php b/tests/Feature/TextPromptTest.php index 27943ca5..2f47b46d 100644 --- a/tests/Feature/TextPromptTest.php +++ b/tests/Feature/TextPromptTest.php @@ -137,3 +137,10 @@ Prompt::validateUsing(fn () => null); }); + +it('allows customizing the cancellation', function () { + Prompt::cancelUsing(fn () => throw new Exception('Cancelled.')); + Prompt::fake([Key::CTRL_C]); + + text('What is your name?'); +})->throws(Exception::class, 'Cancelled.');