rob-revisited/extensions/externals/doc/samples/BrowseSample.php

67 lines
2.3 KiB
PHP

<?php
namespace App\Extensions\Externals;
use JumPHP\Externals\Entry;
use JumPHP\Externals\Externals;
use JumPHP\Renderer\Renderer;
use JumPHP\Scene\AbstractScene;
/**
* The folders the administrator shares with the game, and what is in them: up / down to choose, confirm to enter.
* Run: JUMPHP_SCENE='App\Extensions\Externals\BrowseSample' bin/jumphp run externals-demo
*/
final class BrowseSample extends AbstractScene
{
public const LABEL = 'Browse the shared folders: list() of a folder, entries with their size';
/** @var list<Entry> */
private array $entries = [];
private int $selected = 0;
private string $dir = '';
private string $error = '';
public function __construct(private Externals $externals)
{
}
public function enter(array $params = []): void
{
$this->open('');
}
private function open(string $dir): void
{
$this->dir = $dir;
$this->selected = 0;
$this->externals->list($dir)->then(
fn (array $entries) => $this->entries = $entries,
fn (\Throwable $e) => $this->error = $e->getMessage(),
);
}
public function update(float $dt): void
{
$n = max(1, count($this->entries));
if ($this->actions()->isPressed('down')) {
$this->selected = ($this->selected + 1) % $n;
} elseif ($this->actions()->isPressed('up')) {
$this->selected = ($this->selected + $n - 1) % $n;
} elseif ($this->actions()->isPressed('confirm') && ($this->entries[$this->selected] ?? null)?->isDir()) {
$this->open($this->entries[$this->selected]->path);
} elseif ($this->actions()->isPressed('back')) {
$this->open('');
}
}
public function render(Renderer $r): void
{
$r->clear([16, 20, 40]);
$this->font()->draw($r, 'SHARED: /' . strtoupper($this->dir), 8, 8, 1, [255, 208, 64]);
foreach ($this->entries as $i => $e) {
$color = $i === $this->selected ? [255, 255, 255] : [150, 160, 200];
$this->font()->draw($r, strtoupper($e->name()) . ($e->isDir() ? '/' : ' ' . $e->size . ' B'), 12, 26 + $i * 11, 1, $color);
}
$this->font()->draw($r, $this->error !== '' ? strtoupper($this->error) : 'UP/DOWN, CONFIRM: ENTER, BACK: TOP', 8, 166, 1, [120, 130, 170]);
}
}