diff --git a/AGENTS.md b/AGENTS.md
index 06efb11..fb2fdc0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -14,13 +14,14 @@ This repository is a Laravel package. Keep the package focused, idiomatic, and e
These are recorded in full in the global standards and under `docs/agent/standards/`; the short form:
-- **Code lives in domain modules.** `src/Domains/{Domain}/` (`Access`, `Dashboard`, `History`, `Navigation`, `Plugins`, `Search`, `Settings`, `Themes`, `Widgets`), namespace `RefactorCircus\Atrium\Domains\{Domain}`, each with a `{Domain}ServiceProvider` registered by `Domains\DomainServiceProvider`. Models are `{Entity}Model` in `Models/`; value objects in `Data/`; registries in `Services/`. Package-wide base classes, contracts and `Support/` stay at the top level. A moved model keeps its old class name as a morph alias. See `architecture/domain-modules` (global standard) and `docs/agent/standards/atrium/domains.md`.
+- **Code lives in domain modules.** `src/Domains/{Domain}/` (`Access`, `Dashboard`, `Navigation`, `Plugins`, `Screens`, `Search`, `Settings`, `Themes`, `Widgets`), namespace `RefactorCircus\Atrium\Domains\{Domain}`, each with a `{Domain}ServiceProvider` registered by `Domains\DomainServiceProvider`. Models are `{Entity}Model` in `Models/`; value objects in `Data/`; registries in `Services/`. Package-wide base classes, contracts and `Support/` stay at the top level. A moved model keeps its old class name as a morph alias. See `architecture/domain-modules` (global standard) and `docs/agent/standards/atrium/domains.md`.
- **Actions own mutating logic.** Extend `RefactorCircus\Keystone\Actions\Action`, implement a `protected handle()` with a concrete return type, and let callers use `execute()`. Action input is a `final readonly` `{Action}Data` in the domain's `Data/` (on `RefactorCircus\Keystone\Data\Data`), never an array: fields are promoted constructor properties (camelCase of the input keys; `T|Missing = new Missing` for partial updates), `rules()` lives on the Data, and the starting event carries it. Requests' `rules()` return `XData::rules()` and `persist()` builds with `XData::fromValidated($this->validated())` - never `XData::from()` in a request; untrusted input elsewhere uses `XData::from()`, which validates, and code that vouches for its values uses `new XData(...)`. Nested input is nested Data (`#[ListOf(WidgetPlacementData::class)]`), checked by the parent's rules under its key (`widgets.*.widget_key`). `tests/ArchTest.php` checks this with Keystone's `Testing\Arch`, along with the event pair on every action, writes only inside a transaction, and a `{Entity}{Hook}Event` for every model hook. `handle()` dispatches a starting `{Subject}{Verb-ing}ActionEvent` with the input, runs the work in a private `perform()` wrapped in `DB::transaction()`, then dispatches the finished `{Subject}{Verb-ed}ActionEvent` with the result.
- **Requests own validation, authorization, and the call into an action.** Extend `RefactorCircus\Atrium\Http\Requests\Request` and implement `persist()`. Controllers only `return $request->persist();` and never contain database calls.
- **Events are final classes using `Dispatchable` and `SerializesModels`.** Action events live in the domain's `Events/` and implement `RefactorCircus\Keystone\Contracts\ActionStartingEvent` or `ActionFinishedEvent` (after commit); every action has one of each. Model events live beside them, are named `{Entity}{Hook}Event`, implement `RefactorCircus\Keystone\Contracts\ModelLifecycleEvent`, and are mapped by the `RefactorCircus\Keystone\Models\Concerns\DispatchesModelEvents` trait every model uses.
- **Shared runtime lives in `refactor-circus/keystone`.** The `Action` and `Request` bases, event contracts, `DispatchesModelEvents`, the package registry and the audit seams come from Keystone, which every package in the suite requires. Atrium registers itself as the `atrium` package from `AtriumServiceProvider::definition()`.
- **Tables are configurable.** Models resolve their table with `getTable()` from `Support\Tables` (`atrium.tables`, on Keystone's `Database\Tables`), and the migrations use the same keys, never literal `atrium_*` names. `tests/ArchTest.php` checks with `Arch::literalTableNames()`, and that every model has a policy in `atrium.policies` with `Arch::modelsWithoutPolicies()`; `tests/Modes/RenamedTables` reruns dashboard flows with every table renamed.
- **Requests authorize through policies.** `authorize()` calls `$this->allows()` / `allowsEach()`: `viewAny`/`create` on the model class, `view`/`update`/`delete` on the instance. Every model has a policy; policies extend `Domains\Dashboard\Policies\Policy`, are registered from `atrium.policies` by `registerPolicies()`, and child-model policies defer to the dashboard through the Gate with Keystone's `Policy::allowsOn()`.
+- **Screens declare themselves.** Every Atrium page with a controller view builds `Domains\Screens\Data\Screen::standard()` with its key, record and kind, resolves it with `ScreenExtensions::resolve()` after its own authorization, and renders `x-atrium::screen-tabs`, `x-atrium::screen-tab-panel` and the sections of every slot it declares. Other packages add tabs and sections through `Atrium::screens()` from `boot()`. Atrium knows no other suite package: it requires only Keystone and has no audit concept (the history screen and audit components live in Keen).
- Do not require a feature-flag package such as Pennant; gating is the host application's concern. Pennant is a dev dependency only, for `Domains\Themes\Features\ThemeSwitcherFeature`, which only Pennant resolves. Feature-flag management lives in `refactor-circus/pennantplus`, which plugs into Atrium like any other package.
## PHP Conventions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fdd5af0..82720cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,18 +7,27 @@
- Moved to the Refactor Circus organisation: the package is now `refactor-circus/atrium` with the PHP namespace `RefactorCircus\Atrium` (it was `jayi/atrium` and `JayI\Atrium`). Update `composer.json` requirements and `use` statements. Old class names are not kept as aliases, so stored values written under them - polymorphic `*_type` columns, audit subjects, Pennant feature names - need updating to the new names.
- Actions take Data objects, not arrays: `CreateDashboardAction` takes a `CreateDashboardData`, `UpdateDashboardAction` an `UpdateDashboardData` (fields left out stay as they are), and `SaveDashboardLayoutAction` a `SaveDashboardLayoutData` whose `widgets` are `WidgetPlacementData` objects (`Domains\Dashboard\Data`). The requests' validation rules live on the Data, and the starting events carry it: `DashboardCreatingActionEvent::$data` and `DashboardUpdatingActionEvent::$data` are Data objects, and `DashboardLayoutSavingActionEvent` carries `$data` (its `widgets`) in place of `$widgets`.
- `Domains\Dashboard\Policies\Policy::allowsOnDashboard()` is gone: policies defer to the parent dashboard with refactor-circus/keystone's `Policy::allowsOn()`, which takes the same arguments.
+- **History moved to Keen.** Atrium has no audit concept any more: the history screen, its components and its nav item now live in [refactor-circus/keen](https://github.com/Refactor-Circus/Keen), which adds a History nav item for every package that audits. Install Keen to keep them, and merge Atrium, Keen and the packages that used them together, since the removal breaks anything still calling them. Removed from Atrium:
+ - the `atrium.history.show` route (`GET {path}/history/{package}`), which now answers 404;
+ - the `History` domain: `RefactorCircus\Atrium\Domains\History\HistoryServiceProvider` (no longer registered by `Domains\DomainServiceProvider`) and `RefactorCircus\Atrium\Domains\History\Http\Controllers\HistoryController`;
+ - the `atrium::history.show` view (`resources/views/history/show.blade.php`);
+ - the `x-atrium::audit-trail` component, `x-atrium::audit.entries`, `x-atrium::audit.changes` and the rest of `resources/views/components/audit/`, with their `@source` lines in `resources/css/atrium.css`;
+ - `RefactorCircus\Atrium\Domains\Plugins\Support\Plugin::historyNavItem()`: stop calling it from a plugin's `navigation()`; Keen adds the links;
+ - the 24 `atrium::atrium.audit_*` translation keys (`audit_history`, `audit_empty`, `audit_when`, `audit_action`, `audit_subject`, `audit_actor`, `audit_surface`, `audit_source_app`, `audit_none`, `audit_system`, `audit_no_changes`, `audit_field`, `audit_before`, `audit_after`, `audit_view_all`, `audit_log`, `audit_log_for`, `audit_action_hint`, `audit_subject_type`, `audit_subject_id`, `audit_filter`, `audit_clear`, `audit_newest`, `audit_older`): a view or a published `lang/vendor/atrium` file that still uses them should take Keen's strings instead.
### Added
+- **Screen extensions**: any package can add tabs and sections to any screen that declares itself, registered from its `boot()` with `Atrium::screens()` (`Domains\Screens\Services\ScreenExtensions`, a singleton) for one screen (`{package}.{screen}`), every screen of a package (`{package}.*`) or every screen (`*`). Definitions are `Domains\Screens\Data\TabDefinition` and `SectionDefinition`, visible only through a `permission()` the screen's `access` closure grants, an `authorize()` closure or `public()`; their `authorize` and `resolve` closures receive the `Screen` last. Hosts declare a screen per request with `Screen::standard()` (the `header.actions`, `before`, `after` slots, plus `aside` or the row slot `row.actions`), resolve it with `ScreenExtensions::resolve()` into a `ResolvedScreen`, and render it with the new `x-atrium::screen-tabs`, `x-atrium::screen-sections` and `x-atrium::screen-tab-panel` components. Answers and data are memoized per request in the `scoped()` `ScreenVisibility`; a failing section is reported once and renders nothing. A same-key duplicate on one target throws in `local` and `testing` and is reported and skipped elsewhere; across targets the most specific wins. See the README's "Screen extensions".
+- `Screen::reserve(string ...$keys)` reserves tab keys a host does not render, such as built-in tabs the viewer may not open: a registered tab with a reserved key is skipped and reported like one using a built-in key, and `?tab=` naming one opens the default tab.
+- Atrium's own pages declare themselves as screens: `atrium.dashboard`, `atrium.named-dashboard`, `atrium.dashboard-widget`, `atrium.settings` (with `row.actions` per settings panel, as a `Domains\Settings\Data\SettingsPanelRow`) and `atrium.settings-panel`. With nothing registered they render as before.
+- `RefactorCircus\Atrium\Testing\ResetsScreenExtensions`, a test case trait that snapshots the screen extensions after boot and restores them after each test (`ScreenExtensions::snapshot()` and `restore()`).
+
- **Lazy widgets**: `WidgetDefinition::lazy()` renders a placeholder with the dashboard and fetches the widget's body afterwards from the new `atrium.dashboards.widgets.show` route (`GET {path}/dashboards/{dashboard}/widgets/{widget}`), which answers whoever may see the dashboard. Widgets stay eager unless marked lazy.
- **Configurable table names**: both tables are named under the new `atrium.tables` config key (`dashboards`, `dashboard_widgets`) and read by the migrations and models through `Support\Tables` (on refactor-circus/keystone's `Database\Tables`). Rename them before migrating; keys a published config leaves out keep their default.
-- A package's audit log link, history page and `` panels show only while the package audits (refactor-circus/keystone's `Package::audits()`: Keen installed and its `{key}.audit.enabled` on), not merely while an audit log is installed.
- Four more themes - **Sunset**, **Forest**, **Midnight** and **Ledger** - and theme layouts: `Theme::layout('top')` (or `'layout' => 'top'` in config) lays the shell out with sections across a bar under the topbar and the current section's pages as tabs beneath, as Ledger does.
- A two-level sidebar: a rail of sections (the app's own pages, then one icon per group) and a docked panel with the current section's pages. Clicking a section shows its pages without leaving the page, and hovering previews them. `NavGroup` gains `icon()` and `sort()` for its place in the rail. `Atrium::navigationSections()` lists the rail's entries.
-- A per-package audit log page at `atrium.history.show` (`/atrium/history/{package}`), with filters and paging, and `Plugin::historyNavItem()` to link it from a plugin's sidebar group. History panels link to it.
- Themes: a second built-in theme, **Harbor**, beside the default **Atrium**; themes from `atrium.themes.available` and `Atrium::theme()`; and a theme switcher beside the light/dark toggle, shown behind the `atrium.themes.switcher_feature` feature (Atrium's own `Domains\Themes\Features\ThemeSwitcherFeature` by default, a Pennant feature that is on until turned off, globally or per user, once a feature resolver such as refactor-circus/pennantplus is registered).
- Shared components so the packages of the suite need no markup or styles of their own: `description-list`, `chip`, `search-input`, `flash`, `banner`, `guest`, `form.combobox`, `form.actions`, a `bare` mode for form controls, and `prefix`/`suffix` slots on `form.input`.
-- History components that read the audit log through refactor-circus/keystone's `AuditTrail`: `audit-trail`, `audit.entries` and `audit.changes`. `audit-trail` renders nothing until an audit log (refactor-circus/keen) is installed.
- `Plugin::featuresFromConfig()`, `RefactorCircus\Atrium\Support\ScreenAccess` and the `AuthorizesScreens` controller trait, so a package's plugin and screens stop copying the same feature loading and policy checks.
- A safelist of layout utilities in the compiled stylesheet, and `RefactorCircus\Atrium\Testing\AtriumStyles` for checking a package's views use only Atrium's styles.
@@ -30,7 +39,6 @@
- A page beneath a navigation item now counts as that item's: an item on a resource's `*.index` route stays active on its `*.show` and `*.edit` pages, and a URL item on the paths beneath it. The sidebar's panel and Ledger's tabs no longer disappear on a record's own page.
- Ledger's top bar no longer has a hover menu as well as its row of tabs.
- Form controls no longer render an `id` twice when one is passed.
-- `audit-trail` shows a package's history only to those its history endpoint would answer.
- `form.input` and `form.select` no longer use `null` as an array offset when no `wrapper` is passed, which PHP 8.5 deprecates.
### Changed
diff --git a/README.md b/README.md
index a9dbd19..9e60863 100644
--- a/README.md
+++ b/README.md
@@ -84,22 +84,6 @@ class BillingPlugin extends Plugin
- `RefactorCircus\Atrium\Support\ScreenAccess::allows('billing', 'refund', $invoice)` asks a package's policies exactly as its JSON API and MCP tools do, honouring its `authorization` switch. Use it to hide controls.
- The `RefactorCircus\Atrium\Http\Controllers\Concerns\AuthorizesScreens` trait gives a screen controller `$this->authorizeScreen('refund', $invoice)`, which answers 403 the same way for the package the controller belongs to.
-### A package's own audit log
-
-With an audit log installed ([refactor-circus/keen](https://github.com/Refactor-Circus/Keen)), every package has its own log at `/atrium/history/{package}`: its entries, newest first, filtered by action or record. Add a link to it in your plugin's sidebar group:
-
-```php
-public function navigation(): array
-{
- return [
- // ...
- $this->historyNavItem('billing')->group('Billing')->sort(90),
- ];
-}
-```
-
-The link and the page show only while an audit log is installed and the user may read the package's history, as its history endpoint decides. `` panels link to the same page.
-
### Registering the plugin
Packages declare their plugin in `composer.json` and Atrium discovers it on install:
@@ -124,6 +108,192 @@ Host applications stay in control. Add plugin classes to `plugins` in `config/at
Discovered plugins are cached in `bootstrap/cache/atrium-plugins.php`, as Laravel caches its package manifest, so a request does not read Composer's `installed.json`. `package:discover` (which Composer runs after every install and update) and `optimize` rebuild it, `atrium:discover` rebuilds it by hand, and `optimize:clear` (or `atrium:clear-discovered`) removes it. Without the file, plugins are read from the installed packages on every boot, as before.
+## Screen extensions
+
+Any package can add tabs and sections to any screen that declares itself, without the screen knowing the package exists. A screen declares only generic facts: its key (`{package}.{screen}`), its record, its kind, its built-in tabs and its slots. Atrium declares its own pages: `atrium.dashboard` (`/`), `atrium.named-dashboard` (`d/{slug}`), `atrium.dashboard-widget`, `atrium.settings` and `atrium.settings-panel`.
+
+### Registering tabs and sections
+
+Register from a service provider's `boot()`, and only there. The registry lasts for the process and nothing can be unregistered, so a registration made during a request would leak into the next one. Each registration is copied, so changing your definition afterwards changes nothing.
+
+```php
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Http\Request;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Data\SectionDefinition;
+use RefactorCircus\Atrium\Domains\Screens\Data\TabDefinition;
+use RefactorCircus\Atrium\Facades\Atrium;
+
+public function boot(): void
+{
+ Atrium::screens()
+ // A tab on one screen, opened with ?tab=acme.invoices.
+ ->tab('crm.customer', TabDefinition::make('acme.invoices')
+ ->label('Invoices')
+ ->icon('banknotes')
+ ->view('acme::screens.invoices')
+ ->permission('acme.invoices.view')
+ ->resolve(fn (?Model $record, Screen $screen): array => [
+ 'invoices' => Invoice::forCustomer($record)->latest()->get(),
+ ]))
+
+ // A section in one slot of one screen.
+ ->section('crm.customer', 'aside', SectionDefinition::make('acme.balance')
+ ->component('acme::balance')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $request->user()?->can('view', $record) === true)
+ ->resolve(fn (?Model $record, Screen $screen): array => ['balance' => Balance::of($record)]))
+
+ // A row section: rendered once per row of a list screen, with the row as $record.
+ ->section('crm.customers', 'row.actions', SectionDefinition::make('acme.row-balance')
+ ->view('acme::screens.row-balance')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $record instanceof Customer))
+
+ // A wildcard section: every screen that declares the slot. Return early.
+ ->section('*', 'aside', SectionDefinition::make('acme.notes')
+ ->view('acme::screens.notes')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $screen->kind === Screen::DETAIL
+ && $record !== null
+ && $request->user()?->can('acme.notes', $record) === true));
+}
+```
+
+- **Targets.** An exact screen key (`crm.customer`), every screen of one package (`{package}.*`, such as `crm.*`), or every screen (`*`). A `*` tab joins every declared screen; a `*` section joins every screen declaring its slot. A section on a slot the screen does not declare never renders and its closures never run, and a registration for a screen no installed package declares is kept and never renders, with no error.
+- **Keys.** Prefix every key with your vendor, as `vendor.key` (`acme.invoices`). Keys go into `?tab=`, `data-testid` and URLs, and match `^[a-z0-9][a-z0-9._-]*$`. A registered tab may not reuse a built-in tab key (`overview` included): it is skipped and reported.
+- **Rendering.** Give each tab or section a `view()` or a `component()` (setting one clears the other). A view receives the resolver's data with the host's `screen` (the `Screen`), `record` and `tab` (the open tab's key) over it, so the host's values win. A component receives the resolver's data as one `data` prop.
+- **Who sees it.** Extensions are hidden by default. One shows only when its `permission()` passes the screen's `access` closure, its `authorize()` closure returns `true`, both pass when it has both, or it is `public()`. A screen without an `access` closure hides every `permission()` extension. An `authorize()` that throws counts as a denial and is reported once per request.
+
+### Closures and evaluation order
+
+Every closure receives the `Screen` last:
+
+```php
+->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => ...)
+->resolve(fn (?Model $record, Screen $screen): array => [...])
+```
+
+`$record` is the screen's record (null on screens without one), or the row inside a row slot.
+
+1. The host authorizes the request itself. Nothing of yours runs on a page the viewer may not open.
+2. The host resolves the screen. Each registered tab's visibility is checked, then each section's when its slot renders, once per row in a row slot.
+3. Resolvers run only for what renders: the open registered tab and each visible section in a rendered slot. Answers and data are remembered for the request, per screen, slot, extension and record.
+
+Wildcard and row-slot closures run on every matching screen or row, so keep them cheap: return early on `$screen->key` or `$screen->kind` before any query.
+
+### Opening tabs
+
+A tab opens through `?tab={key}`. An absent or unknown key opens the host's default tab with a 200. A registered tab the viewer cannot see answers 403. That 403-versus-200 difference reveals which tab keys exist, which is accepted: never put anything secret in a key.
+
+The tab bar shows only when two or more tabs are visible. A screen with no built-in tabs gets one, `overview`, holding the page. Registered tabs follow the built-in ones (exact registrations first, then wildcard ones, each in registration order) and are never the default. Built-in labels come from the host; Atrium translates nothing.
+
+A host that leaves out a built-in tab the viewer may not open still reserves its key with `$screen->reserve('salaries')`: a registered tab using a reserved key is skipped and reported, as for a built-in key, so it shows to no one. Reserved keys never render, and `?tab=` naming one opens the default tab with a 200. They match the same key pattern; an invalid one throws.
+
+### What renders around an open registered tab
+
+The tab's panel replaces the host's page content. `header.actions` always renders; `before`, `after`, `aside` and row slots render only while a built-in tab is open.
+
+A section renders into a buffer: one whose resolver or view throws renders nothing, is reported once per request, and the page still answers 200. An open registered tab's panel that throws fails the page (500), as the page itself would.
+
+The tab bar and the sections use only Atrium's design tokens and safelisted utilities, so they look the same in every theme and layout, and a theme sets nothing for them. Keep your views to the same contract and check them with `AtriumStyles` (see [Package styles](#package-styles)).
+
+A section renders inside the host's page, but it writes through your own routes and your own authorization: forms in it post to your routes, and your requests authorize them. The host only decided who may open the page.
+
+### Duplicates
+
+- **The same key twice on one target** (the same target string, and for sections the same slot): registration throws `InvalidArgumentException` naming the key and the target in the `local` and `testing` environments. In production, and any other environment, it reports the exception once through `report()`, skips the later registration and keeps the first, rather than taking down every route and command from `boot()`.
+- **The same key on one screen through different targets**: the more specific target wins: the exact key, then `{package}.*`, then `*`. Each less specific duplicate is skipped and reported once per request.
+
+### Declaring a screen
+
+A host declares a screen per request with `Screen::standard()`, which gives the standard slots: `header.actions`, `before` and `after`, plus `aside` on a `detail` screen or the row slot `row.actions` on a `list` screen. Add more with `slots()` and `rowSlots()`. Resolve it only after your own authorization:
+
+```php
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions;
+
+public function show(Request $request, Invoice $invoice, ScreenExtensions $screens): View
+{
+ $this->authorizeScreen('view', $invoice);
+
+ $screen = Screen::standard('acme.invoice', Screen::DETAIL)
+ ->record($invoice)
+ ->tabs([
+ ['key' => 'details', 'label' => __('Details'), 'icon' => 'document-text'],
+ ['key' => 'payments', 'label' => __('Payments'), 'icon' => 'banknotes'],
+ ])
+ ->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record ? [$record] : []));
+
+ return view('acme::invoices.show', [
+ 'invoice' => $invoice,
+ 'resolved' => $screens->resolve($screen, $request),
+ ]);
+}
+```
+
+```blade
+
+ @if ($resolved->sections('header.actions') !== [])
+
+
+
+ @endif
+
+
+
+
+@if ($resolved->openRegisteredTab !== null)
+
+@else
+
+
+ {{-- Your page, for the built-in tab $resolved->openTab. --}}
+
+
+
+@endif
+```
+
+On a list screen, render the row slot inside each row: ` `.
+
+### Packages know nothing of each other
+
+Atrium requires only [Keystone](https://github.com/Refactor-Circus/Keystone) among the suite's packages; every other suite package is a `suggest`, never a requirement, and a package's Atrium UI loads only when Atrium is installed. So a package's code never names another package's screens. It ships editable defaults in its own config instead, and the application changes or empties the list:
+
+```php
+// config/acme.php
+'atrium' => [
+ 'screens' => [
+ // The target screen => 'tab', or the slot to add a section to.
+ 'crm.customer' => 'tab',
+ 'crm.contact' => 'aside',
+ ],
+],
+```
+
+```php
+// AcmeServiceProvider::boot(); Atrium is suggested, so it may be missing.
+if (class_exists(Atrium::class)) {
+ foreach (config('acme.atrium.screens', []) as $target => $slot) {
+ $slot === 'tab'
+ ? Atrium::screens()->tab($target, $this->invoicesTab())
+ : Atrium::screens()->section($target, $slot, $this->balanceSection());
+ }
+}
+```
+
+A default takes effect only when its target screen exists: a registration for a screen nobody declares never renders.
+
+### Testing
+
+Registrations made in a test would otherwise outlive it. Use `RefactorCircus\Atrium\Testing\ResetsScreenExtensions` on your test case: it snapshots the registry once the application has booted, keeping every provider's `boot()` registrations, and restores the snapshot after each test.
+
+```php
+uses(TestCase::class, ResetsScreenExtensions::class)->in('Feature');
+```
+
## Managing Pennant feature flags
The Feature flags page moved to [refactor-circus/pennantplus](https://github.com/Refactor-Circus/PennantPlus), which registers it as an Atrium plugin when both are installed.
@@ -170,7 +340,7 @@ Available components:
**Forms**: `form.input` (with `prefix` and `suffix` slots), `form.textarea`, `form.select`, `form.checkbox`, `form.radio`, `form.file`, `form.combobox`, `form.actions`. Pass `bare` to an input, textarea, select or checkbox for the control alone, such as in a table cell.
-**History**: `audit-trail` (a package's or one record's history, from the installed audit log), `audit.entries`, `audit.changes`
+**Screens**: `screen-tabs`, `screen-sections` and `screen-tab-panel`, which render a declared screen's extensions (see [Screen extensions](#screen-extensions))
### Screen conventions
@@ -540,6 +710,7 @@ The code is organised into domain modules under `src/Domains/{Domain}`, namespac
| `Dashboard` | `Models\DashboardModel` and `Models\DashboardWidgetModel`, their policies, actions, events, requests and controllers, and `Services\DashboardManager` |
| `Navigation` | `Data\NavItem`, `Data\NavGroup` and `Services\NavigationRegistry` |
| `Plugins` | The `Contracts\Plugin` contract, the `Support\Plugin` base class, `Services\PluginRegistry`, Composer discovery and the plugin commands |
+| `Screens` | `Data\Screen`, `Data\TabDefinition`, `Data\SectionDefinition` and `Data\ResolvedScreen`, `Services\ScreenExtensions` (the registry behind `Atrium::screens()`) and `Services\ScreenVisibility` |
| `Search` | `Data\SearchSource`, `Data\SearchResult`, `Services\SearchRegistry` and the search endpoint |
| `Settings` | `Data\SettingsPanel`, `Services\SettingsRegistry` and the settings pages |
| `Widgets` | `Data\WidgetDefinition` and `Services\WidgetRegistry` |
diff --git a/config/atrium.php b/config/atrium.php
index 648439d..81e7298 100644
--- a/config/atrium.php
+++ b/config/atrium.php
@@ -102,12 +102,11 @@
|--------------------------------------------------------------------------
|
| Atrium keeps no audit log of its own. With refactor-circus/keen
- | installed, Keen records every dashboard change Atrium makes, and
- | Atrium shows each package's history while that package audits.
+ | installed, Keen records every dashboard change Atrium makes and shows
+ | each package's history.
|
| enabled: Set to false to keep Atrium's own dashboard changes out of the
- | audit log even while Keen is installed. Other packages' history
- | follows their own `audit.enabled`.
+ | audit log even while Keen is installed.
|
*/
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/brief.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/brief.md
new file mode 100644
index 0000000..58010b1
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/brief.md
@@ -0,0 +1,36 @@
+Risk: high
+
+## What changed
+- New `Domains/Screens`:
+ - the `ScreenExtensions` registry, a singleton reached through `Atrium::screens()`
+ - `TabDefinition` and `SectionDefinition`
+ - `Screen`, with `standard()` slots: `header.actions`, `before`, `after`, `aside`, and the row slot `row.actions`
+ - `ResolvedScreen`
+ - the per-request memo `ScreenVisibility`
+ - wildcard targets `*` and `{package}.*`
+ - the `x-atrium::screen-tabs`, `screen-tab-panel` and `screen-sections` components
+ - the `Testing\ResetsScreenExtensions` trait
+- All five Atrium pages declare themselves with a tab bar, the standard slots and a Gate `access()` check: the dashboard, the named dashboard, widget detail, the settings index (with a `row.actions` slot on each panel row) and the settings panel.
+- Removed and moved to Keen (D-014, D-016):
+ - the History domain, the `history/{package}` route and `HistoryController`
+ - `x-atrium::audit-trail` and `x-atrium::audit.*`
+ - `Plugin::historyNavItem()`
+- Added a README and Boost "Screen extensions" section, a CHANGELOG upgrade note, and a browser matrix over 6 themes, 2 layouts and light/dark.
+
+## Why
+This makes "register it from your own package" the only way to add tabs and sections to any screen, so host packages stop checking whether other packages are installed (D-017: no package knows another; integrations go through config). It generalises Roster's registered tabs (Roster PR #5).
+
+## Look at
+- `src/Domains/Screens/Services/ScreenExtensions.php`: registration, the duplicate rules by environment (D-022), and exact/`pkg.*`/`*` precedence (D-023, D-028).
+- `src/Domains/Screens/Services/ScreenVisibility.php`: the per-request memo keyed by morph class plus key or the model itself. Visibility answers must never leak across viewers.
+- `resources/views/components/screen-sections.blade.php`: failure isolation. It snapshots and restores the view factory's state so that a throwing section can't break the page (D-015).
+- `src/Domains/Settings/Data/SettingsPanelRow.php`: the unsaved stand-in that carries each settings panel row (D-031, D-033).
+
+## Tested
+- `composer test`: phpstan 0 errors, pint, 100% type coverage, pest 589/589.
+- `composer test:browser`: 46/46, including the 24 theme × layout × mode cases. The gate didn't run this suite; I ran it by hand after the job escalated.
+- `npm run build:css`: `public/atrium.css` is unchanged, so the committed file is current.
+
+## Risks
+- Breaking: the history page, the audit components and `historyNavItem()` are gone. Every host that uses them breaks until its own spec lands (see Breaks). Merge as a group: Atrium, Keen, then the hosts (D-009).
+- Wildcard and row-slot closures run on every matching screen or row, so a slow registrant slows every page. The README tells registrants to return early.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/build.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/build.md
new file mode 100644
index 0000000..9f5f0e0
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/build.md
@@ -0,0 +1,264 @@
+# Build: Screen extensions registry
+
+## Group 1 (salvaged)
+
+**Found.** No index lock and no merge or rebase in progress. The previous build agent left every group 1 file in the worktree, uncommitted: the `Domains/Screens` domain (`ScreensServiceProvider`, `DefinesExtension`, `TabDefinition`, `SectionDefinition`, `Screen`, `ResolvedScreen`, `ScreenExtensions`, `ScreenVisibility`), `Testing\ResetsScreenExtensions`, the edits to `DomainServiceProvider`, `Atrium`, the facade and `tests/TestCase.php`, and all seven test files. It had ticked 1.1 to 1.3 in `tasks.md` but committed nothing and wrote no build note. `tests/Pest.php` needed no change and is untouched.
+
+**Checked.** Read every file against criteria 1 to 8 and 11 and task 1.1's list: singleton and `Atrium::screens()`; setters, defaults, `Error` on writes and closure reads, view/component exclusivity, trailing `Screen`; key, slot and target validation with every D-026 reject; clone on register; `123`/`007` as strings through `?tab=`; duplicates per environment (local/testing throw, production reports once and keeps the first); cross-target precedence in all three pairings for tabs and sections; `snapshot()`/`restore()`/`flush()` and the trait's two-test behaviour; `Screen::make`/`standard()`; tab ordering, reserved keys (exact and `*`), `?tab=` string-only, unknown key 200, hidden key 403; the visibility matrix, throwing `authorize` reported and called once, memo by morph class plus key or the unsaved model itself, `forgetScopedInstances()` between viewers; `*` and `test.*` matching. All present. `php -l` passes on all 20 files. The suite was not run here; the gate runs it.
+
+**Committed.** The 20 group 1 files listed above, plus 1.1 and 1.2 ticked in `tasks.md` and this note.
+
+**Left.**
+- 1.3 (`vendor/bin/pest` green) is unticked: there is no record that the previous agent ran the suite.
+- Two related edits by the previous agent sit outside the group's file list and are left uncommitted in the worktree: `phpstan.neon.dist` adds `tests/TestCase.php` to the analysed paths, so PHPStan analyses the published `ResetsScreenExtensions` trait through its one user instead of reporting it unused; and `docs/agent/standards-feedback.md` records `Screen::kind()` taking a string (with `Screen::DETAIL`/`Screen::LIST`) rather than an enum, because the spec fixes `kind('detail'|'list')` and `standard(string $key, string $kind)`. `composer analyse` likely needs the `phpstan.neon.dist` change.
+- `AGENTS.md` and the group 5 bullet reformat in `tasks.md` are not group 1 changes and are left as found.
+
+## Group 1
+
+Retry to finish 1.3. Nothing had run the group's tests before this, so this pass ran them.
+
+**Files.** `tests/Feature/Screens/VisibilityTest.php` (fixed); also `phpstan.neon.dist` and `docs/agent/standards-feedback.md`, which are outside the group's file list (see Deviations).
+
+**Tests.** `vendor/bin/pest tests/Unit/Screens tests/Feature/Screens` first failed 4 of 172 tests, all in `VisibilityTest`: "hides an extension whose authorize closure throws" and "evaluates afresh for another viewer", for both the tab and the section case. The bug was in the tests, not in `ScreenVisibility`. Each test registered its counting closure inside an arrow function (`fn ($d) => $d->authorize(function () use (&$calls) { ... })`). An arrow function captures `$calls` by value, so the counter the inner closure incremented was the arrow function's copy and the test always saw 0. Both registrations are now plain closures that capture `use (&$calls)` / `use (&$asked, &$resolved)`. After the fix, all 172 pass (392 assertions). `pint --test` passes on every group 1 file, and `phpstan analyse` passes with 0 errors. The full suite was not run here; the gate runs it.
+
+**Deviations.**
+- `phpstan.neon.dist` adds `tests/TestCase.php` to the analysed paths, and this group needs it. Without it, PHPStan reports `trait.unused` on the published `Testing\ResetsScreenExtensions` trait (checked against a copy of the config without that path) and `composer analyse` fails. With it, PHPStan analyses the trait through its one user.
+- `docs/agent/standards-feedback.md` records the `data/value-objects` deviation: `Screen::kind()` takes a string, with `Screen::DETAIL`/`Screen::LIST` constants, instead of an enum, because the spec fixes `kind('detail'|'list')` and `Screen::standard(string $key, string $kind)`.
+
+## Group 4
+
+Built in the `--g4` worktree on `ring-master/2026-10-29-2037-screen-extensions-registry--g4`.
+
+**Files.**
+- Added `tests/Feature/HistoryRemovedTest.php`: `GET /atrium/history/billing` is 404 even with an auditing package and an installed audit trail, and `atrium.history.show` is not a route; `HistoryController` and `HistoryServiceProvider` don't load, and `src/Domains/History`, `history/show`, `audit-trail` and `components/audit/` don't exist; `method_exists(Plugin::class, 'historyNavItem')` is false; no `@source` line in `atrium.css` names `audit` or `history/`.
+- Deleted `src/Domains/History/` (provider, `routes.php`, `HistoryController`), `resources/views/history/show.blade.php`, `resources/views/components/audit-trail.blade.php`, `resources/views/components/audit/` (`entries`, `changes`), `tests/Feature/HistoryPageTest.php` and `tests/Feature/AuditComponentsTest.php`.
+- Edited `resources/css/atrium.css` (dropped the four `@source` lines) and `src/Domains/Plugins/Support/Plugin.php` (removed `historyNavItem()` and its now unused imports).
+
+**Tests.** The new test was written before the deletions. The suite was not run here; the gate runs it.
+
+**Deviations.** These files are outside the group's list:
+- `src/Domains/DomainServiceProvider.php`: dropped `HistoryServiceProvider`, as task 4.2 says.
+- `tests/Feature/DomainLayoutTest.php`: dropped `HistoryServiceProvider` from its provider dataset. Without this the test can't load the class.
+- `lang/en/atrium.php`: removed the 24 `audit_*` keys. Only the deleted views and `historyNavItem()` used them. Keen ships its own.
+- `config/atrium.php`: in the `audit` comment, the claim that Atrium shows each package's history now says Keen does it.
+- `docs/agent/standards/atrium/components.md`: dropped `audit-trail`, `audit.entries` and `audit.changes` from the generic pieces.
+
+**Left for group 6** (it owns these files): `README.md` lines 96, 101 and 173 (`historyNavItem`, `x-atrium::audit-trail`, the History components list); `History` in `CLAUDE.md`, in `docs/agent/standards/atrium/domains.md` and in that standard's description in `docs/agent/standards.index.yml`; rebuilding `public/atrium.css`; the `CHANGELOG.md` upgrade note. The Boost skill had no references.
+
+## Group 2
+
+Built in the `--g2` worktree on `ring-master/2026-10-29-2037-screen-extensions-registry--g2` (commit `667f2d8`).
+
+**Files.**
+- Components: `resources/views/components/screen-tabs.blade.php` (a `flex ... overflow-x-auto` `` of `x-atrium::icon-button` links built with `request()->fullUrlWithQuery(['page' => null, 'tab' => $key])`, primary variant and `aria-current="page"` on the open tab only, unknown icons fall back to `squares-2x2`, nothing below two tabs), `screen-sections.blade.php` (visible sections in order, each wrapped in `data-testid="section-{key}"` with any `class`, each rendered into a buffer and isolated), `screen-tab-panel.blade.php` (the open registered tab in `data-testid="tab-panel-{key}"`, with failures left to propagate).
+- Workbench: `workbench/app/Atrium/ScreenHost/ScreenHostController.php` (`detail` → `test.host`, `list` → `test.list` with three keyed rows; both take another screen key as `{screen?}`; it authorizes through the `viewScreenHost` gate when one is defined, then declares `Screen::standard()`, adds the built-in tabs from `config('screen-host.tabs')` and the extra slots from `config('screen-host.slots')`, and resolves; `register()` loads the routes and the `workbench::` views into a feature test's app), `workbench/resources/views/screen-host.blade.php` (laid out per criterion 15), `workbench/routes/web.php`.
+- Tests (all in `tests/Feature/Screens/`): `EvaluationOrderTest`, `RowSlotsTest`, `WildcardRenderingTest`, `FailureIsolationTest`, `ScreenTabsComponentTest`, `ScreenSectionsComponentTest`, `OpenRegisteredTabTest`, `ScreenStylesTest`.
+
+**Tests.** Written before the components. The group's test files and the rest of `tests/Feature/Screens` (99 tests, 383 assertions) pass, as do `tests/ArchTest.php`, `AtriumStylesTest` and `ComponentLibraryTest`. `pint --test` passes on the new PHP files. The full suite was not run here; the gate runs it.
+
+**Deviations.**
+- These files are outside the group's list. They are shared fixtures in `tests/Fixtures/views`, which is already on the test view path (testing/test-layers puts shared fixtures there): `screens/marker.blade.php`, `screens/spread.blade.php`, `screens/throws.blade.php` and the anonymous component `components/screen-probe.blade.php`.
+- Section isolation snapshots the view factory's state and restores it when a section fails. When a view throws, Laravel's `View::render()` calls `flushState()`, which empties the enclosing page's component stack, and the page then fails with a 500. A buffer alone cannot isolate the failure.
+- `flex-nowrap` is not in the compiled `public/atrium.css`, so the nav does not use it. A flex row's default `flex-wrap` is already `nowrap`, which is what criterion 17 measures.
+- A section's failure is passed to `report()`, which reports it once per request per screen and key through `ScreenVisibility::report()`. Laravel's handler does not log `HttpException`s, so an `abort()` inside a section is isolated but never logged. The test asserts isolation only for that case.
+- `ConvertEmptyStringsToNull` turns a bare query key such as `b` in `?q[]=a&b` into null, and the URL helper then leaves it out of the tab links. The test asserts the escaped `q%5B0%5D=a`.
+- View-path data: `screen` is the `Screen`, `record` is the screen's record or the row, and `tab` is the open tab's key (`ResolvedScreen::openTab`). The component path gets only `data`. This is returned to the user as a decision.
+
+## Group 3
+
+Partly built. Four screens are complete. The settings index's `row.actions` is waiting on a decision (see Left).
+
+**Files.**
+- `src/Domains/Dashboard/Http/Controllers/DashboardController.php`: after its own 404, declares `Screen::standard('atrium.dashboard' | 'atrium.named-dashboard', 'detail')` with the dashboard as its record, and passes `resolved` to the view.
+- `src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php`: after its 404s, declares `atrium.dashboard-widget` (detail, with the widget as its record) and passes it as `widgetScreen`. It is not passed as `resolved` because the dashboard page includes `widget-body` inline for widgets that are not lazy, and the dashboard's own `$resolved` would leak into that include.
+- `src/Domains/Settings/Http/Controllers/SettingsController.php`: `atrium.settings` (list, no record) and, after the 404, `atrium.settings-panel` (detail, no record).
+- Views (`dashboard/index`, `dashboard/widget-body`, `settings/index`, `settings/show`) are laid out per criterion 15. `header.actions` goes in the page header's actions, and the tab bar sits under the header. An open registered tab's panel replaces the page content. `before` and `after` render above and below that content. `aside` is a `lg:grid-cols-3` column (`data-testid="screen-aside"`) that renders only when it has a visible section. The dashboard also hides its edit-layout buttons and save status while a registered tab is open. The settings pages add the page header's actions slot only when `header.actions` has a visible section. As a result, with nothing registered, no wrapper, tab bar or empty actions container renders.
+- `tests/Feature/Screens/AtriumScreensTest.php`: a dataset over the five screens:
+ - A section in every slot renders in its slot, in order (header actions, then the tab bar, `before`, the page content, `aside`, `after`), and its resolver runs once.
+ - A section in an undeclared slot never renders, and its resolver never runs.
+ - The tab appears beside `overview` and opens through `?tab=`, showing only `header.actions` and the panel.
+ - With nothing registered, there is no tab bar, tab, section or aside markup.
+ - Two further tests: a widget body with nothing registered is byte-for-byte the widget's own view (trimmed), and the dashboard's inline widget bodies never render `atrium.dashboard-widget` sections.
+
+**Tests.** Written before the code. `AtriumScreensTest` passes (17 tests, 177 assertions). `SettingsTest`, `LazyWidgetTest`, `DashboardRoutesTest`, `DashboardLayoutTest`, `DashboardPersistenceTest`, `AtriumStylesTest` and `ArchTest` also pass (75 tests). `pint --test` and `composer analyse` pass. The full suite was not run here; the gate runs it.
+
+**Deviations.** None. Every class used is already in the compiled `public/atrium.css`.
+
+**Left.**
+- `row.actions` on `atrium.settings` is declared, because `Screen::standard(..., 'list')` declares it, but it is not rendered per settings panel row. A settings panel is a `SettingsPanel` value object, not a model. `ResolvedScreen::rowSections()`, `data()` and `x-atrium::screen-sections :row` all take a `Model`, so rendering it needs a choice about the public contract. That choice is returned to the user as a decision. The dataset leaves `row.actions` out of the settings index's expected slots until it is settled. 3.1 and 3.2 stay unticked for this reason, and 3.3 stays unticked with them.
+- No Atrium screen sets `access()`, so `permission()` extensions are hidden on all five (criterion 8's default). Which permission check Atrium's screens should use is returned to the user as a decision.
+
+## Group 3
+
+Run 3, after D-031 and D-032. D-032 is built. D-031 is stopped before any code because it conflicts with an arch test (see Left).
+
+**Files.**
+- `src/Domains/Dashboard/Http/Controllers/DashboardController.php`, `DashboardWidgetController.php` and `src/Domains/Settings/Http/Controllers/SettingsController.php`: all five screens (`atrium.dashboard`, `atrium.named-dashboard`, `atrium.dashboard-widget`, `atrium.settings`, `atrium.settings-panel`) declare the D-032 `access()` closure, `Gate::forUser($request->user())->allows($permission, $record ? [$record] : [])`. `SettingsController` shares it between its two screens through a protected `access(Screen)` method.
+- `tests/Feature/Screens/AtriumScreensTest.php`: two new tests.
+ - On every screen, a `permission()` tab and `header.actions` section show while the Gate allows the ability and are hidden while it denies it (10 cases).
+ - The Gate gets the screen's record as its one argument: the dashboard on both dashboard screens and the widget on the widget screen. It gets no arguments on the two settings screens (5 cases).
+
+**Tests.** Written before the code. The "allowed" cases fail without `access()`, because criterion 8 hides every `permission()` extension on a screen that has none. `AtriumScreensTest` passes (32 tests, 237 assertions). `pint --test` passes on the changed files and `composer analyse` reports 0 errors. The full suite was not run here; the gate runs it.
+
+**Deviations.** None.
+
+**Left.**
+- D-031 (`row.actions` per settings panel row) is not built. D-031 places the stand-in at `Domains\Settings\Models\SettingsPanelRowModel` and says its policy entry keeps the every-model-has-a-policy arch test passing. It doesn't cover the arch test "every model fires an event for every lifecycle hook" (`Arch::modelEventGaps()` over every `Domains/*/Models/*.php`, per models/lifecycle-events). A stand-in at that path fails that test unless it uses `DispatchesModelEvents` and ten `Domains\Settings\Events\SettingsPanelRow{Hook}Event` classes exist. None of those events would ever fire, because the model is never saved. Adding them creates public event classes, and exempting the stand-in changes `tests/ArchTest.php` (group 6's file) and breaks a standard. That choice is returned to the user as a decision. The model, its policy, the `atrium.policies` entry, the per-row rendering and the per-row test all wait on it.
+- 3.1 and 3.2 stay unticked until `row.actions` is built, and 3.3 stays unticked with them.
+
+## Group 3
+
+Run 4, after D-033. This finishes `row.actions` on `atrium.settings` and the group.
+
+**Files.**
+- Added `src/Domains/Settings/Data/SettingsPanelRow.php`. It is a final Eloquent model with strict types, and it is never saved. Its string primary key `key` holds the panel's key, it has no incrementing key or timestamps, and it carries the panel as `public private(set) SettingsPanel $panel`. Rows are built with `SettingsPanelRow::for($panel)`. It sits in `Data/`, not `Models/`, so it has no policy entry, no lifecycle events and no arch-test exemption (D-033).
+- `src/Domains/Settings/Http/Controllers/SettingsController.php`: `index()` passes `rows`, one `SettingsPanelRow` per visible panel. It still passes `panels` as well, so views that hosts have already published keep working.
+- `resources/views/settings/index.blade.php`: iterates `rows`. Each panel card renders `x-atrium::screen-sections :screen="$resolved" slot="row.actions" :row="$row" class="mt-3"` under its button. The cards sit inside the built-in branch, so row sections don't render while a registered tab is open (criterion 15).
+- `tests/Feature/Screens/AtriumScreensTest.php`:
+ - The dataset's settings index now expects `row.actions` as a rendered slot (the full plugin's panel is its one row), placed after the page content. The open-tab case now also asserts that `row.actions` is hidden and its resolver never runs.
+ - New test: three panel rows (`alpha`, `beta`, `full`) with a section that admits only `beta`. The markup appears once, in `beta`'s card. `authorize` ran three times, each time with that row's `SettingsPanelRow` (key, panel key and the `Screen`), and the resolver ran once.
+ - New test: rendering fresh `SettingsPanelRow` instances for the same panels twice in one request makes no further calls. This shows the memo is keyed by the panel key, not the object.
+ - New test: a row is unsaved, keyed by the panel key, and carries the panel.
+
+**Tests.** Written before the code. They use `SettingsPanelRow`, which didn't exist yet, but they were not run until the code was in. These pass:
+- `AtriumScreensTest`: 35 tests, 264 assertions.
+- `SettingsTest`, `ArchTest` and `AtriumStylesTest`: 34 tests.
+
+`pint --test` passes on the changed files, and `composer analyse` reports 0 errors. The full suite was not run here; the gate runs it.
+
+**Deviations.** None. `mt-3` is already in the compiled `public/atrium.css`.
+
+## Group 3
+
+Run 5, a retry for 3.1 (the per-row `row.actions` test), 3.2 (`SettingsPanelRow` and per-row rendering) and 3.3. Run 4 (`a403788`) had already committed all of it and ticked 3.1 to 3.3, so this run changed no code.
+
+**Files.** None changed beyond this note. Checked against D-031 and D-033:
+- `src/Domains/Settings/Data/SettingsPanelRow.php` is final, has strict types, and is an unsaved Eloquent model keyed by the panel key that carries the `SettingsPanel`.
+- `SettingsController::index()` passes one row per panel.
+- `settings/index` renders `screen-sections slot="row.actions" :row="$row"` once per panel card.
+- The arch test "action input validates itself" scans `Data/` only for subclasses of Keystone's `Data`, so the stand-in doesn't trip it.
+
+**Tests.** `AtriumScreensTest`, `ArchTest` and `SettingsTest` pass (56 tests, 293 assertions). The full suite was not run here; the gate runs it.
+
+**Deviations.** None.
+
+## Group 5
+
+**Files.**
+- Added `workbench/app/Atrium/ScreenHost/ScreenHostPlugin.php`. It is a final plugin keyed `screen-host`, with a `Screen host` navigation group whose two pages are `test.host` and `test.list`. The top layout draws a group with pages as a `top-tabs` row, so the matrix has a row to check for overlap.
+- `workbench/app/Providers/WorkbenchServiceProvider.php` registers the plugin for `composer serve`.
+- Added `tests/Browser/ScreenExtensionsTest.php`. It runs the dataset `screen extension looks`, 6 themes x `sidebar`/`top` x light/dark, as 24 named cases (`with data set "ledger top dark"`).
+ - **Setup.** Each case registers the plugin with `ScreenHostController::register()` and renders `test.list`. The page has the built-in tabs `details` and `activity`, and twelve public registered tabs, `acme.tab-1` to `acme.tab-12`. The last one has the long label. There is a section in `before` and one in the `row.actions` row slot.
+ - **Theme, layout and mode.** The theme comes from `atrium.themes.default`. The case sets the theme's layout on the registry's `Theme` before the visit. The mode comes from `inDarkMode()`/`inLightMode()`. The test asserts `data-atrium-theme`, `data-atrium-layout` and `.dark` match the case. In the top layout it also asserts the sidebar is hidden and the `group-screen-host` `top-tabs` row is visible. In the sidebar layout it asserts the sidebar is visible and the top nav is hidden.
+ - **Sections.** The `before` section renders once. The row section renders three times, once per row, including in `row-2`.
+ - **Tab bar.** These are asserted before and after the last tab opens. The links come in order: built-ins first, then the registered tabs. The nav's computed `overflow-x` is `auto` or `scroll`, and its `flex-wrap` is `nowrap`. Every link's `white-space` is `nowrap`. All links share one rounded top offset. In the top layout, exactly one `top-tabs` row is on screen and no tab's box overlaps it. In the sidebar layout there is none.
+ - **Last tab.** After `scrollIntoView`, the last tab lies inside the nav's box and the viewport. A click opens it with `aria-current="page"`, `details` loses `aria-current`, and its panel renders. With the pointer moved onto the panel, the open tab's computed background is not transparent and differs from both `details` and `acme.tab-1`.
+ - **Screenshot.** One per case, taken on the built-in tab: `tests/Browser/Screenshots/screen-extensions/{theme}-{layout}-{mode}.png`.
+
+**Tests.** The test was written before the plugin existed. `vendor/bin/pest tests/Browser/ScreenExtensionsTest.php` passes 24 tests (744 assertions), and passes again on a second run. `pint --test` passes on every changed file. Only this file ran: the full suite and `composer test:browser` were not run here, because the gate runs them.
+
+**5.2.** The matrix exposed no theme or layout issue in any of the 24 cases. I looked through the screenshots and nothing is clipped, wrapped or overlapping. No component or stylesheet changed.
+
+**Deviations.**
+- `tests/Pest.php` is outside the group's file list. At boot, pest-plugin-browser's `Screenshot::cleanup()` unlinks every entry in `tests/Browser/Screenshots` and then removes the directory. It can't unlink the `screen-extensions` subdirectory, so it can't remove `Screenshots` either. Each failure raises a suppressed warning, and `failOnWarning` fails the run: the second run of the file passed 24 tests and still exited 1 with 2 warnings. `Pest.php` now empties and removes `Screenshots/screen-extensions` before the plugin boots, outside parallel workers so they never race to delete it. The test makes the directory again. With this change, back-to-back runs exit 0.
+
+## Group 5
+
+Run 2, a retry of 5.1 to 5.3. Run 1 (`fb8ad25`) had already committed all of it and ticked 5.1 to 5.3, so this run changed no code.
+
+**Files.** None changed beyond this note. Checked against criteria 17 and 18:
+- `tests/Browser/ScreenExtensionsTest.php` runs a Pest dataset of 24 named cases (6 themes x `sidebar`/`top` x light/dark). Each case renders `test.list` with 2 built-in tabs, 12 public registered tabs (the last with a long label), a `before` section and a `row.actions` section.
+- Each case asserts these:
+ - The theme, layout and mode match the case.
+ - Both sections render, the row section once in each row.
+ - The nav's `overflow-x` is `auto` or `scroll` and its `flex-wrap` is `nowrap`. Every link's `white-space` is `nowrap`, and all links share one top offset. These are checked before and after the last tab opens.
+ - In the top layout no tab overlaps the one visible `top-tabs` row.
+ - The last tab scrolls into view, opens on a click with `aria-current="page"`, and, with the pointer on the panel, has a background that differs from the idle tabs'.
+ - A screenshot is saved to `tests/Browser/Screenshots/screen-extensions/{theme}-{layout}-{mode}.png`. That path is gitignored.
+- `ScreenHostPlugin` gives the top layout its `top-tabs` row. `WorkbenchServiceProvider` registers it for `composer serve`. The test suites boot only `AtriumServiceProvider`, so this registration doesn't affect them.
+
+**Tests.** `pint --test` passes on the four group files (`tests/Pest.php` included). The suite and `composer test:browser` were not run here; the gate runs them.
+
+**Deviations.** None beyond run 1's `tests/Pest.php` change, recorded above.
+
+## Group 6
+
+**Files.**
+- `tests/ArchTest.php` gains these rules:
+ - The `Domains\Screens` classes are final.
+ - `Domains\Screens` and `Testing\ResetsScreenExtensions` declare strict types.
+ - Every public property of `Screen`, `TabDefinition`, `SectionDefinition` and `ResolvedScreen` is `public private(set)`, and none of them is a `Closure`.
+ - `ScreensServiceProvider` is in `DomainServiceProvider::$providers`.
+ - `composer.json`'s `require` lists `refactor-circus/keystone` and no other `refactor-circus/*` package.
+ - The History domain, `views/history`, `audit-trail` and `components/audit` no longer exist. This is criterion 20's arch test.
+- Added `tests/Feature/DocsTest.php`:
+ - The `## Screen extensions` section of the README and of the Boost skill contains `boot()`, `403`, `vendor.key`, `Keystone` and `config`, plus a marker for each bullet of criterion 21.
+ - The README, the skill, `CLAUDE.md` and `domains.md` mention no `atrium.history`, `x-atrium::audit`, `audit-trail`, `historyNavItem` or `history/{package}`.
+ - `CLAUDE.md` and `domains.md` list `Screens` and not `History`.
+ - `CHANGELOG.md` names each removed route, class, method and component, Keen and `ScreenExtensions`.
+- `README.md`:
+ - New "Screen extensions" section, covering registration (tab, section, row section, `*` section), targets, keys, rendering, visibility, closures and evaluation order, opening tabs (403 versus 200), what renders around an open tab, failures, the theme contract, writing through your own routes, duplicates per environment and across targets, declaring a screen with `Screen::standard()` plus its Blade layout, the suite rule, the config-defaults pattern with an example, and the `ResetsScreenExtensions` trait.
+ - Removed "A package's own audit log" (`historyNavItem`, `audit-trail`) and the History components line.
+ - Added the Screens components and a `Screens` row in the package layout table.
+- `resources/boost/skills/atrium-development/SKILL.md` has the same "Screen extensions" content in compact form. The front-matter description, the component list and the domain list in the anti-patterns are updated, and two anti-patterns are new: registering outside `boot()` or naming another package's screens in code, and requiring a suite package.
+- `CLAUDE.md` is a symlink to `AGENTS.md`, so the edit went to `AGENTS.md`. The domain list has `Screens` and drops `History`, and a new "Screens declare themselves" convention says Atrium requires only Keystone and has no audit concept.
+- `docs/agent/standards/atrium/domains.md` lists `Screens` and drops History in the front matter and the list. New lines describe the Screens domain and say History belongs to Keen.
+- `CHANGELOG.md`:
+ - Breaking: an upgrade note naming the `atrium.history.show` route, `HistoryServiceProvider`, `HistoryController`, the `atrium::history.show` view, `x-atrium::audit-trail`, `x-atrium::audit.entries`, `x-atrium::audit.changes`, the rest of `components/audit/` with its `@source` lines, and `Plugin::historyNavItem()`. It points to refactor-circus/keen and says to merge as a group.
+ - Added: the registry, Atrium's declared screens and `ResetsScreenExtensions`.
+ - Removed: the unreleased Added and Fixed entries that announced the history page, `historyNavItem()` and the audit components, which the note now supersedes.
+- `npm run build:css` left `public/atrium.css` byte-identical, because the new components' classes were already compiled. It did add the `@source` lines for `screen-sections`, `screen-tab-panel` and `screen-tabs` to `resources/css/atrium.css`, which is committed.
+
+**Workspace grep (6.3), for the PR.** Pattern: `atrium\.history|x-atrium::audit|historyNavItem`. Excluded: `vendor`, `node_modules`, `.git`, `storage` and `specs`.
+- **This worktree:** only `CHANGELOG.md` (the upgrade note), `tests/Feature/HistoryRemovedTest.php` and `tests/Feature/DocsTest.php` (both assert the removal), plus this spec's own files. Nothing in `src`, `resources`, `docs/agent/standards`, the README or the Boost skill.
+- **Main checkouts (on `main`, before the grouped merge):**
+ - Atrium: 7 files (the history view, `audit-trail`, `Plugin.php`, README, CHANGELOG, two tests). This job removes them.
+ - Cortex: 10 files.
+ - Impex: 10.
+ - Keen: 6.
+ - PennantPlus: 6.
+ - Polycart: 8.
+ - Roster: 9.
+ - Showroom: 16.
+
+ In each of these packages the matches are its plugin's `historyNavItem()` call, its views' `x-atrium::audit-trail`, a `HistoryNavigationTest`, and its docs.
+ - Keystone, Ringside, Standards and Stretch: none.
+- **Sibling job worktrees** (`Cortex--…-register-roster-redirect-domains`, `Impex--…-register-showroom-run-link`, `Keen--…-history-section-by-capability`, `PennantPlus--…`, `Polycart--…`, `Roster--…-adopt-atrium-screen-registry`, `Showroom--…`): the same files still match. Those packages must drop the references in their own specs before the grouped merge (D-009).
+
+**Tests.** I wrote the tests first. Only `tests/ArchTest.php` and `tests/Feature/DocsTest.php` ran here: 31 tests and 92 assertions, all passing. `pint --test` passes on both. I didn't run `vendor/bin/pest`, `composer test` or `composer test:browser`; the gate runs them (6.4 is ticked for the gate).
+
+**Deviations.**
+- `AGENTS.md` (the target of the `CLAUDE.md` symlink) is the file actually edited. It already had an unrelated uncommitted line from a ringside sync ("Keep this checkout on `main`…"). Only this group's hunks are committed; that line is left uncommitted.
+- `resources/css/atrium.css` is outside the group's file list. `npm run build:css` regenerates its `@source` list, and this commit includes the result.
+
+## Group 6
+
+Run 2, a retry of 6.1 to 6.4. Run 1 (`6877adc`) had already committed all of it and ticked 6.1 to 6.4, so this run changed no committed code.
+
+**Files.** Only this note changed. I checked run 1's work against criteria 16, 20, 21 and 22:
+- `DocsTest` and the new `ArchTest` rules are as listed above.
+- `composer.json` requires `refactor-circus/keystone` and no other suite package.
+- `npm run build:css` leaves `public/atrium.css` byte-identical again.
+- A grep of `src`, `resources`, `docs/agent/standards`, the README and the workbench finds no `atrium.history`, `x-atrium::audit`, `historyNavItem` or `audit-trail`. Run 1's workspace grep for the PR stands.
+
+One more `docs` reference turned up. The generated `docs/agent/standards.index.yml` still described `atrium/domains` with `History` and without `Screens`, because run 1 edited `domains.md` without rebuilding the index, and `ringside check` failed. Running `ringside sync` in the worktree rebuilt it, and `ringside check` now passes. The index is gitignored, so there is nothing to commit for it. The sync also rewrote the uncommitted `AGENTS.md` ringside line, which stays uncommitted as before.
+
+**Tests.** `tests/Feature/DocsTest.php` and `tests/ArchTest.php` pass (31 tests, 92 assertions). `pint --test` passes on both files, and `phpstan analyse` reports 0 errors. I didn't run `vendor/bin/pest`, `composer test` or `composer test:browser`; the gate runs them.
+
+**Deviations.** None in the worktree. Outside it, my first `ringside check` and `ringside sync` ran in the workspace root (`/Users/jay/Projects/packages`), because the shell's cwd resets between calls. The sync regenerated the workspace's own ringside outputs: `docs/agent/standards.index.yml`, `docs/agent/standards.summary.md` and 14 `.claude/skills/ring-master-*/SKILL.md` files. Those are generated files, and the workspace is not a git repo.
+
+## Rework round 1
+
+**Fixed.**
+- Minor (changelog): the History upgrade note in `CHANGELOG.md` now lists the 24 removed `atrium::atrium.audit_*` translation keys by name. It tells a view or a published `lang/vendor/atrium` file that still uses them to take Keen's strings instead.
+- Nit (architecture/domain-modules): `DefinesExtension` moved from `src/Domains/Screens/Data/Concerns/` to `src/Domains/Screens/Concerns/` (namespace `RefactorCircus\Atrium\Domains\Screens\Concerns`). That is the domain-level `Concerns/` folder the standard lists, as `Domains/Access/Concerns` already uses. `TabDefinition` and `SectionDefinition` import it from there. The trait is internal to the two definitions and is not named in the README, the skill or the CHANGELOG. `tasks.md` still lists the old path in group 1's file list, which records what that group built.
+
+**Tests.** `composer test:unit` passes (589 tests, 1760 assertions). `composer lint:check` passes, and `composer analyse` reports 0 errors.
+
+## Rework round 2
+
+**Fixed.**
+- Minor (gate, criterion 16): I ran the `public/atrium.css` done-step again. `npm run build:css` registered 62 Blade files as sources. The compiled `public/atrium.css` came out byte-identical to the committed file, which is also identical to `main`'s, so the file has no diff to commit. The three new components use only classes that the compiled safelist already holds, and `AtriumStylesTest`/`ScreenStylesTest` assert that. Removing the audit components' `@source` lines dropped no compiled class. The only stylesheet change against `main` is the regenerated `@source` list in `resources/css/atrium.css`, which group 6 committed.
+- Same finding (criterion 22): `composer test:browser` now runs. It passes 46 tests with 824 assertions: the 24 `ScreenExtensionsTest` matrix cases and the existing browser suite. The run left no tracked file changed, because the screenshots are gitignored.
+
+**Tests.** `composer test:unit` passes (589 tests, 1760 assertions). `composer test:browser` passes (46 tests, 824 assertions).
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decision.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decision.md
new file mode 100644
index 0000000..8026d02
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decision.md
@@ -0,0 +1,16 @@
+# Factory decision
+
+Status: approved as is (escalated at review round 3: review rounds exhausted)
+
+Accepted finding (minor, gate): the browser suite (criteria 17, 18) and the `public/atrium.css` rebuild (criterion 16) were not verified by the gate. They were verified by hand afterwards: `composer test:browser` passed 46/46 and `npm run build:css` left the file unchanged.
+
+Nits: none.
+
+Breaks: these consumer packages still use `x-atrium::audit*`, `historyNavItem()` or `atrium.history`, so they break until their specs land.
+- Cortex: 6 files
+- Impex: 6 files
+- Keen: 5 files
+- PennantPlus: 4 files
+- Polycart: 5 files
+- Roster: 6 files
+- Showroom: 12 files
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decisions.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decisions.md
new file mode 100644
index 0000000..2c391b7
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/decisions.md
@@ -0,0 +1,159 @@
+# Decisions
+
+D-001 to D-008 are recorded in `shape.md`.
+
+## D-009: How should x-atrium::audit-trail leave Atrium while hosts still use it inline?
+- Choice: Remove it now, and merge Atrium, Keen and the hosts as a group
+- Rationale: Accepted the recommendation. Breaking changes are fine because nothing is on Packagist yet.
+- Date: 2026-10-29
+- Raised by: spec review (scope, risk)
+
+## D-010: How does the test reset treat registrations made in boot()?
+- Choice: Take a snapshot after boot and restore it after each test; keep flush() for the registry's own unit tests
+- Rationale: Accepted the recommendation. A plain flush would wipe consumers' boot() registrations.
+- Date: 2026-10-29
+- Raised by: spec review (testability)
+
+## D-011: What shape should the published testing helper take?
+- Choice: A Pest trait `Testing\ResetsScreenExtensions` that registers the beforeEach/afterEach hooks
+- Rationale: Accepted the recommendation. It sits alongside the existing `Testing\AtriumStyles`.
+- Date: 2026-10-29
+- Raised by: spec review (scope)
+
+## D-012: Should the browser theme matrix be a dataset or one looped test?
+- Choice: A Pest dataset, with one test per theme, layout and mode combination
+- Rationale: Accepted the recommendation. Each failure names its combination.
+- Date: 2026-10-29
+- Raised by: spec review (testability)
+
+## D-013: Do Atrium's own screens adopt Screen::make in this spec? (Q-002)
+- Choice: Yes, and more broadly: every Atrium screen in every package declares itself with `Screen::make`, gets a tab bar, and declares the standard slots. Atrium's own screens are declared in this spec: dashboard, named dashboard, widget detail, settings index and settings panel. Each package's spec declares that package's screens.
+- Rationale: "update all screen across all packages to have support for slots/tab bars".
+- Date: 2026-10-29
+- Raised by: spec review (scope)
+
+## D-014: Where does the history screen live?
+- Choice: In Keen. `history/{package}` (`HistoryController`, `history/show`) moves from Atrium to Keen, along with `x-atrium::audit.entries`, since nothing else in Atrium would use it. This supersedes D-007's "audit.entries stays in Atrium". Atrium's history route, controller, view and component are removed in this spec.
+- Rationale: "the history screen should be moved to keen."
+- Date: 2026-10-29
+- Raised by: user, during spec review
+
+## D-015: How do resolver and view failures affect the host screen? (Q-004)
+- Choice: Isolate sections and row slots: report once per request, skip the section, and the screen still returns 200. Propagate failures in the open tab's panel.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review (risk)
+
+## D-016: Does Plugin::historyNavItem() move to Keen? (Q-008)
+- Choice: Yes. Keen adds a History nav item for every package that audits, and plugins stop calling `historyNavItem()`, which Atrium removes.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review (scope)
+
+## D-017: Suite principle: packages have no knowledge of each other (answer to Q-003)
+- Choice: Atrium has no knowledge of Keen. Keen's functionality is purely plug and play. No package has knowledge of another. Companion packages may be suggested but not required. Integrations are done through simple config.
+- Rationale: In the user's words: "atrium should have no knowledge of keen. keens functionality should be purely plug and play, no package should have knowledge of another. we can suggest companion packages but no require them. itegrations should be done via simple config"
+- Consequence for this spec: `Screen::audits()`, `AuditedSubject`, `ScreenExtensions::audited()` and criterion 10 are removed. The registry instead supports wildcard screen targets (`*`, `{package}.*`), and screens declare only generic facts: key (from which the package is derived), record, tabs and slots. Q-003 no longer applies.
+- Date: 2026-10-29
+- Raised by: spec review (testability), Q-003
+
+## D-018: Which hard requirements may a package have?
+- Choice: Keystone only. Every other suite package, Atrium included, is a `suggest`. A package's UI loads only when Atrium is present, as Keen, Polycart and PennantPlus already do. Roster, Cortex, Impex and Showroom drop `require refactor-circus/atrium`. Guardian suggests Roster and integrates through Roster's seams and config.
+- Rationale: Accepted the recommendation, applying D-017.
+- Date: 2026-10-29
+- Raised by: user, following D-017
+
+## D-019: What shape does "integration via simple config" take?
+- Choice: The registrant ships editable defaults in its own config. Example: `config/cortex.php` `atrium.redirect_domains.screens => ['roster.organization' => 'tab', 'roster.user' => 'aside']`. A default only takes effect when the target screen exists, and the app may change or empty the list. Code never names another package; only the editable config does.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: user, following D-017
+
+## D-020: Rewrite the spec in place, or keep the addenda as overrides?
+- Choice: Rewrite the criteria, Goal and Design in place; keep the addenda only as a short changelog
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (scope)
+
+## D-021: Which Atrium screens does this spec declare?
+- Choice: Every Atrium page that has a controller view, listed by key in the spec: dashboard (`/`), named dashboard (`d/{slug}`), widget detail, settings index and settings panel
+- Rationale: Accepted the recommendation, applying D-013.
+- Date: 2026-10-29
+- Raised by: spec review recheck (scope)
+
+## D-022: Same key registered twice on one target
+- Choice: Throw `InvalidArgumentException` in local and testing. In production, report once, skip the later registration and keep the app running.
+- Rationale: Accepted the recommendation. A throw in boot() would take down every route and command.
+- Date: 2026-10-29
+- Raised by: spec review recheck (risk)
+
+## D-023: A wildcard and an exact registration with the same key on one screen
+- Choice: The exact registration wins. The wildcard duplicate is skipped and reported once per request.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (risk)
+
+## D-024: What renders around an open registered tab?
+- Choice: The tab's panel replaces the host's page content. `header.actions` always renders; `before`, `after` and `aside` render only on built-in tabs.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (scope)
+
+## D-025: How do closures receive the Screen?
+- Choice: `Screen` is passed as a trailing argument to every `authorize` and `resolve` closure
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (testability)
+
+## D-026: Wildcard grammar and duplicate scope
+- Choice: Only `*` and `{package}.*`. Duplicates are checked per target string at boot; cross-target clashes are resolved at render time by D-023 and reported once.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (testability)
+
+## D-027: Test reset API names
+- Choice: `ScreenExtensions::snapshot(): array` and `restore(array $snapshot)`. The `ResetsScreenExtensions` trait snapshots once after boot and restores after each test. `flush()` stays for the registry's own unit tests.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: spec review recheck (testability)
+
+## D-028: A `*` and a `{package}.*` registration use the same key on one screen
+- Choice: The more specific target wins: the exact key, then `{package}.*`, then `*`. The less specific duplicate is skipped and reported once per request.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: the in-place rewrite (gap in D-023/D-026)
+
+## D-029: Approval
+- Choice: Approved for tasks and the factory
+- Date: 2026-10-29
+- Raised by: spec review (approval)
+
+## D-030: Types of the host variables a registered view receives
+- Choice: `screen` is the `Screen` (the same object closures receive), `record` is the screen's record or the row, and `tab` is the open tab's key string (`ResolvedScreen::openTab`). Components get only the `data` prop.
+- Rationale: Accepted the recommendation, which matches what group 2 built and tested.
+- Date: 2026-10-29
+- Raised by: build (group 2)
+
+## D-031: row.actions per settings panel row when panels aren't models
+- Choice: Wrap each panel in an unsaved stand-in Eloquent model, `Domains\Settings\Models\SettingsPanelRowModel`, keyed by the panel key and carrying the panel, so registrants receive it as `$record` and the memo by morph class plus key applies. The Screens contract doesn't change. The stand-in gets a policy entry in `atrium.policies`, deferring to the settings screen's own authorization, so the every-model-has-a-policy arch test holds.
+- Rationale: Accepted the recommendation.
+- Date: 2026-10-29
+- Raised by: build (group 3)
+
+## D-032: The access() closure on Atrium's own screens
+- Choice: Laravel Gate: `Gate::forUser($request->user())->allows($permission, $record ? [$record] : [])`, as the workbench test host does
+- Rationale: Accepted the recommendation. It works for screens without a record.
+- Date: 2026-10-29
+- Raised by: build (group 3)
+
+## D-033: Where the settings-row stand-in lives
+- Choice: `Domains\Settings\Data\SettingsPanelRow`, an unsaved Eloquent model kept out of `Models/`. Neither model arch test scans it, so it needs no lifecycle events, no policy entry and no exemption. This supersedes D-031's namespace and policy entry; the rest of D-031 stands.
+- Rationale: The user chose this to keep the extra surface minimal.
+- Date: 2026-10-29
+- Raised by: build (group 3)
+
+## D-034: Screen::reserve() for keys the viewer may not open
+- Choice: Screen::reserve() for keys the viewer may not open; reserved, not rendered, not openable; added for Roster adopt D-031 at the user's request (2026-10-30)
+- Rationale: Roster must reserve the keys of built-in tabs the current viewer may not open without rendering them, so a registered tab using one is skipped and reported and shown to no one.
+- Date: 2026-10-30
+- Raised by: user
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/meta.yml b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/meta.yml
new file mode 100644
index 0000000..87668b3
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/meta.yml
@@ -0,0 +1,15 @@
+id: 2026-10-29-2037-screen-extensions-registry
+title: 'Screen extensions registry'
+status: in-review
+created: '2026-10-29 20:37'
+pr: { number: 16, url: https://github.com/Refactor-Circus/Atrium/pull/16 }
+standards:
+ refactor-circus/standards:
+ version: dev-main
+ reference: a5b675396232
+review_passes: 2
+runs:
+ - { workflow: ring-master-factory, run_id: wf_5e15100d-418, result: "needs-decision at build: view variable types (D-030); groups 1, 2, 4 built; 2 and 4 merged by hand from --g2/--g4", round: 0, date: 2026-10-29 }
+ - { workflow: ring-master-factory, run_id: wf_88f65899-8fd, result: "needs-decision at build: settings rows (D-031), access closure (D-032)", round: 0, date: 2026-10-29 }
+ - { workflow: ring-master-factory, run_id: wf_d8cb821c-79e, result: "needs-decision at build: stand-in location (D-033)", round: 0, date: 2026-10-29 }
+ - { workflow: ring-master-factory, run_id: wf_e6044f1d-330, result: "escalated at review round 3: rounds exhausted; one minor finding (browser suite and CSS rebuild unverified), verified by hand; approved as is by the user", round: 3, date: 2026-10-29 }
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/questions.yml b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/questions.yml
new file mode 100644
index 0000000..fe51488
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/questions.yml
@@ -0,0 +1 @@
+[]
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/references.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/references.md
new file mode 100644
index 0000000..109701d
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/references.md
@@ -0,0 +1,46 @@
+# References
+
+## Roster registered tabs (the pattern to generalise)
+
+- **Location:**
+ - `Roster/src/Atrium/Tabs.php`, `TabDefinition.php` and `TabVisibility.php`
+ - `Roster/resources/views/ui/partials/tabs.blade.php` and `registered-tab.blade.php`
+ - spec `Roster/docs/agent/specs/2026-10-23-2015-dynamic-tabs-orgs-users/`, which includes D-005 to D-024 and the post-mortem
+- **Relevance:** the behaviour to lift into Atrium as-is.
+- **Borrow:**
+ - key regex `^[a-z0-9][a-z0-9._-]*$`
+ - reserved keys taken from a public constant
+ - clone on register
+ - `public private(set)` properties, with closures kept private
+ - default deny and `public()`
+ - a `scoped()` memo keyed by screen, record and tab
+ - throwing `authorize` closures reported once per request
+ - only the open tab's resolver runs
+ - spread order `[...$data, ...$host]`
+ - a single `data` prop for components
+ - unknown icons fall back via `Icons::has()`
+ - the README section, checked by a docs test
+
+## Atrium widget and plugin registries
+
+- **Location:** `Atrium/src/Domains/Widgets/Services/WidgetRegistry.php` and `WidgetDefinition`; `Atrium/src/Domains/Plugins/Services/PluginRegistry.php`.
+- **Relevance:** existing Atrium registries with per-request availability (`WidgetRegistry::available(Request)`).
+- **Borrow:** registry naming, provider wiring and how availability is filtered per request.
+
+## Atrium themes
+
+- **Location:** `Atrium/src/Domains/Themes/` (`Theme`, `ThemeRegistry`, `ThemesServiceProvider`, which defines `atrium`, `harbor`, `sunset`, `forest`, `midnight` and `ledger`), plus `resources/css/atrium.css` tokens.
+- **Relevance:** dynamic tabs must work in every theme and in both the `sidebar` and `top` layouts.
+- **Borrow:** token-only styling. The existing `x-atrium::tabs` (Alpine, client-side) and `tab-panel` components are related but not the same: screen tabs are server-side `?tab=` links.
+
+## Existing tab bars that will move onto the registry
+
+- Roster organization: `Roster/resources/views/ui/organizations/show.blade.php` and `OrganizationUiController`
+- Roster user: `users/show.blade.php` and `UserUiController`
+- Roster team: `teams/show.blade.php` and `TeamUiController`
+- Roster SSO connection: `sso/show.blade.php` and `SsoUiController` (moves to Guardian)
+
+## Audit trail component (capability target for Keen)
+
+- **Location:** `Atrium/resources/views/components/audit-trail.blade.php` (props `source`, `subject`, `scope`, `action`, `limit`, `title`).
+- **Relevance:** the audited-subject declaration must carry what this component needs (package key, subject or scope, and an optional action prefix).
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/gate.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/gate.md
new file mode 100644
index 0000000..1f92867
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/gate.md
@@ -0,0 +1,26 @@
+VERDICT: PASS
+
+Gate results:
+- composer test: passed (phpstan 0 errors, pint passed, pest 589/589, 1760 assertions)
+- composer lint:check: passed
+- composer exec ringside check: passed
+
+Criteria mapping (by test file; mapped from file names in the diff, individual test names not re-read):
+1-5: tests/Unit/Screens/ScreenExtensionsTest.php, TabDefinitionTest.php, SectionDefinitionTest.php; tests/Feature/Screens/ResetsScreenExtensionsTest.php
+6: tests/Unit/Screens/ScreenTest.php
+7: tests/Feature/Screens/ResolveScreenTest.php, OpenRegisteredTabTest.php
+8: tests/Feature/Screens/VisibilityTest.php
+9: tests/Feature/Screens/EvaluationOrderTest.php
+10: tests/Feature/Screens/RowSlotsTest.php
+11: tests/Feature/Screens/WildcardRenderingTest.php
+12: tests/Feature/Screens/FailureIsolationTest.php
+13: tests/Feature/Screens/ScreenTabsComponentTest.php
+14-15: tests/Feature/Screens/ScreenSectionsComponentTest.php, OpenRegisteredTabTest.php
+16: tests/Feature/Screens/ScreenStylesTest.php
+17-18: tests/Browser/ScreenExtensionsTest.php (browser suite, not part of this gate)
+19: tests/Feature/Screens/AtriumScreensTest.php
+20: tests/Feature/HistoryRemovedTest.php, tests/ArchTest.php
+21: tests/Feature/DocsTest.php
+22: tests/ArchTest.php, tests/Feature/DomainLayoutTest.php
+
+Note: composer test:browser was not part of the requested gate and was not run.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-code.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-code.md
new file mode 100644
index 0000000..2a96b9a
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-code.md
@@ -0,0 +1,3 @@
+VERDICT: PASS
+
+Code review round 1. test:unit passes (589 tests), phpstan and pint pass. Registry, visibility memo, resolved screen and the three components match criteria 1-15. No findings at or above minor. Browser suite not run in this review.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-compat.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-compat.md
new file mode 100644
index 0000000..7579231
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-compat.md
@@ -0,0 +1,5 @@
+VERDICT: CHANGES
+
+minor: lang/en/atrium.php drops 24 audit_* translation keys (atrium::atrium.audit_*) which CHANGELOG.md upgrade note does not list. No sibling package uses them. Fix: name them in the upgrade note.
+
+All other removals (history route, domain, views, audit components, Plugin::historyNavItem) are spec-mandated (D-009, D-014, D-016) and documented.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-security.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-security.md
new file mode 100644
index 0000000..bf03822
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-security.md
@@ -0,0 +1,5 @@
+VERDICT: PASS
+
+Security review, round 1. No findings at or above minor.
+
+Checked: registration-time validation of target, key and slot patterns (anchored with /D); hosts call resolve() after their own authorization; default-deny visibility (no access closure hides permission extensions; throwing authorize counts as denial); per-request scoped memo keyed by record identity; tab links built through fullUrlWithQuery (escaped); ?tab read as string only; section labels escaped, output of sections is rendered markup of registrant-owned views (trusted boot-time code); failures are reported, not shown to users; Gate-based access closures in Atrium controllers; no new routes, config or input surface; history route removed.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-standards.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-standards.md
new file mode 100644
index 0000000..ec1719e
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-1/review-standards.md
@@ -0,0 +1,5 @@
+VERDICT: PASS
+
+Standards review, round 1. Checked container-bindings (singleton registry, scoped visibility, in the domain provider), dependencies (Screens imports no other domain; Atrium still requires only Keystone, arch-tested), domain-modules and atrium/domains (Screens provider registered in DomainServiceProvider, History removed, docs updated), public-api (facade docblock covers every public Atrium method including screens(); classes final), value-objects (public private(set), closures private; the kind-as-string deviation is recorded in standards-feedback.md), atrium/components (audit entries removed from the list), authorization (controllers only build Screen access closures; extension permissions go through the Gate), arch-tests (new rules added), test-layers (Unit plain PHP, Feature on TestCase).
+
+Nit: DefinesExtension trait sits in Data/Concerns, while domain-modules lists Concerns/ at domain level.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/gate.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/gate.md
new file mode 100644
index 0000000..fec6067
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/gate.md
@@ -0,0 +1,33 @@
+VERDICT: PASS
+
+Gate results (run in the Atrium job worktree):
+
+- `composer test`: passed (phpstan 0 errors, pint passed, pest 589 tests / 1760 assertions, 100% coverage).
+- `composer lint:check`: passed.
+- `composer exec ringside check`: passed.
+
+Criteria to proof (file-level mapping from the changed test files; names not individually re-verified in this round):
+
+1. tests/Unit/Screens/ScreenExtensionsTest.php (registry, `Atrium::screens()`, missing screen)
+2. tests/Unit/Screens/TabDefinitionTest.php, SectionDefinitionTest.php
+3. tests/Unit/Screens/ScreenExtensionsTest.php (validation, clone, string keys), tests/Feature/Screens/OpenRegisteredTabTest.php
+4. tests/Unit/Screens/ScreenExtensionsTest.php, tests/Feature/Screens/WildcardRenderingTest.php
+5. tests/Feature/Screens/ResetsScreenExtensionsTest.php, tests/Unit/Screens/ScreenExtensionsTest.php
+6. tests/Unit/Screens/ScreenTest.php
+7. tests/Feature/Screens/ResolveScreenTest.php, OpenRegisteredTabTest.php
+8. tests/Feature/Screens/VisibilityTest.php
+9. tests/Feature/Screens/EvaluationOrderTest.php
+10. tests/Feature/Screens/RowSlotsTest.php
+11. tests/Feature/Screens/WildcardRenderingTest.php
+12. tests/Feature/Screens/FailureIsolationTest.php
+13. tests/Feature/Screens/ScreenTabsComponentTest.php
+14. tests/Feature/Screens/ScreenSectionsComponentTest.php
+15. tests/Feature/Screens/EvaluationOrderTest.php / ScreenSectionsComponentTest.php
+16. tests/Feature/Screens/ScreenStylesTest.php
+17-18. tests/Browser/ScreenExtensionsTest.php (browser suite, `composer test:browser`, not part of this gate)
+19. tests/Feature/Screens/AtriumScreensTest.php
+20. tests/Feature/HistoryRemovedTest.php, tests/ArchTest.php
+21. tests/Feature/DocsTest.php (README, Boost skill, CHANGELOG)
+22. tests/ArchTest.php, tests/Feature/DomainLayoutTest.php
+
+Notes for the reviewer: `public/atrium.css` does not appear in the diff against main (criterion 16 done-step to rebuild); `composer test:browser` was not part of the assigned gate.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/review-standards.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/review-standards.md
new file mode 100644
index 0000000..96d8317
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-2/review-standards.md
@@ -0,0 +1,3 @@
+VERDICT: PASS
+
+Round 2 standards review: the open finding is resolved. CHANGELOG.md now lists all 24 removed atrium::atrium.audit_* keys with an upgrade note, and lang/en/atrium.php has none left. No new findings.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/gate.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/gate.md
new file mode 100644
index 0000000..31b14d2
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/gate.md
@@ -0,0 +1,31 @@
+VERDICT: PASS
+
+Gate commands (all started, all passed):
+- composer test: phpstan 0 errors, pint passed, pest 589 passed (1760 assertions), 100% coverage.
+- composer lint:check: pint passed.
+- composer exec ringside check: passed.
+
+Not verified by the gate: tests/Browser/ScreenExtensionsTest.php (criteria 17, 18) is run by `composer test:browser`, not by `composer test`. public/atrium.css is not in the branch diff (criterion 16 rebuild step); ScreenStylesTest passes.
+
+Criteria mapping (tests under tests/):
+1. Unit/Screens/ScreenExtensionsTest (chaining, missing.screen, accepts/rejects target); Feature/Screens/ResolveScreenTest "is a singleton reachable through Atrium::screens()".
+2. Unit/Screens/TabDefinitionTest and SectionDefinitionTest (setters, private closures, refuses writes, Screen last argument).
+3. Unit/Screens/ScreenExtensionsTest (key, slot, target validation, neither view nor component, stores a copy, all-digit keys); ResolveScreenTest "opens all-digit keys as strings".
+4. ResolveScreenTest "throws in the local and testing environments...", "reports once and keeps the first...", "keeps the more specific tab/section...".
+5. Unit/Screens/ScreenExtensionsTest snapshot/restore/flush; Feature/Screens/ResetsScreenExtensionsTest.
+6. Unit/Screens/ScreenTest (package derivation, standard slots, overview tab).
+7. ResolveScreenTest (ordering, reserved keys, ?tab= cases, 403, memoized data()).
+8. Feature/Screens/VisibilityTest.
+9. Feature/Screens/EvaluationOrderTest.
+10. Feature/Screens/RowSlotsTest.
+11. Feature/Screens/WildcardRenderingTest; ResolveScreenTest wildcard cases.
+12. Feature/Screens/FailureIsolationTest.
+13. Feature/Screens/ScreenTabsComponentTest.
+14. Feature/Screens/ScreenSectionsComponentTest.
+15. Feature/Screens/OpenRegisteredTabTest.
+16. Feature/Screens/ScreenStylesTest (rebuild of public/atrium.css not visible in diff).
+17, 18. tests/Browser/ScreenExtensionsTest.php exists (dataset 6x2x2); not run by this gate.
+19. Feature/Screens/AtriumScreensTest.
+20. Feature/HistoryRemovedTest; Feature/DocsTest (changelog note); ArchTest.
+21. Feature/DocsTest.
+22. tests/ArchTest.php (passed within composer test).
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-code.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-code.md
new file mode 100644
index 0000000..c1d2ab4
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-code.md
@@ -0,0 +1,3 @@
+VERDICT: PASS
+
+Round 3: both open findings are resolved. Rebuilding with npm run build:css leaves public/atrium.css byte-identical (git status shows no change), so there is no diff to commit. The round 2 commit changes only build.md, which records the browser suite passing (46 tests). No findings.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-compat.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-compat.md
new file mode 100644
index 0000000..53779a6
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-compat.md
@@ -0,0 +1,9 @@
+VERDICT: PASS
+
+Round 3 compat review. The only commit since round 2 (b13b1ab) edits build.md, so no public API, config, route, event or schema change was added.
+
+Open finding about public/atrium.css: the done-step was run. build.md line 261 records that npm run build:css left public/atrium.css byte-identical to main, because the new components use classes already in the compiled safelist. There is nothing to commit, and the only stylesheet change against main is the regenerated @source list in resources/css/atrium.css. Resolved.
+
+Open finding about the browser suite: this is a gate matter, not a compat matter.
+
+The removals of History, audit-trail and historyNavItem are covered by D-009, D-014 and D-016, which are final.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-security.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-security.md
new file mode 100644
index 0000000..43e65fd
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-security.md
@@ -0,0 +1,3 @@
+VERDICT: PASS
+
+Since round 2 the only change is build.md in the spec folder (no code). No security findings.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-standards.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-standards.md
new file mode 100644
index 0000000..cab7b2f
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/round-3/review-standards.md
@@ -0,0 +1,3 @@
+VERDICT: PASS
+
+Round 3 (standards). The only change since round 2 is a build.md note in the spec folder (the job record). No code changed, so no standard is newly affected. Both open findings are closed: public/atrium.css rebuilt byte-identical to main (resources/css/atrium.css carries the @source change), and composer test:browser passed (46 tests).
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/shape.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/shape.md
new file mode 100644
index 0000000..2de887d
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/shape.md
@@ -0,0 +1,78 @@
+# Screen extensions registry — Shaping Notes
+
+## Scope
+
+Make "register it from your own package" the one standard way to add tabs and sections to any Atrium screen, replacing every place where a host package checks whether another package is installed and renders that package's UI itself.
+
+This is a change to Atrium. It generalises Roster's `Atrium\Tabs` / `TabDefinition` / `TabVisibility` (Roster PR #5, spec `2026-10-23-2015-dynamic-tabs-orgs-users`) into Atrium so that every package's screens can be extended the same way.
+
+In scope:
+
+- **Registry.** One Atrium registry (working name `ScreenExtensions`), a singleton, populated from providers' `boot()`. It supports:
+ - **Tabs** on a screen's tab bar.
+ - **Sections:** named slots on a screen (a card or panel area, a table-row slot), each holding a list of registered sections.
+ - Screens are identified by a **string key**, `{package}.{screen}` (`roster.organization`, `roster.user`, `roster.team`, `roster.sso-connection`, `showroom.product`, `showroom.transfers`, …), so a registering package never imports the host's classes.
+- **Definitions.** Tab and section definitions keep Roster's proven behaviour:
+ - fluent definitions (`label`, `icon`, `view` / `component`, `resolve`, `permission`, `authorize`, `public`)
+ - key validation, reserved built-in keys and clone-on-register
+ - default-deny visibility
+ - a per-request `scoped()` visibility memo
+ - a host's own screen authorization running before any registered code
+ - a resolver running only for the open tab or rendered section
+ - Roster's variables winning over resolver data
+ - throwing `authorize` closures counted as a denial and reported once per request
+ - `flush()` for tests only
+- **Permission checks.** Atrium can't know each host's permission model. A host screen supplies its own access check, and Roster's `ScreenAccess::allows()` is one such check.
+- **Screen declarations.** A host screen declares:
+ - its key
+ - its record, which may be absent for list or index screens
+ - its built-in tab keys, which are reserved
+ - its section slots
+ - an optional **audited subject**: the package key plus the subject record, a scope record, or package-wide. Keen's History section uses this (see the Keen spec).
+- **Shared rendering components.**
+ - `x-atrium::screen-tabs`: a tab bar built from a screen's built-in and visible registered tabs, as `?tab=` links with `aria-current="page"`.
+ - `x-atrium::screen-sections`: renders a slot's visible sections in registration order.
+ - Both replace Roster's `roster::ui.partials.tabs` and `registered-tab` partials.
+- **Themes.** Dynamic tabs and sections must render correctly in every built-in theme and both layouts:
+ - themes: `atrium`, `harbor`, `sunset`, `forest`, `midnight`, `ledger`
+ - layouts: `sidebar` and `top`
+ - The `top` layout already shows the current section's pages as a tab row under the topbar. A screen's tab bar must not collide with that row, and must stay usable (scrolling or wrapping) when many tabs are registered.
+ - Browser tests cover every theme in both layouts.
+ - Theme authors get a documented contract: the components only use design tokens, so a new theme needs no tab-specific work.
+
+## Decisions
+
+- D-001: the registry lives in Atrium. Roster's `Tabs` / `TabDefinition` / `TabVisibility` are deleted, not kept as wrappers. Roster moves onto Atrium's registry in its own spec. This is a breaking change, accepted because nothing is on Packagist yet. (User, 2026-10-29.)
+- D-002: screens are identified by string keys `{package}.{screen}`, and a registering package never imports host classes. Registering for a screen whose package isn't installed is harmless, because that tab or section simply never renders. Registering packages therefore need no `class_exists()` checks.
+- D-003: Keen's audit trail is added by capability. Screens declare an audited subject, and Keen registers one section that attaches to any screen that declares one. The registry therefore needs a "for every screen declaring X" registration form, alongside the per-screen-key form. (User, 2026-10-29.)
+- D-004: every theme and both layouts must handle dynamic tabs, enforced by browser tests across all themes and layouts. (User, 2026-10-29.)
+- D-005: this replaces section A of the cross-package audit (tabs and sections gated on another package). Section B is out of scope: nav items, whole pages, `historyNavItem()`, the history page and `atrium.keen.*` route checks.
+- D-006: the registry supports per-row section slots: a slot rendered once per table row, with that row's record as the section's record, the resolver and `authorize` running per row, and the visibility memo keyed by row record. Impex's run link on `showroom.transfers` needs this. (User, 2026-10-29.)
+- D-007: `x-atrium::audit-trail` moves out of Atrium into Keen (Keen spec). `x-atrium::audit.entries` stays in Atrium, because Atrium's own history page (`resources/views/history/show.blade.php:17`) renders it. (User, 2026-10-29.)
+- D-008: keys registered on another package's screen are vendor-prefixed (`guardian.sso`, `keen.activity`, `cortex.mcp`), so they never clash with a host's reserved built-in keys while both exist. The README recommends `vendor.key`, and these first-party registrations follow it.
+
+## Context
+
+- **References:** see `references.md`.
+- **Order:** this spec is first. Every other spec in this initiative depends on it:
+ - Roster: adopt the registry
+ - Guardian
+ - Keen: History section
+ - Cortex
+ - Impex
+ - Showroom, Polycart, PennantPlus
+- **Product:** Atrium is the shared dashboard for the Refactor Circus suite. Making it the extension point for screens means packages own their own UI wherever it appears.
+- **Visuals:** none provided. The bar keeps the look of the existing Roster organization tab bar (`x-atrium::icon-button` items).
+
+## Standards
+
+- architecture/public-api: the registry, definitions and screen declaration become Atrium's public API for every package.
+- architecture/container-bindings: the singleton registry plus the `scoped()` per-request visibility memo (Octane-safe).
+- architecture/dependencies: hosts and registrants link only through string keys, with no `class_exists()` checks between packages.
+- architecture/domain-modules: where the registry sits in Atrium's domains (likely a new `Screens` domain beside `Widgets` and `Plugins`).
+- atrium/components: the new `screen-tabs` / `screen-sections` components, using design tokens only and safelisted utilities.
+- atrium/domains: Atrium domain conventions.
+- data/value-objects: immutable-from-outside definitions (`public private(set)`, clone on register).
+- http/authorization: the host's screen authorization comes first, visibility is deny-by-default, and a hidden `?tab=` answers 403.
+- testing/test-layers: unit tests for the registry and definitions, feature tests for rendering, and browser tests for every theme and layout.
+- testing/arch-tests: new classes are final and use strict types.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec-review.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec-review.md
new file mode 100644
index 0000000..22c65cf
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec-review.md
@@ -0,0 +1,37 @@
+
+## Round 1
+
+Edited `spec.md` for the non-architectural findings. Left untouched, because they are open questions: how `x-atrium::audit-trail` leaves Atrium (criterion 17 and Risks), whether Atrium's own screens adopt `Screen::make` (no out-of-scope bullet added; only the Goal now says "any screen that declares itself with `Screen`"), whether the audited slot is implicit or listed in `slots()`, throwing resolvers or views, the flush/boot reset mechanism, the testing helper's shape, and dataset versus loop for the browser matrix.
+
+Changes and why:
+- Goal: scoped to screens declaring `Screen`, removing the ambiguity about Atrium's own screens.
+- C1: test that `Atrium::screens()` returns the singleton.
+- C3: boot-time exception messages name key, screen and call site; README states the throw is intentional (blast radius is diagnosable).
+- C4: test that a `boot()` registration survives between two tests (checks the outcome without choosing the mechanism).
+- C6: explicit tests for each open-tab rule; the 403/200 key-existence leak is accepted and documented.
+- C7 and C9: memo key is morph class plus key, `spl_object_id` for null keys, same key for the `data()` memo (prevents cross-row data exposure); tests added. Undeclared slots render nothing and call nothing.
+- C10: positive test for `AuditedSubject` fields and a custom slot; audited sections are default-deny; README documents the subject-authorization requirement.
+- C11: tab links drop `page` and `tab`, are escaped, with named variant markup and tests for `?page=2&q=x` and array/special characters.
+- C12: tests for class passthrough, empty slot and order.
+- C13: `missingClasses()` emptiness is the test; CSS rebuild is a done-step.
+- C14: browser assertions for computed overflow, nowrap and equal top offsets.
+- C15: failures must name theme, layout and mode.
+- C16: docs test reduced to section existence; README also records the boot-throw and 403 behaviours; CLAUDE.md and domains.md list the Screens domain.
+- C17: added a `history/show` 200 with `audit.entries` test (neutral to the removal decision).
+- Out of scope: audited tabs, and config/event/MCP surface.
+
+## Round 1 (revision 2)
+
+Rewrote `spec.md` in place so the numbered criteria and Design are authoritative; the addendum is now a changelog. Open questions were not decided: where a criterion depends on one, it says "pending Q" and fixes only behaviour that does not depend on the answer.
+
+- Goal, C1, C5, C10, C15, C16, C18, Design: removed `audited()`, `Screen::audits()`, `AuditedSubject`, the `[audited]` store and the audited browser section and README example (D-017 superseded them). C10 is now the wildcard criterion; C10a covers failure isolation. Why: a builder or verifier reading top to bottom no longer meets contradictory scope.
+- C1 and C3: wildcard targets (`*`, `{package}.*`) accepted, with accepted and rejected examples (`*.x`, `te*.x`, `test.a*`, `test.*.x`, `**`); a host `Screen::make()` key is never a wildcard. Slot names validated against `^[a-z0-9][a-z0-9._-]*$`. Why: otherwise `boot()` throws for the wildcards the addendum adds. Call-site in the duplicate message is best-effort and tested only for a closure in the test file.
+- C4: rewritten around snapshot after boot and restore after each test (D-010), trait `Testing\ResetsScreenExtensions` (D-011), `flush()` for unit tests only, with three tests (boot survives, in-test registration gone, flush empties). The public snapshot/restore shape is left pending Q.
+- C5, C6, C11: added `Screen::standard()` and `kind`, exposed `key/package/record/kind`, the synthetic reserved `overview` default tab (hidden alone, tested), wildcard tabs on reserved keys, and ordering (exact first, then wildcard).
+- C7 and C9: null-key models are keyed by strongly held identity, not bare `spl_object_id` (ids are reused after free, which would leak authorization results); a test frees one unsaved row and checks `authorize` runs again.
+- C10a: section output buffered and discarded on failure; all Throwables including HttpException isolated, not suppressed in tests; once-per-key reporting; open-tab panel failure gives a 500. Tests added.
+- C14 and C15: stated the exact properties (`flex-wrap`, `white-space`), the `top-tabs` fixture, and the idle-tab comparison with the pointer elsewhere.
+- C16: README adds wildcards, cheap-closure guidance, the registrant-owns-writes note for settings screens, D-018 and D-019; docs test also checks keywords.
+- C17: history removal now has tests (404 route, arch checks, `historyNavItem` gone, no `audit/` `@source`) and done-steps (workspace grep for removed symbols, safelist check, CHANGELOG upgrade note, grouped merge).
+- C19 (new): exhaustive table of Atrium screens (`atrium.dashboard` for `/` and `d/{slug}`, `atrium.dashboard-widget`, `atrium.settings`, `atrium.settings-panel`) with kind, record, tabs and slots; anything unlisted (including `search`) is out of scope; per-screen tests. The table follows D-013 and is subject to the scope open question.
+- Out of scope and Risks: removals are in scope, only Keen's replacements are out; settled items (D-009, D-012) removed, scope-size risk and grouped merge order added.
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec.md
new file mode 100644
index 0000000..2ead810
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/spec.md
@@ -0,0 +1,167 @@
+# Screen extensions registry
+
+## Goal
+
+Any package can add tabs and sections to any screen that declares itself with `Screen`, by registering them from its own `boot()` for one exact screen (`{package}.{screen}`), for every screen of a package (`{package}.*`) or for every screen (`*`). A screen declares only generic facts (key, package, record, kind, tabs and slots) and stops checking whether other packages are installed. Atrium knows nothing about any other suite package and has no audit concept: the history screen, its components and its nav item leave Atrium for Keen. Every Atrium page with a controller view declares itself with the standard slots and a tab bar, and tabs and sections render the same way in every Atrium theme and layout.
+
+## Acceptance criteria
+
+### Registry and definitions
+
+1. `RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions` is bound as a singleton and reachable as `Atrium::screens()`; a test asserts both return the same instance. It has `tab(string $target, TabDefinition)` and `section(string $target, string $slot, SectionDefinition)`, each returning the registry for chaining. `$target` is an exact screen key, `*` or `{package}.*`. A registration for a key no installed package declares is stored and never renders, with no error: a unit test registers for `missing.screen` and asserts nothing throws and a declared screen is unaffected.
+2. `TabDefinition::make($key)` and `SectionDefinition::make($key)` live in `Domains\Screens\Data`.
+ - **Setters:** `label()`, `icon()` (tabs only), `view()` / `component()` (setting one clears the other), `resolve(Closure)`, `permission(string)`, `authorize(Closure)` and `public()`.
+ - **Closure signatures (D-025):** `authorize(fn (Request $request, ?Model $record, Screen $screen): bool)` and `resolve(fn (?Model $record, Screen $screen): array)`. `Screen` is always the trailing argument; `$record` is the screen's record, or the row inside a row slot.
+ - **State:** `key`, `label`, `icon`, `view`, `component`, `permission` and `public` are `public private(set)`. `label` defaults to the key, a tab's `icon` to `squares-2x2`, `public` to `false`. The resolver and `authorize` closures are private; reading either from outside throws `Error`.
+
+ Unit tests cover view/component exclusivity, that writing any property throws `Error`, and that both closures receive the `Screen` as their last argument.
+3. **Validation.** Each case below throws `InvalidArgumentException`, and a test covers each:
+ - an extension key or slot name not matching `^[a-z0-9][a-z0-9._-]*$` (accepted: `acme.billing`, `header.actions`; rejected: uppercase, a space, a slash, empty)
+ - a definition with neither a view nor a component
+ - a target that is not an exact key `^[a-z0-9-]+\.[a-z0-9.-]+$`, `*` or `^[a-z0-9-]+\.\*$` (D-026). Accepted: `test.screen`, `*`, `test.*`. Rejected: `*.x`, `te*.x`, `test.a*`, `test.*.x`, `**`, `test.**`, empty. `Screen::make()` accepts the exact form only.
+
+ The registry stores a clone: a test mutates the caller's instance after registering and asserts the stored copy is unchanged. Keys are read back as strings: a test registers `123` and `007` and asserts `?tab=007` reaches the view as `'007'`.
+4. **Duplicates.**
+ - **Same key on the same target string (D-022, D-026):** in the `local` and `testing` environments, registration throws `InvalidArgumentException` naming the key and the target. In any other environment it reports the exception once through `report()`, skips the later registration and keeps the first. Tests cover both environments for tabs and sections (same target and slot).
+ - **Same key across targets on one screen (D-023, D-028):** the more specific target wins. The order is the exact key, then `{package}.*`, then `*`. Each less specific duplicate is skipped and reported once per request. Tested for tabs and sections in all three pairings (exact vs `pkg.*`, exact vs `*`, `pkg.*` vs `*`), with a page rendering the slot twice still reporting once.
+5. **Test reset (D-010, D-011, D-027).**
+ - `ScreenExtensions::snapshot(): array` returns the current registrations and `restore(array $snapshot)` replaces them with a snapshot.
+ - The published Pest trait `RefactorCircus\Atrium\Testing\ResetsScreenExtensions` (beside `Testing\AtriumStyles`) takes one snapshot after the application boots and restores it after each test. Atrium's own `TestCase` uses it.
+ - `flush()` forgets everything and is for the registry's own unit tests; nothing can be unregistered at runtime.
+ - Tests: a tab registered from a provider's `boot()` is present in the second of two consecutive tests; a tab registered inside the first test is gone in the second; `restore(snapshot())` round-trips; `flush()` empties both listings.
+
+### Screen declarations
+
+6. A host builds `Screen::make(string $key)` (`Domains\Screens\Data\Screen`) with `record(?Model)`, `kind('detail'|'list')`, `tabs(array $builtIn)` (key, label and icon per entry, in order), `defaultTab(string)`, `slots(string ...)`, `rowSlots(string ...)` and `access(Closure(string $permission, Request, ?Model $record): bool)`.
+ - **Exposed state:** `key`, `package` (the key's first segment), `record`, `kind`, `tabs`, `slots` and `rowSlots`, all `public private(set)`.
+ - **Standard slots (D-013):** `Screen::standard(string $key, string $kind)` returns a screen with `header.actions`, `before` and `after`; a `detail` screen also gets `aside`, a `list` screen also gets the row slot `row.actions`. Hosts may add slots afterwards. A unit test asserts both lists.
+ - **Overview tab:** a screen with no built-in tabs gets one built-in tab, `overview`, holding the page, which is the default tab. Registered tabs are never the default.
+
+ Tests cover `package` derivation, both `standard()` kinds and the synthetic `overview` tab.
+7. The host passes the screen to `ScreenExtensions::resolve(Screen, Request): ResolvedScreen`, which exposes `screen`, `tabs` (visible tabs: built-ins as given, then exact registrations, then wildcard registrations, each in registration order), `openTab` (string), `openRegisteredTab` (`?TabDefinition`), `sections(string $slot)`, `rowSections(string $slot, Model $row)` and `data(TabDefinition|SectionDefinition, ?Model $row = null): array` (computed on first call, memoized for the request).
+ - **Reserved keys:** a registered tab (exact or wildcard) whose key is one of the screen's built-in keys, `overview` included, is skipped and reported once per request with an `InvalidArgumentException` naming the key and screen. Tested for an exact and a `*` registration.
+ - **Open tab:** `?tab=` is read only as a string (`?tab[]=x` counts as absent). An absent or unknown key opens `defaultTab`, or the first built-in, with a 200. A visible registered key opens that tab. A registered key the viewer can't see answers 403; that 403-versus-200 difference reveals which keys exist, which is accepted and documented. A feature test covers each case.
+8. **Visibility.** A tab or section is visible only when its `permission()` passes the screen's `access` closure, its `authorize` closure returns `true`, both pass when it has both, or, with neither, after `public()`. A screen without `access` hides every `permission()` extension.
+ - A throwing `authorize` counts as a denial and is reported once per request per screen and key.
+ - Answers and `data()` are memoized in `ScreenVisibility` (bound `scoped()`), keyed by screen, slot, extension key and record identity: morph class plus key, or the model itself held strongly when its key is null (never a bare `spl_object_id`). Nothing is cached on the registry or the definitions.
+ - Tests, for tabs and sections: permission only, closure only, `public()`, neither (hidden), both passing, one failing, a throwing closure (reported once, called once, page 200). Memo tests: two rows with the same id in two model classes get separate answers and data; a freed unsaved row and a new one each run `authorize` and the resolver; two requests with `forgetScopedInstances()` between them and different viewers evaluate afresh.
+9. **Order of evaluation.**
+ - Hosts call `resolve()` only after their own authorization; a test host denied with 403 runs no `authorize` closure or resolver (both counted).
+ - Resolvers run only through `data()`: for the open registered tab and for each section actually rendered. A counting resolver on a hidden tab, an unopened tab, a hidden section and a section in an unrendered slot is never called.
+ - Component path: resolver data arrives as one `data` prop. View path: resolver data is spread first and the host's `screen`, `record` and `tab` over it, so the host wins (tested by a resolver returning those three keys).
+
+### Row slots, wildcards and failures
+
+10. **Row slots (D-006).** ` ` renders once per row; `authorize` and the resolver receive the row as `$record`, memoized per row identity (criterion 8). A feature test renders three rows with a section admitting only the second and asserts: the markup appears once, in that row; `authorize` ran three times and the resolver once; re-rendering the rows in the same request makes no further calls. A row slot rendered without `:row`, or a normal slot rendered with `:row`, throws `InvalidArgumentException`. A section on a slot the screen didn't declare is never rendered and its closures never run. All tested.
+11. **Wildcards (D-017, D-026).** A `*` registration applies to every declared screen (tabs) or every screen declaring the slot (sections); a `{package}.*` registration only to screens whose `package` matches. Wildcard extensions are default-deny like any other. Tests: a `*` section renders on two test-host screens and receives each one's `Screen`; a `test.*` section renders on `test.a` and not on `other.screen`; a `*` tab opens through `?tab=`; a wildcard section on an undeclared slot never runs its closures; a wildcard `authorize` that returns early on `$screen->key` makes no resolver call elsewhere.
+12. **Failure isolation (D-015).** Each section and row section renders into a buffer. If its resolver or view throws any `Throwable` (including `HttpException`), the buffer is discarded, the failure is reported once per request per screen and key, the section renders nothing and the page still returns 200. Isolation is active in tests too. A throwing open registered tab panel propagates to the exception handler (500). Tests: a view that emits markup then throws leaves none in the response; a section failing in three rows is reported once; a throwing panel gives 500.
+
+### Rendering
+
+13. `x-atrium::screen-tabs :screen="$resolved"` renders a `` of `x-atrium::icon-button` links:
+ - each link is `?tab={key}`, keeping the query string except `page` and `tab`, escaped through the URL helpers (tests: `?page=2&q=x` keeps only `q=x`; `q[]=a&b` and `q="` stay escaped)
+ - each has `data-testid="tab-{key}"`; the open tab alone has `aria-current="page"` and the primary variant (the test names its markup and asserts the others lack both)
+ - labels are escaped (tested with markup in a label); an icon `Icons::has()` doesn't know renders as `squares-2x2` (compared with a `squares-2x2` tab's markup)
+ - it renders nothing when fewer than two tabs are visible: tested with only `overview`, and with one built-in plus one hidden registered tab
+
+ Built-in labels come from the host; Atrium translates nothing.
+14. `x-atrium::screen-sections :screen="$resolved" slot="..." [:row="$model"]` renders the slot's visible sections in order, each wrapped in an element with `data-testid="section-{key}"`, passing through any `class` attribute, and renders an empty string for an empty slot. `x-atrium::screen-tab-panel :screen="$resolved"` renders the open registered tab per criterion 9. Feature tests cover order, `class` passthrough and the empty slot.
+15. **Around an open registered tab (D-024).** The tab's panel replaces the host's page content. `header.actions` always renders; `before`, `after`, `aside` and row slots render only while a built-in tab is open. A feature test on a test-host screen with a section in every standard slot asserts all of them on the built-in tab, and only `header.actions` plus the panel with a registered tab open (and that the hidden slots' resolvers never ran).
+
+### Themes and layouts
+
+16. The new components use only design tokens and utilities in Atrium's compiled safelist: `AtriumStyles::missingClasses()` and `inlineStyles()` are empty for them (tested). Rebuilding `public/atrium.css` is a done-step.
+17. In both layouts the tab bar scrolls horizontally rather than wrapping and never overlaps the top layout's `top-tabs` row. The browser test asserts the nav's computed `overflow-x` is `auto` or `scroll`, its `flex-wrap` is `nowrap`, each link's `white-space` is `nowrap`, and all links share one top offset. The top-layout fixture has a workbench plugin with pages, so `top-tabs` is present.
+18. **Browser matrix (D-004, D-012).** `tests/Browser/ScreenExtensionsTest.php` uses a Pest dataset over the 6 themes (`atrium`, `harbor`, `sunset`, `forest`, `midnight`, `ledger`) x 2 layouts (`sidebar`, `top`) x light/dark, so each of the 24 cases is its own named test. Each renders a workbench test-host screen with two built-in tabs, twelve registered tabs (one with a long label), a normal-slot section and a row-slot section, and asserts: the last tab scrolls into view, clicks and opens with `aria-current="page"`; the open tab's computed background differs from an idle tab's with the pointer elsewhere; in the top layout no tab's bounding box overlaps `top-tabs`; both sections render. It saves a screenshot per case under `tests/Browser/Screenshots/screen-extensions/`.
+
+### Atrium's screens
+
+19. **Declared screens (D-013, D-021).** Every Atrium page with a controller view declares itself with `Screen::standard()` and renders `x-atrium::screen-tabs`, `x-atrium::screen-tab-panel` and the sections of every slot it declares, laid out per criterion 15. Each has only the synthetic `overview` tab built in:
+
+ | Key | Route | Kind | Record | Slots |
+ |---|---|---|---|---|
+ | `atrium.dashboard` | `/` | detail | the dashboard | `header.actions`, `before`, `after`, `aside` |
+ | `atrium.named-dashboard` | `d/{slug}` | detail | the dashboard | `header.actions`, `before`, `after`, `aside` |
+ | `atrium.dashboard-widget` | `dashboards/{dashboard}/widgets/{widget}` | detail | the widget | `header.actions`, `before`, `after`, `aside` |
+ | `atrium.settings` | `settings` | list | none | `header.actions`, `before`, `after`, `row.actions` (per settings panel row) |
+ | `atrium.settings-panel` | `settings/{panel}` | detail | none (a panel is not a model) | `header.actions`, `before`, `after`, `aside` |
+
+ Anything else (login, error pages, `search`, JSON and form-post routes) is out of scope. Per screen, a feature test registers a tab and a section in every standard slot and asserts each section renders in its slot and not in an undeclared one, and the tab appears and opens through `?tab=`. With nothing registered, no tab bar or extra markup renders, and the existing feature and browser suites pass unchanged.
+
+### History removal
+
+20. **History leaves Atrium (D-009, D-014, D-016).** Removed: the `History` domain (`HistoryServiceProvider`, the `history/{package}` route `atrium.history.show`, `HistoryController`), `resources/views/history/show`, `x-atrium::audit-trail`, `x-atrium::audit.entries` and the rest of the `components/audit/` directory, their `@source` lines in `atrium.css`, and `Plugin::historyNavItem()`. Keen takes them over in its own spec.
+ - Tests: `GET history/{package}` returns 404; an arch test asserts `HistoryController` and the audit component files no longer exist; `method_exists(Plugin::class, 'historyNavItem')` is false; `atrium.css` has no `audit` `@source`.
+ - Done-steps: no reference remains in `src`, `resources`, `docs`, the README or the Boost skill; a workspace grep for `atrium.history`, `x-atrium::audit` and `historyNavItem` is listed in the PR; `AtriumStyles::missingClasses()` still passes; `CHANGELOG.md` has an upgrade note naming each removed route, class, method and component and pointing to Keen. Merges are grouped (Atrium, Keen and the hosts together) because the removal breaks packages that still use these.
+
+### Documentation and architecture
+
+21. The README gains a "Screen extensions" section, and the Boost skill under `resources/boost/skills` the same content, covering:
+ - registration examples for a tab, a section, a row section and a wildcard section, and the host-side `Screen::standard()` declaration
+ - the boot-only rule, `vendor.key` keys (D-008), duplicate handling per environment (D-022, D-023) and the 403-versus-200 tab-key behaviour
+ - closure signatures with the trailing `Screen`, the evaluation order, and that wildcard and row-slot closures must be cheap (return early on `$screen->key` or `kind`)
+ - what renders around an open registered tab, and the theme contract (tokens only, nothing per theme)
+ - that a section renders inside the host's page but writes through the registrant's own routes and authorization
+ - the suite rule (D-018): Atrium requires only Keystone; every other suite package is suggested
+ - the config-defaults pattern (D-019) for registrants targeting another package's screens: an editable list of target screens and slots in the registrant's own config, applied only when the target screen exists, with an example
+
+ A docs test asserts the section exists in both files and contains `boot()`, `403`, `vendor.key`, `Keystone` and `config`. Atrium's `CLAUDE.md` and `docs/agent/standards/atrium/domains.md` list the Screens domain and drop History.
+22. `tests/ArchTest.php` passes: the new classes are final with strict types, the value objects use `public private(set)`, and `ScreensServiceProvider` is registered by `Domains\DomainServiceProvider`. `composer.json` still requires only Keystone among suite packages. Done means `composer test` and `composer test:browser` pass.
+
+## Design
+
+**Domain `Domains/Screens`** (`ScreensServiceProvider`, per atrium/domains):
+
+- **`Data`:** `TabDefinition` and `SectionDefinition` (final, sharing a `Concerns\DefinesExtension` trait for key, label, view/component, closures, permission and public, plus `allows(Request, ?Model, Screen, ?Closure $access): bool` and `resolveData(?Model, Screen): array`); `Screen` (host declaration, built per request); `ResolvedScreen`.
+- **`Services`:** `ScreenExtensions`, a singleton holding registrations only, keyed `[target][key]` for tabs and `[target][slot][key]` for sections, with `snapshot()`/`restore()`/`flush()`. Resolution merges exact, `{package}.*` and `*` targets for the screen. `ScreenVisibility`, bound `scoped()`, holds the visibility and data memos and the reported-once set.
+- **Views:** `components/screen-tabs`, `screen-tab-panel` and `screen-sections`.
+- **Testing:** `Testing\ResetsScreenExtensions` trait.
+- **Facade:** `Atrium::screens()`.
+
+The behaviour comes from Roster's `Tabs`/`TabDefinition`/`TabVisibility`, changed so that: the screen is a string key; permissions go through the host's `access` closure (Atrium's `Support\ScreenAccess` may be used inside it); the record may be null; closures receive the `Screen`; and there are sections, row slots, standard slots and wildcard targets.
+
+No config, migrations, routes, events or MCP surface; the registry is code-only, filled from `boot()`.
+
+## Out of scope
+
+- Moving other packages' screens onto the registry: Roster, Showroom, Polycart, PennantPlus, Cortex, Impex, Keen and Guardian each have their own spec.
+- The history page, History nav items and audit components in Keen (Keen's spec). Only their removal from Atrium is in scope.
+- Nav items and whole pages as extension points; screens not in criterion 19.
+- Any audit concept in Atrium; wildcard forms other than `*` and `{package}.*`.
+- Ordering controls, priorities, badges, async tab bodies, per-tab routes, translated registered labels, and overriding, hiding or reordering a host's built-in tabs.
+
+## Risks
+
+- Reserved built-in keys are only known at resolve time, so those clashes are reported per request rather than thrown at boot; `vendor.key` keys (D-008) make them unlikely.
+- In production a duplicate registration is skipped with one report rather than thrown (D-022), so a misconfigured app keeps running with the first registration; the report is the only signal.
+- Wildcard and row-slot closures run on every matching screen or row; slow closures slow every page. The README tells registrants to return early.
+- The history removal breaks every package still using it until its own spec lands, so Atrium, Keen and the hosts merge as a group (D-009).
+- Scope is large: a new domain, five declared screens, the removals and a 24-case browser dataset.
+
+## Changelog
+
+- D-009: history and audit components are removed now; Atrium, Keen and hosts merge as a group (criterion 20, Risks).
+- D-010: test reset snapshots after boot and restores after each test; `flush()` only for the registry's unit tests (criterion 5).
+- D-011: published Pest trait `Testing\ResetsScreenExtensions` (criterion 5).
+- D-012: browser matrix is a Pest dataset, one test per combination (criterion 18).
+- D-013: every screen declares the standard slots and a tab bar, with a synthetic `overview` tab; `Screen::standard()` and `kind` added (criteria 6, 19).
+- D-014: the history screen and `x-atrium::audit.entries` move to Keen, superseding D-007 (criterion 20).
+- D-015: section and row-section failures are isolated and reported once; open-tab panel failures propagate (criterion 12).
+- D-016: `Plugin::historyNavItem()` is removed; Keen adds History nav items (criterion 20).
+- D-017: no audit concept in Atrium; `audits()`, `AuditedSubject`, `audited()` and the old criterion 10 replaced by `*` and `{package}.*` targets (criteria 1, 3, 11).
+- D-018: Atrium requires only Keystone; the README states the suite rule (criteria 21, 22).
+- D-019: the README documents the config-defaults pattern (criterion 21).
+- D-020: spec rewritten in place; addenda replaced by this changelog.
+- D-021: every Atrium page with a controller view is declared, with `/` and `d/{slug}` as separate keys (criterion 19).
+- D-022: same key on one target throws in local/testing, reports once and skips in production (criterion 4).
+- D-023: an exact registration beats a wildcard with the same key; the duplicate is reported once per request (criterion 4).
+- D-024: an open registered tab replaces page content; only `header.actions` stays (criterion 15).
+- D-025: `Screen` is the trailing argument to every `authorize` and `resolve` closure (criteria 2, 11).
+- D-026: wildcard grammar limited to `*` and `{package}.*`; duplicates checked per target string at boot (criteria 3, 4).
+- D-027: `snapshot(): array` and `restore(array)` named (criterion 5).
+- D-028: same key across wildcard levels: the more specific target wins (exact, then `{package}.*`, then `*`).
+- D-030: view variables are `screen` (the `Screen`), `record` and `tab` (the open key as a string); components get only `data` (criterion 9).
+- D-031: settings panel rows render `row.actions` with an unsaved `SettingsPanelRowModel` stand-in per panel (criterion 19).
+- D-032: Atrium's screens declare a Gate-based `access()` closure (criterion 19).
+- D-033: the stand-in is `Domains\Settings\Data\SettingsPanelRow` (not under Models/, no policy entry), superseding D-031's location.
+- D-034: `Screen::reserve(string ...$keys)` reserves tab keys the viewer may not open; reserved keys follow the reserved-key rule, never render and `?tab=` cannot open them (criteria 6, 7).
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/standards.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/standards.md
new file mode 100644
index 0000000..948a196
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/standards.md
@@ -0,0 +1,14 @@
+# Standards for Screen extensions registry
+
+| Standard | File | Source | Why it applies |
+| --- | --- | --- | --- |
+| architecture/public-api | vendor/refactor-circus/standards/standards/architecture/public-api.md | refactor-circus/standards@dev-main | `ScreenExtensions`, the definitions, `Screen` and the components become public API for every package |
+| architecture/container-bindings | vendor/refactor-circus/standards/standards/architecture/container-bindings.md | refactor-circus/standards@dev-main | Singleton registry plus the `scoped()` `ScreenVisibility` memo |
+| architecture/dependencies | vendor/refactor-circus/standards/standards/architecture/dependencies.md | refactor-circus/standards@dev-main | Packages link through string screen keys, with no `class_exists()` checks between them |
+| architecture/domain-modules | vendor/refactor-circus/standards/standards/architecture/domain-modules.md | refactor-circus/standards@dev-main | New `Domains/Screens` module |
+| atrium/components | docs/agent/standards/atrium/components.md | local | New `screen-tabs`, `screen-tab-panel` and `screen-sections` components, token-only |
+| atrium/domains | docs/agent/standards/atrium/domains.md | local | Atrium domain layout and provider registration |
+| data/value-objects | vendor/refactor-circus/standards/standards/data/value-objects.md | refactor-circus/standards@dev-main | Definitions and `Screen` use `public private(set)` and clone on register |
+| http/authorization | vendor/refactor-circus/standards/standards/http/authorization.md | refactor-circus/standards@dev-main | Host authorization first, deny by default, a hidden `?tab=` answers 403 |
+| testing/test-layers | vendor/refactor-circus/standards/standards/testing/test-layers.md | refactor-circus/standards@dev-main | Unit, feature and browser layers, including the theme matrix |
+| testing/arch-tests | vendor/refactor-circus/standards/standards/testing/arch-tests.md | refactor-circus/standards@dev-main | New classes are final with strict types |
diff --git a/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/tasks.md b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/tasks.md
new file mode 100644
index 0000000..9a0d17f
--- /dev/null
+++ b/docs/agent/specs/2026-10-29-2037-screen-extensions-registry/tasks.md
@@ -0,0 +1,64 @@
+# Tasks: Screen extensions registry
+
+## Group 1: Registry, definitions, screen and resolution
+package: Atrium
+depends on: none
+files: src/Domains/Screens/ScreensServiceProvider.php, src/Domains/Screens/Data/Concerns/DefinesExtension.php, src/Domains/Screens/Data/TabDefinition.php, src/Domains/Screens/Data/SectionDefinition.php, src/Domains/Screens/Data/Screen.php, src/Domains/Screens/Data/ResolvedScreen.php, src/Domains/Screens/Services/ScreenExtensions.php, src/Domains/Screens/Services/ScreenVisibility.php, src/Domains/DomainServiceProvider.php, src/Atrium.php, src/Facades/Atrium.php, src/Testing/ResetsScreenExtensions.php, tests/TestCase.php, tests/Pest.php, tests/Unit/Screens/TabDefinitionTest.php, tests/Unit/Screens/SectionDefinitionTest.php, tests/Unit/Screens/ScreenTest.php, tests/Unit/Screens/ScreenExtensionsTest.php, tests/Feature/Screens/ResolveScreenTest.php, tests/Feature/Screens/VisibilityTest.php, tests/Feature/Screens/ResetsScreenExtensionsTest.php
+criteria: 1, 2, 3, 4, 5, 6, 7, 8, 11
+
+- [x] 1.1 Write tests: singleton and `Atrium::screens()`; definition setters, defaults, `Error` on writes and closure reads, view/component exclusivity, trailing `Screen` argument; key, slot and target validation (including all the D-026 rejects); clone on register and string keys (`123`, `007`); duplicates per environment (local/testing throw; production reports once and keeps the first); cross-target precedence exact > `pkg.*` > `*` in all three pairings; `snapshot()`/`restore()`/`flush()` and the trait's two-test behaviour; `Screen::make`/`standard()` (package derivation, both kinds' slots, synthetic `overview`); `resolve()` tab ordering, reserved keys (exact and `*`), `?tab=` handling (string only, unknown key 200, hidden key 403); the visibility matrix, throwing `authorize` reported once, memo keyed by morph class plus key or the model itself, `forgetScopedInstances()` between viewers; wildcard matching (`*`, `test.*`), with resolve-level tests only
+- [x] 1.2 Implement `Domains/Screens`: `DefinesExtension`, `TabDefinition`, `SectionDefinition`, `Screen`, `ResolvedScreen` (`data()` memoized through `ScreenVisibility`), `ScreenExtensions` (registrations keyed by target and slot, the environment-aware duplicate rule, merging exact, `{package}.*` and `*` at resolve), `ScreenVisibility` (`scoped()`), and `ScreensServiceProvider` registered in `DomainServiceProvider`; `Atrium::screens()` on the class and the facade; `Testing\ResetsScreenExtensions`, used by `tests/TestCase.php`
+- [x] 1.3 Run vendor/bin/pest; all green
+
+## Group 2: Rendering components and the test-host screen
+package: Atrium
+depends on: 1
+files: resources/views/components/screen-tabs.blade.php, resources/views/components/screen-tab-panel.blade.php, resources/views/components/screen-sections.blade.php, workbench/app/Atrium/ScreenHost/ScreenHostController.php, workbench/resources/views/screen-host.blade.php, workbench/routes/web.php, tests/Feature/Screens/ScreenTabsComponentTest.php, tests/Feature/Screens/ScreenSectionsComponentTest.php, tests/Feature/Screens/RowSlotsTest.php, tests/Feature/Screens/WildcardRenderingTest.php, tests/Feature/Screens/FailureIsolationTest.php, tests/Feature/Screens/OpenRegisteredTabTest.php, tests/Feature/Screens/EvaluationOrderTest.php, tests/Feature/Screens/ScreenStylesTest.php
+criteria: 9, 10, 11, 12, 13, 14, 15, 16
+
+- [x] 2.1 Write tests against a workbench test-host screen (detail and list variants, with routes `test.host` and `test.list`): host denied with 403 runs no closures; resolvers only run through `data()`; view-path spread order (host's `screen`, `record` and `tab` win); component path gets one `data` prop; row slots (three rows, only the second admitted, call counts, re-render memo, misuse throws, undeclared slot never runs); a `*` section on two screens, `test.*` on `test.a` but not `other.screen`, a `*` tab opening via `?tab=`; failure isolation (markup then throw leaves nothing, reported once across three rows, throwing panel gives 500); tab bar links (query kept except `page`/`tab`, escaping, `data-testid`, `aria-current` and the primary variant only on the open tab, escaped labels, unknown icon falls back to `squares-2x2`, nothing with fewer than 2 visible tabs); sections wrapper, order, `class` passthrough, empty slot; criterion 15's layout around an open registered tab; `AtriumStyles::missingClasses()`/`inlineStyles()` empty for the new components
+- [x] 2.2 Implement the three components (tab bar as a non-wrapping `overflow-x-auto` nav of `x-atrium::icon-button`; buffered, isolated section rendering; panel rendering per criterion 9) and the workbench test-host controller, view and routes
+- [x] 2.3 Run vendor/bin/pest; all green
+
+## Group 3: Declare Atrium's own screens
+package: Atrium
+depends on: 2
+files: src/Domains/Dashboard/Http/Controllers/DashboardController.php, src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php, src/Domains/Settings/Http/Controllers/SettingsController.php, resources/views/dashboard/index.blade.php, resources/views/dashboard/widget-body.blade.php, resources/views/settings/index.blade.php, resources/views/settings/show.blade.php, tests/Feature/Screens/AtriumScreensTest.php
+criteria: 19
+
+- [x] 3.1 Write a dataset test over the five screens (`atrium.dashboard`, `atrium.named-dashboard`, `atrium.dashboard-widget`, `atrium.settings`, `atrium.settings-panel`): with a tab and a section registered in every declared slot, each section renders in its slot and not in undeclared ones, the tab appears and opens via `?tab=`; with nothing registered, no tab bar or extra markup (compare against the current response); the existing dashboard and settings suites stay green
+- [x] 3.2 Declare each screen with `Screen::standard()` in its controller (record and kind per the criterion 19 table; `row.actions` per settings panel row on `atrium.settings`) and render `screen-tabs`, `screen-tab-panel` and every declared slot in the views, laid out per criterion 15
+- [x] 3.3 Run vendor/bin/pest; all green
+
+## Group 4: Remove history from Atrium
+package: Atrium
+depends on: 1
+files: src/Domains/History/HistoryServiceProvider.php, src/Domains/History/routes.php, src/Domains/History/Http/Controllers/HistoryController.php, resources/views/history/show.blade.php, resources/views/components/audit-trail.blade.php, resources/views/components/audit/, resources/css/atrium.css, src/Domains/Plugins/Support/Plugin.php, tests/Feature/HistoryPageTest.php, tests/Feature/AuditComponentsTest.php, tests/Feature/HistoryRemovedTest.php
+criteria: 20
+
+- [x] 4.1 Write `HistoryRemovedTest`: `GET history/{package}` returns 404; the controller and the audit component files don't exist; `method_exists(Plugin::class, 'historyNavItem')` is false; `atrium.css` has no `audit` `@source`
+- [x] 4.2 Delete the History domain (and its entry in `DomainServiceProvider`'s provider list, which this group edits after group 1 has merged), `history/show`, `audit-trail`, the `components/audit/` directory, the `@source` lines and `Plugin::historyNavItem()`; delete `HistoryPageTest` and `AuditComponentsTest`; grep `src`, `resources`, `docs` and the workbench for leftover references
+- [x] 4.3 Run vendor/bin/pest; all green
+
+Note: group 4 also edits `src/Domains/DomainServiceProvider.php` to drop `HistoryServiceProvider`, so it runs after group 1, never in parallel with it.
+
+## Group 5: Browser theme and layout matrix
+package: Atrium
+depends on: 2, 3
+files: tests/Browser/ScreenExtensionsTest.php, workbench/app/Atrium/ScreenHost/ScreenHostPlugin.php, workbench/app/Providers/WorkbenchServiceProvider.php
+criteria: 17, 18
+
+- [x] 5.1 Write `ScreenExtensionsTest` as a Pest dataset over 6 themes x `sidebar`/`top` x light/dark (24 named cases). Each case renders the test host with 2 built-in tabs, 12 registered tabs (one long label), a normal-slot section and a row-slot section, then asserts: the last tab scrolls into view, clicks, and has `aria-current="page"`; the open tab's computed background differs from an idle tab's; the nav has `overflow-x` auto or scroll and `flex-wrap: nowrap`, its links `white-space: nowrap`, and all links share one top offset; in the top layout, no tab overlaps `top-tabs`; both sections render; a screenshot is saved per case Add a workbench plugin with pages so that `top-tabs` exists.
+- [x] 5.2 Fix any theme or layout issue the matrix exposes, using tokens only
+- [x] 5.3 Run vendor/bin/pest and composer test:browser; all green
+
+## Group 6: Documentation, architecture and build
+package: Atrium
+depends on: 3, 4, 5
+files: README.md, resources/boost/skills/atrium-development/SKILL.md, CLAUDE.md, docs/agent/standards/atrium/domains.md, CHANGELOG.md, tests/Feature/DocsTest.php, tests/ArchTest.php, public/atrium.css, composer.json
+criteria: 16, 20, 21, 22
+
+- [x] 6.1 Write the docs test (the "Screen extensions" section exists in the README and the Boost skill, containing `boot()`, `403`, `vendor.key`, `Keystone` and `config`). Extend `ArchTest`: the Screens classes are final with strict types, the value objects use `public private(set)`, `ScreensServiceProvider` is registered, and `composer.json` requires only Keystone among suite packages.
+- [x] 6.2 Write the README and Boost "Screen extensions" section, covering every bullet in criterion 21, including the config-defaults example. Update `CLAUDE.md` and `domains.md` (add Screens, drop History). Write the `CHANGELOG.md` entries for the new registry and the history-removal upgrade note, naming each removed route, class, method and component and pointing to Keen.
+- [x] 6.3 Run `npm run build:css` and commit `public/atrium.css`. Grep the workspace for `atrium.history`, `x-atrium::audit` and `historyNavItem` and record the results for the PR.
+- [x] 6.4 Run vendor/bin/pest, composer test and composer test:browser; all green
diff --git a/docs/agent/standards-feedback.md b/docs/agent/standards-feedback.md
index 4091cb2..ed12164 100644
--- a/docs/agent/standards-feedback.md
+++ b/docs/agent/standards-feedback.md
@@ -4,3 +4,4 @@ Every time work has to break a standard, add a row. `/ring-master-discover-stand
| Date | Spec | Standard | Deviation | Why |
| --- | --- | --- | --- | --- |
+| 2026-10-29 | 2026-10-29-2037-screen-extensions-registry | data/value-objects | `Screen::kind()` takes a string (`detail`/`list`, with `Screen::DETAIL`/`Screen::LIST` constants) instead of a string-backed enum | The spec fixes the public signatures `kind('detail'\|'list')` and `Screen::standard(string $key, string $kind)`; the constants follow `Theme::SIDEBAR`/`Theme::TOP` |
diff --git a/docs/agent/standards/atrium/components.md b/docs/agent/standards/atrium/components.md
index 395dc2e..f6e8d2b 100644
--- a/docs/agent/standards/atrium/components.md
+++ b/docs/agent/standards/atrium/components.md
@@ -16,7 +16,7 @@ Atrium owns every Blade component and every style of the first-party suite; othe
## Existing generic pieces
-- `description-list`, bare form controls (`bare`), input `prefix`/`suffix`, `form.combobox`, `search-input`, `chip`, `banner` (`standalone` for host-app pages), `form.actions`, `flash`, `guest`, `audit-trail`, `audit.entries`, `audit.changes`.
+- `description-list`, bare form controls (`bare`), input `prefix`/`suffix`, `form.combobox`, `search-input`, `chip`, `banner` (`standalone` for host-app pages), `form.actions`, `flash`, `guest`.
## Enforcement
diff --git a/docs/agent/standards/atrium/domains.md b/docs/agent/standards/atrium/domains.md
index 8e6601b..f67e760 100644
--- a/docs/agent/standards/atrium/domains.md
+++ b/docs/agent/standards/atrium/domains.md
@@ -1,5 +1,5 @@
---
-description: "Atrium's domains (Access, Dashboard, History, Navigation, Plugins, Search, Settings, Themes, Widgets), its top-level package-wide code, domain providers on Atrium\\Support\\ServiceProvider loading routes with loadDashboardRoutesFrom(), and the Dashboard morph aliases."
+description: "Atrium's domains (Access, Dashboard, Navigation, Plugins, Screens, Search, Settings, Themes, Widgets), its top-level package-wide code, domain providers on Atrium\\Support\\ServiceProvider loading routes with loadDashboardRoutesFrom(), and the Dashboard morph aliases."
tags: [atrium, domains, service-providers, routes, morph-aliases]
kind: convention
---
@@ -10,8 +10,10 @@ Complements [[domain-modules]]: Atrium's code sits in nine fixed domains whose p
## Domains
-- `Access`, `Dashboard`, `History`, `Navigation`, `Plugins`, `Search`, `Settings`, `Themes`, `Widgets`, under `RefactorCircus\Atrium\Domains\{Domain}`.
+- `Access`, `Dashboard`, `Navigation`, `Plugins`, `Screens`, `Search`, `Settings`, `Themes`, `Widgets`, under `RefactorCircus\Atrium\Domains\{Domain}`.
- A new domain is added to this list and its provider to `Domains\DomainServiceProvider::$providers`.
+- `Screens` holds the screen extensions registry: `Data\Screen`, `Data\TabDefinition`, `Data\SectionDefinition` and `Data\ResolvedScreen`, the `Services\ScreenExtensions` singleton (`Atrium::screens()`) and the `scoped()` `Services\ScreenVisibility`. It registers no routes; its components are `screen-tabs`, `screen-sections` and `screen-tab-panel`.
+- Atrium has no History domain and no audit concept: the history screen, its components and its nav item belong to refactor-circus/keen.
## Top level
diff --git a/lang/en/atrium.php b/lang/en/atrium.php
index 4a7f88f..ff75661 100644
--- a/lang/en/atrium.php
+++ b/lang/en/atrium.php
@@ -47,29 +47,5 @@
'narrower' => 'Make narrower',
'drag_to_reorder' => 'Drag to reorder',
'no_settings_panels' => 'No settings panels are available.',
- 'audit_history' => 'History',
- 'audit_empty' => 'Nothing has been recorded yet.',
- 'audit_when' => 'When',
- 'audit_action' => 'Action',
- 'audit_subject' => 'Record',
- 'audit_actor' => 'By',
- 'audit_surface' => 'Through',
- 'audit_source_app' => 'App',
- 'audit_none' => '—',
- 'audit_system' => 'System',
- 'audit_no_changes' => 'No fields changed.',
- 'audit_field' => 'Field',
- 'audit_before' => 'Before',
- 'audit_after' => 'After',
- 'audit_view_all' => 'View all',
- 'audit_log' => 'Audit log',
- 'audit_log_for' => ':package audit log',
- 'audit_action_hint' => 'Exact, or a prefix ending in a dot: product.',
- 'audit_subject_type' => 'Record type',
- 'audit_subject_id' => 'Record key',
- 'audit_filter' => 'Filter',
- 'audit_clear' => 'Clear',
- 'audit_newest' => 'Newest',
- 'audit_older' => 'Older',
];
diff --git a/phpstan.neon.dist b/phpstan.neon.dist
index 0c76883..962de4e 100644
--- a/phpstan.neon.dist
+++ b/phpstan.neon.dist
@@ -5,4 +5,6 @@ parameters:
- config
- database
- tests/Fixtures/Billing
+ # Analyses the published Testing\ResetsScreenExtensions trait through its user.
+ - tests/TestCase.php
tmpDir: build/phpstan
diff --git a/resources/boost/skills/atrium-development/SKILL.md b/resources/boost/skills/atrium-development/SKILL.md
index bbd5d08..e03d96a 100644
--- a/resources/boost/skills/atrium-development/SKILL.md
+++ b/resources/boost/skills/atrium-development/SKILL.md
@@ -3,7 +3,8 @@ name: atrium-development
description: >
Configure and apply the Atrium dashboard package in Laravel applications,
including the authorization gate, dashboard policies, events, plugins,
- widgets, dashboards, and the shared Blade component library.
+ widgets, dashboards, screen extensions (tabs and sections added to any
+ declared screen), and the shared Blade component library.
license: MIT
metadata:
author: Jay Fletcher
@@ -63,7 +64,7 @@ Screens follow one convention: actions are `
@@ -101,6 +102,104 @@ Event::listen(DashboardCreatedActionEvent::class, fn ($event) => Log::info('Dash
In tests, fake only the events being asserted: `Event::fake([DashboardCreatedActionEvent::class])`.
+## Screen extensions
+
+Any package can add tabs and sections to any screen that declares itself, without the screen knowing the package exists. A screen declares only its key (`{package}.{screen}`), record, kind, built-in tabs and slots. Atrium's own declared screens are `atrium.dashboard`, `atrium.named-dashboard`, `atrium.dashboard-widget`, `atrium.settings` and `atrium.settings-panel`.
+
+### Register from boot() only
+
+Register through `Atrium::screens()` (`RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions`) from a service provider's `boot()`, never during a request: the registry lasts for the process and nothing can be unregistered. Registration keeps a copy of the definition.
+
+```php
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Http\Request;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Data\SectionDefinition;
+use RefactorCircus\Atrium\Domains\Screens\Data\TabDefinition;
+use RefactorCircus\Atrium\Facades\Atrium;
+
+Atrium::screens()
+ // A tab on one screen, opened with ?tab=acme.invoices.
+ ->tab('crm.customer', TabDefinition::make('acme.invoices')
+ ->label('Invoices')
+ ->icon('banknotes')
+ ->view('acme::screens.invoices')
+ ->permission('acme.invoices.view')
+ ->resolve(fn (?Model $record, Screen $screen): array => ['invoices' => Invoice::forCustomer($record)->get()]))
+ // A section in one slot of one screen.
+ ->section('crm.customer', 'aside', SectionDefinition::make('acme.balance')
+ ->component('acme::balance')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $request->user()?->can('view', $record) === true))
+ // A row section: once per row of a list screen, the row as $record.
+ ->section('crm.customers', 'row.actions', SectionDefinition::make('acme.row-balance')
+ ->view('acme::screens.row-balance')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $record instanceof Customer))
+ // A wildcard section on every screen declaring the slot: return early.
+ ->section('*', 'aside', SectionDefinition::make('acme.notes')
+ ->view('acme::screens.notes')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $screen->kind === Screen::DETAIL
+ && $record !== null
+ && $request->user()?->can('acme.notes', $record) === true));
+```
+
+- Targets: an exact key (`crm.customer`), `{package}.*` (every screen of one package) or `*` (every screen). A registration for a screen nobody declares never renders, with no error; a section on an undeclared slot never runs its closures.
+- Keys: always `vendor.key` (`acme.invoices`), matching `^[a-z0-9][a-z0-9._-]*$`. A registered tab may not reuse a built-in tab key (`overview` included); it is skipped and reported.
+- Rendering: `view()` or `component()` (one clears the other). A view gets the resolver's data with the host's `screen` (the `Screen`), `record` and `tab` (the open key) over it; a component gets one `data` prop.
+- Visibility is default-deny: `permission()` (asked through the screen's `access` closure; a screen without one hides it), `authorize()`, both when both are set, or `public()`. A throwing `authorize()` is a denial, reported once per request.
+
+### Closures and evaluation order
+
+Every closure takes the `Screen` last: `authorize(fn (Request $request, ?Model $record, Screen $screen): bool)` and `resolve(fn (?Model $record, Screen $screen): array)`. `$record` is the screen's record, or the row inside a row slot. The host authorizes first and resolves the screen only then; tab visibility is checked at resolve, section visibility when the slot renders (per row in a row slot); resolvers run only for the open registered tab and each rendered section; answers and data are memoized per request. Wildcard and row-slot closures run on every matching screen or row, so keep them cheap: return early on `$screen->key` or `$screen->kind`.
+
+### Tabs, panels and failures
+
+- `?tab={key}` opens a tab. An absent or unknown key opens the default tab (200); a registered tab the viewer cannot see answers 403. That 403-versus-200 difference reveals which keys exist, which is accepted, so never put secrets in a key.
+- The tab bar shows with two or more visible tabs. A screen without built-in tabs gets `overview`; registered tabs follow the built-ins and are never the default. Atrium translates no labels.
+- `$screen->reserve('salaries')` reserves keys of built-in tabs this viewer may not open: a registered tab with one is skipped and reported, as for a built-in key; reserved keys never render, and `?tab=` naming one opens the default (200).
+- An open registered tab's panel replaces the host's page content: `header.actions` always renders, `before`, `after`, `aside` and row slots only on a built-in tab.
+- A failing section renders nothing, is reported once per request, and the page answers 200; a failing open tab panel gives a 500.
+- Theme contract: the components use only design tokens and safelisted utilities, the same in every theme and layout, with nothing per theme. Keep registered views to the same, checked with `AtriumStyles`.
+- A section renders inside the host's page but writes through the registrant's own routes and authorization.
+
+### Duplicates
+
+- Same key twice on one target string (and slot): throws `InvalidArgumentException` in `local` and `testing`; in production and any other environment it is reported once through `report()`, the later one is skipped and the first kept.
+- Same key on one screen through different targets: the more specific wins (exact, then `{package}.*`, then `*`); the rest are skipped and reported once per request.
+
+### Declaring a screen (host side)
+
+```php
+$screen = Screen::standard('acme.invoice', Screen::DETAIL) // header.actions, before, after, aside
+ ->record($invoice)
+ ->tabs([['key' => 'details', 'label' => __('Details'), 'icon' => 'document-text']])
+ ->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record ? [$record] : []));
+
+$resolved = app(ScreenExtensions::class)->resolve($screen, $request); // after the host's own authorization
+```
+
+`Screen::standard($key, Screen::LIST)` gives `header.actions`, `before`, `after` and the row slot `row.actions`; add more with `slots()` / `rowSlots()`. In the view render ` `, then ` ` when `$resolved->openRegisteredTab !== null`, otherwise ` ` (and `aside`, `after`) around the page; `header.actions` always; a row slot per row with `:row="$model"`.
+
+### Suite rule and config defaults
+
+Atrium requires only Keystone (`refactor-circus/keystone`) among the suite packages; every other suite package is a `suggest`, and a package's Atrium UI loads only when Atrium is installed. A package never names another package's screens in code: it ships editable defaults in its own config, applied only when the target screen exists, which the application may change or empty.
+
+```php
+// config/acme.php
+'atrium' => ['screens' => ['crm.customer' => 'tab', 'crm.contact' => 'aside']],
+
+// AcmeServiceProvider::boot()
+if (class_exists(Atrium::class)) {
+ foreach (config('acme.atrium.screens', []) as $target => $slot) {
+ $slot === 'tab'
+ ? Atrium::screens()->tab($target, $this->invoicesTab())
+ : Atrium::screens()->section($target, $slot, $this->balanceSection());
+ }
+}
+```
+
+In tests, use `RefactorCircus\Atrium\Testing\ResetsScreenExtensions` on the test case: it snapshots the registry after boot and restores it after each test.
+
## Rules, References, and Templates
Read before executing:
@@ -128,5 +227,7 @@ Read before executing:
- do not register plugin routes outside the plugin's `routes()` method, which would skip Atrium's middleware and prefix
- do not require a Tailwind build in the host app; the shipped stylesheet is self-contained
- do not bypass the policies by writing dashboards directly in a controller; call the actions, and check `$user->can(...)` first
+- do not register screen extensions outside a provider's `boot()`, give them keys without a vendor prefix, or hard-code another package's screen keys in a package's code; read them from the package's own config
+- do not require another suite package to integrate with it; suggest it and integrate through screens and config
- do not use the pre-release `Atrium\Atrium` namespace or its `Events\Dashboard\*`, `Events\DashboardWidget\*` and `Events\Actions\*` classes
-- do not use the pre-domain class names (`RefactorCircus\Atrium\Plugins\Plugin`, `RefactorCircus\Atrium\Navigation\NavItem`, `RefactorCircus\Atrium\Models\Dashboard`, `RefactorCircus\Atrium\Events\Model\*`, `RefactorCircus\Atrium\Events\Action\*` and so on); every class now lives in a domain module under `RefactorCircus\Atrium\Domains\{Access,Dashboard,Navigation,Plugins,Search,Settings,Widgets}`, with value objects in `Data\`, registries in `Services\` and models named `*Model`
+- do not use the pre-domain class names (`RefactorCircus\Atrium\Plugins\Plugin`, `RefactorCircus\Atrium\Navigation\NavItem`, `RefactorCircus\Atrium\Models\Dashboard`, `RefactorCircus\Atrium\Events\Model\*`, `RefactorCircus\Atrium\Events\Action\*` and so on); every class now lives in a domain module under `RefactorCircus\Atrium\Domains\{Access,Dashboard,Navigation,Plugins,Screens,Search,Settings,Themes,Widgets}`, with value objects in `Data\`, registries in `Services\` and models named `*Model`
diff --git a/resources/css/atrium.css b/resources/css/atrium.css
index 328eaa0..b4cab89 100644
--- a/resources/css/atrium.css
+++ b/resources/css/atrium.css
@@ -40,9 +40,6 @@
/* @atrium-sources */
@source '../views/components/alert.blade.php';
-@source '../views/components/audit-trail.blade.php';
-@source '../views/components/audit/changes.blade.php';
-@source '../views/components/audit/entries.blade.php';
@source '../views/components/avatar.blade.php';
@source '../views/components/badge.blade.php';
@source '../views/components/banner.blade.php';
@@ -73,6 +70,9 @@
@source '../views/components/page-header.blade.php';
@source '../views/components/pagination.blade.php';
@source '../views/components/progress.blade.php';
+@source '../views/components/screen-sections.blade.php';
+@source '../views/components/screen-tab-panel.blade.php';
+@source '../views/components/screen-tabs.blade.php';
@source '../views/components/search-input.blade.php';
@source '../views/components/section.blade.php';
@source '../views/components/skeleton.blade.php';
@@ -91,7 +91,6 @@
@source '../views/dashboard/switcher.blade.php';
@source '../views/dashboard/widget-body.blade.php';
@source '../views/dashboard/widget.blade.php';
-@source '../views/history/show.blade.php';
@source '../views/layouts/app.blade.php';
@source '../views/partials/appearance.blade.php';
@source '../views/partials/nav-item.blade.php';
diff --git a/resources/views/components/audit-trail.blade.php b/resources/views/components/audit-trail.blade.php
deleted file mode 100644
index fce8aa2..0000000
--- a/resources/views/components/audit-trail.blade.php
+++ /dev/null
@@ -1,50 +0,0 @@
-@props([
- // The package key whose history to show, such as `showroom`.
- 'source' => null,
- // One record's history; omit for the whole package's.
- 'subject' => null,
- // Everything scoped to this model, such as an organization.
- 'scope' => null,
- // Only this action, or a prefix ending in a dot: `feature.`.
- 'action' => null,
- 'limit' => 20,
- 'title' => null,
-])
-
-{{--
- A package's own history, read from whichever audit log is installed
- through refactor-circus/keystone's AuditTrail. Renders nothing until one is
- (refactor-circus/keen), or while the package turns its auditing off, so
- packages can place it unconditionally:
-
-
---}}
-
-@php
- $trail = app(\RefactorCircus\Keystone\Audit\Contracts\AuditTrail::class);
- $package = $source === null ? null : app(\RefactorCircus\Keystone\Packages\PackageRegistry::class)->find($source);
-
- // Shown only to those the package's history endpoint would answer.
- $allowed = $package === null || app(\RefactorCircus\Keystone\Audit\History::class)->allows($package, auth()->user(), array_filter([
- 'subject_type' => $subject?->getMorphClass(),
- 'subject_id' => $subject === null ? null : (string) $subject->getKey(),
- ]));
-
- // Only while the package audits (Keen installed, its `audit.enabled` on).
- $page = $allowed && ($package === null ? $trail->available() : $package->audits())
- ? $trail->entries(\RefactorCircus\Keystone\Audit\Data\AuditFilter::make()->source($source)->subject($subject)->scope($scope)->action($action)->limit((int) $limit))
- : null;
-@endphp
-
-@if ($page !== null)
- merge(['data-testid' => 'audit-trail']) }}>
-
-
- {{-- The package's own audit log, filtered to what this panel shows. --}}
- @if ($page->nextCursor !== null && $package !== null)
-
- {{ __('atrium::atrium.audit_view_all') }}
-
- @endif
-
-@endif
diff --git a/resources/views/components/audit/changes.blade.php b/resources/views/components/audit/changes.blade.php
deleted file mode 100644
index 1a2a1e6..0000000
--- a/resources/views/components/audit/changes.blade.php
+++ /dev/null
@@ -1,29 +0,0 @@
-@props([
- // array: field => [old, new]
- 'changes' => [],
-])
-
-@php
- $show = fn (mixed $value): string => is_scalar($value) || $value === null ? var_export($value, true) : (string) json_encode($value, JSON_UNESCAPED_SLASHES);
-@endphp
-
-@if ($changes === [])
- class('text-sm') }}>{{ __('atrium::atrium.audit_no_changes') }}
-@else
- merge(['data-testid' => 'audit-changes']) }}>
-
-
- {{ __('atrium::atrium.audit_field') }}
- {{ __('atrium::atrium.audit_before') }}
- {{ __('atrium::atrium.audit_after') }}
-
-
- @foreach ($changes as $field => $change)
-
- {{ $field }}
- {{ $show($change[0] ?? null) }}
- {{ $show($change[1] ?? null) }}
-
- @endforeach
-
-@endif
diff --git a/resources/views/components/audit/entries.blade.php b/resources/views/components/audit/entries.blade.php
deleted file mode 100644
index d18ae4d..0000000
--- a/resources/views/components/audit/entries.blade.php
+++ /dev/null
@@ -1,53 +0,0 @@
-@props([
- // list<\RefactorCircus\Keystone\Audit\Data\AuditEntry>
- 'entries' => [],
- // Hide the subject column, for a single record's history.
- 'withoutSubject' => false,
-])
-
-@php
- // Keen's dashboard section shows an entry in full; link to it when it
- // is installed.
- $link = \Illuminate\Support\Facades\Route::has('atrium.keen.entries.show');
-@endphp
-
-@if ($entries === [] || (is_countable($entries) && count($entries) === 0))
-
-@else
- merge(['data-testid' => 'audit-entries']) }}>
-
-
- {{ __('atrium::atrium.audit_when') }}
- {{ __('atrium::atrium.audit_action') }}
- @unless ($withoutSubject)
- {{ __('atrium::atrium.audit_subject') }}
- @endunless
- {{ __('atrium::atrium.audit_actor') }}
- {{ __('atrium::atrium.audit_surface') }}
-
-
-
- @foreach ($entries as $entry)
-
-
- @if ($link)
- {{ $entry->createdAt->diffForHumans() }}
- @else
- {{ $entry->createdAt->diffForHumans() }}
- @endif
-
-
- {{ $entry->action }}
- @if ($entry->source === 'app')
- {{ __('atrium::atrium.audit_source_app') }}
- @endif
-
- @unless ($withoutSubject)
- {{ $entry->subjectLabel ?? __('atrium::atrium.audit_none') }}
- @endunless
- {{ $entry->actorLabel ?? __('atrium::atrium.audit_system') }}
- {{ $entry->surface }}
-
- @endforeach
-
-@endif
diff --git a/resources/views/components/screen-sections.blade.php b/resources/views/components/screen-sections.blade.php
new file mode 100644
index 0000000..7c77fb1
--- /dev/null
+++ b/resources/views/components/screen-sections.blade.php
@@ -0,0 +1,63 @@
+{{--
+ The sections of one of a screen's slots the viewer may see, in order, each
+ in an element with data-testid="section-{key}" that carries any `class`
+ given. A row slot renders once per row, with the row:
+
+
+
+
+ A section's data comes from ResolvedScreen::data(), so its resolver runs
+ only when it renders. A view gets the data with the host's `screen`,
+ `record` and `tab` over it; a component gets it as one `data` prop. Each
+ section renders into a buffer first: one whose resolver or view throws
+ renders nothing, is reported once per request, and the page carries on.
+--}}
+@props(['screen', 'row' => null])
+
+@php
+ // `$slot` is Blade's default slot, so the slot name comes from the attributes.
+ $atriumSlot = (string) $attributes->get('slot');
+ $atriumSections = $row === null ? $screen->sections($atriumSlot) : $screen->rowSections($atriumSlot, $row);
+ $atriumRendered = [];
+ $atriumViews = view();
+
+ foreach ($atriumSections as $atriumSection) {
+ $atriumLevel = ob_get_level();
+
+ // A view that throws makes Laravel flush the view factory's state,
+ // which would take the page's open components with it; keep a copy
+ // to put back.
+ $atriumState = (fn (): array => get_object_vars($this))->call($atriumViews);
+
+ try {
+ $atriumData = $screen->data($atriumSection, $row);
+
+ $atriumRendered[] = [$atriumSection->key, $atriumSection->component !== null
+ ? \Illuminate\Support\Facades\Blade::render('component.' :data="$data" />', ['data' => $atriumData])
+ : view($atriumSection->view, [
+ ...$atriumData,
+ 'screen' => $screen->screen,
+ 'record' => $row ?? $screen->screen->record,
+ 'tab' => $screen->openTab,
+ ])->render()];
+ } catch (\Throwable $atriumException) {
+ // Discard whatever the section wrote before it failed.
+ while (ob_get_level() > $atriumLevel) {
+ ob_end_clean();
+ }
+
+ (function (array $state): void {
+ foreach ($state as $property => $value) {
+ $this->{$property} = $value;
+ }
+ })->call($atriumViews, $atriumState);
+
+ app(\RefactorCircus\Atrium\Domains\Screens\Services\ScreenVisibility::class)
+ ->report("render\0{$screen->screen->key}\0{$atriumSection->key}", $atriumException);
+ }
+ }
+@endphp
+
+@foreach ($atriumRendered as [$atriumKey, $atriumHtml])
+ except('slot')->merge(['data-testid' => 'section-'.$atriumKey]) }}>{!! $atriumHtml !!}
+@endforeach
diff --git a/resources/views/components/screen-tab-panel.blade.php b/resources/views/components/screen-tab-panel.blade.php
new file mode 100644
index 0000000..5bed2f5
--- /dev/null
+++ b/resources/views/components/screen-tab-panel.blade.php
@@ -0,0 +1,28 @@
+{{--
+ The open registered tab's panel, which replaces the host's page content;
+ nothing while a built-in tab is open. A view gets the tab's data with the
+ host's `screen`, `record` and `tab` over it; a component gets it as one
+ `data` prop. A panel that throws is not caught: the request fails as any
+ page would.
+
+
+--}}
+@props(['screen'])
+
+@if ($screen->openRegisteredTab !== null)
+ @php
+ $atriumTab = $screen->openRegisteredTab;
+ $atriumData = $screen->data($atriumTab);
+
+ $atriumHtml = $atriumTab->component !== null
+ ? \Illuminate\Support\Facades\Blade::render('component.' :data="$data" />', ['data' => $atriumData])
+ : view($atriumTab->view, [
+ ...$atriumData,
+ 'screen' => $screen->screen,
+ 'record' => $screen->screen->record,
+ 'tab' => $screen->openTab,
+ ])->render();
+ @endphp
+
+ merge(['data-testid' => 'tab-panel-'.$atriumTab->key]) }}>{!! $atriumHtml !!}
+@endif
diff --git a/resources/views/components/screen-tabs.blade.php b/resources/views/components/screen-tabs.blade.php
new file mode 100644
index 0000000..66318cd
--- /dev/null
+++ b/resources/views/components/screen-tabs.blade.php
@@ -0,0 +1,28 @@
+{{--
+ A screen's tab bar: the built-in tabs, then the registered ones the viewer
+ may see, as icon-button links to `?tab={key}` that keep the rest of the
+ query string except `page`. The open tab is the primary button and has
+ aria-current="page". The bar is a flex row, which never wraps, and
+ scrolls sideways when its tabs overflow. It renders nothing while fewer
+ than two tabs are visible.
+
+
+--}}
+@props(['screen'])
+
+@if (count($screen->tabs) >= 2)
+ merge(['data-testid' => 'screen-tabs'])->class('flex items-center gap-1 overflow-x-auto border-b border-outline pb-2 dark:border-outline-dark') }}>
+ @foreach ($screen->tabs as $tab)
+ @php($open = $tab->key === $screen->openTab)
+
+
+ @endforeach
+
+@endif
diff --git a/resources/views/dashboard/index.blade.php b/resources/views/dashboard/index.blade.php
index a80a682..7bb050b 100644
--- a/resources/views/dashboard/index.blade.php
+++ b/resources/views/dashboard/index.blade.php
@@ -1,5 +1,11 @@
@php($visible = $placements->reject(fn ($placement) => $placement->isOrphaned())->values())
+{{-- The `atrium.dashboard` (or `atrium.named-dashboard`) screen: header
+ actions always render; an open registered tab's panel replaces the
+ widgets, and `before`, `aside` and `after` render only around them. --}}
+@php($panelOpen = $resolved->openRegisteredTab !== null)
+@php($aside = ! $panelOpen && $resolved->sections('aside') !== [])
+
{{-- The Alpine scope wraps the header too, so the edit toggle and the grid
share one state. --}}
@@ -17,7 +23,7 @@
@include('atrium::dashboard.switcher')
- @if ($editable)
+ @if ($editable && ! $panelOpen)
{{-- Two buttons rather than one with x-text, so each label
is real markup present before Alpine boots. --}}
@endif
+
+
-
+
- @if ($dashboard === null)
-
+ @if ($panelOpen)
+
@else
- @if ($visible->isEmpty())
-
- @if ($editable)
-
-
+
+
+
+ @if ($aside)
+
+
+ @endif
+
+ @if ($dashboard === null)
+
+ @else
+ @if ($visible->isEmpty())
+
+ @if ($editable)
+
+
+ {{ __('atrium::atrium.add_widget') }}
+
+
+ @endif
+
+ @endif
+
+
+ @foreach ($visible as $placement)
+ @include('atrium::dashboard.widget', ['placement' => $placement, 'editable' => $editable])
+ @endforeach
+
+
+ @if ($editable)
+ @if ($visible->isNotEmpty())
+
+
{{ __('atrium::atrium.add_widget') }}
-
+
@endif
-
+
+ @include('atrium::dashboard.picker', ['available' => $available])
+ @endif
@endif
-
- @foreach ($visible as $placement)
- @include('atrium::dashboard.widget', ['placement' => $placement, 'editable' => $editable])
- @endforeach
-
-
- @if ($editable)
- @if ($visible->isNotEmpty())
-
-
- {{ __('atrium::atrium.add_widget') }}
-
+ @if ($aside)
- @endif
- @include('atrium::dashboard.picker', ['available' => $available])
+
+
@endif
+
+
@endif
diff --git a/resources/views/dashboard/widget-body.blade.php b/resources/views/dashboard/widget-body.blade.php
index f34809a..01df6c6 100644
--- a/resources/views/dashboard/widget-body.blade.php
+++ b/resources/views/dashboard/widget-body.blade.php
@@ -1,6 +1,55 @@
-@if ($definition?->component)
-
-@elseif ($definition?->view)
- @include($definition->view, $definition->resolveData($placement->settings ?? []))
+{{--
+ A placed widget's body. The dashboard page includes it inline; the lazy
+ widget endpoint renders it as the `atrium.dashboard-widget` screen and
+ passes that screen as `widgetScreen`, so header actions and the tab bar
+ sit above it, `before`, `aside` and `after` around it, and an open
+ registered tab's panel replaces it.
+--}}
+@php
+ $atriumWidgetScreen = $widgetScreen ?? null;
+ $atriumWidgetPanel = $atriumWidgetScreen !== null && $atriumWidgetScreen->openRegisteredTab !== null;
+ $atriumWidgetAside = $atriumWidgetScreen !== null && ! $atriumWidgetPanel && $atriumWidgetScreen->sections('aside') !== [];
+@endphp
+
+@if ($atriumWidgetScreen !== null)
+ @if ($atriumWidgetScreen->sections('header.actions') !== [])
+
+
+
+ @endif
+
+
+@endif
+
+@if ($atriumWidgetPanel)
+
+@else
+ @if ($atriumWidgetScreen !== null)
+
+ @endif
+
+ @if ($atriumWidgetAside)
+
+
+ @endif
+
+ @if ($definition?->component)
+
+ @elseif ($definition?->view)
+ @include($definition->view, $definition->resolveData($placement->settings ?? []))
+ @endif
+
+ @if ($atriumWidgetAside)
+
+
+
+
+ @endif
+
+ @if ($atriumWidgetScreen !== null)
+
+ @endif
@endif
diff --git a/resources/views/history/show.blade.php b/resources/views/history/show.blade.php
deleted file mode 100644
index c815978..0000000
--- a/resources/views/history/show.blade.php
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- @if (isset($filters['cursor']) || $page->nextCursor !== null)
-
- @isset($filters['cursor'])
- {{ __('atrium::atrium.audit_newest') }}
- @endisset
- @if ($page->nextCursor !== null)
- {{ __('atrium::atrium.audit_older') }}
- @endif
-
- @endif
-
-
diff --git a/resources/views/settings/index.blade.php b/resources/views/settings/index.blade.php
index 981de79..3564855 100644
--- a/resources/views/settings/index.blade.php
+++ b/resources/views/settings/index.blade.php
@@ -1,17 +1,39 @@
+{{-- The `atrium.settings` screen: header actions always render; an open
+ registered tab's panel replaces the panel list, and `before`, `after` and
+ each panel row's `row.actions` render only around it. A row is the
+ panel's SettingsPanelRow, so row sections receive it as `$record`. --}}
-
+
+ @if ($resolved->sections('header.actions') !== [])
+
+
+
+ @endif
+
- @if (count($panels) === 0)
-
+
+
+ @if ($resolved->openRegisteredTab !== null)
+
@else
-
- @foreach ($panels as $panel)
-
-
- {{ $panel->label }}
-
-
- @endforeach
-
+
+
+ @if (count($rows) === 0)
+
+ @else
+
+ @foreach ($rows as $row)
+
+
+ {{ $row->panel->label }}
+
+
+
+
+ @endforeach
+
+ @endif
+
+
@endif
diff --git a/resources/views/settings/show.blade.php b/resources/views/settings/show.blade.php
index 31c5a65..bf783ef 100644
--- a/resources/views/settings/show.blade.php
+++ b/resources/views/settings/show.blade.php
@@ -1,12 +1,46 @@
+{{-- The `atrium.settings-panel` screen: header actions always render; an
+ open registered tab's panel replaces the settings panel, and `before`,
+ `aside` and `after` render only around it. --}}
+@php($panelOpen = $resolved->openRegisteredTab !== null)
+@php($aside = ! $panelOpen && $resolved->sections('aside') !== [])
+
-
-
-
- @if ($panel->component)
-
- @elseif ($panel->view)
- @include($panel->view, $panel->resolveData())
+
+ @if ($resolved->sections('header.actions') !== [])
+
+
+
+ @endif
+
+
+
+
+ @if ($panelOpen)
+
+ @else
+
+
+ @if ($aside)
+
+
+ @else
+
+ @endif
+ @if ($panel->component)
+
+ @elseif ($panel->view)
+ @include($panel->view, $panel->resolveData())
+ @endif
+
+
+ @if ($aside)
+
+
@endif
-
+
+
+ @endif
diff --git a/src/Atrium.php b/src/Atrium.php
index 39b2a9b..7de94ba 100644
--- a/src/Atrium.php
+++ b/src/Atrium.php
@@ -13,6 +13,7 @@
use RefactorCircus\Atrium\Domains\Navigation\Services\NavigationRegistry;
use RefactorCircus\Atrium\Domains\Plugins\Contracts\Plugin;
use RefactorCircus\Atrium\Domains\Plugins\Services\PluginRegistry;
+use RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions;
use RefactorCircus\Atrium\Domains\Search\Data\SearchResult;
use RefactorCircus\Atrium\Domains\Search\Data\SearchSource;
use RefactorCircus\Atrium\Domains\Search\Services\SearchRegistry;
@@ -35,8 +36,18 @@ public function __construct(
protected Gatekeeper $gatekeeper,
protected StyleRegistry $styles,
protected ThemeRegistry $themes,
+ protected ScreenExtensions $screens,
) {}
+ /**
+ * The tabs and sections packages add to screens. Register from a
+ * provider's `boot()`: `Atrium::screens()->tab('roster.user', ...)`.
+ */
+ public function screens(): ScreenExtensions
+ {
+ return $this->screens;
+ }
+
/**
* Offer a theme in the dashboard's theme switcher, or replace the one
* with the same key.
diff --git a/src/Domains/Dashboard/Http/Controllers/DashboardController.php b/src/Domains/Dashboard/Http/Controllers/DashboardController.php
index 91b53c7..60485a5 100644
--- a/src/Domains/Dashboard/Http/Controllers/DashboardController.php
+++ b/src/Domains/Dashboard/Http/Controllers/DashboardController.php
@@ -6,10 +6,14 @@
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
use RefactorCircus\Atrium\Domains\Dashboard\Actions\CreateDashboardAction;
use RefactorCircus\Atrium\Domains\Dashboard\Data\CreateDashboardData;
use RefactorCircus\Atrium\Domains\Dashboard\Services\DashboardManager;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions;
use RefactorCircus\Atrium\Domains\Widgets\Services\WidgetRegistry;
class DashboardController
@@ -17,6 +21,7 @@ class DashboardController
public function __construct(
protected DashboardManager $dashboards,
protected WidgetRegistry $widgets,
+ protected ScreenExtensions $screens,
) {}
public function index(Request $request): View
@@ -57,10 +62,20 @@ protected function render(Request $request, ?string $slug): View
}
}
+ // `/` and `d/{slug}` are separate screens, so a package can extend
+ // one without the other.
+ // Extensions' `permission()`s are Gate abilities, asked about the
+ // dashboard.
+ $screen = Screen::standard($slug === null ? 'atrium.dashboard' : 'atrium.named-dashboard', Screen::DETAIL)
+ ->record($current)
+ ->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record ? [$record] : []));
+
/** @var view-string $view */
$view = 'atrium::dashboard.index';
return view($view, [
+ 'resolved' => $this->screens->resolve($screen, $request),
'dashboards' => $dashboards,
'dashboard' => $current,
'placements' => $current === null ? collect() : $current->widgets,
diff --git a/src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php b/src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php
index 04b2f12..3442de1 100644
--- a/src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php
+++ b/src/Domains/Dashboard/Http/Controllers/DashboardWidgetController.php
@@ -4,20 +4,28 @@
namespace RefactorCircus\Atrium\Domains\Dashboard\Http\Controllers;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
+use Illuminate\Support\Facades\Gate;
use RefactorCircus\Atrium\Domains\Dashboard\Models\DashboardModel;
use RefactorCircus\Atrium\Domains\Dashboard\Models\DashboardWidgetModel;
use RefactorCircus\Atrium\Domains\Dashboard\Services\DashboardManager;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions;
/**
* Renders one placed widget's body, for widgets defined `->lazy()`. It
* answers whoever may see the dashboard the widget is on, as the dashboard
- * page does, behind the same route gate.
+ * page does, behind the same route gate. It is the `atrium.dashboard-widget`
+ * screen, with the widget as its record.
*/
class DashboardWidgetController
{
- public function __construct(protected DashboardManager $dashboards) {}
+ public function __construct(
+ protected DashboardManager $dashboards,
+ protected ScreenExtensions $screens,
+ ) {}
public function show(Request $request, DashboardModel $dashboard, DashboardWidgetModel $widget): Response
{
@@ -27,9 +35,23 @@ public function show(Request $request, DashboardModel $dashboard, DashboardWidge
abort_if($definition === null, 404);
+ // Extensions' `permission()`s are Gate abilities, asked about the
+ // widget.
+ $screen = Screen::standard('atrium.dashboard-widget', Screen::DETAIL)
+ ->record($widget)
+ ->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record ? [$record] : []));
+
/** @var view-string $view */
$view = 'atrium::dashboard.widget-body';
- return response(view($view, ['placement' => $widget, 'definition' => $definition])->render());
+ // `widgetScreen`, not `resolved`: the dashboard page includes the same
+ // view inline for widgets that are not lazy, with its own screen in
+ // scope as `resolved`.
+ return response(view($view, [
+ 'widgetScreen' => $this->screens->resolve($screen, $request),
+ 'placement' => $widget,
+ 'definition' => $definition,
+ ])->render());
}
}
diff --git a/src/Domains/DomainServiceProvider.php b/src/Domains/DomainServiceProvider.php
index c269261..b0592cb 100644
--- a/src/Domains/DomainServiceProvider.php
+++ b/src/Domains/DomainServiceProvider.php
@@ -7,9 +7,9 @@
use Illuminate\Support\ServiceProvider;
use RefactorCircus\Atrium\Domains\Access\AccessServiceProvider;
use RefactorCircus\Atrium\Domains\Dashboard\DashboardServiceProvider;
-use RefactorCircus\Atrium\Domains\History\HistoryServiceProvider;
use RefactorCircus\Atrium\Domains\Navigation\NavigationServiceProvider;
use RefactorCircus\Atrium\Domains\Plugins\PluginsServiceProvider;
+use RefactorCircus\Atrium\Domains\Screens\ScreensServiceProvider;
use RefactorCircus\Atrium\Domains\Search\SearchServiceProvider;
use RefactorCircus\Atrium\Domains\Settings\SettingsServiceProvider;
use RefactorCircus\Atrium\Domains\Themes\ThemesServiceProvider;
@@ -25,9 +25,9 @@ class DomainServiceProvider extends ServiceProvider
private array $providers = [
AccessServiceProvider::class,
DashboardServiceProvider::class,
- HistoryServiceProvider::class,
NavigationServiceProvider::class,
PluginsServiceProvider::class,
+ ScreensServiceProvider::class,
SearchServiceProvider::class,
SettingsServiceProvider::class,
ThemesServiceProvider::class,
diff --git a/src/Domains/History/HistoryServiceProvider.php b/src/Domains/History/HistoryServiceProvider.php
deleted file mode 100644
index c3bf6d1..0000000
--- a/src/Domains/History/HistoryServiceProvider.php
+++ /dev/null
@@ -1,19 +0,0 @@
-loadDashboardRoutesFrom(__DIR__.'/routes.php');
- }
-}
diff --git a/src/Domains/History/Http/Controllers/HistoryController.php b/src/Domains/History/Http/Controllers/HistoryController.php
deleted file mode 100644
index d38395a..0000000
--- a/src/Domains/History/Http/Controllers/HistoryController.php
+++ /dev/null
@@ -1,39 +0,0 @@
-find($package);
-
- // Only while the package audits: Keen installed, its `audit.enabled` on.
- abort_if($resolved === null || ! $resolved->audits(), 404);
-
- $filters = $request->validate(History::rules());
-
- abort_unless($history->allows($resolved, $request->user(), $filters), 403);
-
- /** @var view-string $view */
- $view = 'atrium::history.show';
-
- return view($view, [
- 'package' => $resolved,
- 'filters' => $filters,
- 'page' => $history->page($resolved, $filters),
- ]);
- }
-}
diff --git a/src/Domains/History/routes.php b/src/Domains/History/routes.php
deleted file mode 100644
index 05f5c53..0000000
--- a/src/Domains/History/routes.php
+++ /dev/null
@@ -1,8 +0,0 @@
-name('history.show');
diff --git a/src/Domains/Plugins/Support/Plugin.php b/src/Domains/Plugins/Support/Plugin.php
index dc81167..7caf4ea 100644
--- a/src/Domains/Plugins/Support/Plugin.php
+++ b/src/Domains/Plugins/Support/Plugin.php
@@ -6,13 +6,9 @@
use Illuminate\Http\Request;
use Illuminate\Support\Str;
-use RefactorCircus\Atrium\Domains\Navigation\Data\NavItem;
use RefactorCircus\Atrium\Domains\Plugins\Contracts\Plugin as PluginContract;
use RefactorCircus\Atrium\Domains\Search\Data\SearchSource;
use RefactorCircus\Atrium\Domains\Settings\Data\SettingsPanel;
-use RefactorCircus\Atrium\Support\Icons;
-use RefactorCircus\Keystone\Audit\History;
-use RefactorCircus\Keystone\Packages\PackageRegistry;
use Throwable;
/**
@@ -71,27 +67,6 @@ private static function loads(string $class): bool
}
}
- /**
- * A navigation item for a package's own audit log, at
- * `atrium.history.show`. It shows only while an audit log (refactor-circus/keen) is
- * installed and the user may read the package's history, as the
- * package's history endpoint decides:
- *
- * $this->historyNavItem('roster')->group(__('Roster'))->sort(50),
- */
- protected function historyNavItem(string $package): NavItem
- {
- return NavItem::make(__('atrium::atrium.audit_log'))
- ->icon(Icons::svg('clipboard-document-list'))
- ->route('atrium.history.show', ['package' => $package])
- ->authorize(function (Request $request) use ($package): bool {
- $definition = app(PackageRegistry::class)->find($package);
- $history = app(History::class);
-
- return $definition !== null && $definition->audits() && $history->allows($definition, $request->user(), []);
- });
- }
-
public function navigation(): array
{
return [];
diff --git a/src/Domains/Screens/Concerns/DefinesExtension.php b/src/Domains/Screens/Concerns/DefinesExtension.php
new file mode 100644
index 0000000..781a77f
--- /dev/null
+++ b/src/Domains/Screens/Concerns/DefinesExtension.php
@@ -0,0 +1,169 @@
+)|null */
+ private ?Closure $resolver = null;
+
+ /** @var (Closure(Request, ?Model, Screen): bool)|null */
+ private ?Closure $authorize = null;
+
+ public function __construct(string $key)
+ {
+ if (preg_match(Screen::NAME_PATTERN, $key) !== 1) {
+ throw new InvalidArgumentException("Screen extension key [{$key}] must match ".Screen::NAME_PATTERN.'; use lowercase letters, digits, dots, dashes and underscores, such as vendor.key.');
+ }
+
+ $this->key = $key;
+ $this->label = $key;
+ }
+
+ public static function make(string $key): static
+ {
+ return new static($key);
+ }
+
+ public function label(string $label): static
+ {
+ $this->label = $label;
+
+ return $this;
+ }
+
+ /**
+ * Render with a Blade view, instead of any component.
+ */
+ public function view(string $view): static
+ {
+ $this->view = $view;
+ $this->component = null;
+
+ return $this;
+ }
+
+ /**
+ * Render with a Blade component, instead of any view.
+ */
+ public function component(string $component): static
+ {
+ $this->component = $component;
+ $this->view = null;
+
+ return $this;
+ }
+
+ /**
+ * The data the view or component gets. Runs only when the extension
+ * renders, after the viewer's access is checked.
+ *
+ * @param Closure(?Model, Screen): array
$resolver
+ */
+ public function resolve(Closure $resolver): static
+ {
+ $this->resolver = $resolver;
+
+ return $this;
+ }
+
+ /**
+ * Show only to viewers the screen's `access` closure grants this
+ * permission; a screen without one grants none.
+ */
+ public function permission(string $permission): static
+ {
+ $this->permission = $permission;
+
+ return $this;
+ }
+
+ /**
+ * Show only when the callback answers true. It runs on every screen and
+ * row it may appear on, so keep it cheap; one that throws hides the
+ * extension and is reported.
+ *
+ * @param Closure(Request, ?Model, Screen): bool $callback
+ */
+ public function authorize(Closure $callback): static
+ {
+ $this->authorize = $callback;
+
+ return $this;
+ }
+
+ /**
+ * Show to anyone who may open the screen.
+ */
+ public function public(): static
+ {
+ $this->public = true;
+
+ return $this;
+ }
+
+ /**
+ * Whether the viewer may see the extension: the permission through the
+ * screen's access closure, then the authorize closure. Anything they
+ * throw propagates; ScreenVisibility reports it and counts it a denial.
+ *
+ * @param (Closure(string, Request, ?Model): bool)|null $access
+ */
+ public function allows(Request $request, ?Model $record, Screen $screen, ?Closure $access): bool
+ {
+ if ($this->permission === null && $this->authorize === null) {
+ return $this->public;
+ }
+
+ if ($this->permission !== null && ($access === null || $access($this->permission, $request, $record) !== true)) {
+ return false;
+ }
+
+ return $this->authorize === null || ($this->authorize)($request, $record, $screen) === true;
+ }
+
+ /**
+ * The resolver's data, or none without a resolver. A resolver returning
+ * anything but an array fails with a TypeError.
+ *
+ * @return array
+ */
+ public function resolveData(?Model $record, Screen $screen): array
+ {
+ return $this->resolver === null ? [] : ($this->resolver)($record, $screen);
+ }
+}
diff --git a/src/Domains/Screens/Data/ResolvedScreen.php b/src/Domains/Screens/Data/ResolvedScreen.php
new file mode 100644
index 0000000..67eee74
--- /dev/null
+++ b/src/Domains/Screens/Data/ResolvedScreen.php
@@ -0,0 +1,141 @@
+
+ */
+ private SplObjectStorage $slotOf;
+
+ /**
+ * @internal Built by ScreenExtensions::resolve().
+ *
+ * @param list $tabs The built-in tabs, then the visible registered ones.
+ * @param list $registeredTabs Every registered tab on the screen, visible or not.
+ * @param array> $sections Every section by declared slot, visible or not.
+ */
+ public function __construct(
+ public private(set) Screen $screen,
+ public private(set) array $tabs,
+ public private(set) string $openTab,
+ public private(set) ?TabDefinition $openRegisteredTab,
+ array $registeredTabs,
+ private array $sections,
+ private Request $request,
+ private ScreenVisibility $visibility,
+ ) {
+ $this->slotOf = new SplObjectStorage;
+
+ foreach ($registeredTabs as $tab) {
+ $this->slotOf[$tab] = ScreenVisibility::TABS;
+ }
+
+ foreach ($sections as $slot => $definitions) {
+ foreach ($definitions as $section) {
+ // An all-digit slot name came back from the array key as an int.
+ $this->slotOf[$section] = (string) $slot;
+ }
+ }
+ }
+
+ /**
+ * The visible sections of a slot, in order; none for a slot the screen
+ * did not declare.
+ *
+ * @return list
+ *
+ * @throws InvalidArgumentException for a row slot, which needs its row
+ */
+ public function sections(string $slot): array
+ {
+ if (in_array($slot, $this->screen->rowSlots, true)) {
+ throw new InvalidArgumentException("Slot [{$slot}] of screen [{$this->screen->key}] is a row slot; render it per row with rowSections().");
+ }
+
+ return $this->visible($slot, $this->screen->record);
+ }
+
+ /**
+ * The sections of a row slot visible for this row, in order; none for a
+ * slot the screen did not declare.
+ *
+ * @return list
+ *
+ * @throws InvalidArgumentException for a slot that is not a row slot
+ */
+ public function rowSections(string $slot, Model $row): array
+ {
+ if (in_array($slot, $this->screen->slots, true)) {
+ throw new InvalidArgumentException("Slot [{$slot}] of screen [{$this->screen->key}] is not a row slot; render it once with sections().");
+ }
+
+ return $this->visible($slot, $row);
+ }
+
+ /**
+ * The data of one of this screen's registered tabs or sections, resolved
+ * on the first call and remembered for the request. A row section needs
+ * its row. A hidden extension has none, and its resolver never runs.
+ *
+ * @return array
+ *
+ * @throws InvalidArgumentException for a built-in tab, another screen's extension, or a missing or stray row
+ */
+ public function data(TabDefinition|SectionDefinition $extension, ?Model $row = null): array
+ {
+ if (! isset($this->slotOf[$extension])) {
+ throw new InvalidArgumentException("[{$extension->key}] is not a registered extension of screen [{$this->screen->key}] as resolved for this request.");
+ }
+
+ $slot = $this->slotOf[$extension];
+ $inRow = in_array($slot, $this->screen->rowSlots, true);
+
+ if ($inRow && $row === null) {
+ throw new InvalidArgumentException("Section [{$extension->key}] is in the row slot [{$slot}] of screen [{$this->screen->key}]; pass its row.");
+ }
+
+ if (! $inRow && $row !== null) {
+ throw new InvalidArgumentException("[{$extension->key}] on screen [{$this->screen->key}] is not in a row slot; pass no row.");
+ }
+
+ $record = $row ?? $this->screen->record;
+
+ if (! $this->visibility->allows($this->screen, $slot, $extension, $this->request, $record)) {
+ return [];
+ }
+
+ return $this->visibility->data($this->screen, $slot, $extension, $record);
+ }
+
+ /**
+ * @return list
+ */
+ private function visible(string $slot, ?Model $record): array
+ {
+ return array_values(array_filter(
+ $this->sections[$slot] ?? [],
+ fn (SectionDefinition $section): bool => $this->visibility->allows($this->screen, $slot, $section, $this->request, $record),
+ ));
+ }
+}
diff --git a/src/Domains/Screens/Data/Screen.php b/src/Domains/Screens/Data/Screen.php
new file mode 100644
index 0000000..087e352
--- /dev/null
+++ b/src/Domains/Screens/Data/Screen.php
@@ -0,0 +1,266 @@
+
+ */
+ public private(set) array $tabs;
+
+ /**
+ * The built-in tab opened without `?tab=`; the first built-in when it
+ * names none of them.
+ */
+ public private(set) ?string $defaultTab = null;
+
+ /**
+ * Tab keys reserved without a tab, such as built-in tabs this viewer may
+ * not open: a registered tab with one is skipped and reported, as for a
+ * built-in key. They never render and `?tab=` cannot open them.
+ *
+ * @var list
+ */
+ public private(set) array $reserved = [];
+
+ /** @var list */
+ public private(set) array $slots = [];
+
+ /** @var list */
+ public private(set) array $rowSlots = [];
+
+ /** @var (Closure(string, Request, ?Model): bool)|null */
+ private ?Closure $access = null;
+
+ public function __construct(string $key)
+ {
+ if (preg_match(self::KEY_PATTERN, $key) !== 1) {
+ throw new InvalidArgumentException("Screen key [{$key}] must be {package}.{screen} and match ".self::KEY_PATTERN.'.');
+ }
+
+ $this->key = $key;
+ $this->package = strstr($key, '.', true) ?: $key;
+ $this->tabs = [self::overview()];
+ }
+
+ public static function make(string $key): self
+ {
+ return new self($key);
+ }
+
+ /**
+ * A screen with the standard slots: `header.actions`, `before` and
+ * `after`, plus `aside` on a detail screen or the row slot `row.actions`
+ * on a list screen.
+ */
+ public static function standard(string $key, string $kind): self
+ {
+ $screen = self::make($key)->kind($kind)->slots('header.actions', 'before', 'after');
+
+ return $kind === self::DETAIL ? $screen->slots('aside') : $screen->rowSlots('row.actions');
+ }
+
+ public function record(?Model $record): self
+ {
+ $this->record = $record;
+
+ return $this;
+ }
+
+ public function kind(string $kind): self
+ {
+ if (! in_array($kind, [self::DETAIL, self::LIST], true)) {
+ throw new InvalidArgumentException("Screen kind [{$kind}] must be [detail] or [list].");
+ }
+
+ $this->kind = $kind;
+
+ return $this;
+ }
+
+ /**
+ * The host's own tabs, in order, each with a `key` and optionally a
+ * `label` (the key by default) and an Atrium `icon`. Registered tabs
+ * follow them and may not reuse their keys.
+ *
+ * @param array> $builtIn Entries of `key`, `label` and `icon`.
+ */
+ public function tabs(array $builtIn): self
+ {
+ $tabs = [];
+
+ foreach ($builtIn as $entry) {
+ $key = $entry['key'] ?? null;
+
+ if (! is_string($key)) {
+ throw new InvalidArgumentException("Every built-in tab of screen [{$this->key}] needs a string key.");
+ }
+
+ if (isset($tabs[$key])) {
+ throw new InvalidArgumentException("Screen [{$this->key}] declares the built-in tab [{$key}] twice.");
+ }
+
+ $tabs[$key] = TabDefinition::make($key)
+ ->label($entry['label'] ?? $key)
+ ->icon($entry['icon'] ?? TabDefinition::DEFAULT_ICON);
+ }
+
+ $this->tabs = $tabs === [] ? [self::overview()] : array_values($tabs);
+
+ return $this;
+ }
+
+ public function defaultTab(string $key): self
+ {
+ $this->defaultTab = $key;
+
+ return $this;
+ }
+
+ /**
+ * Reserve tab keys without rendering them, after any already reserved:
+ * the keys of built-in tabs this viewer may not open. A registered tab
+ * with one is skipped and reported, as for a built-in key, so it shows
+ * to no one, and `?tab=` naming one opens the default tab.
+ */
+ public function reserve(string ...$keys): static
+ {
+ foreach ($keys as $key) {
+ if (preg_match(self::NAME_PATTERN, $key) !== 1) {
+ throw new InvalidArgumentException("Reserved tab key [{$key}] on screen [{$this->key}] must match ".self::NAME_PATTERN.'.');
+ }
+
+ if (! in_array($key, $this->reserved, true)) {
+ $this->reserved[] = $key;
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Slots sections may be added to, after any already declared.
+ */
+ public function slots(string ...$slots): self
+ {
+ $this->slots = $this->declare($this->slots, $this->rowSlots, $slots);
+
+ return $this;
+ }
+
+ /**
+ * Slots rendered once per row, whose sections receive the row as their
+ * record, after any already declared.
+ */
+ public function rowSlots(string ...$slots): self
+ {
+ $this->rowSlots = $this->declare($this->rowSlots, $this->slots, $slots);
+
+ return $this;
+ }
+
+ /**
+ * Decide the extensions' `permission()`s. Without it, every extension
+ * with a permission is hidden.
+ *
+ * @param Closure(string $permission, Request $request, ?Model $record): bool $access
+ */
+ public function access(Closure $access): self
+ {
+ $this->access = $access;
+
+ return $this;
+ }
+
+ /**
+ * Whether the host grants the permission to the request's viewer on the
+ * record (the screen's, or a row's).
+ */
+ public function permits(string $permission, Request $request, ?Model $record): bool
+ {
+ return $this->access !== null && ($this->access)($permission, $request, $record) === true;
+ }
+
+ /**
+ * @param list $declared
+ * @param list $other The other kind of slot, which may not share a name.
+ * @param array $slots
+ * @return list
+ */
+ private function declare(array $declared, array $other, array $slots): array
+ {
+ foreach ($slots as $slot) {
+ if (preg_match(self::NAME_PATTERN, $slot) !== 1) {
+ throw new InvalidArgumentException("Slot name [{$slot}] on screen [{$this->key}] must match ".self::NAME_PATTERN.'.');
+ }
+
+ if (in_array($slot, $other, true)) {
+ throw new InvalidArgumentException("Slot [{$slot}] on screen [{$this->key}] cannot be both a slot and a row slot.");
+ }
+
+ if (! in_array($slot, $declared, true)) {
+ $declared[] = $slot;
+ }
+ }
+
+ return $declared;
+ }
+
+ private static function overview(): TabDefinition
+ {
+ return TabDefinition::make(self::OVERVIEW)->label('Overview');
+ }
+}
diff --git a/src/Domains/Screens/Data/SectionDefinition.php b/src/Domains/Screens/Data/SectionDefinition.php
new file mode 100644
index 0000000..741dcac
--- /dev/null
+++ b/src/Domains/Screens/Data/SectionDefinition.php
@@ -0,0 +1,18 @@
+section()` from a provider's `boot()`. In a row slot it
+ * renders once per row, and its closures receive the row as the record.
+ */
+final class SectionDefinition
+{
+ use DefinesExtension;
+}
diff --git a/src/Domains/Screens/Data/TabDefinition.php b/src/Domains/Screens/Data/TabDefinition.php
new file mode 100644
index 0000000..9c4b95a
--- /dev/null
+++ b/src/Domains/Screens/Data/TabDefinition.php
@@ -0,0 +1,34 @@
+tab()` from a provider's `boot()`.
+ * Opened through `?tab={key}`, its panel replaces the host's page content.
+ *
+ * A screen's built-in tabs are TabDefinitions too, with neither a view nor a
+ * component: the host renders them.
+ */
+final class TabDefinition
+{
+ use DefinesExtension;
+
+ public const string DEFAULT_ICON = 'squares-2x2';
+
+ /**
+ * An Atrium icon name.
+ */
+ public private(set) string $icon = self::DEFAULT_ICON;
+
+ public function icon(string $icon): self
+ {
+ $this->icon = $icon;
+
+ return $this;
+ }
+}
diff --git a/src/Domains/Screens/ScreensServiceProvider.php b/src/Domains/Screens/ScreensServiceProvider.php
new file mode 100644
index 0000000..fe1a239
--- /dev/null
+++ b/src/Domains/Screens/ScreensServiceProvider.php
@@ -0,0 +1,22 @@
+app->singleton(ScreenExtensions::class);
+ $this->app->scoped(ScreenVisibility::class);
+ }
+}
diff --git a/src/Domains/Screens/Services/ScreenExtensions.php b/src/Domains/Screens/Services/ScreenExtensions.php
new file mode 100644
index 0000000..c547297
--- /dev/null
+++ b/src/Domains/Screens/Services/ScreenExtensions.php
@@ -0,0 +1,349 @@
+>,
+ * sections: array>>,
+ * sequence: int,
+ * }
+ */
+final class ScreenExtensions
+{
+ /**
+ * Every screen of one package.
+ */
+ private const string PACKAGE_TARGET = '/^[a-z0-9-]+\.\*$/D';
+
+ /**
+ * Tabs by target, then key, each with its registration number.
+ *
+ * @var array>
+ */
+ private array $tabs = [];
+
+ /**
+ * Sections by target, slot, then key, each with its registration number.
+ *
+ * @var array>>
+ */
+ private array $sections = [];
+
+ /**
+ * The last registration number, which orders wildcard registrations
+ * across their targets.
+ */
+ private int $sequence = 0;
+
+ /**
+ * Add a tab to the target's screens.
+ *
+ * @throws InvalidArgumentException for a bad target, a tab with neither a view nor a component, or (in local and testing) a key the target already has
+ */
+ public function tab(string $target, TabDefinition $tab): self
+ {
+ $this->assertTarget($target);
+
+ $tab = clone $tab;
+ $this->assertRenders('Tab', $tab, $target);
+
+ if (isset($this->tabs[$target][$tab->key])) {
+ $this->duplicate(new InvalidArgumentException("Tab [{$tab->key}] is already registered for [{$target}]."));
+
+ return $this;
+ }
+
+ $this->tabs[$target][$tab->key] = [++$this->sequence, $tab];
+
+ return $this;
+ }
+
+ /**
+ * Add a section to a slot of the target's screens. It renders only on
+ * screens declaring that slot.
+ *
+ * @throws InvalidArgumentException for a bad target or slot, a section with neither a view nor a component, or (in local and testing) a key the target's slot already has
+ */
+ public function section(string $target, string $slot, SectionDefinition $section): self
+ {
+ $this->assertTarget($target);
+
+ if (preg_match(Screen::NAME_PATTERN, $slot) !== 1) {
+ throw new InvalidArgumentException("Slot name [{$slot}] must match ".Screen::NAME_PATTERN.'.');
+ }
+
+ $section = clone $section;
+ $this->assertRenders('Section', $section, $target);
+
+ if (isset($this->sections[$target][$slot][$section->key])) {
+ $this->duplicate(new InvalidArgumentException("Section [{$section->key}] is already registered for [{$target}] in slot [{$slot}]."));
+
+ return $this;
+ }
+
+ $this->sections[$target][$slot][$section->key] = [++$this->sequence, $section];
+
+ return $this;
+ }
+
+ /**
+ * Copies of the tabs registered for exactly this target, in registration
+ * order.
+ *
+ * @return list
+ */
+ public function tabs(string $target): array
+ {
+ return array_values(array_map(fn (array $entry): TabDefinition => clone $entry[1], $this->tabs[$target] ?? []));
+ }
+
+ /**
+ * Copies of the sections registered for exactly this target and slot, in
+ * registration order.
+ *
+ * @return list
+ */
+ public function sections(string $target, string $slot): array
+ {
+ return array_values(array_map(fn (array $entry): SectionDefinition => clone $entry[1], $this->sections[$target][$slot] ?? []));
+ }
+
+ /**
+ * The current registrations, to hand back to `restore()`.
+ *
+ * @return Registrations
+ */
+ public function snapshot(): array
+ {
+ return [
+ 'tabs' => self::copy($this->tabs),
+ 'sections' => array_map(self::copy(...), $this->sections),
+ 'sequence' => $this->sequence,
+ ];
+ }
+
+ /**
+ * Replace every registration with a snapshot's.
+ *
+ * @param Registrations $snapshot
+ */
+ public function restore(array $snapshot): void
+ {
+ $this->tabs = self::copy($snapshot['tabs']);
+ $this->sections = array_map(self::copy(...), $snapshot['sections']);
+ $this->sequence = $snapshot['sequence'];
+ }
+
+ /**
+ * Forget every registration. For the registry's own tests; apps' tests
+ * use `Testing\ResetsScreenExtensions`.
+ */
+ public function flush(): void
+ {
+ $this->tabs = [];
+ $this->sections = [];
+ $this->sequence = 0;
+ }
+
+ /**
+ * The screen with its extensions for this request: the built-in tabs,
+ * then the visible exact registrations, then the visible wildcard ones,
+ * each in registration order; the tab `?tab=` opens; and each declared
+ * slot's sections. Call it only once the host has authorized the
+ * request.
+ *
+ * Of two registrations with one key, the more specific target wins
+ * (exact, then `{package}.*`, then `*`), and a registered tab may not
+ * use a built-in or `reserve()`d key; what is skipped is reported once
+ * per request. A reserved key is never a tab, so `?tab=` naming one
+ * opens the default.
+ *
+ * @throws AccessDeniedHttpException for `?tab=` naming a registered tab the viewer may not see
+ */
+ public function resolve(Screen $screen, Request $request): ResolvedScreen
+ {
+ $visibility = Container::getInstance()->make(ScreenVisibility::class);
+ $targets = [$screen->key, $screen->package.'.*', '*'];
+ $builtIn = array_map(fn (TabDefinition $tab): string => $tab->key, $screen->tabs);
+
+ $registered = $this->merge($screen, $visibility, 'tab', array_map(fn (string $target): array => $this->tabs[$target] ?? [], array_combine($targets, $targets)), [...$builtIn, ...$screen->reserved]);
+
+ $visible = array_values(array_filter(
+ $registered,
+ fn (TabDefinition $tab): bool => $visibility->allows($screen, ScreenVisibility::TABS, $tab, $request, $screen->record),
+ ));
+
+ $sections = [];
+
+ foreach ([...$screen->slots, ...$screen->rowSlots] as $slot) {
+ $sections[$slot] = $this->merge($screen, $visibility, "section in slot [{$slot}]", array_map(fn (string $target): array => $this->sections[$target][$slot] ?? [], array_combine($targets, $targets)), []);
+ }
+
+ [$openTab, $openRegisteredTab] = $this->openTab($screen, $request, $builtIn, $registered, $visible);
+
+ return new ResolvedScreen(
+ $screen,
+ [...$screen->tabs, ...$visible],
+ $openTab,
+ $openRegisteredTab,
+ $registered,
+ $sections,
+ $request,
+ $visibility,
+ );
+ }
+
+ /**
+ * The tab to open: a built-in `?tab=` names, a visible registered one it
+ * names, or else the default.
+ *
+ * @param list $builtIn
+ * @param list $registered
+ * @param list $visible
+ * @return array{string, ?TabDefinition}
+ */
+ private function openTab(Screen $screen, Request $request, array $builtIn, array $registered, array $visible): array
+ {
+ // A string only: ?tab[]=x and the like count as no tab.
+ $requested = $request->query('tab');
+ $requested = is_string($requested) ? $requested : null;
+
+ if ($requested !== null && in_array($requested, $builtIn, true)) {
+ return [$requested, null];
+ }
+
+ foreach ($registered as $tab) {
+ if ($tab->key === $requested) {
+ // Answering 403 rather than opening the default reveals that
+ // the key exists, which is accepted.
+ return in_array($tab, $visible, true) ? [$tab->key, $tab] : throw new AccessDeniedHttpException;
+ }
+ }
+
+ $default = $screen->defaultTab;
+
+ return [$default !== null && in_array($default, $builtIn, true) ? $default : $screen->tabs[0]->key, null];
+ }
+
+ /**
+ * One screen's registrations from its targets, most specific first: the
+ * first of each key wins and the rest are skipped and reported, as are
+ * reserved keys. Exact registrations come first, then wildcard ones,
+ * each in registration order. Each is a copy, so nothing the host does
+ * to it reaches the registry.
+ *
+ * @template T of TabDefinition|SectionDefinition
+ *
+ * @param array> $byTarget
+ * @param list $reserved
+ * @return list
+ */
+ private function merge(Screen $screen, ScreenVisibility $visibility, string $kind, array $byTarget, array $reserved): array
+ {
+ /** @var array $winners */
+ $winners = [];
+
+ foreach ($byTarget as $target => $entries) {
+ foreach ($entries as [$order, $extension]) {
+ $key = $extension->key;
+
+ if (in_array($key, $reserved, true)) {
+ $visibility->report("reserved\0{$screen->key}\0{$kind}\0{$key}\0{$target}", new InvalidArgumentException(
+ "Screen [{$screen->key}] skips the {$kind} [{$key}] registered for [{$target}]: it is a built-in or reserved tab key. Prefix registered keys with a vendor, such as vendor.key.",
+ ));
+
+ continue;
+ }
+
+ if (isset($winners[$key])) {
+ $visibility->report("duplicate\0{$screen->key}\0{$kind}\0{$key}\0{$target}", new InvalidArgumentException(
+ "Screen [{$screen->key}] skips the {$kind} [{$key}] registered for [{$target}]: [{$winners[$key][3]}] registers the same key.",
+ ));
+
+ continue;
+ }
+
+ $winners[$key] = [$target === $screen->key ? 0 : 1, $order, clone $extension, $target];
+ }
+ }
+
+ usort($winners, fn (array $a, array $b): int => [$a[0], $a[1]] <=> [$b[0], $b[1]]);
+
+ return array_map(fn (array $winner): TabDefinition|SectionDefinition => $winner[2], $winners);
+ }
+
+ private function assertTarget(string $target): void
+ {
+ if ($target === '*' || preg_match(Screen::KEY_PATTERN, $target) === 1 || preg_match(self::PACKAGE_TARGET, $target) === 1) {
+ return;
+ }
+
+ throw new InvalidArgumentException("Screen extension target [{$target}] must be an exact screen key ({package}.{screen}), {package}.* or *.");
+ }
+
+ private function assertRenders(string $kind, TabDefinition|SectionDefinition $extension, string $target): void
+ {
+ if ($extension->view === null && $extension->component === null) {
+ throw new InvalidArgumentException("{$kind} [{$extension->key}] registered for [{$target}] needs a view() or a component().");
+ }
+ }
+
+ /**
+ * A duplicate throws where a developer will see it (local, testing and
+ * outside an application); elsewhere it is reported, and the first
+ * registration is kept, rather than taking down every route and command
+ * from boot().
+ */
+ private function duplicate(InvalidArgumentException $exception): void
+ {
+ $app = Container::getInstance();
+
+ if (! $app instanceof Application || $app->environment('local', 'testing') === true) {
+ throw $exception;
+ }
+
+ report($exception);
+ }
+
+ /**
+ * Copies of a target's registrations, so a snapshot and the registry
+ * never share a definition.
+ *
+ * @template T of TabDefinition|SectionDefinition
+ *
+ * @param array> $registrations
+ * @return array>
+ */
+ private static function copy(array $registrations): array
+ {
+ return array_map(
+ fn (array $entries): array => array_map(fn (array $entry): array => [$entry[0], clone $entry[1]], $entries),
+ $registrations,
+ );
+ }
+}
diff --git a/src/Domains/Screens/Services/ScreenVisibility.php b/src/Domains/Screens/Services/ScreenVisibility.php
new file mode 100644
index 0000000..39fce54
--- /dev/null
+++ b/src/Domains/Screens/Services/ScreenVisibility.php
@@ -0,0 +1,148 @@
+>
+ */
+ private array $memo = [];
+
+ /**
+ * Remembered values for records without a key, by what was asked.
+ *
+ * @var SplObjectStorage>
+ */
+ private SplObjectStorage $unsaved;
+
+ /**
+ * Failures already reported this request.
+ *
+ * @var array
+ */
+ private array $reported = [];
+
+ public function __construct()
+ {
+ $this->unsaved = new SplObjectStorage;
+ }
+
+ /**
+ * Whether the viewer may see the extension on this record, asked once
+ * per request. A closure that throws counts as a denial and is reported
+ * once per request per screen and key.
+ */
+ public function allows(Screen $screen, string $slot, TabDefinition|SectionDefinition $extension, Request $request, ?Model $record): bool
+ {
+ return $this->remember('allows', $screen, $slot, $extension, $record, function () use ($screen, $extension, $request, $record): bool {
+ try {
+ return $extension->allows($request, $record, $screen, $screen->permits(...));
+ } catch (Throwable $exception) {
+ $this->report("authorize\0{$screen->key}\0{$extension->key}", $exception);
+
+ return false;
+ }
+ }) === true;
+ }
+
+ /**
+ * The extension's data for this record, resolved once per request. A
+ * resolver that throws is not remembered.
+ *
+ * @return array
+ */
+ public function data(Screen $screen, string $slot, TabDefinition|SectionDefinition $extension, ?Model $record): array
+ {
+ /** @var array */
+ return $this->remember('data', $screen, $slot, $extension, $record, fn (): array => $extension->resolveData($record, $screen));
+ }
+
+ /**
+ * Report the exception unless one under the same key already was this
+ * request.
+ */
+ public function report(string $key, Throwable $exception): void
+ {
+ if (isset($this->reported[$key])) {
+ return;
+ }
+
+ $this->reported[$key] = true;
+
+ report($exception);
+ }
+
+ /**
+ * @param Closure(): mixed $compute
+ */
+ private function remember(string $store, Screen $screen, string $slot, TabDefinition|SectionDefinition $extension, ?Model $record, Closure $compute): mixed
+ {
+ $key = "{$store}\0{$screen->key}\0{$slot}\0{$extension->key}";
+ $identity = $this->identity($record);
+
+ if (is_string($identity)) {
+ if (! array_key_exists($key, $this->memo[$identity] ?? [])) {
+ $this->memo[$identity][$key] = $compute();
+ }
+
+ return $this->memo[$identity][$key];
+ }
+
+ $values = isset($this->unsaved[$identity]) ? $this->unsaved[$identity] : [];
+
+ if (! array_key_exists($key, $values)) {
+ $values[$key] = $compute();
+ $this->unsaved[$identity] = $values;
+ }
+
+ return $values[$key];
+ }
+
+ /**
+ * The record's morph class and key, `-` for no record, or the model
+ * itself while it has no key.
+ */
+ private function identity(?Model $record): string|Model
+ {
+ if ($record === null) {
+ return '-';
+ }
+
+ $key = $record->getKey();
+
+ return is_int($key) || is_string($key) ? $record->getMorphClass()."\0".$key : $record;
+ }
+}
diff --git a/src/Domains/Settings/Data/SettingsPanelRow.php b/src/Domains/Settings/Data/SettingsPanelRow.php
new file mode 100644
index 0000000..f9a7f80
--- /dev/null
+++ b/src/Domains/Settings/Data/SettingsPanelRow.php
@@ -0,0 +1,43 @@
+panel`. It has no table and is never
+ * saved, so it lives here rather than in `Models/` and needs no policy or
+ * lifecycle events.
+ */
+final class SettingsPanelRow extends Model
+{
+ /** @var string */
+ protected $primaryKey = 'key';
+
+ /** @var string */
+ protected $keyType = 'string';
+
+ /** @var bool */
+ public $incrementing = false;
+
+ /** @var bool */
+ public $timestamps = false;
+
+ public private(set) SettingsPanel $panel;
+
+ public static function for(SettingsPanel $panel): self
+ {
+ $row = new self;
+ $row->forceFill(['key' => $panel->key]);
+ $row->panel = $panel;
+
+ return $row;
+ }
+}
diff --git a/src/Domains/Settings/Http/Controllers/SettingsController.php b/src/Domains/Settings/Http/Controllers/SettingsController.php
index 7c44fdf..c5dfe97 100644
--- a/src/Domains/Settings/Http/Controllers/SettingsController.php
+++ b/src/Domains/Settings/Http/Controllers/SettingsController.php
@@ -5,35 +5,62 @@
namespace RefactorCircus\Atrium\Domains\Settings\Http\Controllers;
use Illuminate\Contracts\View\View;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions;
+use RefactorCircus\Atrium\Domains\Settings\Data\SettingsPanelRow;
use RefactorCircus\Atrium\Domains\Settings\Services\SettingsRegistry;
class SettingsController
{
- public function __construct(protected SettingsRegistry $settings) {}
+ public function __construct(
+ protected SettingsRegistry $settings,
+ protected ScreenExtensions $screens,
+ ) {}
public function index(Request $request): View
{
+ $panels = $this->settings->panels($request);
+
/** @var view-string $view */
$view = 'atrium::settings.index';
return view($view, [
- 'panels' => $this->settings->panels($request),
+ 'resolved' => $this->screens->resolve($this->access(Screen::standard('atrium.settings', Screen::LIST)), $request),
+ 'panels' => $panels,
+ // Each panel as the model its `row.actions` sections receive.
+ 'rows' => array_map(SettingsPanelRow::for(...), $panels),
]);
}
public function show(Request $request, string $panel): View
{
- $resolved = $this->settings->find($request, $panel);
+ $found = $this->settings->find($request, $panel);
+
+ abort_if($found === null, 404);
- abort_if($resolved === null, 404);
+ // A panel is not a model, so the screen has no record.
+ $screen = $this->access(Screen::standard('atrium.settings-panel', Screen::DETAIL));
/** @var view-string $view */
$view = 'atrium::settings.show';
return view($view, [
+ 'resolved' => $this->screens->resolve($screen, $request),
'panels' => $this->settings->panels($request),
- 'panel' => $resolved,
+ 'panel' => $found,
]);
}
+
+ /**
+ * Extensions' `permission()`s are Gate abilities, asked about the record
+ * when there is one.
+ */
+ protected function access(Screen $screen): Screen
+ {
+ return $screen->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record ? [$record] : []));
+ }
}
diff --git a/src/Facades/Atrium.php b/src/Facades/Atrium.php
index d890c65..35c7b31 100644
--- a/src/Facades/Atrium.php
+++ b/src/Facades/Atrium.php
@@ -7,6 +7,32 @@
use Illuminate\Support\Facades\Facade;
/**
+ * @method static \RefactorCircus\Atrium\Domains\Screens\Services\ScreenExtensions screens()
+ * @method static \RefactorCircus\Atrium\Atrium theme(\RefactorCircus\Atrium\Domains\Themes\Data\Theme $theme)
+ * @method static array themes()
+ * @method static \RefactorCircus\Atrium\Atrium stylesheet(string $href)
+ * @method static \RefactorCircus\Atrium\Atrium css(string $css, ?string $key = null)
+ * @method static \RefactorCircus\Atrium\Atrium plugin(\RefactorCircus\Atrium\Domains\Plugins\Contracts\Plugin|class-string $plugin)
+ * @method static array plugins()
+ * @method static \RefactorCircus\Atrium\Domains\Plugins\Services\PluginRegistry pluginRegistry()
+ * @method static \RefactorCircus\Atrium\Atrium nav(\RefactorCircus\Atrium\Domains\Navigation\Data\NavItem $item)
+ * @method static \RefactorCircus\Atrium\Atrium navigationGroup(\RefactorCircus\Atrium\Domains\Navigation\Data\NavGroup $group)
+ * @method static \RefactorCircus\Atrium\Atrium resolvePermissionsUsing(?\Closure $callback)
+ * @method static \RefactorCircus\Atrium\Atrium resolveFeaturesUsing(?\Closure $callback)
+ * @method static bool featureEnabled(string $feature, ?\Illuminate\Http\Request $request = null)
+ * @method static array navigation(?\Illuminate\Http\Request $request = null)
+ * @method static array> navigationGroups(?\Illuminate\Http\Request $request = null)
+ * @method static array navigationSections(?\Illuminate\Http\Request $request = null)
+ * @method static \RefactorCircus\Atrium\Atrium widget(\RefactorCircus\Atrium\Domains\Widgets\Data\WidgetDefinition $definition)
+ * @method static array widgets(?\Illuminate\Http\Request $request = null)
+ * @method static \RefactorCircus\Atrium\Domains\Widgets\Services\WidgetRegistry widgetRegistry()
+ * @method static \RefactorCircus\Atrium\Atrium settingsPanel(\RefactorCircus\Atrium\Domains\Settings\Data\SettingsPanel $panel)
+ * @method static array settings(?\Illuminate\Http\Request $request = null)
+ * @method static \RefactorCircus\Atrium\Atrium searchSource(\RefactorCircus\Atrium\Domains\Search\Data\SearchSource $source)
+ * @method static array search(string $query, ?\Illuminate\Http\Request $request = null)
+ * @method static string path()
+ * @method static string url(string $path = '')
+ *
* @see \RefactorCircus\Atrium\Atrium
*/
class Atrium extends Facade
diff --git a/src/Testing/ResetsScreenExtensions.php b/src/Testing/ResetsScreenExtensions.php
new file mode 100644
index 0000000..8c80c38
--- /dev/null
+++ b/src/Testing/ResetsScreenExtensions.php
@@ -0,0 +1,43 @@
+in('Feature');
+ *
+ * @phpstan-import-type Registrations from ScreenExtensions
+ */
+trait ResetsScreenExtensions
+{
+ /** @var Registrations|null */
+ private ?array $screenExtensionsSnapshot = null;
+
+ /**
+ * Called by the test case once the application has booted.
+ */
+ protected function setUpResetsScreenExtensions(): void
+ {
+ $this->screenExtensionsSnapshot = app(ScreenExtensions::class)->snapshot();
+ }
+
+ /**
+ * Called by the test case before the application is destroyed.
+ */
+ protected function tearDownResetsScreenExtensions(): void
+ {
+ if ($this->screenExtensionsSnapshot !== null) {
+ app(ScreenExtensions::class)->restore($this->screenExtensionsSnapshot);
+ }
+ }
+}
diff --git a/tests/ArchTest.php b/tests/ArchTest.php
index 769d833..cb587c7 100644
--- a/tests/ArchTest.php
+++ b/tests/ArchTest.php
@@ -2,7 +2,14 @@
declare(strict_types=1);
use Illuminate\Database\Eloquent\Model;
+use RefactorCircus\Atrium\Domains\DomainServiceProvider;
+use RefactorCircus\Atrium\Domains\Screens\Data\ResolvedScreen;
+use RefactorCircus\Atrium\Domains\Screens\Data\Screen;
+use RefactorCircus\Atrium\Domains\Screens\Data\SectionDefinition;
+use RefactorCircus\Atrium\Domains\Screens\Data\TabDefinition;
+use RefactorCircus\Atrium\Domains\Screens\ScreensServiceProvider;
use RefactorCircus\Atrium\Support\Tables;
+use RefactorCircus\Atrium\Testing\ResetsScreenExtensions;
use RefactorCircus\Keystone\Testing\Arch;
const ATRIUM_DOMAINS = __DIR__.'/../src/Domains';
@@ -80,6 +87,53 @@
))
->toBeEmpty();
+arch('the screens classes are final')
+ ->expect('RefactorCircus\Atrium\Domains\Screens')
+ ->classes()
+ ->toBeFinal();
+
+arch('the screens code declares strict types')
+ ->expect(['RefactorCircus\Atrium\Domains\Screens', ResetsScreenExtensions::class])
+ ->toUseStrictTypes();
+
+arch('the screens value objects expose their state as public private(set)')
+ ->expect(fn (): array => array_values(array_map(
+ fn (ReflectionProperty $property): string => $property->class.'::$'.$property->name,
+ array_filter(
+ array_merge(...array_map(
+ fn (string $class): array => new ReflectionClass($class)->getProperties(ReflectionProperty::IS_PUBLIC),
+ [Screen::class, TabDefinition::class, SectionDefinition::class, ResolvedScreen::class],
+ )),
+ // Closures stay private, so only meaningful state is readable.
+ fn (ReflectionProperty $property): bool => ! $property->isPrivateSet()
+ || ($property->getType() instanceof ReflectionNamedType && $property->getType()->getName() === Closure::class),
+ ),
+ )))
+ ->toBeEmpty();
+
+arch('the screens domain provider is registered by the domain provider')
+ ->expect(fn (): array => new ReflectionProperty(DomainServiceProvider::class, 'providers')->getDefaultValue())
+ ->toContain(ScreensServiceProvider::class);
+
+arch('atrium requires only keystone among the suite packages')
+ ->expect(fn (): array => array_values(array_filter(
+ array_keys(json_decode((string) file_get_contents(__DIR__.'/../composer.json'), true)['require']),
+ fn (string $package): bool => str_starts_with($package, 'refactor-circus/'),
+ )))
+ ->toBe(['refactor-circus/keystone']);
+
+arch('the history screen and audit components left for Keen')
+ ->expect(fn (): array => array_values(array_filter(
+ [
+ ATRIUM_DOMAINS.'/History',
+ __DIR__.'/../resources/views/history',
+ __DIR__.'/../resources/views/components/audit-trail.blade.php',
+ __DIR__.'/../resources/views/components/audit',
+ ],
+ file_exists(...),
+ )))
+ ->toBeEmpty();
+
arch('tables are named through Tables, never as literals')
->expect(fn (): array => Arch::literalTableNames(
[...array_values(array_filter(
diff --git a/tests/Browser/ScreenExtensionsTest.php b/tests/Browser/ScreenExtensionsTest.php
new file mode 100644
index 0000000..1fb457a
--- /dev/null
+++ b/tests/Browser/ScreenExtensionsTest.php
@@ -0,0 +1,204 @@
+detectEnvironment(fn (): string => 'local');
+
+ ScreenHostController::register();
+ Atrium::plugin(ScreenHostPlugin::class);
+
+ config(['screen-host.tabs' => [
+ ['key' => 'details', 'label' => 'Details', 'icon' => 'document-text'],
+ ['key' => 'activity', 'label' => 'Activity', 'icon' => 'clock'],
+ ]]);
+
+ $icons = ['chart-bar', 'users', 'credit-card', 'cog-6-tooth', 'bell', 'truck'];
+
+ foreach (range(1, 12) as $number) {
+ Atrium::screens()->tab('test.list', TabDefinition::make('acme.tab-'.$number)
+ ->label($number === 12 ? 'A registered tab whose label runs on far longer than any tab bar is wide' : 'Registered tab '.$number)
+ ->icon($icons[$number % count($icons)])
+ ->view('screens.marker')
+ ->resolve(fn (): array => ['marker' => 'Panel '.$number])
+ ->public());
+ }
+
+ Atrium::screens()
+ ->section('test.list', 'before', SectionDefinition::make('acme.summary')
+ ->view('screens.marker')
+ ->resolve(fn (): array => ['marker' => 'Normal section'])
+ ->public())
+ ->section('test.list', 'row.actions', SectionDefinition::make('acme.row-action')
+ ->view('screens.marker')
+ ->resolve(fn (): array => ['marker' => 'Row section'])
+ ->public());
+
+ // Pest saves a screenshot only into a directory that exists.
+ if (! is_dir(__DIR__.'/Screenshots/screen-extensions')) {
+ mkdir(__DIR__.'/Screenshots/screen-extensions', 0755, true);
+ }
+});
+
+dataset('screen extension looks', function (): array {
+ $cases = [];
+
+ foreach (['atrium', 'harbor', 'sunset', 'forest', 'midnight', 'ledger'] as $theme) {
+ foreach (['sidebar', 'top'] as $layout) {
+ foreach (['light', 'dark'] as $mode) {
+ $cases["{$theme} {$layout} {$mode}"] = [$theme, $layout, $mode];
+ }
+ }
+ }
+
+ return $cases;
+});
+
+/**
+ * The tab bar's computed layout: criterion 17's no-wrap, scrolling row.
+ */
+function screenExtensionsTabBar(): string
+{
+ return <<<'JS'
+ () => {
+ const nav = document.querySelector('[data-testid="screen-tabs"]');
+ const links = [...nav.querySelectorAll('a[data-testid^="tab-"]')];
+ const style = getComputedStyle(nav);
+
+ return {
+ keys: links.map((link) => link.dataset.testid),
+ overflowX: style.overflowX,
+ flexWrap: style.flexWrap,
+ whiteSpace: [...new Set(links.map((link) => getComputedStyle(link).whiteSpace))],
+ tops: [...new Set(links.map((link) => Math.round(link.getBoundingClientRect().top)))].length,
+ };
+ }
+ JS;
+}
+
+/**
+ * How many tabs overlap a `top-tabs` row that is on screen, and how many
+ * such rows there are.
+ */
+function screenExtensionsTopTabsOverlap(): string
+{
+ return <<<'JS'
+ () => {
+ const rows = [...document.querySelectorAll('[data-testid="top-tabs"]')]
+ .map((row) => row.getBoundingClientRect())
+ .filter((box) => box.width > 0 && box.height > 0);
+
+ const overlapping = [...document.querySelectorAll('[data-testid="screen-tabs"] a[data-testid^="tab-"]')]
+ .map((link) => link.getBoundingClientRect())
+ .filter((tab) => rows.some((row) => tab.left < row.right && tab.right > row.left && tab.top < row.bottom && tab.bottom > row.top));
+
+ return { rows: rows.length, overlapping: overlapping.length };
+ }
+ JS;
+}
+
+/**
+ * Whether the tab lies inside the tab bar's visible box and the viewport.
+ */
+function screenExtensionsTabInView(string $key): string
+{
+ return << {
+ const tab = document.querySelector('[data-testid="tab-{$key}"]').getBoundingClientRect();
+ const nav = document.querySelector('[data-testid="screen-tabs"]').getBoundingClientRect();
+
+ return tab.width > 0 && tab.left >= nav.left - 1 && tab.right <= nav.right + 1 && tab.right <= window.innerWidth;
+ }
+ JS;
+}
+
+function screenExtensionsBackground(string $key): string
+{
+ return "getComputedStyle(document.querySelector('[data-testid=\"tab-{$key}\"]')).backgroundColor";
+}
+
+it('renders tabs and sections in every theme, layout and mode', function (string $theme, string $layout, string $mode): void {
+ // The theme is the default, so a fresh browser shows it; its layout is
+ // set here so every theme is seen in both.
+ config(['atrium.themes.default' => $theme]);
+ app(ThemeRegistry::class)->find($theme)?->layout($layout);
+
+ $visit = visit('/test/list');
+ $page = $mode === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
+
+ $page->assertScript('document.documentElement.dataset.atriumTheme', $theme)
+ ->assertScript('document.documentElement.dataset.atriumLayout', $layout)
+ ->assertScript('document.documentElement.classList.contains("dark")', $mode === 'dark');
+
+ if ($layout === 'top') {
+ $page->assertMissing('@sidebar')
+ ->assertVisible('[data-testid="top-tabs"][data-section="group-screen-host"]');
+ } else {
+ $page->assertVisible('@sidebar')
+ ->assertMissing('@top-nav');
+ }
+
+ // Both sections render on the built-in tab: the normal slot once, the
+ // row slot in each of the three rows.
+ $page->assertSeeIn('[data-testid="section-acme.summary"]', 'Normal section')
+ ->assertCount('[data-testid="section-acme.row-action"]', 3)
+ ->assertSeeIn('[data-testid="row-2"] [data-testid="section-acme.row-action"]', 'Row section')
+ ->assertAttribute('[data-testid="tab-details"]', 'aria-current', 'page')
+ ->screenshot(true, 'screen-extensions/'.$theme.'-'.$layout.'-'.$mode);
+
+ $assertTabBar = function () use ($page, $layout): void {
+ $bar = $page->script(screenExtensionsTabBar());
+
+ expect($bar['keys'])->toBe([
+ 'tab-details',
+ 'tab-activity',
+ ...array_map(fn (int $number): string => 'tab-acme.tab-'.$number, range(1, 12)),
+ ])
+ ->and($bar['overflowX'])->toBeIn(['auto', 'scroll'])
+ ->and($bar['flexWrap'])->toBe('nowrap')
+ ->and($bar['whiteSpace'])->toBe(['nowrap'])
+ ->and($bar['tops'])->toBe(1);
+
+ $overlap = $page->script(screenExtensionsTopTabsOverlap());
+
+ expect($overlap['rows'])->toBe($layout === 'top' ? 1 : 0)
+ ->and($overlap['overlapping'])->toBe(0);
+ };
+
+ $assertTabBar();
+
+ // The last tab scrolls into view, opens on a click, and is the current one.
+ $page->script("() => document.querySelector('[data-testid=\"tab-acme.tab-12\"]').scrollIntoView({ block: 'nearest', inline: 'end' })");
+
+ expect($page->script(screenExtensionsTabInView('acme.tab-12')))->toBeTrue();
+
+ $page->click('[data-testid="tab-acme.tab-12"]')
+ ->assertAttribute('[data-testid="tab-acme.tab-12"]', 'aria-current', 'page')
+ ->assertAttributeMissing('[data-testid="tab-details"]', 'aria-current')
+ ->assertSeeIn('[data-testid="tab-panel-acme.tab-12"]', 'Panel 12')
+ // With the pointer elsewhere, the open tab is filled and an idle one is not.
+ ->hover('[data-testid="tab-panel-acme.tab-12"]')
+ ->assertScript(screenExtensionsBackground('acme.tab-12').' !== "rgba(0, 0, 0, 0)"', true)
+ ->assertScript(screenExtensionsBackground('acme.tab-12').' !== '.screenExtensionsBackground('details'), true)
+ ->assertScript(screenExtensionsBackground('acme.tab-12').' !== '.screenExtensionsBackground('acme.tab-1'), true);
+
+ expect($page->script(screenExtensionsTabInView('acme.tab-12')))->toBeTrue();
+
+ $assertTabBar();
+})->with('screen extension looks');
diff --git a/tests/Feature/AuditComponentsTest.php b/tests/Feature/AuditComponentsTest.php
deleted file mode 100644
index 0978d6c..0000000
--- a/tests/Feature/AuditComponentsTest.php
+++ /dev/null
@@ -1,117 +0,0 @@
-subMinutes(5),
- actorId: '1',
- actorLabel: 'Ada Lovelace',
- subjectType: 'product',
- subjectId: '42',
- subjectLabel: 'Widget',
- changes: $changes,
- );
-}
-
-it('renders nothing for the history while no audit log is installed', function (): void {
- expect(trim(Blade::render(' ')))->toBe('');
-});
-
-it('renders a package history from the installed audit log', function (): void {
- $trail = new class implements AuditTrail
- {
- public ?AuditFilter $filter = null;
-
- public function available(): bool
- {
- return true;
- }
-
- public function entries(AuditFilter $filter): AuditPage
- {
- $this->filter = $filter;
-
- return new AuditPage([auditEntry()]);
- }
- };
-
- app()->instance(AuditTrail::class, $trail);
-
- $user = new User;
- $user->id = 3;
-
- $html = Blade::render(' ', ['subject' => $user]);
-
- expect($html)->toContain('data-testid="audit-trail"')
- ->toContain('product.updated')
- ->toContain('Ada Lovelace')
- ->toContain('atrium')
- // One record's history leaves out the record column.
- ->not->toContain('Widget')
- ->and($trail->filter?->source)->toBe('showroom')
- ->and($trail->filter?->subjectId)->toBe('3')
- ->and($trail->filter?->limit)->toBe(5)
- ->and($trail->filter?->action)->toBe('product.')
- ->and($trail->filter?->scopeId)->toBe('3');
-});
-
-it('marks entries the application recorded itself', function (): void {
- $html = Blade::render(' ', ['entries' => [auditEntry('app')]]);
-
- expect($html)->toContain('Widget')->toMatch('/>\s*App\s*');
-});
-
-it('shows an empty state without entries', function (): void {
- expect(Blade::render(' '))->toContain('Nothing has been recorded yet.');
-});
-
-it('lists field changes with their old and new values', function (): void {
- $html = Blade::render(' ', ['changes' => ['name' => ['Old', 'New'], 'tags' => [null, ['a']]]]);
-
- expect($html)->toContain('name')
- ->toContain(''Old'')
- ->toContain(''New'')
- ->toContain('NULL')
- ->toContain('["a"]');
-});
-
-it('says when no fields changed', function (): void {
- expect(Blade::render(' '))->toContain('No fields changed.');
-});
-
-it('hides a package history from those its history endpoint would refuse', function (): void {
- app()->instance(AuditTrail::class, new class implements AuditTrail
- {
- public function available(): bool
- {
- return true;
- }
-
- public function entries(AuditFilter $filter): AuditPage
- {
- return new AuditPage([auditEntry()]);
- }
- });
-
- app(PackageRegistry::class)->register(
- Package::make('showroom', 'Showroom')->authorizeHistory(fn (): bool => false),
- );
-
- expect(trim(Blade::render(' ')))->toBe('');
-});
diff --git a/tests/Feature/DocsTest.php b/tests/Feature/DocsTest.php
new file mode 100644
index 0000000..14c1962
--- /dev/null
+++ b/tests/Feature/DocsTest.php
@@ -0,0 +1,101 @@
+ dirname(__DIR__, 2).'/README.md',
+ 'Boost skill' => dirname(__DIR__, 2).'/resources/boost/skills/atrium-development/SKILL.md',
+]);
+
+it('documents screen extensions', function (string $path): void {
+ $section = screenExtensionsSection($path);
+
+ expect($section)->not->toBe('')
+ ->and($section)->toContain('boot()')
+ ->and($section)->toContain('403')
+ ->and($section)->toContain('vendor.key')
+ ->and($section)->toContain('Keystone')
+ ->and($section)->toContain('config');
+})->with('screen extension docs');
+
+it('documents every part of the registry', function (string $path): void {
+ $section = screenExtensionsSection($path);
+
+ expect($section)
+ // Registration examples: a tab, a section, a row section, a wildcard,
+ // and the host's declaration.
+ ->toContain('->tab(')
+ ->toContain('->section(')
+ ->toContain("'row.actions'")
+ ->toContain("->section('*'")
+ ->toContain('Screen::standard(')
+ // Closures receive the screen last; wildcard closures return early.
+ ->toContain('Screen $screen')
+ ->toContain('$screen->key')
+ // What renders around an open registered tab, and the theme contract.
+ ->toContain('header.actions')
+ ->toContain('token')
+ // Duplicates per environment and across targets.
+ ->toContain('production')
+ ->toContain('{package}.*')
+ // The suite rule and the config-defaults pattern.
+ ->toContain('suggest');
+})->with('screen extension docs');
+
+it('mentions no history screen or audit component', function (string $path): void {
+ expect((string) file_get_contents($path))
+ ->not->toContain('atrium.history')
+ ->not->toContain('x-atrium::audit')
+ ->not->toContain('audit-trail')
+ ->not->toContain('historyNavItem')
+ ->not->toContain('history/{package}');
+})->with([
+ 'README' => dirname(__DIR__, 2).'/README.md',
+ 'Boost skill' => dirname(__DIR__, 2).'/resources/boost/skills/atrium-development/SKILL.md',
+ 'CLAUDE.md' => dirname(__DIR__, 2).'/CLAUDE.md',
+ 'domains standard' => dirname(__DIR__, 2).'/docs/agent/standards/atrium/domains.md',
+]);
+
+it('lists the Screens domain and drops History', function (string $path): void {
+ expect((string) file_get_contents($path))
+ ->toContain('`Screens`')
+ ->not->toContain('`History`');
+})->with([
+ 'CLAUDE.md' => dirname(__DIR__, 2).'/CLAUDE.md',
+ 'domains standard' => dirname(__DIR__, 2).'/docs/agent/standards/atrium/domains.md',
+]);
+
+it('has an upgrade note for the history removal pointing to Keen', function (): void {
+ $changelog = (string) file_get_contents(dirname(__DIR__, 2).'/CHANGELOG.md');
+
+ expect($changelog)
+ ->toContain('atrium.history.show')
+ ->toContain('HistoryController')
+ ->toContain('HistoryServiceProvider')
+ ->toContain('Plugin::historyNavItem()')
+ ->toContain('x-atrium::audit-trail')
+ ->toContain('x-atrium::audit.entries')
+ ->toContain('refactor-circus/keen')
+ ->toContain('ScreenExtensions');
+});
diff --git a/tests/Feature/DomainLayoutTest.php b/tests/Feature/DomainLayoutTest.php
index fc7b639..37dad8c 100644
--- a/tests/Feature/DomainLayoutTest.php
+++ b/tests/Feature/DomainLayoutTest.php
@@ -8,7 +8,6 @@
use RefactorCircus\Atrium\Domains\Dashboard\Models\DashboardModel;
use RefactorCircus\Atrium\Domains\Dashboard\Models\DashboardWidgetModel;
use RefactorCircus\Atrium\Domains\DomainServiceProvider;
-use RefactorCircus\Atrium\Domains\History\HistoryServiceProvider;
use RefactorCircus\Atrium\Domains\Navigation\NavigationServiceProvider;
use RefactorCircus\Atrium\Domains\Plugins\PluginsServiceProvider;
use RefactorCircus\Atrium\Domains\Search\SearchServiceProvider;
@@ -22,7 +21,6 @@
DomainServiceProvider::class,
AccessServiceProvider::class,
DashboardServiceProvider::class,
- HistoryServiceProvider::class,
NavigationServiceProvider::class,
PluginsServiceProvider::class,
SearchServiceProvider::class,
diff --git a/tests/Feature/HistoryPageTest.php b/tests/Feature/HistoryPageTest.php
deleted file mode 100644
index 29953a6..0000000
--- a/tests/Feature/HistoryPageTest.php
+++ /dev/null
@@ -1,133 +0,0 @@
-detectEnvironment(fn (): string => 'local');
-
- app(PackageRegistry::class)->register(Package::make('billing', 'Billing')->label('Billing'));
-});
-
-/**
- * An installed audit log holding one entry per page, remembering what it was asked.
- */
-function billingTrail(?string $next = null): object
-{
- $trail = new class($next) implements AuditTrail
- {
- public ?AuditFilter $filter = null;
-
- public function __construct(private ?string $next) {}
-
- public function available(): bool
- {
- return true;
- }
-
- public function entries(AuditFilter $filter): AuditPage
- {
- $this->filter = $filter;
-
- return new AuditPage([new AuditEntry(1, 'billing', 'invoice.paid', 'atrium', CarbonImmutable::now(), subjectLabel: 'INV-1')], $this->next);
- }
- };
-
- app()->instance(AuditTrail::class, $trail);
-
- return $trail;
-}
-
-it('shows a package its own audit log', function (): void {
- $trail = billingTrail();
-
- $this->get('/atrium/history/billing?action=invoice.&subject_type=invoice&subject_id=1')
- ->assertOk()
- ->assertSee('Billing audit log')
- ->assertSee('invoice.paid')
- ->assertSee('INV-1');
-
- expect($trail->filter?->source)->toBe('billing')
- ->and($trail->filter?->action)->toBe('invoice.')
- ->and($trail->filter?->subjectId)->toBe('1');
-});
-
-it('pages through older entries', function (): void {
- billingTrail(next: 'abc');
-
- $this->get('/atrium/history/billing')->assertOk()->assertSee('cursor=abc', false);
- $this->get('/atrium/history/billing?cursor=abc')->assertOk()->assertSee('Newest');
-});
-
-it('answers 404 without an audit log or for an unknown package', function (): void {
- $this->get('/atrium/history/billing')->assertNotFound();
-
- billingTrail();
-
- $this->get('/atrium/history/nope')->assertNotFound();
-});
-
-it('refuses those the package history endpoint would refuse', function (): void {
- billingTrail();
- app(PackageRegistry::class)->get('billing')->authorizeHistory(fn (): bool => false);
-
- $this->get('/atrium/history/billing')->assertForbidden();
-});
-
-it('gives plugins an audit log link that shows only when it would open', function (): void {
- $plugin = new class extends Plugin
- {
- public function key(): string
- {
- return 'billing';
- }
-
- public function navigation(): array
- {
- return [$this->historyNavItem('billing')->group('Billing')];
- }
- };
-
- app(PluginRegistry::class)->register($plugin);
-
- $this->get('/atrium')->assertOk()->assertDontSee('/atrium/history/billing', false);
-
- billingTrail();
-
- $this->get('/atrium')->assertOk()->assertSee('/atrium/history/billing', false)->assertSee('Audit log');
-});
-
-it('links a history panel to the package audit log', function (): void {
- billingTrail(next: 'abc');
-
- $user = new User;
- $user->id = 7;
-
- expect(Blade::render(' ', ['subject' => $user]))
- ->toContain('/atrium/history/billing?subject_type=')
- ->toContain('subject_id=7');
-});
-
-it('offers nothing for a package that turns its auditing off', function (): void {
- billingTrail();
- config()->set('billing.audit.enabled', false);
-
- $this->get('/atrium/history/billing')->assertNotFound();
-
- expect(Blade::render(' '))->not->toContain('data-testid="audit-trail"');
-
- config()->set('billing.audit.enabled', true);
-
- expect(Blade::render(' '))->toContain('data-testid="audit-trail"');
-});
diff --git a/tests/Feature/HistoryRemovedTest.php b/tests/Feature/HistoryRemovedTest.php
new file mode 100644
index 0000000..478f208
--- /dev/null
+++ b/tests/Feature/HistoryRemovedTest.php
@@ -0,0 +1,65 @@
+detectEnvironment(fn (): string => 'local');
+
+ // An auditing package with an installed audit log: the page would have opened.
+ app(PackageRegistry::class)->register(Package::make('billing', 'Billing')->label('Billing'));
+ app()->instance(AuditTrail::class, new class implements AuditTrail
+ {
+ public function available(): bool
+ {
+ return true;
+ }
+
+ public function entries(AuditFilter $filter): AuditPage
+ {
+ return new AuditPage([new AuditEntry(1, 'billing', 'invoice.paid', 'atrium', CarbonImmutable::now())]);
+ }
+ });
+
+ $this->get('/atrium/history/billing')->assertNotFound();
+
+ expect(Route::has('atrium.history.show'))->toBeFalse();
+});
+
+it('ships neither the history controller nor the audit components', function (): void {
+ $root = dirname(__DIR__, 2);
+
+ expect(class_exists('RefactorCircus\\Atrium\\Domains\\History\\Http\\Controllers\\HistoryController'))->toBeFalse()
+ ->and(class_exists('RefactorCircus\\Atrium\\Domains\\History\\HistoryServiceProvider'))->toBeFalse()
+ ->and(is_dir($root.'/src/Domains/History'))->toBeFalse()
+ ->and(file_exists($root.'/resources/views/history/show.blade.php'))->toBeFalse()
+ ->and(file_exists($root.'/resources/views/components/audit-trail.blade.php'))->toBeFalse()
+ ->and(is_dir($root.'/resources/views/components/audit'))->toBeFalse();
+});
+
+it('gives plugins no history nav item', function (): void {
+ expect(method_exists(Plugin::class, 'historyNavItem'))->toBeFalse();
+});
+
+it('compiles no audit or history view into the stylesheet', function (): void {
+ $sources = array_filter(
+ file(dirname(__DIR__, 2).'/resources/css/atrium.css', FILE_IGNORE_NEW_LINES) ?: [],
+ fn (string $line): bool => str_starts_with(trim($line), '@source'),
+ );
+
+ expect(array_filter($sources, fn (string $line): bool => str_contains($line, 'audit') || str_contains($line, 'history/')))->toBe([]);
+});
diff --git a/tests/Feature/Screens/AtriumScreensTest.php b/tests/Feature/Screens/AtriumScreensTest.php
new file mode 100644
index 0000000..cbb211c
--- /dev/null
+++ b/tests/Feature/Screens/AtriumScreensTest.php
@@ -0,0 +1,351 @@
+detectEnvironment(fn (): string => 'local');
+
+ app(WidgetRegistry::class)->add(WidgetDefinition::make('quick')->view('alpha-stats'));
+ app(PluginRegistry::class)->register(FullPlugin::class);
+
+ $this->user = User::forceCreate(['name' => 'Ada', 'email' => 'ada@example.com', 'password' => bcrypt('secret')]);
+
+ $this->dashboard = DashboardModel::query()->create([
+ 'name' => 'Mine',
+ 'owner_type' => $this->user->getMorphClass(),
+ 'owner_id' => $this->user->getKey(),
+ ]);
+
+ $this->widget = $this->dashboard->widgets()->create(['widget_key' => 'quick']);
+});
+
+/**
+ * Register a public tab on the screen, and a public section in each of the
+ * given slots, counting each section's resolver calls by slot.
+ *
+ * @param list $slots
+ * @param array $calls
+ */
+function atriumScreensRegister(string $screen, array $slots, array &$calls): void
+{
+ Atrium::screens()->tab($screen, TabDefinition::make('acme.tab')->label('Acme')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'the acme panel']));
+
+ foreach ($slots as $slot) {
+ $calls[$slot] = 0;
+
+ Atrium::screens()->section($screen, $slot, SectionDefinition::make('acme.'.$slot)->view('screens.marker')->public()
+ ->resolve(function () use (&$calls, $slot): array {
+ $calls[$slot]++;
+
+ return ['marker' => 'in '.$slot];
+ }));
+ }
+}
+
+dataset('atrium screens', [
+ 'the dashboard' => [
+ 'atrium.dashboard',
+ fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboard'),
+ 'Alpha stats widget',
+ ['header.actions', 'before', 'aside', 'after'],
+ ['row.actions'],
+ ],
+ 'a named dashboard' => [
+ 'atrium.named-dashboard',
+ fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboard.show', $dashboard->slug),
+ 'Alpha stats widget',
+ ['header.actions', 'before', 'aside', 'after'],
+ ['row.actions'],
+ ],
+ 'a dashboard widget' => [
+ 'atrium.dashboard-widget',
+ fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboards.widgets.show', [$dashboard->id, $widget->id]),
+ 'Alpha stats widget',
+ ['header.actions', 'before', 'aside', 'after'],
+ ['row.actions'],
+ ],
+ // The full plugin's panel is the settings index's one row, so its
+ // `row.actions` section renders, and resolves, once.
+ 'the settings index' => [
+ 'atrium.settings',
+ fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.settings'),
+ 'Full Settings',
+ ['header.actions', 'before', 'row.actions', 'after'],
+ ['aside'],
+ ],
+ 'a settings panel' => [
+ 'atrium.settings-panel',
+ fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.settings.show', 'full'),
+ 'Full plugin settings body',
+ ['header.actions', 'before', 'aside', 'after'],
+ ['row.actions'],
+ ],
+]);
+
+it('renders each registered section in its own slot and none in an undeclared one', function (string $screen, Closure $url, string $content, array $slots, array $undeclared): void {
+ $calls = [];
+ atriumScreensRegister($screen, [...$slots, ...$undeclared], $calls);
+
+ $response = $this->actingAs($this->user)->get($url($this->dashboard, $this->widget))->assertOk();
+
+ foreach ($slots as $slot) {
+ $response->assertSee('data-testid="section-acme.'.$slot.'"', false)->assertSee('in '.$slot.' on '.$screen);
+ }
+
+ // Header actions, then the tab bar, then the page with `before` above
+ // it, its rows' actions in it, `aside` beside it and `after` below it.
+ $response->assertSeeInOrder([
+ 'data-testid="section-acme.header.actions"',
+ 'data-testid="screen-tabs"',
+ 'data-testid="section-acme.before"',
+ $content,
+ ...(in_array('row.actions', $slots, true) ? ['data-testid="section-acme.row.actions"'] : []),
+ ...(in_array('aside', $slots, true) ? ['data-testid="section-acme.aside"'] : []),
+ 'data-testid="section-acme.after"',
+ ], false);
+
+ foreach ($undeclared as $slot) {
+ $response->assertDontSee('data-testid="section-acme.'.$slot.'"', false)->assertDontSee('in '.$slot.' on');
+ }
+
+ expect($calls)->toBe([
+ ...array_fill_keys($slots, 1),
+ ...array_fill_keys($undeclared, 0),
+ ]);
+})->with('atrium screens');
+
+it('shows the registered tab and opens it through ?tab= in place of the page', function (string $screen, Closure $url, string $content, array $slots, array $undeclared): void {
+ $calls = [];
+ atriumScreensRegister($screen, $slots, $calls);
+
+ $page = $url($this->dashboard, $this->widget);
+
+ $this->actingAs($this->user)->get($page)
+ ->assertOk()
+ ->assertSee('data-testid="tab-overview"', false)
+ ->assertSee('data-testid="tab-acme.tab"', false)
+ ->assertDontSee('data-testid="tab-panel-acme.tab"', false);
+
+ // A fresh request, so nothing is remembered from the one above.
+ app()->forgetScopedInstances();
+ $calls = array_map(fn (): int => 0, $calls);
+
+ $open = $this->actingAs($this->user)->get($page.'?tab=acme.tab')
+ ->assertOk()
+ ->assertSee('data-testid="tab-panel-acme.tab"', false)
+ ->assertSee('the acme panel on '.$screen)
+ ->assertSee('data-testid="section-acme.header.actions"', false)
+ ->assertDontSee($content);
+
+ foreach (array_diff($slots, ['header.actions']) as $slot) {
+ $open->assertDontSee('data-testid="section-acme.'.$slot.'"', false)->assertDontSee('in '.$slot.' on');
+ }
+
+ expect($calls)->toBe([...array_fill_keys($slots, 0), 'header.actions' => 1]);
+})->with('atrium screens');
+
+it('renders no tab bar or extra markup while nothing is registered', function (string $screen, Closure $url, string $content): void {
+ $html = (string) $this->actingAs($this->user)->get($url($this->dashboard, $this->widget))
+ ->assertOk()
+ ->assertSee($content)
+ ->getContent();
+
+ expect($html)
+ ->not->toContain('data-testid="screen-tabs"')
+ ->not->toContain('data-testid="tab-')
+ ->not->toContain('data-testid="section-')
+ ->not->toContain('data-testid="screen-aside"');
+})->with('atrium screens');
+
+it('shows a permission() extension only while the Gate allows it', function (bool $allowed, string $screen, Closure $url, string $content): void {
+ Gate::define('acme.see', fn (User $user, mixed ...$arguments): bool => $allowed);
+
+ Atrium::screens()
+ ->tab($screen, TabDefinition::make('acme.gated-tab')->label('Gated')->view('screens.marker')->permission('acme.see'))
+ ->section($screen, 'header.actions', SectionDefinition::make('acme.gated')->view('screens.marker')->permission('acme.see')
+ ->resolve(fn (): array => ['marker' => 'the gated section']));
+
+ $response = $this->actingAs($this->user)->get($url($this->dashboard, $this->widget))
+ ->assertOk()
+ ->assertSee($content);
+
+ if ($allowed) {
+ $response->assertSee('data-testid="section-acme.gated"', false)
+ ->assertSee('the gated section on '.$screen)
+ ->assertSee('data-testid="tab-acme.gated-tab"', false);
+ } else {
+ $response->assertDontSee('data-testid="section-acme.gated"', false)
+ ->assertDontSee('the gated section')
+ ->assertDontSee('data-testid="tab-acme.gated-tab"', false);
+ }
+})->with([
+ 'allowed' => [true],
+ 'denied' => [false],
+])->with('atrium screens');
+
+it('asks the Gate about the screen record, or with no arguments when there is none', function (string $screen, Closure $url, string $expected): void {
+ $received = [];
+
+ Gate::define('acme.see', function (User $user, mixed ...$arguments) use (&$received): bool {
+ $received[] = array_map(fn (mixed $argument): string => get_debug_type($argument), $arguments);
+
+ return true;
+ });
+
+ Atrium::screens()->section($screen, 'header.actions', SectionDefinition::make('acme.gated')->view('screens.marker')->permission('acme.see'));
+
+ $this->actingAs($this->user)->get($url($this->dashboard, $this->widget))->assertOk();
+
+ expect($received)->toBe([$expected === '' ? [] : [$expected]]);
+})->with([
+ 'the dashboard' => ['atrium.dashboard', fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboard'), DashboardModel::class],
+ 'a named dashboard' => ['atrium.named-dashboard', fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboard.show', $dashboard->slug), DashboardModel::class],
+ 'a dashboard widget' => ['atrium.dashboard-widget', fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.dashboards.widgets.show', [$dashboard->id, $widget->id]), DashboardWidgetModel::class],
+ 'the settings index' => ['atrium.settings', fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.settings'), ''],
+ 'a settings panel' => ['atrium.settings-panel', fn (DashboardModel $dashboard, DashboardWidgetModel $widget): string => route('atrium.settings.show', 'full'), ''],
+]);
+
+/**
+ * A row section on the settings index admitting only the `beta` panel's row,
+ * recording what its closures receive.
+ *
+ * @param list $asked
+ * @param list $resolved
+ */
+function atriumScreensSettingsRowSection(array &$asked, array &$resolved): SectionDefinition
+{
+ return SectionDefinition::make('acme.row-action')
+ ->view('screens.marker')
+ ->authorize(function (Request $request, ?Model $record, Screen $screen) use (&$asked): bool {
+ $asked[] = [get_debug_type($record), $record?->getKey(), $record instanceof SettingsPanelRow ? $record->panel->key : null, $screen->key];
+
+ return $record?->getKey() === 'beta';
+ })
+ ->resolve(function (?Model $record, Screen $screen) use (&$resolved): array {
+ $resolved[] = $record?->getKey();
+
+ return ['marker' => 'row action'];
+ });
+}
+
+/**
+ * The settings index's markup for one panel's card, from its link to the next
+ * panel's link (or the end).
+ */
+function atriumScreensSettingsRow(string $html, string $panel, ?string $next): string
+{
+ $start = strrpos($html, 'href="'.route('atrium.settings.show', $panel).'"');
+
+ expect($start)->not->toBeFalse();
+
+ $end = $next === null ? false : strrpos($html, 'href="'.route('atrium.settings.show', $next).'"');
+
+ return substr($html, (int) $start, $end === false ? null : $end - (int) $start);
+}
+
+it('renders row.actions once per settings panel row, with that row as the record', function (): void {
+ app(SettingsRegistry::class)
+ ->add(SettingsPanel::make('alpha')->label('Alpha')->sort(1))
+ ->add(SettingsPanel::make('beta')->label('Beta')->sort(2));
+
+ $asked = [];
+ $resolved = [];
+
+ Atrium::screens()->section('atrium.settings', 'row.actions', atriumScreensSettingsRowSection($asked, $resolved));
+
+ $html = (string) $this->actingAs($this->user)->get(route('atrium.settings'))->assertOk()->getContent();
+
+ // The rows are the panels in order: alpha, beta, then the full plugin's.
+ expect(substr_count($html, 'data-testid="section-acme.row-action"'))->toBe(1)
+ ->and(atriumScreensSettingsRow($html, 'beta', 'full'))->toContain('data-testid="section-acme.row-action"')
+ ->and(atriumScreensSettingsRow($html, 'beta', 'full'))->toContain('row action on atrium.settings')
+ ->and(atriumScreensSettingsRow($html, 'alpha', 'beta'))->not->toContain('row action')
+ ->and(atriumScreensSettingsRow($html, 'full', null))->not->toContain('row action')
+ ->and($asked)->toBe([
+ [SettingsPanelRow::class, 'alpha', 'alpha', 'atrium.settings'],
+ [SettingsPanelRow::class, 'beta', 'beta', 'atrium.settings'],
+ [SettingsPanelRow::class, 'full', 'full', 'atrium.settings'],
+ ])
+ ->and($resolved)->toBe(['beta']);
+});
+
+it('remembers each settings panel row\'s answer and data when the rows render again in the request', function (): void {
+ $asked = [];
+ $resolved = [];
+
+ Atrium::screens()->section('atrium.settings', 'row.actions', atriumScreensSettingsRowSection($asked, $resolved));
+
+ $screen = Atrium::screens()->resolve(Screen::standard('atrium.settings', Screen::LIST), request());
+ $template = ' ';
+
+ // Each pass builds new rows, so only the panel key ties them together.
+ foreach ([1, 2] as $pass) {
+ foreach (['alpha', 'beta', 'full'] as $key) {
+ $html = Blade::render($template, ['screen' => $screen, 'row' => SettingsPanelRow::for(SettingsPanel::make($key))]);
+
+ expect(str_contains($html, 'row action'))->toBe($key === 'beta');
+ }
+ }
+
+ expect(array_column($asked, 1))->toBe(['alpha', 'beta', 'full'])
+ ->and($resolved)->toBe(['beta']);
+});
+
+it('keys an unsaved settings panel row by its panel key and carries the panel', function (): void {
+ $panel = SettingsPanel::make('billing')->label('Billing');
+ $row = SettingsPanelRow::for($panel);
+
+ expect($row->getKey())->toBe('billing')
+ ->and($row->panel)->toBe($panel)
+ ->and($row->exists)->toBeFalse();
+});
+
+it('serves a widget body unchanged while nothing is registered', function (): void {
+ $html = (string) $this->actingAs($this->user)
+ ->get(route('atrium.dashboards.widgets.show', [$this->dashboard->id, $this->widget->id]))
+ ->assertOk()
+ ->getContent();
+
+ expect(trim($html))->toBe(trim(view('alpha-stats')->render()));
+});
+
+it('keeps the dashboard screen out of an inline widget body', function (): void {
+ $calls = [];
+ atriumScreensRegister('atrium.dashboard-widget', ['header.actions', 'before', 'aside', 'after'], $calls);
+
+ // The widget is placed on the dashboard, which includes its body inline;
+ // only the widget's own route is the widget screen.
+ $this->actingAs($this->user)->get(route('atrium.dashboard'))
+ ->assertOk()
+ ->assertSee('Alpha stats widget')
+ ->assertDontSee('data-testid="section-acme.', false);
+
+ expect(array_sum($calls))->toBe(0);
+});
diff --git a/tests/Feature/Screens/EvaluationOrderTest.php b/tests/Feature/Screens/EvaluationOrderTest.php
new file mode 100644
index 0000000..63a97fc
--- /dev/null
+++ b/tests/Feature/Screens/EvaluationOrderTest.php
@@ -0,0 +1,121 @@
+ $calls
+ * @return Closure(): array
+ */
+function evaluationResolver(array &$calls, string $name): Closure
+{
+ $calls[$name] = 0;
+
+ return function () use (&$calls, $name): array {
+ $calls[$name]++;
+
+ return ['marker' => $name.' data'];
+ };
+}
+
+it('runs no closure of any extension for a viewer the host refuses', function (): void {
+ Gate::define('viewScreenHost', fn (?Authenticatable $user = null): bool => false);
+
+ $asked = 0;
+ $resolved = 0;
+
+ $authorize = function () use (&$asked): bool {
+ $asked++;
+
+ return true;
+ };
+
+ $resolve = function () use (&$resolved): array {
+ $resolved++;
+
+ return [];
+ };
+
+ Atrium::screens()
+ ->tab('test.host', TabDefinition::make('acme.tab')->view('screens.marker')->authorize($authorize)->resolve($resolve))
+ ->section('test.host', 'before', SectionDefinition::make('acme.section')->view('screens.marker')->authorize($authorize)->resolve($resolve));
+
+ $this->get(route('test.host'))->assertForbidden();
+ $this->get(route('test.host', ['tab' => 'acme.tab']))->assertForbidden();
+
+ expect($asked)->toBe(0)
+ ->and($resolved)->toBe(0);
+});
+
+it('runs resolvers only for the open registered tab and the sections that render', function (): void {
+ config(['screen-host.slots' => ['unrendered']]);
+
+ $calls = [];
+
+ Atrium::screens()
+ ->tab('test.host', TabDefinition::make('acme.open')->view('screens.marker')->public()->resolve(evaluationResolver($calls, 'open tab')))
+ ->tab('test.host', TabDefinition::make('acme.unopened')->view('screens.marker')->public()->resolve(evaluationResolver($calls, 'unopened tab')))
+ ->tab('test.host', TabDefinition::make('acme.hidden')->view('screens.marker')->resolve(evaluationResolver($calls, 'hidden tab')))
+ ->section('test.host', 'header.actions', SectionDefinition::make('acme.shown')->view('screens.marker')->public()->resolve(evaluationResolver($calls, 'shown section')))
+ ->section('test.host', 'header.actions', SectionDefinition::make('acme.hidden')->view('screens.marker')->authorize(fn (): bool => false)->resolve(evaluationResolver($calls, 'hidden section')))
+ ->section('test.host', 'unrendered', SectionDefinition::make('acme.unrendered')->view('screens.marker')->public()->resolve(evaluationResolver($calls, 'unrendered section')));
+
+ $this->get(route('test.host', ['tab' => 'acme.open']))
+ ->assertOk()
+ ->assertSee('open tab data on test.host')
+ ->assertSee('shown section data on test.host')
+ ->assertDontSee('unrendered section data');
+
+ expect($calls)->toBe([
+ 'open tab' => 1,
+ 'unopened tab' => 0,
+ 'hidden tab' => 0,
+ 'shown section' => 1,
+ 'hidden section' => 0,
+ 'unrendered section' => 0,
+ ]);
+});
+
+it('spreads a view\'s data first, so the host\'s screen, record and tab win', function (): void {
+ $data = fn (): array => ['screen' => 'from resolver', 'record' => 'from resolver', 'tab' => 'from resolver', 'extra' => 'kept'];
+
+ Atrium::screens()
+ ->tab('test.host', TabDefinition::make('acme.tab')->view('screens.spread')->public()->resolve($data))
+ ->section('test.host', 'before', SectionDefinition::make('acme.section')->view('screens.spread')->public()->resolve($data));
+
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertSee('screen=test.host;record=Host record;tab=overview;extra=kept');
+
+ $this->get(route('test.host', ['tab' => 'acme.tab']))
+ ->assertOk()
+ ->assertSee('screen=test.host;record=Host record;tab=acme.tab;extra=kept');
+});
+
+it('gives a component its resolver data as one data prop', function (): void {
+ $data = fn (): array => ['marker' => 'probed', 'total' => 3];
+
+ Atrium::screens()
+ ->tab('test.host', TabDefinition::make('acme.tab')->component('screen-probe')->public()->resolve($data))
+ ->section('test.host', 'before', SectionDefinition::make('acme.section')->component('screen-probe')->public()->resolve($data));
+
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertSee('component data: marker,total = probed,3; data only');
+
+ $this->get(route('test.host', ['tab' => 'acme.tab']))
+ ->assertOk()
+ ->assertSee('component data: marker,total = probed,3; data only');
+});
diff --git a/tests/Feature/Screens/FailureIsolationTest.php b/tests/Feature/Screens/FailureIsolationTest.php
new file mode 100644
index 0000000..a0f15b7
--- /dev/null
+++ b/tests/Feature/Screens/FailureIsolationTest.php
@@ -0,0 +1,80 @@
+section('test.host', 'before', SectionDefinition::make('acme.broken')->view('screens.throws')->public())
+ ->section('test.host', 'before', SectionDefinition::make('acme.fine')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'still here']));
+
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertDontSee('leaked markup')
+ ->assertDontSee('section-acme.broken', false)
+ ->assertSee('still here on test.host');
+
+ Exceptions::assertReportedCount(1);
+ // Blade wraps what a view throws, naming the view.
+ Exceptions::assertReported(fn (ViewException $exception): bool => str_contains($exception->getMessage(), 'The section view failed.')
+ && $exception->getPrevious() instanceof RuntimeException);
+});
+
+it('isolates a resolver that throws, an HTTP exception included', function (): void {
+ Atrium::screens()
+ ->section('test.host', 'after', SectionDefinition::make('acme.aborts')->view('screens.marker')->public()
+ ->resolve(fn (): array => abort(404)))
+ ->section('test.host', 'after', SectionDefinition::make('acme.fails')->view('screens.marker')->public()
+ ->resolve(fn (): array => throw new LogicException('The resolver failed.')))
+ ->section('test.host', 'after', SectionDefinition::make('acme.fine')->view('screens.marker')->public());
+
+ // The HTTP exception goes to report() too, which Laravel's handler
+ // leaves unlogged, as it does any HTTP exception.
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertDontSee('section-acme.aborts', false)
+ ->assertDontSee('section-acme.fails', false)
+ ->assertSee('data-testid="section-acme.fine"', false);
+});
+
+it('reports a row section failing in every row once', function (): void {
+ Exceptions::fake();
+
+ $calls = 0;
+
+ Atrium::screens()->section('test.list', 'row.actions', SectionDefinition::make('acme.row-broken')->view('screens.marker')->public()
+ ->resolve(function () use (&$calls): array {
+ $calls++;
+
+ throw new RuntimeException('The row resolver failed.');
+ }));
+
+ $this->get(route('test.list'))
+ ->assertOk()
+ ->assertSee('Row 3')
+ ->assertDontSee('section-acme.row-broken', false);
+
+ expect($calls)->toBe(3);
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'The row resolver failed.');
+});
+
+it('lets a throwing open tab panel fail the request', function (): void {
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.broken')->view('screens.throws')->public());
+
+ $this->get(route('test.host', ['tab' => 'acme.broken']))->assertStatus(500);
+});
diff --git a/tests/Feature/Screens/OpenRegisteredTabTest.php b/tests/Feature/Screens/OpenRegisteredTabTest.php
new file mode 100644
index 0000000..a198ec0
--- /dev/null
+++ b/tests/Feature/Screens/OpenRegisteredTabTest.php
@@ -0,0 +1,68 @@
+ $slots
+ * @param array $calls
+ */
+function openTabRegister(string $screen, array $slots, array &$calls): void
+{
+ Atrium::screens()->tab($screen, TabDefinition::make('acme.tab')->label('Acme')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'the acme panel']));
+
+ foreach ($slots as $slot) {
+ $calls[$slot] = 0;
+
+ Atrium::screens()->section($screen, $slot, SectionDefinition::make('acme.'.$slot)->view('screens.marker')->public()
+ ->resolve(function () use (&$calls, $slot): array {
+ $calls[$slot]++;
+
+ return ['marker' => 'in '.$slot];
+ }));
+ }
+}
+
+it('renders every slot on a built-in tab and only header.actions around an open registered tab', function (string $route, string $screen, array $slots): void {
+ $calls = [];
+ openTabRegister($screen, $slots, $calls);
+
+ $builtIn = $this->get(route($route))->assertOk()->assertSee('data-testid="host-content"', false);
+
+ foreach ($slots as $slot) {
+ $builtIn->assertSee('data-testid="section-acme.'.$slot.'"', false)->assertSee('in '.$slot.' on '.$screen);
+ }
+
+ $builtIn->assertDontSee('data-testid="tab-panel-acme.tab"', false);
+
+ // A fresh request, so nothing is remembered from the one above.
+ app()->forgetScopedInstances();
+ $calls = array_map(fn (): int => 0, $calls);
+
+ $open = $this->get(route($route, ['tab' => 'acme.tab']))
+ ->assertOk()
+ ->assertSee('data-testid="tab-panel-acme.tab"', false)
+ ->assertSee('the acme panel on '.$screen)
+ ->assertSee('data-testid="section-acme.header.actions"', false)
+ ->assertDontSee('data-testid="host-content"', false);
+
+ foreach (array_diff($slots, ['header.actions']) as $slot) {
+ $open->assertDontSee('data-testid="section-acme.'.$slot.'"', false)->assertDontSee('in '.$slot.' on');
+ }
+
+ expect($calls)->toBe([...array_map(fn (): int => 0, $calls), 'header.actions' => 1]);
+})->with([
+ 'a detail screen' => ['test.host', 'test.host', ['header.actions', 'before', 'after', 'aside']],
+ 'a list screen' => ['test.list', 'test.list', ['header.actions', 'before', 'after', 'row.actions']],
+]);
diff --git a/tests/Feature/Screens/ResetsScreenExtensionsTest.php b/tests/Feature/Screens/ResetsScreenExtensionsTest.php
new file mode 100644
index 0000000..6a5986c
--- /dev/null
+++ b/tests/Feature/Screens/ResetsScreenExtensionsTest.php
@@ -0,0 +1,84 @@
+assertArrayHasKey(ResetsScreenExtensions::class, class_uses_recursive(TestCase::class));
+ }
+
+ public function test_a_tab_registered_on_boot_is_present_and_one_registered_in_a_test_is_added(): void
+ {
+ $this->assertSame(['acme.boot'], $this->tabKeys());
+
+ Atrium::screens()->tab('test.screen', TabDefinition::make('acme.inline')->view('acme::inline'));
+
+ $this->assertSame(['acme.boot', 'acme.inline'], $this->tabKeys());
+ }
+
+ #[Depends('test_a_tab_registered_on_boot_is_present_and_one_registered_in_a_test_is_added')]
+ public function test_the_next_test_keeps_the_boot_tab_and_loses_the_test_tab(): void
+ {
+ $this->assertSame(['acme.boot'], $this->tabKeys());
+ }
+
+ public function test_the_snapshot_taken_after_boot_is_restored_when_the_test_ends(): void
+ {
+ Atrium::screens()
+ ->tab('test.screen', TabDefinition::make('acme.inline')->view('acme::inline'))
+ ->section('*', 'before', SectionDefinition::make('acme.inline')->view('acme::inline'));
+
+ // What the trait runs as the application is torn down.
+ $this->tearDownResetsScreenExtensions();
+
+ $this->assertSame(['acme.boot'], $this->tabKeys());
+ $this->assertSame([], Atrium::screens()->sections('*', 'before'));
+ }
+
+ public function test_restoring_its_own_snapshot_changes_nothing(): void
+ {
+ $screens = Atrium::screens();
+ $snapshot = $screens->snapshot();
+
+ $screens->restore($screens->snapshot());
+
+ $this->assertEquals($snapshot, $screens->snapshot());
+ $this->assertSame(['acme.boot'], $this->tabKeys());
+ }
+
+ /**
+ * @return list
+ */
+ private function tabKeys(): array
+ {
+ return array_map(fn (TabDefinition $tab): string => $tab->key, Atrium::screens()->tabs('test.screen'));
+ }
+}
+
+/**
+ * A package registering a tab from its provider's boot(), as consumers do.
+ */
+final class RegistersScreenTabOnBoot extends ServiceProvider
+{
+ public function boot(): void
+ {
+ Atrium::screens()->tab('test.screen', TabDefinition::make('acme.boot')->view('acme::boot'));
+ }
+}
diff --git a/tests/Feature/Screens/ResolveScreenTest.php b/tests/Feature/Screens/ResolveScreenTest.php
new file mode 100644
index 0000000..f0b0825
--- /dev/null
+++ b/tests/Feature/Screens/ResolveScreenTest.php
@@ -0,0 +1,453 @@
+view('acme::'.$key)->label($label === '' ? $key : $label)->public();
+}
+
+function resolveSection(string $key, string $label = ''): SectionDefinition
+{
+ return SectionDefinition::make($key)->view('acme::'.$key)->label($label === '' ? $key : $label)->public();
+}
+
+/**
+ * @param list $definitions
+ * @return list
+ */
+function resolveKeys(array $definitions): array
+{
+ return array_map(fn (TabDefinition|SectionDefinition $definition): string => $definition->key, $definitions);
+}
+
+function resolveScreen(Screen $screen, string $uri = '/'): ResolvedScreen
+{
+ return Atrium::screens()->resolve($screen, Request::create($uri));
+}
+
+/**
+ * A route that resolves the screen the closure builds and answers with what
+ * it opened, as a host controller would.
+ *
+ * @param Closure(): Screen $screen
+ */
+function resolveRoute(Closure $screen): void
+{
+ Route::get('screen-test', function (Request $request) use ($screen) {
+ $resolved = Atrium::screens()->resolve($screen(), $request);
+
+ return response()->json([
+ 'open' => $resolved->openTab,
+ 'registered' => $resolved->openRegisteredTab?->key,
+ 'tabs' => resolveKeys($resolved->tabs),
+ ]);
+ });
+}
+
+describe('the registry', function (): void {
+ it('is a singleton reachable through Atrium::screens()', function (): void {
+ $screens = app(ScreenExtensions::class);
+
+ expect(app(ScreenExtensions::class))->toBe($screens)
+ ->and(Atrium::screens())->toBe($screens)
+ ->and(app(AtriumClass::class)->screens())->toBe($screens);
+ });
+
+ it('is registered by the Screens domain provider, with request-scoped answers', function (): void {
+ $visibility = app(ScreenVisibility::class);
+
+ expect(app()->getProvider(ScreensServiceProvider::class))->toBeInstanceOf(ScreensServiceProvider::class)
+ ->and(app(ScreenVisibility::class))->toBe($visibility);
+
+ app()->forgetScopedInstances();
+
+ expect(app(ScreenVisibility::class))->not->toBe($visibility);
+ });
+});
+
+describe('tabs', function (): void {
+ it('lists built-ins as given, then exact registrations, then wildcards, each in registration order', function (): void {
+ Atrium::screens()
+ ->tab('*', resolveTab('acme.w1'))
+ ->tab('test.screen', resolveTab('acme.e1'))
+ ->tab('test.*', resolveTab('acme.w2'))
+ ->tab('test.screen', resolveTab('acme.e2'))
+ ->tab('*', resolveTab('acme.w3'))
+ ->tab('other.screen', resolveTab('acme.elsewhere'))
+ ->tab('other.*', resolveTab('acme.elsewhere-package'));
+
+ $screen = Screen::make('test.screen')->tabs([
+ ['key' => 'members', 'label' => 'Members'],
+ ['key' => 'teams', 'label' => 'Teams'],
+ ]);
+
+ expect(resolveKeys(resolveScreen($screen)->tabs))
+ ->toBe(['members', 'teams', 'acme.e1', 'acme.e2', 'acme.w1', 'acme.w2', 'acme.w3']);
+ });
+
+ it('skips and reports once a registered tab using a built-in key', function (string $target, string $key): void {
+ Exceptions::fake();
+
+ Atrium::screens()->tab($target, resolveTab($key, 'Registered'));
+
+ $screen = fn (): Screen => Screen::make('test.screen')->tabs([['key' => 'members', 'label' => 'Members']]);
+ $overview = fn (): Screen => Screen::make('test.screen');
+ $built = $key === 'overview' ? $overview : $screen;
+
+ $first = resolveScreen($built());
+ resolveScreen($built());
+
+ expect(array_map(fn (TabDefinition $tab): string => $tab->label, $first->tabs))->not->toContain('Registered');
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), "[{$key}]")
+ && str_contains($exception->getMessage(), '[test.screen]'));
+ })->with([
+ 'exact, overview' => ['test.screen', 'overview'],
+ 'exact, a host tab' => ['test.screen', 'members'],
+ 'every screen, overview' => ['*', 'overview'],
+ 'every screen, a host tab' => ['*', 'members'],
+ ]);
+
+ it('skips and reports once a registered tab using a reserved key, and never shows it', function (string $target): void {
+ Exceptions::fake();
+
+ Atrium::screens()->tab($target, resolveTab('x', 'Registered'));
+
+ $screen = fn (): Screen => Screen::make('test.screen')->tabs([['key' => 'members']])->reserve('x');
+
+ $first = resolveScreen($screen());
+ resolveScreen($screen(), '/?tab=x');
+
+ expect(resolveKeys($first->tabs))->toBe(['members']);
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[x]')
+ && str_contains($exception->getMessage(), '[test.screen]'));
+ })->with([
+ 'exact' => ['test.screen'],
+ 'every screen' => ['*'],
+ ]);
+
+ it('answers 200 with the default tab for a reserved key', function (): void {
+ Atrium::screens()->tab('test.screen', resolveTab('x'));
+ resolveRoute(fn (): Screen => Screen::make('test.screen')->tabs([['key' => 'members'], ['key' => 'teams']])->defaultTab('teams')->reserve('x'));
+
+ $this->get('/screen-test?tab=x')
+ ->assertOk()
+ ->assertJsonPath('open', 'teams')
+ ->assertJsonPath('registered', null)
+ ->assertJsonPath('tabs', ['members', 'teams']);
+ });
+
+ it('never makes a registered tab the default', function (): void {
+ Atrium::screens()->tab('test.screen', resolveTab('acme.first'));
+
+ $resolved = resolveScreen(Screen::make('test.screen'));
+
+ expect($resolved->openTab)->toBe('overview')
+ ->and($resolved->openRegisteredTab)->toBeNull();
+ });
+
+ it('opens the default tab, or the first built-in, for an absent or unknown key', function (): void {
+ $screen = fn (): Screen => Screen::make('test.screen')->tabs([['key' => 'members'], ['key' => 'teams']]);
+
+ expect(resolveScreen($screen())->openTab)->toBe('members')
+ ->and(resolveScreen($screen()->defaultTab('teams'))->openTab)->toBe('teams')
+ ->and(resolveScreen($screen()->defaultTab('unknown'))->openTab)->toBe('members')
+ ->and(resolveScreen($screen(), '/?tab=teams')->openTab)->toBe('teams')
+ ->and(resolveScreen($screen(), '/?tab=nothing')->openTab)->toBe('members');
+ });
+
+ it('answers 200 with the default tab for an unknown key', function (): void {
+ resolveRoute(fn (): Screen => Screen::make('test.screen'));
+
+ $this->get('/screen-test?tab=acme.unknown')
+ ->assertOk()
+ ->assertJsonPath('open', 'overview')
+ ->assertJsonPath('registered', null);
+ });
+
+ it('reads ?tab= only as a string', function (): void {
+ Atrium::screens()->tab('test.screen', resolveTab('acme.x'));
+ resolveRoute(fn (): Screen => Screen::make('test.screen'));
+
+ $this->get('/screen-test?tab[]=acme.x')
+ ->assertOk()
+ ->assertJsonPath('open', 'overview');
+ });
+
+ it('opens a visible registered tab', function (): void {
+ Atrium::screens()->tab('test.screen', resolveTab('acme.x'));
+ resolveRoute(fn (): Screen => Screen::make('test.screen'));
+
+ $this->get('/screen-test?tab=acme.x')
+ ->assertOk()
+ ->assertJsonPath('open', 'acme.x')
+ ->assertJsonPath('registered', 'acme.x')
+ ->assertJsonPath('tabs', ['overview', 'acme.x']);
+ });
+
+ it('answers 403 for a registered tab the viewer cannot see', function (): void {
+ Atrium::screens()->tab('test.screen', TabDefinition::make('acme.hidden')->view('acme::hidden'));
+ resolveRoute(fn (): Screen => Screen::make('test.screen'));
+
+ $this->get('/screen-test?tab=acme.hidden')->assertForbidden();
+ $this->get('/screen-test')->assertOk()->assertJsonPath('tabs', ['overview']);
+
+ expect(fn () => resolveScreen(Screen::make('test.screen'), '/?tab=acme.hidden'))
+ ->toThrow(fn (HttpException $exception) => expect($exception->getStatusCode())->toBe(403));
+ });
+
+ it('opens all-digit keys as strings', function (): void {
+ Atrium::screens()
+ ->tab('test.screen', resolveTab('123'))
+ ->tab('test.screen', resolveTab('007'));
+ resolveRoute(fn (): Screen => Screen::make('test.screen'));
+
+ $this->get('/screen-test?tab=007')
+ ->assertOk()
+ ->assertJsonPath('open', '007')
+ ->assertJsonPath('registered', '007')
+ ->assertJsonPath('tabs', ['overview', '123', '007']);
+
+ $this->get('/screen-test?tab=123')->assertJsonPath('open', '123');
+
+ expect(resolveScreen(Screen::make('test.screen'), '/?tab=007')->openRegisteredTab?->key)->toBe('007');
+ });
+
+ it('memoizes data() for the request and refuses a built-in tab', function (): void {
+ $calls = 0;
+
+ Atrium::screens()->tab('test.screen', resolveTab('acme.x')->resolve(function () use (&$calls): array {
+ $calls++;
+
+ return ['total' => 3];
+ }));
+
+ $resolved = resolveScreen(Screen::make('test.screen'), '/?tab=acme.x');
+ $again = resolveScreen(Screen::make('test.screen'), '/?tab=acme.x');
+ $tab = $resolved->openRegisteredTab;
+
+ expect($tab)->not->toBeNull()
+ ->and($resolved->data($tab))->toBe(['total' => 3])
+ ->and($resolved->data($tab))->toBe(['total' => 3])
+ ->and($again->data($again->openRegisteredTab))->toBe(['total' => 3])
+ ->and($calls)->toBe(1)
+ // Only this screen's registered extensions have data.
+ ->and(fn () => $resolved->data($resolved->tabs[0]))->toThrow(InvalidArgumentException::class)
+ ->and(fn () => $resolved->data(resolveTab('acme.x')))->toThrow(InvalidArgumentException::class);
+ });
+});
+
+describe('sections', function (): void {
+ it('lists a slot\'s sections, exact registrations before wildcards, each in registration order', function (): void {
+ Atrium::screens()
+ ->section('*', 'before', resolveSection('acme.w1'))
+ ->section('test.screen', 'before', resolveSection('acme.e1'))
+ ->section('test.*', 'before', resolveSection('acme.w2'))
+ ->section('test.screen', 'before', resolveSection('acme.e2'))
+ ->section('test.screen', 'after', resolveSection('acme.after'));
+
+ $resolved = resolveScreen(Screen::standard('test.screen', 'detail'));
+
+ expect(resolveKeys($resolved->sections('before')))->toBe(['acme.e1', 'acme.e2', 'acme.w1', 'acme.w2'])
+ ->and(resolveKeys($resolved->sections('after')))->toBe(['acme.after'])
+ ->and($resolved->sections('aside'))->toBe([])
+ ->and($resolved->sections('undeclared'))->toBe([]);
+ });
+
+ it('keeps normal and row slots apart', function (): void {
+ $resolved = resolveScreen(Screen::standard('test.list', 'list'));
+ $row = new User;
+
+ expect(fn () => $resolved->sections('row.actions'))->toThrow(InvalidArgumentException::class)
+ ->and(fn () => $resolved->rowSections('before', $row))->toThrow(InvalidArgumentException::class)
+ ->and($resolved->rowSections('row.actions', $row))->toBe([])
+ ->and($resolved->rowSections('row.undeclared', $row))->toBe([]);
+ });
+});
+
+describe('duplicate registrations on one target', function (): void {
+ it('throws in the local and testing environments, naming the key and target', function (string $environment, Closure $register): void {
+ if ($environment !== 'testing') {
+ $this->withEnvironment($environment);
+ }
+
+ $register(Atrium::screens());
+
+ expect(fn () => $register(Atrium::screens()))
+ ->toThrow(InvalidArgumentException::class, '[acme.x]')
+ ->and(fn () => $register(Atrium::screens()))
+ ->toThrow(InvalidArgumentException::class, '[test.*]');
+ })->with(['testing', 'local'])->with([
+ 'a tab' => fn (ScreenExtensions $screens): ScreenExtensions => $screens->tab('test.*', resolveTab('acme.x')),
+ 'a section' => fn (ScreenExtensions $screens): ScreenExtensions => $screens->section('test.*', 'before', resolveSection('acme.x')),
+ ]);
+
+ it('reports once and keeps the first registration in other environments', function (): void {
+ $this->withEnvironment('production');
+ Exceptions::fake();
+
+ Atrium::screens()
+ ->tab('test.screen', resolveTab('acme.x', 'First'))
+ ->tab('test.screen', resolveTab('acme.x', 'Second'))
+ ->section('test.screen', 'before', resolveSection('acme.y', 'First'))
+ ->section('test.screen', 'before', resolveSection('acme.y', 'Second'))
+ // The same key in another slot is no duplicate.
+ ->section('test.screen', 'after', resolveSection('acme.y', 'Elsewhere'));
+
+ Exceptions::assertReportedCount(2);
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[acme.x]')
+ && str_contains($exception->getMessage(), '[test.screen]'));
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[acme.y]'));
+
+ expect(array_map(fn (TabDefinition $tab): string => $tab->label, Atrium::screens()->tabs('test.screen')))->toBe(['First'])
+ ->and(array_map(fn (SectionDefinition $section): string => $section->label, Atrium::screens()->sections('test.screen', 'before')))->toBe(['First'])
+ ->and(array_map(fn (SectionDefinition $section): string => $section->label, Atrium::screens()->sections('test.screen', 'after')))->toBe(['Elsewhere']);
+ });
+
+ it('lets one key be registered on different targets', function (): void {
+ Atrium::screens()
+ ->tab('test.screen', resolveTab('acme.x'))
+ ->tab('test.*', resolveTab('acme.x'))
+ ->tab('*', resolveTab('acme.x'));
+
+ expect(resolveKeys(Atrium::screens()->tabs('*')))->toBe(['acme.x']);
+ });
+});
+
+describe('the same key across targets', function (): void {
+ it('keeps the more specific tab and reports the other once per request', function (string $winner, string $loser): void {
+ Exceptions::fake();
+
+ Atrium::screens()
+ ->tab($loser, resolveTab('acme.x', 'Loser'))
+ ->tab($winner, resolveTab('acme.x', 'Winner'));
+
+ $first = resolveScreen(Screen::make('test.screen'));
+ resolveScreen(Screen::make('test.screen'));
+
+ expect(array_map(fn (TabDefinition $tab): string => $tab->label, $first->tabs))->toBe(['Overview', 'Winner']);
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[acme.x]')
+ && str_contains($exception->getMessage(), "[{$loser}]"));
+ })->with([
+ 'exact over the package' => ['test.screen', 'test.*'],
+ 'exact over every screen' => ['test.screen', '*'],
+ 'the package over every screen' => ['test.*', '*'],
+ ]);
+
+ it('keeps the more specific section and reports the other once per request', function (string $winner, string $loser): void {
+ Exceptions::fake();
+
+ Atrium::screens()
+ ->section($loser, 'before', resolveSection('acme.x', 'Loser'))
+ ->section($winner, 'before', resolveSection('acme.x', 'Winner'));
+
+ $resolved = resolveScreen(Screen::standard('test.screen', 'detail'));
+
+ // A page rendering the slot twice.
+ $labels = array_map(fn (SectionDefinition $section): string => $section->label, $resolved->sections('before'));
+ $resolved->sections('before');
+ resolveScreen(Screen::standard('test.screen', 'detail'))->sections('before');
+
+ expect($labels)->toBe(['Winner']);
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (InvalidArgumentException $exception): bool => str_contains($exception->getMessage(), '[acme.x]')
+ && str_contains($exception->getMessage(), "[{$loser}]"));
+ })->with([
+ 'exact over the package' => ['test.screen', 'test.*'],
+ 'exact over every screen' => ['test.screen', '*'],
+ 'the package over every screen' => ['test.*', '*'],
+ ]);
+});
+
+describe('wildcards', function (): void {
+ it('adds a * tab to every screen and a package tab to that package\'s screens only', function (): void {
+ Atrium::screens()
+ ->tab('*', resolveTab('acme.everywhere'))
+ ->tab('test.*', resolveTab('acme.test-only'));
+
+ // Wildcard registrations keep their registration order across targets.
+ expect(resolveKeys(resolveScreen(Screen::make('test.a'))->tabs))->toBe(['overview', 'acme.everywhere', 'acme.test-only'])
+ ->and(resolveKeys(resolveScreen(Screen::make('other.screen'))->tabs))->toBe(['overview', 'acme.everywhere']);
+ });
+
+ it('opens a * tab through ?tab=', function (): void {
+ Atrium::screens()->tab('*', resolveTab('acme.everywhere'));
+ resolveRoute(fn (): Screen => Screen::make('other.screen'));
+
+ $this->get('/screen-test?tab=acme.everywhere')
+ ->assertOk()
+ ->assertJsonPath('registered', 'acme.everywhere');
+ });
+
+ it('adds a * section to every screen declaring the slot, with that screen', function (): void {
+ $screens = [];
+
+ Atrium::screens()->section('*', 'before', SectionDefinition::make('acme.everywhere')->view('acme::x')
+ ->authorize(function (Request $request, ?Model $record, Screen $screen) use (&$screens): bool {
+ $screens[] = $screen->key;
+
+ return true;
+ }));
+
+ expect(resolveKeys(resolveScreen(Screen::standard('test.a', 'detail'))->sections('before')))->toBe(['acme.everywhere'])
+ ->and(resolveKeys(resolveScreen(Screen::standard('other.screen', 'list'))->sections('before')))->toBe(['acme.everywhere'])
+ ->and($screens)->toBe(['test.a', 'other.screen']);
+ });
+
+ it('adds a package section only to that package\'s screens', function (): void {
+ Atrium::screens()->section('test.*', 'before', resolveSection('acme.test-only'));
+
+ expect(resolveKeys(resolveScreen(Screen::standard('test.a', 'detail'))->sections('before')))->toBe(['acme.test-only'])
+ ->and(resolveScreen(Screen::standard('other.screen', 'detail'))->sections('before'))->toBe([]);
+ });
+
+ it('never runs the closures of a wildcard section on a slot the screen lacks', function (): void {
+ $calls = 0;
+
+ Atrium::screens()->section('*', 'sidebar', SectionDefinition::make('acme.x')->view('acme::x')
+ ->authorize(function () use (&$calls): bool {
+ $calls++;
+
+ return true;
+ }));
+
+ $resolved = resolveScreen(Screen::standard('test.a', 'detail'));
+
+ expect($resolved->sections('sidebar'))->toBe([])
+ ->and($calls)->toBe(0);
+ });
+
+ it('keeps wildcard extensions hidden unless they say who may see them', function (): void {
+ Atrium::screens()
+ ->tab('*', TabDefinition::make('acme.tab')->view('acme::x'))
+ ->section('*', 'before', SectionDefinition::make('acme.section')->view('acme::x'));
+
+ $resolved = resolveScreen(Screen::standard('test.a', 'detail'));
+
+ expect(resolveKeys($resolved->tabs))->toBe(['overview'])
+ ->and($resolved->sections('before'))->toBe([]);
+ });
+});
diff --git a/tests/Feature/Screens/RowSlotsTest.php b/tests/Feature/Screens/RowSlotsTest.php
new file mode 100644
index 0000000..4eb08cd
--- /dev/null
+++ b/tests/Feature/Screens/RowSlotsTest.php
@@ -0,0 +1,143 @@
+not->toBeFalse();
+
+ $end = strpos($html, 'data-testid="row-', (int) $start + 1);
+
+ return substr($html, (int) $start, $end === false ? null : $end - (int) $start);
+}
+
+/**
+ * The innermost exception, past Blade's view wrappers.
+ */
+function rowSlotsCause(Closure $render): ?Throwable
+{
+ try {
+ $render();
+ } catch (Throwable $exception) {
+ while ($exception->getPrevious() !== null) {
+ $exception = $exception->getPrevious();
+ }
+
+ return $exception;
+ }
+
+ return null;
+}
+
+/**
+ * A row section admitting only the second row, counting its closures.
+ *
+ * @param list $asked
+ * @param list $resolved
+ */
+function rowSlotsSection(array &$asked, array &$resolved): SectionDefinition
+{
+ return SectionDefinition::make('acme.row-action')
+ ->view('screens.marker')
+ ->authorize(function (Request $request, ?Model $record, Screen $screen) use (&$asked): bool {
+ $asked[] = $record?->name;
+
+ return $record?->getKey() === 2;
+ })
+ ->resolve(function (?Model $record) use (&$resolved): array {
+ $resolved[] = $record?->name;
+
+ return ['marker' => 'row action'];
+ });
+}
+
+it('renders a row section in the rows it admits, with the row as its record', function (): void {
+ $asked = [];
+ $resolved = [];
+
+ Atrium::screens()->section('test.list', 'row.actions', rowSlotsSection($asked, $resolved));
+
+ $html = $this->get(route('test.list'))->assertOk()->getContent();
+
+ expect(substr_count($html, 'row action on test.list'))->toBe(1)
+ ->and(rowSlotsRow($html, 2))->toContain('row action on test.list for Row 2')
+ ->and(rowSlotsRow($html, 1))->not->toContain('row action')
+ ->and(rowSlotsRow($html, 3))->not->toContain('row action')
+ ->and($asked)->toBe(['Row 1', 'Row 2', 'Row 3'])
+ ->and($resolved)->toBe(['Row 2']);
+});
+
+it('remembers each row\'s answer and data when the rows render again in the request', function (): void {
+ $asked = [];
+ $resolved = [];
+
+ Atrium::screens()->section('test.list', 'row.actions', rowSlotsSection($asked, $resolved));
+
+ $screen = Atrium::screens()->resolve(Screen::standard('test.list', Screen::LIST), request());
+ $rows = [1, 2, 3];
+ $template = ' ';
+
+ foreach ([1, 2] as $pass) {
+ foreach ($rows as $id) {
+ $row = new User()->forceFill(['id' => $id, 'name' => 'Row '.$id]);
+ $html = Blade::render($template, ['screen' => $screen, 'row' => $row]);
+
+ expect(str_contains($html, 'row action'))->toBe($id === 2);
+ }
+ }
+
+ expect($asked)->toBe(['Row 1', 'Row 2', 'Row 3'])
+ ->and($resolved)->toBe(['Row 2']);
+});
+
+it('refuses a row slot without its row and a normal slot with one', function (): void {
+ $screen = Atrium::screens()->resolve(Screen::standard('test.list', Screen::LIST), request());
+ $row = new User()->forceFill(['id' => 1, 'name' => 'Row 1']);
+
+ $withoutRow = rowSlotsCause(fn () => Blade::render(' ', ['screen' => $screen]));
+ $withRow = rowSlotsCause(fn () => Blade::render(' ', ['screen' => $screen, 'row' => $row]));
+
+ expect($withoutRow)->toBeInstanceOf(InvalidArgumentException::class)
+ ->and($withoutRow?->getMessage())->toContain('[row.actions]')
+ ->and($withRow)->toBeInstanceOf(InvalidArgumentException::class)
+ ->and($withRow?->getMessage())->toContain('[before]');
+});
+
+it('never runs or renders a section on a slot the screen did not declare', function (): void {
+ $calls = 0;
+
+ $count = function () use (&$calls): bool {
+ $calls++;
+
+ return true;
+ };
+
+ Atrium::screens()
+ ->section('test.list', 'row.undeclared', SectionDefinition::make('acme.undeclared-row')->view('screens.marker')->authorize($count))
+ ->section('test.list', 'aside', SectionDefinition::make('acme.aside')->view('screens.marker')->authorize($count));
+
+ $this->get(route('test.list'))
+ ->assertOk()
+ ->assertDontSee('section-acme.undeclared-row', false)
+ ->assertDontSee('section-acme.aside', false);
+
+ expect($calls)->toBe(0);
+});
diff --git a/tests/Feature/Screens/ScreenSectionsComponentTest.php b/tests/Feature/Screens/ScreenSectionsComponentTest.php
new file mode 100644
index 0000000..daf84a4
--- /dev/null
+++ b/tests/Feature/Screens/ScreenSectionsComponentTest.php
@@ -0,0 +1,73 @@
+resolve(Screen::standard('test.host', Screen::DETAIL), Request::create($uri));
+}
+
+function screenSection(string $key, string $marker): SectionDefinition
+{
+ return SectionDefinition::make($key)->view('screens.marker')->public()->resolve(fn (): array => ['marker' => $marker]);
+}
+
+/**
+ * Each wrapper's test id, class and markup, in order.
+ *
+ * @return list
+ */
+function screenSectionsWrappers(string $html): array
+{
+ preg_match_all('/]*\bdata-testid="([^"]*)")(?:(?=[^>]*\bclass="([^"]*)"))?[^>]*>(.*?)<\/div>/s', $html, $matches, PREG_SET_ORDER);
+
+ return array_map(fn (array $match): array => [$match[1], $match[2], trim($match[3])], $matches);
+}
+
+it('wraps each visible section of the slot in order, passing class through', function (): void {
+ Atrium::screens()
+ ->section('*', 'before', screenSection('acme.third', 'third'))
+ ->section('test.host', 'before', screenSection('acme.first', 'first'))
+ ->section('test.host', 'before', SectionDefinition::make('acme.hidden')->view('screens.marker'))
+ ->section('test.host', 'before', screenSection('acme.second', 'second'))
+ ->section('test.host', 'after', screenSection('acme.elsewhere', 'elsewhere'));
+
+ $html = Blade::render('
', ['screen' => screenSectionsResolve()]);
+
+ expect(screenSectionsWrappers($html))->toBe([
+ ['section-acme.first', 'mb-6 flex', '
first on test.host for no record with overview open
'],
+ ['section-acme.second', 'mb-6 flex', '
second on test.host for no record with overview open
'],
+ ['section-acme.third', 'mb-6 flex', '
third on test.host for no record with overview open
'],
+ ])
+ ->and($html)->not->toContain('slot=');
+});
+
+it('renders an empty string for an empty slot', function (): void {
+ Atrium::screens()->section('test.host', 'before', SectionDefinition::make('acme.hidden')->view('screens.marker'));
+
+ $screen = screenSectionsResolve();
+
+ expect(trim(Blade::render('
', ['screen' => $screen])))->toBe('')
+ ->and(trim(Blade::render('
', ['screen' => $screen])))->toBe('')
+ ->and(trim(Blade::render('
', ['screen' => $screen])))->toBe('');
+});
+
+it('renders the open registered tab\'s panel and nothing on a built-in tab', function (): void {
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.tab')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'the panel']));
+
+ $template = '
';
+
+ expect(trim(Blade::render($template, ['screen' => screenSectionsResolve()])))->toBe('')
+ ->and(screenSectionsWrappers(Blade::render($template, ['screen' => screenSectionsResolve('/?tab=acme.tab')])))->toBe([
+ ['tab-panel-acme.tab', 'pt-4', '
the panel on test.host for no record with acme.tab open
'],
+ ]);
+});
diff --git a/tests/Feature/Screens/ScreenStylesTest.php b/tests/Feature/Screens/ScreenStylesTest.php
new file mode 100644
index 0000000..cc8c3fc
--- /dev/null
+++ b/tests/Feature/Screens/ScreenStylesTest.php
@@ -0,0 +1,26 @@
+toBeFile();
+
+ $contents = (string) file_get_contents($path);
+
+ // Classes given through $attributes->class('...') are checked too.
+ $contents = (string) preg_replace("/->class\\('([^']*)'\\)/", ' class="$1" ', $contents);
+
+ file_put_contents($views.'/'.$component.'.blade.php', $contents);
+ }
+
+ expect(AtriumStyles::missingClasses($views))->toBe([])
+ ->and(AtriumStyles::inlineStyles($views))->toBe([]);
+});
diff --git a/tests/Feature/Screens/ScreenTabsComponentTest.php b/tests/Feature/Screens/ScreenTabsComponentTest.php
new file mode 100644
index 0000000..c45e828
--- /dev/null
+++ b/tests/Feature/Screens/ScreenTabsComponentTest.php
@@ -0,0 +1,144 @@
+ [
+ ['key' => 'details', 'label' => 'Details', 'icon' => 'document-text'],
+ ['key' => 'activity', 'label' => 'Activity'],
+ ]]);
+});
+
+/**
+ * The opening tag of a tab's link.
+ */
+function screenTabsLink(string $html, string $key): string
+{
+ expect(preg_match('/
]*data-testid="tab-'.preg_quote($key, '/').'"[^>]*>/', $html, $match))->toBe(1);
+
+ return $match[0];
+}
+
+/**
+ * The markup inside a tab's link: its icon.
+ */
+function screenTabsIcon(string $html, string $key): string
+{
+ expect(preg_match('/ ]*data-testid="tab-'.preg_quote($key, '/').'"[^>]*>(.*?)<\/a>/s', $html, $match))->toBe(1);
+
+ return trim($match[1]);
+}
+
+/**
+ * @return list
+ */
+function screenTabsClasses(string $link): array
+{
+ preg_match('/\sclass="([^"]*)"/', $link, $match);
+
+ return preg_split('/\s+/', $match[1] ?? '', flags: PREG_SPLIT_NO_EMPTY) ?: [];
+}
+
+it('links each tab to ?tab= keeping the query string except page and tab', function (): void {
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.billing')->label('Billing')->view('screens.marker')->public());
+
+ $html = $this->get(route('test.host', ['page' => 2, 'q' => 'x', 'tab' => 'activity']))->assertOk()->getContent();
+
+ expect(screenTabsLink($html, 'details'))->toContain('href="'.e(route('test.host').'?q=x&tab=details').'"')
+ ->and(screenTabsLink($html, 'acme.billing'))->toContain('href="'.e(route('test.host').'?q=x&tab=acme.billing').'"');
+});
+
+it('escapes the query string it keeps', function (): void {
+ $html = $this->get(route('test.host').'?q[]=a&b')->assertOk()->getContent();
+
+ // The empty `b` reaches the URL helper as null (ConvertEmptyStringsToNull), which leaves it out.
+ expect(screenTabsLink($html, 'details'))->toContain('?q%5B0%5D=a&tab=details"');
+
+ $html = $this->get(route('test.host').'?q='.rawurlencode('"'))->assertOk()->getContent();
+
+ expect(screenTabsLink($html, 'details'))->toContain('?q=%3Cx%3E%22&tab=details"')
+ ->and($html)->not->toContain('"');
+});
+
+it('marks the open tab alone as current and primary', function (): void {
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.billing')->label('Billing')->view('screens.marker')->public());
+
+ $html = $this->get(route('test.host', ['tab' => 'acme.billing']))->assertOk()->getContent();
+
+ $open = screenTabsLink($html, 'acme.billing');
+
+ expect($open)->toContain('aria-current="page"')
+ ->and(screenTabsClasses($open))->toContain('bg-primary');
+
+ foreach (['details', 'activity'] as $idle) {
+ $link = screenTabsLink($html, $idle);
+
+ expect($link)->not->toContain('aria-current')
+ ->and(screenTabsClasses($link))->not->toContain('bg-primary');
+ }
+
+ $html = $this->get(route('test.host'))->assertOk()->getContent();
+
+ expect(screenTabsLink($html, 'details'))->toContain('aria-current="page"')
+ ->and(screenTabsLink($html, 'acme.billing'))->not->toContain('aria-current');
+});
+
+it('renders a scrolling, non-wrapping nav of icon buttons with escaped labels', function (): void {
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.marked-up')->label('Bold & co')->view('screens.marker')->public());
+
+ $html = $this->get(route('test.host'))->assertOk()->getContent();
+
+ expect(preg_match('/]*data-testid="screen-tabs"[^>]*>/', $html, $nav))->toBe(1)
+ // A flex row never wraps unless told to.
+ ->and(screenTabsClasses($nav[0]))->toContain('flex', 'overflow-x-auto')
+ ->and(screenTabsClasses($nav[0]))->not->toContain('flex-wrap')
+ ->and(screenTabsLink($html, 'acme.marked-up'))->toContain('aria-label="<b>Bold</b> & co"')
+ ->and($html)->toContain('<b>Bold</b> & co')
+ ->and($html)->not->toContain('Bold ');
+});
+
+it('falls back to squares-2x2 for an icon Atrium does not know', function (): void {
+ Atrium::screens()
+ ->tab('test.host', TabDefinition::make('acme.unknown-icon')->icon('not-a-real-icon')->view('screens.marker')->public())
+ ->tab('test.host', TabDefinition::make('acme.squares')->icon('squares-2x2')->view('screens.marker')->public());
+
+ $html = $this->get(route('test.host'))->assertOk()->getContent();
+
+ expect(screenTabsIcon($html, 'acme.unknown-icon'))->toBe(screenTabsIcon($html, 'acme.squares'))
+ ->and(screenTabsIcon($html, 'acme.squares'))->toContain('and(screenTabsIcon($html, 'details'))->not->toBe(screenTabsIcon($html, 'acme.squares'));
+});
+
+it('renders nothing with fewer than two visible tabs', function (): void {
+ config(['screen-host.tabs' => []]);
+
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertDontSee('data-testid="screen-tabs"', false)
+ ->assertDontSee('data-testid="tab-overview"', false);
+
+ config(['screen-host.tabs' => [['key' => 'details', 'label' => 'Details']]]);
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.hidden')->view('screens.marker'));
+
+ $this->get(route('test.host'))
+ ->assertOk()
+ ->assertDontSee('data-testid="screen-tabs"', false)
+ ->assertDontSee('data-testid="tab-details"', false);
+});
+
+it('does not render reserved keys, or a registered tab using one', function (): void {
+ config(['screen-host.reserved' => ['secrets', 'acme.billing']]);
+ Atrium::screens()->tab('test.host', TabDefinition::make('acme.billing')->label('Billing')->view('screens.marker')->public());
+
+ $this->get(route('test.host', ['tab' => 'secrets']))
+ ->assertOk()
+ ->assertSee('data-testid="tab-details"', false)
+ ->assertDontSee('data-testid="tab-secrets"', false)
+ ->assertDontSee('data-testid="tab-acme.billing"', false);
+});
diff --git a/tests/Feature/Screens/VisibilityTest.php b/tests/Feature/Screens/VisibilityTest.php
new file mode 100644
index 0000000..eacba4b
--- /dev/null
+++ b/tests/Feature/Screens/VisibilityTest.php
@@ -0,0 +1,283 @@
+view('acme::x');
+ $configure($tab);
+ Atrium::screens()->tab('test.screen', $tab);
+
+ return;
+ }
+
+ $section = SectionDefinition::make('acme.x')->view('acme::x');
+ $configure($section);
+ Atrium::screens()->section('test.screen', 'before', $section);
+}
+
+/**
+ * A detail screen whose host grants only the `granted` permission.
+ */
+function visibilityScreen(bool $access = true): Screen
+{
+ $screen = Screen::standard('test.screen', 'detail');
+
+ return $access ? $screen->access(fn (string $permission): bool => $permission === 'granted') : $screen;
+}
+
+function visibilityResolve(?Screen $screen = null, ?Request $request = null): ResolvedScreen
+{
+ return Atrium::screens()->resolve($screen ?? visibilityScreen(), $request ?? Request::create('/'));
+}
+
+/**
+ * Whether `acme.x` shows on the resolved screen.
+ */
+function visibilityShows(string $kind, ResolvedScreen $resolved): bool
+{
+ $definitions = $kind === 'tab' ? $resolved->tabs : $resolved->sections('before');
+
+ return in_array('acme.x', array_map(fn (TabDefinition|SectionDefinition $definition): string => $definition->key, $definitions), true);
+}
+
+/**
+ * A list screen with a `row.actions` row slot holding `acme.x`.
+ */
+function visibilityRowScreen(SectionDefinition $section): Screen
+{
+ Atrium::screens()->section('test.list', 'row.actions', $section);
+
+ return Screen::standard('test.list', 'list');
+}
+
+it('shows an extension only when it says who may see it', function (string $kind, Closure $configure, bool $access, bool $visible): void {
+ visibilityRegister($kind, $configure);
+
+ expect(visibilityShows($kind, visibilityResolve(visibilityScreen($access))))->toBe($visible);
+})->with(['tab', 'section'])->with([
+ 'a granted permission' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('granted'), true, true],
+ 'a refused permission' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('refused'), true, false],
+ 'a permission on a screen without access' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('granted'), false, false],
+ 'a closure answering true' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->authorize(fn (): bool => true), true, true],
+ 'a closure answering false' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->authorize(fn (): bool => false), true, false],
+ 'a closure answering something truthy' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->authorize(fn (): int => 1), true, false],
+ 'public' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->public(), true, true],
+ 'neither' => [fn (TabDefinition|SectionDefinition $d): mixed => $d, true, false],
+ 'both passing' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('granted')->authorize(fn (): bool => true), true, true],
+ 'the permission failing' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('refused')->authorize(fn (): bool => true), true, false],
+ 'the closure failing' => [fn (TabDefinition|SectionDefinition $d): mixed => $d->permission('granted')->authorize(fn (): bool => false), true, false],
+]);
+
+it('hides an extension whose authorize closure throws, reporting it once and calling it once', function (string $kind): void {
+ Exceptions::fake();
+ $calls = 0;
+
+ // A plain closure, not an arrow function: an arrow function would capture
+ // $calls by value and the counter would never reach the test.
+ visibilityRegister($kind, function (TabDefinition|SectionDefinition $d) use (&$calls): mixed {
+ return $d->authorize(function () use (&$calls): bool {
+ $calls++;
+
+ throw new RuntimeException('authorize failed');
+ });
+ });
+
+ Route::get('screen-test', function (Request $request) use ($kind) {
+ $first = visibilityResolve(request: $request);
+ $second = visibilityResolve(request: $request);
+
+ return response()->json([visibilityShows($kind, $first), visibilityShows($kind, $second), visibilityShows($kind, $second)]);
+ });
+
+ $this->get('/screen-test')->assertOk()->assertExactJson([false, false, false]);
+
+ expect($calls)->toBe(1);
+
+ Exceptions::assertReportedCount(1);
+ Exceptions::assertReported(fn (RuntimeException $exception): bool => $exception->getMessage() === 'authorize failed');
+})->with(['tab', 'section']);
+
+it('asks the host about a row section\'s permission with the row as the record', function (): void {
+ $seen = [];
+ $row = new User;
+ $row->id = 5;
+
+ $screen = visibilityRowScreen(SectionDefinition::make('acme.x')->view('acme::x')->permission('granted'))
+ ->access(function (string $permission, Request $request, ?Model $record) use (&$seen): bool {
+ $seen[] = [$permission, $record];
+
+ return true;
+ });
+
+ expect(visibilityResolve($screen)->rowSections('row.actions', $row))->toHaveCount(1)
+ ->and($seen)->toBe([['granted', $row]]);
+});
+
+it('asks and resolves again for rows with the same id in two model classes', function (): void {
+ $first = new class extends Model {};
+ $first->id = 1;
+ $second = new class extends Model {};
+ $second->id = 1;
+ // Another instance of the same class with the same key.
+ $twin = clone $first;
+
+ $asked = 0;
+ $resolved = 0;
+
+ $resolvedScreen = visibilityResolve(visibilityRowScreen(SectionDefinition::make('acme.x')->view('acme::x')
+ ->authorize(function (Request $request, ?Model $record) use (&$asked, $first): bool {
+ $asked++;
+
+ return $record !== null && $record::class === $first::class;
+ })
+ ->resolve(function (?Model $record) use (&$resolved): array {
+ $resolved++;
+
+ return ['class' => $record === null ? null : $record::class];
+ })));
+
+ $forFirst = $resolvedScreen->rowSections('row.actions', $first);
+
+ expect($forFirst)->toHaveCount(1)
+ ->and($resolvedScreen->rowSections('row.actions', $second))->toBe([])
+ ->and($asked)->toBe(2)
+ ->and($resolvedScreen->data($forFirst[0], $first))->toBe(['class' => $first::class])
+ // A hidden row's data is never resolved.
+ ->and($resolvedScreen->data($forFirst[0], $second))->toBe([])
+ ->and($resolved)->toBe(1);
+
+ // The same class and key is the same row: nothing runs again.
+ expect($resolvedScreen->rowSections('row.actions', $twin))->toHaveCount(1)
+ ->and($resolvedScreen->data($forFirst[0], $twin))->toBe(['class' => $first::class])
+ ->and($resolvedScreen->rowSections('row.actions', $second))->toBe([])
+ ->and($asked)->toBe(2)
+ ->and($resolved)->toBe(1);
+});
+
+it('keeps separate data for rows with the same id in two model classes', function (): void {
+ $first = new class extends Model {};
+ $first->id = 1;
+ $second = new class extends Model {};
+ $second->id = 1;
+ $resolved = 0;
+
+ $resolvedScreen = visibilityResolve(visibilityRowScreen(SectionDefinition::make('acme.x')->view('acme::x')->public()
+ ->resolve(function (?Model $record) use (&$resolved): array {
+ $resolved++;
+
+ return ['class' => $record === null ? null : $record::class];
+ })));
+
+ $section = $resolvedScreen->rowSections('row.actions', $first)[0];
+
+ expect($resolvedScreen->data($section, $first))->toBe(['class' => $first::class])
+ ->and($resolvedScreen->data($section, $second))->toBe(['class' => $second::class])
+ ->and($resolvedScreen->data($section, $first))->toBe(['class' => $first::class])
+ ->and($resolved)->toBe(2);
+});
+
+it('asks and resolves again for a new unsaved row after the last one is freed', function (): void {
+ $asked = 0;
+ $resolved = 0;
+ $make = fn (): Model => new class extends Model {};
+
+ $resolvedScreen = visibilityResolve(visibilityRowScreen(SectionDefinition::make('acme.x')->view('acme::x')
+ ->authorize(function () use (&$asked): bool {
+ $asked++;
+
+ return true;
+ })
+ ->resolve(function () use (&$resolved): array {
+ $resolved++;
+
+ return [];
+ })));
+
+ $row = $make();
+ $section = $resolvedScreen->rowSections('row.actions', $row)[0];
+ $resolvedScreen->data($section, $row);
+ $resolvedScreen->rowSections('row.actions', $row);
+ $resolvedScreen->data($section, $row);
+
+ expect($asked)->toBe(1)
+ ->and($resolved)->toBe(1);
+
+ unset($row);
+ gc_collect_cycles();
+
+ $row = $make();
+ $resolvedScreen->rowSections('row.actions', $row);
+ $resolvedScreen->data($section, $row);
+
+ expect($asked)->toBe(2)
+ ->and($resolved)->toBe(2);
+});
+
+it('evaluates afresh for another viewer once the scoped instances are forgotten', function (string $kind): void {
+ $asked = 0;
+ $resolved = 0;
+
+ visibilityRegister($kind, function (TabDefinition|SectionDefinition $d) use (&$asked, &$resolved): mixed {
+ return $d
+ ->authorize(function (Request $request) use (&$asked): bool {
+ $asked++;
+
+ return $request->user()?->getAuthIdentifier() === 1;
+ })
+ ->resolve(function () use (&$resolved): array {
+ $resolved++;
+
+ return [];
+ });
+ });
+
+ $ada = new User;
+ $ada->id = 1;
+ $bob = new User;
+ $bob->id = 2;
+
+ $asAda = Request::create('/?tab=acme.x');
+ $asAda->setUserResolver(fn (): User => $ada);
+ $asBob = Request::create('/');
+ $asBob->setUserResolver(fn (): User => $bob);
+
+ $forAda = visibilityResolve(request: $asAda);
+ $extension = $kind === 'tab' ? $forAda->openRegisteredTab : ($forAda->sections('before')[0] ?? null);
+
+ expect(visibilityShows($kind, $forAda))->toBeTrue()
+ ->and($extension)->not->toBeNull()
+ ->and($forAda->data($extension))->toBe([]);
+
+ app()->forgetScopedInstances();
+
+ expect(visibilityShows($kind, visibilityResolve(request: $asBob)))->toBeFalse()
+ ->and($asked)->toBe(2);
+
+ app()->forgetScopedInstances();
+
+ $again = visibilityResolve(request: $asAda);
+ $extension = $kind === 'tab' ? $again->openRegisteredTab : $again->sections('before')[0];
+ $again->data($extension);
+
+ expect($asked)->toBe(3)
+ ->and($resolved)->toBe(2);
+})->with(['tab', 'section']);
diff --git a/tests/Feature/Screens/WildcardRenderingTest.php b/tests/Feature/Screens/WildcardRenderingTest.php
new file mode 100644
index 0000000..80c4dbb
--- /dev/null
+++ b/tests/Feature/Screens/WildcardRenderingTest.php
@@ -0,0 +1,91 @@
+section('*', 'before', SectionDefinition::make('acme.everywhere')->view('screens.marker')->public()
+ ->resolve(fn (?Model $record, Screen $screen): array => ['marker' => 'everywhere for '.$screen->kind]));
+
+ $this->get(route('test.host', ['screen' => 'test.a']))
+ ->assertOk()
+ ->assertSee('everywhere for detail on test.a');
+
+ $this->get(route('test.list', ['screen' => 'other.screen']))
+ ->assertOk()
+ ->assertSee('everywhere for list on other.screen');
+});
+
+it('renders a package section on that package\'s screens only', function (): void {
+ Atrium::screens()->section('test.*', 'before', SectionDefinition::make('acme.test-only')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'test package only']));
+
+ $this->get(route('test.host', ['screen' => 'test.a']))
+ ->assertOk()
+ ->assertSee('test package only on test.a');
+
+ $this->get(route('test.host', ['screen' => 'other.screen']))
+ ->assertOk()
+ ->assertDontSee('test package only')
+ ->assertDontSee('section-acme.test-only', false);
+});
+
+it('opens a * tab through ?tab=', function (): void {
+ Atrium::screens()->tab('*', TabDefinition::make('acme.everywhere')->label('Everywhere')->view('screens.marker')->public()
+ ->resolve(fn (): array => ['marker' => 'the everywhere panel']));
+
+ $this->get(route('test.host', ['screen' => 'other.screen', 'tab' => 'acme.everywhere']))
+ ->assertOk()
+ ->assertSee('data-testid="tab-panel-acme.everywhere"', false)
+ ->assertSee('the everywhere panel on other.screen');
+});
+
+it('never runs a wildcard section\'s closures on a screen without its slot', function (): void {
+ $calls = 0;
+
+ Atrium::screens()->section('*', 'sidebar', SectionDefinition::make('acme.sidebar')->view('screens.marker')
+ ->authorize(function () use (&$calls): bool {
+ $calls++;
+
+ return true;
+ })
+ ->resolve(function () use (&$calls): array {
+ $calls++;
+
+ return [];
+ }));
+
+ $this->get(route('test.host', ['screen' => 'test.a']))->assertOk()->assertDontSee('section-acme.sidebar', false);
+ $this->get(route('test.list', ['screen' => 'other.screen']))->assertOk()->assertDontSee('section-acme.sidebar', false);
+
+ expect($calls)->toBe(0);
+});
+
+it('makes no resolver call where a wildcard authorize returns early on the screen key', function (): void {
+ $resolvedOn = [];
+
+ Atrium::screens()->section('*', 'before', SectionDefinition::make('acme.picky')->view('screens.marker')
+ ->authorize(fn (Request $request, ?Model $record, Screen $screen): bool => $screen->key === 'test.a')
+ ->resolve(function (?Model $record, Screen $screen) use (&$resolvedOn): array {
+ $resolvedOn[] = $screen->key;
+
+ return ['marker' => 'picky'];
+ }));
+
+ $this->get(route('test.host', ['screen' => 'other.screen']))->assertOk()->assertDontSee('picky on');
+ $this->get(route('test.list', ['screen' => 'test.b']))->assertOk()->assertDontSee('picky on');
+ $this->get(route('test.host', ['screen' => 'test.a']))->assertOk()->assertSee('picky on test.a');
+
+ expect($resolvedOn)->toBe(['test.a']);
+});
diff --git a/tests/Fixtures/views/components/screen-probe.blade.php b/tests/Fixtures/views/components/screen-probe.blade.php
new file mode 100644
index 0000000..6a738b3
--- /dev/null
+++ b/tests/Fixtures/views/components/screen-probe.blade.php
@@ -0,0 +1,3 @@
+@props(['data'])
+
+component data: {{ implode(',', array_keys($data)) }} = {{ implode(',', $data) }}; {{ isset($screen) || isset($record) || isset($tab) ? 'host variables leaked' : 'data only' }}
diff --git a/tests/Fixtures/views/screens/marker.blade.php b/tests/Fixtures/views/screens/marker.blade.php
new file mode 100644
index 0000000..456258a
--- /dev/null
+++ b/tests/Fixtures/views/screens/marker.blade.php
@@ -0,0 +1 @@
+{{ $marker ?? 'marker' }} on {{ $screen->key }} for {{ $record instanceof \Illuminate\Database\Eloquent\Model ? $record->name : 'no record' }} with {{ $tab }} open
diff --git a/tests/Fixtures/views/screens/spread.blade.php b/tests/Fixtures/views/screens/spread.blade.php
new file mode 100644
index 0000000..2d69d19
--- /dev/null
+++ b/tests/Fixtures/views/screens/spread.blade.php
@@ -0,0 +1 @@
+screen={{ $screen instanceof \RefactorCircus\Atrium\Domains\Screens\Data\Screen ? $screen->key : 'lost' }};record={{ $record instanceof \Illuminate\Database\Eloquent\Model ? $record->name : 'lost' }};tab={{ $tab }};extra={{ $extra }}
diff --git a/tests/Fixtures/views/screens/throws.blade.php b/tests/Fixtures/views/screens/throws.blade.php
new file mode 100644
index 0000000..8abeefe
--- /dev/null
+++ b/tests/Fixtures/views/screens/throws.blade.php
@@ -0,0 +1,2 @@
+leaked markup
+@php(throw new RuntimeException('The section view failed.'))
diff --git a/tests/Pest.php b/tests/Pest.php
index ceeae23..3528386 100644
--- a/tests/Pest.php
+++ b/tests/Pest.php
@@ -2,6 +2,7 @@
declare(strict_types=1);
+use Pest\Plugins\Parallel;
use RefactorCircus\Atrium\Tests\BrowserTestCase;
use RefactorCircus\Atrium\Tests\RenamedTablesTestCase;
use RefactorCircus\Atrium\Tests\TestCase;
@@ -16,6 +17,20 @@
}
}
+// It only removes files, though, and warns on a directory it cannot unlink
+// and on a Screenshots directory that is not empty. The screen-extensions
+// matrix saves into a directory of its own, so clear it first, as the plugin
+// does the rest of the last run's screenshots; ScreenExtensionsTest makes it
+// again. Parallel workers leave it alone, as the plugin does, so they never
+// race each other to delete it.
+if (! Parallel::isWorker() && is_dir(__DIR__.'/Browser/Screenshots/screen-extensions')) {
+ foreach (glob(__DIR__.'/Browser/Screenshots/screen-extensions/*') ?: [] as $screenshot) {
+ unlink($screenshot);
+ }
+
+ rmdir(__DIR__.'/Browser/Screenshots/screen-extensions');
+}
+
uses(TestCase::class)->in(__DIR__.'/Feature');
// The Feature suite's dashboard flows again, with every table renamed.
diff --git a/tests/TestCase.php b/tests/TestCase.php
index 3a8e5f5..e316bdf 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -10,10 +10,12 @@
use Orchestra\Testbench\Concerns\WithLaravelMigrations;
use Orchestra\Testbench\TestCase as Orchestra;
use RefactorCircus\Atrium\AtriumServiceProvider;
+use RefactorCircus\Atrium\Testing\ResetsScreenExtensions;
abstract class TestCase extends Orchestra
{
use RefreshDatabase;
+ use ResetsScreenExtensions;
use WithLaravelMigrations;
protected function getPackageProviders($app): array
@@ -33,11 +35,11 @@ protected function withEnvironment(string $environment): void
$this->app->detectEnvironment(fn (): string => $environment);
$this->app->make(ConsoleKernel::class);
- $this->app['env'] = $environment;
+ $this->app->instance('env', $environment);
$this->beforeApplicationDestroyed(function (): void {
$this->app->detectEnvironment(fn (): string => 'testing');
- $this->app['env'] = 'testing';
+ $this->app->instance('env', 'testing');
});
}
diff --git a/tests/Unit/Screens/ScreenExtensionsTest.php b/tests/Unit/Screens/ScreenExtensionsTest.php
new file mode 100644
index 0000000..31b9b4a
--- /dev/null
+++ b/tests/Unit/Screens/ScreenExtensionsTest.php
@@ -0,0 +1,162 @@
+ Container::setInstance(new Container));
+
+afterEach(fn () => Container::setInstance(null));
+
+function unitTab(string $key): TabDefinition
+{
+ return TabDefinition::make($key)->view('acme::'.$key)->public();
+}
+
+function unitSection(string $key): SectionDefinition
+{
+ return SectionDefinition::make($key)->view('acme::'.$key)->public();
+}
+
+/**
+ * @param list $definitions
+ * @return list
+ */
+function unitKeys(array $definitions): array
+{
+ return array_map(fn (TabDefinition|SectionDefinition $definition): string => $definition->key, $definitions);
+}
+
+it('returns itself from both registration methods for chaining', function (): void {
+ $screens = new ScreenExtensions;
+
+ expect($screens->tab('test.screen', unitTab('acme.a')))->toBe($screens)
+ ->and($screens->section('test.screen', 'before', unitSection('acme.b')))->toBe($screens);
+});
+
+it('accepts an exact key, every screen or every screen of a package as the target', function (string $target): void {
+ $screens = (new ScreenExtensions)
+ ->tab($target, unitTab('acme.a'))
+ ->section($target, 'before', unitSection('acme.b'));
+
+ expect(unitKeys($screens->tabs($target)))->toBe(['acme.a'])
+ ->and(unitKeys($screens->sections($target, 'before')))->toBe(['acme.b']);
+})->with(['test.screen', 'test.a.b', 'acme-billing.invoices', '*', 'test.*', 'acme-billing.*']);
+
+it('rejects any other target', function (string $target): void {
+ expect(fn () => (new ScreenExtensions)->tab($target, unitTab('acme.a')))->toThrow(InvalidArgumentException::class)
+ ->and(fn () => (new ScreenExtensions)->section($target, 'before', unitSection('acme.b')))->toThrow(InvalidArgumentException::class);
+})->with([
+ 'a wildcard package' => '*.x',
+ 'a partial package' => 'te*.x',
+ 'a partial screen' => 'test.a*',
+ 'a wildcard in the middle' => 'test.*.x',
+ 'a double star' => '**',
+ 'a package double star' => 'test.**',
+ 'empty' => '',
+ 'no package' => 'screen',
+ 'uppercase' => 'Test.screen',
+]);
+
+it('accepts slot names like header.actions and rejects others', function (): void {
+ $screens = (new ScreenExtensions)->section('test.screen', 'header.actions', unitSection('acme.a'));
+
+ expect(unitKeys($screens->sections('test.screen', 'header.actions')))->toBe(['acme.a']);
+
+ foreach (['Header', 'a b', 'a/b', ''] as $slot) {
+ expect(fn () => $screens->section('test.screen', $slot, unitSection('acme.b')))->toThrow(InvalidArgumentException::class);
+ }
+});
+
+it('refuses a definition with neither a view nor a component', function (): void {
+ expect(fn () => (new ScreenExtensions)->tab('test.screen', TabDefinition::make('acme.a')->public()))
+ ->toThrow(InvalidArgumentException::class, 'acme.a')
+ ->and(fn () => (new ScreenExtensions)->section('test.screen', 'before', SectionDefinition::make('acme.b')->public()))
+ ->toThrow(InvalidArgumentException::class, 'acme.b');
+});
+
+it('stores a copy, so later changes to the caller\'s instance change nothing', function (): void {
+ $tab = unitTab('acme.a')->label('Before');
+ $section = unitSection('acme.b')->label('Before');
+
+ $screens = (new ScreenExtensions)
+ ->tab('test.screen', $tab)
+ ->section('test.screen', 'before', $section);
+
+ $tab->label('After');
+ $section->label('After');
+
+ expect($screens->tabs('test.screen')[0]->label)->toBe('Before')
+ ->and($screens->sections('test.screen', 'before')[0]->label)->toBe('Before');
+
+ // Nor do changes to what it hands out.
+ $screens->tabs('test.screen')[0]->label('Changed');
+
+ expect($screens->tabs('test.screen')[0]->label)->toBe('Before');
+});
+
+it('reads all-digit keys back as strings, in registration order', function (): void {
+ $screens = (new ScreenExtensions)
+ ->tab('test.screen', unitTab('123'))
+ ->tab('test.screen', unitTab('007'))
+ ->section('test.screen', 'before', unitSection('123'))
+ ->section('test.screen', 'before', unitSection('007'));
+
+ expect(unitKeys($screens->tabs('test.screen')))->toBe(['123', '007'])
+ ->and(unitKeys($screens->sections('test.screen', 'before')))->toBe(['123', '007']);
+});
+
+it('keeps a registration for a screen nobody declares without error or effect', function (): void {
+ $screens = (new ScreenExtensions)
+ ->tab('test.screen', unitTab('acme.kept'))
+ ->tab('missing.screen', unitTab('acme.missing'))
+ ->section('missing.screen', 'before', unitSection('acme.missing'));
+
+ $resolved = $screens->resolve(Screen::standard('test.screen', 'detail'), Request::create('/'));
+
+ expect(unitKeys($screens->tabs('missing.screen')))->toBe(['acme.missing'])
+ ->and(unitKeys($resolved->tabs))->toBe(['overview', 'acme.kept'])
+ ->and($resolved->sections('before'))->toBe([]);
+});
+
+it('round-trips its registrations through snapshot() and restore()', function (): void {
+ $screens = (new ScreenExtensions)
+ ->tab('test.screen', unitTab('acme.a'))
+ ->section('*', 'before', unitSection('acme.b'));
+
+ $snapshot = $screens->snapshot();
+
+ $screens->tab('test.screen', unitTab('acme.later'))
+ ->section('*', 'before', unitSection('acme.later'));
+
+ $screens->restore($snapshot);
+
+ expect(unitKeys($screens->tabs('test.screen')))->toBe(['acme.a'])
+ ->and(unitKeys($screens->sections('*', 'before')))->toBe(['acme.b'])
+ ->and($screens->snapshot())->toEqual($snapshot);
+
+ // The snapshot is a copy too: restoring twice gives the same state.
+ $screens->tab('test.screen', unitTab('acme.again'));
+ $screens->restore($snapshot);
+
+ expect(unitKeys($screens->tabs('test.screen')))->toBe(['acme.a']);
+});
+
+it('forgets everything on flush()', function (): void {
+ $screens = (new ScreenExtensions)
+ ->tab('test.screen', unitTab('acme.a'))
+ ->section('test.screen', 'before', unitSection('acme.b'));
+
+ $screens->flush();
+
+ expect($screens->tabs('test.screen'))->toBe([])
+ ->and($screens->sections('test.screen', 'before'))->toBe([])
+ ->and($screens->snapshot())->toEqual((new ScreenExtensions)->snapshot());
+});
diff --git a/tests/Unit/Screens/ScreenTest.php b/tests/Unit/Screens/ScreenTest.php
new file mode 100644
index 0000000..3a9e91a
--- /dev/null
+++ b/tests/Unit/Screens/ScreenTest.php
@@ -0,0 +1,157 @@
+package)->toBe($package);
+})->with([
+ ['atrium.dashboard', 'atrium'],
+ ['acme-billing.invoices.show', 'acme-billing'],
+ ['test.a', 'test'],
+]);
+
+it('starts as a detail screen with no record, no slots and the overview tab', function (): void {
+ $screen = Screen::make('test.screen');
+
+ expect($screen->key)->toBe('test.screen')
+ ->and($screen->record)->toBeNull()
+ ->and($screen->kind)->toBe('detail')
+ ->and($screen->slots)->toBe([])
+ ->and($screen->rowSlots)->toBe([])
+ ->and(array_map(fn (TabDefinition $tab): string => $tab->key, $screen->tabs))->toBe(['overview'])
+ ->and($screen->tabs[0]->label)->toBe('Overview');
+});
+
+it('accepts only an exact screen key', function (string $key): void {
+ expect(fn () => Screen::make($key))->toThrow(InvalidArgumentException::class);
+})->with(['*', 'test.*', '*.x', 'test', 'Test.screen', 'test screen', '', '.screen', "test.screen\n"]);
+
+it('declares the standard slots of a detail screen', function (): void {
+ $screen = Screen::standard('test.screen', 'detail');
+
+ expect($screen->kind)->toBe('detail')
+ ->and($screen->slots)->toBe(['header.actions', 'before', 'after', 'aside'])
+ ->and($screen->rowSlots)->toBe([]);
+});
+
+it('declares the standard slots of a list screen', function (): void {
+ $screen = Screen::standard('test.list', 'list');
+
+ expect($screen->kind)->toBe('list')
+ ->and($screen->slots)->toBe(['header.actions', 'before', 'after'])
+ ->and($screen->rowSlots)->toBe(['row.actions']);
+});
+
+it('lets the host add slots after the standard ones, once each', function (): void {
+ $screen = Screen::standard('test.list', 'list')
+ ->slots('filters', 'before')
+ ->rowSlots('row.badges');
+
+ expect($screen->slots)->toBe(['header.actions', 'before', 'after', 'filters'])
+ ->and($screen->rowSlots)->toBe(['row.actions', 'row.badges']);
+});
+
+it('rejects a slot name outside the pattern, or one declared as both kinds', function (Closure $declare): void {
+ expect(fn () => $declare(Screen::make('test.screen')))->toThrow(InvalidArgumentException::class);
+})->with([
+ 'uppercase' => fn (Screen $screen): Screen => $screen->slots('Before'),
+ 'a space' => fn (Screen $screen): Screen => $screen->slots('a b'),
+ 'empty row slot' => fn (Screen $screen): Screen => $screen->rowSlots(''),
+ 'both kinds' => fn (Screen $screen): Screen => $screen->slots('row.actions')->rowSlots('row.actions'),
+]);
+
+it('rejects an unknown kind', function (): void {
+ expect(fn () => Screen::make('test.screen')->kind('grid'))->toThrow(InvalidArgumentException::class)
+ ->and(fn () => Screen::standard('test.screen', 'grid'))->toThrow(InvalidArgumentException::class);
+});
+
+it('keeps the built-in tabs in order, with their labels and icons', function (): void {
+ $screen = Screen::make('test.screen')->tabs([
+ ['key' => 'members', 'label' => 'Members', 'icon' => 'users'],
+ ['key' => 'teams', 'label' => 'Teams'],
+ ]);
+
+ expect(array_map(fn (TabDefinition $tab): array => [$tab->key, $tab->label, $tab->icon], $screen->tabs))->toBe([
+ ['members', 'Members', 'users'],
+ ['teams', 'Teams', 'squares-2x2'],
+ ]);
+});
+
+it('falls back to the synthetic overview tab when there are no built-in tabs', function (): void {
+ $screen = Screen::make('test.screen')->tabs([]);
+
+ expect(array_map(fn (TabDefinition $tab): string => $tab->key, $screen->tabs))->toBe(['overview']);
+});
+
+it('rejects a built-in tab without a valid key, or the same key twice', function (array $tabs): void {
+ expect(fn () => Screen::make('test.screen')->tabs($tabs))->toThrow(InvalidArgumentException::class);
+})->with([
+ 'no key' => [[['label' => 'Members']]],
+ 'bad key' => [[['key' => 'Members']]],
+ 'twice' => [[['key' => 'members'], ['key' => 'members']]],
+]);
+
+it('reserves tab keys without making them tabs, once each and in order', function (): void {
+ $screen = Screen::make('test.screen')->tabs([['key' => 'members']]);
+
+ expect($screen->reserved)->toBe([])
+ ->and($screen->reserve('secrets', 'audit')->reserve('secrets', 'members'))->toBe($screen)
+ ->and($screen->reserved)->toBe(['secrets', 'audit', 'members'])
+ ->and(array_map(fn (TabDefinition $tab): string => $tab->key, $screen->tabs))->toBe(['members']);
+});
+
+it('rejects a reserved key outside the key pattern', function (string $key): void {
+ expect(fn () => Screen::make('test.screen')->reserve('fine', $key))
+ ->toThrow(InvalidArgumentException::class, "[{$key}]");
+})->with(['Upper', 'a b', '', '.dot', '-dash', "x\n"]);
+
+it('remembers the default tab and the record', function (): void {
+ $record = new class extends Model {};
+ $screen = Screen::make('test.screen')->defaultTab('teams')->record($record);
+
+ expect($screen->defaultTab)->toBe('teams')
+ ->and($screen->record)->toBe($record);
+});
+
+it('answers permissions through the access closure, and denies them without one', function (): void {
+ $request = Request::create('/');
+ $record = new class extends Model {};
+ $seen = [];
+
+ $screen = Screen::make('test.screen')->access(function (string $permission, Request $given, ?Model $model) use (&$seen): bool {
+ $seen = [$permission, $given, $model];
+
+ return $permission === 'granted';
+ });
+
+ expect($screen->permits('granted', $request, $record))->toBeTrue()
+ ->and($seen)->toBe(['granted', $request, $record])
+ ->and($screen->permits('denied', $request, $record))->toBeFalse()
+ ->and(Screen::make('test.screen')->permits('granted', $request, $record))->toBeFalse();
+});
+
+it('refuses writes to its state from outside', function (string $property, mixed $value): void {
+ $screen = Screen::make('test.screen');
+
+ expect(fn () => $screen->{$property} = $value)->toThrow(Error::class);
+})->with([
+ 'key' => ['key', 'other.screen'],
+ 'package' => ['package', 'other'],
+ 'record' => ['record', null],
+ 'kind' => ['kind', 'list'],
+ 'tabs' => ['tabs', []],
+ 'slots' => ['slots', []],
+ 'rowSlots' => ['rowSlots', []],
+ 'reserved' => ['reserved', []],
+]);
+
+it('keeps the access closure private', function (): void {
+ $screen = Screen::make('test.screen')->access(fn (): bool => true);
+
+ expect(fn () => $screen->access)->toThrow(Error::class);
+});
diff --git a/tests/Unit/Screens/SectionDefinitionTest.php b/tests/Unit/Screens/SectionDefinitionTest.php
new file mode 100644
index 0000000..3ab1d40
--- /dev/null
+++ b/tests/Unit/Screens/SectionDefinitionTest.php
@@ -0,0 +1,118 @@
+key)->toBe('acme.summary')
+ ->and($section->label)->toBe('acme.summary')
+ ->and($section->view)->toBeNull()
+ ->and($section->component)->toBeNull()
+ ->and($section->permission)->toBeNull()
+ ->and($section->public)->toBeFalse();
+});
+
+it('has no icon', function (): void {
+ expect(property_exists(SectionDefinition::class, 'icon'))->toBeFalse()
+ ->and(method_exists(SectionDefinition::class, 'icon'))->toBeFalse();
+});
+
+it('is configured through fluent setters', function (): void {
+ $section = SectionDefinition::make('acme.summary');
+
+ expect($section->label('Summary'))->toBe($section)
+ ->and($section->component('acme::summary'))->toBe($section)
+ ->and($section->permission('summary.view'))->toBe($section)
+ ->and($section->resolve(fn (): array => []))->toBe($section)
+ ->and($section->authorize(fn (): bool => true))->toBe($section)
+ ->and($section->public())->toBe($section);
+
+ expect($section->label)->toBe('Summary')
+ ->and($section->component)->toBe('acme::summary')
+ ->and($section->permission)->toBe('summary.view')
+ ->and($section->public)->toBeTrue();
+});
+
+it('renders with either a view or a component, never both', function (): void {
+ $section = SectionDefinition::make('acme.summary')->component('acme::summary');
+
+ $section->view('acme::summary');
+
+ expect($section->view)->toBe('acme::summary')
+ ->and($section->component)->toBeNull();
+
+ $section->component('acme::summary');
+
+ expect($section->component)->toBe('acme::summary')
+ ->and($section->view)->toBeNull();
+});
+
+it('refuses writes to its state from outside', function (string $property, mixed $value): void {
+ $section = SectionDefinition::make('acme.summary');
+
+ expect(fn () => $section->{$property} = $value)->toThrow(Error::class);
+})->with([
+ 'key' => ['key', 'other'],
+ 'label' => ['label', 'Other'],
+ 'view' => ['view', 'other'],
+ 'component' => ['component', 'other'],
+ 'permission' => ['permission', 'other'],
+ 'public' => ['public', true],
+]);
+
+it('keeps its closures private', function (string $property): void {
+ $section = SectionDefinition::make('acme.summary')->resolve(fn (): array => [])->authorize(fn (): bool => true);
+
+ expect(fn () => $section->{$property})->toThrow(Error::class);
+})->with(['resolver', 'authorize']);
+
+it('passes the screen as the last argument to both closures', function (): void {
+ $screen = Screen::make('test.screen');
+ $request = Request::create('/');
+ $seen = [];
+
+ $section = SectionDefinition::make('acme.summary')
+ ->authorize(function (Request $given, ?Model $model, Screen $last) use (&$seen): bool {
+ $seen['authorize'] = [$given, $model, $last];
+
+ return true;
+ })
+ ->resolve(function (?Model $model, Screen $last) use (&$seen): array {
+ $seen['resolve'] = [$model, $last];
+
+ return [];
+ });
+
+ $section->allows($request, null, $screen, null);
+ $section->resolveData(null, $screen);
+
+ expect($seen['authorize'])->toBe([$request, null, $screen])
+ ->and($seen['resolve'])->toBe([null, $screen]);
+});
+
+it('decides visibility by permission, closure or public', function (): void {
+ $screen = Screen::make('test.screen');
+ $request = Request::create('/');
+ $access = fn (string $permission): bool => $permission === 'granted';
+
+ expect(SectionDefinition::make('a')->allows($request, null, $screen, $access))->toBeFalse()
+ ->and(SectionDefinition::make('a')->public()->allows($request, null, $screen, $access))->toBeTrue()
+ ->and(SectionDefinition::make('a')->permission('granted')->allows($request, null, $screen, $access))->toBeTrue()
+ ->and(SectionDefinition::make('a')->permission('denied')->allows($request, null, $screen, $access))->toBeFalse()
+ ->and(SectionDefinition::make('a')->permission('granted')->allows($request, null, $screen, null))->toBeFalse()
+ ->and(SectionDefinition::make('a')->authorize(fn (): bool => true)->allows($request, null, $screen, $access))->toBeTrue()
+ ->and(SectionDefinition::make('a')->authorize(fn (): bool => false)->allows($request, null, $screen, $access))->toBeFalse()
+ ->and(SectionDefinition::make('a')->permission('granted')->authorize(fn (): bool => true)->allows($request, null, $screen, $access))->toBeTrue()
+ ->and(SectionDefinition::make('a')->permission('denied')->authorize(fn (): bool => true)->allows($request, null, $screen, $access))->toBeFalse()
+ ->and(SectionDefinition::make('a')->permission('granted')->authorize(fn (): bool => false)->allows($request, null, $screen, $access))->toBeFalse();
+});
+
+it('rejects keys outside the pattern', function (string $key): void {
+ expect(fn () => SectionDefinition::make($key))->toThrow(InvalidArgumentException::class);
+})->with(['Upper', 'a b', 'a/b', '']);
diff --git a/tests/Unit/Screens/TabDefinitionTest.php b/tests/Unit/Screens/TabDefinitionTest.php
new file mode 100644
index 0000000..c68faba
--- /dev/null
+++ b/tests/Unit/Screens/TabDefinitionTest.php
@@ -0,0 +1,111 @@
+key)->toBe('acme.billing')
+ ->and($tab->label)->toBe('acme.billing')
+ ->and($tab->icon)->toBe('squares-2x2')
+ ->and($tab->view)->toBeNull()
+ ->and($tab->component)->toBeNull()
+ ->and($tab->permission)->toBeNull()
+ ->and($tab->public)->toBeFalse();
+});
+
+it('is configured through fluent setters', function (): void {
+ $tab = TabDefinition::make('acme.billing');
+
+ expect($tab->label('Billing'))->toBe($tab)
+ ->and($tab->icon('banknotes'))->toBe($tab)
+ ->and($tab->view('acme::billing'))->toBe($tab)
+ ->and($tab->permission('billing.view'))->toBe($tab)
+ ->and($tab->resolve(fn (): array => []))->toBe($tab)
+ ->and($tab->authorize(fn (): bool => true))->toBe($tab)
+ ->and($tab->public())->toBe($tab);
+
+ expect($tab->label)->toBe('Billing')
+ ->and($tab->icon)->toBe('banknotes')
+ ->and($tab->view)->toBe('acme::billing')
+ ->and($tab->permission)->toBe('billing.view')
+ ->and($tab->public)->toBeTrue();
+});
+
+it('renders with either a view or a component, never both', function (): void {
+ $tab = TabDefinition::make('acme.billing')->view('acme::billing');
+
+ $tab->component('acme::billing-tab');
+
+ expect($tab->component)->toBe('acme::billing-tab')
+ ->and($tab->view)->toBeNull();
+
+ $tab->view('acme::billing');
+
+ expect($tab->view)->toBe('acme::billing')
+ ->and($tab->component)->toBeNull();
+});
+
+it('refuses writes to its state from outside', function (string $property, mixed $value): void {
+ $tab = TabDefinition::make('acme.billing');
+
+ expect(fn () => $tab->{$property} = $value)->toThrow(Error::class);
+})->with([
+ 'key' => ['key', 'other'],
+ 'label' => ['label', 'Other'],
+ 'icon' => ['icon', 'users'],
+ 'view' => ['view', 'other'],
+ 'component' => ['component', 'other'],
+ 'permission' => ['permission', 'other'],
+ 'public' => ['public', true],
+]);
+
+it('keeps its closures private', function (string $property): void {
+ $tab = TabDefinition::make('acme.billing')->resolve(fn (): array => [])->authorize(fn (): bool => true);
+
+ expect(fn () => $tab->{$property})->toThrow(Error::class);
+})->with(['resolver', 'authorize']);
+
+it('passes the screen as the last argument to both closures', function (): void {
+ $screen = Screen::make('test.screen');
+ $request = Request::create('/');
+ $record = new class extends Model {};
+ $seen = [];
+
+ $tab = TabDefinition::make('acme.billing')
+ ->authorize(function (Request $given, ?Model $model, Screen $last) use (&$seen): bool {
+ $seen['authorize'] = [$given, $model, $last];
+
+ return true;
+ })
+ ->resolve(function (?Model $model, Screen $last) use (&$seen): array {
+ $seen['resolve'] = [$model, $last];
+
+ return ['total' => 3];
+ });
+
+ expect($tab->allows($request, $record, $screen, null))->toBeTrue()
+ ->and($tab->resolveData($record, $screen))->toBe(['total' => 3])
+ ->and($seen['authorize'])->toBe([$request, $record, $screen])
+ ->and($seen['resolve'])->toBe([$record, $screen]);
+});
+
+it('accepts keys of lowercase letters, digits, dots, dashes and underscores', function (string $key): void {
+ expect(TabDefinition::make($key)->key)->toBe($key);
+})->with(['acme.billing', 'header.actions', 'a', '123', '007', 'acme_billing-2']);
+
+it('rejects any other key', function (string $key): void {
+ expect(fn () => TabDefinition::make($key))->toThrow(InvalidArgumentException::class);
+})->with([
+ 'uppercase' => 'Acme.billing',
+ 'a space' => 'acme billing',
+ 'a slash' => 'acme/billing',
+ 'empty' => '',
+ 'a leading dot' => '.acme',
+ 'a trailing newline' => "acme\n",
+]);
diff --git a/workbench/app/Atrium/ScreenHost/ScreenHostController.php b/workbench/app/Atrium/ScreenHost/ScreenHostController.php
new file mode 100644
index 0000000..c984591
--- /dev/null
+++ b/workbench/app/Atrium/ScreenHost/ScreenHostController.php
@@ -0,0 +1,97 @@
+group($workbench.'/routes/web.php');
+ Route::getRoutes()->refreshNameLookups();
+ }
+
+ public function detail(Request $request, string $screen = 'test.host'): View
+ {
+ return $this->show($request, Screen::standard($screen, Screen::DETAIL)->record(self::user(10, 'Host record')), []);
+ }
+
+ public function list(Request $request, string $screen = 'test.list'): View
+ {
+ return $this->show($request, Screen::standard($screen, Screen::LIST), [
+ self::user(1, 'Row 1'),
+ self::user(2, 'Row 2'),
+ self::user(3, 'Row 3'),
+ ]);
+ }
+
+ /**
+ * @param list $rows
+ */
+ private function show(Request $request, Screen $screen, array $rows): View
+ {
+ // The host's own authorization comes first, so nothing registered
+ // runs for a viewer it refuses.
+ abort_if(Gate::has('viewScreenHost') && Gate::denies('viewScreenHost'), 403);
+
+ /** @var array> $tabs */
+ $tabs = config('screen-host.tabs', []);
+
+ /** @var list $slots */
+ $slots = config('screen-host.slots', []);
+
+ /** @var list $reserved */
+ $reserved = config('screen-host.reserved', []);
+
+ $screen->tabs($tabs)
+ ->reserve(...$reserved)
+ ->slots(...$slots)
+ ->access(fn (string $permission, Request $request, ?Model $record): bool => Gate::forUser($request->user())
+ ->allows($permission, $record === null ? [] : [$record]));
+
+ return view('workbench::screen-host', [
+ 'resolved' => Atrium::screens()->resolve($screen, $request),
+ 'rows' => $rows,
+ ]);
+ }
+
+ /**
+ * A keyed record that needs no database.
+ */
+ private static function user(int $id, string $name): User
+ {
+ return new User()->forceFill(['id' => $id, 'name' => $name]);
+ }
+}
diff --git a/workbench/app/Atrium/ScreenHost/ScreenHostPlugin.php b/workbench/app/Atrium/ScreenHost/ScreenHostPlugin.php
new file mode 100644
index 0000000..2a82466
--- /dev/null
+++ b/workbench/app/Atrium/ScreenHost/ScreenHostPlugin.php
@@ -0,0 +1,58 @@
+route('test.host')
+ ->icon(Icons::svg('document-text'))
+ ->group('Screen host')
+ ->sort(10),
+
+ NavItem::make('List screen')
+ ->route('test.list')
+ ->icon(Icons::svg('table-cells'))
+ ->group('Screen host')
+ ->sort(20),
+ ];
+ }
+
+ public function navigationGroups(): array
+ {
+ return [
+ NavGroup::make('Screen host')->icon(Icons::svg('squares-2x2'))->sort(90),
+ ];
+ }
+}
diff --git a/workbench/app/Providers/WorkbenchServiceProvider.php b/workbench/app/Providers/WorkbenchServiceProvider.php
index 209aad7..274331e 100644
--- a/workbench/app/Providers/WorkbenchServiceProvider.php
+++ b/workbench/app/Providers/WorkbenchServiceProvider.php
@@ -9,6 +9,7 @@
use RefactorCircus\Atrium\Facades\Atrium;
use Workbench\App\Atrium\DemoData;
use Workbench\App\Atrium\DemoPlugin;
+use Workbench\App\Atrium\ScreenHost\ScreenHostPlugin;
use Workbench\App\Http\Middleware\SignInWorkbenchUser;
use Workbench\App\Models\User;
@@ -37,8 +38,10 @@ public function boot(): void
$this->loadViewsFrom(__DIR__.'/../../resources/views', 'workbench');
// Installed packages are discovered from their composer.json; the
- // workbench app is the host, so it registers its plugin explicitly.
+ // workbench app is the host, so it registers its plugins explicitly.
+ // The screen host's pages are the screen-extensions test screens.
Atrium::plugin(DemoPlugin::class);
+ Atrium::plugin(ScreenHostPlugin::class);
// The workbench dashboard is open so `composer serve` is usable
// without logging in. A real application defines a real gate.
diff --git a/workbench/resources/views/screen-host.blade.php b/workbench/resources/views/screen-host.blade.php
new file mode 100644
index 0000000..202cff5
--- /dev/null
+++ b/workbench/resources/views/screen-host.blade.php
@@ -0,0 +1,56 @@
+{{--
+ The screen-extensions test host. `header.actions` always renders; with a
+ registered tab open its panel replaces the page content, and the other
+ slots render only while a built-in tab is open.
+--}}
+@php($screen = $resolved->screen)
+
+
+
+
+
+
+
+
+
+
+
+
+ @if ($resolved->openRegisteredTab !== null)
+
+ @else
+
+
+ @if ($screen->kind === \RefactorCircus\Atrium\Domains\Screens\Data\Screen::DETAIL)
+
+
+ {{ $screen->record?->name }}: the {{ $resolved->openTab }} tab.
+
+
+
+
+ @else
+
+
+
+ Name
+ Actions
+
+
+
+ @foreach ($rows as $row)
+
+ {{ $row->name }}
+
+
+
+
+ @endforeach
+
+ @endif
+
+
+ @endif
+
diff --git a/workbench/routes/web.php b/workbench/routes/web.php
index 147cedf..62c6110 100644
--- a/workbench/routes/web.php
+++ b/workbench/routes/web.php
@@ -1,7 +1,18 @@
where('screen', '[a-z0-9.-]+')
+ ->name('test.host');
+
+Route::get('test/list/{screen?}', [ScreenHostController::class, 'list'])
+ ->where('screen', '[a-z0-9.-]+')
+ ->name('test.list');