--- url: https://script-ui.runio.dev/guide/what-it-is-for.md --- # What it is for Every team that runs software has small jobs that somebody inside has to do now and then: refund an order, extend a trial, import a file from a supplier, send an invoice again. Each job is a few inputs, a button and a result. Such a job seldom gets a page of its own. A page costs a route, a controller, a template, validation and some JavaScript. That is a lot for something that five colleagues use twice a week. So a developer does the job by hand in the database, or writes a console command that nobody else can run. Script UI makes the page cost one script. ## Who does what * **A developer** writes each tool as one PHP script, says who may open it, and can read later who pressed what. * **Colleagues** in support, finance or operations open a tool from a list and use it. They never see code. * **Your application** stays in charge of the login, the rights and the data. Script UI has no users and no database of its own. * **A worker** of yours does the work that takes long. The tool starts it and shows how far it is. ## What a tool looks like Most tools are one of four kinds. Each links to a tool of the demo, with a picture and its source. | Kind | What the script does | In the demo | |---|---|---| | Change something | A few inputs, a table to tick rows in, a button that asks before it acts | [Refund orders](https://script-ui.runio.dev/examples.md#refund), [Give a coupon](https://script-ui.runio.dev/examples.md#coupon), [Ship orders](https://script-ui.runio.dev/examples.md#ship) | | Look something up | Filters, a table, the details of one row | [Customers](https://script-ui.runio.dev/examples.md#customers), [Order archive](https://script-ui.runio.dev/examples.md#archive) | | Bring data in or out | An upload that is checked before anything is saved, a download | [Import orders](https://script-ui.runio.dev/examples.md#import), [Export orders](https://script-ui.runio.dev/examples.md#export) | | Watch something | Numbers and charts that keep themselves up to date | [Sales dashboard](https://script-ui.runio.dev/examples.md#dashboard), [Audit log](https://script-ui.runio.dev/examples.md#audit) | ## Is it the right tool? Script UI is for a task. In three cases something else fits better. * **The page is for the public.** Every tool looks like every other tool, and it keeps what was entered in a session. Customers deserve a page of your application. * **The job is to manage records.** Lists with create, edit and delete, for many kinds of records, are what admin generators such as EasyAdmin, Filament and Nova are built for. They do that with far less code than a tool would need. Many teams will use both: the admin for the records, and a tool for the task that fits no record. A [link can open a tool with its fields filled in](https://github.com/RunIO-dev/runio-script-ui#links-that-fill-in-fields), so the admin can lead to it. * **The page needs its own design or its own interactions.** A tool takes what the library draws. Where that is not enough, build the page by hand. ## What it does not bring * No login and no users. `auth:` asks your application who is there. * No database layer. A tool calls your own code. * No queue and no worker. A tool starts your job and shows its numbers. * No theme. Every tool looks like every other tool. [Safety and limits](https://script-ui.runio.dev/guide/safety.md) lists what this version cannot do, in detail. ## If you know Streamlit The idea is the same: a script that runs again from the top on every interaction, and functions that draw something and return a value. This is what differs. * It is PHP, and it runs inside your application: behind your login, with your classes. * A run is one ordinary request. No process stays up between two runs, and there is no websocket. * Nothing lives in memory between two runs. What a tool needs again comes from its inputs, which the session keeps, or from your storage. Next: [How it works](https://script-ui.runio.dev/guide/how-it-works.md). --- --- url: https://script-ui.runio.dev/guide/how-it-works.md --- # How it works A tool is a script that runs from top to bottom. Every time the user changes an input or presses a button, the browser sends the whole form and **the script runs again**. Each function draws its part of the page and returns what the user did with it. ## What the functions return | You write | You get | |---|---| | `text('Customer email')` | what the user typed | | `select('Status', ['paid', 'shipped'])` | one of your options, whatever the browser sent | | `table($rows, selectable: true)` | the rows the user ticked | | `file_input('Orders', types: ['csv'])` | the uploaded file, on every run until it is removed | | `button('Save')` | `true` in the run that its click started, and only there | | `button('Delete', confirm: 'Delete 3 rows?')` | `true` only after the user answered yes to exactly that question | [All functions](https://script-ui.runio.dev/reference/functions.md) has the rest. ## Three things that follow **The order of the code is the order of the page.** What you call first stands at the top. An `if` around a part decides whether it is there. An early `return` ends the page. **Data changes behind a button.** The script also runs when somebody only changes a filter, and when a page refreshes by itself. Work that changes something belongs inside `if (button(...))`, which is true once for each click. ```php if (button('Refund', confirm: 'Refund order ' . $order['id'] . '?')) { $refunds->create($order['id']); // runs once, after a click and a yes success('Refunded.'); } ``` **The script keeps nothing between two runs.** A variable is gone when the run ends. What the user entered comes back through the input functions, because the library saves the inputs of every tool in the session. Everything else comes from your database, as in any PHP request. ## When the script runs again | The user | The script runs again | |---|---| | chooses an option, ticks a box, picks a date, changes a number | at once | | types into a text field | when they press Enter or leave the field | | types into the search box of a table | after a short pause in the typing | | presses a button | at once, and `button()` is true in that run | | does nothing, on a page that calls `refresh(30)` | every 30 seconds, while the page is in view. It waits while the user is in the middle of something, and pauses after an hour that nobody touched it | ## What the user notices * The page updates in place. With JavaScript only the content is swapped, and the keyboard focus stays where it was. Without JavaScript the page works as a plain form. * The inputs survive a reload. The link "Reset" in the header forgets them. * After an action, `rerun()` runs the script once more, so that a table above the button shows the new data. Messages written after the click are kept. ## The names of inputs Every input and every button has a key. It names the form field and the saved value, and it is made from the label: `'Customer email'` becomes `customer-email`. Two inputs with the same label on one page are an error until each has a key of its own, as in `text('Name', key: 'billing-name')`. In a loop, build the key from the row: ```php foreach ($orders as $order) { if (button('Refund', key: 'refund-' . $order['id'])) { $refunds->create($order['id']); } } ``` The README says [why keys are not simply numbered](https://github.com/RunIO-dev/runio-script-ui#keys). ## Where to go from here * [Your first tool](https://script-ui.runio.dev/tutorials/first-tool.md) builds a page in ten minutes. * [A tool that changes data](https://script-ui.runio.dev/tutorials/change-data.md) shows the confirmation and the checks. * [Safety and limits](https://script-ui.runio.dev/guide/safety.md) says what every request passes before your script runs. --- --- url: https://script-ui.runio.dev/guide/safety.md --- # Safety and limits A tool changes real data, so the library is strict where a mistake would hurt. This page says what it does by itself, what stays your job, and what this version cannot do. ## What a request passes The first two questions are asked on every request, also when a page only refreshes itself. The third is asked whenever a form comes in: a changed input, a pressed button, an upload, a refresh. A page that is only opened sends no form. Only after that does the first line of your script run. ## What the library does This list is the one of the README, word for word. * **No login check, no outside access.** Without `auth`, tools only answer to a browser on the computer they run on. The request must come from a loopback address, with a local host name, and must not look passed on (proxy headers, HTTP/1.0, `Connection: close`). No check of this kind can see through every proxy or tunnel, so anything that can be reached from outside needs `auth`. * **A tool can be closed to some users.** `allow:` is asked before anything of a tool runs, on every request, and only a plain `true` opens the tool. Without `allow:` every tool is open to everybody who gets past the login check. Both checks are settings of `serve()`: a tool file that the web server runs by itself knows nothing of them, which is why the folder of tools stays out of the web root. * **What a tool keeps belongs to one user.** The inputs, the uploaded files and the messages that the library keeps in a session are dropped when the login check names another user in that session, as after a login without a logout before it. The forms of the user before are not taken any more. The library knows a user by the name the login check gives: a text, a number, or an object that says who it is (`getUserIdentifier()`, `getAuthIdentifier()` or `__toString()`). A login check that returns `true`, an array or another object names nobody, and then the users of one session cannot be told apart. * **Forged requests are refused.** Every form carries a token. A button only counts on a form that was sent from the page itself. The "Reset" link carries a code of its own. * **Everything is escaped.** Labels, table cells and messages are text, never HTML. Output printed with `echo` is shown as text too. * **A strict Content-Security-Policy** on every page: no inline styles, no inline handlers, nothing from other sites, no framing. * **A download is a file, never a page.** It is sent with the order to save it, never as HTML or a script, and it may do nothing if it is opened in the browser after all. Its name is made safe, also when it contains something a user typed. In CSV that the library writes, formula cells are defused. Every download goes to the log with the name and the size of the file. When the log cannot be written (the `log` callback throws or returns false), the file is not sent. * **An uploaded file is out of reach.** It lies under a random name that says nothing about it, in a folder that only the PHP user reads. (That holds for the library's own folder on Linux and macOS. A folder you name with `uploads:` is as closed as you made it.) The page names it by a random handle that is not that name and only counts for the session, the tool and the field the file was uploaded to. No request can name a path, a file of another user or a file of another tool. The name the user gave is cleaned before it is shown or logged, and it is never used on the disk. The library does not serve uploads and does not run them. * **A page that refreshes changes nothing.** A run that the page starts by itself presses no button, takes no file and saves nothing, whatever its request says. It needs the token of the form like every other run. * **Selections come from your data.** `table()` returns rows from the array you passed in. The browser only says which rows are ticked, and a tick never moves to another row or another table. A row that the search of a table hides is not returned, and the search reads only the columns that are shown. * **A query gets nothing straight from the browser.** A table that reads its pages through a function hands that function a search text to bind as a parameter, a sort value out of your own `sortable:` list, and a limit and an offset that are whole numbers. A form cannot name another column, and a page that is not there ends at one that is. * **A column you leave out stays out.** What a table puts into the page about a row, besides the cells it shows, is made with a secret that never leaves the session. Neither the id of a row nor a column you left out with `columns:` can be read from the page, or guessed by trying values against it. * **Files are found by listing the folder.** An address can never point outside it. * **Error details stay private.** They are shown only while no login check is set, because then nobody but your own computer gets in. With a login check they go to the error log unless you pass `debug: true`. PHP warnings and notices are kept out of the page in the same way. What stays your job: decide who may open which tool (`allow:`) and who may do what inside one (`user()` tells you who is asking), and never change data outside an `if (button(...))` block, because the script also runs on every plain page view. ## Before colleagues get in {#checklist} 1. **Set `auth:`.** Without a login check the tools answer only on the computer they run on. 2. **Keep the folder of tools out of the web root.** Only the one script that calls `serve()` lies where the web server looks for files. Then try the address of a tool file: `/tools/refund.php` has to answer 403 or 404. 3. **Set `allow:`** when not every tool is for everybody who can log in. 4. **Change data only inside `if (button(...))`.** The script also runs when somebody changes a filter, and when a page refreshes by itself. 5. **Set `log:`** and keep the entries. They say who pressed what, with which inputs. 6. **Leave `debug:` off on the server.** With a login check, error details go to the error log and not into the page. 7. **Keep uploads small.** Set `maxSize:` and PHP's own limits as low as your tools need. 8. **In a framework:** end a run with `stop()` and never with `exit`. In Laravel, take the route out of the CSRF check and add `->block()`. [Inside your application](https://script-ui.runio.dev/tutorials/your-application.md) says why. ## Limits of this version Also word for word from the README. [What comes next](https://script-ui.runio.dev/roadmap.md) says which of them may go. * Uploads have no progress bar, and cannot be resumed or stopped once they are on their way. A field holds up to 20 files and a session 200. The kind of a file is judged by the ending of its name only. * Nothing limits the bytes that uploads take on the disk, only their number: a session keeps up to 200 files of the size you allow, for a day at most. Somebody who is logged in and means harm can use that. Keep `maxSize:` and PHP's limits as low as your tools need. * Uploaded files wait in PHP's temp folder unless you set `uploads:`. They are closed to other system users, but another PHP application that runs as the same user can read them. * While a tool works on a request, PHP holds the session, and other requests of the same user wait. That shows with a large upload that a tool reads for a long time. * A table gets all its rows from the script and searches, sorts and pages them itself, on every run. That is quick up to about twenty thousand rows: on a laptop a search took 0.1 seconds, and so did sorting by a text column. For more, pass a function and let the database search, sort and cut the pages. * A table that reads its pages through a function keeps ticks for the page on the screen only. It has no "filtered from" count, and it decides by the rows of one page which columns hold numbers. * `multiselect()` is a group of tick boxes. It has no search and no "select all", so it suits lists of up to a few dozen options. The ticks of one field are remembered between page views up to 8 KB of option values. Beyond that the next page view starts from the default again. * A message of `field_error()` is gone with the next run, unless the script says it again. Nothing keeps a note under its field until that field is corrected: check on every run for that. Only inputs can be marked, not a table and not a button. * Every tab of `tabs()` runs on every run. There is no way yet to run only the open one, and a link cannot open a tab or an expander. * `refresh()` runs the whole script and swaps the whole content. There is no way yet to refresh one part of a page, and the server pushes nothing: the page asks. When something above the place you look at grows or shrinks, the page moves under your eyes. * `progress()` shows two numbers that the tool has. The library has no queue and no worker, cannot stop a task and does not work out the time that is left. A bar moves when the page runs again, which `refresh()` does every two seconds at best. * Charts are bar and line charts with one axis and at most 8 series. * State lives in the session: PHP's own, or the one you pass to `respond()` with `session:`. Two browser tabs of the same tool share saved inputs. A session remembers the inputs of the 50 tools that were used last. * A script that runs on its own (without `serve()`) is told apart by its file and its path. Tools that share both and differ only in the query string (`index.php?page=refund`) work, but they do not remember their inputs separately. --- --- url: https://script-ui.runio.dev/guide/ai-assistant.md description: >- How to let an AI assistant write tools: the page that the package brings for it, the lines for AGENTS.md, Laravel Boost and Symfony AI Mate, and what a trial with ten tasks showed. --- # With an AI assistant An assistant has not seen this library when it was trained, so it has to read before it writes. The package brings what it needs: [`docs/on-one-page.md`](https://script-ui.runio.dev/reference/on-one-page.md) has the rules, every function with its arguments and one whole tool. The tests of the library hold that page against the code, so it names no function and no argument that is not there. **Tell the assistant that the page is there.** Put these lines into the file that your assistant reads in every session, such as `AGENTS.md` or `CLAUDE.md`: ```markdown ## Internal tools The scripts in `tools/` are internal tools made with runio/script-ui. Before you write or change one, read `vendor/runio/script-ui/docs/on-one-page.md`. It has the rules and every function. A function that is not on that page does not exist. ``` Then ask for a tool as you would ask a colleague: "Write a tool that finds the orders of a customer and refunds the ticked ones." **Laravel Boost** tells the assistant the same by itself. The package has lines for it in `resources/boost/guidelines/core.blade.php`: they point at the page too, and they add the rules that matter most. `php artisan boost:install` lists `runio/script-ui` among the third-party guidelines. Tick it, and Boost writes the lines into the instruction file of your assistant. **Symfony AI Mate** asks nothing. The `composer.json` of the package names the same text under `extra.ai-mate`, and `vendor/bin/mate discover` writes it into `mate/AGENT_INSTRUCTIONS.md`. Both were tried with a fresh application: Laravel 13 with Boost 2.10, and Symfony 8.1 with AI Mate 0.15. **Read what it wrote.** A tool is short, so that takes a minute. Look at three things: that data changes only inside `if (button(...))`, that a button asks first when its work cannot be undone, and who may open the tool (`allow:`). **How much the page helps was tried**, with ten small tasks and two models. [`e2e/assistants/README.md`](https://github.com/RunIO-dev/runio-script-ui/blob/main/e2e/assistants/README.md) has the tasks, the checks and the counts. ## What a trial showed Ten small tools were asked of an assistant that had never seen the library: a form that says what is wrong under its fields, a CSV import, a page with tabs, a task that takes long and six more. Each task went to two models in three ways: without the help, with the page in the package, and with the page and the lines above. A browser used every tool that came back. A tool counts when it passes every test of its task. | Model | The help | Tools that work | Tokens read | Cost of a tool | |---|---|---|---|---| | Sonnet 5.5 | none | 10 of 10 | 146,000 | $0.19 | | Sonnet 5.5 | the page | 10 of 10 | 82,000 | $0.10 | | Sonnet 5.5 | the page and the lines | 10 of 10 | 48,000 | $0.07 | | Haiku 5.5 | none | 8 of 10 | 157,000 | $0.012 | | Haiku 5.5 | the page | 10 of 10 | 142,000 | $0.012 | | Haiku 5.5 | the page and the lines | 9 of 10 | 43,000 | $0.004 | * With the help, 39 of 40 tools worked at the first try. Without it, 18 of 20. That difference is small, and with one run for each cell it can be chance. * The stronger model wrote ten working tools either way. What the help changed for it is the effort: with the lines it read a third of the tokens, and a tool cost 7 cents where it had cost 19. * The three tools that failed have the same mistake: a function that is called and not imported with `use function`. It is the first thing to look for when a tool of an assistant ends in an error. The trial ran on 2026-11-28 with Claude Code, and the assistants could run nothing: a tool had to be right as it was written. Tokens and cost are the median of ten runs. [The notes of the trial](https://github.com/RunIO-dev/runio-script-ui/blob/main/e2e/assistants/README.md) have the tasks, the checks, every run, and what such a trial cannot say. ## On the web An assistant that reads the web finds the same texts here, as plain markdown: * [`/llms.txt`](https://script-ui.runio.dev/llms.txt) lists the pages of this site, and names the page to read first. * /reference/on-one-page.md is that page: [Script UI on one page](https://script-ui.runio.dev/reference/on-one-page.md). * [`/llms-full.txt`](https://script-ui.runio.dev/llms-full.txt) holds every page of the site in one file. * Every page is there as markdown too. Put `.md` in the place of `.html`. The page in the package is the one that fits the version you installed. This site describes the newest one. --- --- url: https://script-ui.runio.dev/tutorials/first-tool.md --- # 1. Your first tool You need PHP 8.2 or newer and Composer. At the end you have a page with an input, a button and a table that filters. It takes about ten minutes. ## Install ```bash mkdir back-office && cd back-office composer require runio/script-ui mkdir tools ``` ## One file Put this into `tools/hello.php`: ```php \[tools/hello.php] : ```bash php vendor/bin/script-ui serve tools ``` ![The list of tools: one entry, "Hello", with the description "My first tool."](https://script-ui.runio.dev/shots/list.png){.shot} The list shows every PHP file of the folder, except those whose name starts with `_`: they are helpers. The first comment of a file is the name of the tool, and the comment lines after it describe it. Open "Hello", type a name and press the button: ![The page before the click: an empty field "Your name" and a button "Greet".](https://script-ui.runio.dev/shots/hello-start.png){.shot} ![The page after the click: the field holds "Ava", and under the button stands the message "Hello, Ava."](https://script-ui.runio.dev/shots/hello.png){.shot} ## What happened 1. You typed a name and pressed "Greet". The browser sent the form. 2. The script ran again from the top. This time `text('Your name')` returned `'Ava'`, and `button('Greet')` returned `true`. 3. `success()` put the message on the page, and the browser swapped the new content in. Now change the name and leave the field. The script runs again, but nobody pressed the button, so `button()` is `false` in that run and the message is gone. A button is true for one run only. ## Inputs that filter a table A second file. Tools need no button at all: ```php \[tools/orders.php] 1041, 'customer' => 'Ava Morgan', 'status' => 'paid', 'total' => 84.50], ['id' => 1042, 'customer' => 'Omar Haddad', 'status' => 'shipped', 'total' => 19.90], ['id' => 1043, 'customer' => 'Lina Saleh', 'status' => 'paid', 'total' => 240.00], ['id' => 1044, 'customer' => 'Noah Becker', 'status' => 'refunded', 'total' => 52.25], ['id' => 1045, 'customer' => 'Omar Haddad', 'status' => 'paid', 'total' => 132.10], ['id' => 1046, 'customer' => 'Mia Rossi', 'status' => 'shipped', 'total' => 61.00], ]; title('Find orders'); $name = text('Customer', placeholder: 'Part of a name'); $status = select('Status', ['any', 'paid', 'shipped', 'refunded']); $found = array_values(array_filter($orders, fn (array $order): bool => ($name === '' || stripos($order['customer'], $name) !== false) && ($status === 'any' || $order['status'] === $status))); note(count($found) . ' of ' . count($orders) . ' orders.'); table($found, columns: ['id' => 'Order', 'customer' => 'Customer', 'status' => 'Status', 'total' => 'Total']); if ($found !== []) { download('Download as CSV', $found, 'orders.csv'); } ``` ![The tool "Find orders": the field "Customer" holds "ha", and the table shows the two orders of Omar Haddad out of six.](https://script-ui.runio.dev/shots/orders.png){.shot} Things to notice: * **Nothing is wired up.** Type a part of a name and press Enter, or choose a status: the script runs again, and the table shows what is left. * **`select()` returns one of your options**, whatever a browser sends. There is nothing to validate. * **`table()` sorts** when a header is clicked, and it cuts a long list into pages. * **`download()` hands over the rows as a CSV file.** A cell that a spreadsheet would take for a formula is made harmless. * **A reload keeps the filter.** The inputs of a tool are saved in the session. "Reset" in the header forgets them. ## What you did not write No route, no controller, no template, no form handling, no JavaScript and no CSS. The form token, the escaping and the page design came with the library. Next: [A tool that changes data](https://script-ui.runio.dev/tutorials/change-data.md). --- --- url: https://script-ui.runio.dev/tutorials/change-data.md --- # 2. A tool that changes data A tool that only shows data cannot do much harm. One that refunds orders can. This tutorial walks through two tools of the demo: one that asks before it acts, and one that checks what was typed. The demo is not part of the Composer package. It runs from a copy of the repository: ```bash git clone https://github.com/RunIO-dev/runio-script-ui.git cd runio-script-ui composer install php bin/script-ui serve examples/tools ``` ## Ask before you act This is the whole refund tool. `$shop` stands in for your own code. ```php {16-20,24-29,33-40} orders(email: $email, status: $status); $picked = table( $orders, selectable: true, columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'total' => 'Total'], empty: 'No ' . $status . ' orders for ' . $email . '.', ); $count = count($picked) === 1 ? '1 order' : count($picked) . ' orders'; if ($picked && button('Refund selected', style: 'danger', confirm: 'Refund ' . $count . '?')) { foreach ($picked as $order) { $shop->refund($order['id']); } success('Refunded ' . $count . '.'); rerun(); } ``` **Lines 16 to 20: nothing to do yet.** Without an email there is nothing to show. An early `return` ends the page there. **Lines 24 to 29: the table returns the ticked rows.** They come back exactly as you passed them in. The browser only says which rows are ticked, so `$order['id']` is an id of yours, never something that was typed into a request. **Line 33: the button.** It is drawn only while something is ticked. `confirm:` makes it ask first, and the question names what will happen: ![The refund tool with two ticked orders. Under the red button "Refund selected" a question asks "Refund 2 orders?" with the buttons "Yes" and "Cancel".](https://script-ui.runio.dev/shots/refund.png){.shot} `button()` returns `true` only after the user answered yes to exactly that question. When the selection changes in between, the question changes with it, and an old yes does not count. **Lines 34 to 39: the work.** It runs once. `rerun()` then runs the script again, so that the table above shows the orders that are left. The message survives that: ![The refund tool after the yes: the message "Refunded 2 orders." and one order left in the table.](https://script-ui.runio.dev/shots/refund-done.png){.shot} ## Check what was typed `field_error()` writes under an input what is wrong with it. `valid()` says whether anything was found wrong in this run. ```php {25-27,31-42,56-60} customer($email); $coupons = $customer === null ? [] : $shop->coupons($customer['email']); // Checked on every run: the note comes when the user leaves the field, and it // stays until the field is right. An empty field is left alone here, or a new // page would start full of red. The answer tells whoever may open this tool // who is a customer. That is fine in a back office, and nowhere else. if ($email !== '' && $customer === null) { field_error('Customer email', 'No customer has this email.'); } if (button('Give coupon', style: 'primary')) { // Checked when the button is pressed: what is missing, and what only counts now. if ($email === '') { field_error('Customer email', 'Enter the email of a customer.'); } if ($percent === null) { field_error('Discount in percent', 'Enter a discount from 1 to 50.'); } if ($until === null) { field_error('Valid until', 'Choose the last day of the coupon.'); } if ($percent > 20 && mb_strlen($reason) < 10) { field_error('Reason', 'More than 20 percent needs a reason. Write a sentence.'); } // The form still holds what was typed after the coupon was given. A second // press, or a double click, must not give a second one. Two requests at the // very same moment would both pass this check: where it matters, let the // database refuse the second one, with a unique key. foreach ($coupons as $coupon) { if ($coupon['until'] >= date('Y-m-d')) { field_error('Customer email', $customer['name'] . ' has a coupon already: ' . $coupon['code'] . ', valid until ' . $coupon['until'] . '.'); break; } } // field_error() does not stop the script. Nothing is done until all of it is right. if (valid()) { $code = $shop->addCoupon($customer['email'], $percent, $until); $coupons = $shop->coupons($customer['email']); success($customer['name'] . ' got ' . $percent . ' % off with the code ' . $code . ', until ' . $until . '.'); } } if ($customer !== null) { heading('Coupons of ' . $customer['name']); table( $coupons, columns: ['code' => 'Code', 'percent' => 'Percent', 'until' => 'Valid until', 'given' => 'Given on'], empty: 'No coupon yet.', ); } ``` ![The coupon tool after a press on "Give coupon": a red note under "Customer email" says "Enter the email of a customer.", and one under "Reason" says that more than 20 percent needs a reason.](https://script-ui.runio.dev/shots/coupon.png){.shot} There are two places to check, and this tool uses both. **On every run, lines 25 to 27.** The note comes as soon as the user leaves the field, and it stays until the field is right. An empty field is left alone there, or a new page would start full of red. **Behind the button, lines 31 to 42.** What is missing is asked for when the button is pressed. The first field that is wrong gets the keyboard focus, and software that reads the page out says the note. **Lines 56 to 60.** `field_error()` does not stop the script. Ask `valid()` before the work is done. The comment above line 47 names something every such tool has to think of: the form still holds what was typed after the coupon was given, so a second press must not give a second one. ## Who pressed what Colleagues will press buttons that change data. With `log:` every press and every download reaches a function of yours. This is the setting of the demo: ```php {17-26} fn () => $_SESSION['admin_email'] ?? null, */ return [ 'name' => 'Shop back office', // Called for every button a user presses and every file a user downloads. Here: one JSON line per action. // It returns false when the line could not be written. A download is then not sent. 'log' => static function (array $entry): bool { $file = __DIR__ . '/../var/audit.log'; if (!is_dir(dirname($file))) { mkdir(dirname($file), 0777, true); } return file_put_contents($file, json_encode($entry, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX) !== false; }, ]; ``` An entry says who it was, which tool and which button, whether a question was answered with yes, what every input held in that run, and what the page said was wrong. The demo shows its log in a tool of its own: ![The audit log of the demo: a table with the time, the user, the tool, the button and the inputs of every press.](https://script-ui.runio.dev/shots/audit.png){.shot} ## Rules for a tool that changes data 1. Change data only inside `if (button(...))`. The script also runs when somebody changes a filter. 2. Ask with `confirm:` before something that cannot be undone, and say in the question what will happen. 3. Check behind the button, and ask `valid()` before the work. 4. A button can be pressed twice, and by two people. Where that matters, let the database refuse the second one. 5. Call `rerun()` after the work when the page above the button shows the data. Next: [Inside your application](https://script-ui.runio.dev/tutorials/your-application.md). --- --- url: https://script-ui.runio.dev/tutorials/your-application.md --- # 3. Inside your application `script-ui serve` is for your own computer. It has no login check, so it answers nobody else. Colleagues need the tools on a server, behind the login of your application. There are two ways to get there. In plain PHP, one script behind your web server calls `serve()`, and the library sends the page. In Symfony or Laravel, a controller calls `respond()`, and the framework sends it. The rest of this page is the text of the README, word for word, so it cannot say something else than the manual does. ## A folder of tools behind your web server **A folder of tools.** Put this in a script behind your web server: ```php // public/admin.php: the only file of all this that lies in the web root require __DIR__ . '/../vendor/autoload.php'; require __DIR__ . '/../bootstrap.php'; // starts your session, connects your database Runio\ScriptUi\serve( __DIR__ . '/../tools', auth: fn () => $_SESSION['admin_email'] ?? null, // who is asking, or null to refuse log: fn (array $entry) => $auditLog->write($entry), // called for every button a user presses and every file a user downloads name: 'Back office', ); ``` An entry is an array with `time`, `user`, `tool`, `action` (the label of the button), `key`, `confirmed`, `inputs`, `error`, `field_errors` and `download`. `field_errors` holds what the page said is wrong in that run, by the key of the input: the messages of `field_error()`, and those of a file field that turned a file down. When it is not empty, the button most likely did not do its work. `inputs` holds what every input of the page returned in that run, by key. Not every value is a text: a tick box gives `true` or `false`, `multiselect()` a list of options, a table the ids of its ticked rows, and a file field the name, the size and the SHA-256 of the file. Turn the entry into JSON if your log takes one line of text. Every PHP file in the folder becomes a tool, listed on an index page. The first comment in a file is its title, more comment lines are its description. Files that start with `_` are helpers and are never served. **Keep the folder of tools out of the web root**, next to `vendor/`. Only the script above belongs where the web server looks for files. A file that the web server runs by itself never passes `serve()`, so nobody asks `auth:` or `allow:` about it. That goes for the helper files in the folder too. When the folder has to lie in the web root, close it in the web server. With Apache 2.4 that is a file `.htaccess` in the folder with the line `Require all denied` (it needs `AllowOverride`). With nginx it is `location ^~ /tools/ { deny all; }`. Then try it: `/tools/refund.php` has to answer 403 or 404. The list of tools says so when the folder lies in the web root. It says it only where error details are shown: on your own computer without a login check, or with `debug: true`. The library cannot see what the web server was told, so the note stays while the folder lies there. No note is not a proof that the folder is closed. Where the web server runs on another machine or in another container, PHP may not see the web root at all, and a link from the web root to the folder is not seen either. With a login check, error details go to the error log and not into the page. Pass `debug: true` where you develop. **Who may open which tool.** The login check lets somebody in, and then every tool is open to them. `allow:` decides for one user and one tool: ```php Runio\ScriptUi\serve( __DIR__ . '/../tools', auth: fn () => $_SESSION['admin_email'] ?? null, allow: fn (mixed $user, string $tool) => $permissions->has($user, 'tool.' . $tool), ); ``` It gets two things. The first is what your login check returned, as it is: a name, a number or the user object of your application. It is `null` when the login check only said `true`, and when there is no login check. The second is the id of the tool: the file name without `.php`, so `refund` for `tools/refund.php`. It answers `true` or `false`. Compare strictly where you compare: `in_array($user, $team, true)`. A tool that is not allowed is left out of the list, and whoever opens its address reads "Not allowed" before anything of the tool runs, whether that is a page view, a pressed button or a download. The question is asked on every request, so access that you take away ends with the next click, also on a page that is open. Only `true` opens a tool. Any answer other than `true` or `false`, and a check that throws, lets nobody in, and the reason goes to the error log. That holds for the list too: it asks once for every tool, so one answer that is neither closes the list for everybody. Keep the check cheap for the same reason. What somebody may do inside a tool they may open stays the tool's own `if`: `user()` tells it who is asking. A file name is an address, and "Not allowed" is another answer than "There is no tool at this address". So whoever is logged in can find out that a tool with a certain name is there, without seeing anything of it. Name the files with that in mind. **Variables for the tools.** A tool is a script of its own, so it sees no variable of yours. `variables:` hands some over by name: ```php Runio\ScriptUi\serve( __DIR__ . '/../tools', variables: ['orders' => $orderRepository, 'mailer' => $mailer], ); ``` Every tool of the folder then starts with `$orders` and `$mailer`. An object is the object itself. Everything else is a copy that a tool may change for itself. A line such as `/** @var OrderRepository $orders */` at the top of a tool tells your editor about the variable. By default tools are chosen with `?_tool=refund`. With `base: '/admin/tools'` they get clean addresses such as `/admin/tools/refund` (send those addresses to the script in your web server configuration). The list is at the base as you write it: at `/admin/tools`, or at `/admin/tools/` when the base ends with a slash. ## Inside Symfony and Laravel `serve()` sends the page itself. A framework wants to send it: a controller returns a response, and the framework adds its cookies and headers on the way out. `respond()` takes everything `serve()` takes. It works out the same page and hands it back, with `->status`, `->headers` and `->body`. One route leads every address under `base:` to it. The folder of tools lies next to `src/` or `app/`, outside the web root. Symfony: ```php // src/Controller/ToolsController.php use function Runio\ScriptUi\respond; final class ToolsController extends AbstractController { #[Route('/admin/tools/{tool}', defaults: ['tool' => ''], methods: ['GET', 'POST'])] public function tools(Request $request): Response { $page = respond( $this->getParameter('kernel.project_dir') . '/tools', base: '/admin/tools', auth: fn () => $this->getUser(), allow: fn ($user, string $tool) => $tool !== 'payroll' || $this->isGranted('ROLE_PAYROLL'), session: $request->getSession(), ); return new Response($page->body, $page->status, $page->headers); } } ``` Laravel: ```php // routes/web.php use function Runio\ScriptUi\respond; Route::match(['get', 'post'], '/admin/tools/{tool?}', function (Request $request) { $page = respond( base_path('tools'), base: '/admin/tools', auth: fn () => $request->user(), allow: fn ($user, string $tool) => Gate::forUser($user)->allows('open-tool', $tool), session: $request->session(), ); return response($page->body, $page->status, $page->headers); })->block(); ``` ```php // bootstrap/app.php, inside withMiddleware() $middleware->validateCsrfTokens(except: ['admin/tools', 'admin/tools/*']); ``` Pass the status and all of `$page->headers` on. They belong to the answer: where a pressed button leads on to, the name and the kind of a download, the order not to keep the page, and the rule that lets the script of the page run. **The session.** With `session:` the tools keep what they keep in the session of your application, under the one key `_script_ui`, and a logout ends it. Without it they use PHP's own session. In Laravel that is a second session next to Laravel's, and a logout of Laravel does not end it. The session needs room. What one tool keeps of its inputs is a few kilobytes as a rule and 256 KB at most, and a session remembers 50 tools. A session that lives in a cookie, such as Laravel's `cookie` driver, is too small: a cookie holds about 4 KB. A database column of 64 KB can run full too. The `BLOB` that Symfony's `PdoSessionHandler` creates on MySQL is one, and Symfony names `MEDIUMBLOB` for more. **The user.** `auth:` returns the user object of the framework, and `allow:` gets that object. `user()` and the log name it by `getUserIdentifier()` in Symfony and by `getAuthIdentifier()` in Laravel, which is the key of the row unless your model says otherwise. To show an email instead, return it: `auth: fn () => $request->user()?->email`. Then `allow:` gets the email too. What a tool keeps is bound to that name, so a name that changes, such as an email, starts from nothing once. For the same reason every place that serves tools in one session has to name a user the same way, and two kinds of users that share a number, such as admin 1 and customer 1, need names that differ. **Laravel checks every form for its own token.** The forms of the tools carry the token of the library, and the library checks it on every request. So the route is taken out of Laravel's check, with the line for `bootstrap/app.php` above. Without it Laravel 12 answers every pressed button with "419 Page Expired". Laravel 13 lets a button through when the browser says that the request comes from the same site. Browsers say that on HTTPS and on localhost only, so the line is needed there as well. The line takes every address under `admin/tools` out of Laravel's check, so keep those addresses for the tools alone. **Laravel does not lock its session.** Two requests of one user at the same moment each write the whole session, and the later one wins. What a tool kept in the other is lost then, for instance when a page that refreshes itself and a click meet. `->block()` lets the second wait for the first. It needs a cache that can lock, such as file, database or Redis. Symfony keeps its session in PHP's own by default, which locks. **Errors.** The error handling of the framework stays in charge. Laravel makes an error of every PHP warning, and Symfony does in its dev environment: a warning in a tool then ends the run, and the page says that the tool failed. After a fatal error the framework shows its own error page. What the tool had printed with `echo` by then stands in front of it. **End a run with `stop()`, not with `exit`.** `exit` ends the framework together with the tool. The page is still sent and what the tool keeps is saved, but nothing of the framework runs after that line. In Laravel the lock of `->block()` is not given back, and the next click of that user waits until it runs out, which is 10 seconds. **A file that a tool sends by itself.** Hand files to `download()`. A tool may also close its page with one `ob_end_clean()` and print an answer of its own, and `respond()` hands that back with its status and headers. It holds all of the answer in memory, so it cannot stream: give a large file a route of its own. A tool that closes every output buffer, as in `while (ob_get_level()) ob_end_clean();`, sends its answer past `respond()` and past the framework, without the cookies and headers of your application. The error log says so. **Another Content-Security-Policy.** The page brings its own. A browser applies every policy it gets, so a second one that your application adds to all its responses blocks the script and the styles of the page. Leave this route out of it. **What does not work.** `respond()` takes the request from PHP itself (`$_SERVER`, `$_GET`, `$_POST` and `$_FILES`). The test client of a framework does not fill those in, so a tool cannot be opened with `$client->request()` or `$this->get()`. `respond()` says so with an exception. Try a tool in a browser test. Servers that keep PHP running between requests, such as Laravel Octane, RoadRunner, Swoole and FrankenPHP in worker mode, are not supported. **What was tried.** Laravel 12 and 13 and Symfony 7.4 and 8.1, as they are after a fresh install, on PHP's built-in web server. The suite in [`e2e/frameworks`](https://github.com/RunIO-dev/runio-script-ui/blob/main/e2e/frameworks) runs the same tools inside each of them. Not tried with a framework: php-fpm, Apache and nginx, Symfony's prod environment, and a user that comes from a database. ## Before colleagues get in Go through the [checklist](https://script-ui.runio.dev/guide/safety.md#checklist): a login check, the folder outside the web root, who may open which tool, and a log. Next: [A table of 100,000 rows](https://script-ui.runio.dev/tutorials/big-table.md). --- --- url: https://script-ui.runio.dev/tutorials/big-table.md --- # 4. A table of 100,000 rows `table($rows)` gets all its rows from the script, and it searches, sorts and pages them itself. That is quick up to about twenty thousand rows. Beyond that the rows should stay in the database, and the table should ask for one page at a time. ## The tool of the demo The demo has such a table over 100,000 orders. The tool itself stays short: ```php {12-19} 'Order', 'customer' => 'Customer', 'placed' => 'Placed on', 'status' => 'Status', 'total' => 'Total'], search: true, sortable: ['id', 'customer', 'placed', 'total'], count: Archive::count(...), // gets the search, says how many orders it leaves ); if (button('Print labels')) { if ($picked === []) { warning('Tick the orders that need a label first.'); } else { success('Labels are on their way for ' . implode(', ', array_column($picked, 'id')) . '.'); } } ``` ![The order archive of the demo, searched for "haddad": a table of 25 orders with a search box, headers that sort, and a line that says which rows of how many are shown.](https://script-ui.runio.dev/shots/archive.png){.shot} In place of the rows, the table gets a function (line 13). It calls that function with a `TableQuery` and gets the rows of one page back. `sortable:` names the columns whose headers can be clicked, and `count:` is a second function that says how many rows the search leaves. In the demo both functions work the orders out from their numbers, so it needs no database. In a real tool they are two queries. ## With your database From here on this page is the text of the README, word for word. A table that gets all its rows is quick up to about twenty thousand of them. For more, pass a function in place of the rows. The table asks it for one page at a time, and the rows stay in the database: ```php use Runio\ScriptUi\TableQuery; // To LIKE, % and _ stand for any text. A user who types one means that character. $like = fn (string $search): string => '%' . strtr($search, ['!' => '!!', '%' => '!%', '_' => '!_']) . '%'; $picked = table( function (TableQuery $query) use ($pdo, $like): array { $rows = $pdo->prepare( "SELECT id, customer, total FROM orders WHERE customer LIKE :search ESCAPE '!'" . ' ORDER BY ' . ($query->sort ?? 'id') . ($query->descending ? ' DESC' : ' ASC') . ', id' . ' LIMIT :limit OFFSET :offset' ); $rows->bindValue('search', $like($query->search)); $rows->bindValue('limit', $query->limit, PDO::PARAM_INT); $rows->bindValue('offset', $query->offset, PDO::PARAM_INT); $rows->execute(); return $rows->fetchAll(PDO::FETCH_ASSOC); }, selectable: true, search: true, sortable: ['id', 'customer', 'total'], count: function (string $search) use ($pdo, $like): int { $count = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE customer LIKE :search ESCAPE '!'"); $count->execute(['search' => $like($search)]); return (int) $count->fetchColumn(); }, ); ``` The function gets a `TableQuery`. Nothing in it is taken from the browser as it came: | Value | What it holds | |---|---| | `search` | What the search box holds, as one line of at most 200 characters, or `''`. Bind it as a parameter, like any text a user typed. | | `sort` | What the user sorted by: a value out of your `sortable:` list and never anything else, so it may go into the query as it is. `null` while no header was clicked. | | `descending` | `true` for high to low. | | `limit`, `offset` | The page, as whole numbers that the table worked out. Without `count:` the limit is one row more than a page holds. | `sortable:` names the columns whose headers sort. No other header can be clicked. `['customer' => 'c.name']` says what the function gets for a column, which helps in a query with joins. End the order with a column that no two rows share, as the example does with `, id`. Rows that sort alike may otherwise change places between two pages, and one of them shows up twice or not at all. `count:` gets the search and returns how many rows it leaves. The table then says "Rows 26 to 50 of 100,000" and knows its last page. Leave it out when counting is slow. The table then asks for one row more than a page holds, to see whether another page follows, and offers "Previous" and "Next" without a count. `search: true` shows the box and hands over what was typed, as one piece of text. What is searched, and how, is up to your query. The table does not split the text into words or look past accents, as it does when it holds all rows. Whether `LIKE` tells upper case from lower case depends on the database: PostgreSQL does and has `ILIKE` for a search that does not. And `LIKE` never matches a column that is `NULL`, not even for an empty search: where `customer` may be `NULL`, search in `COALESCE(customer, '')`. Ticks count for the page on the screen. The table holds one page, so it returns the ticked rows of that page, as the function returned them in that run. A tick does not travel to another page. When the user turns the page, sorts or searches, the ticked rows that are not on the new page are unticked, and the table says how many they were. It says nothing when the user stayed on their page and a ticked row is gone, as after a button that deleted it. Where the list has more pages than one, the line under the table reads "2 selected on this page". A button still never acts on a row the user does not see. The table starts again at its first page when it is sorted or searched. When the user changes another input of the tool, it stays on its page while the count is the same, and starts again when the count changed or there is none. A function that returns more rows than it was asked for is turned down with an error: it most likely left out the limit. The function and `count:` run on every run of the tool: with every click, with every pause while the user types into the search box and with every `refresh()`, also while the table sits in a closed expander or in a tab that is not in view. A page far into the list makes the database pass over all rows before it. So the query has to be one that your database answers quickly: an index on the columns of `sortable:`, a search it can do fast, and no `count:` where counting is slow. The table shows the columns that the rows of the page have. Name them with `columns:` where not every row has every column, or the headers change from page to page. Next: [A task that takes long](https://script-ui.runio.dev/tutorials/long-task.md). --- --- url: https://script-ui.runio.dev/tutorials/long-task.md --- # 5. A task that takes long An import of fifty thousand rows does not fit into one run of a tool. The browser waits, PHP's time limit ends the script, and nobody sees how far it is. Work like that belongs to a worker: a job in a queue, a cron job, a command. The tool starts the task and then shows how far it is. The tool and the worker never talk to each other. They share one row in your storage. The worker writes how far it is, and the page reads that row every two seconds. ## The tool of the demo The export of the demo takes half a minute. Its clock stands in for a worker, and everything else is what a real tool does: ```php {13-15,17-22,24-27,37-39,44-45,47-51} state === 'waiting' || $export->state === 'running') { // The work goes on somewhere else. This page looks at it every two seconds, for as long as it is open. refresh(2); if ($export->state === 'waiting') { // No value: nobody knows yet how far it is. progress('Waiting for a worker'); } else { progress('Exporting orders', $export->done, Export::ORDERS, text: number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders'); } if (button('Stop the export', confirm: 'Stop the export where it is?')) { Export::stop(); rerun(); } return; } if ($export->state === 'finished') { success(number_format($export->done) . ' orders are exported.'); download('Download orders.csv', Export::orders(...), 'orders.csv'); } elseif ($export->state === 'stopped') { warning('The export was stopped at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders.'); } elseif ($export->state === 'failed') { // A short message of your own. What the worker threw is in its log: it names paths and queries. error('The export failed at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders. There is no file to download.'); } else { note('An export of all orders takes about half a minute. In a real shop a worker would write it. Here the clock stands in for the worker.'); } // Only the demo asks this. Its clock cannot fail, and a real worker needs no help with that. $fails = checkbox('Let the worker give up half way', help: 'To see what a failed export looks like.'); if (button($export->state === 'none' ? 'Start the export' : 'Start a new export', style: 'primary')) { // Hands the work over and comes back at once. No message: the bar on the next page says that it started. Export::start($fails); rerun(); } ``` ![The export of the demo while it runs: a bar that is about a third full, the words "900 of 2,400 orders" beside it, and a button "Stop the export".](https://script-ui.runio.dev/shots/export.png){.shot} **Lines 13 to 15.** While the task waits or runs, `refresh(2)` runs the script again every two seconds. When the task is over, the script no longer reaches that line, and the page stands still. **Lines 17 to 22.** `progress()` without a value says only that work is going on: nobody knows yet how far it is. With two numbers it draws a bar, and `text:` puts your own words beside it in place of the percentage. **Lines 24 to 27.** Stopping is a wish. The button writes it down, and the worker looks for it between two steps. **Lines 37 to 39.** A task that failed shows `error()` in place of the bar, with a short message of your own. The script no longer reaches `refresh()`, so the page stands still, as it does for a task that finished or was stopped. What the worker threw is not shown: it names paths and queries, and belongs into your log. **Lines 44 and 45.** Only the demo has this box. Its clock cannot fail, so a tick asks it to give up half way, and you can see the failed state without breaking anything. A real worker writes "failed" into the row by itself, when something throws. **Lines 47 to 51.** The start hands the work over and comes back at once. It writes no message: the bar on the next page says that the task started. ## What the tool shows in each state The demo shows all five. To see the failed one, tick "Let the worker give up half way" before you start the export: it fails at 1,200 of 2,400 orders, about fifteen seconds later. ## What to think of The rest of this page is the text of the README, word for word. `progress()` draws a label, a bar and a percentage from the two numbers it gets in this run. It keeps nothing, returns nothing and does not move by itself. `refresh(2)` is what moves it: the script runs again every two seconds and reads the numbers anew. When the task is over the script no longer reaches `refresh()`, and the page stands still. * `progress('Waiting for a worker')`, without a value, draws a bar that only says that work is going on. A `max:` of 0 or less does the same, and so does `NAN` or `INF`: a task that has not counted its rows yet has not done all of them. * The value counts up to the third argument, and up to 100 without one: `progress('Disk', 73)`. More than that counts as all of it, and less than 0 as nothing. The percentage is cut and not rounded, so it says "100%" only when all of it is done. Both are numbers: a script with `strict_types` casts what a database hands it as text, `(int) $row['done']`. * `text:` puts your own words beside the bar in place of the percentage, and a screen reader says them for the value: `progress('Importing orders', 1200, 3000, text: '1,200 of 3,000 orders')`. The time that is left belongs there too when you know it. * A bar is not an input. It has no key, a link cannot set it, and a page may show several. Its label is its name, for a screen reader too, so an empty label is an error. **The task is yours.** The library starts no worker and keeps no task. A worker writes down how far it is, every few hundred rows rather than every row, and the tool reads that. Every open page reads it every two seconds, so make it one cheap query. A queue may know the numbers already: in Laravel, the batch that `Bus::findBatch($id)` returns has `processedJobs()` and `totalJobs`. What such a tool has to think of: * **Start it once.** A button can be pressed twice, and by two people. Let the start find out that a task is running and write the new one in one statement of the database, not with a read and a write after it. * **Say nothing after the start.** The bar on the next page says that the task started. A `success()` next to it holds the page for ten seconds, so that it can be read, and the bar stands still that long. After that it is gone with the next run, read or not. What the user has to keep, the number of the task for example, belongs into the page and not into such a message. * **A worker can die.** Its bar then waits for ever. Let the worker write the time with every step, and say `warning()` in place of the bar when that time is too old. * **A task can fail.** Keep its state next to the numbers, and show `error()` in place of the bar with a short message of your own. What the worker threw belongs into your log: it names paths and queries. The export of the demo fails half way when its box "Let the worker give up half way" is ticked before the start. * **Stopping is a wish.** A button can write down that the task should stop. The worker has to look for that between two steps. * **Whose task it is.** The export of the demo belongs to the shop: everybody who opens the page sees the same one. A task that belongs to one user needs that user in its row, and `user()` says who is asking. * **Who may start it.** `allow:` says who may open the tool, and whoever opens it can press every button it draws. Where only a few may start or stop a task, ask `user()` and draw those buttons for them only. * **A page that nobody touches pauses after an hour.** For a longer task give `refresh()` a longer `stopAfter:`. * **Do not let the page do the work**, one slice with every refresh. A refresh runs only while somebody has the page open and in view, it waits while they type, and two open tabs would do the same slice twice. The work needs a worker that runs without a browser. That was the last tutorial. [All functions](https://script-ui.runio.dev/reference/functions.md) has every function with its parameters, and the [examples](https://script-ui.runio.dev/examples.md) show ten whole tools. --- --- url: https://script-ui.runio.dev/examples.md --- # Examples The demo is a small back office of a shop, in ten tools. Each one is a single PHP file. The pictures on this page are taken from the running demo, and the sources are the files of the repository as they are. ![The list of tools of the demo, "Shop back office": ten cards, each with the name of a tool and a line that says what it does.](https://script-ui.runio.dev/shots/demo-list.png){.shot} The demo is not part of the Composer package. Run it from a copy of the repository: ```bash git clone https://github.com/RunIO-dev/runio-script-ui.git cd runio-script-ui composer install php bin/script-ui serve examples/tools ``` Then open . The demo keeps its data in `examples/var/`, and the audit log has a button that brings the sample data back. ## Change something ### Refund orders {#refund} Find the orders of a customer, tick the ones to refund, and say yes. It shows a table that returns the ticked rows, and a button that asks before it acts. The [second tutorial](https://script-ui.runio.dev/tutorials/change-data.md) walks through it. ![The refund tool with two ticked orders and the question "Refund 2 orders?" with the buttons "Yes" and "Cancel".](https://script-ui.runio.dev/shots/refund.png){.shot} ```php orders(email: $email, status: $status); $picked = table( $orders, selectable: true, columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'total' => 'Total'], empty: 'No ' . $status . ' orders for ' . $email . '.', ); $count = count($picked) === 1 ? '1 order' : count($picked) . ' orders'; if ($picked && button('Refund selected', style: 'danger', confirm: 'Refund ' . $count . '?')) { foreach ($picked as $order) { $shop->refund($order['id']); } success('Refunded ' . $count . '.'); rerun(); } ``` ### Give a coupon {#coupon} A form that checks what was typed, and says under each field what is wrong with it. Some checks run while the user fills the form in, and the rest when the button is pressed. ![The coupon tool after a press on "Give coupon": red notes under the fields "Customer email" and "Reason" say what is missing.](https://script-ui.runio.dev/shots/coupon.png){.shot} ```php customer($email); $coupons = $customer === null ? [] : $shop->coupons($customer['email']); // Checked on every run: the note comes when the user leaves the field, and it // stays until the field is right. An empty field is left alone here, or a new // page would start full of red. The answer tells whoever may open this tool // who is a customer. That is fine in a back office, and nowhere else. if ($email !== '' && $customer === null) { field_error('Customer email', 'No customer has this email.'); } if (button('Give coupon', style: 'primary')) { // Checked when the button is pressed: what is missing, and what only counts now. if ($email === '') { field_error('Customer email', 'Enter the email of a customer.'); } if ($percent === null) { field_error('Discount in percent', 'Enter a discount from 1 to 50.'); } if ($until === null) { field_error('Valid until', 'Choose the last day of the coupon.'); } if ($percent > 20 && mb_strlen($reason) < 10) { field_error('Reason', 'More than 20 percent needs a reason. Write a sentence.'); } // The form still holds what was typed after the coupon was given. A second // press, or a double click, must not give a second one. Two requests at the // very same moment would both pass this check: where it matters, let the // database refuse the second one, with a unique key. foreach ($coupons as $coupon) { if ($coupon['until'] >= date('Y-m-d')) { field_error('Customer email', $customer['name'] . ' has a coupon already: ' . $coupon['code'] . ', valid until ' . $coupon['until'] . '.'); break; } } // field_error() does not stop the script. Nothing is done until all of it is right. if (valid()) { $code = $shop->addCoupon($customer['email'], $percent, $until); $coupons = $shop->coupons($customer['email']); success($customer['name'] . ' got ' . $percent . ' % off with the code ' . $code . ', until ' . $until . '.'); } } if ($customer !== null) { heading('Coupons of ' . $customer['name']); table( $coupons, columns: ['code' => 'Code', 'percent' => 'Percent', 'until' => 'Valid until', 'given' => 'Given on'], empty: 'No coupon yet.', ); } ``` ### Ship orders {#ship} All paid orders, ten on a page, with a search over all of them. A tick stays when the page of the table is turned, so one press can ship orders from several pages. ![The tool "Ship orders": a search box, a table of paid orders with a tick box in every row, and the pages of the table under it.](https://script-ui.runio.dev/shots/ship.png){.shot .cut} ```php orders(status: 'paid'); if ($orders === []) { info('No paid order is waiting.'); return; } // All paid orders go in. The table shows ten at a time and searches all of them. // A tick stays when the page changes. A ticked row that the search hides is not // in $picked, and it is ticked again when the search shows it. $picked = table( $orders, selectable: true, columns: ['id' => 'Order', 'created_at' => 'Placed on', 'customer' => 'Customer', 'items' => 'Items', 'total' => 'Total'], pageSize: 10, search: true, ); $count = count($picked) === 1 ? '1 order' : count($picked) . ' orders'; if ($picked && button('Mark as shipped', style: 'primary', confirm: 'Mark ' . $count . ' as shipped?')) { foreach ($picked as $order) { $shop->ship($order['id']); } success('Marked ' . $count . ' as shipped.'); rerun(); } ``` ## Look something up ### Customers {#customers} Filters in three columns, tick boxes for the countries, and a table. Tick one customer and the page shows their orders and their record in two tabs, a link that opens the refund tool with the email filled in, and a download of what the filters left. ![The customer list, searched for "omar": one customer is ticked, and under the table stand a download button, a link to the refund tool, and two tabs with the orders and the record of that customer.](https://script-ui.runio.dev/shots/customers.png){.shot .cut} ```php customers(); title('Customers'); $search = $minSpent = $joinedAfter = null; columns( function () use (&$search): void { $search = text('Search', placeholder: 'Name or email'); }, function () use (&$minSpent): void { $minSpent = number('Spent at least', default: 0, min: 0, step: 50); }, function () use (&$joinedAfter): void { $joinedAfter = date_input('Joined after'); }, ); $countries = array_column($customers, 'country'); sort($countries); $from = multiselect('Country', $countries, horizontal: true, help: 'Tick none to see every country.'); $refundsOnly = checkbox('Only customers with a refund'); $found = array_values(array_filter($customers, static fn (array $customer): bool => ($search === '' || stripos($customer['name'] . ' ' . $customer['email'], $search) !== false) && ($from === [] || in_array($customer['country'], $from, true)) && $customer['spent'] >= ($minSpent ?? 0) && ($joinedAfter === null || $customer['joined'] > $joinedAfter) && (!$refundsOnly || $customer['refunds'] > 0))); $picked = table( $found, selectable: true, columns: ['name' => 'Name', 'email' => 'Email', 'country' => 'Country', 'joined' => 'Joined', 'orders' => 'Orders', 'refunds' => 'Refunds', 'spent' => 'Spent'], rowKey: 'email', // a customer has no id column; the email tells them apart empty: 'No customer matches these filters.', ); // The file holds what the filters above leave, with every column. if ($found !== []) { download('Download as CSV', $found, 'customers.csv'); } if (count($picked) === 1) { $customer = $picked[0]; $orders = $shop->orders(email: $customer['email']); heading($customer['name']); link('Refund an order of this customer', '/refund?customer-email=' . rawurlencode($customer['email'])); // Two views of one customer, one of them in sight. Both run on every run: // changing the tab asks nothing of the server. tabs([ 'Orders (' . count($orders) . ')' => fn () => table( $orders, columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'status' => 'Status', 'total' => 'Total'], key: 'orders', pageSize: 10, ), 'Record' => fn () => json($customer), ]); } elseif (count($picked) > 1) { note('Tick a single customer to see the details.'); } ``` ### Order archive {#archive} A table over 100,000 orders that holds one page at a time. It asks a function for the rows of the page it shows. The [fourth tutorial](https://script-ui.runio.dev/tutorials/big-table.md) shows the same with a database. ![The order archive, searched for "haddad": a search box and a table of orders with tick boxes and headers that sort.](https://script-ui.runio.dev/shots/archive.png){.shot .cut} ```php 'Order', 'customer' => 'Customer', 'placed' => 'Placed on', 'status' => 'Status', 'total' => 'Total'], search: true, sortable: ['id', 'customer', 'placed', 'total'], count: Archive::count(...), // gets the search, says how many orders it leaves ); if (button('Print labels')) { if ($picked === []) { warning('Tick the orders that need a label first.'); } else { success('Labels are on their way for ' . implode(', ', array_column($picked, 'id')) . '.'); } } ``` ## Bring data in and out ### Import orders {#import} Upload a CSV file, look at what it holds, and only then add the orders to the shop. The file waits on the server while the user looks at it, and nothing is saved before the button is pressed. ![The import tool after an upload: the file "orders.csv" with a link "Remove", a table with the two orders the file holds, and a button "Import 2 orders".](https://script-ui.runio.dev/shots/import.png){.shot} ```php checkOrders($file->rows()); if ($problems !== []) { $more = count($problems) - 5; warning(implode("\n", array_slice($problems, 0, 5)) . ($more > 0 ? "\nAnd " . $more . ' more.' : '')); } if ($orders === []) { error('No order could be read from ' . $file->name . '.'); return; } table($orders, columns: ['customer' => 'Customer', 'email' => 'Email', 'items' => 'Items', 'total' => 'Total'], pageSize: 10); $count = count($orders) === 1 ? '1 order' : count($orders) . ' orders'; if (button('Import ' . $count, style: 'primary', confirm: 'Add ' . $count . ' to the shop?')) { $shop->addOrders($orders); // The tool is done with the file. Without this line it would wait on the server for a day. $file->forget(); success('Added ' . $count . ' from ' . $file->name . '.'); rerun(); } ``` ### Export orders {#export} A task that takes half a minute: start it, watch how far it is, stop it, fetch the file. The page looks at the task every two seconds. A tick before the start lets the task fail half way, and the page then shows an error in place of the bar. The [fifth tutorial](https://script-ui.runio.dev/tutorials/long-task.md) walks through it. ![The export while it runs: a bar that is about a third full, the words "900 of 2,400 orders" beside it, and a button "Stop the export".](https://script-ui.runio.dev/shots/export.png){.shot} ```php state === 'waiting' || $export->state === 'running') { // The work goes on somewhere else. This page looks at it every two seconds, for as long as it is open. refresh(2); if ($export->state === 'waiting') { // No value: nobody knows yet how far it is. progress('Waiting for a worker'); } else { progress('Exporting orders', $export->done, Export::ORDERS, text: number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders'); } if (button('Stop the export', confirm: 'Stop the export where it is?')) { Export::stop(); rerun(); } return; } if ($export->state === 'finished') { success(number_format($export->done) . ' orders are exported.'); download('Download orders.csv', Export::orders(...), 'orders.csv'); } elseif ($export->state === 'stopped') { warning('The export was stopped at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders.'); } elseif ($export->state === 'failed') { // A short message of your own. What the worker threw is in its log: it names paths and queries. error('The export failed at ' . number_format($export->done) . ' of ' . number_format(Export::ORDERS) . ' orders. There is no file to download.'); } else { note('An export of all orders takes about half a minute. In a real shop a worker would write it. Here the clock stands in for the worker.'); } // Only the demo asks this. Its clock cannot fail, and a real worker needs no help with that. $fails = checkbox('Let the worker give up half way', help: 'To see what a failed export looks like.'); if (button($export->state === 'none' ? 'Start the export' : 'Start a new export', style: 'primary')) { // Hands the work over and comes back at once. No message: the bar on the next page says that it started. Export::start($fails); rerun(); } ``` ## Watch something ### Sales dashboard {#dashboard} Four numbers with their change, two charts and the latest orders. The page runs again every 30 seconds while somebody looks at it, and it waits while they are in the middle of something. ![The sales dashboard: a choice of the period, four numbers (revenue, orders, average order and refunds) with their change, a bar chart of the revenue per day and a line chart of orders and refunds.](https://script-ui.runio.dev/shots/dashboard.png){.shot .cut} ```php 'Last 7 days', 14 => 'Last 14 days', 30 => 'Last 30 days'], default: 14, horizontal: true); $now = $shop->daily($days); $before = array_slice($shop->daily($days * 2), 0, $days); $sum = static fn (array $rows, string $column): float => (float) array_sum(array_column($rows, $column)); $change = static function (float $now, float $before): ?string { if ($before == 0.0) { return null; } return sprintf('%+.1f%%', ($now - $before) / $before * 100); }; $revenue = $sum($now, 'revenue'); $orders = $sum($now, 'orders'); $refunds = $sum($now, 'refunds'); columns( fn () => metric('Revenue', '$' . number_format($revenue), $change($revenue, $sum($before, 'revenue'))), fn () => metric('Orders', number_format($orders), $change($orders, $sum($before, 'orders'))), fn () => metric('Average order', '$' . number_format($orders > 0 ? $revenue / $orders : 0, 2)), fn () => metric('Refunds', number_format($refunds), $change($refunds, $sum($before, 'refunds')), inverse: true), ); // What is not needed every time stays one click away. expander('How these numbers are counted', function () use ($days): void { note('Revenue and orders leave out the orders that were refunded. A refund counts on the day its order was placed.'); note('The change under a number compares the last ' . $days . ' days with the ' . $days . ' days before them.'); }); chart($now, x: 'day', y: 'revenue', title: 'Revenue per day (USD)'); chart($now, x: 'day', y: ['orders' => 'Orders', 'refunds' => 'Refunds'], type: 'line', title: 'Orders and refunds per day'); heading('Latest orders'); table( $shop->orders(days: $days), columns: ['id' => 'Order', 'created_at' => 'Placed on', 'customer' => 'Customer', 'items' => 'Items', 'status' => 'Status', 'total' => 'Total'], pageSize: 10, ); ``` ### Audit log {#audit} Every pressed button and every download of the demo: who it was, in which tool, with which inputs, and whether a question was answered with yes. The tool only reads the lines that the `log:` setting of the demo writes. ![The audit log: a table with the time, the user, the tool, the button, whether it was confirmed, and the inputs of three presses.](https://script-ui.runio.dev/shots/audit.png){.shot} ```php date('Y-m-d H:i:s', (int) strtotime((string) $entry['time'])), 'user' => $entry['user'] ?? 'local', 'tool' => $entry['tool'], 'action' => $entry['action'], 'confirmed' => $entry['confirmed'], 'file' => $entry['download']['file'] ?? null, 'inputs' => $entry['inputs'], // What the page said is wrong with its inputs in that run. A press that found something wrong did not do its work. 'found_wrong' => implode(' ', array_merge([], ...array_values(array_filter((array) ($entry['field_errors'] ?? []), is_array(...))))), ]; } } table($entries, search: true, empty: 'Nothing logged yet. Refund an order, then come back.'); if (button('Reset the demo data', confirm: 'Bring back the sample orders and empty this log?')) { Shop::open()->reset(); if (is_file($file)) { unlink($file); } success('The demo data is fresh again.'); rerun(); } ``` ## In another language ### An Arabic page {#arabic} A tool with an Arabic title is Arabic throughout. The page runs from right to left, and the texts that the library writes itself, such as "Reset" and the search box of the table, are Arabic too. German is built in as well, and any other language can be passed in. ![An Arabic tool: the title, the labels and the headers of the table are Arabic, and the page runs from right to left.](https://script-ui.runio.dev/shots/orders-ar.png){.shot .cut} ```php 'كل الحالات', 'paid' => 'مدفوع', 'shipped' => 'تم الشحن', 'refunded' => 'مُسترجَع']); }, ); $orders = $shop->orders(email: $email === '' ? null : $email, status: $status === '' ? null : $status); columns( fn () => metric('عدد الطلبات', number_format(count($orders))), fn () => metric('الإجمالي', '$' . number_format(array_sum(array_column($orders, 'total')), 2)), ); table( $orders, columns: ['id' => 'رقم الطلب', 'created_at' => 'التاريخ', 'customer' => 'العميل', 'items' => 'المنتجات', 'total' => 'المبلغ'], pageSize: 20, search: true, empty: 'لا توجد طلبات مطابقة.', ); // اسم الملف بالعربية، والدالة لا تُستدعى إلا عند طلب الملف. if ($orders !== []) { download('تنزيل CSV', fn () => $orders, 'الطلبات.csv', key: 'download'); } ``` --- --- url: https://script-ui.runio.dev/reference/on-one-page.md description: >- The whole library on one page: the model, the rules, every function with its arguments and one whole tool. For people, and for an AI assistant that writes a tool. --- # Script UI on one page How to write a tool with [runio/script-ui](https://script-ui.runio.dev): 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](https://github.com/RunIO-dev/runio-script-ui/blob/main/README.md) says each point at length, and [`src/functions.php`](https://github.com/RunIO-dev/runio-script-ui/blob/main/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 . ## Rules 1. **Draw with the functions of this page only.** No `echo`, no HTML, and never `$_GET`, `$_POST` or `$_SESSION`. Everything is shown as text: a label, a cell or a message can hold no HTML. 2. **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?'`. 3. **What is not called is not drawn.** Write `button('Greet') && $name !== ''` in this order. The other way round, PHP does not call `button()` while the name is empty, and the button is gone. An input that a run does not draw loses its value. 4. **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. 5. **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'])`. 6. **Say what is wrong with an input under that input**, with `field_error()`, and ask `valid()` before the work is done. `error()` is for what belongs to no input. 7. **A part of `columns()`, `expander()` or `tabs()` is a function**: `fn () => ...`, or `function () 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. 8. **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()` and `refresh()`. 9. **End a run with `stop()` or `return`**, never with `exit`. 10. **Who may open a tool is decided where the tools are served**, with `auth:` and `allow:`. 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: ```php 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: ```php 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. ```php 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 run ``` Tables and charts: ```php 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: ```php 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 wanted ``` Layout and flow: ```php 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 check ``` Serving the tools. The application calls these, not a tool. ```php 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 job ``` ## One whole tool ```php $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: ```php $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: ```php $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: ```php 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: ```php $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()` or `image()`. * Nothing keeps a value between runs but the inputs and your own storage: no `state()` and no `session()`. * 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()`, no `sidebar()`, no dialog besides `confirm:`, 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 ```php // 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. --- --- url: https://script-ui.runio.dev/reference/functions.md --- # All functions Every function of the library, with the description from its source. This page is built from [`src/functions.php`](https://github.com/RunIO-dev/runio-script-ui/blob/v0.3.0/src/functions.php) of version 0.3.0, so it cannot say something else than the code does. Import the functions you use, or give the namespace a short name: ```php use function Runio\ScriptUi\{title, text, button, success}; use Runio\ScriptUi as ui; // then: ui\title('Find orders'); ``` | Group | Functions | |---|---| | [Display](#display) | [`title`](#title) [`heading`](#heading) [`note`](#note) [`code`](#code) [`json`](#json) [`link`](#link) [`divider`](#divider) [`metric`](#metric) [`progress`](#progress) [`success`](#success) [`info`](#info) [`warning`](#warning) [`error`](#error) | | [Inputs](#inputs) | [`text`](#text) [`textarea`](#textarea) [`number`](#number) [`select`](#select) [`radio`](#radio) [`multiselect`](#multiselect) [`checkbox`](#checkbox) [`date_input`](#date_input) [`file_input`](#file_input) [`field_error`](#field_error) [`valid`](#valid) | | [Data](#data) | [`table`](#table) [`chart`](#chart) | | [Actions](#actions) | [`button`](#button) [`download`](#download) [`csv`](#csv) | | [Flow and layout](#flow-and-layout) | [`columns`](#columns) [`expander`](#expander) [`tabs`](#tabs) [`refresh`](#refresh) [`stop`](#stop) [`rerun`](#rerun) | | [Hosting](#hosting) | [`user`](#user) [`configure`](#configure) [`clean_uploads`](#clean_uploads) [`serve`](#serve) [`respond`](#respond) | ## Display {#display} ### title() {#title} ```php function title(string $text): void ``` The big heading of the page. The first one also names the browser tab. ### heading() {#heading} ```php function heading(string $text): void ``` A section heading. ### note() {#note} ```php function note(string $text): void ``` A paragraph of plain text. Line breaks are kept. ### code() {#code} ```php function code(string $text): void ``` Text in a fixed-width block, for code, SQL or log lines. ### json() {#json} ```php function json(mixed $value): void ``` Any value as readable JSON. ### link() {#link} ```php function link(string $label, string $url, bool $newTab = false): void ``` A link. Only http, https and mailto addresses and paths on this site are accepted. ### divider() {#divider} ```php function divider(): void ``` A thin line between two parts of the page. ### metric() {#metric} ```php function metric(string $label, string|int|float $value, string|int|float|null $delta = null, bool $inverse = false): void ``` One number that matters, with an optional change such as "+4.2%". * `$inverse` (`bool`): set it when going up is bad news (refunds, errors, churn) ### progress() {#progress} ```php function progress(string $label, int|float|null $value = null, int|float $max = 100, ?string $text = null): void ``` A bar that shows how far a task is: progress('Importing orders', $done, $total). It draws what the two numbers say in this run, and nothing moves by itself. For a task that runs somewhere else, call refresh() on the same page: every run reads the numbers anew. * `$label` (`string`): what is counted. It names the bar, also for a screen reader, so it must not be empty * `$value` (`int|float|null`): how much is done. Leave it out while nobody knows: the bar then only says that work is going on * `$max` (`int|float`): how much there is to do. A value beyond it counts as all of it, and one below 0 as nothing. While $max is 0 or less, or one of the two is no number that can be counted with (NAN, INF), nobody knows how far the task is, and the bar says that * `$text` (`string|null`): your own words beside the bar, in place of the percentage: "1,200 of 3,000 orders". '' leaves the place empty ### success() {#success} ```php function success(string $text): void ``` A message that something worked. Line breaks are kept. ### info() {#info} ```php function info(string $text): void ``` A message that tells the user something they should know. Line breaks are kept. ### warning() {#warning} ```php function warning(string $text): void ``` A message that something needs care. Software that reads the page out says it at once. ### error() {#error} ```php function error(string $text): void ``` A message that something went wrong. Software that reads the page out says it at once. What is wrong with one input belongs to field_error(). ## Inputs {#inputs} ### text() {#text} ```php function text(string $label, string $default = '', ?string $placeholder = null, ?string $help = null, ?string $key = null): string ``` A single line of text. Returns what the user typed, trimmed. ### textarea() {#textarea} ```php function textarea(string $label, string $default = '', int $rows = 4, ?string $placeholder = null, ?string $help = null, ?string $key = null): string ``` Several lines of text. ### number() {#number} ```php function 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 ``` A number, kept between $min and $max. Returns null while the field is empty. A whole number comes back as an int, anything else as a float. With a whole-number $step the result is always a whole number. ### select() {#select} ```php function select(string $label, array $options, mixed $default = null, ?string $help = null, ?string $key = null, ?bool $byKey = null): mixed ``` A choice from a list. Returns one of the options, never anything else. * `$options` (`array`): \['paid', 'shipped'] offers those values; \[7 => 'Last 7 days', 30 => 'Last 30 days'] shows the texts and returns 7 or 30 * `$byKey` (`bool|null`): PHP cannot tell \[0 => 'No', 1 => 'Yes'] from the list \['No', 'Yes']. When the keys count up from 0 and are the values, say so with byKey: true ### radio() {#radio} ```php function radio( string $label, array $options, mixed $default = null, bool $horizontal = false, ?string $help = null, ?string $key = null, ?bool $byKey = null, ): mixed ``` A choice from a short list, with every option in view. Returns one of the options, never anything else: the first one until the user chooses another. It takes the options the way select() does. With more than a handful of options, select() needs less room. * `$options` (`array`): see select() * `$horizontal` (`bool`): the options stand side by side instead of one under the other * `$byKey` (`bool|null`): see select() ### multiselect() {#multiselect} ```php function multiselect( string $label, array $options, array $default = [], bool $horizontal = false, ?string $help = null, ?string $key = null, ?bool $byKey = null, ): array ``` Several choices from a list: a tick box for every option. Returns the ticked options as a list, in the order of the options. Nothing ticked is an empty list. * `$options` (`array`): see select() * `$default` (`array`): the options that are ticked until the user says otherwise * `$horizontal` (`bool`): the options stand side by side instead of one under the other * `$byKey` (`bool|null`): see select() **Returns** `list` ### checkbox() {#checkbox} ```php function checkbox(string $label, bool $default = false, ?string $help = null, ?string $key = null): bool ``` A tick box. ### date_input() {#date_input} ```php function 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 ``` A date. Returns it as "YYYY-MM-DD", or null while the field is empty. ### file_input() {#file_input} ```php function file_input( string $label, ?array $types = null, bool $multiple = false, ?int $maxSize = null, ?string $help = null, ?string $key = null, ): Upload|array|null ``` A field that takes a file from the user's computer. It returns the file once it is there, on every run, until the user removes it or the tool forgets it: ```php $file = file_input('Orders', types: ['csv']); if ($file && button('Import')) { import($file->path); $file->forget(); } ``` The file lies in a folder that only PHP reads, for a day at most. Nothing about it is trusted: its name is made safe, its content is whatever the user sent, and its ending says nothing about what is in it. A field that is not drawn in a run gives its file up, as a text field loses its text. That includes a run that ends above the field with stop() or an early return. * `$types` (`list|null`): the endings a file may have, such as \['csv', 'xlsx']. null takes every kind of file * `$multiple` (`bool`): take several files, up to 20 and never more than PHP takes in one request (max_file_uploads in php.ini). The function then returns a list * `$maxSize` (`int|null`): the largest file in bytes. PHP's own limits (upload_max_filesize and post_max_size in php.ini) count as well, and the smaller one wins **Returns** `($multiple is true ? list : Upload|null)`: the file, or null while there is none. With $multiple the files, in the order they arrived ### field_error() {#field_error} ```php function field_error(string $field, string $message): void ``` Says what is wrong with what an input holds, right under that input. The input is marked, and software that reads the page out says so too. ```php $amount = number('Amount'); $email = text('Customer email'); if (button('Refund')) { if ($amount === null || $amount <= 0) { field_error('Amount', 'Enter an amount above 0.'); } if (!str_contains($email, '@')) { field_error('Customer email', 'Enter an email address.'); } if (valid()) { // do the work } } ``` Call it below the input, in the same run: the input has to be on the page already. After a pressed button the first input that is wrong gets the keyboard focus, and an expander or a tab that hides it comes into sight. Nothing is kept of a message. It is there in the run that says it: checked behind a button, it is gone with the next change on the page, and checked on every run, it stays until the input is right. It does not stop the script either: ask valid() before the work is done. * `$field` (`string`): the label of the input, exactly as it was written, or its key. Two inputs with the same label are told apart by their keys. A name that is the key of one input and the label of another means the one with that key * `$message` (`string`): what the user has to change. It is shown as text, and cut after 500 characters. One input shows up to ten messages ### valid() {#valid} ```php function valid(): bool ``` True as long as nothing was found wrong with an input in this run: no input that was drawn so far shows a note that says what is wrong with it. Such a note comes from field_error(), or from file_input() when it turned a file down in this run: one that is too large, or of the wrong kind. That file did not arrive, and the user may believe that it is attached. ## Data {#data} ### table() {#table} ```php function 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 ``` A table of rows. Click a column header to sort. A long table is shown one page at a time. Pass all rows: the table sorts all of them and cuts them into pages itself. Or pass a function, for a table that is too long for that. The table asks it for one page at a time and hands it a TableQuery: the search, the order, a limit and an offset. The function reads those rows from the database and returns them, and the table never holds more than a page. Such a table sorts by the columns that $sortable names, searches when the function does, and its ticks count for the page on the screen. * `$rows` (`iterable|\Closure`): arrays or objects, for example what a database query returned. Or a function that gets a TableQuery and returns the rows of one page * `$selectable` (`bool`): adds a tick box to every row. A tick stays when the page of the table changes, unless the rows come from a function * `$columns` (`array|null`): \['id', 'total'] to choose columns, \['id' => 'Order'] to also rename them * `$rowKey` (`string`): the column that identifies a row. A row without it is known by what is in it: its tick is dropped when the row changes * `$pageSize` (`int`): how many rows one page shows, from 1 to 200 * `$search` (`bool`): adds a search box. It filters the rows while the user types and reads the columns that are shown. A ticked row that it hides is not returned. With a function it only hands over what was typed: the function searches * `$empty` (`string|null`): what to say when there are no rows. By default "No rows." in the language of the page * `$sortable` (`array|null`): with a function only: the columns whose headers sort, \['id', 'total']. \['customer' => 'c.name'] also says what the function gets for a column. The function only ever gets a value of this list, or null * `$count` (`\Closure|null`): with a function only: gets the search and returns how many rows there are. Without it the table shows no page count, only "Previous" and "Next" **Returns** `list`: the rows the user ticked on all pages of the list, exactly as they were passed in (always empty unless $selectable). With a function: the ticked rows of the page on the screen, as the function returned them ### chart() {#chart} ```php function chart( iterable $rows, string $x, string|array $y, string $type = 'bar', ?string $title = null, int $height = 240, bool $data = true, ): void ``` A bar or line chart of the rows. * `$rows` (`iterable`) * `$x` (`string`): the column with the labels along the bottom * `$y` (`string|array`): the column with the numbers; a list of columns draws several series, \['revenue' => 'Revenue (USD)'] also names them * `$type` (`string`): "bar" or "line" * `$data` (`bool`): also offer the numbers as a table under the chart ## Actions {#actions} ### button() {#button} ```php function button( string $label, string $style = 'default', ?string $confirm = null, ?string $yes = null, ?string $no = null, ?string $key = null, ): bool ``` A button. Returns true only in the run that its click started, so "if (button('Save')) { ... }" does the work exactly once per click. In a loop every button needs its own key, made from the row it belongs to: button('Refund', key: 'refund-' . $order\['id']). * `$style` (`string`): "default", "primary" or "danger" * `$confirm` (`string|null`): a question to ask first. The button then returns true only after the user answered yes to exactly this text. Keep it the same from run to run: with the time of day in it, the answer would never fit the question * `$yes` (`string|null`): the text of the answer that goes ahead. By default "Yes" in the language of the page * `$no` (`string|null`): the text of the answer that does nothing. By default "Cancel" in the language of the page ### download() {#download} ```php function download(string $label, iterable|string|\Closure $content, string $file, string $style = 'default', ?string $key = null): void ``` A button that hands the user a file. ```php download('Download CSV', $orders, 'orders.csv'); ``` Rows become a CSV file, or JSON when the name ends in ".json". Text is sent as it is. A function is called only when the user asks for the file, so a slow query does not run on every page view: ```php download('Export all', fn () => $db->fetchAll('SELECT * FROM orders'), 'orders.csv'); ``` The run ends where the file is made, as after stop(). A download is written to the log like a pressed button, with the name and the size of the file. When the log cannot be written (the callback throws or returns false), the file is not sent. The file is made in memory. No rows give an empty file: to still write the names of the columns, pass csv($rows, columns: \[...]). * `$content` (`iterable|string|\Closure`): rows, text, or a function that returns one of the two. A generator can be read only once: when the page shows the same rows, pass an array or a function * `$file` (`string`): the name of the file, such as "orders.csv". It may contain what a user typed: it is made safe. Its ending should come from you, because the ending decides what a computer does with the file * `$style` (`string`): "default", "primary" or "danger" ### csv() {#csv} ```php function csv(iterable $rows, ?array $columns = null, string $separator = ',', bool $allowFormulas = false, bool $bom = true): string ``` Rows as CSV text, for download() when the defaults do not fit: ```php download('Export', fn () => csv($orders, separator: ';'), 'orders.csv'); ``` * `$rows` (`iterable`) * `$columns` (`array|null`): \['id', 'total'] to choose columns, \['id' => 'Order'] to also rename them. By default every column, under its own name. For a very long export name the columns: the rows are then written one by one and not kept * `$separator` (`string`): what stands between two cells: ",", ";", "|", ":" or a tab. Excel expects ";" where people write 1,5 for one and a half * `$allowFormulas` (`bool`): a spreadsheet runs a cell that starts with "=", "+", "-" or "@" as a formula. By default such a cell gets a "'" in front, and numbers are left alone. Pass true only when every cell comes from you * `$bom` (`bool`): start the file with the mark that tells Excel the text is UTF-8 ## Flow and layout {#flow-and-layout} ### columns() {#columns} ```php function columns(callable ...$columns): void ``` Puts things side by side. Each argument is a function that draws one column: fn () => ..., a method, or name(...). The name of a function in quotes is not run. ### expander() {#expander} ```php function expander(string $label, callable $content, bool $open = false, ?string $key = null): void ``` A part of the page under a line that opens and closes it. For what is not needed every time: advanced options, the details of a row, a long explanation. The content always runs, and the inputs inside keep working and keep their values while the part is closed. Closed only means out of sight. It does not mean private: what is inside is in the page, for everybody who can open the tool. stop() inside ends this part and not the page. * `$content` (`callable():mixed`): draws what is inside: fn () => ..., a method, or name(...). The name of a function in quotes is not run * `$open` (`bool`): how it starts. From then on it stays the way the user left it ### tabs() {#tabs} ```php function tabs(array $tabs, ?string $key = null): void ``` Parts of the page behind headers, one of them in view at a time. For a page that holds more than one screen should show at once: the orders, the customers and the settings of a shop. Every tab runs on every run, whichever is in view. The inputs behind the others keep working and keep their values, and changing the tab needs no run of the tool. Work that takes long belongs behind a button. A tab that is not open is out of sight, not private: it is in the page, for everybody who can open the tool. stop() inside a tab ends that tab and not the page. * `$tabs` (`array`): the label of each tab and the function that draws it: \['Orders' => fn () => table($orders), 'Settings' => $settings]. The name of a function in quotes is not run ### refresh() {#refresh} ```php function refresh(int $seconds, ?int $stopAfter = 3600): void ``` Lets the page run again by itself, so that a dashboard or the state of a queue stays up to date while somebody looks at it. Where it is called, a small line says when the page was made, with a button that pauses it. Every refresh is a whole run of the script, so the rate should fit the work: the next run starts $seconds after the answer to the last one, never before. Call it near the top, and not inside expander() or tabs(): its line must be in sight. A page that ends before it reaches the call stops refreshing. A refresh waits while the user is in the middle of something: typing, choosing from a list, answering the question of a button, or moving the mouse. It presses no button, writes nothing to the log and changes nothing that the tool remembers. Without JavaScript nothing refreshes. It is a whole run all the same: what the script does on every run, it now does every few seconds with nobody at the page. Work that changes something belongs behind a button. And the login check runs for it like for any request: one that counts the time without a request should leave out those with the header "X-Script-Ui: refresh". * `$seconds` (`int`): the wait between an answer and the next run: 2 or more * `$stopAfter` (`int|null`): the page stops by itself when nobody touched it for this many seconds, and says so. An hour by default: a page that keeps asking keeps its session alive. It has to be longer than $seconds. null: never, for a screen on a wall ### stop() {#stop} ```php function stop(): never ``` Ends the run here. Everything drawn so far is shown. Inside expander() and tabs() it ends that part only, and the rest of the page still runs. So it is no permission check there. Decide who may see or do something before the part is drawn, or right where the work is done. ### rerun() {#rerun} ```php function rerun(): never ``` Ends the run and loads the page again from the top. Call it after a button did its work, so that tables above the button show the new data. Messages written with success(), info(), warning() or error() after the click are kept. ## Hosting {#hosting} ### user() {#user} ```php function user(): ?string ``` Who is using the tool: what the login check returned. Null when there is no login check. ### configure() {#configure} ```php function 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 ``` Settings for tools that are opened directly as scripts. Call it before anything is drawn, typically in a file that every tool includes. * `$auth` (`callable|null`): the login check: receives the request, returns the user's name, or null to refuse * `$log` (`callable|null`): called with an array for every button a user presses and every file a user downloads. It should throw or return false when the entry could not be written: a download is then not sent * `$debug` (`bool|null`): show error details in the page. By default they are shown only without a login check, where nobody but this computer gets in. With a login check, pass true where you develop * `$name` (`string|null`): the name of the tool collection * `$language` (`string|null`): the language of the built-in texts ("Yes", "Reset", "No rows.") on every page: "en", "ar" or "de", or a language you pass the texts for. By default each page follows the language its title is written in * `$texts` (`array|null`): your own built-in texts, per language: \['de' => \['page.reset' => 'Leeren']]. All texts and their ids are in resources/texts/en.php * `$uploads` (`string|null`): the folder that keeps uploaded files until a tool is done with them. It must not be a folder the web server serves. By default a folder of its own inside PHP's temp folder * `$allow` (`callable|null`): who may open which script: receives what the login check returned, and the id of the script (its file name without ".php"), and returns true or false. See serve() ### clean_uploads() {#clean_uploads} ```php function clean_uploads(?string $folder = null): int ``` Deletes the uploaded files that are older than a day. The library does this itself while files arrive. Call it from a scheduled job when the files of users who left must not wait for the next upload to be cleaned away. The job has to run as the system user that runs PHP for the web server. As another user it finds another folder, and nothing in it. * `$folder` (`string|null`): the folder you passed as uploads:. null: the folder of this system user inside PHP's temp folder **Returns** `int`: how many files were deleted ### serve() {#serve} ```php function 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 in a folder as a tool, with a page that lists them. Without $auth the tools only answer to a browser on the computer they run on. That check cannot see through every proxy or tunnel: anything that can be reached from outside needs $auth. * `$auth` (`callable|null`): the login check: receives the request, returns the user's name, or null to refuse * `$log` (`callable|null`): called with an array for every button a user presses and every file a user downloads. It should throw or return false when the entry could not be written: a download is then not sent * `$debug` (`bool|null`): show error details in the page. By default only without $auth; with it, pass true where you develop * `$base` (`string|null`): null: one address, tools are chosen with "?\_tool=id". A path such as "/admin/tools": tools get the addresses "/admin/tools/{id}" (the web server must send those addresses to the script that calls serve()). * `$language` (`string|null`): the language of the built-in texts ("Yes", "Reset", "No rows.") on every page: "en", "ar" or "de", or a language you pass the texts for. By default each page follows the language its title is written in * `$texts` (`array|null`): your own built-in texts, per language: \['de' => \['page.reset' => 'Leeren']]. All texts and their ids are in resources/texts/en.php * `$uploads` (`string|null`): the folder that keeps uploaded files until a tool is done with them. It must not be a folder the web server serves. By default a folder of its own inside PHP's temp folder * `$allow` (`callable|null`): who may open which tool: receives what the login check returned (a name, a number or your user object; null when it only said true, or when there is none), and the id of a tool (its file name without ".php"), and returns true or false. A tool that is not allowed is left out of the list, and answers "Not allowed" before anything of it runs. Without it everybody who gets past the login check may open every tool * `$variables` (`array|null`): variables for every tool of the folder, by name: \['orders' => $orders] makes $orders in each tool. A tool is a script of its own and sees no variable of yours otherwise ### respond() {#respond} ```php function 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 ``` serve() for an application that sends its pages itself, as one built on Symfony or Laravel does. It works out the same page, and hands it back instead of sending it: the status, the headers and the body. A controller makes the response of its framework from them: ```php $page = respond(__DIR__ . '/../../tools', base: '/admin/tools', session: $request->getSession()); return new Response($page->body, $page->status, $page->headers); ``` The headers belong to the answer, and so does the status. Pass all of them on: they say where a pressed button leads on to, what a file is called and of which kind it is, that the page is not to be kept, and which script the page may run. The request is the one PHP itself is working on ($\_SERVER, $\_GET, $\_POST and $\_FILES). The test client of a framework does not fill those in, so a tool cannot be tried with it. Every setting is the one of serve(), and there is one more: * `$auth` (`callable|null`): see serve() * `$log` (`callable|null`): see serve() * `$name` (`string|null`): see serve() * `$debug` (`bool|null`): see serve() * `$base` (`string|null`): see serve(). In an application it is the path of the route that leads to the controller, as the browser sees it * `$language` (`string|null`): see serve() * `$texts` (`array|null`): see serve() * `$uploads` (`string|null`): see serve() * `$allow` (`callable|null`): see serve() * `$variables` (`array|null`): see serve() * `$session` (`object|null`): the session of your application: the tools keep what they have to keep in it, under one key, and a logout of your application ends that too. An object with get() and set(), as in Symfony, or with get() and put(), as in Laravel. null: PHP's own session **Returns** `Http\Response`: the page: ->status, ->headers and ->body ## Objects a tool gets to hold {#objects} ### Upload {#upload} What `file_input()` returns. A file that a user uploaded with file_input(). The file lies in a folder of the server that only PHP reads. It stays until the user removes it, the tool forgets it or a day has passed. Copy it with saveTo() when it has to stay for longer. * `$name` (`string`): what the file was called on the user's computer, made safe: it never names a folder. Its ending decides what a computer does with the file, so do not trust it * `$size` (`int`): in bytes * `$path` (`string`): where the file lies now. It is not the name the user gave it **contents()** ```php public function contents(): string ``` Everything that is in the file, as one text. For a large file read from path with fopen() or SplFileObject instead. **Throws** * `\RuntimeException` when the file is no longer there **rows()** ```php public function rows(?string $separator = null, ?string $encoding = null): array ``` The rows of a CSV file: the first line names the columns, and every other line becomes one row, name => text. ```php foreach ($file->rows() as $row) { $orders->add($row['email'], (float) $row['total']); } ``` It reads what spreadsheets write: cells apart by ",", ";" or a tab, with or without the mark for UTF-8, in UTF-8, in UTF-16 or in the Western Windows encoding of older versions of Excel. Empty lines are left out, and a line that ends early gets empty cells. Every cell is text and stays as it is in the file: "007" is not 7, and "1,50" is not a number yet. A file that is not text has no rows. The file comes from a user, so look whether the columns you need are there before you use them. The whole file is read into memory. Read a very large file from path yourself, line by line. * `$separator` (`string|null`): what stands between two cells: ",", ";", "|", ":" or a tab. null: found out from the first lines * `$encoding` (`string|null`): for a file in another encoding, such as "Windows-1256" for Arabic from an older Excel. null: found out as far as that goes **Returns** `list>` **Throws** * `\RuntimeException` when the file is no longer there * `\InvalidArgumentException` for a separator or an encoding that cannot be used **saveTo()** ```php public function saveTo(string $path, bool $overwrite = false): void ``` Copies the file to a place where it stays. The name of the new file is yours to choose. When you build it from the name the user gave, remember that a ".php" in a folder the web server serves is a program. The copy is for the PHP user only, as the upload was. Call chmod() on it when somebody else has to read it, such as a web server that runs as another user. * `$overwrite` (`bool`): replace a file that is already there. Without it that is an error **Throws** * `\RuntimeException` when the copy could not be made **forget()** ```php public function forget(): void ``` Deletes the file now and empties its field. Call it when the tool is done with the file, after an import for example: the file would otherwise wait in its field, ready to be imported a second time. The file is gone at once and stays gone, also when the run fails further down. Whatever was done with it has happened by then. ### TableQuery {#tablequery} What a function gets that you pass to `table()` in place of the rows. What a table asks for when it gets a function in place of its rows: one page of the rows, searched and sorted the way the user has set the table. Nothing in it is taken from the browser as it came. The search is one line of text, cut and tidied: put it into a query as a parameter, like any text a user typed. The sort is a value from the sortable: list of the table, or null. The limit and the offset are numbers that the table worked out. Two things are left to the query. To LIKE, % and \_ in the search stand for any text, until the query escapes them. And an order by a column that several rows share has to end with one that no two rows share, or such rows change places between two pages. * `$search` (`string`): what the search box holds. '' while it is empty, and when the table has none * `$sort` (`string|null`): what sortable: says for the column the user sorted by. null while no column is chosen * `$descending` (`bool`): true when that column is sorted from high to low * `$limit` (`int`): how many rows to return at most * `$offset` (`int`): how many rows of the list come before them ### Response {#response} What `respond()` returns. What goes back to the browser. * `$status` (`int`): the HTTP status * `$body` (`string`): the page, or the file of a download * `$headers` (`array`): the headers that belong to the answer, by name * `$alreadySent` (`bool`): the script answered on its own; there is nothing left to send **header()** ```php public function header(string $name): ?string ``` One header by its name, in whatever case it is written. null when the answer has none of that name. **send()** ```php public function send(): void ``` Sends the status, the headers and the body. It does nothing when the script answered on its own. --- --- url: https://script-ui.runio.dev/changelog.md --- # Changelog All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Added * The export of the demo can fail. A box under its start, "Let the worker give up half way", lets the export end at 1,200 of 2,400 orders, and the tool then shows `error()` in place of the bar and offers no file. The tutorial on long tasks walks through those lines. The library itself is unchanged. ## [0.3.0] - 2026-11-29 Help for AI assistants: the whole library on one page that ships with the package, lines that tell an assistant where the page is, and a trial that counts what the help is worth. The code of the library is the same as in 0.2.0, so a tool that runs today runs as before. ### Added * `docs/on-one-page.md`: the model, the rules, every function with its arguments and one whole tool, on one page. It ships with the package, for a person who wants the library at a glance and for an AI assistant that is asked to write a tool. The tests hold the page against the code: every function as `src/functions.php` has it, no function that is not there, and every example run as a tool. * An assistant is told that the page is there. The README has the lines for `AGENTS.md` or `CLAUDE.md`. Laravel Boost offers a few lines more with `php artisan boost:install` (they are in `resources/boost/guidelines/core.blade.php`), and Symfony AI Mate writes the same text into `mate/AGENT_INSTRUCTIONS.md` (`extra.ai-mate` in `composer.json` names it). Tried with Boost 2.10 and AI Mate 0.15. * A trial that counts what this help is worth, in `e2e/assistants`: ten tasks, a browser check for each, and a script that asks Claude Code for every tool without the help, with the page, and with the page and the lines. On 2026-11-28, 39 of 40 tools that were written with the help worked at the first try, and 18 of 20 without it. With the lines an assistant read a third of the tokens. `e2e/assistants/README.md` has the counts and what they cannot say. ## [0.2.0] - 2026-11-28 Tools run inside Symfony and Laravel, a tool can be closed to some users, a table reads its pages from a database, and a bar shows how far a long task is. Before you update from 0.1.0, read "Security" and "Changed": a few things behave differently, and a class of your own that implements `Session` needs one more method. ### Added * `progress()` shows how far a task is: a label, the browser's own bar and a percentage, or your own words with `text:`. Without a value the bar only says that work is going on. With `refresh()` on the same page it follows a task that a worker does somewhere else. There, good news of a button (`success()`, `info()`) next to a bar that is not full stays for ten seconds, and the page then goes on by itself. Bad news waits for the user, as on every page. The demo has a tool that exports orders this way. * `table()` takes a function in place of the rows, for a table that is too long to pass in. The table asks it for one page at a time with a `TableQuery` (the search, the order, a limit and an offset), and the rows stay in the database. `sortable:` names the columns whose headers sort, and `count:` says how many rows there are. Without `count:` the table offers "Previous" and "Next" without a count. Ticks count for the page on the screen, and the table says so when a turned page leaves ticked rows behind. * `respond()` hands the page back instead of sending it, for an application built on Symfony or Laravel: a controller makes the response of its framework from the status, the headers and the body. `session:` keeps what the tools keep in the session of the application. Tried inside Laravel 12 and 13 and Symfony 7.4 and 8.1. * `variables:` in `serve()` gives every tool of a folder variables by name. * `user()` and the log name a user object of Symfony or Laravel by its identifier (`getUserIdentifier()`, `getAuthIdentifier()`), when the login check returns one. * The list of tools says when the folder of tools lies in the web root, where a web server runs a tool file by its name and past the checks of `serve()`. The note shows only where error details are shown. * `allow:` in `serve()` and `configure()` says who may open which tool. It gets what the login check returned and the id of a tool. A tool that is not allowed is left out of the list and answers "Not allowed" before anything of it runs. Only a plain `true` opens a tool, and the question is asked on every request. ### Security * What the library keeps in a session belongs to the user the login check named. When another name shows up in the same session, as after a login without a logout before it, the saved inputs, the uploaded files, the waiting messages and the token of the forms are dropped. Before, they went to whoever used the session next. A session that an older version began has no owner yet, so it starts from nothing once as well. ### Changed * A user object that has `getUserIdentifier()` or `getAuthIdentifier()` goes by what that returns, also when the object is a text as well (`__toString()`). Before, the text was its name. * The `Session` interface has a new method, `clear()`. A class of your own that implements the interface needs it too. * A served tool that ends PHP with `exit` gets its page sent at that moment, and no longer when PHP shuts down. * The list of tools is at the base as `base:` is written. With `base: '/admin/tools'` the links to the list now lead to `/admin/tools` and no longer to `/admin/tools/`. End the base with a slash to keep the old address. ### Fixed * After a fatal error in a served tool the page reports the failure also when another shutdown function raised a warning first. Before, that warning hid the error, and the half-drawn page was sent as if all was well. ## [0.1.0] - 2026-11-27 First version. Requires PHP 8.2+ with the mbstring and session extensions, and no other package. ### Added * A tool is one PHP script. It runs from top to bottom and runs again on every interaction. * Text and messages: `title`, `heading`, `note`, `code`, `json`, `link`, `divider`, `metric`, `success`, `info`, `warning`, `error`. * Inputs that return their current value: `text`, `textarea`, `number`, `select`, `checkbox`, `date_input`. * `radio` shows every option and takes one. `multiselect` shows a tick box for every option and returns the ticked ones as a list. Both take their options the way `select` does, lay them out in a column, in several columns or in a row (`horizontal: true`), and can be filled in by a link. * `table` with sorting, pages (`pageSize:`), a search box (`search: true`) and rows you can tick on any page, one by one or a page at a time. `chart` with bar and line charts drawn as SVG. * `button` with an optional question before it acts, plus `columns`, `stop` and `rerun`. * `expander` puts a part of the page under a line that opens and closes it, and `tabs` puts parts behind headers with one of them in view. What is out of sight still runs: the inputs inside keep working, and opening a part or changing the tab needs no run of the tool. The page remembers what was left open. * `refresh` lets a page run again by itself every few seconds, for dashboards and queues. It waits while the user is in the middle of something, stops while the page is out of sight or nobody is there, waits longer after failures, and never presses a button or changes what the page remembers. * `field_error` says under an input what is wrong with what it holds, and `valid` tells whether anything was found wrong. After a pressed button the first wrong input gets the keyboard focus, and an expander or a tab that hides it comes into sight. Screen readers are told that the input is invalid and read the note with it. A file that a file field turns down is marked in the same way and counts for `valid`. The log entry of a press says what was found wrong. * `file_input` takes files from the user: one or several, with limits on size and kind. A file stays on the server between the runs of a tool, in a folder only PHP reads, and the page names it by a random handle. `Upload` gives the tool `name`, `size`, `path`, `contents()`, `saveTo()` and `forget()`, and `rows()` reads an uploaded CSV file as rows, whichever spreadsheet wrote it. `uploads:` sets the folder, `clean_uploads()` deletes what was left behind. * `download` hands the user a file: rows as CSV or JSON, or any text. `csv` writes rows as CSV with a choice of columns and separator. Cells that a spreadsheet would run as a formula are defused. * `serve()` for a folder of tools with an index page, `configure()` for a script on its own, and the `script-ui serve` command for local use. * A login check and an audit log (`auth`, `log`), protection against forged requests, a strict Content-Security-Policy, and local-only access while no login check is set. * The help text of an input is read out with the input by software that reads the page. * Pages update in place with JavaScript and work as plain forms without it. A title in Arabic or Hebrew turns the page right to left. * The library's own texts ("Yes", "Reset", "No rows.") in English, Arabic and German. A page follows the language of its title, `language:` sets one language for every page, and `texts:` replaces single texts or adds a language. [Unreleased]: https://github.com/RunIO-dev/runio-script-ui/compare/v0.3.0...HEAD [0.3.0]: https://github.com/RunIO-dev/runio-script-ui/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/RunIO-dev/runio-script-ui/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/RunIO-dev/runio-script-ui/releases/tag/v0.1.0 --- --- url: https://script-ui.runio.dev/roadmap.md --- # Roadmap What comes next in Script UI. What is done already is in the [changelog](https://script-ui.runio.dev/changelog.md). An item starts under "Proposed". It moves to "Ready" when the maintainer has approved it. The order under "Ready" is the order of the work: one item at a time, each on a branch of its own, each as a pull request. Each item under "Ready" ends with the public names that it may bring. The maintainer has approved them. `f(a, b)` is a new function with its arguments in their order. `f(+x)` is a new argument at the end of a function that exists. A name with a backslash is a class below `Runio\ScriptUi`. "None" says that the item brings no public name. A pull request that brings another public name, leaves one of these out, or changes a name that exists, waits for the maintainer. ## Ready Approved on 2026-11-28, in this order. The reasons for the order: * Then what makes every later item safer to build: tools that can be tried in a unit test. * Then what people ask for first when they start to use the library. * Proof on real servers and stricter uploads come before the long tail of new inputs, because they decide whether a team may use the library at all. 1. **R2: Try a tool in a unit test.** Fill inputs, press a button and read the messages from PHPUnit. Today a tool can only be tried in a browser test. Names: `Testing\ToolTester`, `Testing\ToolTester::open(file, user)`, `Testing\ToolTester::fill(label, value)`, `Testing\ToolTester::upload(label, file)`, `Testing\ToolTester::tick(rows, table)`, `Testing\ToolTester::press(label)`, `Testing\ToolTester::messages(kind)`, `Testing\ToolTester::value(label)`, `Testing\ToolTester::rows(table)`, `Testing\ToolTester::download()`, `Testing\ToolTester::html()`. 2. **R4: A button in every row of a table.** Today the user ticks a row and presses a button under the table. For one row that is a step too many. Names: `table(+rowButtons)`. 3. **R3: Several inputs sent together.** Every changed choice runs the script again. A long form with a slow query behind it wants one run, when its button is pressed. Names: `form(content, button, key)`. 4. **R14: Recipes for php-fpm with nginx and Apache**, tried in CI. So far the library was tried on PHP's own server only. Names: none. 5. **R1: Choices that search in your data.** `select()` and `multiselect()` get all their options from the script. A customer out of 50,000 cannot be chosen that way. A function would get what was typed and return the options that match. Names: none. 6. **R9: Stricter uploads.** Judge a file by what is in it and not by its name, and limit the bytes a session may hold. Names: `configure(+uploadLimit)`, `serve(+uploadLimit)`, `respond(+uploadLimit)`. 7. **R7: More inputs.** A time, a range of dates, a slider, a switch, a password. Names: `time_input(label, default, min, max, step, help, key)`, `date_range(label, default, min, max, help, key)`, `slider(label, default, min, max, step, help, key)`, `toggle(label, default, help, key)`, `password(label, placeholder, help, key)`. 8. **R5: Tabs that run only when they are open.** Every tab runs on every run. A link cannot open a tab or an expander yet. Names: `tabs(+onlyOpen)`. 9. **R8: Pictures and formatted text.** `image()` and `markdown()`. Names: `image(source, alt, caption, width)`, `markdown(text)`. 10. **R15: More for screen readers.** Say the note under a field while the user types, and give the signs in front of messages words. Names: none. 11. **R13: Browser tests on Firefox and WebKit.** Names: none. 12. **R12: The table example on MySQL and PostgreSQL**, in CI. Names: none. 13. **R6: A refresh for one part of a page.** `refresh()` runs the whole script and swaps the whole content. Names: `refresh(+content)`. 14. **R10: More kinds of charts.** Stacked bars and areas. Names: `chart(+stacked)`. 15. **R11: More built-in languages.** French, Spanish and Turkish next to English, German and Arabic. Names: none. ## In review Nothing yet. ## Proposed Not approved yet. Each of these needs a decision that only the maintainer can make. * **R16: The website published by CI** with every release, with fresh pictures. CI builds and checks it already, and publishing is done by hand. It needs a key for the server in the settings of the repository. Later a public demo with data of its own for every visitor. * **R20: A hint when a tool calls a function that it did not import.** A tool that calls `table()` without `use function Runio\ScriptUi\table;` ends in "Call to undefined function". The trial with AI assistants found this mistake in all three tools that failed. Where error details are shown, the page could say which line is missing. * **R17: Packages for Laravel and Symfony.** A route, the session and the rights wired up around `respond()`, in place of the lines of the manual. Each would be a package and a repository of its own. ## Not planned * **A queue or a worker inside the library.** A tool starts your job and shows its numbers. The job stays yours. * **Pages for the public.** A tool is for people inside, behind a login.