diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e1c67378..96bad9e34 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,6 +22,15 @@ if(WIN32) add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN) endif() +# Links run at most this many at once under Ninja. A debug-info link of a ladder test binary takes several GB, and a +# build parallel to the core count links as many binaries at once, which is what exhausts a 16 GB CI runner; compiles +# keep the full parallelism. +set(MORPH_LINK_JOBS 2 CACHE STRING "Links Ninja runs at once (0: no limit)") +if(CMAKE_GENERATOR MATCHES "Ninja" AND MORPH_LINK_JOBS GREATER 0) + set_property(GLOBAL APPEND PROPERTY JOB_POOLS morph_link=${MORPH_LINK_JOBS}) + set(CMAKE_JOB_POOL_LINK morph_link) +endif() + option(MORPH_BUILD_TESTS "Build tests" ON) option(MORPH_BUILD_EXAMPLES "Build examples" ON) option(MORPH_BUILD_BANK_EXAMPLE "Build the SQLite/Lightweight bank example (heavy deps)" OFF) diff --git a/docs/KEEPING-SCREENS-CURRENT.md b/docs/KEEPING-SCREENS-CURRENT.md index 11efbb05a..e6c7cd129 100644 --- a/docs/KEEPING-SCREENS-CURRENT.md +++ b/docs/KEEPING-SCREENS-CURRENT.md @@ -117,6 +117,54 @@ Rules of thumb: - **`updates` and `changes` together mean the whole type**: the change is reported without keys. - Declare each action's effects in **one** place. A header included by several translation units is still one declaration; a second, different declaration for the same action is refused. +- **A write that lands in another module's record** is declared by the code that composes the two modules, with + `BRIDGE_ADD_EFFECTS` (below). The action's own module cannot name that record, and a second + `BRIDGE_REGISTER_EFFECTS` is refused. + +### Effects the composing code adds + +An action sometimes changes a record of a module it must not include: a billing action that posts a ledger entry in +its own transaction, or an organisation action that changes which samples a lab screen lists. The module cannot write +that effect, and the application that links both can. + +```cpp +// app/src/ledger_wiring.cpp, which includes both modules +BRIDGE_ADD_EFFECTS(lims::PostInvoice, ::morph::effects::changes) +``` + +- The addition is **unioned** with the action's own `BRIDGE_REGISTER_EFFECTS`; it can never remove an effect, and + `none` is not accepted in it. An action with no declaration of its own has the additions alone. +- Two different `BRIDGE_REGISTER_EFFECTS` for one action are still refused. An addition is the only second source. +- It takes any of `updates`, `changes` and `changesInstance`, and `R` must be a registered record. An addition + for an action nobody registered, or for an unregistered record, is refused when the registries are first read, with + the other problems, and never ignored. +- It expands to nothing under `MORPH_CLIENT_ONLY`. +- Put it in a translation unit that is always linked into the server, such as the one that wires the modules together. + A static library's object that nothing references is dropped, and its addition with it. + +### Facts that change with time alone + +A list filtered by a deadline changes when the clock passes the deadline, though no action runs. The model says when, +and the server tells the watchers at that instant. + +```cpp +// A registered read beside the others: the next instant, after now, at which a requisition's scope moves. +struct NextRequisitionDeadline {}; +std::optional ProcurementModel::execute(NextRequisitionDeadline const&); +BRIDGE_REGISTER_ACTION(lims::ProcurementModel, lims::NextRequisitionDeadline, "NextRequisitionDeadline") +BRIDGE_REGISTER_CHANGES_AT(lims::ProcurementModel, lims::NextRequisitionDeadline, lims::RequisitionView) +``` + +- The action reports a fact and nothing else. It arms no timer and posts no work; the server owns the clock. +- It must return `std::optional`: an instant strictly after the model's own now, or `nullopt` + when nothing is pending. It declares no effects, takes no fields, and reads from the same clock the server uses + (`ServerConfig::clock`). +- At that instant the server marks every listed record, and every record derived from it, as changed, as if an + action declaring `changes` had run, and then asks for the following instant. It asks again after any action + whose effects name one of the records, since the next instant may have moved. +- A reporter that is not a registered action, that declares effects, or that names an unregistered record is + refused with the other registry problems. +- In a local-mode client there is no server, so nothing is told at the instant: use `refreshEvery` there. ## Records @@ -216,7 +264,8 @@ Work through it every time you add an action or change what one does. A coding a every action's effects. 5. **Would a key alone leak something to another user?** Add `privateKeys` to the record. 6. **Write `BRIDGE_REGISTER_EFFECTS` (``) directly under the action's - `BRIDGE_REGISTER_ACTION`.** + `BRIDGE_REGISTER_ACTION`.** A record the action's module cannot include is added by the composing code with + `BRIDGE_ADD_EFFECTS`. 7. **Remove any refresh the screens did by hand**: an `onSuccess` refetch that the effects now cover. 8. **Build and run the screen tests.** A bad declaration fails when the server starts. Check that the bundle loads with no warnings ([Testing](#testing)). diff --git a/docs/spec/core/backend.md b/docs/spec/core/backend.md index 2cf4f5749..6ff9370a8 100644 --- a/docs/spec/core/backend.md +++ b/docs/spec/core/backend.md @@ -783,6 +783,8 @@ changes it. | `payloadCompleteness` | `Lenient` | See [`PayloadCompleteness`](#payloadcompleteness--enforcing-the-action-evolution-policy). | | `services` | empty | `IEnvelopeService` extensions; see [Envelope services](#envelope-services). A null entry makes the constructor throw `std::invalid_argument`. | | `coalesceWindow` | `50 ms` | How long a connection's changes are merged before one `changes` event is sent; see [Coalescing](#coalescing). | +| `clock` | the system clock | The server's "now", read by [time-derived fan-out](#time-derived-fan-out). A test supplies one it advances by hand. | +| `clockRecheck` | `1 s` | The longest the server sleeps before reading `clock` again; see [time-derived fan-out](#time-derived-fan-out). Not positive is refused by the constructor. | ```cpp using LogProvider = std::function( @@ -1324,6 +1326,32 @@ through `dispatchExecute`. second plus one per 256 keys (or topics) the connection is sent. A burst of one hundred writes to one type reaches each watching connection as one event, so one refetch per showing query. +- **Time-derived fan-out.** Some records change + with no action behind them: an approval's scope moves from a site to its company at a + deadline. A model reports such a fact through an action registered with + `BRIDGE_REGISTER_CHANGES_AT` (see [registry.md, "Effects"](registry.md#effects)), and the + server, which owns the clock, does the rest through the same `fanOut` an action's effects + take: + - *Asking.* The first envelope the server handles, and every later fan-out that names one of a + reporter's records, schedules one ask for that reporter: a fresh instance of its model is made + through the `ModelRegistryFactory`, the action is dispatched on it with an empty payload on + a model strand (never the server strand, whose tasks must not block), and the instance is + dropped. An ask in flight is not repeated; a change that arrives during it asks once more + when it ends, because the answer may predate the change. An ask that throws is logged and + leaves the reporter with no instant until a later change asks again. + - *Waiting.* The server keeps the instant it was told and sleeps on its strand timer for + `min(instant - clock(), clockRecheck)`. It never trusts the elapsed sleep: after each wake it + reads `clock` again, because a system clock can be set and an injected one is advanced by a + test without any sleep. The instant has come when `clock() >= instant`. + - *Firing.* The server fans out a whole-type `changes` for each listed record, and every + record derived from it, as `fanOut(changes, 0, "")`: no caller, so no connection is exempt + and a `privateKeys` record reaches every watcher without its keys. Re-authorisation and + coalescing apply as to any fan-out. It then asks again for the following instant. + - *What the model must do.* Report an instant strictly after its own now, from the same + clock the server is configured with, so a reported instant that has come is never reported + again. The model is not told when it fires, and nothing in it is scheduled. + - A record changed by time alone and by an action declares the action's effects as usual; + the two paths meet in `fanOut`. - **The registries are read at construction.** Every `RemoteServer` constructor reads the record and effects registries once, so a process whose declarations are invalid fails with `EffectsRegistrationError` when the server @@ -2471,6 +2499,8 @@ server: each call is a loop task, so the loop serialises them. | `payloadCompleteness` | `PayloadCompleteness`; default `Lenient`. | | `services` | `std::vector>`: extensions consulted, in order, for a kind the server does not answer itself; a null entry throws `std::invalid_argument`. See [Envelope services](#envelope-services). | | `coalesceWindow` | `std::chrono::milliseconds`, default `50 ms`: how long a connection's changes are merged before one `changes` event is sent; zero sends each fan-out at once; negative throws `std::invalid_argument`. See [Coalescing](#coalescing). | +| `clock` | `std::function`, default empty (the system clock): the server's "now" for [time-derived fan-out](#time-derived-fan-out). | +| `clockRecheck` | `std::chrono::milliseconds`, default `1 s`: the longest sleep before `clock` is read again; not positive throws `std::invalid_argument`. | ### `SimulatedRemoteBackend` diff --git a/docs/spec/core/registry.md b/docs/spec/core/registry.md index a39694a5a..420e5b1c1 100644 --- a/docs/spec/core/registry.md +++ b/docs/spec/core/registry.md @@ -1773,6 +1773,30 @@ for every action, which records its result holds. two such halves). It belongs beside the action's registration, in a header or a source file: each translation unit that sees it registers the same declaration, which is one. +- **Additions from the composing code.** `BRIDGE_ADD_EFFECTS(A, effects...)` + stores `{Kind, std::type_index?}` per effect under the action's id in + `detail::mutableAddedEffectsRegistry()`, apart from the base declarations. + It is for code that links two modules and so can name a record the action's + own module cannot: a write that crosses a module boundary is declared by the + composer, not by either side. The effects are `updates`, `changes` and + `changesInstance`; `none` is refused at compile time, since an addition adds + and `none` adds nothing. Repeating an addition, in any order and from any + number of translation units, is a no-op, and additions from several + composers are unioned. Like `BRIDGE_REGISTER_EFFECTS`, it asserts the + registration latch, defines no specialisation and compiles out under + `MORPH_CLIENT_ONLY`. +- **Time-derived facts.** `BRIDGE_REGISTER_CHANGES_AT(Model, A, records...)` registers action `A` + of `Model` as the reporter of an instant: the next moment at which the listed records change by + the passage of time alone, with no action behind it (an approval that escalates at a deadline). + `A`'s result must be `std::optional`, checked at compile time; the + instant is strictly after the model's own now, and `nullopt` means nothing is pending. The + registrar stores `{actionId, modelId, record types}` in + `detail::mutableChangeTimesRegistry()` beside the effects, lazily matched like them, and + compiles out under `MORPH_CLIENT_ONLY`. The model only reports a fact: it arms no timer and + posts no work, and does not know the server exists. Naming no record is a compile error. + Resolution refuses, with the other problems, a reporter that is no registered action, one + that also declares effects (it reads, and the server runs it unprompted), and one naming a + record that is not registered. `Resolved::changeTimes` lists the reporters and `effects::changeTimesOf()` reads them. - **Idempotent per action.** Each action id keeps its distinct declarations; one equal to a stored one, in any order, is not added again. Two distinct declarations are a conflict, recorded rather than thrown so the registrar @@ -1786,6 +1810,14 @@ for every action, which records its result holds. latch in a debug build. Resolution cannot run at the latch: `closeRegistrationPhase()` is `noexcept`, and a release build closes it only when the application asks. +- **The union.** An action's effects are its base declaration unioned with + its additions. An addition never removes an effect: a base `none` is dropped + when an addition exists, because the action then changes something, but no + base `updates`, `changes` or `changesInstance` is ever lost. An action with + additions and no base declaration has the additions alone. Two *different + base* declarations are still a conflict; additions never make or hide one. + Every addition passes the same checks as a base effect (see Validation), so + an `updates` addition needs a keyed `R` that the action's result holds. - **Matching.** For each action, its result slots are taken in path order, and a slot is kept when its type is a registered record and no kept slot's path contains it (a path contains itself and every path below it; `""` contains @@ -1799,6 +1831,9 @@ for every action, which records its result holds. - an action with two different effects declarations. A declaration is a set, so a repeated effect counts once and order does not matter; - `none` together with any other effect in one declaration; + - an addition for an action id that no action registered: it would declare + effects for nothing, so a misspelt or removed action is refused rather than + ignored. The record of an addition is checked as a base effect's is; - `updates` or `changes` where `R` is not a registered record; - `updates` where `R` has no key, or where the action's `recordsOf` does not name `R`; @@ -1830,6 +1865,6 @@ for every action, which records its result holds. `changesInstance` and `none`. `recordNamed(name)` points into the resolved copy of the record registry, valid for the life of the process. - **Testing.** `detail::resolveForTesting(records, slots, effects, - slotConflicts)` runs the same resolution over registries a test builds, so an + slotConflicts, additions)` runs the same resolution over registries a test builds, so an invalid configuration can be exercised without making the process registry invalid for the rest of the suite. diff --git a/docs/spec/forms/engine.md b/docs/spec/forms/engine.md index 12fc9304c..d8a8cc4e7 100644 --- a/docs/spec/forms/engine.md +++ b/docs/spec/forms/engine.md @@ -190,11 +190,24 @@ it. A view mounted on it is destroyed first. engagement, and its members' and rows') as `prefill`, `reset` or `assign` last left it, and as it was built. `refill(bodyJson)` loads like `prefill`, except that a top-level field whose snapshot differs (the user changed it since) keeps what was entered. It is for a later value of the record already being edited; `prefill` is for - another record. A successful submission of an explicit form ends the edit of every field still holding what it - sent, so the record's later values reach those; a field changed while the submission was in flight, or one whose - submission failed, stays an edit. An automatic form's submission does not end an edit: it goes out while the person - may still be typing, and loading the record's form of a number (`1.000` for a typed `1`) would change the text - under their cursor. + another record. A successful submission, automatic or explicit, ends the edit of every field still holding what it + sent, so the record's later values reach those; a field changed after the submission was sent, or one whose + submission failed, stays an edit. An automatic form submits while the person may still be typing, which two rules + make safe. First, the record's form of the value just sent does not load: a saved scalar takes the record's value + only when it would encode differently from the draft, so a typed `1` stays `1` when the record answers `1.000` + (the comparison is the encoded body entry, not the text). Second, the snapshot a success is judged against is the + one taken when that submission went out, so text typed while it was in flight is never mistaken for it, even when a + following submission starts in the same turn as the reply. The engine has no focus, so "still typing" is "changed + since the last send", which is exactly what the snapshots record. An automatic form's object and collection do not + end their edit on a save: their members and rows cannot be compared with the record without rebuilding them under + the cursor, so they own what was entered until the form is rebuilt or loaded with `prefill`. A member the record leaves out loads blank into a field that is no longer an edit, as it does in `prefill`. +- **Formatting follows the screen.** `setFormat(locale, datePattern, dateTimePattern)` on a `FormSession` (and so on a + `WizardSession`'s steps and a `CollectionSession`'s editor) replaces the number locale and the date patterns of a + built form. The number locale is read by every field's encoding, so each re-encodes its draft at once and the body + follows; the drafts keep the text as typed, so `1,5` typed under a comma locale reads as an error once the locale + switches to a point. The date inputs' `pattern` is read tracked and follows. The screen's interpreter keeps an effect per + form, collection and wizard that applies the session's current formatting, and holds the facts it applied, because the + number locale is a set of views into them. The display zone and the translations are read once, at build. - **Choice options** are a `reactive::Query` per Choice, keyed on the options request: `{}` for an independent Choice, `{"parent": , …}` once every parent encodes, idle while one does not. A parent change refetches, and a reply for a superseded request is dropped. A selection the answered options no @@ -257,7 +270,7 @@ before it. | Quantity | `TextInput` showing its unit, as a Decimal's (one unit); with alternatives, a `TextInput` with no unit and a unit `Select` beside it; switching converts the draft exactly | | Boolean | `Checkbox` labelled with the field | | Enum, Choice | `Select` (dropdown, or radio for `x-widget: radio`) keyed by each option's JSON literal; a Choice adds a `Busy` while its options load | -| DateTime, EpochDateTime; Date, EpochDate | `DateTimeInput` (date-time in the display zone; date); the input shows and reads `FormSessionOptions::datePattern` or `dateTimePattern` while they are set (`ScreenCore::engineOptions` fills them from the session's formatting), and the draft text stays ISO | +| DateTime, EpochDateTime; Date, EpochDate | `DateTimeInput` (date-time in the display zone; date); the input shows and reads `FormSessionOptions::datePattern` or `dateTimePattern` while they are set (`ScreenCore::engineOptions` fills them from the session's formatting), and the draft text stays ISO; the input follows `FormSession::setFormat`, which the screen calls whenever its formatting changes | | Slider | `Slider` over `x-min`..`x-max` by `x-step` | | Array | `TextInput`, comma-separated | | Object | `Panel` of its members' cells | diff --git a/docs/spec/qt_quick/backend.md b/docs/spec/qt_quick/backend.md index 81c1383fd..c2d129b66 100644 --- a/docs/spec/qt_quick/backend.md +++ b/docs/spec/qt_quick/backend.md @@ -173,7 +173,7 @@ throws is logged and goes no further. Only the user's own actions fire: Qt Quick | Splitter | `MorphSplitter` | a `SplitView` (a horizontal one without matching sizes places each pane by its own width in `applyOwn`: fixed in units, percent as a share of the split view's width, the rest by weight with content as weight 1, the heaviest taking `fillWidth`; every `MorphWidget` binds `SplitView.minimumWidth`/`maximumWidth` and the heights from its bounds, so a drag stops there; the shares are applied again as the width changes until the user drags, and when a pane's sizing changes; the splitter's natural width reads no width from a pane that is fixed (its units), a share or a stretch while its container sizes it, since such a pane's implicit width can follow the width it is given and the natural width would grow on every pass) whose handles are made from its `handle` part (`MorphSplitterHandle`); the splitter sets each handle's `axis` and `scheme`, and leaves a handle's implicit extent along the axis between two panes. The stock handle is 6 px thick, in `scheme.border` and `scheme.controlBorder` while hovered or pressed, with a `grip` centred on it: 2 px across the axis, `min(28, length / 3)` along it, radius 1, in `scheme.neutralDot` | the panes' sizes once a drag ends | | Slot | `MorphSlot` | its children inset by `contentInset` (0 unless a tabs node gives its page the page padding), packed at the top unless one stretches vertically. A scrollable slot scrolls only while its content does not fit, in a `Flickable` with `MorphScrollBar`s made from its `bar` part, and the focused item is kept in view on both axes (`reveal`). With `inset` for `contentInset`, `needX` the column's `Layout.minimumWidth` plus `2 * inset` and `needY` its implicit height plus `2 * inset`: `overY` is `stretchFloor + 2 * inset > height` while a child stretches down and `needY > height + 0.5` otherwise, `overX` is `needX > width + 2`, and the slot scrolls (`clip`, `flick.interactive`) while either holds. `flickableDirection` follows the axes that overflow; `flick.contentWidth` is `needX` and `contentHeight` the content's height plus the padding on an axis that overflows, the viewport's otherwise; the column lies at `(inset, inset)`, `needX` or the viewport's width less `2 * inset` wide, and is `max(flick.height - 2 * inset, stretchFloor)` tall while a child stretches down. The vertical bar shows while `overY`, the horizontal one (always on) while `overX`. The column's `childBleedInset` is `contentInset`, so the page's bleeding children reach the slot's own edges. A slot reports content wider than itself, scrolling or not (`page`) | wheel, drag | | Tabs | `MorphTabs` | with `inset`, the `TabBar` and More start `Theme.spaceOf(inset)` in and each page slot is padded by it on every side, inside its own scroll (`pages` has no margins; `MorphTabs` binds each page's `contentInset` to `pageInsetPx` as the page is added), or by `Theme.spaceOf(pageInset)` once `pageInset` is written; the mount lays each page out `stretch` both ways, so it fills the area under the strip and a short page sits directly under the strip's rule instead of centred; with `stripSurface`, the strip row is drawn on the surface's background across the whole width (`stripSurface`), under the rule. A `TabBar` over the page slots, one `TabButton` per caption (the chosen tab's label in the text colour over a 2 px accent underline, the others' muted) (the `Repeater`'s model is the caption count, so a relabel keeps the buttons, the highlight and the focus), the chosen tab kept wholly in view (`select` calls the bar's `positionViewAtIndex(index, ListView.Contain)` once the bar is laid out, and again when its width changes, so a tab chosen before the first layout is placed too), `Theme.spaceOf(3)` above them (none while the strip is inset: the pages' own inset is the gap), each `TabButton` at least `Theme.targetHeight` tall, the control height, and 44 px while the window is compact; `barShown` false hides the bar and gives its height to the pages, and its `focusTarget` is then the pages, so a hidden bar never holds the keyboard focus. When the tab buttons together are wider than the row, only the leading tabs that fit beside a `More` button stay in the bar, as many as fit (each tab is `Theme.tabInsetX` in from its label on both sides, and `More` too: the theme's `tabs.paddingX`, or `Theme.spaceOf(3)` while it is 0. Each tab after the first also draws `Theme.tabGap` (`tabs.gap`) in from its leading edge, as a `leftInset` of its own button that its padding includes, so the gap is inside the next tab's hit area, a hidden tab at width 0 takes none, and the active underline spans the label and its padding without the gap; `More` takes the gap while a tab is shown before it, and `moreWidthFor(label, shown)` adds it only for `shown > 0`, so More as the first item stands at the padding. The underline is named `tabUnderline`. More's menu opens at the button's left, which is the gap before its label), and `More` follows the last shown tab with the 1 px rule under the tabs running on past it; a tab past the fit is `visible: false` and has no width, so it leaves the bar, the focus chain and the accessibility tree, while `bar.count` stays the tab count and `bar.currentIndex` the chosen tab's index. `More` (`more`) is a sibling of the bar, an `Accessible.Button` named by its shown label (`moreLabel` and `▾`, or, while the chosen tab is one of the menu's, that tab's label with the active underline), and is measured at its widest label so what fits never depends on the label it shows. It opens a `MorphPopupBackground` menu of the hidden tabs (Enter, Space or Down on it, or a click); choosing an entry sends the tab's own index as a click on its button does. Right on the last shown tab focuses `More`, and Left on `More` goes back. The fit is recomputed on every width change | the tab clicked, or a menu entry | -| Dialog | `MorphDialog` | a modal `Popup`, centred, drawn as the theme's `card` surface (`color.surface`, its border, `radius.card` and a shadow, `dialogShadow`, from `elevation.dialog`, which is `elevation.card` while the theme sets none; a `MorphShadow`, which draws the outline offset and grown by the token, blurred as a Gaussian of deviation `blur / 2` in 16 nested rounded rectangles whose alphas composite to the falloff, the strength reached after the k-th layer growing as the square of its position so the outermost layers add less than one 8-bit level and the shadow ends in no visible step, so it needs no offscreen texture; only a dialog and a drawer draw one) with `Theme.spaceOf(4)` padding, whatever surface encloses the node: its content and title draw with the card's scheme; its `footer` item, under the content, holds the footer (a `MorphFooter`: its children in a row against the right edge, `Theme.actionSpacing` apart), shown only while it holds something. With `sheet` the popup is placed in the overlay's coordinates and fills it, its footer (`MorphFooter.stretching`) filling the sheet's width with its actions sharing it equally, so a lone action spans the footer, with no margin and radius 0 and no shadow; a head row holds a flat button (`objectName` `sheetDismiss`, its text and accessible name `dismissLabel`) and the title, and the content scrolls between the head and the footer. The sheet's head draws the title (`sheetTitle`, plain characters, never markup) centred on the sheet, a trailing item as wide as the dismiss button balancing the row, and a head rule always shows under the head (under the description where there is one). A restyle declares `sheet` and `dismissLabel`, or it stays a centred popup with no dismiss control. The title is drawn in `Theme.headingFont` (the heading size at the strong weight), a sheet's too. While the footer holds an action, a 1 px `Theme.dialogRuleShown` rule (`footerRule`; `color.dialogRule`, else the card scheme's divider) sits above it, outside the `ScrollView` and in its height cap. The head's and the footer's rules span the overlay, edge to edge: each takes negative layout margins of the popup's side padding, so it reaches the border. A `description` is a muted, wrapping label under the title (given as runs, `descriptionRuns`, it draws their markup), then a 1 px `Theme.dialogRuleShown` rule across the overlay (`headRule`), both outside the `ScrollView`, whose height cap subtracts them and their spacing. Each rule stands `Theme.spaceOf(3)` off the item above it and the item below it (its layout margins are that step less the column's spacing), and while the footer shows the popup's bottom padding is `Theme.spaceOf(3)`, so the actions sit that far from the edge. A `Popup` takes no `Accessible` attached property, so the content column is the overlay's accessible node (`accessibleItem`): `Accessible.Dialog`, named by the title or the node's `a11y.name`, described by the description | Escape or a press outside, as a dismissal; a sheet closes only on Escape or its dismiss button, either a dismissal | +| Dialog | `MorphDialog` | a modal `Popup`, centred, drawn as the theme's `card` surface (`color.surface`, its border, `radius.card` and a shadow, `dialogShadow`, from `elevation.dialog`, which is `elevation.card` while the theme sets none; a `MorphShadow`, which draws the outline offset and grown by the token, blurred as a Gaussian of deviation `blur / 2` in 16 nested rounded rectangles whose alphas composite to the falloff, the strength reached after the k-th layer growing as the square of its position so the outermost layers add less than one 8-bit level and the shadow ends in no visible step, so it needs no offscreen texture; only a dialog and a drawer draw one) with `Theme.spaceOf(4)` padding, whatever surface encloses the node: its content and title draw with the card's scheme; its `footer` item, under the content, holds the footer (a `MorphFooter`: its children in a row against the right edge, `Theme.actionSpacing` apart), shown only while it holds something. With `sheet` the popup is placed in the overlay's coordinates and fills it, its footer (`MorphFooter.stretching`) filling the sheet's width with its actions sharing it equally, so a lone action spans the footer, with no margin and radius 0 and no shadow; a head row holds a flat button (`objectName` `sheetDismiss`, its text and accessible name `dismissLabel`) and the title, and the content scrolls between the head and the footer. The sheet's head draws the title (`sheetTitle`, plain characters, never markup) centred on the sheet, a trailing item as wide as the dismiss button balancing the row, and a head rule always shows under the head (under the description where there is one). A restyle declares `sheet`, `dismissLabel`, `headNote`, `footerNote` and `closeButton`, or it stays a centred popup with no dismiss control. Outside a sheet the title sits in a row (`titleRow`) with the head note (`headNote`, muted, trailing) and, with `closeButton`, a flat dismiss button (`headClose`, labelled `dismissLabel`) after it; a drawer draws the same row. The footer note (`footerNote`, muted) leads in the `MorphFooter`, above the actions while the footer stretches, and a note alone makes the footer show. The title is drawn in `Theme.headingFont` (the heading size at the strong weight), a sheet's too. While the footer holds an action, a 1 px `Theme.dialogRuleShown` rule (`footerRule`; `color.dialogRule`, else the card scheme's divider) sits above it, outside the `ScrollView` and in its height cap. The head's and the footer's rules span the overlay, edge to edge: each takes negative layout margins of the popup's side padding, so it reaches the border. A `description` is a muted, wrapping label under the title (given as runs, `descriptionRuns`, it draws their markup), then a 1 px `Theme.dialogRuleShown` rule across the overlay (`headRule`), both outside the `ScrollView`, whose height cap subtracts them and their spacing. Each rule stands `Theme.spaceOf(3)` off the item above it and the item below it (its layout margins are that step less the column's spacing), and while the footer shows the popup's bottom padding is `Theme.spaceOf(3)`, so the actions sit that far from the edge. A `Popup` takes no `Accessible` attached property, so the content column is the overlay's accessible node (`accessibleItem`): `Accessible.Dialog`, named by the title or the node's `a11y.name`, described by the description | Escape or a press outside, as a dismissal; a sheet closes only on Escape or its dismiss button, either a dismissal | | Drawer | `MorphDrawer` | a modal `Drawer` on the start or end edge, drawn as a dialog is but square against its edge, with a dialog's title size, shadow and divider-coloured head and footer rules spanning the drawer and standing off their neighbours as a dialog's do; it cannot be swiped open; its `footer` as a dialog's, at the bottom | as a dialog | | Toast | `MorphToast` | a non-modal, non-dimming `Popup` near a corner of `Overlay.overlay`, `closePolicy: Popup.NoAutoClose`; `show(text, tone)` is a QML function call, not a property write, so a repeated call with the same text and tone still restarts the dismiss `Timer` and reopens the popup if it closed | — | | Popover | `MorphPopover` | a non-modal, non-dimming, focus-less `Popup` whose `parent` is the container the popover is mounted in, placed at the container's leading edge under its box (`x: 0`, `y: parent.height`), as wide as `widthUnits` units or the container; it takes no room in the container's layout; `closePolicy` is a press outside the container, which reports a dismissal (Escape is the focused field's, since a focus-less popup receives no keys); `show(open)` opens and closes it without one; drawn as the theme's card | — | diff --git a/docs/spec/tui/frontend.md b/docs/spec/tui/frontend.md index b6e4b3f0e..c83f14891 100644 --- a/docs/spec/tui/frontend.md +++ b/docs/spec/tui/frontend.md @@ -90,7 +90,7 @@ width: the terminal does not wrap it, so it has no unbreakable segment to keep w | Panel | a box with a title; a collapsible one folds to its title line | Enter, Space, click on the title | | Scroll | a viewport that follows the focus | arrows, PageUp/PageDown, Home/End, wheel | | Tabs | with an inset, the tabs start the step's columns in (step 4: 2 columns) and the pages are padded by its rows and columns, or by a page inset's when the node gives one; the strip's surface draws nothing new, as `bar` is not inverted. A one-row bar over the page slots, with no blank row under it (a terminal row costs more than the separation earns); a bar narrower than its labels draws whole labels from a first visible one, which painting moves so the highlighted label fits, with `‹` at the start and `›` at the end while labels are cut there; a hidden bar gives its row to the pages and takes no focus; the theme's `tabs.paddingX` and `tabs.gap` are not read, since a label is separated by cells already; `moreLabel` is stored and not drawn, since the markers already reach every tab | Left, Right, click on a label; a click on `‹` or `›` selects the previous or next tab | -| Dialog | a centred box over everything; a description given as runs draws them on the description's row, as a text draws runs; its footer is the box's bottom row, its children against the right edge, one cell apart, and stays last when the content mounts again. As a sheet the box fills the viewport, its top row draws `[dismissLabel]` before the title, and its footer takes the box's last rows under content that fills the rest | Esc dismisses; a press on a sheet's `[dismissLabel]` dismisses as Esc does | +| Dialog | a centred box over everything; a description given as runs draws them on the description's row, as a text draws runs; its footer is the box's bottom row, its children against the right edge, one cell apart, and stays last when the content mounts again. As a sheet the box fills the viewport, its top row draws `[dismissLabel]` before the title, and its footer takes the box's last rows under content that fills the rest | Esc dismisses; a press on a sheet's `[dismissLabel]` dismisses as Esc does. A head note is drawn muted on the title's row against its right end, followed by `[dismissLabel]` while the close control is on and the box is not a sheet; a press on it dismisses as Esc does. A footer note takes a row of its own at the bottom of the box, muted | | Drawer | a box against its side, the screen's height; its footer as a dialog's | Esc dismisses | | Busy | a spinner and its label while active | — | | Table | a header (set apart by its role: the terminal reads no table colour, so `color.table.header` and `color.table.headerRule` are not read and no rule is drawn under it) and keyed rows, `*` on selected rows, `>` on the cursor; with a select column a five-cell gutter, `[x]` or `[ ]` per row in place of the `*`, under a header box `[x]`, `[-]` or `[ ]` — a click on a row's box toggles the row as Ctrl+click does, and on the header box is Ctrl+A; a toned row's cells draw in the tone's style, keeping any inverse; the layout solver never squeezes a column below its header's width (a fixed column below its own width), and the columns past the table's edge are cut; a stretch column starts from its content and gives in the contract's four steps (`layout::planColumns`), in cells, with a 2-cell gutter and 1-cell gaps, a floor of `min(header, 4)` for a column that may `shrink`; the least width of a text cell in a wrapping column is its widest word and that of any other cell its natural width, so a text inside a container cell is never narrowed; a row's cells keep their own height and sit at its top, centre (rounded down) or bottom by their column's `valign`; a text cell cut at its column's width draws an ellipsis in its last cell, on each of its lines (spans too), because the terminal cannot wrap (a mono text outside a table, too); in a column that does not wrap (`wrap: false`) the spans share one line; a text, a badge, a check box or a push button is drawn at its natural width at its column's start, centre or end by the column's `align`, and the header's label with it; a text input keeps its text at the start, since `core::tui::InputField` has no alignment; the sorted column's label is followed by ` ▲` or ` ▼`, and a sortable column's header keeps room for it; a heading row is one cell across every column and their gaps, with nothing in its gutter, and widens no column; a hidden cell widens no column either; a spanning cell (`setRowSpans`) is drawn once, in its column over the lines of the rows it covers, placed down them by the column's `valign` (the centre rounded down), and every line of the span, covered rows' included, is drawn in the origin row's style (tone, selection, inverse), the rest of the covered rows in their own; `TableImpl` places a spanning cell itself, over the union of the covered rows' areas: a view is clipped to its parent's area, so the table lifts the cell's view out of its row into its own while the span holds (its tone, still its origin row's), and returns it when the span goes; the lifted cell is left out of the origin row's natural height and placement, and the table works out which cells span and which are covered from the rows' order at every frame, also before the layout that sizes it (a table holding spans is planned when the screen is fitted), so the frame that lifts a cell is already laid out with the shorter row; a table with no span does no such work; the covered cells widen no column, and when the span's text has more lines than the rows it covers have, the last covered row grows by the shortfall; the table scrolls by row, so with the origin row above the top and covered rows shown the cell is clipped at the table's top edge and placed again within the covered lines still shown, its text showing in the first of them; the cursor, `*` and `[x]` stay per row, and a click on a line in a spanning cell's column acts on its origin row, the hit-test taking the column's x as well as the line and covering the whole height of the rows the span covers, not only the lines its content is drawn on (a centred one-line cell leaves blank covered lines, and a click on one is a click on the span) | arrows, Space selects or toggles, Shift+Up and Shift+Down select a range from the anchor, Ctrl+A selects every row or clears them (Multiple), Enter activates; a click selects only its row, Ctrl+click toggles it and Shift+click selects a range where the emulator passes the modifier on (`clickWith`), and a plain double click activates; a click on a sortable column's header asks to sort by it (the header takes no keyboard focus); the cursor passes over a heading row, a click on one does nothing, and Ctrl+A, a range and the header box leave it out | diff --git a/docs/spec/ui/author.md b/docs/spec/ui/author.md index 1ab530bf1..b0c05bd90 100644 --- a/docs/spec/ui/author.md +++ b/docs/spec/ui/author.md @@ -186,7 +186,7 @@ disabled on the first. The three labels are plain text and default to English (` `continue`. `DialogOptions::actions` (a `dialog`'s or `drawer`'s) lists its footer buttons as `ActionButtonOptions`, run in its scope, and `DialogOptions::description` writes its head's description line. -`DialogOptions::sheet` and `dismissLabel` are a dialog's: the condition for drawing it as a sheet, and its dismiss control's label. +`DialogOptions::sheet` is a dialog's: the condition for drawing it as a sheet. `dismissLabel` labels the dismiss control of a sheet or of `closeButton`; `headNote` and `footerNote` are the notes on the title's row and in the footer's row, and `closeButton` is the condition for a dismiss control on the title's row. The keys every node takes are member functions of `Node`, each returning a copy with the key set: `id(element)`, `visible`, `enabled`, `tooltip`, `sizing`, `span`, `autofocus`, `testId`, `surface` (a name, or an diff --git a/docs/spec/ui/backend_contract.md b/docs/spec/ui/backend_contract.md index cf3603824..ee2eaa51a 100644 --- a/docs/spec/ui/backend_contract.md +++ b/docs/spec/ui/backend_contract.md @@ -382,7 +382,7 @@ child does. Across, a child its maximum stops from filling is placed by its alig | `ScrollWidget` | — | — | | `SlotWidget` | `setScrollable(scrollable)` (a new slot does not scroll) | — | | `TabsWidget` | `setTabs(labels)` (may be called again; a call with the same number of labels replaces the captions and keeps the highlight, the shown page and the keyboard focus), `setSelected(index)` (past the last highlights none), `setBarShown(shown)` (whether the strip of tab buttons is drawn; the selected page shows either way, and a new tabs widget shows its strip), `setMoreLabel(label)` (the label of the menu that holds the tabs that do not fit in the bar; a frontend that does not draw one stores it) | `setOnSelect(index)` | -| `DialogWidget` | `setOpen`, `setTitle`, `setDescription` (a line under the title in the head, not scrolled with the content, and the overlay's accessible description), `footer()`, `setSheet`, `setDismissLabel` (called only when the document binds or sets them) | `setOnDismiss` (Esc on the TUI), for an open dialog, which the dismissal closes first | +| `DialogWidget` | `setOpen`, `setTitle`, `setDescription` (a line under the title in the head, not scrolled with the content, and the overlay's accessible description), `footer()`, `setSheet`, `setDismissLabel`, `setHeadNote` (a muted note on the title's row, trailing), `setFooterNote` (a muted note leading in the footer's row; the footer shows while it is not empty), `setCloseButton` (a dismiss control on the title's row, labelled by `setDismissLabel`; a `DrawerWidget` has the same four) (called only when the document binds or sets them) | `setOnDismiss` (Esc on the TUI), for an open dialog, which the dismissal closes first | | `ToastWidget` | `show(text, tone)` (one call: shows the message and restarts the dismiss interval regardless of whether the toast is already on-screen) | — | | `BusyWidget` | `setActive`, `setLabel` | — | | `TableWidget` | `setColumns(vector)`, `setSelectionMode`, `setRowKey(row, key)`, `setRowTone(row, optional)` (after `setRowKey`, and on every change), `setSelection(keys)`, `setSelectColumn(bool)`, `setSelectAllLabel(text)`, `setRowLabel(row, text)`, `setRowHeading(row)` (once, after `setRowKey`: the row is never marked, reported or activated), `setRowSpans(row, vector)` (after `setRowKey`, and on every change; the spans are resolved ([Row spans](view_tree.md#row-spans)), so once a change settles a backend is told none out of range, overlapping, past the last row or on a heading; while it settles it may see one, so it derives coverage at layout or paint time from the rows' current order, never at this call, and clips a span that runs past its last row or onto a heading; a call with an empty list clears the row's), `setExistingKeys(keys)` (every key, in row order, above the virtualization threshold), `setSort(optional)` (marks the column's header with the direction, or none; only for a table with a sortable column) | `setOnSelectionChange(keys, SelectionChange)`, `setOnActivate(Key)` (Enter or a double click), `setOnSort(column)` (a click on a sortable column's header, or Enter or Space on it where the header takes focus; the index counts the columns `setColumns` gave, which the select column is not one of; another header reports nothing). The backend never reorders rows for a sort: it shows `setSort`, and what a click means is the lowering's | diff --git a/docs/spec/ui/document.md b/docs/spec/ui/document.md index 2cc3dcd87..65c891247 100644 --- a/docs/spec/ui/document.md +++ b/docs/spec/ui/document.md @@ -290,7 +290,7 @@ weight and face, so `{role: display, tone: err}` is a large red figure. | `scroll` | `axis`, `children` | | | `switch` | `on` (required), `cases`: parts `{when, scope, children ⓘ}`, `default` | | | `tabs` | `tabs`: parts `{id, label, children}`, `selected`, `onChoose`, `moreLabel` (an expression, default `More`, translated with `t` and in English: the label of the menu a frontend may draw for the tabs that do not fit in the bar), `inset` (a literal spacing step, 0 to 5, default 0: the strip and its rule span the node's width, the first tab starts this far in from the leading edge, and each page is padded by it on every side, and the page's inset is the whole gap under the strip's rule; a computed or out-of-range value is refused), `pageInset` (a literal spacing step, 0 to 5, default `inset`: the padding of each page, apart from the strip's; each page pads its own content inside its own scroll, so a `bleed` child of a page reaches the node's edges whether or not the page scrolls; a computed or out-of-range value is refused), `stripSurface` (a surface name: the strip, and nothing else, is drawn on that surface across the node's width; with a `pageEdge` column as the root, a tabs node with both is a page whose strip sits in the head's block and whose content is inset below its rule); a tab's `label` follows its expression, and the list of tabs is fixed (a tab takes no `visible`). `selected` is the id of the tab shown, controlled as a select's: a pick runs `onChoose` with the tab's id as `event`, and the page follows `selected` alone; a literal `null` is no binding. Without it the node keeps the user's pick, so picking a tab mounts and shows its page. A relabel keeps the pick. A command chooses a tab by setting the state `selected` reads; `set` never names a tabs node | `selected` (the shown tab's id: the bound one, else the pick, else the first tab's) | -| `dialog`, `drawer` | `open`, `gap` (the spacing step between several `children`, default 3, read once), `title`, `description` (a line in the head under the title, ruled off from the body, which does not scroll with the content and is the overlay's accessible description), `descriptionSpans` (the line as runs, as a `text`'s `spans`: a client that knows it draws them in place of `description`, and the accessible description is their characters joined), `showErrors`, `side`, `scope`, `children` ⓘ, `default` ⓘ, `cancel` ⓘ, `actions` ⓘ (parts `actionButton`, [The head](#the-head)), `onDismiss`; a dialog's `sheet` (a condition: while true the dialog is drawn as a sheet that fills the window, with a head of a dismiss control and the title centred on the sheet, ruled off from the body, the document choosing by the width class, as `{"fn": "eq", "args": [{"env": "widthClass"}, "compact"]}`) and `dismissLabel` (the dismiss control's label, default `Close`, translated with `t`; only with `sheet`); the dismiss control dismisses exactly as Escape does, and a drawer takes neither | `open`, `ready`, `submitted` | +| `dialog`, `drawer` | `open`, `gap` (the spacing step between several `children`, default 3, read once), `title`, `description` (a line in the head under the title, ruled off from the body, which does not scroll with the content and is the overlay's accessible description), `descriptionSpans` (the line as runs, as a `text`'s `spans`: a client that knows it draws them in place of `description`, and the accessible description is their characters joined), `showErrors`, `side`, `scope`, `children` ⓘ, `default` ⓘ, `cancel` ⓘ, `actions` ⓘ (parts `actionButton`, [The head](#the-head)), `onDismiss`; a dialog's `sheet` (a condition: while true the dialog is drawn as a sheet that fills the window, with a head of a dismiss control and the title centred on the sheet, ruled off from the body, the document choosing by the width class, as `{"fn": "eq", "args": [{"env": "widthClass"}, "compact"]}`) and `dismissLabel` (the dismiss control's label, default `Close`, translated with `t`; only with `sheet` or `closeButton`); `headNote` (a muted note on the title's row, against its trailing edge) and `footerNote` (a muted note leading in the footer's row, opposite the actions, which shows the footer while it is not empty), both expressions, empty showing none; `closeButton` (a condition: while true a dismiss control labelled `dismissLabel` is drawn on the title's row, against the trailing edge; a sheet's head holds one already, so it adds nothing while `sheet` holds); the dismiss control dismisses exactly as Escape does, and a drawer takes no `sheet` | `open`, `ready`, `submitted` | | `busy` | `active`, `label` | | | `forEach` | `rows` (required), `key` ⓘ, `axis`, `gap`, `wrap` (a literal boolean, default `false`; the rows continue on the next line when they do not fit; the loader refuses `true` where a literal `axis` is not `horizontal`, and a computed `axis` that is not horizontal at lowering is reported and the rows do not wrap), `divided` (as a column's, for a vertical `forEach`; the loader refuses it where a literal `axis` is `horizontal`), `scope`, `children` ⓘ | | | `table` | `rows`, or `model` and `action` with `body` and `mode`; `key` ⓘ, `columns` (parts `{id, label, width, role ⓘ, align, valign, sortable, wrap, shrink, sortBy ⓘ, cell ⓘ}`, or an expression of `{id, label, align, valign}` records — `role` styles the column's default cell and has no other effect on one with its own `cell`; it takes a text's role names, and a literal one is checked the same way; a `mono` role also sets the width unit of the column's `fixed(n)`: n mono characters, plus the cell padding, with or without a `cell`, so a column of identifiers says `mono` to hold them whole; `wrap` (a literal boolean, default `true`) with `false` draws the column's text cells on one line, cut at the column's width with an ellipsis, such as a value with its unit; `shrink` (a literal flag, default off, for a column whose `width` stretches; on any other column it is reported once and ignored) lets the column go narrower than its header when the table is narrower than its columns need, down to a floor of 8 units, its header and cells then cut, where otherwise no column is narrower than its header and the table scrolls sideways, and makes it give up width before the other stretch columns (the two meanings are one flag; a column that may go under its header but keeps its content late has no spelling); a stretch `width` starts from the column's content (its header and its widest shown cell) and its weight shares only the width the content leaves, so proportions that ignore the content cannot be said, a literal `percent` column stays refused, and a width the user sets would be a fixed column; `align` (`start`, the default, `center`, `end`) places a text cell's or a text input's text, a badge, check box or push button cell, and the header label across the column, while a container cell fills it; `valign` (`start`, `center`, the default, `end`) places every cell down its row; both are literal names, and a computed column's place of no known name is reported once and takes the default), `valign` (the default of every column that gives none), `selectionMode`, `selection` (a list of row keys: bound, it is controlled, as a select's `selected` is; refused without a `selectionMode` of `single` or `multiple`, and on a model-backed table), `onSelectionChange` (after each user change, with `event` the new keys; the same rules), `selectColumn` (a literal flag, only with a literal `selectionMode: multiple`: the table draws its selection as a leading column of check boxes under a select-all box), `selectAllLabel` (the select-all box's accessible name, only with `selectColumn`; default `Select all`, translated with `t`), `rowLabel` ⓘ (each row's accessible name, which its box carries; default the row's key as text), `sort` (a list of keys `{"column": , "direction": "asc" or "desc"}`, most significant first, `[]` the source order: the table orders its rows by it; bound, it is controlled, as `selection` is, and unbound the table holds it from `[]`; a literal one names sortable columns, each once; a column's `sortable`, a literal flag that needs its `id`, makes a click on its header sort by it alone, ascending, or descending when it already is the first key ascending; its `sortBy`, only with `sortable`, is the value the rows order by, read per row as `key` is, default the row's field of the column's `id`), `onSortChange` (after a header click, with `event` the new sort; needs a sortable column), `pageSize` (a positive integer: the table shows one page of that many of its sorted rows; absent or `null`, every row; a literal below 1 is refused), `group` (a part `{by ⓘ, heading ⓘ}`: a heading row before each run of adjacent rows whose `by` values are equal, drawn from `heading` in a row scope whose `row` is the run's record `{key, count, first, last, items}` of the whole group; a heading spans every column, is never selected, marked or activated, and counts in no element value; with a sort, each group keeps its place and its rows are sorted within it, and a group split across pages gets its heading on both; refused on a model-backed table; a heading's key is reserved, `"\u001Fgroup:"` then the canonical JSON of its run's key, `":"` and its ordinal among the runs with that key, and a data row with a field `"\u001Fgroup"` is taken for a heading), `page` (the page shown, from 0, clamped to the last; absent or `null`, the first; needs `pageSize`; `pageSize` and `page` are refused on a model-backed table, whose engine pages), `filters` and `highlightKey` (a model-backed table's only), `rowTone` ⓘ, `rowSpans` ⓘ (each row's spans, read in the row scope: a list of `{column, rows}` records, `column` the id of a column and `rows` an integer from 1 counting the row itself, whose cell in that column covers the rows below; `null` or `[]` none; the cells it covers are not shown and their content is ignored, though a client that does not know the key draws them, so a document leaves them empty; a table that is sorted, or above its virtualization threshold, draws no spans, and a span that names no column, repeats a column of its row, runs past the last row of the page the table holds, runs over a group heading, or starts in a column an earlier span covers, is refused and reported, the cell then standing in its own row (the interpreter's reports carry a path; the mount's for a span past the last row, onto a covered column, or above the virtualization threshold are bare and name none, so look at the rows' order); a spanned table should not page, or should page by groups, since a page boundary through a span refuses it; [`view_tree.md`](view_tree.md#row-spans)), `onActivate` ⓘ, `empty` (nodes: shown instead of the table while `rows` is an empty list), `scope` | `selection`, `activeKey`, `sort`, `filters`, `viewCount` (the rows the table orders, every page), `sourceCount` (the rows `rows` gave), `selectedCount`, `pending`, `error`, `hoveredKey`, `page` (the page shown, clamped), `pageCount` (at least 1), `pageFirst` and `pageLast` (the 1-based positions of the page's first and last rows, both 0 when there are none; a table that does not page reads page 0 of 1 over every row) | diff --git a/docs/spec/ui/view_tree.md b/docs/spec/ui/view_tree.md index 3de71512b..f1e9ce59f 100644 --- a/docs/spec/ui/view_tree.md +++ b/docs/spec/ui/view_tree.md @@ -115,7 +115,7 @@ lowers them to the kinds below. | `Scroll` | `scroll` | `child`, `axis` (`Axis{Vertical, Horizontal}`, set once) | | `Switch` | `switchOf`, `switchOn` | `selector` (`Prop`), `cases` (`SwitchCase{key, node}`; the first case with the key wins), `fallback` | | `Tabs` | `tabs` | `inset` (an `int` spacing step, set once; the mount calls `TabsWidget::setInset` only for a nonzero step), `pageInset` (a `std::optional` spacing step, set once; engaged, the mount calls `TabsWidget::setPageInset`, even with 0, and the pages are padded by it in place of `inset`) and `stripSurface` (a surface name, set once; `TabsWidget::setStripSurface` only for a nonempty one), `tabs` (`Tab{label, node}`; the list is set once, each `label` is a `Prop` the bar follows: the mount sends every caption again when one changes), `selected` (`Prop`), `onSelect`, `moreLabel` (`Prop`, default `More`; the mount tells the widget only when it is bound or not the default) | -| `Dialog` | `dialog` | `open`, `title`, `description` (applied only when bound or not empty), `descriptionSpans` (the description as runs; while bound or not empty, `setDescriptionSpans` is called in place of `setDescription`), `child`, `onDismiss`, `sheet` (default `false`), `dismissLabel` (default `Close`): the mount calls `setSheet` and `setDismissLabel` only when they are bound or not the default | +| `Dialog` | `dialog` | `open`, `title`, `description` (applied only when bound or not empty), `descriptionSpans` (the description as runs; while bound or not empty, `setDescriptionSpans` is called in place of `setDescription`), `child`, `onDismiss`, `sheet` (default `false`), `dismissLabel` (default `Close`; labels a sheet's control and the one `closeButton` draws), `headNote` and `footerNote` (muted text on the title's row, against its trailing edge, and leading in the footer's row; empty shows none), `closeButton` (default `false`: a dismiss control on the title's row, dismissing as Escape does; a sheet's head holds one already, so it adds nothing there): the mount calls `setSheet`, `setDismissLabel`, `setHeadNote`, `setFooterNote` and `setCloseButton` only when they are bound or not the default. A `Drawer` takes `headNote`, `footerNote`, `closeButton` and `dismissLabel` as a dialog does | | `Busy` | `busy` | `active`, `label` | | `ForEach` | `forEach` | rows, key function, row view, `axis`, `gap`, `common` (the row container's, as on every kind), `wrap` (a `bool`; honoured on a horizontal `axis` only, as a Row's), `divided` (a `bool`; honoured on a vertical `axis` only, as a Column's) ([below](#keyed-collections)) | | `Table` | `table` | `columns` (`TableColumn{label, width, role, align, valign, sortable, wrap, shrink}`, set once; a `Stretch` `width` starts from the column's content and its weight shares only the width the content leaves (the contract's four steps), and `shrink` also makes the column give up width before the other stretch columns; `sortable` makes a click on the header ask to sort by the column; `role` styles a column's default cell and has no effect on the style of one with its own `.cell`, and a `Mono` role makes a fixed width count monospace characters; `wrap`, default `true`, with `false` keeps the column's text cells to one line, cut at the column's width with an ellipsis; `align`, default `Start`, places a text's or a text input's text, a label-width cell and the header label across the column, and `valign`, default `Center`, places every cell down its row, `Stretch` filling it), rows, key function, cells — or a row view answering `TableRowView{cells, tone, label, heading, spans}`, whose tone, label and `spans` bind in the row's own scope and whose `heading` makes the row a heading of exactly one cell (`ui::table` refuses any other count, as it refuses a data row of the wrong count); a row's `spans` let its cells cover the rows below it ([Row spans](#row-spans)), and a sorted or virtualized table draws no spans, and a bad span is refused alone — and `TableOptions{selectionMode, selection, onSelectionChange (the keys and a `SelectionChange`: `Replace`, the whole selection, or `Extend`, which keeps the keys the backend does not hold), onActivate, selectColumn (set once: a leading column of check boxes drawing the selection), selectAllLabel (the header box's name, default `Select all`), sort (a `Prop>`: the column whose header marks the sort, and its `SortDirection`; the table never reorders its rows, which arrive sorted), onSort (a sortable column's index when the user asks to sort by it), common}`; the mount tells the widget `sort` and `onSort` only when a column is sortable ([below](#keyed-collections)) | diff --git a/examples/common/testkit/backend_rig.hpp b/examples/common/testkit/backend_rig.hpp index 7502d925e..bdfcc5281 100644 --- a/examples/common/testkit/backend_rig.hpp +++ b/examples/common/testkit/backend_rig.hpp @@ -20,6 +20,7 @@ #include #include +#include "clock.hpp" #include "testkit/server_connection.hpp" /// @file @@ -244,6 +245,10 @@ class BackendRig { ::morph::backend::ServerConfig config; // Lets a connection from connect() take events; a socket client never sends this kind. config.services.push_back(std::make_shared()); + // The server waits for a model's reported instant on the ladder's clock, which a test moves by hand, + // so it reads the clock often. + config.clock = [] { return *::morph::ladder::now().value; }; + config.clockRecheck = std::chrono::milliseconds{20}; if (authorizer) { _server = std::make_shared<::morph::backend::RemoteServer>(*_workerPool, authorizer, config); } else { diff --git a/examples/common/testkit/screen_harness.hpp b/examples/common/testkit/screen_harness.hpp index 73257675b..17e5cc596 100644 --- a/examples/common/testkit/screen_harness.hpp +++ b/examples/common/testkit/screen_harness.hpp @@ -37,6 +37,7 @@ #include #include +#include "clock.hpp" #include "testkit/fake_app_context.hpp" #include "testkit/wait.hpp" @@ -85,19 +86,27 @@ class SimulatedAppSource final : public ::morph::client::Source { _workers = std::make_unique(2); backend::ServerConfig config; config.services.push_back(std::make_shared(std::move(*bundle))); + // The server waits for a model's reported instant on the ladder's clock, which a test moves by hand, so it + // reads the clock often. + config.clock = [] { return *::morph::ladder::now().value; }; + config.clockRecheck = std::chrono::milliseconds{20}; _server = _app.serverAuthorizer ? std::make_shared(*_workers, _app.serverAuthorizer(), config) : std::make_shared(*_workers, config); - ui::Exchange exchange = [server = _server](wire::Envelope const& request, - std::function const& done) { + // One connection for the models and for the `ui-*` requests, as one socket would be: the server tells a + // connection what changed only when that connection negotiated events and has a watch. + backend::ConnectionId const cid = _server->openConnection(); + ui::Exchange exchange = [server = _server, cid](wire::Envelope const& request, + std::function const& done) { try { - done(wire::decode(server->handleInline(wire::encode(request)))); + done(wire::decode(server->handleInline(wire::encode(request), cid))); } catch (std::exception const& error) { done(std::unexpected(std::string{error.what()})); } }; - return Transport{.backend = std::make_unique(*_server), - .exchange = std::move(exchange)}; + return Transport{.backend = std::make_unique(*_server, cid), + .exchange = std::move(exchange), + .serverEvents = true}; } void disconnect() override { diff --git a/examples/lims/CMakeLists.txt b/examples/lims/CMakeLists.txt index 6d07c0982..d7cae14a6 100644 --- a/examples/lims/CMakeLists.txt +++ b/examples/lims/CMakeLists.txt @@ -85,9 +85,9 @@ if(MORPH_BUILD_TESTS AND NOT EMSCRIPTEN) _lims_boundary_probe(inventory_includes_posting inventory pass lims/posting/posting.hpp) _lims_boundary_probe(billing_includes_inventory billing fail lims/inventory/models/stock_model.hpp) - # The composing code declaring one module's action's effect on another module's record: the probe adds a second - # effects registration for PostInvoice and must be refused; the control, without it, must resolve. - foreach(_variant IN ITEMS refused control) + # The composing code declaring one module's action's effect on another module's record: the probe adds an + # effect to PostInvoice and the union must keep the action's own effect too; the control, without it, must resolve. + foreach(_variant IN ITEMS accepted control) add_executable(lims_cross_module_effects_${_variant} tests/compile_checks/cross_module_effects_probe.cpp) target_link_libraries(lims_cross_module_effects_${_variant} PRIVATE ladder_lims_lib) set_target_properties(lims_cross_module_effects_${_variant} PROPERTIES EXPORT_COMPILE_COMMANDS OFF) @@ -96,9 +96,9 @@ if(MORPH_BUILD_TESTS AND NOT EMSCRIPTEN) endif() add_test(NAME lims.cross_module_effects.${_variant} COMMAND lims_cross_module_effects_${_variant}) endforeach() - target_compile_definitions(lims_cross_module_effects_refused PRIVATE LIMS_PROBE_DECLARES_LEDGER_EFFECT=1) - set_tests_properties(lims.cross_module_effects.refused PROPERTIES LABELS ladder-lims - PASS_REGULAR_EXPRESSION "declares different effects in two registrations") + target_compile_definitions(lims_cross_module_effects_accepted PRIVATE LIMS_PROBE_DECLARES_LEDGER_EFFECT=1) + set_tests_properties(lims.cross_module_effects.accepted PROPERTIES LABELS ladder-lims + PASS_REGULAR_EXPRESSION "PostInvoice adds Ledger_Entry: 1") set_tests_properties(lims.cross_module_effects.control PROPERTIES LABELS ladder-lims PASS_REGULAR_EXPRESSION "effects resolved") endif() diff --git a/examples/lims/README.md b/examples/lims/README.md index f89c7abfe..92d3ae792 100644 --- a/examples/lims/README.md +++ b/examples/lims/README.md @@ -902,8 +902,9 @@ not list queries, and an action that changes a record is authorized by its decla **Finding: a shared module's action cannot declare effects on another module's records.** Assigning or revoking a role changes which samples a principal sees, so `AssignRole` changes the rows `ListSamples` answers. But `AssignRole` belongs to `org`, which cannot name lab's `SampleView`, and a second `BRIDGE_REGISTER_EFFECTS` for the same action -from `app` is refused as "declares different effects in two registrations". So a screen listing samples does not -refresh when its viewer's roles change; it refreshes on the next sample change or reload. Registering `SampleView` as +from `app` is refused as "declares different effects in two registrations". `BRIDGE_ADD_EFFECTS` from `app` is the +way to declare it (decision 39). Until it does, a screen listing samples does not refresh when its viewer's roles +change; it refreshes on the next sample change or reload. Registering `SampleView` as derived from the role-assignment record would give the same refresh, but the registry refuses a derived record that has a key (`include/morph/core/effects.hpp`, the "is derived from other records but has a key" check), and `SampleView` has one. Inferred from reading `include/morph/core/effects.hpp` (`addEffects`, the two-declarations check, and the @@ -1184,10 +1185,12 @@ with lab's verification but the declared authorization (`lims::Authorization`, ` instance, but escalation is not scheduled work: it is a deadline the rule reads when an approver acts or lists, so nothing has to start at the deadline or resume after a restart. Measured in the same file with the clock before and after the deadline. The one consequence is an effects question, not a scheduling one, measured in -`screens/tests/test_lims_approval_inbox.cpp`: a site approver's inbox, mounted before the deadline, still lists the -invoice after it, and shows the escalation only when it asks again. What the test measures is that the open inbox is -not told: it is checked after the harness advances past the deadline. The cause is inferred, not measured: no action -ran, so no effect was declared or fanned out. Hypothesis 4 therefore has one instance in this design, the billing run +`screens/tests/test_lims_approval_inbox.cpp`: a site approver's inbox, mounted before the deadline, must drop the +invoice when the deadline passes. No action runs at that instant, so no effect fans out; the model reports the instant +instead. `NextApprovalDeadline` answers the earliest deadline still ahead and is registered with +`BRIDGE_REGISTER_CHANGES_AT` for `InvoiceView`; the server owns the clock, tells every watcher of the record when the +clock reaches the instant, and asks again. The test moves the clock without sleeping and asserts that the open inbox +shows "0 pending". Hypothesis 4 therefore has one instance in this design, the billing run (decision 34), and the design's row says so. Part C's requisition escalation is expected to take this shape. ### 36. Billing's approval pairs and the approver's value limit are declared, and checked in the model (hypothesis 6, second instance) @@ -1300,13 +1303,13 @@ empty for such a caller, which cannot mislead, since recording the posting refus Two causes, measured apart in `tests/test_cross_module_effects.cpp` and by the `lims.cross_module_effects.*` probes. -**(i) An action cannot declare an effect on another module's record — confirmed.** `PostInvoice` posting in one -shared transaction (decision 38) writes the ledger's `Ledger_Entry` inside billing's action; an accountant watching -`Ledger_Entry` is not told, while the ledger's own `CreateDraftEntry` on the same connection is heard. Billing cannot -name the ledger's record (it does not include the ledger), and the composing code, which sees both, cannot add the -declaration: a second `BRIDGE_REGISTER_EFFECTS` for `PostInvoice` makes the effects configuration refuse to resolve, -"action `PostInvoice` declares different effects in two registrations" (the `refused` probe prints it; the `control` -probe, without the second registration, resolves). +**(i) An action cannot declare an effect on another module's record, so the composing code adds it.** `PostInvoice` +posting in one shared transaction (decision 38) writes the ledger's `Ledger_Entry` inside billing's action. Billing +cannot name the ledger's record (it does not include the ledger), and a second `BRIDGE_REGISTER_EFFECTS` is refused. +The app, which includes both, states it with `BRIDGE_ADD_EFFECTS` in `app/src/ledger_wiring.cpp`; the addition is +unioned with billing's own `updates`, and an accountant watching `Ledger_Entry` hears the posting. The +`accepted` probe checks that the union holds both effects, the `control` probe that the configuration resolves without +the addition. **(ii) A write outside any action derives no changes — confirmed, and not a gap.** `RecordBillableLine` run in process outside any dispatch writes the line and no watcher of `Billing_Line` is told; the same write dispatched through the @@ -1317,8 +1320,7 @@ events client is heard. Changes are derived from executed actions by design: the The measured miss exists only in the shared-transaction mode. The shipped server posts dispatched, and there the ledger's half runs as the ledger's own `RecordPosting`, which a watching accountant hears (decision 38's test). The shared transaction is itself the workaround for hypothesis 1's missing seam — two modules' actions as one fact, each -keeping its effects — and if that seam lands this instance goes with it. The instance no other seam fixes is decision -26's, still inferred: org's `AssignRole` changes which samples lab's list returns, a change of visibility rather than a +keeping its effects — and if that seam lands this instance goes with it. Decision 26's case, still inferred: org's `AssignRole` changes which samples lab's list returns, a change of visibility rather than a write, which neither dispatching nor a multi-action seam would make lab's screen hear. The one existing mechanism that carries a change from one record to another, `record::derivedFrom`, is refused on a keyed record, and both `Ledger_Entry` and `SampleView` are keyed. So cause (i) is filed against `include/morph` as a missing seam: a way for @@ -1492,10 +1494,10 @@ submitted on one rig is approved on another a day later in `Local`, `LocalSingle and the limit hold. The lifecycle needed no state outside the row, and shares no code with invoice approval but the declared authorization: each lifecycle wrote its own transition helper, pending list and escalation predicate (`requisitions.cpp`, 320 lines; `invoice_approval.cpp`, 250). Escalation is again a deadline the rule reads, not -scheduled work (decision 35); and again an approver's open inbox is not told when the deadline passes. That is -measured on a site approver's watching connection, with a requisition raised after the deadline in the same case as -the control that the connection hears a change of the record. It is the same gap in a second module, so it is filed -against `include/morph`; Part D Task 20 builds the deadline effect. +scheduled work (decision 35); and again an approver's open inbox had to be told when the deadline passes. That is +measured on a site approver's watching connection: `NextRequisitionDeadline` reports the instant, and the connection +hears a change of `Inventory_Requisition` when the clock reaches it. It is the same gap in a second module, which is +why the framework took it: the model reports the instant and the server owns the timer. **Declared authorization, third module.** The rule is declared once beside each action (`inventory_authorization.hpp`) and the framework's guard runs it; no handler makes the first authorization call. diff --git a/examples/lims/app/src/ledger_wiring.cpp b/examples/lims/app/src/ledger_wiring.cpp index d5e799e1e..dc4b7dec1 100644 --- a/examples/lims/app/src/ledger_wiring.cpp +++ b/examples/lims/app/src/ledger_wiring.cpp @@ -1,12 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 #include "lims/app/ledger_wiring.hpp" +#include #include +#include "lims/billing/models/invoice_model.hpp" #include "lims/ledger/db/ledger_store.hpp" #include "lims/ledger/models/ledger_model.hpp" #include "lims/posting/ledger_port.hpp" +// In the shared-transaction mode `PostInvoice` writes the ledger's entry inside its own action, so a watcher of the +// ledger's entries is told only if the action says so. Billing cannot name the ledger's record; this unit, which +// composes both, can. +BRIDGE_ADD_EFFECTS(lims::PostInvoice, ::morph::effects::changes) + namespace lims::app { void installLedgerPort(InternalClient& posting, PostingMode mode) { diff --git a/examples/lims/billing/include/lims/billing/dto/invoice_dto.hpp b/examples/lims/billing/include/lims/billing/dto/invoice_dto.hpp index 4fe6dc34c..fcffc7356 100644 --- a/examples/lims/billing/include/lims/billing/dto/invoice_dto.hpp +++ b/examples/lims/billing/include/lims/billing/dto/invoice_dto.hpp @@ -141,6 +141,14 @@ struct PostInvoice { static constexpr bool explicitSubmit = true; }; +/// @brief Reports the next instant at which a submitted invoice's approval escalates from its site to its company, +/// for the server to tell the screens that list invoices by that scope. +struct NextApprovalDeadline { + /// @brief Whether the query is well-formed. + /// @return Always `true`: it names nothing. + [[nodiscard]] static bool validate() noexcept { return true; } +}; + /// @brief Lists the submitted invoices the caller could approve now. struct ListPendingApprovals { /// @brief Whether the query is well-formed. diff --git a/examples/lims/billing/include/lims/billing/models/invoice_model.hpp b/examples/lims/billing/include/lims/billing/models/invoice_model.hpp index b49a11054..66f2d94cf 100644 --- a/examples/lims/billing/include/lims/billing/models/invoice_model.hpp +++ b/examples/lims/billing/include/lims/billing/models/invoice_model.hpp @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include "lims/billing/dto/invoice_dto.hpp" #include "lims/billing/dto/lease_dto.hpp" @@ -120,6 +122,13 @@ class InvoiceModel { /// @throws EmptyPrincipalError if no principal is authenticated. ::core::async::Task execute(PostInvoice action); + /// @brief The next instant, after now, at which a submitted invoice's approval moves from its site to its + /// company: the earliest deadline still ahead. The invoices an approver may approve change at that + /// instant with no action behind it. + /// @param action Carries nothing. + /// @return The instant, or nothing when no submitted invoice has a deadline ahead. + std::optional<::morph::time::DateTime> execute(const NextApprovalDeadline& action); + /// @brief Lists the submitted invoices the caller could approve now, judged by the rule `ApproveInvoice` is. /// @param action The query. /// @return The invoices by id. @@ -201,6 +210,9 @@ BRIDGE_DECLARE_ACTION(lims::InvoiceModel, lims::PostInvoice, "PostInvoice") BRIDGE_REGISTER_EFFECTS(lims::PostInvoice, ::morph::effects::updates) BRIDGE_DECLARE_ACTION(lims::InvoiceModel, lims::ListPendingApprovals, "ListPendingApprovals", ::morph::model::Loggable::No) +BRIDGE_DECLARE_ACTION(lims::InvoiceModel, lims::NextApprovalDeadline, "NextApprovalDeadline", + ::morph::model::Loggable::No) +BRIDGE_REGISTER_CHANGES_AT(lims::InvoiceModel, lims::NextApprovalDeadline, lims::InvoiceView) // The shell's open-work counts and search over the invoices. BRIDGE_DECLARE_ACTION(lims::InvoiceModel, lims::CountOpenInvoiceWork, "CountOpenInvoiceWork", ::morph::model::Loggable::No) diff --git a/examples/lims/billing/src/models/invoice_approval.cpp b/examples/lims/billing/src/models/invoice_approval.cpp index cffa7e846..9389be553 100644 --- a/examples/lims/billing/src/models/invoice_approval.cpp +++ b/examples/lims/billing/src/models/invoice_approval.cpp @@ -3,9 +3,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include "lims/billing/authorization/billing_authorization.hpp" @@ -217,6 +220,30 @@ InvoiceView InvoiceModel::execute(const ApproveInvoice& action) { return invoiceView(mapper, static_cast(row.id.Value())); } +// An action handler: the registry calls it on the instance, like every other. +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +std::optional<::morph::time::DateTime> InvoiceModel::execute(const NextApprovalDeadline& action) { + static_cast(action); + Lightweight::DataMapper mapper; + auto const rows = mapper.Query() + .Where(::Lightweight::FieldNameOf<&db::InvoiceRecord::state>, "=", + static_cast(InvoiceState::Submitted)) + .All(); + std::optional next; + std::int64_t const now = nowMillis(); + for (auto const& row : rows) { + // `escalated` holds from the deadline on, so only a deadline strictly ahead is still to come. + std::int64_t const deadline = row.deadlineAt.Value(); + if (deadline > now && (!next || deadline < *next)) { + next = deadline; + } + } + if (!next) { + return std::nullopt; + } + return ::morph::time::DateTime{std::chrono::sys_time{std::chrono::milliseconds{*next}}}; +} + // An action handler: the registry calls it on the instance, like every other. // NOLINTNEXTLINE(readability-convert-member-functions-to-static) ListInvoicesResult InvoiceModel::execute(const ListPendingApprovals& action) { diff --git a/examples/lims/billing/src/models/invoice_model.cpp b/examples/lims/billing/src/models/invoice_model.cpp index a922a3eda..d3a5a315c 100644 --- a/examples/lims/billing/src/models/invoice_model.cpp +++ b/examples/lims/billing/src/models/invoice_model.cpp @@ -359,6 +359,7 @@ BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::CreateInvoice) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::SubmitInvoice) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::ApproveInvoice) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::PostInvoice) +BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::NextApprovalDeadline) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::ListPendingApprovals) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::CountOpenInvoiceWork) BRIDGE_REGISTER_ACTION_SOURCE(lims::InvoiceModel, lims::CountPendingApprovals) diff --git a/examples/lims/inventory/include/lims/inventory/dto/requisition_dto.hpp b/examples/lims/inventory/include/lims/inventory/dto/requisition_dto.hpp index c44ca4620..5048e9166 100644 --- a/examples/lims/inventory/include/lims/inventory/dto/requisition_dto.hpp +++ b/examples/lims/inventory/include/lims/inventory/dto/requisition_dto.hpp @@ -169,6 +169,14 @@ struct ListRequisitions { [[nodiscard]] bool validate() const noexcept { return company.hasValue(); } }; +/// @brief Reports the next instant at which a submitted requisition's approval escalates from its site to its +/// company, for the server to tell the screens that list requisitions by that scope. +struct NextRequisitionDeadline { + /// @brief Whether the query is well-formed. + /// @return Always `true`: it names nothing. + [[nodiscard]] static bool validate() noexcept { return true; } +}; + /// @brief Lists the submitted requisitions the caller could approve now. struct ListPendingRequisitions { /// @brief Whether the query is well-formed. diff --git a/examples/lims/inventory/include/lims/inventory/models/procurement_model.hpp b/examples/lims/inventory/include/lims/inventory/models/procurement_model.hpp index a812b4d85..b5dd5be7f 100644 --- a/examples/lims/inventory/include/lims/inventory/models/procurement_model.hpp +++ b/examples/lims/inventory/include/lims/inventory/models/procurement_model.hpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include "lims/inventory/dto/order_dto.hpp" #include "lims/inventory/dto/receipt_dto.hpp" @@ -90,6 +92,13 @@ class ProcurementModel { /// @throws ValidationError if no company is named. ListRequisitionsResult execute(const ListRequisitions& action); + /// @brief The next instant, after now, at which a submitted requisition's approval moves from its site to its + /// company: the earliest deadline still ahead. The requisitions an approver may approve change at that + /// instant with no action behind it. + /// @param action Carries nothing. + /// @return The instant, or nothing when no submitted requisition has a deadline ahead. + std::optional<::morph::time::DateTime> execute(const NextRequisitionDeadline& action); + /// @brief Lists the submitted requisitions the caller could approve now: those whose approval rule allows them, /// at the site before the deadline and at the company from it. /// @param action Carries nothing. @@ -209,6 +218,9 @@ BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::GetRequisition, "GetRequisit BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::ListRequisitions, "ListRequisitions", ::morph::model::Loggable::No) BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::ListPendingRequisitions, "ListPendingRequisitions", ::morph::model::Loggable::No) +BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::NextRequisitionDeadline, "NextRequisitionDeadline", + ::morph::model::Loggable::No) +BRIDGE_REGISTER_CHANGES_AT(lims::ProcurementModel, lims::NextRequisitionDeadline, lims::RequisitionView) BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::CountPendingRequisitions, "CountPendingRequisitions", ::morph::model::Loggable::No) BRIDGE_DECLARE_ACTION(lims::ProcurementModel, lims::CreateSupplier, "CreateSupplier") diff --git a/examples/lims/inventory/src/models/procurement_model.cpp b/examples/lims/inventory/src/models/procurement_model.cpp index 9c8ccffae..5044b301b 100644 --- a/examples/lims/inventory/src/models/procurement_model.cpp +++ b/examples/lims/inventory/src/models/procurement_model.cpp @@ -13,6 +13,7 @@ BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::SubmitRequisition) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::ApproveRequisition) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::GetRequisition) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::ListRequisitions) +BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::NextRequisitionDeadline) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::ListPendingRequisitions) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::CountPendingRequisitions) BRIDGE_REGISTER_ACTION_SOURCE(lims::ProcurementModel, lims::CreateSupplier) diff --git a/examples/lims/inventory/src/models/requisitions.cpp b/examples/lims/inventory/src/models/requisitions.cpp index fdfc12d52..50e9afd9b 100644 --- a/examples/lims/inventory/src/models/requisitions.cpp +++ b/examples/lims/inventory/src/models/requisitions.cpp @@ -2,9 +2,12 @@ #include #include #include +#include #include #include +#include #include +#include #include #include @@ -253,6 +256,30 @@ ListRequisitionsResult ProcurementModel::execute(const ListRequisitions& action) return result; } +// An action handler: the registry calls it on the instance, like every other. +// NOLINTNEXTLINE(readability-convert-member-functions-to-static) +std::optional<::morph::time::DateTime> ProcurementModel::execute(const NextRequisitionDeadline& action) { + static_cast(action); + Lightweight::DataMapper mapper; + auto const rows = mapper.Query() + .Where(::Lightweight::FieldNameOf<&db::RequisitionRecord::state>, "=", + static_cast(RequisitionState::Submitted)) + .All(); + std::optional next; + std::int64_t const now = nowMillis(); + for (auto const& row : rows) { + // A requisition escalates from its deadline on, so only a deadline strictly ahead is still to come. + std::int64_t const deadline = row.deadlineAt.Value(); + if (deadline > now && (!next || deadline < *next)) { + next = deadline; + } + } + if (!next) { + return std::nullopt; + } + return ::morph::time::DateTime{std::chrono::sys_time{std::chrono::milliseconds{*next}}}; +} + // An action handler: the registry calls it on the instance, like every other. // NOLINTNEXTLINE(readability-convert-member-functions-to-static) ListRequisitionsResult ProcurementModel::execute(const ListPendingRequisitions& action) { diff --git a/examples/lims/screens/tests/approval_inbox_world.cpp b/examples/lims/screens/tests/approval_inbox_world.cpp index 30dc3ee83..5ec911903 100644 --- a/examples/lims/screens/tests/approval_inbox_world.cpp +++ b/examples/lims/screens/tests/approval_inbox_world.cpp @@ -12,6 +12,8 @@ #include "billing_test_support.hpp" #include "lims/billing/models/invoice_model.hpp" +#include "lims/org/dto/auth_dto.hpp" +#include "lims/org/models/auth_model.hpp" namespace lims::inboxtest { @@ -21,9 +23,12 @@ morph::time::DateTime at(int year, unsigned month, unsigned day, int hour) { return lims::test::at(year, month, day, hour); } -std::expected, morph::ui::Refusal> inboxBundle() { - ui::ScreenRegistry screens; - auto registered = screens.add(ui::screen(std::string{kInbox}, [](ui::Scope& screen) { +namespace { + +/// @brief The inbox screen. +/// @return The screen. +ui::Screen inboxScreen() { + return ui::screen(std::string{kInbox}, [](ui::Scope& screen) { auto const invoices = screen.model("invoices"); auto const pending = screen.query("pending", invoices); auto const rows = pending.value().at(&lims::ListInvoicesResult::invoices); @@ -34,21 +39,79 @@ std::expected, morph::ui::Refusal ui::button({.label = "Submit", .onClick = ui::run(submit, {{&lims::SubmitInvoice::invoiceId, 1}})}) .testId("submit"), }); - })); - if (!registered) { - return std::unexpected(registered.error()); + }); +} + +/// @brief The sign-in screen: any username, then the inbox. +/// @return The screen. +ui::Screen signInScreen() { + return ui::screen(std::string{kSignIn}, [](ui::Scope& screen) { + auto const auth = screen.model("auth", {.instance = ui::Instance::Private}); + auto const username = ui::element("username"); + auto const login = + screen.mutation("login", auth, + { + .body = {{&lims::LimsLogin::username, username.value()}}, + .onSuccess = + { + ui::signIn(ui::MutationRef{"login"}), + ui::navigate(std::string{kInbox}), + }, + }); + return ui::column({ + ui::textInput({.label = "Username"}).id(username).testId("username"), + ui::button({.label = "Sign in", .onClick = ui::run(login)}).testId("signIn"), + }); + }); +} + +/// @brief A bundle of the inbox, and of the sign-in before it when asked. +/// @param withSignIn Whether the bundle opens with the sign-in. +/// @return The bundle, or the refusal. +std::expected, morph::ui::Refusal> bundleOf(bool withSignIn) { + ui::ScreenRegistry screens; + auto inbox = screens.add(inboxScreen()); + if (!inbox) { + return std::unexpected(inbox.error()); + } + ui::RegisteredScreen const* signIn = nullptr; + if (withSignIn) { + auto registered = screens.add(signInScreen()); + if (!registered) { + return std::unexpected(registered.error()); + } + signIn = *registered; } morph::ui::UiRegistry served{morph::ui::ApplicationInfo{.id = "lims-approval-inbox-test", .version = "1.0"}, screens.catalog()}; + if (signIn != nullptr) { + morph::ui::CatalogEntry entry; + entry.id = std::string{kSignIn}; + entry.title = "Sign in"; + entry.isPublic = true; + if (auto added = served.addScreen(std::move(entry), signIn->text); !added) { + return std::unexpected(std::move(added.error())); + } + } morph::ui::CatalogEntry entry; entry.id = std::string{kInbox}; entry.title = "Approvals"; - if (auto added = served.addScreen(std::move(entry), (*registered)->text); !added) { + if (auto added = served.addScreen(std::move(entry), (*inbox)->text); !added) { return std::unexpected(std::move(added.error())); } return served.build(); } +} // namespace + +std::expected, morph::ui::Refusal> inboxBundle() { + return bundleOf(false); +} + +std::expected, morph::ui::Refusal> signInBundle() { + return bundleOf(true); +} + struct World::Impl { lims::test::LabFixture fixture; std::optional invoice; diff --git a/examples/lims/screens/tests/approval_inbox_world.hpp b/examples/lims/screens/tests/approval_inbox_world.hpp index eaa7db39d..7fdb5343c 100644 --- a/examples/lims/screens/tests/approval_inbox_world.hpp +++ b/examples/lims/screens/tests/approval_inbox_world.hpp @@ -16,6 +16,9 @@ namespace lims::inboxtest { /// @brief The screen id of the inbox. inline constexpr std::string_view kInbox = "test.approvalInbox"; +/// @brief The screen id of the sign-in that `signInBundle` opens with. +inline constexpr std::string_view kSignIn = "test.approvalSignIn"; + /// @brief A UTC instant on a calendar day. /// @param year The year. /// @param month The month, 1 to 12. @@ -29,6 +32,11 @@ inline constexpr std::string_view kInbox = "test.approvalInbox"; /// @return The bundle, or the refusal. std::expected, morph::ui::Refusal> inboxBundle(); +/// @brief The inbox bundle behind a sign-in screen: any username signs in and lands on the inbox, for a server that +/// authenticates its callers. +/// @return The bundle, or the refusal. +std::expected, morph::ui::Refusal> signInBundle(); + /// @brief A fresh database holding the lab the approval tests run in, destroyed with the object. class World { public: diff --git a/examples/lims/screens/tests/test_lims_approval_inbox.cpp b/examples/lims/screens/tests/test_lims_approval_inbox.cpp index 26527e2dc..4371fd19d 100644 --- a/examples/lims/screens/tests/test_lims_approval_inbox.cpp +++ b/examples/lims/screens/tests/test_lims_approval_inbox.cpp @@ -1,23 +1,30 @@ // SPDX-License-Identifier: Apache-2.0 // // What an approver's inbox is told. Escalation is a deadline the approval rule reads, and no action runs when it -// passes, so nothing tells the inbox. A submission is an action, and its declared effect decides whether an open -// inbox learns of the invoice it gained. +// passes, so the model reports the instant and the server tells the inbox. A submission is an action, and its declared +// effect decides whether an open inbox learns of the invoice it gained. #include #include +#include +#include #include #include #include #include "approval_inbox_world.hpp" #include "clock.hpp" +#include "lims/app/lims_authorizer.hpp" +#include "lims/org/models/org_model.hpp" +#include "lims_screens.hpp" namespace { using lims::inboxtest::at; using lims::inboxtest::inboxBundle; using lims::inboxtest::kInbox; +using lims::inboxtest::kSignIn; +using lims::inboxtest::signInBundle; using lims::inboxtest::World; using morph::examples::testing::RigMode; using morph::examples::testing::ScreenHarness; @@ -25,35 +32,33 @@ using morph::ladder::ScopedClockOverride; } // namespace -// The expected outcome: past the deadline, paula's inbox still lists the invoice she can no longer approve, until it -// asks again. The check sees a refresh the harness's manual scheduler can fire, such as a poll; a refresh driven by a -// real timer is outside the window. Mutations: judge the approval scope at the site whatever the time (the control, -// the refetch showing "0 pending", fails); poll the inbox every second (the check that nothing told the inbox -// fails). -TEST_CASE("approval inbox: a site approver's inbox is not told when an approval's deadline passes", +// Past the deadline, paula's inbox is told and drops the invoice she can no longer approve. The server learns the +// instant from `NextApprovalDeadline`, owns the clock, and tells every watcher of the invoice record when the clock +// reaches it; nothing polls and the harness's manual scheduler is never advanced. The screen runs behind a server that +// authenticates, so paula signs in. Mutations: judge the approval scope at the site whatever the time (the count +// never reads "1 pending" before the deadline's refetch shows "0 pending", so the control after the wait fails); drop +// the server's fan-out at the reported instant (the count stays "1 pending"). +TEST_CASE("approval inbox: a site approver's inbox is told when an approval's deadline passes", "[lims-screens][billing][h4]") { World const world; world.draftInvoice(); world.submitInvoice(); std::optional clock; clock.emplace(at(2026, 11, 12, 8)); - ScreenHarness harness{morph::client::LocalApp{.name = "lims-approval-inbox", .bundle = &inboxBundle, .setUp = {}}, - std::string{kInbox}, - RigMode::Local, - {}, - morph::client::LocalSetup{.db = {}, .user = "paula"}}; + morph::client::LocalApp app{.name = "lims-approval-inbox", .bundle = &signInBundle, .setUp = {}}; + app.setUp = [](morph::client::LocalSetup const& setup) { lims::screens::prepareLocal(setup.user); }; + app.serverAuthorizer = [] { + return std::make_shared( + "lims-local-development", morph::session::hmacSha256, + [](std::string_view principal) { return lims::OrgModel::rolesAnywhere(principal); }); + }; + ScreenHarness harness{app, std::string{kSignIn}, RigMode::Simulated}; + harness.edit("username", "paula"); + harness.click("signIn"); REQUIRE(harness.waitForText("pendingCount", "1 pending")); clock.reset(); - clock.emplace(at(2026, 11, 12, 10)); // the deadline was 09:00 - harness.advance(std::chrono::minutes{10}); // the harness's scheduler is manual: a poll fires only here - bool const told = - harness.waitFor([&harness] { return harness.text("pendingCount") == std::optional{"0 pending"}; }, - std::chrono::milliseconds{1500}); - CHECK_FALSE(told); - - // The control: asked again, the same panel shows the escalation, so the panel can show it. - harness.click("refresh"); + clock.emplace(at(2026, 11, 12, 10)); // the deadline was 09:00 CHECK(harness.waitForText("pendingCount", "0 pending")); CHECK(harness.problems().empty()); } diff --git a/examples/lims/tests/compile_checks/cross_module_effects_probe.cpp b/examples/lims/tests/compile_checks/cross_module_effects_probe.cpp index 4e2a9d3ae..a54104866 100644 --- a/examples/lims/tests/compile_checks/cross_module_effects_probe.cpp +++ b/examples/lims/tests/compile_checks/cross_module_effects_probe.cpp @@ -2,18 +2,20 @@ // // Built twice, linked with every lims module. With LIMS_PROBE_DECLARES_LEDGER_EFFECT it adds, from the composing // code, the declaration billing cannot make: PostInvoice changes the ledger's Ledger_Entry. Either way it reads the -// effects registry once and prints whether the configuration resolved. +// effects registry once and prints whether the configuration resolved; the added build also prints whether the +// action's effects hold both its own `updates` of the invoice and the added `changes` of the entry. +#include #include #include +#include #include "lims/billing/models/invoice_model.hpp" #include "lims/ledger/dto/entry_dto.hpp" #ifdef LIMS_PROBE_DECLARES_LEDGER_EFFECT // NOLINTBEGIN(misc-const-correctness) -BRIDGE_REGISTER_EFFECTS(lims::PostInvoice, ::morph::effects::updates, - ::morph::effects::changes) +BRIDGE_ADD_EFFECTS(lims::PostInvoice, ::morph::effects::changes) // NOLINTEND(misc-const-correctness) #endif @@ -21,7 +23,19 @@ int main() { try { static_cast(::morph::effects::actionsHolding("Billing_Invoice")); std::cout << "effects resolved\n"; +#ifdef LIMS_PROBE_DECLARES_LEDGER_EFFECT + auto const effects = + ::morph::effects::effectsOf("PostInvoice").value_or(std::vector<::morph::effects::Effect>{}); + bool const keepsOwn = std::ranges::contains( + effects, ::morph::effects::Effect{.kind = ::morph::effects::Kind::Updates, .record = "Billing_Invoice"}); + bool const addsEntry = std::ranges::contains( + effects, ::morph::effects::Effect{.kind = ::morph::effects::Kind::Changes, .record = "Ledger_Entry"}); + std::cout << "PostInvoice keeps its own effect: " << keepsOwn + << "\nPostInvoice adds Ledger_Entry: " << addsEntry << '\n'; + return keepsOwn && addsEntry ? 0 : 1; +#else return 0; +#endif } catch (::morph::model::EffectsRegistrationError const& error) { std::cout << error.what() << '\n'; return 1; diff --git a/examples/lims/tests/test_cross_module_effects.cpp b/examples/lims/tests/test_cross_module_effects.cpp index 23b4a7446..78b5781c5 100644 --- a/examples/lims/tests/test_cross_module_effects.cpp +++ b/examples/lims/tests/test_cross_module_effects.cpp @@ -1,8 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // // The cross-module effects question, cause by cause, on watching connections: (i) billing's PostInvoice writes the -// ledger's Ledger_Entry inside itself and cannot declare it; (ii) the relay's billing line reaches a watcher when its -// write is a dispatched action, and not when the same write runs outside any dispatch. +// ledger's Ledger_Entry inside itself, and the composing code declares that effect for it; (ii) the relay's billing +// line reaches a watcher when its write is a dispatched action, and not when the same write runs outside any dispatch. #include #include @@ -59,9 +59,10 @@ namespace { } // namespace -// Cause (i). The control is the ledger's own action on the same connection, which it hears. +// Cause (i). Mutation: drop the union of added effects (the watcher hears nothing within the window). The ledger's own +// action on the same connection is heard either way. TEST_CASE( - "cross-module effects (i): billing's write of a ledger entry inside its own action reaches no ledger " + "cross-module effects (i): billing's write of a ledger entry inside its own action reaches a ledger " "watcher", "[lims][effects]") { lims::test::LabFixture const fixture; @@ -77,7 +78,7 @@ TEST_CASE( REQUIRE(posted.state == lims::InvoiceState::Posted); bool const heard = ServerConnection::eventually([&] { return accountant->heardOf("Ledger_Entry"); }, std::chrono::milliseconds{1500}); - CHECK_FALSE(heard); + CHECK(heard); // The control: the ledger's own action, dispatched on the same server, is heard on the same connection. auto const ledger = accountant->registerModel("LedgerModel", as("acc")); diff --git a/examples/lims/tests/test_invoice_posting.cpp b/examples/lims/tests/test_invoice_posting.cpp index 9f13e9ce2..4251615a6 100644 --- a/examples/lims/tests/test_invoice_posting.cpp +++ b/examples/lims/tests/test_invoice_posting.cpp @@ -263,8 +263,9 @@ TEST_CASE("Hypothesis 1: in one shared transaction, a failure between the halves } // What each way keeps of the ledger's own action: its authorization, its effect on a watching connection, its journal -// entry. The control is billing's own effect, which both keep. Mutation: declare RecordPosting with no effect (the -// dispatched case's Ledger_Entry check fails). +// entry. The control is billing's own effect, which both keep. The ledger's effect reaches a watcher in both ways: the +// dispatched one runs the ledger's action, and the shared transaction's is declared by the app that composes billing +// and the ledger. Mutation: declare RecordPosting with no effect (the dispatched case's Ledger_Entry check fails). TEST_CASE("Hypothesis 1: what the shared transaction gives up of the ledger's action", "[lims][billing][posting][h1]") { auto const mode = GENERATE(PostingMode::Dispatched, PostingMode::SharedTransaction); @@ -304,7 +305,7 @@ TEST_CASE("Hypothesis 1: what the shared transaction gives up of the ledger's ac CHECK(ServerConnection::eventually([&] { return clerk->heardOf("Billing_Invoice"); })); bool const ledgerHeard = ServerConnection::eventually([&] { return accountant->heardOf("Ledger_Entry"); }, std::chrono::milliseconds{1500}); - CHECK(ledgerHeard == dispatched); + CHECK(ledgerHeard); CHECK(journal->holds("InvoiceModel", "PostInvoice")); CHECK(journal->holds("LedgerModel", "RecordPosting") == dispatched); } diff --git a/examples/lims/tests/test_ledger_entries.cpp b/examples/lims/tests/test_ledger_entries.cpp index 3b75b5ad5..2dd908250 100644 --- a/examples/lims/tests/test_ledger_entries.cpp +++ b/examples/lims/tests/test_ledger_entries.cpp @@ -1534,10 +1534,14 @@ void writeJournal(lims::PeriodId period, std::vector const& rows) { // Mutations: drop the plan's filters from the statement (translate returns "1" for the filter); order empty cells // first; render an exclude as NOT (cell condition) without COALESCE; round an integer operand; drop the Latin-1 fold; // order by the transaction-time seconds without the floor. -TEST_CASE( - "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " - "filter the journal offers", - "[lims][ledger][pages]") { +namespace { + +// The corpus is split into this many test cases, each comparing every `kCorpusParts`-th query: a page costs a load per +// row, and the whole corpus in one case outlasts a test's time limit under the sanitizers. +constexpr std::size_t kCorpusParts = 4; + +// Compares the queries at @p part, @p part + kCorpusParts, ... of the corpus. +void checkEntryPagesAgainstEngine(std::size_t part) { DbFixture fixture; auto const period = books(); writeJournal(period.id, journalRows()); @@ -1556,6 +1560,11 @@ TEST_CASE( for (auto&& query : groupQueries()) { corpus.push_back(std::move(query)); } + decltype(corpus) slice; + for (std::size_t i = part; i < corpus.size(); i += kCorpusParts) { + slice.push_back(std::move(corpus.at(i))); + } + REQUIRE_FALSE(slice.empty()); morph::table::ConformanceOptions options; options.limits.totalCap = 10; @@ -1573,17 +1582,47 @@ TEST_CASE( out.offset = page.offset; return out; }; - auto const failures = morph::table::conformanceFailures(source, model, corpus, options); + auto const failures = morph::table::conformanceFailures(source, model, slice, options); for (std::size_t i = 0; i < failures.size() && i < 10; ++i) { WARN(failures[i]); } CHECK(failures.empty()); } -// The control for the case above: the journal and the corpus compare what the helper is said to compare. Every column +} // namespace + +TEST_CASE( + "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " + "filter the journal offers (part 1 of 4)", + "[lims][ledger][pages]") { + checkEntryPagesAgainstEngine(0); +} + +TEST_CASE( + "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " + "filter the journal offers (part 2 of 4)", + "[lims][ledger][pages]") { + checkEntryPagesAgainstEngine(1); +} + +TEST_CASE( + "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " + "filter the journal offers (part 3 of 4)", + "[lims][ledger][pages]") { + checkEntryPagesAgainstEngine(2); +} + +TEST_CASE( + "ledger: a page of entries from the database equals the engine's page over the same rows, for every sort and " + "filter the journal offers (part 4 of 4)", + "[lims][ledger][pages]") { + checkEntryPagesAgainstEngine(3); +} + +// The control for the cases above: the journal and the corpus compare what the helper is said to compare. Every column // the database can translate is filtered, somewhere in the corpus, by a query the plan accepts and whose view is // neither empty nor the whole journal, except the company, which every entry shares. The standard quick-search group -// spans `lines` and is refused as Unavailable, so the group queries of the case above are the ones that are compared. +// spans `lines` and is refused as Unavailable, so the group queries of the cases above are the ones that are compared. TEST_CASE("ledger: the entry page refuses the columns the database cannot compare, and nothing else", "[lims][ledger][pages]") { DbFixture fixture; diff --git a/examples/lims/tests/test_requisitions.cpp b/examples/lims/tests/test_requisitions.cpp index 52af6eef0..8ffef4b84 100644 --- a/examples/lims/tests/test_requisitions.cpp +++ b/examples/lims/tests/test_requisitions.cpp @@ -2,7 +2,7 @@ // // Hypothesis 5, second instance: a requisition is raised, submitted and approved as ordinary actions on its row, four // eyes and a value limit per role hold, its approval escalates from the site to the company at its deadline, and -// an open approvals inbox is not told when the deadline passes. +// an open approvals inbox is told when the deadline passes. #include #include @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -247,40 +248,31 @@ TEST_CASE("Hypothesis 5: a requisition submitted on one rig is approved on anoth } } -// The second time this is measured (decision 35 is the first): nothing tells an open inbox that a deadline passed. -// The witness is anna, a site approver, whose pending list loses the requisition at the deadline. The control is in -// the case: after the silence, a requisition raised through the server reaches the same connection, so the -// connection can hear a change of the record and the silence before it is the measurement. Mutation: watch a record -// name no record has ("Inventory_Requisitions"): the silence still holds, and the control's CHECK fails. -TEST_CASE("requisitions: an approver's open inbox is not told when a deadline passes", +// An open inbox is told when a deadline passes. The witness is anna, a site approver, whose pending list loses the +// requisition at the deadline; the server learns the instant from `NextRequisitionDeadline`, owns the clock, and tells +// the connection watching `Inventory_Requisition` when the clock reaches it. Before the deadline the connection is +// told nothing, so the message after it is the deadline's. Mutation: drop the server's fan-out at the reported +// instant (the connection is told nothing and the check after the deadline fails). +TEST_CASE("requisitions: an approver's open inbox is told when a deadline passes", "[lims][inventory][requisition][effects]") { DbFixture fixture; auto const setUp = lims::test::requisitionSetUp(); static_cast(submitted(setUp.draft)); + std::optional clock; + clock.emplace(at(2026, 11, 11)); BackendRig rig{Mode::Socket, 0, lims::test::limsAuthorizer(kSecret)}; auto const anna = rig.connect(); REQUIRE(anna->watch({"Inventory_Requisition"}, as("anna")).kind == "ok"); - { - ScopedClockOverride const before{at(2026, 11, 11)}; - REQUIRE(pendingFor("anna") == std::vector{*setUp.draft.id}); - } + REQUIRE(pendingFor("anna") == std::vector{*setUp.draft.id}); auto const heardBefore = anna->changes().size(); - ScopedClockOverride const past{at(2026, 11, 12, 10)}; - bool const told = ServerConnection::eventually([&] { return anna->changes().size() > heardBefore; }, - std::chrono::milliseconds{1000}); - CHECK_FALSE(told); - CHECK(pendingFor("anna").empty()); - // The control: a change of the same record, made through the server after the deadline, is heard. - auto const rita = rig.connect(); - auto const procurement = rita->registerModel("ProcurementModel", as("rita")); - REQUIRE(procurement != 0); - auto const body = glz::write_json(lims::CreateRequisition{.company = lims::test::seededCompany(), - .site = lims::test::seededSite(), - .reason = "control"}) - .value_or(std::string{}); - REQUIRE(rita->execute(procurement, "ProcurementModel", "CreateRequisition", body, as("rita")).kind == "ok"); + CHECK_FALSE(ServerConnection::eventually([&] { return anna->changes().size() > heardBefore; }, + std::chrono::milliseconds{300})); + + clock.reset(); + clock.emplace(at(2026, 11, 12, 10)); // past the requisition's deadline CHECK(ServerConnection::eventually([&] { return anna->changes().size() > heardBefore; }, - std::chrono::milliseconds{1000})); + std::chrono::milliseconds{3000})); + CHECK(pendingFor("anna").empty()); } namespace { diff --git a/examples/lims_gallery/src/screens/console.cpp b/examples/lims_gallery/src/screens/console.cpp index 8929ddf4b..1f66e182b 100644 --- a/examples/lims_gallery/src/screens/console.cpp +++ b/examples/lims_gallery/src/screens/console.cpp @@ -572,7 +572,7 @@ ui::Node worklistTable(Console const& console, ui::AnyHandle const& rows, std::s {.name = "test", .label = "Test", .width = ui::content(), .wrap = false}, {.name = "priority", .label = "Priority", - .width = ui::fixed(7), + .width = ui::content(), .cell = layout::priorityTag(ui::row("priority"))}, {.name = "due", .label = "Due", .width = ui::fixed(12), .cell = dueCell(), .wrap = false}, {.name = "status", diff --git a/examples/lims_gallery/src/screens/results.cpp b/examples/lims_gallery/src/screens/results.cpp index 1985a73f2..e828167ae 100644 --- a/examples/lims_gallery/src/screens/results.cpp +++ b/examples/lims_gallery/src/screens/results.cpp @@ -416,7 +416,8 @@ ui::Node suitability() { {.gap = 1, .align = Align::Center}) .testId(std::string{"suitability-"} + check.name)); } - return ui::panel({ui::row(checks, {.gap = 4, .align = Align::Center})}, {.padding = 1}).testId("suitability"); + return ui::panel({ui::row(checks, {.gap = 4, .align = Align::Center, .wrap = true})}, {.padding = 1}) + .testId("suitability"); } ui::Node resultInput(Worksheet const& sheet, Evaluation const& evaluation, Field const& field) { @@ -467,7 +468,7 @@ ui::Node resultTable(Worksheet const& sheet) { .cell = ui::text({.text = ui::row("spec")})}, {.name = "evaluation", .label = "Evaluation", - .width = ui::fixed(26), + .width = ui::fixed(27), .cell = evaluationCell(sheet, evaluation)}}; return ui::table( sheet.lines, diff --git a/examples/lims_gallery/src/screens/samples.cpp b/examples/lims_gallery/src/screens/samples.cpp index 8edc66250..bd03d3640 100644 --- a/examples/lims_gallery/src/screens/samples.cpp +++ b/examples/lims_gallery/src/screens/samples.cpp @@ -517,7 +517,7 @@ ui::Node samplesTable(Samples const& list) { {.name = "tests", .label = "Tests", .width = ui::stretch(4)}, {.name = "priority", .label = "Priority", - .width = ui::fixed(7), + .width = ui::content(), .cell = layout::priorityTag(ui::row("priority"))}, {.name = "status", .label = "Status", diff --git a/examples/lims_gallery/src/screens/stability.cpp b/examples/lims_gallery/src/screens/stability.cpp index 4d28689ed..b94ed454f 100644 --- a/examples/lims_gallery/src/screens/stability.cpp +++ b/examples/lims_gallery/src/screens/stability.cpp @@ -598,11 +598,13 @@ ui::Node expandedConditions(Study const& study) { {.padding = 2}) .testId("conditions-card"); auto const aside = ui::panel({summary(study)}, {.title = "Summary", .padding = 3}) - // 26 % of the row, at most 33 units: 250 px on the 1000 px page. No floor: on the 785 px - // page the share is wide enough for the longest value segment beside the 13-unit caption - // column, so none breaks; the conditions' labels wrap between words there. + // 26 % of the row, at least 36 and at most 38 units: 250 px on the 1000 px page. The + // floor keeps the longest value beside the 13-unit caption column whole in a font + // wider than the default, where 26 % of the 785 px page is too narrow; the conditions' + // labels wrap between words there. .sizing(ui::percent(26)) - .maxWidth(33) + .minWidth(36) + .maxWidth(38) .a11y("Summary") .testId("summary-panel"); return ui::row( diff --git a/examples/lims_gallery/tests/test_console.cpp b/examples/lims_gallery/tests/test_console.cpp index 9b3825720..3cee22e2a 100644 --- a/examples/lims_gallery/tests/test_console.cpp +++ b/examples/lims_gallery/tests/test_console.cpp @@ -30,7 +30,7 @@ TEST_CASE("console, expanded: navigation, alert, figures, chart, instruments and CHECK(screen.backend().find("Text", "text", "% LC").has_value()); // The Test column takes its text whole and Status, last, takes what is left, so the table does not scroll. CHECK(screen.prop("Table", "worklist", "columns").value_or("none") == - "[Sample:fixed(11),Test:content;wrap=false,Priority:fixed(7),Due:fixed(12);wrap=false,Status:stretch(1);" + "[Sample:fixed(11),Test:content;wrap=false,Priority:content,Due:fixed(12);wrap=false,Status:stretch(1);" "shrink=true]"); // The operator stays with its number when the label wraps: the space between them does not break. CHECK(screen.backend().find("Text", "text", "Impurity A · ≤\u00a00.10").has_value()); diff --git a/examples/lims_gallery/tests/test_samples.cpp b/examples/lims_gallery/tests/test_samples.cpp index 8b7ac6e3b..b00df2d08 100644 --- a/examples/lims_gallery/tests/test_samples.cpp +++ b/examples/lims_gallery/tests/test_samples.cpp @@ -40,7 +40,7 @@ TEST_CASE("samples, expanded: the table, its out-of-spec tone, and three rows se screen.requireNoProblems(); CHECK(screen.shows("Table", "samples")); CHECK(screen.prop("Table", "samples", "columns") == - "[Sample:fixed(11);sortable=true,Product · lot:stretch(6),Tests:stretch(4),Priority:fixed(7)," + "[Sample:fixed(11);sortable=true,Product · lot:stretch(6),Tests:stretch(4),Priority:content," "Status:fixed(11),Due:fixed(12);sortable=true;wrap=false,Specification:fixed(12)]"); // Sorted by due time, earliest first, 25 rows a page. CHECK(screen.prop("Table", "samples", "sort") == "5:Ascending"); diff --git a/examples/lims_gallery/tests/test_stability.cpp b/examples/lims_gallery/tests/test_stability.cpp index 9f2639b17..b06edaeff 100644 --- a/examples/lims_gallery/tests/test_stability.cpp +++ b/examples/lims_gallery/tests/test_stability.cpp @@ -44,7 +44,7 @@ TEST_CASE("stability, expanded: step 2 of the wizard, the matrix and the summary CHECK(screen.prop("Steps", "steps", "current") == "1"); CHECK(screen.shows("Table", "matrix")); // The summary is a share of the row, capped at the mockup's width. - CHECK(screen.prop("Panel", "summary-panel", "layout").value_or("none").starts_with("percent(26) max=33/")); + CHECK(screen.prop("Panel", "summary-panel", "layout").value_or("none").starts_with("percent(26) min=36 max=38/")); CHECK(screen.backend().prop(monthBox(screen, "25\u00a0°C", "T0"), "checked") == "true"); CHECK(screen.backend().prop(monthBox(screen, "25\u00a0°C", "1 m"), "checked") == "false"); // The summary's captions take the design's 13-unit column. diff --git a/include/morph/core/changes.hpp b/include/morph/core/changes.hpp index d5e514f05..ea7a734ec 100644 --- a/include/morph/core/changes.hpp +++ b/include/morph/core/changes.hpp @@ -250,6 +250,19 @@ inline void addUpdatesChange(Resolved const& resolved, std::string_view actionId return changes; } +/// @brief The whole-type changes of @p records, and of every record derived from them. +/// @param resolved The resolved registries. +/// @param records The changed records' wire names. +/// @return The changes. +[[nodiscard]] inline Changes wholeTypeChanges(Resolved const& resolved, std::vector const& records) { + Changes changes; + for (auto const& record : records) { + addRecordChange(changes, record, std::nullopt); + addDerivedChanges(resolved, record, changes); + } + return changes; +} + } // namespace detail /// @brief The changes a successful execute made, from the action's declared effects and its result. diff --git a/include/morph/core/effects.hpp b/include/morph/core/effects.hpp index 6e1f0dd19..af7618df4 100644 --- a/include/morph/core/effects.hpp +++ b/include/morph/core/effects.hpp @@ -19,6 +19,7 @@ #include #include +#include "../util/datetime.hpp" #include "detail/result_walker.hpp" #include "records.hpp" #include "registry.hpp" @@ -124,6 +125,22 @@ struct ActionRecord { friend bool operator==(ActionRecord const& lhs, ActionRecord const& rhs) = default; }; +/// @brief An action that reports when records change by the passage of time alone. +struct ChangeTimeSource { + /// The reporting action's id. + std::string action; + /// The type id of the model the action belongs to; a fresh instance of it answers. + std::string model; + /// The wire names of the records that change at the reported instant. + std::vector records; + + /// @brief Memberwise equality. + /// @param lhs One source. + /// @param rhs The other. + /// @return True when action, model and records match. + friend bool operator==(ChangeTimeSource const& lhs, ChangeTimeSource const& rhs) = default; +}; + namespace detail { /// @brief One effect as a registrar records it: the record still a type, not yet a name. @@ -143,6 +160,27 @@ struct DeclaredEffect { /// @brief Every distinct effects declaration, by action id. More than one for an id is a conflict. using EffectsMap = std::map>, std::less<>>; +/// @brief The effects added to each action by the code that composes its module with others, by action id. +/// +/// Apart from `EffectsMap`: an addition is never in conflict with a base declaration, it is unioned with it. +using AddedEffectsMap = std::map, std::less<>>; + +/// @brief One time-derived fact as a registrar records it: the records still types, not yet names. +struct DeclaredChangeTime { + /// The reporting action's id. + std::string action; + /// The model's type id. + std::string model; + /// The record types. + std::vector records; + + /// @brief Memberwise equality. + /// @param lhs One declaration. + /// @param rhs The other. + /// @return True when action, model and records match. + friend bool operator==(DeclaredChangeTime const& lhs, DeclaredChangeTime const& rhs) = default; +}; + /// @brief Maps an effect tag type to its `DeclaredEffect`. /// @tparam E An effect tag. template @@ -203,6 +241,23 @@ inline void addEffects(EffectsMap& map, std::string_view actionId, std::vector const& added) { + auto entry = map.find(actionId); + if (entry == map.end()) { + entry = map.emplace(std::string{actionId}, std::vector{}).first; + } + for (auto const& effect : added) { + if (std::ranges::find(entry->second, effect) == entry->second.end()) { + entry->second.push_back(effect); + } + } +} + /// @brief The process-level effects registry, appended to by static registrars. /// @return The mutable map. inline EffectsMap& mutableEffectsRegistry() { @@ -228,6 +283,75 @@ inline bool registerEffectsOnce() noexcept { return true; } +/// @brief The process-level list of time-derived facts, appended to by static registrars. +/// @return The mutable list. +inline std::vector& mutableChangeTimesRegistry() { + static std::vector entries; + return entries; +} + +/// @brief Adds a time-derived fact, unless an equal one is already there. +/// @param list The registry to add to. +/// @param declared The fact. +inline void addChangeTime(std::vector& list, DeclaredChangeTime declared) { + if (std::ranges::find(list, declared) == list.end()) { + list.push_back(std::move(declared)); + } +} + +/// @brief Static-init helper for `BRIDGE_REGISTER_CHANGES_AT`. +/// @tparam Model The model the action belongs to. +/// @tparam Action The reporting action; its result must be `std::optional`. +/// @tparam Records The record types that change at the reported instant. +/// @return Always true, so the result can initialise a namespace-scope variable. +template +inline bool registerChangeTimeOnce() noexcept { + static_assert(sizeof...(Records) > 0, "BRIDGE_REGISTER_CHANGES_AT: name at least one record"); + static_assert( + std::is_same_v::Result, std::optional<::morph::time::DateTime>>, + "BRIDGE_REGISTER_CHANGES_AT: the action must return std::optional"); + // NOLINTNEXTLINE(misc-static-assert,cert-dcl03-c) + assert(!::morph::model::registrationPhaseClosed() && + "registerChangeTimeOnce: registration after the registration phase closed. The process-level " + "registries are unsynchronised and are read-only once dispatch begins -- registering now " + "races their internals against concurrent lookups. Load and register plugin modules before " + "the first dispatch."); + addChangeTime(mutableChangeTimesRegistry(), + DeclaredChangeTime{ + .action = std::string{::morph::model::ActionTraits::typeId()}, + .model = std::string{::morph::model::ModelTraits::typeId()}, + .records = {std::type_index{typeid(Records)}...}, + }); + return true; +} + +/// @brief The process-level registry of added effects, appended to by static registrars. +/// @return The mutable map. +inline AddedEffectsMap& mutableAddedEffectsRegistry() { + static AddedEffectsMap entries; + return entries; +} + +/// @brief Static-init helper for `BRIDGE_ADD_EFFECTS`. +/// @tparam Action The action type; `ActionTraits` must be visible. +/// @tparam E The effect tags. +/// @return Always true, so the result can initialise a namespace-scope variable. +template +inline bool registerAddedEffectsOnce() noexcept { + static_assert(sizeof...(E) > 0, "BRIDGE_ADD_EFFECTS: add at least one effect"); + static_assert((!std::is_same_v && ...), + "BRIDGE_ADD_EFFECTS: an addition adds an effect, and none is the absence of one"); + // NOLINTNEXTLINE(misc-static-assert,cert-dcl03-c) + assert(!::morph::model::registrationPhaseClosed() && + "registerAddedEffectsOnce: registration after the registration phase closed. The process-level " + "registries are unsynchronised and are read-only once dispatch begins -- registering now " + "races their internals against concurrent lookups. Load and register plugin modules before " + "the first dispatch."); + addAddedEffects(mutableAddedEffectsRegistry(), ::morph::model::ActionTraits::typeId(), + std::vector{EffectOf::value()...}); + return true; +} + /// @brief The matched and validated registries: what every read is answered from. struct Resolved { /// @brief The records, one entry per registered type, in registration order. @@ -238,6 +362,8 @@ struct Resolved { std::map, std::less<>> actionRecords; /// @brief The ids of the actions holding each record, by record name, in id order. std::map, std::less<>> holding; + /// @brief The actions that report when records change by time alone, in registration order. + std::vector changeTimes; /// @brief See `morph::effects::effectsOf`. /// @param actionId The action's id. @@ -345,11 +471,15 @@ inline void findDerivationCycles(std::vector const& records, /// @param resultSlots Every action's result slots, by action id. /// @param declared Every action's effects declarations, by action id. /// @param slotConflicts Action ids registered by more than one action type. +/// @param added Every action's added effects, by action id. +/// @param changeTimes Every time-derived fact. /// @return The resolved registries. /// @throws morph::model::EffectsRegistrationError listing every problem, when there is one. [[nodiscard]] inline Resolved resolve(std::vector records, model::detail::ActionResultSlotMap const& resultSlots, - EffectsMap const& declared, std::vector const& slotConflicts) { + EffectsMap const& declared, std::vector const& slotConflicts, + AddedEffectsMap const& added, + std::vector const& changeTimes) { std::vector problems; // An identical registration, as a record registered in a header gives once per translation unit, is @@ -437,16 +567,42 @@ inline void findDerivationCycles(std::vector const& records, } } - for (auto const& [actionId, declarations] : declared) { - if (declarations.size() > 1) { + // Every action with a base declaration or an addition. An addition for an id no action registered is refused. + std::map> actionIds; + for (auto const& entry : declared) { + actionIds.emplace(entry.first, 0); + } + for (auto const& entry : added) { + actionIds.emplace(entry.first, 0); + if (!resultSlots.contains(entry.first)) { + problems.push_back("effects are added to action `" + entry.first + "`, which is not a registered action"); + } + } + for (auto const& idEntry : actionIds) { + std::string const& actionId = idEntry.first; + auto const base = declared.find(actionId); + if (base != declared.end() && base->second.size() > 1) { problems.push_back("action `" + actionId + "` declares different effects in two registrations"); continue; } - auto const& declaration = declarations.front(); - if (declaration.size() > 1 && - std::ranges::any_of(declaration, [](DeclaredEffect const& effect) { return effect.kind == Kind::None; })) { - problems.push_back("action `" + actionId + "` declares none together with other effects"); - continue; + std::vector declaration; + if (base != declared.end()) { + declaration = base->second.front(); + if (declaration.size() > 1 && std::ranges::any_of(declaration, [](DeclaredEffect const& effect) { + return effect.kind == Kind::None; + })) { + problems.push_back("action `" + actionId + "` declares none together with other effects"); + continue; + } + } + // An addition changes something, so a base `none` does not stand beside it; no other base effect is dropped. + if (auto const addition = added.find(actionId); addition != added.end()) { + std::erase_if(declaration, [](DeclaredEffect const& effect) { return effect.kind == Kind::None; }); + for (auto const& effect : addition->second) { + if (std::ranges::find(declaration, effect) == declaration.end()) { + declaration.push_back(effect); + } + } } std::vector effects; for (auto const& effect : declaration) { @@ -479,6 +635,29 @@ inline void findDerivationCycles(std::vector const& records, resolved.effects.emplace(actionId, std::move(effects)); } + for (auto const& fact : changeTimes) { + if (!resultSlots.contains(fact.action)) { + problems.push_back("`" + fact.action + + "` reports when records change by time, but is not a registered action"); + continue; + } + if (resolved.effects.contains(fact.action)) { + problems.push_back("`" + fact.action + + "` reports when records change by time, so it reads, and it also declares effects"); + } + ChangeTimeSource source{.action = fact.action, .model = fact.model, .records = {}}; + for (auto const& type : fact.records) { + auto const found = indexOf.find(type); + if (found == indexOf.end()) { + problems.push_back("`" + fact.action + "` reports when " + type.name() + + " changes by time, which is not a registered record"); + continue; + } + source.records.push_back(records.at(found->second).name); + } + resolved.changeTimes.push_back(std::move(source)); + } + if (!problems.empty()) { throw model::EffectsRegistrationError(std::move(problems)); } @@ -491,13 +670,17 @@ inline void findDerivationCycles(std::vector const& records, /// @param resultSlots The action result slots, by action id. /// @param declared The effects declarations, by action id. /// @param slotConflicts Action ids registered by more than one action type. +/// @param added The added effects, by action id. +/// @param changeTimes The time-derived facts. /// @return The resolved registries. /// @throws morph::model::EffectsRegistrationError listing every problem, when there is one. [[nodiscard]] inline Resolved resolveForTesting(std::vector records, model::detail::ActionResultSlotMap const& resultSlots, EffectsMap const& declared, - std::vector const& slotConflicts = {}) { - return resolve(std::move(records), resultSlots, declared, slotConflicts); + std::vector const& slotConflicts = {}, + AddedEffectsMap const& added = {}, + std::vector const& changeTimes = {}) { + return resolve(std::move(records), resultSlots, declared, slotConflicts, added, changeTimes); } /// @brief The process registries, matched and validated on the first call. @@ -519,7 +702,8 @@ inline void findDerivationCycles(std::vector const& records, std::call_once(state.once, [] { try { state.value.emplace(resolve(record::detail::recordRegistry(), model::detail::actionResultSlots(), - mutableEffectsRegistry(), model::detail::actionResultConflicts())); + mutableEffectsRegistry(), model::detail::actionResultConflicts(), + mutableAddedEffectsRegistry(), mutableChangeTimesRegistry())); } catch (model::EffectsRegistrationError const& error) { state.error.emplace(error); } @@ -540,6 +724,11 @@ inline void findDerivationCycles(std::vector const& records, return detail::resolved().effectsOf(actionId); } +/// @brief The actions that report when records change by time alone, with the records each names. +/// @return One entry per reporter, in registration order. +/// @throws morph::model::EffectsRegistrationError when the registered configuration is invalid. +[[nodiscard]] inline std::vector changeTimesOf() { return detail::resolved().changeTimes; } + /// @brief The records an action's result holds, with the paths to each. /// /// Each path stops at the first registered record on it, so the members of a @@ -591,4 +780,51 @@ inline void findDerivationCycles(std::vector const& records, morph::effects::detail::registerEffectsOnce(); \ } #endif + +/// @def BRIDGE_REGISTER_CHANGES_AT +/// @brief Registers action @p A of model @p M as the reporter of the next instant at which the listed records +/// change by the passage of time alone, with no action behind it. +/// +/// @p A returns `std::optional`: the next such instant, strictly after the model's own +/// now, or `nullopt` when none is pending. It is a read: it declares no effects and takes no fields. The server +/// asks it, owns the clock, and at that instant marks the records changed as an action's `changes` would, then +/// asks again; the model arms no timer and posts no work. A reporter that is not a registered action, that also +/// declares effects, or that names an unregistered record is refused on the first read. Repeating the same +/// registration is a no-op. Expands to nothing under `MORPH_CLIENT_ONLY`. +/// @param M The model type. +/// @param A The reporting action type. +/// @param ... The record types. +#ifdef MORPH_CLIENT_ONLY +#define BRIDGE_REGISTER_CHANGES_AT(M, A, ...) +#else +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage): a registration macro is the public API. +#define BRIDGE_REGISTER_CHANGES_AT(M, A, ...) \ + namespace { \ + [[maybe_unused]] const bool BRIDGE_DETAIL_CAT(bridge_change_time_reg_, __COUNTER__) = \ + morph::effects::detail::registerChangeTimeOnce(); \ + } +#endif + +/// @def BRIDGE_ADD_EFFECTS +/// @brief Adds effects to action @p A from the code that composes its module with the module that owns the +/// record: any of `morph::effects::updates`, `changes` and `changesInstance`. +/// +/// The action's own module cannot name a record of a module it does not include, and a second +/// `BRIDGE_REGISTER_EFFECTS` for the action is refused, so the composing code, which includes both, adds the +/// effect here. The addition is unioned with the action's own declaration and never removes an effect; `none` is +/// refused at compile time. An addition for an action nobody registered, or for a record nobody registered, is +/// refused on the first read, never ignored. Repeating an addition is a no-op. Place it in a translation unit +/// that is always linked into the server. Expands to nothing under `MORPH_CLIENT_ONLY`. +/// @param A The action type. +/// @param ... The effects to add. +#ifdef MORPH_CLIENT_ONLY +#define BRIDGE_ADD_EFFECTS(A, ...) +#else +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage): a registration macro is the public API. +#define BRIDGE_ADD_EFFECTS(A, ...) \ + namespace { \ + [[maybe_unused]] const bool BRIDGE_DETAIL_CAT(bridge_added_effects_reg_, __COUNTER__) = \ + morph::effects::detail::registerAddedEffectsOnce(); \ + } +#endif // NOLINTEND(bugprone-throwing-static-initialization,cert-err58-cpp,misc-anonymous-namespace-in-header,cert-dcl59-cpp) diff --git a/include/morph/core/remote.hpp b/include/morph/core/remote.hpp index 505a32582..72ea6fc5e 100644 --- a/include/morph/core/remote.hpp +++ b/include/morph/core/remote.hpp @@ -30,6 +30,7 @@ #include "../core/backend.hpp" #include "../journal/action_log.hpp" #include "../session/session.hpp" +#include "../util/datetime.hpp" #include "changes.hpp" #include "completion.hpp" #include "connection_writer.hpp" @@ -356,6 +357,20 @@ struct ServerConfig { /// queued. Zero sends each fan-out's event at once, unmerged. Negative is /// refused by the constructor. std::chrono::milliseconds coalesceWindow{50}; + + /// @brief The server's "now", read when it waits for an instant a model reported + /// (`BRIDGE_REGISTER_CHANGES_AT`). Empty: `morph::time::DateTime::now()`. + /// + /// A test supplies a clock it advances by hand, so a deadline passes without a sleep. The model reports its + /// instants from the same clock. + std::function<::morph::time::DateTime()> clock; + + /// @brief The longest the server sleeps before reading `clock` again while it waits for a reported instant. + /// + /// A system clock can be set and an injected one is advanced by a test, neither of which a sleep notices, so + /// the instant is judged by reading `clock`, never by the length of the sleep. Not positive is refused by the + /// constructor. + std::chrono::milliseconds clockRecheck{1000}; }; /// @brief Server-side message handler that owns model instances and dispatches actions. @@ -831,6 +846,7 @@ class RemoteServer : public std::enable_shared_from_this { void fanOut(::morph::effects::Changes changes, ConnectionId caller, std::string_view callerPrincipal) { assert(_strand.runningHere() && "RemoteServer::fanOut runs on the server strand"); noteOwner("RemoteServer::fanOut"); + askTimeFactsNamedIn(changes); std::map bodies; for (auto const& change : changes.records) { for (ConnectionId const cid : _watches.watchersOf(change.record)) { @@ -983,12 +999,182 @@ class RemoteServer : public std::enable_shared_from_this { if (config.coalesceWindow.count() < 0) { throw std::invalid_argument("ServerConfig: coalesceWindow must not be negative"); } + if (config.clockRecheck.count() <= 0) { + throw std::invalid_argument("ServerConfig: clockRecheck must be positive"); + } if (std::ranges::find(config.services, nullptr) != config.services.end()) { throw std::invalid_argument("ServerConfig: services must not hold a null entry"); } return config; } + /// One reporter of a time-derived fact, and what the server knows of it. Server strand state. + struct TimeFact { + ::morph::effects::ChangeTimeSource source; + /// The instant the model last reported; empty while none is pending or an ask is in flight. + std::optional<::morph::time::DateTime> next; + /// The instant most recently fanned out; a report at or before it is the model's own clock running ahead + /// of the server's, and is ignored, so one instant never fires twice. + std::optional<::morph::time::DateTime> fired; + /// An ask is running on a model strand. + bool asking{false}; + /// A change arrived while an ask ran, whose answer may predate it. + bool askAgain{false}; + /// The timer armed for `next`, and the number its wake-up carries. + ::morph::async::detail::TimeoutScheduler::Handle timer{0}; + std::uint64_t wake{0}; + }; + + /// @brief The server's "now". + /// @return `ServerConfig::clock`, or the system clock when none is configured. + [[nodiscard]] ::morph::time::DateTime now() const { + return _config.clock ? _config.clock() : ::morph::time::DateTime::now(); + } + + /// @brief Begins asking every reporter this server can run for its instant, once, on the first envelope the + /// server handles. + /// + /// Not in the constructor: asking runs model code, and a task needs the server held by a `shared_ptr`. A reporter + /// whose model this server's registry does not hold is skipped: the declarations are process-wide, the registry is + /// this server's, and an ask it cannot answer would only be a model-strand task outliving whoever owns it. + /// On the server strand. + void startTimeFacts() { + if (_timeFactsStarted) { + return; + } + _timeFactsStarted = true; + for (auto const& source : ::morph::effects::detail::resolved().changeTimes) { + if (_registry.contains(source.model)) { + _timeFacts.push_back(TimeFact{.source = source}); + } + } + for (std::size_t index = 0; index < _timeFacts.size(); ++index) { + askTimeFact(index); + } + } + + /// @brief Asks again every reporter that names a record @p changes holds: its next instant may have moved. + /// @param changes What is about to be fanned out. On the server strand. + void askTimeFactsNamedIn(::morph::effects::Changes const& changes) { + for (std::size_t index = 0; index < _timeFacts.size(); ++index) { + auto const& named = _timeFacts.at(index).source.records; + bool const touched = + std::ranges::any_of(changes.records, [&](::morph::effects::RecordChange const& change) { + return std::ranges::find(named, change.record) != named.end(); + }); + if (touched) { + askTimeFact(index); + } + } + } + + /// @brief Runs reporter @p index on a fresh instance of its model and takes its answer back to the strand. + /// + /// One ask runs at a time; a request made during one is remembered and asks once more when it ends. The ask + /// runs on a model strand, never the server's, so a model that reads a database does not hold up the server. + /// @param index The reporter's place in `_timeFacts`. On the server strand. + void askTimeFact(std::size_t index) { + TimeFact& fact = _timeFacts.at(index); + if (fact.asking) { + fact.askAgain = true; + return; + } + fact.asking = true; + fact.next.reset(); + _strands->post(nextOpaqueId(), [self = shared_from_this(), index, source = fact.source] { + std::optional<::morph::time::DateTime> reported; + try { + auto holder = self->_registry.create(source.model); + std::string const result = self->_dispatcher.dispatch(source.model, source.action, *holder, "{}"); + if (auto const error = glz::read_json(reported, result)) { + reported.reset(); + ::morph::log::logError("[timeFacts] {} answered {}: not an instant", source.action, result); + } + } catch (const std::exception& exc) { + ::morph::log::logError("[timeFacts] {} not answered: {}", source.action, exc.what()); + } catch (...) { + ::morph::log::logError("[timeFacts] {} not answered: unknown exception", source.action); + } + self->_strand.postTask([self, index, reported] { self->timeFactAnswered(index, reported); }); + }); + } + + /// @brief Takes reporter @p index's answer and waits for its instant. + /// @param index The reporter's place in `_timeFacts`. + /// @param reported The instant, or empty when none is pending or the ask failed. On the server strand. + void timeFactAnswered(std::size_t index, std::optional<::morph::time::DateTime> reported) { + noteOwner("RemoteServer::timeFactAnswered"); + TimeFact& fact = _timeFacts.at(index); + fact.asking = false; + if (reported && fact.fired && *reported <= *fact.fired) { + ::morph::log::logWarn("[timeFacts] {} reported an instant it already reported; ignored", + fact.source.action); + reported.reset(); + } + fact.next = reported; + if (fact.askAgain) { + fact.askAgain = false; + askTimeFact(index); + return; + } + waitForTimeFact(index); + } + + /// @brief Sleeps until reporter @p index's instant, or `clockRecheck`, whichever is sooner, then reads the clock. + /// @param index The reporter's place in `_timeFacts`. On the server strand. + void waitForTimeFact(std::size_t index) { + TimeFact& fact = _timeFacts.at(index); + if (fact.timer != 0 && _strandTimer) { + _strandTimer->cancel(fact.timer); + } + fact.timer = 0; + if (!fact.next || fact.asking) { + return; + } + auto const remaining = std::chrono::duration_cast(fact.next->value - now().value); + if (remaining.count() <= 0) { + fireTimeFact(index); + return; + } + if (!_strandTimer) { + _strandTimer = std::make_unique<::morph::async::detail::TimeoutScheduler>(); + } + std::uint64_t const wake = ++fact.wake; + fact.timer = + _strandTimer->schedule(std::min(remaining, _config.clockRecheck), [weak = weak_from_this(), index, wake] { + if (auto const self = weak.lock()) { + self->_strand.postTask([self, index, wake] { self->timeFactWoke(index, wake); }); + } + }); + } + + /// @brief Reads the clock after a sleep, and fires the instant if it has come, or waits on. + /// @param index The reporter's place in `_timeFacts`. + /// @param wake The number the wait carried; a later wait has superseded a different one. + // NOLINTNEXTLINE(bugprone-easily-swappable-parameters): a place, then a number; swapped, nothing matches and the wake is dropped. + void timeFactWoke(std::size_t index, std::uint64_t wake) { + noteOwner("RemoteServer::timeFactWoke"); + if (_timeFacts.at(index).wake != wake) { + return; + } + _timeFacts.at(index).timer = 0; + waitForTimeFact(index); + } + + /// @brief Fans out the change reporter @p index's instant makes, through the path an action's effects take. + /// + /// The instant is consumed first. The fan-out names the reporter's records, so it asks for the following + /// instant by itself. + /// @param index The reporter's place in `_timeFacts`. On the server strand. + void fireTimeFact(std::size_t index) { + TimeFact& fact = _timeFacts.at(index); + fact.fired = fact.next; + fact.next.reset(); + auto changes = + ::morph::effects::detail::wholeTypeChanges(::morph::effects::detail::resolved(), fact.source.records); + fanOut(std::move(changes), 0, std::string_view{}); + } + /// @brief Hands each service this server, the first time any of them is about to answer. On the server strand. void bindServices() { if (_servicesBound) { @@ -2162,6 +2348,7 @@ class RemoteServer : public std::enable_shared_from_this { reply(::morph::wire::encode(::morph::wire::makeErr("server shutting down", env.callId))); return; } + startTimeFacts(); try { if (env.kind == "register") { MORPH_ZONE("RemoteServer::register"); @@ -2898,6 +3085,9 @@ class RemoteServer : public std::enable_shared_from_this { // Numbers each coalescing window, so a window's late close cannot send a // queue a later window holds. std::uint64_t _nextWindow{0}; + // The reporters of time-derived facts; filled by the first envelope handled. + std::vector _timeFacts; + bool _timeFactsStarted{false}; // Drawn off the strand by openConnection(), which answers at once. std::atomic _nextConnectionId{0}; diff --git a/include/morph/forms/engine/collection.hpp b/include/morph/forms/engine/collection.hpp index 9a62b7722..ab1dc6b66 100644 --- a/include/morph/forms/engine/collection.hpp +++ b/include/morph/forms/engine/collection.hpp @@ -491,6 +491,17 @@ class CollectionSession { /// @return The editor, or null when the view has no row action or its schema is unknown or malformed. [[nodiscard]] FormSession* editor() const noexcept { return _editor.get(); } + /// @brief Replaces the number locale and the date patterns the editor reads (`FormSession::setFormat`); nothing + /// when the collection has no editor. + /// @param locale The number format. Its views must outlive the session or the next call. + /// @param datePattern The date pattern; empty keeps ISO. + /// @param dateTimePattern The date-time pattern; empty keeps ISO. + void setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern) { + if (_editor) { + _editor->setFormat(locale, std::move(datePattern), std::move(dateTimePattern)); + } + } + /// @brief Whether an action is in flight. Tracked. /// @return `true` while one is. [[nodiscard]] bool actionPending() const { return _actions.pending(); } diff --git a/include/morph/forms/engine/form_session.hpp b/include/morph/forms/engine/form_session.hpp index 5db00a6ae..1ead250ae 100644 --- a/include/morph/forms/engine/form_session.hpp +++ b/include/morph/forms/engine/form_session.hpp @@ -88,10 +88,13 @@ class SessionCore { _model{std::move(model)}, _choices{std::move(choices)}, _options{std::move(options)}, - _values{.locale = _options.locale, - .displayOffsetMinutes = _options.displayOffsetMinutes, - .translations = _options.translations, - .bcp47 = _options.bcp47} {} + _values{ + .locale = _options.locale, + .displayOffsetMinutes = _options.displayOffsetMinutes, + .translations = _options.translations, + .bcp47 = _options.bcp47, + }, + _format{runtime, std::uint64_t{0}} {} /// @brief The runtime. /// @return The runtime passed at construction. @@ -105,9 +108,34 @@ class SessionCore { /// @return The options. [[nodiscard]] FormSessionOptions const& options() const noexcept { return _options; } - /// @brief The options a value conversion reads. + /// @brief The options a value conversion reads. Tracked: a change of the number format (`setFormat`) reruns what + /// read them. /// @return The value context. - [[nodiscard]] ValueContext const& values() const noexcept { return _values; } + [[nodiscard]] ValueContext const& values() const { + static_cast(_format.get()); + return _values; + } + + /// @brief The pattern a date or date-time input shows and reads. Tracked. + /// @param date `true` for the date pattern, `false` for the date-time pattern. + /// @return The pattern; empty keeps ISO. + [[nodiscard]] std::string const& pattern(bool date) const { + static_cast(_format.get()); + return date ? _options.datePattern : _options.dateTimePattern; + } + + /// @brief Replaces the number locale and the date patterns every field reads. Drafts keep their text; the + /// fields check it again against the new format. + /// @param locale The number format. Its views must outlive the session or the next call. + /// @param datePattern The date pattern. + /// @param dateTimePattern The date-time pattern. + void setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern) { + _options.locale = locale; + _options.datePattern = std::move(datePattern); + _options.dateTimePattern = std::move(dateTimePattern); + _values.locale = locale; + _format.set(_format.peek() + 1); + } /// @brief The Choice fetcher. /// @return The fetcher; may be empty. @@ -143,6 +171,7 @@ class SessionCore { ChoiceFetcher _choices; FormSessionOptions _options; ValueContext _values; + reactive::Signal _format; std::function _programmatic; std::vector> const* _fields = nullptr; }; @@ -451,6 +480,34 @@ class FieldState { return out; } + /// @brief Whether loading @p value would leave what the field encodes unchanged: a scalar whose draft decodes + /// from the wire value to the same body entry as the current draft, such as `1` and the record's `1.000`. + /// An Object, a collection and a truncated field never match (their rows and members would be rebuilt + /// rather than compared). Untracked. + /// @param value The wire value, or null for blank. + /// @return `true` when the current draft already encodes as @p value does. + [[nodiscard]] bool encodesLike(detail::engine::Json const* value) const { + if (_spec->truncated || _spec->kind == FieldKind::Object || _spec->kind == FieldKind::ObjectArray) { + return false; + } + bool const present = value != nullptr && !value->is_null(); + std::string draft = present ? decodeScalar(*_spec, *value, _core->values(), _places.peek()) : std::string{}; + std::size_t const unit = _spec->entryUnit; + if (unit != 0 && unit < _spec->units.size() && !draft.empty()) { + draft = convertDraft(draft, _spec->units.front(), _spec->units.at(unit), _core->values().locale) + .value_or(std::string{}); + } + Encoding const incoming = encodeScalar(*_spec, draft, unit, _core->values(), _places.peek()); + Encoding const& current = _encoded.peek(); + if (incoming.has_value() != current.has_value()) { + return false; + } + if (!incoming.has_value()) { + return true; + } + return incoming->has_value() && current->has_value() && (*incoming)->json == (*current)->json; + } + /// @brief Replaces the draft with a wire value as the user's own edit, in one batch: a `load` the session does /// not mark programmatic, so the field counts as changed and is validated as an edit is. /// @param value The wire value; null is blank. @@ -835,7 +892,10 @@ class FormSession { } markLoaded(); _autoSubmit = std::make_unique(runtime, [this] { autoSubmit(); }); - _acceptSent = std::make_unique(runtime, [this] { acceptSent(); }); + _acceptSent = std::make_unique(runtime, [this, &runtime] { + static_cast(_mutation.successCount()); + runtime.untracked([&] { acceptSent(); }); + }); } ~FormSession() = default; @@ -860,6 +920,20 @@ class FormSession { /// @return The options. [[nodiscard]] FormSessionOptions const& options() const noexcept { return _core->options(); } + /// @brief Replaces the number locale and the date patterns the form reads, so a mounted form follows a change + /// of the session's formatting. Drafts keep their text and are checked again against the new format. + /// @param locale The number format. Its views must outlive the session or the next call. + /// @param datePattern The date pattern; empty keeps ISO. + /// @param dateTimePattern The date-time pattern; empty keeps ISO. + void setFormat(render::NumericLocale locale, std::string datePattern, std::string dateTimePattern) { + _core->setFormat(locale, std::move(datePattern), std::move(dateTimePattern)); + } + + /// @brief The pattern the form's date or date-time inputs show. Tracked. + /// @param date `true` for the date pattern, `false` for the date-time pattern. + /// @return The pattern; empty keeps ISO. + [[nodiscard]] std::string const& pattern(bool date) const { return _core->pattern(date); } + /// @brief The top-level fields, in `x-order`. /// @return The fields. [[nodiscard]] std::span const> fields() const noexcept { return _fields; } @@ -972,11 +1046,12 @@ class FormSession { /// @brief Loads a stored payload like `prefill`, except that a top-level field the user changed since the form /// was last loaded keeps what they entered: a later value of the record being edited, such as its first - /// value arriving after the user started typing, or a refetch, does not discard the edit. An explicit - /// form's successful submission ends the edit of every field still holding what it sent, so the record's - /// later values reach those. An automatic form's does not: it submits while the person may still be - /// typing, and loading the record's form of a number would change the text under their cursor. Nothing - /// is submitted. Text that is not a JSON object changes nothing. + /// value arriving after the user started typing, or a refetch, does not discard the edit. A successful + /// submission ends the edit of every field still holding what it sent, so the record's later values reach + /// those. An automatic form submits while the person may still be typing, so there a saved scalar takes a + /// record value only when it encodes differently from the draft: the record's form of the same value + /// (`1.000` for a typed `1`) leaves the text alone. A saved object or collection of an automatic form + /// stays an edit. Nothing is submitted. Text that is not a JSON object changes nothing. /// @param bodyJson The payload. void refill(std::string_view bodyJson) { auto const dom = detail::engine::parseJson(bodyJson); @@ -987,10 +1062,18 @@ class FormSession { runtime().batch([&] { for (std::size_t index = 0; index < _fields.size(); ++index) { FieldState& field = *_fields.at(index); - if (field.snapshot() == _loaded.at(index)) { - field.load(detail::engine::member(*dom, field.spec().name)); - loaded.push_back(index); + if (field.snapshot() != _loaded.at(index)) { + continue; } + detail::engine::Json const* const incoming = detail::engine::member(*dom, field.spec().name); + // An automatic form's saved field is a finished edit only while the record differs from what the + // person typed: the record's form of the same value (`1.000` for `1`) is left out, so a refill + // never rewrites text the person may still be typing. + if (submitMode() == SubmitMode::Automatic && field.encodesLike(incoming)) { + continue; + } + field.load(incoming); + loaded.push_back(index); } _core->markProgrammatic(); }); @@ -1086,13 +1169,12 @@ class FormSession { // Only while nothing is in flight: the submission is Exclusive, so a run made during one is refused and what it // would have sent was never saved. void rememberSent() { - if (_core->model().submitMode() != SubmitMode::Explicit) { - return; - } runtime().untracked([&] { if (_mutation.pending()) { return; } + // A success the accept effect has not yet seen belongs to the snapshots about to be replaced. + acceptSent(); _sent.clear(); for (auto const& field : _fields) { _sent.push_back(field->snapshot()); @@ -1100,20 +1182,30 @@ class FormSession { }); } + // An explicit form ends the edit of what it saved. An automatic one does so only for a scalar: its refill compares + // the record's value with the draft, which a collection's rows and an object's members do not allow, and + // rebuilding them would replace the row the person is typing in. + [[nodiscard]] bool endsEditOnSave(FieldState const& field) const { + if (_core->model().submitMode() == SubmitMode::Explicit) { + return true; + } + FieldSpec const& spec = field.spec(); + return !spec.truncated && spec.kind != FieldKind::Object && spec.kind != FieldKind::ObjectArray; + } + + // Ends the edit of what the last success sent. Runs untracked: the accept effect and the next send both call it. void acceptSent() { std::uint64_t const successes = _mutation.successCount(); if (successes == _acceptedSuccesses) { return; } _acceptedSuccesses = successes; - runtime().untracked([&] { - for (std::size_t index = 0; index < _sent.size(); ++index) { - if (_fields.at(index)->snapshot() == _sent.at(index)) { - _loaded.at(index) = _sent.at(index); - } + for (std::size_t index = 0; index < _sent.size(); ++index) { + if (_fields.at(index)->snapshot() == _sent.at(index) && endsEditOnSave(*_fields.at(index))) { + _loaded.at(index) = _sent.at(index); } - _sent.clear(); - }); + } + _sent.clear(); } void markLoaded() { @@ -1172,6 +1264,7 @@ class FormSession { return; } _lastSubmitted = body; + rememberSent(); std::string const toSend = *body; runtime().untracked([&] { if (_mutation.run(toSend)) { diff --git a/include/morph/forms/engine/form_view.hpp b/include/morph/forms/engine/form_view.hpp index a5bd047fb..aae3c40a0 100644 --- a/include/morph/forms/engine/form_view.hpp +++ b/include/morph/forms/engine/form_view.hpp @@ -254,8 +254,8 @@ using ViewOptions = std::shared_ptr; }; auto const dateInput = [&](bool date) { int const offset = date ? 0 : session.options().displayOffsetMinutes; - // The input shows and reads the session's pattern; the draft text below stays ISO. - std::string const pattern = date ? session.options().datePattern : session.options().dateTimePattern; + // The input shows and reads the session's pattern, which it follows; the draft text below stays ISO. + FormSession const* const owner = &session; return ui::dateTimeInput(ui::DateTimeInput{ .value = [field, date, offset] { return draftInstant(trim(field->text().get()), date, offset); }, .onChange = @@ -268,7 +268,7 @@ using ViewOptions = std::shared_ptr; .showLabel = false, .field = fieldState(field), .common = controlCommon(field), - .pattern = pattern, + .pattern = [owner, date] { return owner->pattern(date); }, }); }; if (spec.kind == FieldKind::Multiline) { diff --git a/include/morph/forms/engine/wizard.hpp b/include/morph/forms/engine/wizard.hpp index 9723d5af9..407e32fcf 100644 --- a/include/morph/forms/engine/wizard.hpp +++ b/include/morph/forms/engine/wizard.hpp @@ -259,6 +259,16 @@ class WizardSession { return found == _resolved.end() ? std::nullopt : std::optional{found->second}; } + /// @brief Replaces the number locale and the date patterns every step reads (`FormSession::setFormat`). + /// @param locale The number format. Its views must outlive the session or the next call. + /// @param datePattern The date pattern; empty keeps ISO. + /// @param dateTimePattern The date-time pattern; empty keeps ISO. + void setFormat(render::NumericLocale locale, std::string const& datePattern, std::string const& dateTimePattern) { + for (auto const& step : _steps) { + step->setFormat(locale, datePattern, dateTimePattern); + } + } + /// @brief The wizard's title, resolved through the translations (`.title`). /// @return The title. [[nodiscard]] std::string title() const { diff --git a/include/morph/ui/author.hpp b/include/morph/ui/author.hpp index 203a12f5d..34afeefbb 100644 --- a/include/morph/ui/author.hpp +++ b/include/morph/ui/author.hpp @@ -4536,8 +4536,16 @@ struct DialogOptions { /// @brief A dialog's condition for being drawn as a sheet that fills the window, such as /// `eq(env("widthClass"), "compact")`; a drawer takes none. AnyHandle sheet; - /// @brief The label of a sheet's dismiss control; absent is "Close". Only with `sheet`. + /// @brief The label of the dismiss control of a sheet or of `closeButton`; absent is "Close". Only with one of + /// them. AnyHandle dismissLabel; + /// @brief A short muted note on the title's row, against the trailing edge. + AnyHandle headNote; + /// @brief A short muted note leading in the footer's row, opposite the actions. + AnyHandle footerNote; + /// @brief A condition: while true a dismiss control, labelled `dismissLabel`, is drawn on the title's row. A + /// sheet's head holds one already, so it adds nothing while `sheet` holds. + AnyHandle closeButton; }; namespace detail { @@ -4572,6 +4580,9 @@ namespace detail { return node.put("side", options.side) .put("sheet", options.sheet) .put("dismissLabel", options.dismissLabel) + .put("headNote", options.headNote) + .put("footerNote", options.footerNote) + .put("closeButton", options.closeButton) .scope(scope) .put("children", children) .put("default", options.defaultAction) diff --git a/include/morph/ui/backend.hpp b/include/morph/ui/backend.hpp index 267e45ed1..c7776642a 100644 --- a/include/morph/ui/backend.hpp +++ b/include/morph/ui/backend.hpp @@ -695,10 +695,27 @@ class DialogWidget : public ContainerWidget { /// @param sheet Whether it is a sheet. virtual void setSheet(bool sheet) = 0; - /// @brief Sets the label of a sheet's dismiss control; a new dialog's is "Close". The mount calls this only when - /// the label is bound or not the default. + /// @brief Sets the label of the dismiss control, a sheet's or the one `setCloseButton` draws; a new overlay's is + /// "Close". The mount calls this only when the label is bound or not the default. /// @param label The label, UTF-8. virtual void setDismissLabel(std::string_view label) = 0; + + /// @brief Shows a short muted note on the title's row, against the trailing edge. The mount calls it only when + /// the note is bound or not empty. + /// @param note The note, UTF-8; empty shows none. + virtual void setHeadNote(std::string_view note) = 0; + + /// @brief Shows a short muted note leading in the footer's row, opposite the actions. The footer shows while + /// the note is not empty, though it holds no action. The mount calls it only when the note is bound or + /// not empty. + /// @param note The note, UTF-8; empty shows none. + virtual void setFooterNote(std::string_view note) = 0; + + /// @brief Draws a dismiss control (labelled by `setDismissLabel`) on the title's row, against the trailing edge, + /// which dismisses exactly as Escape does. A sheet's head already holds one, so this adds nothing there. + /// The mount calls it only when the condition is bound or true. + /// @param shown Whether the control is drawn. + virtual void setCloseButton(bool shown) = 0; }; /// @brief A progress indicator. @@ -1126,6 +1143,28 @@ class DrawerWidget : public ContainerWidget { /// The mount puts the drawer's actions here. /// @return It, owned by the drawer and valid as long as the drawer. virtual ContainerWidget& footer() = 0; + + /// @brief Sets the label of the dismiss control `setCloseButton` draws; a new drawer's is "Close". The mount + /// calls this only when the label is bound or not the default. + /// @param label The label, UTF-8. + virtual void setDismissLabel(std::string_view label) = 0; + + /// @brief Shows a short muted note on the title's row, against the trailing edge. The mount calls it only when + /// the note is bound or not empty. + /// @param note The note, UTF-8; empty shows none. + virtual void setHeadNote(std::string_view note) = 0; + + /// @brief Shows a short muted note leading in the footer's row, opposite the actions. The footer shows while + /// the note is not empty, though it holds no action. The mount calls it only when the note is bound or + /// not empty. + /// @param note The note, UTF-8; empty shows none. + virtual void setFooterNote(std::string_view note) = 0; + + /// @brief Draws a dismiss control (labelled by `setDismissLabel`) on the title's row, against the trailing edge, + /// which dismisses exactly as Escape does. + /// The mount calls it only when the condition is bound or true. + /// @param shown Whether the control is drawn. + virtual void setCloseButton(bool shown) = 0; }; /// @brief A non-modal panel that belongs to another widget: the results of a search under its field. It takes no diff --git a/include/morph/ui/interpreter.hpp b/include/morph/ui/interpreter.hpp index 61ae56277..5d3e97c80 100644 --- a/include/morph/ui/interpreter.hpp +++ b/include/morph/ui/interpreter.hpp @@ -682,6 +682,11 @@ class MORPH_API Session { /// @return They. [[nodiscard]] FormatContext const& formatting() const { return *_format.get(); } + /// @brief The formatting facts as a shared handle, for what holds views into them past a later change. A tracked + /// read. + /// @return They. + [[nodiscard]] std::shared_ptr formattingHandle() const { return _format.get(); } + /// @brief The formatting facts, read without tracking: what a value set once at mount reads. /// @return They. [[nodiscard]] FormatContext const& formattingNow() const { return *_format.peek(); } @@ -2152,6 +2157,7 @@ class MORPH_API ScreenCore { [[nodiscard]] FormSubmitter aliasCalls(ModelAlias* alias); [[nodiscard]] FormSubmitter aliasSubmits(ModelAlias* alias, std::string read = {}); [[nodiscard]] forms::FormSessionOptions engineOptions() const; + void followFormatting(ElementState& element, RtScope& scope); void wireComposite(ElementState& element); Node lowerComposite(DocNode const& node, LowerCtx const& ctx, ElementState* element); void presentForm(DocNode const& node, LowerCtx const& ctx, forms::FormViewOptions& options); diff --git a/include/morph/ui/mount.hpp b/include/morph/ui/mount.hpp index b7fee6221..b541bb979 100644 --- a/include/morph/ui/mount.hpp +++ b/include/morph/ui/mount.hpp @@ -1411,9 +1411,6 @@ class Mounter { if (spec.sheet.isBound() || spec.sheet.constant()) { bind(scope, spec.sheet, [&widget](bool sheet) { widget.setSheet(sheet); }); } - if (spec.dismissLabel.isBound() || spec.dismissLabel.constant() != "Close") { - bind(scope, spec.dismissLabel, [&widget](std::string const& label) { widget.setDismissLabel(label); }); - } return mountOverlay(scope, spec, widget); } @@ -1436,6 +1433,7 @@ class Mounter { bind(scope, spec.description, [&widget](std::string const& description) { widget.setDescription(description); }); } + bindOverlayChrome(scope, spec, widget); auto& content = scope.make>(); auto& shownOpen = scope.make>(); // A bound `open` is controlled: a dismissal the document refuses opens the dialog again, over the content it @@ -1483,6 +1481,24 @@ class Mounter { return widget; } + // An overlay's notes, close control and dismiss label: each is told only when the document sets it, so a backend + // keeps its own default for the rest. + template + void bindOverlayChrome(reactive::Scope& scope, Spec const& spec, OverlayWidget& widget) { + if (spec.headNote.isBound() || !spec.headNote.constant().empty()) { + bind(scope, spec.headNote, [&widget](std::string const& note) { widget.setHeadNote(note); }); + } + if (spec.footerNote.isBound() || !spec.footerNote.constant().empty()) { + bind(scope, spec.footerNote, [&widget](std::string const& note) { widget.setFooterNote(note); }); + } + if (spec.closeButton.isBound() || spec.closeButton.constant()) { + bind(scope, spec.closeButton, [&widget](bool shown) { widget.setCloseButton(shown); }); + } + if (spec.dismissLabel.isBound() || spec.dismissLabel.constant() != "Close") { + bind(scope, spec.dismissLabel, [&widget](std::string const& label) { widget.setDismissLabel(label); }); + } + } + // After a Dialog's content failed to mount: tells the application through `onDismiss` that the dialog is closed. // It runs last, from a copy: it is a widget callback, which may destroy the Mounted and with it the dialog and // the Effect that called this; the caller only rethrows after it. Nothing thrown here may replace the failure diff --git a/include/morph/ui/testing/recording_backend.hpp b/include/morph/ui/testing/recording_backend.hpp index 9abae4812..7cc0c4d34 100644 --- a/include/morph/ui/testing/recording_backend.hpp +++ b/include/morph/ui/testing/recording_backend.hpp @@ -1437,8 +1437,8 @@ class FakeOverlay : public FakeContainer { std::unique_ptr _footer; }; -/// @brief A fake `DialogWidget`: properties `open`, `title`, `description`, `sheet` and `dismissLabel` (when set); a -/// `Footer` child once its footer is asked for. +/// @brief A fake `DialogWidget`: properties `open`, `title`, `description`, `sheet`, `dismissLabel`, `headNote`, +/// `footerNote` and `closeButton` (when set); a `Footer` child once its footer is asked for. class FakeDialog final : public FakeOverlay { public: using FakeOverlay::FakeOverlay; @@ -1451,6 +1451,9 @@ class FakeDialog final : public FakeOverlay { void setOnDismiss(Action onDismiss) override { callbacks().dismiss = std::move(onDismiss); } void setSheet(bool sheet) override { set("sheet", formatBool(sheet)); } void setDismissLabel(std::string_view label) override { set("dismissLabel", formatText(label)); } + void setHeadNote(std::string_view note) override { set("headNote", formatText(note)); } + void setFooterNote(std::string_view note) override { set("footerNote", formatText(note)); } + void setCloseButton(bool shown) override { set("closeButton", formatBool(shown)); } }; /// @brief A fake `BannerWidget`: properties `tone`, `text`, `spans` (as `formatSpans` gives them), `actionLabel`, @@ -1680,8 +1683,8 @@ class FakeEmptyState final : public FakeLeaf { void setOnAction(Action onAction) override { callbacks().action = std::move(onAction); } }; -/// @brief A fake `DrawerWidget`: properties `side`, `open`, `title`, `description`; a `Footer` child once its footer -/// is asked for. +/// @brief A fake `DrawerWidget`: properties `side`, `open`, `title`, `description`, and `headNote`, `footerNote`, +/// `closeButton` and `dismissLabel` (when set); a `Footer` child once its footer is asked for. class FakeDrawer final : public FakeOverlay { public: using FakeOverlay::FakeOverlay; @@ -1692,6 +1695,10 @@ class FakeDrawer final : public FakeOverlay { set("descriptionSpans", formatSpans(spans)); } void setOnDismiss(Action onDismiss) override { callbacks().dismiss = std::move(onDismiss); } + void setDismissLabel(std::string_view label) override { set("dismissLabel", formatText(label)); } + void setHeadNote(std::string_view note) override { set("headNote", formatText(note)); } + void setFooterNote(std::string_view note) override { set("footerNote", formatText(note)); } + void setCloseButton(bool shown) override { set("closeButton", formatBool(shown)); } }; /// @brief A fake `PopoverWidget`: properties `open` and `width`. diff --git a/include/morph/ui/view.hpp b/include/morph/ui/view.hpp index 6c12cff42..3cd8e745b 100644 --- a/include/morph/ui/view.hpp +++ b/include/morph/ui/view.hpp @@ -1025,11 +1025,18 @@ struct Dialog { /// @brief Whether it is drawn as a sheet that fills the window, with a head holding a dismiss control and the /// title. Changing it while open keeps the content and its state. Prop sheet = false; - /// @brief The label of a sheet's dismiss control, which dismisses as Escape does. + /// @brief The label of the dismiss control, a sheet's or `closeButton`'s, which dismisses as Escape does. Prop dismissLabel = std::string{"Close"}; /// @brief The description as runs; while bound or not empty, shown in place of `description`, which an older /// client draws. Prop> descriptionSpans; + /// @brief A short muted note on the title's row, against the trailing edge; empty shows none. + Prop headNote; + /// @brief A short muted note leading in the footer's row, opposite the actions; empty shows none. + Prop footerNote; + /// @brief Whether a dismiss control, labelled `dismissLabel`, is drawn on the title's row, against the trailing + /// edge. A sheet's head holds one already, so this adds nothing while `sheet` holds. + Prop closeButton = false; }; /// @brief A progress indicator. @@ -1610,6 +1617,14 @@ struct Drawer { Common common{}; /// @brief The description as runs, as a dialog's. Prop> descriptionSpans; + /// @brief A short muted note on the title's row, as a dialog's. + Prop headNote; + /// @brief A short muted note leading in the footer's row, as a dialog's. + Prop footerNote; + /// @brief Whether a dismiss control is drawn on the title's row, as a dialog's. + Prop closeButton = false; + /// @brief The label of the dismiss control `closeButton` draws. + Prop dismissLabel = std::string{"Close"}; }; /// @brief A row of buttons: the actions of what holds it. Inside the content of a dialog or drawer, at any depth, it diff --git a/scripts/branch_partial_allowlist.json b/scripts/branch_partial_allowlist.json index b0d1a0728..f0a8c7ca3 100644 --- a/scripts/branch_partial_allowlist.json +++ b/scripts/branch_partial_allowlist.json @@ -121,28 +121,28 @@ }, { "file": "src/ui/document.cpp", - "line": 1538, + "line": 1541, "source": "default:", "context": "download(cmd, fields, primary, path);", "reason": "The default arm is unreachable: the switch names every enumerator of CommandKind, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentParser::command's switch over the command kinds." }, { "file": "src/ui/document.cpp", - "line": 1913, + "line": 1916, "source": "default:", "context": "case Shape::Keys:", "reason": "The default arm is unreachable: the switch names every enumerator of detail::Shape, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentParser::entry's switch over a key's shape." }, { "file": "src/ui/document.cpp", - "line": 4453, + "line": 4455, "source": "default:", "context": "if (cmd.value) {", "reason": "The default arm is unreachable: the switch names every enumerator of CommandKind, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is DocumentValidator::checkCommand's switch." }, { "file": "src/ui/document.cpp", - "line": 4795, + "line": 4797, "source": "default: {", "reason": "The default arm is unreachable: the switch names every enumerator of NameCategory, so no value reaches `default`. The project's strict warnings require both at once -- -Wswitch-enum wants every enumerator listed and -Wswitch-default wants a default label -- so the default shares the last enumerator's body and is never the label taken. It is ScopeResolver::ref's switch over what a name declares." }, diff --git a/scripts/check_branch_coverage.py b/scripts/check_branch_coverage.py index 2cc2b4846..2b97cc516 100644 --- a/scripts/check_branch_coverage.py +++ b/scripts/check_branch_coverage.py @@ -119,11 +119,11 @@ # Measured in the CI coverage leg (22 branch arms) when the test kit was installed with # morph::reactive. "include/morph/testing": (74.0, 77.27), - # 5261 of 5562 branch arms (94.59%) with the UI document, expr/1, the whole palette, the document interpreter - # and the authoring builders: the interpreter's clang 22.1.8 coverage build of morph_tests gave 4901 of 5202, - # and the authoring builders add 360 arms, every one taken in the same configuration. The ui tests are the - # only ones that reach these headers. - "include/morph/ui": (92.0, 94.59), + # 15784 of 17204 branch arms (91.75%) in the CI coverage leg, over the headers and the compiled src/ui sources + # together: the document, expr/1, the palette, the interpreter, the shell and the authoring builders. The floor + # sits below the measurement by the margin the other subsystems keep, so new ui code is held to its own tests + # rather than to the coverage the older code built up. + "include/morph/ui": (90.0, 91.75), "include/morph/util": (93.0, 96.39), } diff --git a/scripts/check_coverage_objects.sh b/scripts/check_coverage_objects.sh index af66b7df9..1590dc1dc 100755 --- a/scripts/check_coverage_objects.sh +++ b/scripts/check_coverage_objects.sh @@ -82,8 +82,8 @@ coverage_exclusion_reason() { morph_effects_unseen_links) echo "the BRIDGE_REGISTER_EFFECTS link probe (tests/CMakeLists.txt): two translation units, only one of which sees an action's effects, must link into one program and read the same effects; the fixture record and action exist nowhere else in the tree, so instrumenting it would only score probe-unique template instantiations against the library" ;; - lims_cross_module_effects_refused|lims_cross_module_effects_control) - echo "the lims cross-module effects probes (examples/lims/CMakeLists.txt): one program registers a second effects declaration for another module's action and must be refused, the other omits it and must resolve; they assert a registration rule about one fixture and drive no model code, so instrumenting them would only score probe-specific instantiations against the rung" + lims_cross_module_effects_accepted|lims_cross_module_effects_control) + echo "the lims cross-module effects probes (examples/lims/CMakeLists.txt): one program adds an effect to another module's action and must resolve to the union, the other omits it and must resolve; they assert a registration rule about one fixture and drive no model code, so instrumenting them would only score probe-specific instantiations against the rung" ;; fuzz_wire_decode|fuzz_dispatch_execute) echo "libFuzzer harnesses (MORPH_BUILD_FUZZERS=ON only, which the coverage leg does not set); apply_fuzzer() builds them at -O1 under -fsanitize=fuzzer,address, a different instrumentation from apply_coverage()'s" diff --git a/src/qt_quick/kinds.hpp b/src/qt_quick/kinds.hpp index 93fbe775d..75ea113b5 100644 --- a/src/qt_quick/kinds.hpp +++ b/src/qt_quick/kinds.hpp @@ -457,6 +457,16 @@ class OverlayImpl : public ContainerItemWidget { this->write("description", toQString(ui::spansText(spans))); this->write("descriptionRuns", runsOf(spans)); } + void setHeadNote(std::string_view note) override { this->write("headNote", toQString(note)); } + // The note is drawn by the footer item, so a note needs one even when no action asked for it. + void setFooterNote(std::string_view note) override { + if (!note.empty()) { + static_cast(footer()); + } + this->write("footerNote", toQString(note)); + } + void setCloseButton(bool shown) override { this->write("closeButton", shown); } + void setDismissLabel(std::string_view label) override { this->write("dismissLabel", toQString(label)); } void setOnDismiss(ui::Action onDismiss) override { this->relay().on(QStringLiteral("dismiss"), [onDismiss = std::move(onDismiss)](QVariant const&) { if (onDismiss) { @@ -489,7 +499,6 @@ class DialogImpl final : public OverlayImpl { public: using OverlayImpl::OverlayImpl; void setSheet(bool sheet) override { write("sheet", sheet); } - void setDismissLabel(std::string_view label) override { write("dismissLabel", toQString(label)); } }; using DrawerImpl = OverlayImpl; diff --git a/src/qt_quick/qml/MorphDialog.qml b/src/qt_quick/qml/MorphDialog.qml index de7332e67..2a0c1798e 100644 --- a/src/qt_quick/qml/MorphDialog.qml +++ b/src/qt_quick/qml/MorphDialog.qml @@ -17,7 +17,14 @@ MorphWidget { // joined characters of; while there are any, the label shows their markup. property var descriptionRuns: [] property bool sheet: false + // The label of the dismiss control: the sheet's, or the head's `closeButton`. property string dismissLabel: "Close" + // A muted note trailing on the title's row. + property string headNote: "" + // A muted note leading in the footer's row. + property string footerNote: "" + // Whether the title's row holds a dismiss control; a sheet's head holds one already. + property bool closeButton: false // Set while C++ opens or closes it, so that is not taken for a dismissal. property bool programmatic: false readonly property Item content: column @@ -181,19 +188,78 @@ MorphWidget { text: root.title } - Item { - Layout.preferredWidth: dismissButton.width - Layout.preferredHeight: 1 + // As wide as the dismiss button so the title stays centred; it holds the head note, which a longer note + // widens up to a third of the sheet. + Label { + id: sheetNote + objectName: "sheetHeadNote" + textFormat: Text.PlainText + Layout.preferredWidth: Math.max(dismissButton.width, Math.min(implicitWidth, contentColumn.width / 3)) + horizontalAlignment: Text.AlignRight + font: Theme.bodyFont + color: Theme.cardScheme.muted + elide: Text.ElideRight + text: root.headNote } } - Label { - textFormat: Text.PlainText - id: titleLabel - font: Theme.headingFont - color: Theme.cardScheme.text - visible: root.title !== "" && !root.sheet - text: root.title + // The title, with the head note trailing, muted, and the close control after it. + RowLayout { + id: titleRow + objectName: "titleRow" + visible: !root.sheet && (root.title !== "" || root.headNote !== "" || root.closeButton) + Layout.fillWidth: true + spacing: Theme.spaceOf(2) + + Label { + textFormat: Text.PlainText + id: titleLabel + Layout.fillWidth: true + font: Theme.headingFont + color: Theme.cardScheme.text + elide: Text.ElideRight + visible: root.title !== "" + text: root.title + } + + Label { + id: headNoteLabel + objectName: "headNote" + textFormat: Text.PlainText + Layout.alignment: Qt.AlignRight | Qt.AlignVCenter + Layout.fillWidth: root.title === "" + horizontalAlignment: Text.AlignRight + font: Theme.bodyFont + color: Theme.cardScheme.muted + elide: Text.ElideRight + visible: root.headNote !== "" + text: root.headNote + } + + Button { + id: headClose + objectName: "headClose" + visible: root.closeButton && !root.sheet + flat: true + text: root.dismissLabel + font: Theme.bodyFont + leftPadding: Theme.spaceOf(1) + rightPadding: Theme.spaceOf(1) + palette.buttonText: Theme.cardScheme.accent + contentItem: MorphPlainContent { + control: headClose + color: headClose.palette.buttonText + } + background: MorphButtonBackground { + scheme: Theme.cardScheme + ghost: true + hovered: headClose.hovered + pressed: headClose.down + focused: headClose.visualFocus + } + Accessible.name: root.dismissLabel + onClicked: popup.close() + } } Label { @@ -236,7 +302,7 @@ MorphWidget { Layout.maximumHeight: root.sheet ? Infinity : Math.max(0, (popup.Overlay.overlay?.height ?? Infinity) - 4 * Theme.unitHeight - - titleLabel.height - footerArea.height - + (titleRow.visible ? titleRow.height : 0) - footerArea.height - (footerRule.visible ? footerRule.height + contentColumn.spacing + 2 * contentColumn.ruleMargin : 0) - contentColumn.spacing * 2 - (headRule.visible ? 2 * contentColumn.ruleMargin : 0) - (root.description === "" ? 0 : descriptionLabel.height + headRule.height + @@ -270,6 +336,8 @@ MorphWidget { ColumnLayout { id: footerArea Layout.fillWidth: true + // The footer reads the note from the area it sits in. + property string footerNote: root.footerNote // A sheet's footer fills the sheet's width, so its action is as wide as a thumb needs; the footer // reads this from the area it sits in. property bool stretchesFooter: root.sheet diff --git a/src/qt_quick/qml/MorphDrawer.qml b/src/qt_quick/qml/MorphDrawer.qml index 049414387..6f51d5a11 100644 --- a/src/qt_quick/qml/MorphDrawer.qml +++ b/src/qt_quick/qml/MorphDrawer.qml @@ -18,6 +18,14 @@ MorphWidget { // 0 start, 1 end; fixed at creation. property int side: 0 property bool programmatic: false + // The label of the head's dismiss control, shown by `closeButton`. + property string dismissLabel: "Close" + // A muted note trailing on the title's row. + property string headNote: "" + // A muted note leading in the footer's row. + property string footerNote: "" + // Whether the title's row holds a dismiss control. + property bool closeButton: false readonly property Item content: column // Where C++ puts the drawer's footer, under the content: a restyle lays it out where it wants. readonly property Item footer: footerArea @@ -123,13 +131,63 @@ MorphWidget { Accessible.name: root.accessibleName Accessible.description: root.description - Label { - textFormat: Text.PlainText - id: titleLabel - font: Theme.headingFont - color: Theme.cardScheme.text - visible: root.title !== "" - text: root.title + // The title, with the head note trailing, muted, and the close control after it. + RowLayout { + id: titleRow + objectName: "titleRow" + visible: (root.title !== "" || root.headNote !== "" || root.closeButton) + Layout.fillWidth: true + spacing: Theme.spaceOf(2) + + Label { + textFormat: Text.PlainText + id: titleLabel + Layout.fillWidth: true + font: Theme.headingFont + color: Theme.cardScheme.text + elide: Text.ElideRight + visible: root.title !== "" + text: root.title + } + + Label { + id: headNoteLabel + objectName: "headNote" + textFormat: Text.PlainText + Layout.alignment: Qt.AlignRight | Qt.AlignVCenter + Layout.fillWidth: root.title === "" + horizontalAlignment: Text.AlignRight + font: Theme.bodyFont + color: Theme.cardScheme.muted + elide: Text.ElideRight + visible: root.headNote !== "" + text: root.headNote + } + + Button { + id: headClose + objectName: "headClose" + visible: root.closeButton + flat: true + text: root.dismissLabel + font: Theme.bodyFont + leftPadding: Theme.spaceOf(1) + rightPadding: Theme.spaceOf(1) + palette.buttonText: Theme.cardScheme.accent + contentItem: MorphPlainContent { + control: headClose + color: headClose.palette.buttonText + } + background: MorphButtonBackground { + scheme: Theme.cardScheme + ghost: true + hovered: headClose.hovered + pressed: headClose.down + focused: headClose.visualFocus + } + Accessible.name: root.dismissLabel + onClicked: drawer.close() + } } Label { @@ -169,7 +227,7 @@ MorphWidget { id: scroll Layout.fillWidth: true Layout.fillHeight: true - Layout.maximumHeight: Math.max(0, drawer.height - titleLabel.height - footerArea.height - + Layout.maximumHeight: Math.max(0, drawer.height - (titleRow.visible ? titleRow.height : 0) - footerArea.height - (footerRule.visible ? footerRule.height + contentColumn.spacing + 2 * contentColumn.ruleMargin : 0) - contentColumn.spacing * 2 - (headRule.visible ? 2 * contentColumn.ruleMargin : 0) - (root.description === "" ? 0 : descriptionLabel.height + @@ -204,6 +262,8 @@ MorphWidget { ColumnLayout { id: footerArea Layout.fillWidth: true + // The footer reads the note from the area it sits in. + property string footerNote: root.footerNote visible: { for (let i = 0; i < footerArea.children.length; ++i) { if ((footerArea.children[i] as MorphFooter)?.holding) diff --git a/src/qt_quick/qml/MorphFooter.qml b/src/qt_quick/qml/MorphFooter.qml index b84bda93c..07a3b6789 100644 --- a/src/qt_quick/qml/MorphFooter.qml +++ b/src/qt_quick/qml/MorphFooter.qml @@ -1,33 +1,56 @@ // SPDX-License-Identifier: Apache-2.0 pragma ComponentBehavior: Bound import QtQuick +import QtQuick.Controls import QtQuick.Layouts -// An overlay's footer: what C++ puts in it (the overlay's actions) in one row against the right edge. Empty, it -// takes no room. While `stretching`, as a sheet's footer does, it fills the overlay's width and its actions share it. +// An overlay's footer: what C++ puts in it (the overlay's actions) in one row against the right edge, and the +// overlay's footer note, muted, leading against the left. Empty, it takes no room. While `stretching`, as a sheet's +// footer does, it fills the overlay's width and its actions share it, with the note above them. MorphWidget { id: root readonly property Item content: row - // Whether anything is in the footer. - readonly property bool holding: row.children.length > 0 // Whether the footer fills its width and its actions share it equally: while the area it sits in says so. // Untyped, so the area may declare `stretchesFooter` or not. readonly property var area: parent readonly property bool stretching: area !== null && area !== undefined && area.stretchesFooter === true + // The note the area it sits in carries; untyped, so the area may declare `footerNote` or not. + readonly property string note: root.area?.footerNote ?? "" + // Whether anything is in the footer. + readonly property bool holding: row.children.length > 0 || root.note !== "" + // A stretching footer's actions fill its width, so its note stands above them instead of beside them. + readonly property bool noteAbove: root.stretching && root.note !== "" sharesWidth: stretching // Always the area's full width: the actions sit against its right edge, or share it while stretching. Layout.fillWidth: true - implicitWidth: row.implicitWidth - implicitHeight: row.implicitHeight + implicitWidth: row.implicitWidth + (root.note !== "" && !root.stretching ? noteLabel.implicitWidth + Theme.actionSpacing : 0) + implicitHeight: root.noteAbove ? noteLabel.implicitHeight + Theme.actionSpacing + row.implicitHeight + : Math.max(row.implicitHeight, root.note !== "" ? noteLabel.implicitHeight : 0) + + Label { + id: noteLabel + objectName: "footerNote" + visible: root.note !== "" + text: root.note + textFormat: Text.PlainText + font: Theme.bodyFont + color: Theme.cardScheme.muted + elide: Text.ElideRight + anchors.left: parent.left + anchors.top: root.noteAbove ? parent.top : undefined + anchors.verticalCenter: root.noteAbove ? undefined : parent.verticalCenter + width: root.noteAbove ? root.width : Math.max(0, root.width - row.implicitWidth - Theme.actionSpacing) + } RowLayout { id: row anchors.right: parent.right anchors.left: root.stretching ? parent.left : undefined - height: root.height + anchors.bottom: root.noteAbove ? parent.bottom : undefined + height: root.noteAbove ? row.implicitHeight : root.height spacing: Theme.actionSpacing // A stretching footer's actions each take an equal share, so a lone action fills the footer. onChildrenChanged: root.share() diff --git a/src/tui/container_widgets.cpp b/src/tui/container_widgets.cpp index 3700a19ad..b79011927 100644 --- a/src/tui/container_widgets.cpp +++ b/src/tui/container_widgets.cpp @@ -971,7 +971,36 @@ void OverlayCore::setDismissLabel(std::string_view label) { _self->refresh(); } -std::pair OverlayCore::dismissCells() const { return {2, displayWidth(_dismissLabel) + 2}; } +void OverlayCore::setHeadNote(std::string_view note) { + _headNote = std::string{note}; + _self->refresh(); +} + +void OverlayCore::setFooterNote(std::string_view note) { + _footerNote = std::string{note}; + _self->refresh(); +} + +void OverlayCore::setCloseButton(bool shown) { + _closeButton = shown; + _self->refresh(); +} + +int OverlayCore::closeControlWidth() const { return displayWidth(_dismissLabel) + 2; } + +int OverlayCore::trailingWidth() const { + int const control = hasCloseControl() ? closeControlWidth() : 0; + int const note = displayWidth(_headNote); + return note + control + (note != 0 && control != 0 ? 1 : 0); +} + +// A sheet's control leads the row; a head's close control ends it, against the box's inside edge. +std::pair OverlayCore::dismissCells() const { + if (hasCloseControl()) { + return {frameSize().width - 2 - closeControlWidth(), closeControlWidth()}; + } + return {2, closeControlWidth()}; +} ::core::tui::Size FooterImpl::naturalSize() const { return stackNaturalSize(children(), ui::Axis::Horizontal, 1); } @@ -997,7 +1026,11 @@ ui::ContainerWidget& OverlayFooter::of(ContainerBase& overlay) { std::vector<::core::tui::Rect> OverlayCore::childAreas(::core::tui::Size size) const { int const head = _description.empty() ? 0 : 2; ::core::tui::Rect const inner{ - .x = 2, .y = 1 + head, .width = std::max(0, size.width - 4), .height = std::max(0, size.height - 2 - head)}; + .x = 2, + .y = 1 + head, + .width = std::max(0, size.width - 4), + .height = std::max(0, size.height - 2 - head - footerNoteRows()), + }; std::span const children = _self->children(); // A sheet's footer stands at the bottom of the box, under content that takes the rest of its height. bool const footerLast = _sheet && !children.empty() && children.back() == _footer && _footer->shown(); @@ -1034,12 +1067,17 @@ ::core::tui::Size OverlayCore::frameSize() const { if (_sheet && !_side.has_value()) { return {.width = area.width, .height = area.height}; } - int const width = std::max({inner.width + 4, displayWidth(_title) + 4, displayWidth(_description) + 4}); + int const titleRow = displayWidth(_title) + trailingWidth() + (trailingWidth() != 0 && !_title.empty() ? 1 : 0); + int const width = + std::max({inner.width + 4, titleRow + 4, displayWidth(_description) + 4, displayWidth(_footerNote) + 4}); int const head = _description.empty() ? 0 : 2; if (_side.has_value()) { return {.width = std::min(width, area.width), .height = area.height}; } - return {.width = std::min(width, area.width), .height = std::min(inner.height + 2 + head, area.height)}; + return { + .width = std::min(width, area.width), + .height = std::min(inner.height + 2 + head + footerNoteRows(), area.height), + }; } // A dialog is centred; a drawer stands against its side, the whole height of the screen. @@ -1063,7 +1101,11 @@ void OverlayCore::paintFrame(::core::tui::Canvas& canvas) { auto const& theme = canvas.theme(); canvas.fill(canvas.area(), ' ', theme.dialogBackground); canvas.drawBox(canvas.area(), ::core::tui::BorderStyle::Single, theme.dialogBorder); - auto title = canvas.subcanvas({.x = 2, .y = 0, .width = std::max(0, canvas.width() - 4), .height = 1}); + int const rowWidth = std::max(0, canvas.width() - 4); + int const trailing = trailingWidth(); + // The title gives up the cells the trailing note and control take, and one between. + auto title = canvas.subcanvas( + {.x = 2, .y = 0, .width = std::max(0, rowWidth - trailing - (trailing != 0 ? 1 : 0)), .height = 1}); if (_sheet) { std::string const control = "[" + _dismissLabel + "]"; title.putString(0, 0, control, theme.dialogTitle); @@ -1071,6 +1113,21 @@ void OverlayCore::paintFrame(::core::tui::Canvas& canvas) { } else { title.putString(0, 0, _title, theme.dialogTitle); } + if (trailing != 0) { + auto tail = canvas.subcanvas({.x = 2, .y = 0, .width = rowWidth, .height = 1}); + int column = rowWidth - trailing; + if (!_headNote.empty()) { + tail.putString(0, column, _headNote, theme.textMuted); + column += displayWidth(_headNote) + 1; + } + if (hasCloseControl()) { + tail.putString(0, column, "[" + _dismissLabel + "]", theme.dialogTitle); + } + } + if (!_footerNote.empty() && canvas.height() > 2) { + auto line = canvas.subcanvas({.x = 2, .y = canvas.height() - 2, .width = rowWidth, .height = 1}); + line.putString(0, 0, splitLines(_footerNote).front(), theme.textMuted); + } if (!_description.empty() && canvas.height() > 3) { // One row, clipped at the frame's width like any terminal text, then a rule across the frame's inside. auto line = canvas.subcanvas({.x = 2, .y = 1, .width = std::max(0, canvas.width() - 4), .height = 1}); @@ -1098,7 +1155,8 @@ ::core::tui::EventResult OverlayCore::frameEvent(::core::tui::InputEvent const& // core::tui made the event relative to the box, so this is the cell in it. auto const [first, width] = dismissCells(); int const column = mouse->x - 1; - bool const onDismiss = _sheet && mouse->y - 1 == 0 && column >= first && column < first + width; + bool const onDismiss = + (_sheet || hasCloseControl()) && mouse->y - 1 == 0 && column >= first && column < first + width; if (onDismiss && _open && _self->actionable()) { dismiss(); } diff --git a/src/tui/container_widgets.hpp b/src/tui/container_widgets.hpp index a995ce496..9c8b50a4d 100644 --- a/src/tui/container_widgets.hpp +++ b/src/tui/container_widgets.hpp @@ -346,6 +346,10 @@ class PopoverImpl final : public TuiContainer { /// /// A dialog drawn as a sheet fills the viewport; its top row draws `[dismissLabel]` before the title, and a press on /// it dismisses as Esc does. Its footer, when it holds anything, takes the box's bottom rows. +/// +/// The head note is drawn muted on the title's row against its right end, after which comes `[dismissLabel]` while +/// the close control is on and the box is not a sheet; a press on the control dismisses as Esc does. The footer note +/// is drawn muted on a row of its own at the bottom of the box, under the content and the footer. class OverlayCore { public: /// @param self The dialog or drawer this is the overlay of. @@ -367,6 +371,9 @@ class OverlayCore { void setOnDismiss(ui::Action onDismiss) { _onDismiss = std::move(onDismiss); } void setSheet(bool sheet); void setDismissLabel(std::string_view label); + void setHeadNote(std::string_view note); + void setFooterNote(std::string_view note); + void setCloseButton(bool shown); /// The footer, which a sheet lays out at the bottom of its box. void setFooter(WidgetBase const* footer) noexcept { _footer = footer; } /// Closes the overlay and calls `onDismiss`, as Esc does. @@ -386,6 +393,14 @@ class OverlayCore { [[nodiscard]] ::core::tui::Size frameSize() const; /// The cells of a sheet's dismiss control in the box's top row: its first column and its width. [[nodiscard]] std::pair dismissCells() const; + /// Whether the title's row ends in a close control: asked for, and not a sheet, whose head holds one already. + [[nodiscard]] bool hasCloseControl() const noexcept { return _closeButton && !_sheet; } + /// The width of the dismiss control, `[label]`. + [[nodiscard]] int closeControlWidth() const; + /// The width the title row gives its trailing part: the note, then the close control, one cell apart. + [[nodiscard]] int trailingWidth() const; + /// The rows the footer note takes under the content: one while it is not empty. + [[nodiscard]] int footerNoteRows() const noexcept { return _footerNote.empty() ? 0 : 1; } void paintFrame(::core::tui::Canvas& canvas); [[nodiscard]] ::core::tui::EventResult frameEvent(::core::tui::InputEvent const& event); [[nodiscard]] bool holdsFocus() const; @@ -406,6 +421,9 @@ class OverlayCore { std::vector _descriptionRuns; ///< The description's runs; empty for a plain description. ui::Action _onDismiss; std::string _dismissLabel = "Close"; + std::string _headNote; + std::string _footerNote; + bool _closeButton = false; WidgetBase const* _footer = nullptr; bool _sheet = false; bool _open = false; @@ -454,6 +472,9 @@ class DialogImpl final : public TuiContainer { void setOnDismiss(ui::Action onDismiss) override { _overlay.setOnDismiss(std::move(onDismiss)); } void setSheet(bool sheet) override { _overlay.setSheet(sheet); } void setDismissLabel(std::string_view label) override { _overlay.setDismissLabel(label); } + void setHeadNote(std::string_view note) override { _overlay.setHeadNote(note); } + void setFooterNote(std::string_view note) override { _overlay.setFooterNote(note); } + void setCloseButton(bool shown) override { _overlay.setCloseButton(shown); } [[nodiscard]] ui::ContainerWidget& footer() override { ui::ContainerWidget& footer = _footer.of(*this); _overlay.setFooter(dynamic_cast(&footer)); @@ -492,6 +513,10 @@ class DrawerImpl final : public TuiContainer { void setDescriptionSpans(std::vector const& spans) override { _overlay.setDescriptionSpans(spans); } [[nodiscard]] std::string accessibleDescription() const override { return _overlay.description(); } void setOnDismiss(ui::Action onDismiss) override { _overlay.setOnDismiss(std::move(onDismiss)); } + void setDismissLabel(std::string_view label) override { _overlay.setDismissLabel(label); } + void setHeadNote(std::string_view note) override { _overlay.setHeadNote(note); } + void setFooterNote(std::string_view note) override { _overlay.setFooterNote(note); } + void setCloseButton(bool shown) override { _overlay.setCloseButton(shown); } [[nodiscard]] ui::ContainerWidget& footer() override { return _footer.of(*this); } [[nodiscard]] ::core::tui::Size naturalSize() const override { return {.width = 0, .height = 0}; } [[nodiscard]] std::string probeText() const override { return _overlay.title(); } diff --git a/src/ui/document.cpp b/src/ui/document.cpp index 7711994af..c4bbbeb02 100644 --- a/src/ui/document.cpp +++ b/src/ui/document.cpp @@ -255,7 +255,7 @@ constexpr std::array kTabsKeys = {{{"tabs", Shape::Parts, "tab"}, constexpr std::array kTabKeys = { {{"id", Shape::Name}, {"label", Shape::Expr}, {"children", Shape::Nodes}}}; /// @brief The keys of `dialog` and `drawer`. -constexpr std::array kDialogKeys = {{{"open", Shape::Condition}, +constexpr std::array kDialogKeys = {{{"open", Shape::Condition}, {"gap", Shape::Expr}, {"title", Shape::Expr}, {"description", Shape::Expr}, @@ -268,7 +268,10 @@ constexpr std::array kDialogKeys = {{{"open", Shape::Condition}, {"side", Shape::Expr}, {"sheet", Shape::Condition}, {"dismissLabel", Shape::Expr}, - {"descriptionSpans", Shape::Expr}}}; + {"descriptionSpans", Shape::Expr}, + {"headNote", Shape::Expr}, + {"footerNote", Shape::Expr}, + {"closeButton", Shape::Condition}}}; /// @brief The keys of `group`: a labelled set of inputs, lowered to a column of existing kinds. constexpr std::array kGroupKeys = {{{"label", Shape::Expr}, {"required", Shape::Condition}, @@ -3188,19 +3191,18 @@ class DocumentValidator { } } - // A dialog's `sheet` and the label of its dismiss control: a drawer already fills the height on a phone and takes - // neither, and a `dismissLabel` labels only a sheet's control. + // A dialog's `sheet`: a drawer already fills the height on a phone and takes none. A `dismissLabel` labels the + // dismiss control of a sheet or of a `closeButton`, so it needs one of them (a drawer has no sheet). static void checkSheet(DocNode const& node) { - if (node.kind == "drawer") { - for (std::string_view const key : {"sheet", "dismissLabel"}) { - if (node.prop(key)) { - refuse(pointerAppend(node.path, key), - "`" + std::string{key} + "` is a dialog's; a drawer already fills the height"); - } - } - } else if (node.kind == "dialog" && node.prop("dismissLabel") && !node.prop("sheet")) { + if (node.kind == "drawer" && node.prop("sheet")) { + refuse(pointerAppend(node.path, "sheet"), "`sheet` is a dialog's; a drawer already fills the height"); + } + bool const sheet = node.kind == "dialog" && node.prop("sheet"); + if ((node.kind == "dialog" || node.kind == "drawer") && node.prop("dismissLabel") && !sheet && + !node.prop("closeButton")) { refuse(pointerAppend(node.path, "dismissLabel"), - "`dismissLabel` labels a sheet's dismiss control; give the dialog `sheet`"); + "`dismissLabel` labels a sheet's dismiss control or a `closeButton`; give the " + node.kind + + (node.kind == "dialog" ? " `sheet` or `closeButton`" : " `closeButton`")); } } diff --git a/src/ui/interpreter.cpp b/src/ui/interpreter.cpp index 669d5f5c2..c3210b903 100644 --- a/src/ui/interpreter.cpp +++ b/src/ui/interpreter.cpp @@ -6598,6 +6598,7 @@ void ScreenCore::wireForm(ElementState& element) { } element.form = std::make_unique(runtime(), *std::move(model), aliasSubmits(alias->model), aliasCalls(alias->model), engineOptions()); + followFormatting(element, scope); // An overlay's `decimals` follows its expression: the field keeps the draft as typed and checks it again against // the places the expression gives now. for (DocNodePtr const& record : node.partList("fields")) { @@ -6916,12 +6917,37 @@ forms::FormSessionOptions ScreenCore::engineOptions() const { return options; } +// Keeps a form's, collection's or wizard's number locale and date patterns at the session's current formatting. The +// engine's number locale holds views into the facts it was given, so the effect also holds the facts it last applied. +void ScreenCore::followFormatting(ElementState& element, RtScope& scope) { + auto const held = std::make_shared>(); + forms::FormSession* const form = element.form.get(); + forms::CollectionSession* const collection = element.collection.get(); + forms::WizardSession* const wizard = element.wizard.get(); + scope.nodes.effect([this, held, form, collection, wizard] { + std::shared_ptr const format = session.formattingHandle(); + runtime().untracked([&] { + render::NumericLocale const locale = withoutGrouping(format->numeric); + if (form != nullptr) { + form->setFormat(locale, format->datePattern, format->dateTimePattern); + } + if (collection != nullptr) { + collection->setFormat(locale, format->datePattern, format->dateTimePattern); + } + if (wizard != nullptr) { + wizard->setFormat(locale, format->datePattern, format->dateTimePattern); + } + *held = format; + }); + }); +} + // Builds a collection's or wizard's session when its element is declared. The node's `action` is the collection's // query or the wizard's first step; the catalog answers the document for it, and every call (the query, the actions, // every step's submission) goes through the node's model alias. void ScreenCore::wireComposite(ElementState& element) { DocNode const& node = *element.node; - RtScope const& scope = *element.scope; + RtScope& scope = *element.scope; bool const collection = node.kind == "collection"; std::string const action{node.name("action")}; Catalog const& catalog = session.options().catalog; @@ -6954,6 +6980,7 @@ void ScreenCore::wireComposite(ElementState& element) { element.collection = std::make_unique(runtime(), *std::move(model), schemas, aliasSubmits(alias->model, std::move(query)), call, engineOptions()); + followFormatting(element, scope); return; } // The wizard's id, the stem of its translation keys, is the action it starts with. @@ -6971,6 +6998,7 @@ void ScreenCore::wireComposite(ElementState& element) { try { element.wizard = std::make_unique(runtime(), *std::move(model), schemas, aliasSubmits(alias->model), call, engineOptions()); + followFormatting(element, scope); } catch (std::invalid_argument const& error) { report(node.path, error.what()); } @@ -7110,6 +7138,10 @@ Node ScreenCore::lowerDialog(DocNode const& node, LowerCtx const& ctx, ElementSt .child = std::move(body), .onDismiss = std::move(onDismiss), .side = side && textOf(once(ctx, side), ctx.scope->formatting()) == "start" ? Side::Start : Side::End, + .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), + .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), + .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), + .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), }; if (ExprPtr const spans = node.prop("descriptionSpans")) { spec.descriptionSpans = spansProp(ctx, spans); @@ -7126,6 +7158,9 @@ Node ScreenCore::lowerDialog(DocNode const& node, LowerCtx const& ctx, ElementSt .common = {}, // NOLINT(readability-trailing-comma): the comma ends the designator, not the empty braces. .sheet = bindProp(ctx, node.prop("sheet"), false, boolOf), .dismissLabel = bindProp(ctx, node.prop("dismissLabel"), std::string{"Close"}, stringOf), + .headNote = bindProp(ctx, node.prop("headNote"), std::string{}, stringOf), + .footerNote = bindProp(ctx, node.prop("footerNote"), std::string{}, stringOf), + .closeButton = bindProp(ctx, node.prop("closeButton"), false, boolOf), }; if (ExprPtr const spans = node.prop("descriptionSpans")) { spec.descriptionSpans = spansProp(ctx, spans); diff --git a/tests/qt_quick/test_qt_quick_components.cpp b/tests/qt_quick/test_qt_quick_components.cpp index 92c5777d1..394b539a0 100644 --- a/tests/qt_quick/test_qt_quick_components.cpp +++ b/tests/qt_quick/test_qt_quick_components.cpp @@ -565,6 +565,7 @@ TEST_CASE("qt_quick components: a dialog restyle without the footer part is refu auto refused = components.restyle(probeEngine, "dialog", "BareDialog"); REQUIRE_FALSE(refused.has_value()); CHECK(refused.error().reason == - "restyle of `dialog`: BareDialog does not declare description, descriptionChanged, descriptionRuns, " - "descriptionRunsChanged, footer, footerChanged"); + "restyle of `dialog`: BareDialog does not declare closeButton, closeButtonChanged, description, " + "descriptionChanged, descriptionRuns, descriptionRunsChanged, footer, footerChanged, footerNote, " + "footerNoteChanged, headNote, headNoteChanged"); } diff --git a/tests/qt_quick/test_qt_quick_overlays.cpp b/tests/qt_quick/test_qt_quick_overlays.cpp index 28a699427..38d12a128 100644 --- a/tests/qt_quick/test_qt_quick_overlays.cpp +++ b/tests/qt_quick/test_qt_quick_overlays.cpp @@ -546,6 +546,79 @@ TEST_CASE( CHECK_FALSE(dynamic_cast(*dialog).open()); } +// Mutation: ignore `headNote`, `footerNote` or `closeButton` in MorphDialog/MorphDrawer/MorphFooter (the named item +// is missing, hidden or empty). +TEST_CASE("qt_quick dialog and drawer: head note, footer note and close control are drawn, and the control dismisses", + "[qt_quick]") { + Scene scene; + auto dialog = scene.backend().createDialog(nullptr); + auto drawer = scene.backend().createDrawer(nullptr, ui::Side::End); + int dismissals = 0; + dialog->setTitle("Edit"); + dialog->setOnDismiss([&dismissals] { ++dismissals; }); + drawer->setTitle("Filters"); + drawer->setOnDismiss([&dismissals] { ++dismissals; }); + + // Nothing is drawn until asked for. + dialog->setOpen(true); + scene.settle(); + auto const hidden = [&](char const* name) { + QQuickItem const* const found = namedItem(scene.window().contentItem(), QString::fromLatin1(name)); + return found == nullptr || !found->isVisible(); + }; + CHECK(hidden("headNote")); + CHECK(hidden("footerNote")); + CHECK(hidden("headClose")); + dialog->setOpen(false); + + dialog->setHeadNote("3 of 9"); + dialog->setFooterNote("Saved just now"); + dialog->setCloseButton(true); + dialog->setDismissLabel("Done"); + dialog->setOpen(true); + scene.settle(); + QQuickItem const* const note = namedItem(scene.window().contentItem(), QStringLiteral("headNote")); + REQUIRE(note != nullptr); + CHECK(note->isVisible()); + CHECK(note->property("text").toString() == QStringLiteral("3 of 9")); + QQuickItem const* const foot = namedItem(scene.window().contentItem(), QStringLiteral("footerNote")); + REQUIRE(foot != nullptr); + CHECK(foot->isVisible()); + CHECK(foot->property("text").toString() == QStringLiteral("Saved just now")); + QQuickItem const* const close = namedItem(scene.window().contentItem(), QStringLiteral("headClose")); + REQUIRE(close != nullptr); + CHECK(close->isVisible()); + CHECK(close->property("text").toString() == QStringLiteral("Done")); + scene.click(*close); + CHECK(dismissals == 1); + CHECK_FALSE(dynamic_cast(*dialog).open()); + dialog->setOpen(false); + + // A sheet's head holds the dismiss control already, so `closeButton` adds none. + dialog->setSheet(true); + dialog->setOpen(true); + scene.settle(); + CHECK(hidden("headClose")); + dialog->setOpen(false); + + drawer->setHeadNote("beta"); + drawer->setFooterNote("Unsaved"); + drawer->setCloseButton(true); + drawer->setOpen(true); + scene.settle(); + QQuickItem const* const drawerNote = namedItem(scene.window().contentItem(), QStringLiteral("headNote")); + REQUIRE(drawerNote != nullptr); + CHECK(drawerNote->property("text").toString() == QStringLiteral("beta")); + QQuickItem const* const drawerFoot = namedItem(scene.window().contentItem(), QStringLiteral("footerNote")); + REQUIRE(drawerFoot != nullptr); + CHECK(drawerFoot->isVisible()); + QQuickItem const* const drawerClose = namedItem(scene.window().contentItem(), QStringLiteral("headClose")); + REQUIRE(drawerClose != nullptr); + CHECK(drawerClose->property("text").toString() == QStringLiteral("Close")); + scene.click(*drawerClose); + CHECK(dismissals == 2); +} + namespace { // A popup's left and right edges in window coordinates; the popup is placed in its parent item's coordinates. diff --git a/tests/test_forms_engine_session.cpp b/tests/test_forms_engine_session.cpp index 309582de0..3decfa85d 100644 --- a/tests/test_forms_engine_session.cpp +++ b/tests/test_forms_engine_session.cpp @@ -205,21 +205,56 @@ TEST_CASE("FormSession: a record loaded while a save was in flight takes its lat CHECK(form->field("a").text().peek() == "5"); } -// Mutation: accept what was sent in automatic mode too -> a record's value loads under someone still typing. -TEST_CASE("FormSession: an automatic form's saved field stays an edit", "[forms-engine][session]") { +// Mutation: leave a saved automatic field an edit forever -> another client's value never reaches it. +TEST_CASE("FormSession: an automatic form's saved field takes the record's later value", "[forms-engine][session]") { Harness harness; auto const form = harness.session("TestAction", kTwoInts); harness.type(*form, "a", "9"); harness.type(*form, "b", "2"); REQUIRE(form->successCount() == 1); - // The explicit trigger, which an automatic form also has, is no end of an edit either. + // The explicit trigger, which an automatic form also has, ends an edit the same way. form->submit(); harness.settle(); REQUIRE(form->successCount() == 2); form->refill(R"({"a":5,"b":6})"); harness.settle(); - CHECK(form->field("a").text().peek() == "9"); - CHECK(form->field("b").text().peek() == "2"); + CHECK(form->field("a").text().peek() == "5"); + CHECK(form->field("b").text().peek() == "6"); +} + +// Mutation: load the record's form of the saved value -> `1` becomes `1.000` under the cursor. +TEST_CASE("FormSession: an automatic form's saved field keeps its text when the record echoes the same value", + "[forms-engine][session]") { + constexpr std::string_view kNumber = + R"({"properties":{"mass":{"type":["object","null"],"x-decimalPlaces":3,)" + R"("ExtUnits":{"unitAscii":"kg","unitUnicode":"kg"},"x-order":0}},"required":["mass"]})"; + Harness harness; + auto const form = harness.session("TestAction", kNumber); + harness.type(*form, "mass", "1"); + REQUIRE(form->successCount() == 1); + form->refill(R"({"mass":{"num":1,"den":1,"dp":3}})"); + harness.settle(); + CHECK(form->field("mass").text().peek() == "1"); + form->refill(R"({"mass":{"num":5,"den":2,"dp":3}})"); + harness.settle(); + CHECK(form->field("mass").text().peek() == "2.500"); +} + +// Mutation: end the edit of a field changed after the save was sent -> the record's value replaces what was typed. +TEST_CASE("FormSession: an automatic form's field typed after the save was sent stays an edit", + "[forms-engine][session]") { + Harness harness; + auto const form = harness.session("TestAction", kTwoInts); + harness.server.replyWith([](auto const&) { return std::optional{}; }); + harness.type(*form, "a", "9"); + harness.type(*form, "b", "2"); + harness.type(*form, "a", "12"); + harness.server.resolveSubmit(0, R"({"ok":true})"); + harness.settle(); + REQUIRE(form->successCount() >= 1); + form->refill(R"({"a":5,"b":6})"); + harness.settle(); + CHECK(form->field("a").text().peek() == "12"); } // Mutation: advance the baseline when the save is sent rather than when it succeeds -> a refused save loses what was @@ -316,6 +351,26 @@ TEST_CASE("FormSession: a stored payload round-trips, absent members start blank CHECK(shifted->body()->contains(R"("takenAt":"2026-07-20T09:00:00Z")")); } +// Mutation: leave the locale out of `SessionCore::setFormat` -> the body keeps reading the old decimal separator. +TEST_CASE("FormSession: setFormat moves the number locale and the date patterns of a built form", + "[forms-engine][session]") { + constexpr std::string_view kSchema = R"({"$defs":{"double":{"type":"number"}},"properties":{ + "reading":{"$ref":"#/$defs/double","x-order":0}, + "day":{"type":"string","format":"date","x-order":1}},"required":["reading"],"x-submitMode":"explicit"})"; + Harness harness; + auto const form = harness.session("TestAction", kSchema); + harness.type(*form, "reading", "1,5"); + CHECK_FALSE(form->ready()); + CHECK(form->pattern(true).empty()); + + form->setFormat({.decimalSeparator = ",", .groupSeparator = "."}, "dd.MM.yyyy", "dd.MM.yyyy HH:mm"); + harness.settle(); + CHECK(form->ready()); + CHECK(form->body() == R"({"reading":1.5})"); + CHECK(form->pattern(true) == "dd.MM.yyyy"); + CHECK(form->pattern(false) == "dd.MM.yyyy HH:mm"); +} + TEST_CASE("FormSession: x-blankAs empty submits \"\" once the field was filled, and only then", "[forms-engine][session]") { constexpr std::string_view kEdit = R"({"type":"object","properties":{ @@ -724,7 +779,7 @@ TEST_CASE("FormSession: a collection nobody entered is left out of the body, one auto const form = harness.session("TestAction", kGroupAndRows); harness.type(*form, "n", "1"); CHECK(form->body() == R"({"n":1})"); - form->refill(R"({"rows":[]})"); + form->refill(R"({"n":1,"rows":[]})"); harness.settle(); CHECK(form->body() == R"({"n":1,"rows":[]})"); } diff --git a/tests/test_push_effects.cpp b/tests/test_push_effects.cpp index edd67495a..3126da454 100644 --- a/tests/test_push_effects.cpp +++ b/tests/test_push_effects.cpp @@ -44,11 +44,16 @@ struct ListLate { int limit{}; }; +struct PostItems { + int limit{}; +}; + struct EffectsModel { ItemList execute(EditItem const& /*action*/) { return {}; } ItemList execute(LoadItems const& /*action*/) { return {}; } ItemList execute(OpenItems const& /*action*/) { return {}; } push_records_late::LateList execute(ListLate const& /*action*/) { return {}; } + ItemList execute(PostItems const& /*action*/) { return {}; } }; } // namespace push_effects_test @@ -68,6 +73,13 @@ BRIDGE_REGISTER_EFFECTS(LoadItems, effects::changesInstance) BRIDGE_REGISTER_ACTION(EffectsModel, OpenItems, "T_EffectsOpen") BRIDGE_REGISTER_EFFECTS(OpenItems, effects::none) +// An action whose own declaration is one effect, and which the composing code adds a second to. The addition is +// stated twice, as two composing translation units would. +BRIDGE_REGISTER_ACTION(EffectsModel, PostItems, "T_EffectsPost") +BRIDGE_REGISTER_EFFECTS(PostItems, effects::changesInstance) +BRIDGE_ADD_EFFECTS(PostItems, effects::changes) +BRIDGE_ADD_EFFECTS(PostItems, effects::changes) + // The record this action holds and its effects name is registered in push_records_late.cpp, whose // static initialisers run after this file's. BRIDGE_REGISTER_ACTION(EffectsModel, ListLate, "T_EffectsListLate") @@ -95,6 +107,7 @@ struct VActionA {}; struct VActionB {}; using morph::effects::Kind; +using morph::effects::detail::AddedEffectsMap; using morph::effects::detail::DeclaredEffect; using morph::effects::detail::EffectsMap; using morph::model::detail::ActionResult; @@ -155,6 +168,8 @@ TEST_CASE("effects_declared_are_read_back", "[push][records]") { std::vector{{effects::Kind::Updates, "T_EItem"}, {effects::Kind::Changes, "T_EItem"}}); REQUIRE(effects::effectsOf("T_EffectsLoad") == std::vector{{effects::Kind::ChangesInstance, ""}}); REQUIRE(effects::effectsOf("T_EffectsOpen") == std::vector{{effects::Kind::None, ""}}); + REQUIRE(effects::effectsOf("T_EffectsPost") == + std::vector{{effects::Kind::ChangesInstance, ""}, {effects::Kind::Changes, "T_EItem"}}); REQUIRE(effects::recordsOf("T_EffectsEdit") == std::vector{{"T_EItem", "id", {"items"}}}); } @@ -234,6 +249,157 @@ TEST_CASE("effects_conflict_throws", "[push][records]") { REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("different effects")); } +// ── Effects added by the composing code ────────────────────────────────────── + +TEST_CASE("an_addition_is_unioned_with_the_base_declaration", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Post", result({{.type = typeid(VList), .path = ""}})); + EffectsMap declared; + morph::effects::detail::addEffects(declared, "A_Post", {changesOf(typeid(VRow))}); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Post", {changesOf(typeid(VOther))}); + // The same addition again adds nothing. + morph::effects::detail::addAddedEffects(added, "A_Post", {changesOf(typeid(VOther))}); + REQUIRE(added.at("A_Post").size() == 1); + + auto const resolved = morph::effects::detail::resolveForTesting( + {record("V_Row", typeid(VRow)), record("V_Other", typeid(VOther))}, slots, declared, {}, added); + REQUIRE(resolved.effectsOf("A_Post") == + std::vector{{Kind::Changes, "V_Row"}, {Kind::Changes, "V_Other"}}); +} + +TEST_CASE("an_addition_naming_a_base_effect_does_not_repeat_it", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Post", result({{.type = typeid(VList), .path = ""}})); + EffectsMap declared; + morph::effects::detail::addEffects(declared, "A_Post", {changesOf(typeid(VRow))}); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Post", {changesOf(typeid(VRow))}); + auto const resolved = + morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, declared, {}, added); + REQUIRE(resolved.effectsOf("A_Post") == std::vector{{Kind::Changes, "V_Row"}}); +} + +TEST_CASE("an_addition_alone_declares_an_action_with_no_base", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Assign", result({{.type = typeid(VList), .path = ""}})); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Assign", {changesOf(typeid(VRow))}); + auto const resolved = + morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, {}, {}, added); + REQUIRE(resolved.effectsOf("A_Assign") == std::vector{{Kind::Changes, "V_Row"}}); +} + +TEST_CASE("an_addition_replaces_only_a_base_none", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Quiet", result({{.type = typeid(VList), .path = ""}})); + EffectsMap declared; + morph::effects::detail::addEffects(declared, "A_Quiet", {DeclaredEffect{.kind = Kind::None, .record = {}}}); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Quiet", {changesOf(typeid(VRow))}); + auto const resolved = + morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, declared, {}, added); + REQUIRE(resolved.effectsOf("A_Quiet") == std::vector{{Kind::Changes, "V_Row"}}); +} + +TEST_CASE("two_different_base_declarations_are_refused_whatever_is_added", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Both", result({{.type = typeid(VList), .path = ""}})); + EffectsMap declared; + morph::effects::detail::addEffects(declared, "A_Both", {changesOf(typeid(VRow))}); + morph::effects::detail::addEffects(declared, "A_Both", {changesOf(typeid(VOther))}); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Both", {changesOf(typeid(VRow))}); + std::string message; + try { + static_cast(morph::effects::detail::resolveForTesting( + {record("V_Row", typeid(VRow)), record("V_Other", typeid(VOther))}, slots, declared, {}, added)); + } catch (morph::model::EffectsRegistrationError const& error) { + message = error.what(); + } + REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("`A_Both` declares different effects")); +} + +TEST_CASE("an_addition_for_an_unknown_action_or_record_is_refused", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Known", result({{.type = typeid(VList), .path = ""}})); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Missing", {changesOf(typeid(VRow))}); + morph::effects::detail::addAddedEffects(added, "A_Known", {changesOf(typeid(VOther))}); + std::string message; + try { + static_cast( + morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, {}, {}, added)); + } catch (morph::model::EffectsRegistrationError const& error) { + message = error.what(); + } + REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("`A_Missing`, which is not a registered action")); + REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("`A_Known` declares changes<")); + REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("which is not a registered record")); +} + +TEST_CASE("an_added_updates_must_be_held_by_the_result", "[push][records][added]") { + ActionResultSlotMap slots; + slots.emplace("A_Counts", result({{.type = typeid(VList), .path = ""}})); + AddedEffectsMap added; + morph::effects::detail::addAddedEffects(added, "A_Counts", {updatesOf(typeid(VRow))}); + std::string message; + try { + static_cast( + morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, {}, {}, added)); + } catch (morph::model::EffectsRegistrationError const& error) { + message = error.what(); + } + REQUIRE_THAT(message, Catch::Matchers::ContainsSubstring("result holds no `V_Row`")); +} + +// ── Time-derived facts ─────────────────────────────────────────────────────── + +namespace { + +std::string timeFactRefusal(ActionResultSlotMap const& slots, EffectsMap const& declared, + std::vector const& facts) { + try { + static_cast(morph::effects::detail::resolveForTesting({record("V_Row", typeid(VRow))}, slots, declared, + {}, {}, facts)); + } catch (morph::model::EffectsRegistrationError const& error) { + return error.what(); + } + FAIL_CHECK("resolving did not throw EffectsRegistrationError"); + return {}; +} + +} // namespace + +TEST_CASE("a_time_fact_resolves_to_record_names", "[push][records][time]") { + ActionResultSlotMap slots; + slots.emplace("A_Next", result({})); + auto const resolved = morph::effects::detail::resolveForTesting( + {record("V_Row", typeid(VRow))}, slots, {}, {}, {}, + {{.action = "A_Next", .model = "M_Rows", .records = {typeid(VRow)}}}); + REQUIRE(resolved.changeTimes == std::vector{ + {.action = "A_Next", .model = "M_Rows", .records = {"V_Row"}}}); +} + +TEST_CASE("a_time_fact_is_refused_when_it_names_nothing_registered", "[push][records][time]") { + ActionResultSlotMap slots; + slots.emplace("A_Next", result({})); + auto const unknownAction = + timeFactRefusal(slots, {}, {{.action = "A_Gone", .model = "M", .records = {typeid(VRow)}}}); + REQUIRE_THAT(unknownAction, Catch::Matchers::ContainsSubstring("`A_Gone`")); + REQUIRE_THAT(unknownAction, Catch::Matchers::ContainsSubstring("not a registered action")); + + auto const unknownRecord = + timeFactRefusal(slots, {}, {{.action = "A_Next", .model = "M", .records = {typeid(VOther)}}}); + REQUIRE_THAT(unknownRecord, Catch::Matchers::ContainsSubstring("not a registered record")); + + EffectsMap declared; + morph::effects::detail::addEffects(declared, "A_Next", {changesOf(typeid(VRow))}); + auto const withEffects = + timeFactRefusal(slots, declared, {{.action = "A_Next", .model = "M", .records = {typeid(VRow)}}}); + REQUIRE_THAT(withEffects, Catch::Matchers::ContainsSubstring("also declares effects")); +} + TEST_CASE("action_id_held_by_two_action_types_throws", "[push][records]") { ActionResultSlotMap slots; slots.emplace("A_Shared", result({{.type = typeid(VRow), .path = ""}})); diff --git a/tests/test_push_watch.cpp b/tests/test_push_watch.cpp index 82aff23d4..a721c5974 100644 --- a/tests/test_push_watch.cpp +++ b/tests/test_push_watch.cpp @@ -18,7 +18,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -146,6 +148,50 @@ inline std::binary_semaphore& fanGate() { return gate; } +/// A row that expires by the clock alone. +struct TimedRow { + std::int64_t id{}; +}; + +struct TimedRowList { + std::vector rows; +}; + +/// Reports the next instant a timed row expires. +struct NextTimedExpiry {}; + +/// Changes which instant is next, as an action that adds a row with an earlier expiry would. +struct SetTimedExpiry { + std::int64_t atMs{}; +}; + +/// The instant `NextTimedExpiry` reports in epoch milliseconds; zero reports none. +inline std::atomic& timedNextMs() { + static std::atomic value{0}; + return value; +} + +/// The server's clock in these cases, in epoch milliseconds; the tests advance it without sleeping. +inline std::atomic& timedClockMs() { + static std::atomic value{0}; + return value; +} + +struct TimedModel { + std::optional<::morph::time::DateTime> execute(NextTimedExpiry const& /*action*/) { + auto const next = timedNextMs().load(); + if (next == 0) { + return std::nullopt; + } + return ::morph::time::DateTime{ + std::chrono::sys_time{std::chrono::milliseconds{next}}}; + } + TimedRowList execute(SetTimedExpiry const& action) { + timedNextMs().store(action.atMs); + return {}; + } +}; + struct FanModel { int touched = 0; FanRowList execute(EditFanRow const& action) { return {.rows = {{.id = action.id, .name = "edited"}}}; } @@ -194,6 +240,13 @@ BRIDGE_REGISTER_EFFECTS(EditFanPrivate, morph::effects::updates) BRIDGE_REGISTER_ACTION(FanModel, GatedTouchFan, "T_FanGatedTouch") BRIDGE_REGISTER_EFFECTS(GatedTouchFan, morph::effects::changesInstance) +BRIDGE_REGISTER_RECORD(TimedRow, "T_TimedRow") +BRIDGE_REGISTER_MODEL(TimedModel, "T_TimedModel") +BRIDGE_REGISTER_ACTION(TimedModel, NextTimedExpiry, "T_TimedNext") +BRIDGE_REGISTER_CHANGES_AT(TimedModel, NextTimedExpiry, TimedRow) +BRIDGE_REGISTER_ACTION(TimedModel, SetTimedExpiry, "T_TimedSet") +BRIDGE_REGISTER_EFFECTS(SetTimedExpiry, morph::effects::changes) + namespace { using ::morph::backend::ConnectionId; @@ -859,10 +912,14 @@ struct FanRig { /// before its strand task ends; the coalescing cases pass their own. explicit FanRig(std::chrono::milliseconds executeTimeout = std::chrono::milliseconds{0}, std::shared_ptr<::morph::session::IAuthorizer> authorizer = nullptr, - std::chrono::milliseconds coalesceWindow = std::chrono::milliseconds{0}) { + std::chrono::milliseconds coalesceWindow = std::chrono::milliseconds{0}, + std::function const& configure = {}) { ::morph::backend::ServerConfig config; config.limits.executeTimeout = executeTimeout; config.coalesceWindow = coalesceWindow; + if (configure) { + configure(config); + } config.services.push_back(std::make_shared()); server = authorizer ? std::make_shared(pool, std::move(authorizer), std::move(config)) : std::make_shared(pool, std::move(config)); @@ -1804,3 +1861,167 @@ TEST_CASE("changes_after_a_discarded_queue_are_sent", "[push][watch]") { }, ::morph::testing::WaitBudget{std::chrono::milliseconds{5000}})); } + +// ── Time-derived facts: a record that changes by the clock alone ───────────── + +namespace { + +using std::chrono::milliseconds; + +/// A server whose clock the test sets and whose recheck is short, so the clock is read soon after it moves. +struct TimedRig : FanRig { + TimedRig() + : FanRig{milliseconds{0}, nullptr, milliseconds{0}, [](::morph::backend::ServerConfig& config) { + config.clock = [] { + return ::morph::time::DateTime{ + std::chrono::sys_time{milliseconds{timedClockMs().load()}}}; + }; + config.clockRecheck = milliseconds{5}; + }} { + timedClockMs().store(1000); + timedNextMs().store(0); + } + + /// Whether @p cid is told, within a bound, that `T_TimedRow` changed as a whole type. + bool toldOfRow(ConnectionId cid, std::size_t atLeast = 1) { + auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; + while (std::chrono::steady_clock::now() < deadline) { + flush(); + if (wire(cid).changes().size() >= atLeast) { + return true; + } + std::this_thread::sleep_for(milliseconds{2}); + } + return false; + } + + /// Whether @p cid is told nothing in a short while. + bool toldNothing(ConnectionId cid) { + std::this_thread::sleep_for(milliseconds{60}); + flush(); + return wire(cid).changes().empty(); + } +}; + +} // namespace + +TEST_CASE("a_watcher_is_told_when_the_clock_passes_a_reported_instant", "[push][watch][time]") { + TimedRig rig; + timedNextMs().store(5000); + auto const cid = rig.connect(); + rig.watch(cid, records({"T_TimedRow"})); + // The first envelope handled, the watch above, asked for the instant. + CHECK(rig.toldNothing(cid)); + + timedClockMs().store(4999); + CHECK(rig.toldNothing(cid)); + + timedClockMs().store(5000); + REQUIRE(rig.toldOfRow(cid)); + auto const bodies = rig.wire(cid).changes(); + REQUIRE(bodies.size() == 1U); + REQUIRE(bodies.front().records.size() == 1U); + CHECK(bodies.front().records.front().record == "T_TimedRow"); + CHECK_FALSE(bodies.front().records.front().keys.has_value()); +} + +TEST_CASE("an_instant_that_has_come_is_told_once", "[push][watch][time]") { + TimedRig rig; + timedNextMs().store(5000); + auto const cid = rig.connect(); + rig.watch(cid, records({"T_TimedRow"})); + timedClockMs().store(5000); + REQUIRE(rig.toldOfRow(cid)); + + // The model still reports the instant that has come, as one whose clock runs ahead of the server's would: the + // server asked again after firing, and does not tell the same instant twice. + std::this_thread::sleep_for(milliseconds{60}); + rig.flush(); + CHECK(rig.wire(cid).changes().size() == 1U); +} + +TEST_CASE("an_action_on_the_record_moves_the_awaited_instant", "[push][watch][time]") { + TimedRig rig; + timedNextMs().store(9000); + auto const cid = rig.connect(); + auto const other = rig.connect(); + rig.watch(cid, records({"T_TimedRow"})); + auto const timed = [&] { + auto const env = ::morph::wire::makeRegister("T_TimedModel"); + auto const reply = ::morph::wire::decode(rig.server->handleInline(::morph::wire::encode(env), other)); + REQUIRE(reply.kind == "ok"); + return reply.modelId; + }(); + auto const run = [&](std::int64_t atMs) { + ::morph::wire::Envelope env; + env.kind = "execute"; + env.callId = 3; + env.modelId = timed; + env.modelType = "T_TimedModel"; + env.actionType = "T_TimedSet"; + env.body = glz::write_json(SetTimedExpiry{.atMs = atMs}).value_or(std::string{}); + auto const waiter = std::make_shared<::morph::testing::WaitReply>(); + rig.server->handle(::morph::wire::encode(env), [waiter](std::string const& msg) { (*waiter)(msg); }, other); + REQUIRE(waiter->await()); + REQUIRE(waiter->env.kind == "ok"); + }; + + run(2000); // earlier than the instant the server was waiting for + REQUIRE(rig.toldOfRow(cid, 1)); + std::size_t const afterAction = rig.wire(cid).changes().size(); + + timedClockMs().store(2000); + REQUIRE(rig.toldOfRow(cid, afterAction + 1)); +} + +TEST_CASE("no_pending_instant_tells_nothing", "[push][watch][time]") { + TimedRig rig; + auto const cid = rig.connect(); + rig.watch(cid, records({"T_TimedRow"})); + timedClockMs().store(1'000'000); + CHECK(rig.toldNothing(cid)); +} + +TEST_CASE("a_non_positive_clock_recheck_is_refused", "[push][watch][time]") { + ::morph::exec::ThreadPoolExecutor pool{1}; + ::morph::backend::ServerConfig config; + config.clockRecheck = milliseconds{0}; + CHECK_THROWS_AS(std::make_shared(pool, std::move(config)), std::invalid_argument); +} + +TEST_CASE("the_process_registry_lists_the_reporter", "[push][watch][time]") { + auto const sources = ::morph::effects::changeTimesOf(); + auto const found = + std::ranges::find(sources, std::string{"T_TimedNext"}, &::morph::effects::ChangeTimeSource::action); + REQUIRE(found != sources.end()); + CHECK(found->model == "T_TimedModel"); + CHECK(found->records == std::vector{"T_TimedRow"}); +} + +// The reporter declarations are process-wide; a server asks only those its own registry can run. One that asked the +// rest would leave a model-strand task reading a registry its owner is free to destroy once the reply is in. +TEST_CASE("a_server_asks_only_the_reporters_its_registry_holds", "[push][watch][time]") { + std::mutex mutex; + std::vector asked; + ::morph::log::ScopedLoggerOverride const guard{ + [&](::morph::log::LogLevel, std::string_view message) { + if (message.contains("[timeFacts]")) { + std::scoped_lock const lock{mutex}; + asked.emplace_back(message); + } + }, + ::morph::log::LogLevel::debug, + }; + ::morph::model::detail::ModelRegistryFactory registry; + ::morph::model::detail::ActionDispatcher dispatcher; + { + ::morph::exec::ThreadPoolExecutor pool{2}; + auto const server = + std::make_shared(pool, ::morph::backend::ServerConfig{}, dispatcher, registry); + auto const reply = ::morph::wire::decode( + server->handleInline(::morph::wire::encode(::morph::wire::makeRegister("T_NotHere")))); + CHECK(reply.kind == "err"); + } // the pool joins here: anything the server posted has run + std::scoped_lock const lock{mutex}; + CHECK(asked.empty()); +} diff --git a/tests/test_ui_bound_decimals.cpp b/tests/test_ui_bound_decimals.cpp index abfe26e9f..130016ae7 100644 --- a/tests/test_ui_bound_decimals.cpp +++ b/tests/test_ui_bound_decimals.cpp @@ -337,3 +337,24 @@ TEST_CASE("a form's date fields carry the session's date patterns", "[ui][form-d CHECK(h.backend.prop(h.byTestId("DateTimeInput", "field_day"), "pattern") == "dd.MM.yyyy"); CHECK(h.backend.prop(h.byTestId("DateTimeInput", "field_at"), "pattern") == "dd.MM.yyyy HH:mm"); } + +// Mutation: build the form's options once and never rebuild the form when the formatting changes -> the pattern +// stays at what it was at mount. +TEST_CASE("a mounted form's date fields follow a later change of the session's date patterns", "[ui][form-dates]") { + constexpr std::string_view kSchedule = R"({ + "vocab": "ui/1", "id": "schedule", + "models": { "sample": { "type": "Lims_SampleModel" } }, + "view": { "kind": "form", "id": "sched", "model": "sample", "action": "Lims_ScheduleSample", + "submit": "explicit" } + })"; + Harness h; + h.session.setDatePatterns("dd.MM.yyyy", "dd.MM.yyyy HH:mm"); + auto const screen = h.mount(kSchedule); + REQUIRE(h.diagnostics.empty()); + REQUIRE(h.backend.prop(h.byTestId("DateTimeInput", "field_day"), "pattern") == "dd.MM.yyyy"); + + h.session.setDatePatterns("MM/dd/yyyy", "MM/dd/yyyy hh:mm a"); + h.settle(); + CHECK(h.backend.prop(h.byTestId("DateTimeInput", "field_day"), "pattern") == "MM/dd/yyyy"); + CHECK(h.backend.prop(h.byTestId("DateTimeInput", "field_at"), "pattern") == "MM/dd/yyyy hh:mm a"); +} diff --git a/tests/test_ui_interpreter_control.cpp b/tests/test_ui_interpreter_control.cpp index de2ffff58..0ea234ddf 100644 --- a/tests/test_ui_interpreter_control.cpp +++ b/tests/test_ui_interpreter_control.cpp @@ -1092,6 +1092,30 @@ TEST_CASE("interpreter control: a text's align reaches the backend only when the CHECK_FALSE(h.backend.hasProp(h.byTestId("Text", "none"), "align")); } +// Mutation: leave any of `headNote`, `footerNote`, `closeButton` out of the dialog or drawer lowering (its property is +// never sent), or bind the drawer's from the dialog's keys. +TEST_CASE("interpreter control: a dialog's and a drawer's notes and close control are sent", "[ui][interpreter]") { + Harness h; + auto const screen = h.mount(R"({ + "vocab": "ui/1", "id": "notes", + "state": { "shown": { "init": true } }, + "view": { "kind": "column", "children": [ + { "kind": "dialog", "id": "a", "testId": "a", "title": "Edit", "open": true, "headNote": "3 of 9", + "footerNote": "Saved just now", "dismissLabel": "Done", "closeButton": { "ref": "shown" }, "children": [] }, + { "kind": "drawer", "id": "b", "testId": "b", "title": "Filters", "open": true, "headNote": "beta", + "footerNote": "Unsaved", "closeButton": true, "dismissLabel": "Hide", "children": [] } ] } })"); + int const dialog = h.byTestId("Dialog", "a"); + CHECK(h.backend.prop(dialog, "headNote") == "3 of 9"); + CHECK(h.backend.prop(dialog, "footerNote") == "Saved just now"); + CHECK(h.backend.prop(dialog, "closeButton") == "true"); + CHECK(h.backend.prop(dialog, "dismissLabel") == "Done"); + int const drawer = h.byTestId("Drawer", "b"); + CHECK(h.backend.prop(drawer, "headNote") == "beta"); + CHECK(h.backend.prop(drawer, "footerNote") == "Unsaved"); + CHECK(h.backend.prop(drawer, "closeButton") == "true"); + CHECK(h.backend.prop(drawer, "dismissLabel") == "Hide"); +} + // Mutation: leave the mount's setSheet out for a bound `sheet` (no `sheet` property at all). TEST_CASE("interpreter control: a dialog's sheet follows the width class, and its dismiss label is sent", "[ui][interpreter]") { diff --git a/tests/test_ui_kinds.cpp b/tests/test_ui_kinds.cpp index 1c8efbced..12d0f79ec 100644 --- a/tests/test_ui_kinds.cpp +++ b/tests/test_ui_kinds.cpp @@ -206,6 +206,52 @@ TEST_CASE("ui::drawer: the content exists only while open, a closed drawer takes CHECK(ran == Lines{"apply", "dismiss"}); } +// The notes and the close control reach the widget whether given as constants or bound. Mutations: drop any of the +// three `bind` calls for the notes and the close control in mountOverlay (the property is never set); apply them +// under a different Prop (the values swap). +TEST_CASE("ui::dialog and ui::drawer: head note, footer note and close control reach the widget", "[ui]") { + Owner owner; + Runtime runtime{owner}; + RecordingBackend backend; + Signal note{runtime, "3 of 9"}; + Signal close{runtime, false}; + ui::Node dialogWithNotes = ui::dialog({ + .title = "Edit", + .dismissLabel = "Done", + .headNote = [&] { return note.get(); }, + .footerNote = "Saved just now", + .closeButton = [&] { return close.get(); }, + }); + ui::Node drawerWithNotes = ui::drawer({ + .title = "Filters", + .headNote = "beta", + .footerNote = "Unsaved", + .closeButton = true, + .dismissLabel = "Hide", + }); + ui::Mounted const view{ + runtime, + backend, + ui::column( + {.children = {std::move(dialogWithNotes), std::move(drawerWithNotes), ui::dialog({.title = "Plain"})}}), + }; + CHECK(backend.prop(2, "headNote") == "3 of 9"); + CHECK(backend.prop(2, "footerNote") == "Saved just now"); + CHECK(backend.prop(2, "closeButton") == "false"); + CHECK(backend.prop(2, "dismissLabel") == "Done"); + CHECK(backend.prop(3, "headNote") == "beta"); + CHECK(backend.prop(3, "footerNote") == "Unsaved"); + CHECK(backend.prop(3, "closeButton") == "true"); + CHECK(backend.prop(3, "dismissLabel") == "Hide"); + // A dialog that sets none of them is told none of them. + CHECK(backend.dump().contains("Dialog#4 open=false title=Plain\n")); + note.set("4 of 9"); + close.set(true); + owner.runAll(); + CHECK(backend.prop(2, "headNote") == "4 of 9"); + CHECK(backend.prop(2, "closeButton") == "true"); +} + // A drawer's `open` is controlled as a dialog's is: the user's dismissal closes it, and a document that keeps it open // opens it again over the content it still holds. Mutations: leave Drawer out of RecordingBackend::dismiss's close (it // never shows closed); skip the re-assertion in mountOverlay (it stays closed). diff --git a/tests/tui/test_tui_dialog.cpp b/tests/tui/test_tui_dialog.cpp index 534ff9af3..75fe49284 100644 --- a/tests/tui/test_tui_dialog.cpp +++ b/tests/tui/test_tui_dialog.cpp @@ -149,6 +149,39 @@ TEST_CASE("tui dialog: a sheet fills the screen, its footer at the bottom, and i CHECK(harness.draw().front().starts_with("[ Behind ]")); } +// Control: ignore setHeadNote, setFooterNote or setCloseButton in the overlay (the note or the control is missing from +// the box, or a press on the control dismisses nothing), or let a sheet draw the control too. +TEST_CASE("tui dialog: a head note and a close control end the title's row, a footer note takes the last row", + "[tui][dialog]") { + Harness harness{30, 9}; + Scene scene{harness, {}}; + auto const text = harness.make(scene.body.get()); + text->setText("Sure?"); + int dismissed = 0; + scene.dialog->setOnDismiss([&] { ++dismissed; }); + scene.dialog->setHeadNote("3 of 9"); + scene.dialog->setFooterNote("Saved just now"); + scene.dialog->setCloseButton(true); + scene.dialog->setDismissLabel("Done"); + scene.dialog->setOpen(true); + Rows const rows = harness.draw(); + REQUIRE(rows.size() >= 6); + CHECK(rows.at(2) == " ┌─Confirm─3 of 9─[Done]─┐"); + CHECK(rows.at(3) == " │ Sure? │"); + CHECK(rows.at(4) == " │ Saved just now │"); + CHECK(rows.at(5) == " └───────────────────────┘"); + // A press on the note does nothing; one on the control dismisses once and closes the box. + static_cast(harness.click({.x = 14, .y = 2})); + CHECK(dismissed == 0); + static_cast(harness.click({.x = 21, .y = 2})); + CHECK(dismissed == 1); + CHECK_FALSE(scene.dialog->isOpen()); + // A sheet's head holds its own control, so the close control is not drawn beside it. + scene.dialog->setSheet(true); + scene.dialog->setOpen(true); + CHECK(harness.draw().front().find("[Done]") == harness.draw().front().rfind("[Done]")); +} + TEST_CASE("tui dialog: Esc anywhere inside calls onDismiss", "[tui][dialog]") { Harness harness{30, 10}; Scene scene{harness, {"OK"}}; diff --git a/tests/ui/corpus/documents.json b/tests/ui/corpus/documents.json index 24d73b00f..db418b623 100644 --- a/tests/ui/corpus/documents.json +++ b/tests/ui/corpus/documents.json @@ -296,6 +296,7 @@ {"name": "a stability trend of two conditions", "doc": {"vocab": "ui/1", "id": "t", "state": {"assay25": {"init": {"lit": [{"month": 0, "value": 100}, {"month": 3, "value": 99}]}}, "assay40": {"init": {"lit": [{"month": 0, "value": 100}, {"month": 3, "value": 97}]}}, "trendSummary": {"init": "Both conditions within specification"}}, "view": {"kind": "chart", "summary": {"ref": "trendSummary"}, "yLabel": "Assay, % LC", "series": [{"label": "25 °C / 60 % RH", "points": {"ref": "assay25"}, "x": {"row": "month"}, "y": {"row": "value"}, "xLabel": {"fn": "format", "args": ["{0} m", {"row": "month"}]}}, {"label": "40 °C / 75 % RH", "points": {"ref": "assay40"}, "x": {"row": "month"}, "y": {"row": "value"}, "xLabel": {"fn": "format", "args": ["{0} m", {"row": "month"}]}}], "lines": [{"value": 95, "label": "LSL 95.0", "tone": "err", "style": "dashed"}, {"value": 105, "label": "USL 105.0", "tone": "err", "style": "dashed"}]}}}, { "name": "a head menu with a separator, a description and a submenu", "doc": { "vocab": "ui/1", "id": "t", "menuLabel": "More", "state": { "on": { "init": true } }, "menu": [ { "id": "calibrate", "label": "Calibrate", "onClick": [ { "set": "on", "value": false } ] }, { "separator": true }, { "id": "retire", "label": "Retire", "description": "needs reason", "visible": { "ref": "on" } }, { "label": "Export", "items": [ { "id": "csv", "label": "CSV" } ] } ], "view": { "kind": "text", "text": "x" } } }, { "name": "a head search and a head select", "doc": { "vocab": "ui/1", "id": "t", "state": { "q": { "init": "" }, "lab": { "init": "North" }, "compact": { "init": false } }, "tools": [ { "id": "q", "kind": "search", "label": "Search", "value": { "ref": "q" }, "placeholder": "Sample ID", "width": 24, "onChange": [ { "set": "q", "value": { "ref": "event" } } ], "onSubmit": [ { "set": "q", "value": "" } ], "visible": { "fn": "not", "args": [ { "ref": "compact" } ] } }, { "id": "lab", "kind": "select", "label": "Lab", "style": "dropdown", "options": { "lit": ["North", "South"] }, "selected": { "ref": "lab" }, "onChoose": [ { "set": "lab", "value": { "ref": "event" } } ], "enabled": true } ], "view": { "kind": "text", "text": "x" } } }, + { "name": "a dialog and a drawer with notes and a close button", "doc": { "vocab": "ui/1", "id": "t", "view": { "kind": "column", "children": [ { "kind": "dialog", "id": "d", "headNote": "3 of 9", "footerNote": "Saved", "closeButton": true, "dismissLabel": "Done", "children": [] }, { "kind": "drawer", "id": "e", "headNote": "beta", "closeButton": true, "dismissLabel": "Hide", "children": [] } ] } } }, { "name": "a dialog that is a sheet on compact", "doc": { "vocab": "ui/1", "id": "t", "view": { "kind": "dialog", "id": "d", "title": "Sign", "dismissLabel": "Cancel", "sheet": { "fn": "eq", "args": [ { "env": "widthClass" }, "compact" ] }, "children": [] } } }, { "name": "a title as runs beside the plain title", "doc": { "vocab": "ui/1", "id": "t", "title": "Plate PL-0193", "titleSpans": { "list": [ "Plate ", { "obj": { "text": "PL-0193", "mono": true } } ] }, "view": { "kind": "text", "text": "x" } } }, { "name": "an eyebrow beside its runs", "doc": { "vocab": "ui/1", "id": "t", "eyebrow": "Worksheet WS-1", "eyebrowSpans": { "list": [ "Worksheet ", { "obj": { "text": "WS-1", "mono": true } } ] }, "view": { "kind": "text", "text": "x" } } }, @@ -771,7 +772,8 @@ { "name": "a head tool id used twice", "doc": { "tools": [ { "id": "q", "kind": "search", "label": "Q" }, { "id": "q", "kind": "search", "label": "R" } ] }, "at": "/tools/1/id", "reason": "is used twice" }, { "name": "head tools on the app document", "doc": { "id": "app", "tools": [] }, "at": "/tools", "reason": "is a screen's; the app document has none" }, { "name": "a sheet on a drawer", "doc": { "view": { "kind": "drawer", "id": "d", "sheet": true, "children": [] } }, "at": "/view/sheet", "reason": "is a dialog's; a drawer already fills the height" }, - { "name": "a dismiss label without a sheet", "doc": { "view": { "kind": "dialog", "id": "d", "dismissLabel": "Cancel", "children": [] } }, "at": "/view/dismissLabel", "reason": "labels a sheet's dismiss control" } + { "name": "a dismiss label without a sheet", "doc": { "view": { "kind": "dialog", "id": "d", "dismissLabel": "Cancel", "children": [] } }, "at": "/view/dismissLabel", "reason": "labels a sheet's dismiss control" }, + { "name": "a dismiss label on a drawer without a close button", "doc": { "view": { "kind": "drawer", "id": "d", "dismissLabel": "Hide", "children": [] } }, "at": "/view/dismissLabel", "reason": "labels a sheet's dismiss control or a `closeButton`" } , { "name": "a lead placed at the top", "doc": { "leadPlacement": "top" }, "at": "/leadPlacement", "reason": "`leadPlacement` is `below`, `inline` or `end`" }, { "name": "a title role of display", "doc": { "titleRole": "display" }, "at": "/titleRole", "reason": "`titleRole` is `heading` or `headline`" },