Skip to content

Adds custom control mapping #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 48 additions & 8 deletions src/CliMenu.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,25 @@ class CliMenu
*/
protected $parent;

/**
* @var array
*/
protected $defaultControlMappings = [
'^P' => InputCharacter::UP,
'k' => InputCharacter::UP,
'^K' => InputCharacter::DOWN,
'j' => InputCharacter::DOWN,
"\r" => InputCharacter::ENTER,
' ' => InputCharacter::ENTER,
'l' => InputCharacter::LEFT,
'm' => InputCharacter::RIGHT,
];

/**
* @var array
*/
protected $customControlMappings = [];

/**
* @var Frame
*/
Expand Down Expand Up @@ -156,6 +175,30 @@ private function selectFirstItem() : void
}
}

/**
* Adds a custom control mapping
*/
public function addCustomControlMapping(string $input, callable $callable) : void
{
if (isset($this->defaultControlMappings[$input]) || isset($this->customControlMappings[$input])) {
throw new \InvalidArgumentException('Cannot rebind this input.');
}

$this->customControlMappings[$input] = $callable;
}

/**
* Removes a custom control mapping
*/
public function removeCustomControlMapping(string $input) : void
{
if (!isset($this->customControlMappings[$input])) {
throw new \InvalidArgumentException('This input is not registered.');
}

unset($this->customControlMappings[$input]);
}

/**
* Display menu and capture input
*/
Expand All @@ -164,17 +207,14 @@ private function display() : void
$this->draw();

$reader = new NonCanonicalReader($this->terminal);
$reader->addControlMappings([
'^P' => InputCharacter::UP,
'k' => InputCharacter::UP,
'^K' => InputCharacter::DOWN,
'j' => InputCharacter::DOWN,
"\r" => InputCharacter::ENTER,
' ' => InputCharacter::ENTER,
]);
$reader->addControlMappings($this->defaultControlMappings);

while ($this->isOpen() && $char = $reader->readCharacter()) {
if (!$char->isHandledControl()) {
$rawChar = $char->get();
if (isset($this->customControlMappings[$rawChar])) {
$this->customControlMappings[$rawChar]($this);
}
continue;
}

Expand Down