-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrealtime.php
More file actions
65 lines (55 loc) · 1.56 KB
/
Copy pathrealtime.php
File metadata and controls
65 lines (55 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
/**
* Realtime updates — `Cmd::tick` for periodic refresh; the model
* re-schedules itself after every tick to keep the loop alive.
*
* php examples/realtime.php
*
* Watch the clock. Press 'q' to quit.
*/
require __DIR__ . '/../vendor/autoload.php';
use SugarCraft\Core\Cmd;
use SugarCraft\Core\KeyType;
use SugarCraft\Core\Model;
use SugarCraft\Core\Msg;
use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Core\Program;
final class TickMsg implements Msg
{
public function __construct(public readonly float $now)
{
}
}
final class Realtime implements Model
{
public function __construct(public readonly float $now = 0.0)
{
}
public function init(): ?\Closure
{
return Cmd::tick(0.1, static fn (): Msg => new TickMsg(microtime(true)));
}
public function update(Msg $msg): array
{
if ($msg instanceof KeyMsg && $msg->type === KeyType::Char && $msg->rune === 'q') {
return [$this, Cmd::quit()];
}
if ($msg instanceof TickMsg) {
return [
new self($msg->now),
Cmd::tick(0.1, static fn (): Msg => new TickMsg(microtime(true))),
];
}
return [$this, null];
}
public function view(): string
{
if ($this->now === 0.0) {
return "Starting clock…\n";
}
$pretty = date('H:i:s', (int) $this->now) . sprintf('.%03d', ($this->now - (int) $this->now) * 1000);
return "Time: $pretty\n\n(q to quit)\n";
}
}
(new Program(new Realtime()))->run();