Skip to content

Commit

Permalink
Merge pull request #87 from Lynesth/patch-7
Browse files Browse the repository at this point in the history
Adds custom control mapping
  • Loading branch information
AydinHassan authored May 1, 2018
2 parents b59108c + b4968db commit 82796c1
Showing 1 changed file with 48 additions and 8 deletions.
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 @@ -180,6 +199,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 @@ -188,17 +231,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

0 comments on commit 82796c1

Please sign in to comment.