Skip to content

Commit

Permalink
Merge branch 'main' into multi-select-options-closure
Browse files Browse the repository at this point in the history
  • Loading branch information
GoodM4ven authored Mar 11, 2024
2 parents aaa2692 + 6f7d73f commit 1236c6c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/MultiSelectPrompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function __construct(
public int $scroll = 5,
public bool|string $required = false,
public mixed $validate = null,
public bool $validateOnToggle = false,
public string $hint = '',
) {
$this->options = $options instanceof Collection ? $options->all() : $options;
Expand Down Expand Up @@ -186,6 +187,9 @@ protected function toggleHighlighted(): void
}

$this->state = 'toggle';
if ($this->validateOnToggle) {
$this->validated = true;
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ function select(string $label, array|Collection $options, int|string|null $defau
* @param array<int|string>|Collection<int, int|string> $default
* @return array<int|string>
*/
function multiselect(string $label, array|Collection|Closure $options, array|Collection $default = [], int $scroll = 5, bool|string $required = false, mixed $validate = null, string $hint = 'Use the space bar to select options.'): array
function multiselect(string $label, array|Collection|Closure $options, array|Collection $default = [], int $scroll = 5, bool|string $required = false, mixed $validate = null, bool $validateOnToggle = false, string $hint = 'Use the space bar to select options.'): array
{
return (new MultiSelectPrompt(...func_get_args()))->prompt();
}
Expand Down
19 changes: 19 additions & 0 deletions tests/Feature/MultiSelectPromptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,25 @@
Prompt::assertOutputContains('You must select at least one color.');
});

it('can validate automatically upon toggling options', function () {
Prompt::fake([Key::DOWN, Key::SPACE, Key::SPACE, Key::UP, Key::SPACE, Key::ENTER]);

$result = multiselect(
label: 'What was the reason for the guard\'s retirement?',
options: [
'arrow' => 'He took an arrow in the knee',
'swordless' => 'He lost his sword',
'dragone' => 'He defeated all dragons',
],
validate: fn ($values) => in_array('arrow', $values) ? null : 'Missing a joke!',
validateOnToggle: true,
);

expect($result)->toBe(['arrow']);

Prompt::assertOutputContains('Missing a joke!');
});

it('can fall back', function () {
Prompt::fallbackWhen(true);

Expand Down

0 comments on commit 1236c6c

Please sign in to comment.