Skip to content

Implement item shortcuts #176

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 7 commits into from
Apr 30, 2019
Merged
Show file tree
Hide file tree
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
42 changes: 39 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
* [Menu Methods](#menu-methods)
* [Redrawing the Menu](#redrawing-the-menu)
* [Getting, Removing and Adding items](#getting-removing-and-adding-items)
* [Custom Control Mapping](#custom-control-mapping)
* [Custom Control Mapping](#custom-control-mapping)
* [Item Keyboard Shortcuts](#item-keyboard-shortcuts)
* [Dialogues](#dialogues)
* [Flash](#flash)
* [Confirm](#confirm)
Expand All @@ -61,7 +62,7 @@
* [Number](#number-input)
* [Password](#password-input)
* [Custom Input](#custom-input)
* [Dialogues & Input Styling](#dialogues-input-styling)
* [Dialogues & Input Styling](#dialogues--input-styling)
* [Docs Translations](#docs-translations)
* [Integrations](#integrations)

Expand Down Expand Up @@ -888,7 +889,7 @@ $menu = (new CliMenuBuilder)
$menu->open();
```

### Custom Control Mapping
## Custom Control Mapping

This functionality allows to map custom key presses to a callable. For example we can set the key press "x" to close the menu:

Expand Down Expand Up @@ -933,6 +934,41 @@ $menu->addCustomControlMapping('C', $myCallback);
$menu->open();
```

## Item Keyboard Shortcuts

If you enable auto shortcuts `CliMenuBuilder` will parse the items text and check for shortcuts. Any single character inside square brackets
will be treated as a shortcut. Pressing that character when the menu is open will trigger that items callable.

This functionality works for split items as well as sub menus. The same characters can be used inside sub menus and the
callable which is invoked will depend on which menu is currently open.

Note: all shortcuts are lower cased.

To enable this automatic keyboard shortcut mapping simply call `->enableAutoShortcuts()`:

```php
<?php

use PhpSchool\CliMenu\Builder\CliMenuBuilder;
use PhpSchool\CliMenu\CliMenu;

$myCallback = function(CliMenu $menu) {
// Do something
};

$menu = (new CliMenuBuilder)
->enableAutoShortcuts()
->addItem('List of [C]lients', $myCallback)
->build();

$menu->open();

//Pressing c will execute $myCallback.
```

You can customise the shortcut matching by passing your own regex to `enableAutoShortcuts`. Be careful to only match
one character in the first capture group or an exception will be thrown.

### Dialogues

#### Flash
Expand Down
39 changes: 39 additions & 0 deletions examples/shortcuts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

use PhpSchool\CliMenu\Builder\SplitItemBuilder;
use PhpSchool\CliMenu\CliMenu;
use PhpSchool\CliMenu\Builder\CliMenuBuilder;

require_once(__DIR__ . '/../vendor/autoload.php');

$itemCallable = function (CliMenu $menu) {
echo $menu->getSelectedItem()->getText();
};

$menu = (new CliMenuBuilder)
->enableAutoShortcuts()
->setTitle('Basic CLI Menu')
->addItem('[F]irst Item', $itemCallable)
->addItem('Se[c]ond Item', $itemCallable)
->addItem('Third [I]tem', $itemCallable)
->addSubMenu('[O]ptions', function (CliMenuBuilder $b) {
$b->setTitle('CLI Menu > Options')
->addItem('[F]irst option', function (CliMenu $menu) {
echo sprintf('Executing option: %s', $menu->getSelectedItem()->getText());
})
->addLineBreak('-');
})
->addSplitItem(function (SplitItemBuilder $b) use ($itemCallable) {
$b->addItem('Split Item [1]', function() { echo 'Split Item 1!'; })
->addItem('Split Item [2]', function() { echo 'Split Item 2!'; })
->addItem('Split Item [3]', function() { echo 'Split Item 3!'; })
->addSubMenu('Split Item [4]', function (CliMenuBuilder $builder) use ($itemCallable) {
$builder->addItem('Third [I]tem', $itemCallable);

});
})
->addLineBreak('-')
->build();

$menu->open();

110 changes: 105 additions & 5 deletions src/Builder/CliMenuBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@

use PhpSchool\CliMenu\Action\ExitAction;
use PhpSchool\CliMenu\Action\GoBackAction;
use PhpSchool\CliMenu\Exception\InvalidShortcutException;
use PhpSchool\CliMenu\MenuItem\AsciiArtItem;
use PhpSchool\CliMenu\MenuItem\LineBreakItem;
use PhpSchool\CliMenu\MenuItem\MenuItemInterface;
use PhpSchool\CliMenu\MenuItem\MenuMenuItem;
use PhpSchool\CliMenu\MenuItem\SelectableItem;
use PhpSchool\CliMenu\CliMenu;
use PhpSchool\CliMenu\MenuItem\SplitItem;
use PhpSchool\CliMenu\MenuItem\StaticItem;
use PhpSchool\CliMenu\MenuStyle;
use PhpSchool\CliMenu\Terminal\TerminalFactory;
Expand Down Expand Up @@ -56,6 +58,22 @@ class CliMenuBuilder
*/
private $disabled = false;

/**
* Whether or not to auto create keyboard shortcuts for items
* when they contain square brackets. Eg: [M]y item
*
* @var bool
*/
private $autoShortcuts = false;

/**
* Regex to auto match for shortcuts defaults to looking
* for a single character encased in square brackets
*
* @var string
*/
private $autoShortcutsRegex = '/\[(.)\]/';

/**
* @var bool
*/
Expand Down Expand Up @@ -87,6 +105,8 @@ public function addMenuItem(MenuItemInterface $item) : self
{
$this->menu->addItem($item);

$this->processItemShortcut($item);

return $this;
}

Expand Down Expand Up @@ -135,6 +155,10 @@ public function addSubMenu(string $text, \Closure $callback) : self
{
$builder = self::newSubMenu($this->terminal);

if ($this->autoShortcuts) {
$builder->enableAutoShortcuts($this->autoShortcutsRegex);
}

$callback = $callback->bindTo($builder);
$callback($builder);

Expand All @@ -147,12 +171,14 @@ public function addSubMenu(string $text, \Closure $callback) : self
$menu->setStyle($this->menu->getStyle());
}

$this->menu->addItem(new MenuMenuItem(
$this->menu->addItem($item = new MenuMenuItem(
$text,
$menu,
$builder->isMenuDisabled()
));


$this->processItemShortcut($item);

return $this;
}

Expand All @@ -167,24 +193,98 @@ public function addSubMenuFromBuilder(string $text, CliMenuBuilder $builder) : s
$menu->setStyle($this->menu->getStyle());
}

$this->menu->addItem(new MenuMenuItem(
$this->menu->addItem($item = new MenuMenuItem(
$text,
$menu,
$builder->isMenuDisabled()
));

$this->processItemShortcut($item);

return $this;
}

public function enableAutoShortcuts(string $regex = null) : self
{
$this->autoShortcuts = true;

if (null !== $regex) {
$this->autoShortcutsRegex = $regex;
}

return $this;
}

private function extractShortcut(string $title) : ?string
{
preg_match($this->autoShortcutsRegex, $title, $match);

if (!isset($match[1])) {
return null;
}

if (mb_strlen($match[1]) > 1) {
throw InvalidShortcutException::fromShortcut($match[1]);
}

return isset($match[1]) ? strtolower($match[1]) : null;
}

private function processItemShortcut(MenuItemInterface $item) : void
{
$this->processIndividualShortcut($item, function (CliMenu $menu) use ($item) {
$menu->executeAsSelected($item);
});
}

private function processSplitItemShortcuts(SplitItem $splitItem) : void
{
foreach ($splitItem->getItems() as $item) {
$this->processIndividualShortcut($item, function (CliMenu $menu) use ($splitItem, $item) {
$current = $splitItem->getSelectedItemIndex();

$splitItem->setSelectedItemIndex(
array_search($item, $splitItem->getItems(), true)
);

$menu->executeAsSelected($splitItem);

if ($current !== null) {
$splitItem->setSelectedItemIndex($current);
}
});
}
}

private function processIndividualShortcut(MenuItemInterface $item, callable $callback) : void
{
if (!$this->autoShortcuts) {
return;
}

if ($shortcut = $this->extractShortcut($item->getText())) {
$this->menu->addCustomControlMapping(
$shortcut,
$callback
);
}
}

public function addSplitItem(\Closure $callback) : self
{
$builder = new SplitItemBuilder($this->menu);

if ($this->autoShortcuts) {
$builder->enableAutoShortcuts($this->autoShortcutsRegex);
}

$callback = $callback->bindTo($builder);
$callback($builder);

$this->menu->addItem($builder->build());

$this->menu->addItem($splitItem = $builder->build());

$this->processSplitItemShortcuts($splitItem);

return $this;
}

Expand Down
31 changes: 31 additions & 0 deletions src/Builder/SplitItemBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ class SplitItemBuilder
*/
private $splitItem;

/**
* Whether or not to auto create keyboard shortcuts for items
* when they contain square brackets. Eg: [M]y item
*
* @var bool
*/
private $autoShortcuts = false;

/**
* Regex to auto match for shortcuts defaults to looking
* for a single character encased in square brackets
*
* @var string
*/
private $autoShortcutsRegex = '/\[(.)\]/';

public function __construct(CliMenu $menu)
{
$this->menu = $menu;
Expand Down Expand Up @@ -59,6 +75,10 @@ public function addSubMenu(string $text, \Closure $callback) : self
{
$builder = CliMenuBuilder::newSubMenu($this->menu->getTerminal());

if ($this->autoShortcuts) {
$builder->enableAutoShortcuts($this->autoShortcutsRegex);
}

$callback = $callback->bindTo($builder);
$callback($builder);

Expand All @@ -80,6 +100,17 @@ public function setGutter(int $gutter) : self

return $this;
}

public function enableAutoShortcuts(string $regex = null) : self
{
$this->autoShortcuts = true;

if (null !== $regex) {
$this->autoShortcutsRegex = $regex;
}

return $this;
}

public function build() : SplitItem
{
Expand Down
21 changes: 20 additions & 1 deletion src/CliMenu.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ public function disableDefaultControlMappings() : void
public function setDefaultControlMappings(array $defaultControlMappings) : void
{
$this->defaultControlMappings = $defaultControlMappings;
}
}

/**
* Adds a custom control mapping
Expand Down Expand Up @@ -379,6 +379,25 @@ public function getSelectedItem() : MenuItemInterface
: $item;
}

public function setSelectedItem(MenuItemInterface $item) : void
{
$key = array_search($item, $this->items, true);

if (false === $key) {
throw new \InvalidArgumentException('Item does not exist in menu');
}

$this->selectedItem = $key;
}

public function executeAsSelected(MenuItemInterface $item) : void
{
$current = $this->items[$this->selectedItem];
$this->setSelectedItem($item);
$this->executeCurrentItem();
$this->setSelectedItem($current);
}

/**
* Execute the current item
*/
Expand Down
14 changes: 14 additions & 0 deletions src/Exception/InvalidShortcutException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace PhpSchool\CliMenu\Exception;

/**
* @author Aydin Hassan <[email protected]>
*/
class InvalidShortcutException extends \RuntimeException
{
public static function fromShortcut(string $shortcut) : self
{
return new static(sprintf('Shortcut key must be only one character. Got: "%s"', $shortcut));
}
}
2 changes: 1 addition & 1 deletion test/Builder/CliMenuBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ public function testAddSplitItemWithClosureBinding() : void

$this->checkItems($menu->getItems()[0]->getItems(), $expected);
}

private function checkMenuItems(CliMenu $menu, array $expected) : void
{
$this->checkItems($this->readAttribute($menu, 'items'), $expected);
Expand Down