Script UI on one page
How to write a tool with runio/script-ui: the model, the rules, every function and one whole tool. For people, and for an AI assistant that is asked to write a tool. The README says each point at length, and src/functions.php describes every argument.
The model
A tool is one PHP script in your folder of tools. It has no HTML, no JavaScript, no route and no form handling.
<?php
// Hello
// My first tool.
use function Runio\ScriptUi\{title, text, button, success};
title('Hello');
$name = text('Your name');
if (button('Greet') && $name !== '') {
success('Hello, ' . $name . '.');
}- The script runs from top to bottom, and it runs again from the top on every interaction: an input that changed, a button that was pressed.
- An input returns its value.
text('Your name')draws the field and returns what the user typed. The library keeps what the inputs hold between two runs, for each user and each tool. - A button is an
if.button('Greet')draws the button, and returnstrueonly in the run that its click started. - Nothing else outlives a run. A variable is gone when the run ends. What a tool needs again comes from its inputs or from your own storage.
- The first comment of the file names the tool in the list of tools, and the comment lines after it describe it.
tools/refund.phpis the toolrefund. A file whose name starts with_is a helper and never a tool.
To try the tools on your own computer, run php vendor/bin/script-ui serve tools and open http://localhost:8765.
Rules
- Draw with the functions of this page only. No
echo, no HTML, and never$_GET,$_POSTor$_SESSION. Everything is shown as text: a label, a cell or a message can hold no HTML. - Change data only inside
if (button(...)). The script also runs for every page view and every changed input. Where the work cannot be undone, let the button ask first:confirm: 'Refund 2 orders?'. - What is not called is not drawn. Write
button('Greet') && $name !== ''in this order. The other way round, PHP does not callbutton()while the name is empty, and the button is gone. An input that a run does not draw loses its value. - Call
rerun()after the work when something above the button shows the data that has just changed. It ends the run and loads the page again. Messages written after the click are kept. - A label is a name. Two inputs or buttons with the same label on one page are an error until each has a
key:. In a loop, make the key from the row:button('Refund', key: 'refund-' . $order['id']). - Say what is wrong with an input under that input, with
field_error(), and askvalid()before the work is done.error()is for what belongs to no input. - A part of
columns(),expander()ortabs()is a function:fn () => ..., orfunction () use (&$limit): void { ... }to get a value out. Every part runs on every run, also a closed expander and a tab that is not in view. Out of sight is not private. - Work that takes long belongs to a worker: a job in a queue, a cron job. The tool starts it, and shows how far it is with
progress()andrefresh(). - End a run with
stop()orreturn, never withexit. - Who may open a tool is decided where the tools are served, with
auth:andallow:. Inside a tool,user()says who is asking.
Functions
Import the ones you use: use function Runio\ScriptUi\{title, text, table, button};. Pass the arguments after the first ones by name: number('Percent', min: 1, max: 50).
Text and numbers:
title(string $text): void // the heading of the page: call it first
heading(string $text): void
note(string $text): void // a paragraph of plain text. Line breaks are kept
code(string $text): void // fixed-width text: code, SQL, lines of a log
json(mixed $value): void // any value as readable JSON
link(string $label, string $url, bool $newTab = false): void // http, https, mailto, or a path of this site
divider(): void
metric(string $label, string|int|float $value, string|int|float|null $delta = null, bool $inverse = false): void
// one number that matters. $delta is a change such as "+4.2%". $inverse: going up is bad news
progress(string $label, int|float|null $value = null, int|float $max = 100, ?string $text = null): void
// a bar. It moves only when the page runs again, so call refresh() on the same page.
// $text replaces the percentage: "1,200 of 3,000 orders"Messages:
success(string $text): void
info(string $text): void
warning(string $text): void
error(string $text): void // what is wrong with one input belongs to field_error()Inputs. The label names the field. $help is a line under it. $key is needed only where two labels are the same.
text(string $label, string $default = '', ?string $placeholder = null, ?string $help = null, ?string $key = null): string
// one line, trimmed. '' while it is empty
textarea(string $label, string $default = '', int $rows = 4, ?string $placeholder = null, ?string $help = null, ?string $key = null): string
number(string $label, int|float|null $default = null, int|float|null $min = null, int|float|null $max = null, int|float|null $step = null, ?string $help = null, ?string $key = null): int|float|null
// null while it is empty. Kept between $min and $max
select(string $label, array $options, mixed $default = null, ?string $help = null, ?string $key = null, ?bool $byKey = null): mixed
// one of the options, the first until the user chooses. ['paid', 'shipped'] returns the text.
// [7 => 'Last 7 days', 30 => 'Last 30 days'] shows the texts and returns 7 or 30
radio(string $label, array $options, mixed $default = null, bool $horizontal = false, ?string $help = null, ?string $key = null, ?bool $byKey = null): mixed
// as select(), with every option in view
multiselect(string $label, array $options, array $default = [], bool $horizontal = false, ?string $help = null, ?string $key = null, ?bool $byKey = null): array
// a tick box for every option. Returns the ticked ones as a list, [] for none
checkbox(string $label, bool $default = false, ?string $help = null, ?string $key = null): bool
date_input(string $label, string|\DateTimeInterface|null $default = null, string|\DateTimeInterface|null $min = null, string|\DateTimeInterface|null $max = null, ?string $help = null, ?string $key = null): ?string
// "YYYY-MM-DD", or null while it is empty
file_input(string $label, ?array $types = null, bool $multiple = false, ?int $maxSize = null, ?string $help = null, ?string $key = null): Upload|array|null
// the file that the user uploaded, on every run until it is removed, or null. $types: ['csv', 'xlsx'].
// An Upload has ->name, ->size, ->path, ->contents(), ->rows() (a CSV file as rows), ->saveTo($path) and ->forget()
field_error(string $field, string $message): void // a note under the input with this label or key. Call it below that input
valid(): bool // true while nothing was found wrong with an input in this runTables and charts:
table(iterable|\Closure $rows, bool $selectable = false, ?array $columns = null, ?string $key = null, string $rowKey = 'id', int $pageSize = 25, bool $search = false, ?string $empty = null, ?array $sortable = null, ?\Closure $count = null): array
// $rows: arrays or objects, as a query returns them. A header sorts, and a long table has pages.
// $selectable: a tick box in every row. The ticked rows come back, so give every row an 'id' (or name that column with $rowKey).
// $columns: ['id', 'total'] chooses columns, ['id' => 'Order'] also renames them. $search: a search box. $empty: what to say without rows.
// Above some 20,000 rows pass a function in place of the rows, with $sortable and $count: see the README.
chart(iterable $rows, string $x, string|array $y, string $type = 'bar', ?string $title = null, int $height = 240, bool $data = true): void
// $x: the column with the labels. $y: the column with the numbers, or several: ['orders' => 'Orders', 'refunds' => 'Refunds'].
// $type: 'bar' or 'line'Actions:
button(string $label, string $style = 'default', ?string $confirm = null, ?string $yes = null, ?string $no = null, ?string $key = null): bool
// true only in the run that its click started. $style: 'default', 'primary' or 'danger'.
// $confirm: a question to ask first. Then it is true only after a yes. Keep the question the same from run to run
download(string $label, iterable|string|\Closure $content, string $file, string $style = 'default', ?string $key = null): void
// hands the user a file. Rows become CSV, or JSON when $file ends in ".json". Text is sent as it is.
// A function is called only when the user asks for the file
csv(iterable $rows, ?array $columns = null, string $separator = ',', bool $allowFormulas = false, bool $bom = true): string
// rows as CSV text, for download() when other columns or another separator are wantedLayout and flow:
columns(callable ...$columns): void // side by side: one function for each column
expander(string $label, callable $content, bool $open = false, ?string $key = null): void // a part that opens and closes
tabs(array $tabs, ?string $key = null): void // ['Orders' => fn () => table($orders), ...]: one function for each tab
refresh(int $seconds, ?int $stopAfter = 3600): void
// the page runs again by itself, $seconds (2 or more) after every answer. Call it near the top,
// and not inside expander() or tabs()
stop(): never // ends the run here. What was drawn so far is shown
rerun(): never // ends the run and loads the page again
user(): ?string // who is using the tool, as the login check named them. null without a login checkServing the tools. The application calls these, not a tool.
serve(string $directory, ?callable $auth = null, ?callable $log = null, ?string $name = null, ?bool $debug = null, ?string $base = null, ?string $language = null, ?array $texts = null, ?string $uploads = null, ?callable $allow = null, ?array $variables = null): void
// serves every PHP file of a folder as a tool, from one script behind the web server
respond(string $directory, ?callable $auth = null, ?callable $log = null, ?string $name = null, ?bool $debug = null, ?string $base = null, ?string $language = null, ?array $texts = null, ?string $uploads = null, ?callable $allow = null, ?array $variables = null, ?object $session = null): Http\Response
// the same for Symfony and Laravel: it hands the page back as ->status, ->headers and ->body
configure(?callable $auth = null, ?callable $log = null, ?bool $debug = null, ?string $name = null, ?string $language = null, ?array $texts = null, ?string $uploads = null, ?callable $allow = null): void
// the settings for a script that the web server runs by itself
clean_uploads(?string $folder = null): int // deletes uploaded files that are older than a day, for a daily jobOne whole tool
<?php
// Refund orders
// Find the orders of a customer and refund the ticked ones.
use function Runio\ScriptUi\{title, text, select, info, table, button, success, rerun};
/** @var Shop $shop your own code. serve(variables: ['shop' => $shop]) hands it to every tool */
title('Refund orders');
$email = text('Customer email', placeholder: 'ava@example.com');
$status = select('Status', ['paid', 'shipped']);
if ($email === '') {
info('Type a customer email to see their orders.');
return;
}
$picked = table(
$shop->orders($email, $status), // rows with the keys id, total and created_at
selectable: true,
columns: ['id' => 'Order', 'total' => 'Total', 'created_at' => 'Placed on'],
empty: 'No orders.',
);
// The button comes last here on purpose: while no row is ticked, there is nothing to press.
if ($picked && button('Refund selected', style: 'danger', confirm: 'Refund ' . count($picked) . ' orders?')) {
foreach ($picked as $order) {
$shop->refund($order['id']);
}
success('Refunded ' . count($picked) . ' orders.');
rerun(); // the table above now shows what is left
}More patterns
What is wrong with an input:
$code = text('Code');
$percent = number('Percent', min: 1, max: 50);
if (button('Create coupon', style: 'primary')) {
if (preg_match('/^[A-Z0-9]{4,10}$/', $code) !== 1) {
field_error('Code', 'Use 4 to 10 capital letters or digits.');
}
if ($percent === null) {
field_error('Percent', 'Enter a percent from 1 to 50.');
}
if (valid()) {
$shop->addCoupon($code, $percent);
success('Coupon ' . $code . ' created.');
}
}A file from the user, and a file for the user:
$file = file_input('Orders as CSV', types: ['csv']);
if ($file !== null) {
$rows = $file->rows(); // the first line names the columns, and every cell is text
table($rows);
if (button('Import ' . count($rows) . ' orders')) {
$shop->import($rows);
$file->forget(); // done with it: delete the file
success('Imported ' . count($rows) . ' orders.');
rerun();
}
}
download('Export all', fn () => csv($shop->allOrders(), columns: ['id' => 'Order', 'total']), 'orders.csv');Side by side, an expander and tabs:
columns(
fn () => metric('Orders', count($orders)),
fn () => metric('Revenue', number_format($revenue, 2), '+4.2%'),
);
$limit = 100;
expander('Advanced options', function () use (&$limit): void {
$limit = number('Limit', default: 100, min: 1) ?? 100;
});
tabs([
'Orders' => fn () => table($orders, pageSize: 10),
'Per day' => fn () => chart($perDay, x: 'day', y: 'revenue', title: 'Revenue per day'),
]);A task that takes long:
$export = $shop->latestExport(); // a row that your worker keeps up to date
if ($export !== null && $export['done'] < $export['total']) {
refresh(2);
progress('Exporting orders', $export['done'], $export['total'], text: $export['done'] . ' of ' . $export['total'] . ' orders');
return;
}
if (button('Start the export', style: 'primary')) {
$shop->startExport(); // hands the work over and comes back at once
rerun();
}What is not there
A function that is not on this page does not exist. This is what people look for and do not find:
- Nothing draws HTML, Markdown or a picture: no
html(),markdown()orimage(). - Nothing keeps a value between runs but the inputs and your own storage: no
state()and nosession(). - No
form()that collects inputs and sends them together. Every changed input runs the script, and a text field does when the user presses Enter or leaves it. - No button inside a row of a table. Let the user tick rows and put the button under the table, or draw one button for each row in a loop.
- No
redirect(), nosidebar(), no dialog besidesconfirm:, no theme and no CSS of your own. - No
slider(), no input for a time or a password, and no way to switch an input or a button off: leave it out instead. - Charts are bar and line charts.
Where the tools are served
// public/admin.php: the only file of all this that lies in the web root
require __DIR__ . '/../vendor/autoload.php';
Runio\ScriptUi\serve(
__DIR__ . '/../tools',
auth: fn () => $_SESSION['admin_email'] ?? null, // who is asking, or null to refuse
allow: fn (mixed $user, string $tool) => $tool !== 'payroll' || $user === 'ava@example.com',
variables: ['shop' => $shop],
);Without auth: the tools answer only to a browser on the computer they run on. In Symfony or Laravel a controller calls respond() with the same settings: see "Inside Symfony and Laravel" in the README.