ui_app

source of ui_app

1// The app services of pkg::alloy::ui (REFOCUS.md, R6e, question2// 9A): screens and history, numbers moving, dates in the locale, forms,3// requests, storage, file dialogs and drops, on the core's widgets and4// ui_controls'.5//6// ```text7// import pkg::alloy::ui;8// import pkg::alloy::ui_app;9//10// fn main() -> i32 {11//     return app(&WindowConfig { .title = &"Notes", .app = &"notes" }, (ui) => {12//         const notes = ui.persisted(&"notes", String::empty(), Write::text(), Read::text());13//         return ui.add(Text { .text = copy notes.get(&ui) });14//     });15// }16// ```17//18// Each keeps its state as an extension of the Ui (`Extension`), installed19// as it is first used, so a program not using one carries none of its20// code.21//22// ## How it was built23//24// **R6f as built** (2026-10-26; REFOCUS.md, the portal and25// drops under ui_app): `Files` calls the window's `install_files` as it26// first gives the window something, so the portal's file chooser, the27// shell's dialogs, NSOpenPanel and the drop targets are linked only into28// programs asking for a dialog or laying out a `DropArea`; on Linux the29// settings portal's wish for less motion comes with them (or with30// pkg::alloy::ui_access), else reads as off.31//32// **R6e as built** (2026-10-26): moved out of `ui`, whose notes of F11c,33// F11d, F11e, F12c, F12d, F12e and F13 tell how each was first built,34// with their notes here: `screens.alloy` (`Navigator`, `ui.screens`, the35// window's history, screens pushed and popped moving), `animations.alloy`36// (`ui.animated`), `dates.alloy` (`Calendar`, `DatePicker`, `TimePicker`,37// `ui.today()`, `ui.locale()` with CLDR's tables), `forms.alloy`,38// `network.alloy` (`ui.send`, `ui.load`), `persisted.alloy` (`ui.store()`,39// `ui.persisted`), `files.alloy` (`ui.open_files`, `save_file`,40// `save_bytes`, `DropArea`). Hooks became extensions: `Navigation` (Back,41// Alt+Left, `Event::Navigated`, the window's history as it is shown),42// `Animations`, `Dates`, `Forms` (a field's focus left), `Requests` (an43// owner going, the network's deadline, busy nodes, the page's inbox),44// `KeptState` (the store written after each event and as the window45// closes), `Files` (dialogs' results, drags and drops). The network's46// tasks run as the core's `Service`, started by the first request in the47// scope `app` gives its workers. `on_drop` on `Column`, `Row` and `Stack`48// became the `DropArea` widget, and `ReplayConfig.responses` the49// `replay` taking them.50//51// **F11c as built** (2026-10-15; decisions/F11.md, "Screens",52// questions 5A and 6B), the part ui_app holds since R6e:53// - Navigators: `Navigator<R>` a handle on a signal of `Routes<R>` (the54//   routes, a serial each telling a route replaced, the routes `back`55//   took, kept for Forward, the paths and the screens' element);56//   `navigator`, `navigator_with`, `push`, `back`, `replace`, `reset`,57//   `current`, `depth`. `ui.screens(nav, screen)` is a transparent58//   element keeping a screen a route: those whose serials stay are kept,59//   those above freed with all they made, new ones made, all but the top60//   hidden. A screen hidden under a new one keeps the element that had61//   the focus in it; once laid out, a screen shown again gives that62//   element the focus, a new one its first taking it63//   (`ui.focus_after`).64// - Back: `nav.back`, the mouse's Back button (natively; on the web the65//   browser goes back by it, which comes as Navigated), Alt+Left or66//   Command+[ on macOS before the focused element, each to the deepest67//   navigator on screen (alive, its screens in no hidden view) with more68//   than one screen; navigators are `Navigable` objects in69//   `ui.navigators`, forgotten once gone.70// - History (question 6B): after each event the Ui gives the window71//   `set_history(depth, path)`, the depth 1 and one more for each screen72//   over a first among the navigators on screen, the path the deepest73//   one's with paths. `Event::Navigated` takes the navigators back or74//   forward until as deep, forward bringing back what `back` took, the75//   last step the entry's path's screen when it parses. The first76//   navigator with paths starts at the path the page opened at77//   (`window.start_path()`), over its first screen, unless it is the78//   first's own.79//80// **F11d as built** (2026-10-15; decisions/F11.md, "Dates and81// times", questions 8A, 9A and 10A):82// - std::time's calendar (question 8A): `Month` and `Weekday` tagged with83//   their numbers, `Date` (a struct `==` compares, so `Equal` with no84//   marker) with `of`, `try_of`, `from_days`, `today`, `days`, `weekday`,85//   `add_days`, `add_months`, `compare`, `before`, `after`, written as86//   ISO 8601; `TimeOfDay` written `14:30`; `local_offset` through a new87//   `al_sys_local_offset` in each system file, the page's `Date` on the88//   web.89// - `Calendar` (`dates.alloy`): the month's title between two chevron90//   buttons (marks `previous` and `next`, made as one first lays out),91//   the weekdays' first two letters from `first_weekday`, and six weeks92//   of 36-pixel days, those of other months left blank. The chosen day93//   is a filled circle, today a ring, the keyboard's day a rounded94//   square; days outside `earliest` and `latest` muted, those95//   `available` refuses muted and struck through. One Tab stop: Left and96//   Right a day, Up and Down a week, Page Up and Down a month, with Shift97//   a year, Home and End the week's ends, all kept within the range;98//   the month follows the day and is announced (`ui.announce`, polite);99//   Enter, Space or a click choose; the buttons turn the month, the day100//   moving with it. A program choosing a day in another month shows that101//   month. English names (question 9A): `month_name`, `weekday_name`,102//   `long_date` ("15 October 2026"), `month_title` ("October 2026"),103//   which F12e replaced by the locale's.104//   `ui.today()` is the day calendars take as today, `ui.set_today` fixes105//   it for tests and goldens.106// - `DatePicker`: a field like a Select's showing `format`'s text or the107//   placeholder, as wide as the longest month's day, opening a Calendar of108//   its options in a popup below it by a click, Enter, Space, Down or109//   Expand; choosing a day closes it first, the day already chosen unheard.110// - `TimePicker` (question 10A): a `Select<TimeOfDay>` it makes from its111//   options as it first lays out and renews after, the times from112//   `earliest` to `latest` by `step_minutes`; Select's input became113//   `handle(ui, input, closed)`, `closed` telling the element holding it114//   that its list closed. `TimeOfDay` satisfies `Equal` with no marker.115// - Accessibility: the calendar is a `Grid` described by its month, its116//   days `GridCell` parts labelled "Thursday 15 October 2026" with their117//   row and column (window's new `Semantics.cell`), `selected`,118//   `disabled` outside the range or refused, today `current`; a119//   DatePicker a button with the date as its value and `expanded`,120//   which every tree gives (question 19A); a TimePicker a combo box.121// - Size (question 16A): the counter grew by 14.3 KB natively (1,813,040122//   bytes) and 1.4 KB on the web (1,296,717): the grid roles in each tree,123//   AT-SPI's Table and TableCell interfaces most of it natively; the124//   widgets come only with a program using them.125// - Tests: five in `ui/tests.alloy` (a calendar's keys across months and126//   years and its announcements; its pointer, buttons and range; its127//   tree; a date picker by the pointer and the keys; a time picker's128//   choices and type-ahead); goldens `calendar.png`, `calendar_dark.png`129//   and `date_picker_open.png`; std's `calendar` and `time_zone` tests;130//   `tests/atspi` reads a date picker's calendar through Table and picks131//   a day, `tests/automation` (by hand on Windows) the same through Grid132//   and SelectionItem.133// - Sample `booking.alloy`: a visit booked from an inline calendar of134//   the next three months (Mondays closed, a few days sold out) and a135//   time from 10:00 to 18:00 by half hours, and the same as a form with a136//   date picker, a time picker and a summary.137//138// **F11e as built** (2026-10-15; decisions/F11.md, "Motion",139// questions 11A, 12A and 13A), the part ui_app holds since R6e:140// - `ui.animated(value, motion) -> Animated`: a signal of a course,141//   `get` giving where it is at the Ui's time and recording the read;142//   `set` (question 21: the design's `to` is a keyword), `jump`,143//   `target`. A new target adds a move of the difference beside those144//   under way, each eased from its own start, so the value is continuous145//   and its speed kept (four at most, then gathered into one); a146//   repeated motion goes from where it is. Under reduced motion, unless147//   essential, `set` jumps.148//149// **F12c as built** (2026-10-16; decisions/F12.md, "Waiting in150// ui", questions 4A, 7A and 8C):151// - `ui.send(request, then) -> Pending`, `cancel_request`, `progress`;152//   `ui.load(request, read, LoadOptions) -> Resource<T>` with `state`,153//   `stage` (a `Stage` key for `switch`), `latest` and `reload`;154//   `Loading<T>`, `Failure` (Format: "the server answered 503").155//   `network.alloy`: each request is an exchange slot belonging to an156//   owner (the element's whose handler sent it), whose going cancels it;157//   what came back runs as a handler at the next update, `then` never158//   once cancelled. A resource's request is a binding: run again when a159//   signal it read changes, it cancels the exchange under way and starts160//   the next after `delay` (the first at once), None waiting for161//   nothing; the last Done is kept as `latest` while the next loads162//   (`keep`). A failure the user asked for (`send`, `reload`) is163//   announced assertively.164// - Where requests run: natively on eight network tasks in `app`'s scope165//   beside the four workers (since question 20B started by the first166//   request: "Sizes after F12"), serving the same loop (a job takes the167//   network's state, `Workers.network`); a task makes a `Control` per168//   exchange, listed by the Ui's id so the UI thread cancels it and169//   reads its progress, `read` running on the task, and the result goes170//   back through the background work's channel and waker. Closing the171//   window cancels what is under way and refuses what is queued. Since172//   question 18A (2026-10-16) the app's `Network` holds a173//   `std::http::Client` its tasks send through, so an app's requests174//   share kept connections, disposed with the workers as `app` ends. On the175//   web `std::http::start` over `fetch` (std's `http.web.js`), its176//   callback putting the result in an inbox on the heap and waking the177//   loop through `Waker::Page`. In a replay, `ReplayConfig.responses`178//   (`ScriptedResponse::answered`, `failed`) answer by URL at their179//   script time, the progress going evenly until then, a request none180//   answers failing with Unsupported; `replay` runs `read` at once. A Ui181//   on its own sends at once (Unsupported in the interpreter).182// - Progress: while a shown binding reads an exchange's progress (a183//   `send`'s through `ui.progress`, a resource's through its state), a184//   timer looks at it every 100 ms (`arm_network` before the deadline),185//   setting what changed.186// - `ProgressBar` (value 0 to 1, or None: a third of the track crossing187//   it each second, pulsing under reduced motion), a progress bar to188//   screen readers with its value in percent. `busy`: an element whose189//   binding read a resource waiting, or the nearest above it with a190//   role, the window when none (an effect now knows its element,191//   `Effect.node`).192// - Hooks for an owner going, the deadline, the tree sent, the page's193//   wake and the window closing, set as the first request goes;194//   `gpu::Resource` is `BindingResource` (question 19); `ui.alloy`195//   imports `std::result as std_result`, `gpu` having its own `Result`.196// - std: `JsonReader` (std::json), `std::http::start`, `cancel` and197//   `progress` of an `Exchange` on the web.198// - Size (question 20): the counter is 1,831,968 bytes natively199//   (1,830,080 before, +1.9 KB) and its wasm 1,307,087 (1,305,177, +1.9200//   KB), built as `bench.sh` builds it. The shows sample is 2.53 MB201//   natively (TLS and std::http with it) and 1.73 MB of wasm.202// - Tests: five in `ui/tests.alloy` (a resource waiting, failing,203//   loading again and keeping its last value; a request asked again204//   after its delay as a search is typed, one request going; progress205//   every 100 ms and owners cancelling; busy and the progress bar in the206//   tree; a Ui on its own), goldens `loading`, `load_failed` and207//   `progress` in light and dark and `loaded`; `tests/network` against208//   the shows server (shows, a hold, a 3 MB ticket with its progress209//   read on the way, a 503, a request cancelled) under weston, under210//   qemu and in node's page through node's fetch; `tests/access` and211//   `tests/atspi` read a progress bar and busy. Under the headless212//   weston frames presented one after another stall for seconds, so213//   `tests/network` draws nothing that changes.214// - Samples `shows_server.alloy` (shows as JSON, holds running out after215//   two minutes, a 3 MB ticket over two seconds, the web build's page,216//   `?delay=` and `?fail=`) and `shows.alloy` (a search loading as one217//   types, a spinner, the reason and Try again, holds counting down to218//   the server's moment, a download with a progress bar and Cancel).219//220// **F12d as built** (2026-10-16; decisions/F12.md, "Storage",221// question 9A):222// - `WindowConfig.app` (window): the name the app's data is kept under,223//   else the title (`app_name`), also sent as Wayland's `app_id`.224// - `ui.store() -> &var KeptStore` (`persisted.alloy`): std::storage's225//   store "app" under the app's name, opened when first asked for, a226//   `KeptStore` since the Ui cannot be disposed (question 21); a Ui made227//   on its own has no name and keeps it in memory. After each event,228//   Redraws too, the `stored` hook writes what changed: at once when the229//   last write began a second ago or more, else once a timer of the Ui's230//   own says it has; natively on a worker (`unsaved`, then `write` on231//   the worker, `wrote` back on the UI thread), in place with no232//   workers. As the window closes, and as a replay ends, `store_ending`233//   writes what is left. The worker's write and the last one take turns234//   through `Network.kept`, a mutex over how many changes the file235//   holds, so the older never lands over the newer (since question 23B236//   a flag: see "Sizes after F12"). On the web nothing is hooked: each237//   set reaches localStorage at once.238// - `ui.persisted(key, initial, write, read) -> Signal<T>`: the value239//   `read` takes from the store, else `initial`; an effect of the240//   signal's owner writes it back as it changes, its first run only241//   reading.242// - Tests: three in `ui/tests.alloy` (saved after the handler, a second243//   apart at most, as the window closes and as a replay ends, the next244//   run starting from it; what `read` refuses giving `initial` beside245//   the program's own keys; a Ui on its own in memory); `tests/storage`246//   counts its runs across two runs under weston, natively and under247//   qemu, each with a data directory of its own, and in node's page over248//   the fake page's localStorage kept in a file (`ALLOY_PAGE_STORAGE`),249//   then refusing writes (`ALLOY_PAGE=full`); `scripts/test.sh` gives250//   every program run a data and cache directory of the test's own.251// - Size: the counter is 1,874,896 bytes natively (1,871,456 before, +3.4252//   KB) and its wasm 1,335,883 (1,333,439, +2.4 KB), built as `bench.sh`253//   builds it: the app's name kept and sent as `app_id`, the hooks'254//   calls and the Ui's and Network's new fields' glue (question 23);255//   window's hello +0.9 KB natively, +0.3 KB of wasm, mostly `app_id`. A256//   counter whose count is persisted is 18.7 KB larger natively and 55 KB257//   of wasm (std::json's exact floats, std::fs and the store).258// - Sample `preferences.alloy`: the dark theme, a name, a basket of four259//   items and five recent searches, each persisted, a line saying where260//   they are kept, and "Forget everything" (question 22).261//262// **F12e as built** (2026-10-16; decisions/F12.md, "Dates in the263// world", questions 10A-14A; std::time's zones and std::locale's notes264// have the rest):265// - The Ui's locale (question 14A): `ui.locale()` is the one266//   `ui.set_locale(::Some(locale))` set, else `Locale::system()`, read267//   only when a date widget or the app asks, so a program showing no date268//   links none of std::locale's tables; `kept_locale` keeps the system's269//   once read. `set_locale` lays everything out again; since question 27B270//   (2026-10-16) the locale is a signal of the Ui's own, made with it, so271//   bindings reading `ui.locale()` run again too (a test in272//   `ui/tests.alloy`; `showtimes.alloy`'s rows read it).273// - `Calendar` and `DatePicker`: `first_weekday` is an `Option`, None the274//   locale's. The calendar writes its title (`format_date` of month and275//   year: "October 2026", "octobre 2026", "2026年10月"), the weekdays'276//   short names (`Width::Short`, "Mon", "lun.", "月", question 30B; at277//   first CLDR's shorter `Width::Shortest`, "Mo"; the narrow ones where278//   one is wider than a day, as Arabic's), the days' numbers in the279//   locale's digits and the spoken dates ("Thursday, 15 October 2026")280//   in the locale it last laid out in, keeping its layouts until the281//   locale, the first weekday or the fonts change (`Ui.fonts_changed`,282//   counted as a window's canvas replaces the bundled fonts and as fonts283//   arrive on the web). In a locale written right to left284//   (`Locale.right_to_left()`, question 28A, 2026-10-16) the week runs285//   from the right, the month before's button is on the right, each286//   chevron pointing away, and Left and Right go the way the week shows;287//   the cells keep their logical columns in the trees (a test in288//   `ui/tests.alloy`, golden `calendar_ar`).289// - `DatePicker.format` is an `Option`, None the locale's medium date290//   ("15 Oct 2026", "Oct 22, 2026", "22 oct. 2026", question 24B, built291//   2026-10-16 after the long date first); its width is the widest of292//   the year's months' 28th.293// - `TimePicker` writes its times on the locale's clock ("14:30",294//   "2:30 PM", through `format_moment` on UTC, question 29) and makes its295//   Select's choices again when the locale changes; type-ahead follows296//   what is shown ("3" goes to 3:00 PM in en-US).297// - The English `month_name`, `weekday_name`, `long_date` and298//   `month_title` are gone; `samples/booking.alloy` writes its summary299//   in the locale.300// - Tests pin `en-GB` where they pin today, so F11's goldens and access301//   trees stay but for the comma CLDR puts after the weekday in a spoken302//   date ("Thursday, 22 October 2026" in `tests/atspi` and303//   `tests/automation`); goldens `calendar_fr` and `calendar_en_us`; a304//   test in `ui/tests.alloy` switching the pickers and the calendar305//   between en-GB, en-US and French.306// - Benchmark `dates_format` (`bench/dates.alloy`): 10,000 moments with307//   names in French on Paris's clocks, 75 ms (budget 120, question 25).308// - Size: the counter is 1,875,504 bytes natively (+608 since F12d, 96309//   of them the Ui's locale) and its wasm 1,336,363 (+480); hello world310//   is unchanged. A program formatting dates with names carries the311//   tables: booking grows by 241 KB natively and 250 KB of wasm312//   (question 26).313// - Sample `showtimes.alloy`: shows in Paris, New York and Tokyo from314//   `showtimes.json` (RFC 3339 times, read by `#read_file`), each written315//   on the venue's clocks and the user's with the zones' names, prices in316//   the venue's currency; a Select of locales (the system's, en-US,317//   en-GB, fr, de, ja, ar) changes every date, price and the calendar of318//   the days with a show, and a field goes to a day typed in ISO 8601.319//320// **F13 as built** (2026-10-17; decisions/F13.md, decided as321// recommended, 1A-5A, 6B, 7A-10A; questions 11-13 then decided A):322// - Forms (`forms.alloy`): `ui.form()` is a handle on three signals of the323//   owner making it: the fields' slots with what a submit that passes324//   runs (`FormFields`, peeked, never read in a binding), `tried` and the325//   `failure` of the whole. A field's slot keeps its label, hint, whether326//   it is required, the signals of its text and its `FieldState` (left,327//   a server's refusal), the element showing it and its parsing and rules328//   behind a `Checking` object (`Checked<T>`, a `Source<T>` typed by a329//   `Parser<T>` or picked into a signal), so only giving a value is330//   generic; `Field<T>` is the form and an index. `Rule<T>` and331//   `Parser<T>` are named function types (the language's 1A), lambdas and332//   named functions taking their place; a typed field's `FieldOptions`333//   leaves its type arguments out (2A). `Checked<bool>`'s own `unset` and334//   `wanted` (specializations) make a required box Check one that must be335//   true.336// - Nothing of a verdict is kept: `verdict`, `error`, `valid` and337//   `errors` parse and check again, so a binding showing an error follows338//   every signal its rules read (a password's repetition follows the339//   password). An error shows once its field was left changed (the text340//   field's focus, through the new `field_focus` hook a text field calls341//   as it gains or loses the focus, set by the first form), the form was342//   submitted or a server refused it, and from then on as it changes; a343//   picked field's error shows once picked. A field counts while its344//   element exists in no hidden view.345// - `submit`: the errors in Tab order (each field where the first element346//   taking the focus in its element comes, `tab_order`), the first focused347//   with the ring and scrolled into view, one assertive announcement ("2348//   fields need attention: City, Street."), else `on_submit`'s function.349//   `field.refuse` shows at once, announces "Card number: ..." and focuses350//   the field when it is the first in error; its next edit clears it.351//   `form.refuse` sets `failure` until the next submit, announced.352// - Showing fields: `ui.text_field` binds a TextField (text, error,353//   `required`, the label for screen readers, the hint as its new354//   `description`, `on_change`, Enter submitting on one line); `ui.input`355//   binds any widget, recording its element; `ui.labelled` a column of the356//   label (13 px semibold, " (optional)" muted when not required, none357//   over a Checkbox), the hint, the element and the error revealed under358//   it in the theme's danger color, as the checkout had them;359//   `ui.form_summary` a panel from the first failed submit while errors or360//   a failure remain, made again (`switch`) as they change: "There is a361//   problem", the failure, a plain button a field focusing it; to screen362//   readers a group named by its title (`SummaryPanel`).363// - Rules (`Rules::length` in grapheme clusters through364//   pkg::alloy::text's new `grapheme_count`, the text's ends' spaces365//   aside; `email`, WHATWG's grammar with a dot in the domain; `shape`;366//   `between<T: Number>`; `.said`) and parsers (`Parse::integer` in ASCII367//   or another script's digits with no tables, `number`, `date` and `time`368//   through std::locale's new `parse_number`, `parse_date` and369//   `parse_time` in the Ui's locale). Messages are English370//   (`english_*`), unless `ui.set_form_messages` gave others; they take the371//   Ui (question 11), reading its locale only for an example or a number.372// - Widgets: `TextField.text` defaults to empty and gains `description`373//   and `required`; Select, ChoiceList, Radios, Checkbox, DatePicker and374//   TimePicker gain `error` and `required`: a field's border in the danger375//   color at 1.5 pixels (2 with the focus ring), a checkbox's box and the376//   radios' circles in it, and `invalid`, `required` and the message as377//   the description to screen readers. Window's `Semantics.required`:378//   UI Automation's `IsRequiredForForm` and `required=true` in379//   `AriaProperties`, AT-SPI's `REQUIRED` with its `StateChanged`,380//   `aria-required`, NSAccessibility's `isAccessibilityRequired`.381// - Size: the counter is 1,907,392 bytes natively (1,907,088 before382//   F13, +304) and 1,357,334 of wasm (1,357,062, +272), built383//   as `bench.sh` builds it: `required` in each tree and the semantics'384//   glue, the hook's field and call in the text field (not in the385//   counter), the Ui's `forms` signal handle. A first measure had the386//   forms' state behind an object (+352 bytes of glue) and the focus hook387//   in `focus_node` (+384): the state is now a signal of the root's and388//   the hook the text field's.389// - Tests: fifteen in `ui/tests.alloy` (when errors show, Tab order and390//   the announcement, Enter submitting, a hidden field, a rule reading391//   another field, refusals, picked fields required, the trees, messages392//   replaced, `valid` in a binding, the rules' table, a replay's393//   announcement, the parsers in French and American English, `between`,394//   a parsed field); goldens `form_errors`, `form_errors_dark`,395//   `form_summary` and `pickers_error`; `tests/access` (`aria-required`),396//   `tests/atspi` (`REQUIRED`), `tests/automation` (`IsRequiredForForm`,397//   by hand on Windows). Benchmark `ui_form`: a keystroke in the first of398//   50 labelled fields after a submit, the last field's rule reading it,399//   0.008 ms (budget 0.1): its bindings and layout touch only the400//   two fields.401// - Samples: `form`, `todo`, `dialogs`, `screens`, `choices`,402//   `preferences`, `booking`, `clock` and `showtimes` validate, each403//   saying what in its opening comment; new `signup.alloy`. The tickets'404//   checkout is a form (F13c): its fields' rules (the card's check digit,405//   the expiry parsed into a month and a year not past) are functions the406//   tickets' tests call, a declined card is `field.refuse` on the card407//   number, and `form.alive` (new) tells a payment's answer whether the408//   screen is still there; goldens `checkout` and `declined` made again.409//   No sample disables its submit button (4A). `Field.form` is exported,410//   for a button submitting a field's form.411412import std::string;413import std::vector;414import std::option;415import std::math;416import std::number;417import std::sync;418import std::map;419import std::hash as hash;420import std::equal;421import std::time;422import std::result as std_result;423import std::format;424import std::http;425import std::json;426import std::storage;427import std::locale;428import pkg::alloy::window;429import pkg::alloy::draw;430import pkg::alloy::text as text;431432import pkg::alloy::ui;433import pkg::alloy::ui::store;434import pkg::alloy::ui::tree;435import pkg::alloy::ui::layout;436import pkg::alloy::ui::painting;437import pkg::alloy::ui::events;438import pkg::alloy::ui::widgets;439import pkg::alloy::ui::fields;440import pkg::alloy::ui::scrolling;441import pkg::alloy::ui::running;442import pkg::alloy::ui::timers;443import pkg::alloy::ui::layers;444import pkg::alloy::ui::motion;445import pkg::alloy::ui::transitions;446import pkg::alloy::ui::languages;447import pkg::alloy::ui::extensions;448import pkg::alloy::ui::views;449import pkg::alloy::ui_controls;450import screens;451import animations;452import dates;453import forms;454import network;455import persisted;456import files;457458// Replays the app as `replay` does, every request answered from the459// responses, none by the network.460exp fn replay(461    config: &WindowConfig,462    options: ReplayConfig,463    responses: Vector<ScriptedResponse>,464    view: |=| (&var Ui) -> Element,465    events: &[Event]466) -> Replayed {467    var answered = |move responses, move view| (ui: &var Ui) -> Element {468        ui.use_script(copy responses);469        return view(&var ui);470    };471    return replay(&config, move options, move answered, &events);472}473474// Shows a dialog choosing files to open, then calls `then` with them,475// unless it was cancelled. On the web each file comes with its bytes.476exp fn open_files(self ui: &var Ui, dialog: FileDialog, then: |=| (&var Ui, Vector<ChosenFile>)) {477    ui.ask_dialog(AskedDialog {478        .kind = DialogKind::Open,479        .dialog = move dialog,480        .then = move then481    });482}483484// Shows a dialog choosing where to save, then calls `then` with the485// file, unless it was cancelled; `save_bytes` writes it.486exp fn save_file(self ui: &var Ui, dialog: FileDialog, then: |=| (&var Ui, ChosenFile)) {487    ui.ask_dialog(AskedDialog {488        .kind = DialogKind::Save,489        .dialog = move dialog,490        .then = |move then| (ui: &var Ui, files: Vector<ChosenFile>) {491            var all = move files;492            if (all.try_remove(0) is ::Some |move file|) {493                then(&var ui, move file);494            }495        }496    });497}498499// Writes the bytes into a file `save_file` gave (Window::save_bytes);500// whether it was written, or given to the page to write.501exp fn save_bytes(self ui: &var Ui, file: &ChosenFile, bytes: &[u8]) -> bool {502    return ui.save_for_page(&file, &bytes);503}504505// Its children laid out as a stack's, taking files or text dropped on it,506// which `on_drop` is given at their point in its coordinates; while507// something dragged over the window would drop on it, it shows so.508exp type DropArea : Widget = struct {509    exp children: &[Element] = &[],510    exp on_drop: |=| (&var Ui, &Drop),511    exp padding: Padding = Padding {},512    exp align: Alignment = Alignment::Start,513    exp background: Ink = Ink::None,514    exp border: Ink = Ink::None,515    exp radius: f32 = 0.0,516    exp sizing: Sizing = Sizing {},517    pub targeted: bool = false, // its own state: something would drop on it518};519520/* --- Waiting (decisions/F12.md, F12c) --- */521522// What a resource `load` keeps holds now.523exp type Loading<T> = enum {524    Waiting: Progress, // the exchange under way, or none asked for525    Done: T,526    Failed: Failure,527};528529// Why a resource or a request failed.530exp type Failure : Format = enum {531    Network: HttpError, // nothing usable came back532    Status: Response, // the server answered, not with 2xx533    Unreadable: String, // the answer came, but `read` refused it: why534};535536// The reason, as a sentence goes on after "failed: ".537exp fn format(self failure: &Failure, out: &var String) {538    write_failure(&failure, &var out);539}540541// A Loading's variant alone: a key for `switch`.542exp type Stage = enum {543    Waiting,544    Done,545    Failed,546};547548exp type LoadOptions = struct {549    // wait this long after the request last changed: a search asked for550    // as one stops typing551    exp delay: Duration = Duration::from_nanoseconds(0),552    exp keep: bool = true, // keep the last Done value readable while the next loads553    // what the resource belongs to, going with it: None, what is made now554    exp owner: Option<Owner> = ::None,555};556557// Data a request gives, read into the program's type, in a signal558// (`load`).559exp type Resource<T> = struct {560    pub state: Signal<Loaded<T>>,561    pub slot: u32, // its slot among the Ui's resources, and its generation562    pub generation: u32,563};564565// A request `send` sent, until what came back is handled.566exp type Pending = struct {567    pub index: u32,568    pub generation: u32, // a pending finished names nothing569};570571// A response `replay` gives a request for the URL, at the script's time;572// each answers one request, those for one URL in order. Until then the573// exchange's progress goes evenly from nothing to the body's length.574exp type ScriptedResponse = struct {575    exp url: String,576    exp at: Duration,577    exp answer: std_result::Result<Response, HttpError>,578};579580// A response of the status and the body, at the time.581exp fn ScriptedResponse::answered(582    url: &[u8],583    at: Duration,584    status: u16,585    body: &[u8]586) -> ScriptedResponse {587    return ScriptedResponse {588        .url = String::from(&url),589        .at = at,590        .answer = ::Ok(Response {591            .status = status,592            .headers = Vector<Header>::empty(),593            .body = Vector<u8>::from(&body),594            .url = String::from(&url)595        })596    };597}598599// The request failing at the time.600exp fn ScriptedResponse::failed(url: &[u8], at: Duration, error: HttpError) -> ScriptedResponse {601    return ScriptedResponse { .url = String::from(&url), .at = at, .answer = ::Err(move error) };602}603604// The data the request gives, read by `read`, kept in a signal. The605// request function is a binding, run again when a signal it read606// changes, which cancels the exchange under way and starts the new one607// (after `delay`; the first starts at once); None leaves the resource608// waiting for nothing. Natively `read` runs with the exchange, off the UI609// thread. The exchange is cancelled when the owner goes.610//611// ```text612// const shows = ui.load(613//     (ui) => ::Some(Request::get(&f"{API}/shows?q={encoded(&search.get(&ui).view())}".view())),614//     (response) => read_shows(&response),615//     LoadOptions { .delay = Duration::from_milliseconds(300) },616// );617// ui.switch((ui) => shows.stage(&ui), (ui, stage) => match (stage) { ... }, Keep::None);618// ```619exp fn load<T>(620    self ui: &var Ui,621    request: |=| (&Ui) -> Option<Request>,622    read: |=| (&Response) -> std_result::Result<T, String>,623    options: LoadOptions624) -> Resource<T> {625    const saved = ui.owner;626    ui.owner = ui.owner_given(options.owner);627    const resource = ui.new_resource(move request, move read, options);628    ui.owner = saved;629    return resource;630}631632// What the resource holds now; read in a binding, which runs again when633// it changes.634exp fn state<T>(self r: &Resource<T>, ui: &Ui) -> &Loading<T> {635    return &r.state.get(&ui).now;636}637638// Whether it waits, is done or failed: a key for `switch`, which changes639// only between those.640exp fn stage<T>(self r: &Resource<T>, ui: &Ui) -> Stage {641    return match (r.state.get(&ui).now) {642        ::Waiting Stage::Waiting;643        ::Done Stage::Done;644        ::Failed Stage::Failed;645    };646}647648// The last Done value, kept while the next loads unless `keep` is false.649exp fn latest<T>(self r: &Resource<T>, ui: &Ui) -> Option<&T> {650    const loaded = &r.state.get(&ui);651    if (loaded.now is ::Done |&value|) {652        return ::Some(&value);653    }654    if (loaded.kept is ::Some |&value|) {655        return ::Some(&value);656    }657    return ::None;658}659660// Asks for the request again now, the exchange under way cancelled: "Try661// again", or pulling to refresh. A failure then is announced.662exp fn reload<T>(self r: &Resource<T>, ui: &var Ui) {663    ui.reload_resource(r.slot, r.generation);664}665666// Sends the request; `then` runs as a handler with what came back. The667// exchange belongs to the owner of the element whose handler sent it and668// is cancelled when the owner goes (`then` then never runs). A failure,669// the request's or the server's, is announced.670exp fn send(671    self ui: &var Ui,672    request: Request,673    then: |=| (&var Ui, std_result::Result<Response, HttpError>)674) -> Pending {675    return ui.send_request(move request, move then, ::None);676}677678// `send` with the options: a request belonging to their owner, as a679// payment whose answer counts after its screen went.680exp fn send(681    self ui: &var Ui,682    request: Request,683    then: |=| (&var Ui, std_result::Result<Response, HttpError>),684    options: HandlerOptions685) -> Pending {686    const owner: Option<u32> = if (687        options.owner is ::Some |o|688    ) ::Some(ui.owner_index(o)) else ::None;689    return ui.send_request(move request, move then, owner);690}691692// Cancels the request: `then` never runs. Nothing once it finished.693exp fn cancel_request(self ui: &var Ui, pending: Pending) {694    ui.cancel_pending(pending);695}696697// How far the request has gone; None once it finished. Read in a698// binding, which runs again as more arrives, at most every 100 ms.699exp fn progress(self ui: &Ui, pending: Pending) -> Option<Progress> {700    return ui.pending_progress(pending);701}702703/* --- Storage (decisions/F12.md, F12d) --- */704705// The app's store, named "app" under the app's name (`WindowConfig.app`,706// else its title), opened the first time it is asked for (std::storage).707// What a handler sets in it is written back once the event is handled,708// at most once a second, natively on a worker, and as the app ends; on709// the web each set reaches the page's localStorage at once. A Ui made on710// its own keeps it in memory.711exp fn store(self ui: &var Ui) -> &var KeptStore {712    return &var ui.kept_state().store;713}714715// A signal holding what the app's store keeps under the key, read by716// `read` as the signal is made, and written back by `write` each time it717// changes. `initial` is its value when nothing is saved under the key or718// `read` refuses what is.719//720// ```text721// const dark = ui.persisted(&"dark", false, (on) => Json::bool(on), (j) => j.as_bool());722// ```723exp fn persisted<T>(724    self ui: &var Ui,725    key: &[u8],726    initial: T,727    write: |=| (&T) -> Json,728    read: |=| (&Json) -> Option<T>729) -> Signal<T> {730    return ui.persist(&key, move initial, move write, move read);731}732733/* --- Dates (decisions/F11.md, F11d) --- */734735// A month as a grid of its days in weeks from `first_weekday` (the Ui's736// locale's unless set), the month and year above it in the locale's names737// between buttons going to the months before and after.738// One Tab stop: Left and Right move a day, Up and Down a week, Page Up739// and Page Down a month (with Shift a year), Home and End to the week's740// ends, the month following the focused day; Enter, Space or a click741// choose. The chosen day is filled in the primary color, today has a742// ring, days outside `earliest` and `latest` are muted and those743// `available` refuses struck through, neither chosen. To a screen744// reader a grid of days described by its month, announced as it changes.745exp type Calendar : Widget = struct {746    exp date: Option<Date> = ::None, // the chosen day747    exp earliest: Option<Date> = ::None,748    exp latest: Option<Date> = ::None,749    exp available: |=| (&Date) -> bool = (d) => true,750    exp first_weekday: Option<Weekday> = ::None, // the locale's751    exp accessible: String = String::empty(),752    exp on_change: |=| (&var Ui, Date) = (ui, d) {},753    exp enabled: bool = true,754    exp sizing: Sizing = Sizing {},755    // a DatePicker's: choosing closes the calendar's layer before calling756    // `on_change`757    pub popup: bool = false,758    pub state: CalendarState = CalendarState {}, // its own759};760761// A field showing the chosen day as `format` writes it (the Ui's762// locale's medium date by default, "15 Oct 2026" in en-GB) or the763// placeholder, and a chevron, opening a Calendar of the same options in a764// popup below it by a click, Space, Enter or Down; choosing a day or765// Escape closes it. To a screen reader a button whose value is the day766// shown, expanded while the calendar is open.767exp type DatePicker : Widget + Popup = struct {768    exp date: Option<Date> = ::None,769    exp earliest: Option<Date> = ::None,770    exp latest: Option<Date> = ::None,771    exp available: |=| (&Date) -> bool = (d) => true,772    exp first_weekday: Option<Weekday> = ::None, // the locale's773    exp placeholder: String = String::empty(),774    exp accessible: String = String::empty(),775    exp format: Option<|=| (&Date) -> String> = ::None, // the locale's776    exp on_change: |=| (&var Ui, Date) = (ui, d) {},777    // a "Clear" under its calendar, going back to no day (`on_clear`)778    exp clearable: bool = false,779    exp on_clear: |=| (&var Ui) = (ui) {},780    exp enabled: bool = true,781    exp error: String = String::empty(), // as a Select's782    exp required: bool = false,783    exp sizing: Sizing = Sizing {},784    pub open: Option<Layer> = ::None, // its own state: the calendar it opened785    pub closing: Option<Layer> = ::None, // to close, its options having changed786    pub laid: Option<*text::Layout> = ::None, // the day shown or the placeholder787    pub widest: f32 = 0.0,788    pub locale: Option<Locale> = ::None, // as last laid out789};790791// A Select of the times from `earliest` to `latest` by `step_minutes`,792// written on the Ui's locale's clock (`14:30`, `2:30 PM`), with its keys793// and type-ahead: typing "14" goes to 14:00. To a screen reader a combo794// box.795exp type TimePicker : Widget + Popup = struct {796    exp time: Option<TimeOfDay> = ::None,797    exp earliest: TimeOfDay = TimeOfDay { .hour = 0, .minute = 0 },798    exp latest: TimeOfDay = TimeOfDay { .hour = 23, .minute = 59 },799    exp step_minutes: u32 = 30,800    exp placeholder: String = String::empty(),801    exp accessible: String = String::empty(),802    exp on_change: |=| (&var Ui, TimeOfDay) = (ui, t) {},803    exp enabled: bool = true,804    exp error: String = String::empty(), // as a Select's805    exp required: bool = false,806    exp sizing: Sizing = Sizing {},807    // its own state: the Select it is, made from its options as it first808    // lays out, and the locale it wrote the times in809    pub select: Option<*var Select<TimeOfDay>> = ::None,810    pub locale: Option<Locale> = ::None,811};812813// The day calendars take as today: the system's, unless set.814exp fn today(self ui: &Ui) -> Date {815    if (ui.extension<Dates>() is ::Some |&d| && d.today is ::Some |day|) {816        return day;817    }818    return Date::today();819}820821// Sets the day calendars take as today, for tests and goldens; None822// gives the system's again.823exp fn set_today(self ui: &var Ui, day: Option<Date>) {824    ui.dates().today = day;825}826827// The locale calendars, pickers and the app's own dates follow: the one828// set, else the system's (question 14A). A binding reading it runs again829// when it changes (question 27B).830exp fn locale(self ui: &Ui) -> Locale {831    if (ui.extension<Dates>() is ::Some |&d|) {832        if (d.locale.get(&ui) is ::Some |locale|) {833            return locale;834        }835    } else {836        // read before the locale's signal is made, its making marks this837        ui.language_set.get(&ui);838    }839    return Locale::system();840}841842// The locale, the system's kept once read; no read recorded.843pub fn kept_locale(self ui: &var Ui) -> Locale {844    const signal = ui.dates().locale;845    const kept = &var signal.peek_var(&var ui);846    if (kept is ::None) {847        kept = ::Some(Locale::system());848    }849    if (kept is ::Some |locale|) {850        return locale;851    }852    return Locale::system();853}854855// Sets the app's locale, None giving the system's again; everything is856// laid out again in it, and the bindings that read it run again.857exp fn set_locale(self ui: &var Ui, locale: Option<Locale>) {858    ui.dates().locale.set(&var ui, locale);859    // and those that read it before its signal was made860    ui.changed_signal(ui.language_set.index);861    ui.invalidate_all();862}863864/* --- Forms (decisions/F13.md) --- */865866// A check a field states: what is wrong with its value, or None. It may867// read the Ui (its locale, today) and other fields, and a binding showing868// the field's error follows what it reads.869exp type Rule<T> = |=| (&Ui, &T) -> Option<String>;870871// Reads a typed field's text into its value, or says what is wrong.872exp type Parser<T> = |=| (&Ui, &[u8]) -> std_result::Result<T, String>;873874// What a field is.875exp type FieldOptions<T> = struct {876    exp label: String, // the label `labelled` shows, the summary's line, the trees'877    exp hint: String = String::empty(), // shown under the label, and said after the error878    // must hold something: checked before the rules, and said to screen879    // readers; an empty field not required is valid, gives no value and880    // runs no rules881    exp required: bool = false,882    // checked in order once it holds something, the first message found883    // being its error884    exp rules: &[Rule<T>] = &[],885};886887// What a field holds now.888exp type Verdict<T> = enum {889    Empty, // nothing typed but spaces, or nothing picked890    Valid: T,891    Invalid: String,892};893894// What a required field asks for while empty, which its message says.895exp type Wanted = enum {896    Text, // something typed897    Pick, // one of its choices898    Check, // a box checked899};900901// A form: its fields, whether a submit was tried, a failure of the902// whole. A copyable handle, valid until its owner goes, as signals are.903exp type Form = struct {904    pub fields: Signal<FormFields>,905    pub tried: Signal<bool>,906    pub failure: Signal<String>,907};908909// A field of a form, giving a T: a copyable handle, valid until the910// owner that made it goes.911exp type Field<T> = struct {912    exp form: Form,913    pub index: u32, // among the form's fields914};915916// A field in error, as `errors` gives them.917exp type FormError = struct {918    exp label: String,919    exp message: String,920    exp element: Element, // showing the field921};922923// The built-in rules, each with an English message in the Ui's locale924// that `said` replaces.925exp type Rules = struct {};926927// The built-in parsers, reading what the Ui's locale writes and ISO 8601.928exp type Parse = struct {};929930// What forms say, each a function of the Ui (its locale) and what the931// message needs; the defaults are the English ones.932exp type FormMessages = struct {933    exp required: |=| (&Ui, Wanted) -> String = english_required,934    exp length: |=| (&Ui, u64, u64, u64) -> String = english_length, // least, most, now935    exp email: |=| (&Ui) -> String = english_email,936    exp shape: |=| (&Ui, &[u8]) -> String = english_shape, // the example937    exp integer: |=| (&Ui) -> String = english_integer,938    exp number: |=| (&Ui) -> String = english_number,939    exp between: |=| (&Ui, f64, f64) -> String = english_between,940    exp date: |=| (&Ui, &Date) -> String = english_date, // an example day941    exp time: |=| (&Ui, &TimeOfDay) -> String = english_time,942    exp optional: |=| (&Ui) -> String = english_optional, // "(optional)"943    // "There is a problem" for 0, else "2 fields need attention"944    exp summary: |=| (&Ui, u64) -> String = english_summary,945};946947// A new form, belonging to what is being made as a signal does.948exp fn form(self ui: &var Ui) -> Form => ui.make_form();949950// A field of text kept as typed.951exp fn text(952    self form: &Form,953    ui: &var Ui,954    text: String,955    options: FieldOptions<String>956) -> Field<String> {957    return ui.add_text_field(&form, move text, move options);958}959960// A field of text read into a T by `parse`, whose message is the field's961// error when it fails.962exp fn parsed<T>(963    self form: &Form,964    ui: &var Ui,965    text: String,966    parse: Parser<T>,967    options: FieldOptions<T>968) -> Field<T> {969    return ui.add_field(&form, move text, Source<T>::Typed(move parse), Wanted::Text, move options);970}971972// A field of a value picked rather than typed: a Select's, a973// DatePicker's, a Checkbox's (a required `Field<bool>` must be true).974exp fn picked<T>(975    self form: &Form,976    ui: &var Ui,977    value: Option<T>,978    options: FieldOptions<T>979) -> Field<T> {980    const signal = ui.signal(move value);981    return ui.add_field(982        &form,983        String::empty(),984        Source<T>::Picked(signal),985        Checked<T>::wanted(),986        move options987    );988}989990// What a submit that passes runs, as a handler; set once the fields it991// reads are made.992exp fn on_submit(self form: &Form, ui: &var Ui, then: |=| (&var Ui)) {993    form.fields.peek_var(&var ui).then = ::Some(move then);994}995996// Checks every field shown (an element `text_field` or `input` made for997// it exists, in no hidden view). With some wrong, their errors show, the998// first in Tab order takes the focus, and screen readers are told at once999// ("2 fields need attention: Card number, Expiry."); else `on_submit`'s1000// function runs.1001exp fn submit(self form: &Form, ui: &var Ui) {1002    ui.submit_form(copy form);1003}10041005// Whether every field shown is valid; read in a binding, it follows them.1006exp fn valid(self form: &Form, ui: &Ui) -> bool => ui.form_errors(copy form).length() == 0;10071008// The fields shown in error, in Tab order, whether their errors show yet1009// or not.1010// Whether the form is still there: false once its owner went, as when a1011// server answers after its screen closed.1012exp fn alive(self form: &Form, ui: &Ui) -> bool => ui.signal_alive(1013    form.fields.index,1014    form.fields.generation1015);10161017exp fn errors(self form: &Form, ui: &Ui) -> Vector<FormError> => ui.form_errors(copy form);10181019// The whole form refused, as by a server: the message is `failure` until1020// the next submit, and screen readers say it at once.1021exp fn refuse(self form: &Form, ui: &var Ui, message: String) {1022    ui.announce(copy message, true);1023    form.failure.set(&var ui, move message);1024}10251026// What `refuse` said, empty when nothing was refused since the last1027// submit; read in a binding.1028exp fn failure(self form: &Form, ui: &Ui) -> &String => &form.failure.get(&ui);10291030// Nothing tried, left or refused any more, the texts and values kept:1031// after a submit that passed on a form that stays, its texts cleared.1032exp fn reset(self form: &Form, ui: &var Ui) {1033    ui.reset_form(copy form);1034}10351036// What the field holds now, its error shown or not; read in a binding,1037// it follows the field and what its rules read.1038exp fn verdict<T>(self field: &Field<T>, ui: &Ui) -> Verdict<T> => ui.field_verdict(copy field);10391040// The field's value: after a submit that passed. Faults unless valid.1041exp fn value<T>(self field: &Field<T>, ui: &Ui) -> T {1042    if (ui.field_verdict(copy field) is ::Valid |move value|) {1043        return move value;1044    }1045    panic "pkg::alloy::ui: the value of a field not valid";1046}10471048// The field's value while valid.1049exp fn try_value<T>(self field: &Field<T>, ui: &Ui) -> Option<T> {1050    if (ui.field_verdict(copy field) is ::Valid |move value|) {1051        return ::Some(move value);1052    }1053    return ::None;1054}10551056// The message to show now: empty while valid, and until the field was1057// left changed, the form submitted or a server refused it.1058exp fn error<T>(1059    self field: &Field<T>,1060    ui: &Ui1061) -> String => ui.shown_error(field.form, field.index);10621063// What is typed in the field.1064exp fn text<T>(self field: &Field<T>, ui: &Ui) -> &String => &field.slot(&ui).text.get(&ui);10651066// Puts the text in the field: a text field's `on_change`. A server's1067// refusal goes with it.1068exp fn edit<T>(self field: &Field<T>, ui: &var Ui, text: String) {1069    ui.edit_field(field.form, field.index, move text);1070}10711072// Picks the value, or none: a Select's or a DatePicker's `on_change`.1073// The error shows from then on.1074exp fn pick<T>(self field: &Field<T>, ui: &var Ui, value: Option<T>) {1075    ui.pick_field(copy field, move value);1076}10771078// The server's verdict on what the field was sent with: shown at once,1079// said to screen readers at once, the field focused when it is the first1080// in error; its next change takes it away.1081exp fn refuse<T>(self field: &Field<T>, ui: &var Ui, message: String) {1082    ui.refuse_field(field.form, field.index, move message);1083}10841085// A TextField showing the field: its text, its error once shown,1086// `required`, the label for screen readers unless `look` gives one, the1087// hint said after the error, `on_change` editing the field and, on one1088// line, Enter submitting the form; `look` gives the rest. A binding,1089// recorded as the field's element.1090exp fn text_field<T>(self ui: &var Ui, field: Field<T>, look: TextField) -> Element {1091    return ui.make_text_field(field.form, field.index, move look);1092}10931094// Another widget showing the field, its options bound as `bind` binds1095// them and the wiring the program's own (`selected`, `error`, `required`,1096// `on_change` picking); its element recorded as the field's.1097exp fn input<T, W: Widget>(self ui: &var Ui, field: Field<T>, options: |=| (&Ui) -> W) -> Element {1098    const element = ui.bind(move options);1099    ui.record_field(field.form, field.index, element);1100    return element;1101}11021103// The field's label above its element, "(optional)" after it when not1104// required, its hint under the label and its error under the element in1105// the theme's danger color, coming and going as it changes. A Checkbox1106// keeps its own label: only the hint and the error are added.1107exp fn labelled<T>(self ui: &var Ui, field: Field<T>, input: Element) -> Element {1108    return ui.make_labelled(field.form, field.index, input);1109}11101111// An element showing nothing until a submit fails: then a panel, "There1112// is a problem", the form's failure and a line for each field in error,1113// a plain button focusing it, following the errors until none is left.1114exp fn form_summary(self ui: &var Ui, form: Form) -> Element => ui.make_summary(form);11151116// What forms say from now on, in the program's own words.1117exp fn set_form_messages(self ui: &var Ui, messages: FormMessages) {1118    ui.forms_state().messages = ::Some(move messages);1119}11201121// The text, its spaces at either end aside, from `least` to `most`1122// characters long, counted as a person counts them (grapheme clusters):1123// "Use at least 10 characters (now 7)."1124exp fn Rules::length(least: u64, most: u64) -> Rule<String> => length_rule(least, most);11251126// A valid email address (WHATWG's, as browsers check one) whose domain has1127// a dot: "Enter an email address, like [email protected]."1128exp fn Rules::email() -> Rule<String> => email_rule();11291130// The text written in the shape, 9 standing for a digit, A for a letter1131// and * for either, anything else for itself, `like` an example for the1132// message: `Rules::shape(&"99/99", &"12/29")`, "Write it like 12/29."1133exp fn Rules::shape(shape: &[u8], like: &[u8]) -> Rule<String> => shape_rule(&shape, &like);11341135// The rule, its message replaced: `Rules::length(1, 40).said(&"Keep the1136// name to 40 characters.")`.1137exp fn said<T>(self rule: &Rule<T>, message: &[u8]) -> Rule<T> => said_rule(&rule, &message);11381139// The number from `least` to `most`: "Enter a number from 1 to 10."1140exp fn Rules::between<T: Number>(1141    least: T,1142    most: T1143) -> Rule<T> => between_rule(move least, move most);11441145// A whole number, in ASCII digits or another script's, its sign before1146// it: "Enter a whole number."1147exp fn Parse::integer() -> Parser<i64> => integer_parser();11481149// A number as the Ui's locale writes it, its groups or none (`1 234,5` in1150// French, `1,234.5` in English): "Enter a number, like 2.5."1151exp fn Parse::number() -> Parser<f64> => number_parser();11521153// A day in the Ui's locale's short date (`21/11/2026` in British English)1154// or ISO 8601: "Enter a date, like 21/11/2026." with today.1155exp fn Parse::date() -> Parser<Date> => date_parser();11561157// A time of day on either clock, `14:30` or `2:30 pm`: "Enter a time,1158// like 14:30." on the locale's own.1159exp fn Parse::time() -> Parser<TimeOfDay> => time_parser();11601161/* --- Screens (decisions/F11.md, F11c) --- */11621163// A stack of screens, by routes of the program's own type, the top one1164// shown: a copyable handle, valid until its owner goes.1165exp type Navigator<R> : Navigable = struct {1166    pub state: Signal<Routes<R>>,1167};11681169// How a navigator's routes show in the page's address, and are read1170// from it: on the web the address follows the top screen1171// (`index.html#/events/42`), and a page opened or reloaded at an address1172// starts at that screen; elsewhere they are not used.1173exp type Paths<R> = struct {1174    exp path: |=| (&R) -> String,1175    exp parse: |=| (&[u8]) -> Option<R>,1176};11771178// A navigator at its first screen.1179exp fn navigator<R>(self ui: &var Ui, first: R) -> Navigator<R> {1180    return ui.make_navigator(move first, ::None);1181}11821183// A navigator showing its routes in the page's address, starting at the1184// address's when it has one.1185exp fn navigator_with<R>(self ui: &var Ui, first: R, paths: Paths<R>) -> Navigator<R> {1186    return ui.make_navigator(move first, ::Some(move paths));1187}11881189// Shows the route's screen over the current one, which is kept hidden.1190exp fn push<R>(self nav: &Navigator<R>, ui: &var Ui, route: R) {1191    nav.state.update(&var ui, |move route| (routes: &var Routes<R>) {1192        routes.forward.clear();1193        routes.add(move route);1194    });1195}11961197// Frees the top screen, showing the one under it as it was left, once1198// `on_leaving` agrees; false at the first screen, which stays, or when it1199// does not. The header's Back, the mouse's, Alt+Left and the browser's1200// all come here.1201exp fn back<R>(self nav: &Navigator<R>, ui: &var Ui) -> bool {1202    if (nav.state.peek(&ui).routes.length() < 2 || !nav.may_leave(&var ui)) {1203        return false;1204    }1205    return nav.pop(&var ui);1206}12071208// Asks the function before going back from the top screen, with its1209// route: true lets it go; false keeps it, as for a form or a cart left1210// half done, the function asking the person (a dialog whose "Leave" then1211// calls `pop`).1212exp fn on_leaving<R>(self nav: &Navigator<R>, ui: &var Ui, asks: |=| (&var Ui, R) -> bool) {1213    nav.state.peek_var(&var ui).leaving = ::Some(move asks);1214}12151216// Frees the top screen as `back` does, without asking `on_leaving`.1217exp fn pop<R>(self nav: &Navigator<R>, ui: &var Ui) -> bool {1218    if (nav.state.peek(&ui).routes.length() < 2) {1219        return false;1220    }1221    nav.state.update(&var ui, (routes: &var Routes<R>) {1222        routes.serials.pop();1223        if (routes.routes.pop() is ::Some |move gone|) {1224            routes.forward.push(move gone);1225        }1226    });1227    return true;1228}12291230// Shows the route's screen in place of the top one, which is freed.1231exp fn replace<R>(self nav: &Navigator<R>, ui: &var Ui, route: R) {1232    nav.state.update(&var ui, |move route| (routes: &var Routes<R>) {1233        routes.serials.pop();1234        routes.routes.pop();1235        routes.add(move route);1236    });1237}12381239// Shows the route's screen alone, freeing every other.1240exp fn reset<R>(self nav: &Navigator<R>, ui: &var Ui, route: R) {1241    nav.state.update(&var ui, |move route| (routes: &var Routes<R>) {1242        routes.serials.clear();1243        routes.routes.clear();1244        routes.forward.clear();1245        routes.add(move route);1246    });1247}12481249// The top screen's route; in a binding, recorded so the binding runs1250// again when it changes.1251exp fn current<R>(self nav: &Navigator<R>, ui: &Ui) -> &R => &nav.state.get(&ui).routes.last();12521253// How many screens there are, 1 at the first; in a binding, recorded.1254exp fn depth<R>(self nav: &Navigator<R>, ui: &Ui) -> u64 => nav.state.get(&ui).routes.length();12551256// An element showing the navigator's top screen, made by `screen` from1257// its route when pushed and freed when taken off, on the theme's1258// background; the screens under it are kept hidden, as `switch` keeps1259// views. A screen shown gives the focus to its first element taking it,1260// or, shown again, to the one that had it. Back comes from `back`, the mouse's Back button, Alt+Left1261// (Command+[ on macOS) and on the web the browser's Back and Forward,1262// to the deepest navigator on screen that can go back.1263exp fn screens<R>(1264    self ui: &var Ui,1265    nav: Navigator<R>,1266    screen: |=| (&var Ui, &R) -> Element1267) -> Element {1268    const element = ui.element(ui.new_node(new Group {}, true));1269    const state = ui.signal(Vector<ScreenSlot>::empty());1270    nav.state.peek_var(&var ui).screens = ::Some(element);1271    const effect = ui.new_effect();1272    ui.set_effect(effect, ::Some(element.index), |move screen, nav, element, state| (ui: &var Ui) {1273        ui.run_screens(element, nav, state, &screen);1274    });1275    ui.run_effect(effect);1276    return element;1277}12781279// A number moving to its target over its motion, read in bindings as a1280// signal is: a binding reading it runs again each frame while it moves.1281// A copyable handle, valid until its owner goes.1282exp type Animated = struct {1283    pub course: Signal<Course>,1284};12851286// A number at the value, moving over the motion when given a target,1287// belonging to what is being made as a signal does.1288exp fn animated(self ui: &var Ui, value: f32, motion: Motion) -> Animated {1289    return ui.make_animated(value, motion);1290}12911292// Where the number is this frame; in a binding, recorded so the binding1293// runs again as it moves.1294exp fn get(self a: &Animated, ui: &Ui) -> f32 => a.course.get(&ui).value_at(ui.time.nanoseconds);12951296// Moves the number to the target from where it is, its speed kept;1297// under reduced motion, unless essential, it jumps there. (The design's1298// `to` is a keyword: decisions/F11.md, question 21.)1299exp fn set(self a: &Animated, ui: &var Ui, target: f32) {1300    ui.animate_to(a.course, target);1301}13021303// Puts the number at the value at once.1304exp fn jump(self a: &Animated, ui: &var Ui, value: f32) {1305    ui.jump_to(a.course, value);1306}13071308// Where the number is going, or is.1309exp fn target(self a: &Animated, ui: &Ui) -> f32 => a.course.get(&ui).target;