middag-io/ui
Larablocks Analysis
middag-io/ui works with any PHP project: the latest release (v1.15.0, Nov 24, 2026) doesn't depend on Laravel.
Recommendation checks
Solid choiceSolid choice: maintained and up to date, meets 2 of 3 checks; below the bar for Recommended on use.
- Released in the last 12 months (Nov 24, 2026)
- 11,429 downloads a month (at least 10,000)
- 0 GitHub stars (needs 100)
State
Actively maintained- Last stable release: Nov 24, 2026.
- Latest pre-release: v2.0.0-rc.2, Nov 25, 2026.
- 49 releases in the last 12 months.
- First released: May 12, 2026.
- Monthly downloads: 11,429, up 1243% from six months ago.
- 3 open issues on GitHub.
Data from Packagist and GitHub, checked by Larablocks on Dec 1, 2026.
| Install | |
|---|---|
composer require middag-io/ui |
|
| Latest Version: | v1.15.0 |
| PHP: | ^8.3 |
| License: | Apache-2.0 |
| Last Updated: | Dec 1, 2026 |
| Links: | GitHub · Packagist |
middag-io/ui
Transport-agnostic PHP contract builders — describe a page once, render it anywhere.
Transport-agnostic PHP contract builder system for MIDDAG's contract-driven UI. Produces PageContract (JSON) consumed by @middag-io/react via Inertia or any transport layer.
Zero external dependencies. PHP 8.3+ only.
Open source — Apache-2.0. The foundation layer of the MIDDAG framework stack (ui → framework → moodle / wordpress adapters; @middag-io/react on the client). Host-agnostic and transport-agnostic by design: this package knows nothing about Moodle, WordPress, or any transport — it only describes pages.
[!NOTE] Documentation: https://docs.middag.dev/framework/explanation/ui/overview — the hub is the reference; this README is a summary.
What It Does
Pages in the MIDDAG stack are described by a PageContract — a JSON document declaring shell, page metadata, layout template, regions, and blocks. This library provides the PHP side: builders that produce that document. The React side (@middag-io/react) consumes it to render the actual UI.
This means PHP never renders HTML for pages — it declares structure, and React renders.
Features
| Feature | What you get |
|---|---|
| Transport-agnostic contracts | Builders produce JsonSerializable → PageContract (JSON). No Inertia/transport dependency; works with any wire. |
| Zero dependencies | PHP ^8.3 only. Consumers inherit no transitive packages. |
| Host-agnostic | No Moodle / WordPress / mform / capability coupling. Host-specifics live in the adapter, never here. tests/Architecture/HostVocabularyTest.php scans src/ and schema/, comments included, for host vocabulary. |
| 3 levels of composition | Convention (CrudBuilder) → convention + overrides → free composition (PageBuilder). |
| CRUD convention builder | index/create/edit/show pages from an entity class: i18n titles, filters, search, per-action capability gating. |
| Block types | denseTable, formPanel, detailPanel, metricCard, emptyState, statusStrip, activityTimeline, markdownPanel, cardGrid, actionGrid, linkList, chart, tabs — via BlockBuilder or the fluent RegionBuilder. |
| Typed value objects | final readonly + JsonSerializable. camelCase wire keys (the exceptions are csrf_token and the snake_case condition keys visible_when, hidden_when, disabled_when, required_when and loading_when, plus disabled_reason_field), omit-empty payloads, immutable witters. |
| Partial fragments | Server-push slices: Fragment, RegionUpdate, ActionResult (push + pull). Provisional: @internal until a first-party client reads them. |
| Navigation tree | 3-level NavigationNode (group / section / item), capability-filtered, drill-down, collapsible and badge are data hints a client shell may honour (a shell that does not implement them renders the tree flat), delivered as a NavigationTree (tree, activeKey, footer). |
| Shared props | SharedProps describes the props shared with every page (auth, theme, flash, errors, csrf_token, locale, scope, navigation), published as schema/shared-props.json. |
| Form system | Contracts + VOs (FieldDefinition, Condition, FormState, Section, Group). Renderers live in adapters. |
| i18n intents | Translatable {key, domain, params}. The library never resolves translations — the client does. |
| Quality gates | CI runs the test suite, PHPStan level 6, php-cs-fixer and Rector (dry run) on every pull request. No coverage threshold is enforced. |
Three Levels of Composition
Level 1 — Convention (CrudBuilder)
Full CRUD pages from an entity class name:
// index page with default columns, actions, pagination
$contract = PageBuilder::crud(Invoice::class)->build('index', [
'rows' => $invoices,
'pagination' => ['page' => 1, 'perPage' => 25, 'total' => 100, 'lastPage' => 4],
]);
Level 2 — Convention + Overrides (CrudBuilder)
Customize columns, actions, layout without leaving the convention:
$contract = CrudBuilder::for(Invoice::class, slug: 'invoices')
->without('show')
->columns(['number', 'status', 'amount', 'due_date'])
->column('status', fn (array &$col) => $col['variant'] = 'badge')
->filters([new FilterDefinition(key: 'status', label: 'Status')])
->searchable() // or mark a column searchable in its configurator
->sort('due_date', 'asc')
->perPage(50)
->i18n(domain: 'local_app') // titles as i18n intent; falls back to literal nouns
->label('Invoice', 'Invoices') // or override the noun explicitly
->build('index', ['rows' => $invoices]);
Row actions take convention names or ready actions with any target, and
page() hands over the underlying PageBuilder for anything the convention
does not cover (shell, subtitle, extra regions, the editable panel). Use
toProps() instead of build() when the page declares settings that travel
next to the contract, such as the editable panel:
$props = CrudBuilder::for(Agent::class, slug: 'agents')
->columns(['name', 'role', 'workload'])
->column('role', fn (array &$col) => $col['variant'] = ColumnVariant::Badge)
->rowActions([new Action(id: 'edit', label: 'Edit', target: ActionTarget::panel()), 'delete'])
->rowHref('/agents/{id}')
->page(fn (PageBuilder $page) => $page
->layout('dashboard') // renders the `metrics` region above `content`
->subtitle('Who answers tickets')
->region('metrics', fn (RegionBuilder $r) => $r->metricCard('agents', 12, 'Agents'))
->editablePanel('/agents/{id}/panel'))
->toProps('index', ['rows' => $agents]); // ['contract' => PageContract, 'editablePanel' => ...]
The class basename is treated as a singular noun. The library never
fabricates a plural: the slug defaults to the singular, and for(class, slug:)
overrides it for a plural URL. Titles resolve via ->label() (explicit) →
<key>_plural i18n convention → singular fallback; create/edit verbs are
emitted as crud_create/crud_edit intents in a shared UI domain.
Shells
A shell is the application frame around the page. PageBuilder defaults to product, the default application frame every client registers, so a page that never calls shell() gets it. Call shell() to pick another frame, such as immersive.
Layouts
A layout is a template plus named regions. The client renders four templates: stack (the default), sidebar (regions main and aside), dashboard (a metrics region above content) and wizard. Every builder in this library emits one of them.
Level 3 — Free Composition (PageBuilder)
Full control over every block and region:
$contract = PageBuilder::page('invoices.show')
->title('Invoice #1234')
->subtitle('Due Jan 31')
->shell('product')
->layout('sidebar')
->breadcrumbs(fn ($bc) => $bc->item('Invoices', '/invoices')->current('#1234'))
->actions([
PageBuilder::action('pay', 'Mark Paid', ActionTarget::request('/invoices/1234/pay'), ActionIntent::Primary),
])
->region('main', [
BlockBuilder::detailPanel('invoice.detail', $sections),
])
->region('aside', [
BlockBuilder::activityTimeline('invoice.activity', $groups),
])
->build();
Page Props
A page response carries the contract plus the page-level settings that travel next to it: contract, overlay, help, inspector and editablePanel. toProps() builds them, and schema/page-props.json publishes their shape (root PageProps). The open-source client renders overlay. It exports the editable panel components, but none of its shells mounts them, so editablePanel is rendered by a shell that does. help and inspector are the open layer that carries data to a commercial client (both also travel inside the contract). The root is open, so a host can merge its own props into the same object.
return $this->inertia('Page', PageBuilder::page('orders.create')
->title('New Order')
->overlay()
->help('Creating an order', 'Fill in the details below.')
->inspector('/api/products/{id}')
->toProps());
// toProps() returns: ['contract' => ..., 'overlay' => true, 'help' => [...], 'inspector' => ...]
Partial Fragments (server push)
Provisional.
Fragment,RegionUpdate,ActionResult,FragmentKindandRegionUpdateModeare@internaland outside the support promise until a first-party client reads them. The schema keeps publishing their shapes, marked as provisional. See "Provisional wire shapes" inAPI-STABILITY.md.
A page can be served two ways, and both share one envelope contract (ContractEnvelopeInterface, carrying the same version):
- Full page in PHP —
PageContractdeclares the whole page (shell, layout, regions, blocks). The default. - Page owned by the client, partial props from PHP — when React owns the layout, the server returns a
Fragment: one ready, self-describing slice of the contract (a block, a table, a region update, notifications) plus its routingkind. A fragment is a node of the contract with its own header, not a smaller page.
use Middag\Ui\Region\Fragment;
use Middag\Ui\Region\RegionUpdate;
// after a filter/paginate, swap a region's content without reloading the page
$fragment = Fragment::region(RegionUpdate::replace('orders', $block1, $block2));
// {version: '2', kind: 'region', payload: {region: 'orders', mode: 'replace', blocks: [...]}}
RegionUpdate modes: replace / append / prepend / remove (by key) / update (match by key).
Mutations return an ActionResult, which carries both update strategies — push and pull:
use Middag\Ui\Action\ActionResult;
return new ActionResult(
fragments: [Fragment::table($tableConfig)], // push: server already built the fresh piece
refreshBlocks: ['sidebar'], // pull: client re-fetches these keys itself
);
Block Types
Static factories in BlockBuilder:::
| Method | React Component |
|---|---|
BlockBuilder::denseTable($key, $columns, $rows) |
Dense data grid |
BlockBuilder::formPanel($key, $action, $method, $schema, $values) |
Form panel |
BlockBuilder::detailPanel($key, $sections) |
Read-only detail view |
BlockBuilder::metricCard($key, $value, $label, $delta, $icon, $href) |
KPI card |
BlockBuilder::emptyState($key, $variant, $description, $cta, $icon, $ctaHref) |
Empty state |
BlockBuilder::statusStrip($key, $items, $tone) |
Status bar |
BlockBuilder::activityTimeline($key, $groups, $hasMore, $loadMoreHref) |
Activity feed |
BlockBuilder::markdownPanel($key, $content, $maxHeight) |
Markdown body |
BlockBuilder::cardGrid($key, $columns, $rows, $variant) |
Card grid |
BlockBuilder::actionGrid($key, $items, $flash) |
Action card grid |
BlockBuilder::linkList($key, $items) |
Link list |
BlockBuilder::chart($key, $type, ChartSeries[], ...) |
Chart (ChartType enum) |
BlockBuilder::tabs($key, Tab[]) |
Tabs container |
Or via RegionBuilder fluent API inside a ->region() closure. Each method
mirrors its BlockBuilder factory one-to-one, so the same block type produces
an identical descriptor whichever entry point you use:
->region('content', function ($r) {
$r->metricCard('revenue', 42000, 'Revenue', delta: '+8%')
->denseTable('orders', ['id', 'total'], $rows)
->emptyState('no_results', variant: 'no_results');
})
Navigation
NavigationNode is the @api value object for nav tree entries. It serializes to the NavigationNode shape of the published schema, which a client's navigation component reads from the navigation shared prop. Its key has one to three dot-separated segments: one for a group, two for a section, three for an item.
$node = new NavigationNode(
key: 'audience.segments.index',
label: 'Segments',
icon: 'users',
href: '/segments',
active: true,
weight: 10,
);
NavigationNode also takes the optional entityType (an open string the client interprets), badgeEmphasis (an Emphasis: subtle or strong), tone (a Tone: neutral, info, success, warning or danger) and target (an HTML link target such as _blank), each omitted when unset. Emphasis and Tone are open vocabularies: a client shows an unknown value as subtle or neutral, and a colour outside them comes from the theme, never from a free string. The constructor rejects an href with a javascript:, data: or vbscript: scheme.
Hosts build nodes through their implementation of NavigationRegistryInterface. Labels are a string or a Translatable, stored as given; the client resolves a Translatable. entityType, badgeEmphasis and tone work on every level; target and href are for items. An item has either a route or an external href (an absolute http:// or https:// URL), never both:
use Middag\Ui\Shared\Enum\Tone;
use Middag\Ui\Shared\ValueObject\Translatable;
$registry->group('audience', Translatable::of('nav.audience', 'app'), icon: 'users', tone: Tone::Info)
->section('audience.segments', 'Segments')
->item('audience.segments.index', 'All segments', 'segments.index')
->item('audience.segments.docs', 'Docs', null, href: 'https://docs.example', target: '_blank');
NavigationRegistryInterface::build() returns a NavigationTree. It always serializes three keys: tree (the main node list), activeKey (the dot-notation key of the active node, '' when none is active) and footer (the secondary node list).
use Middag\Ui\Navigation\NavigationTree;
$navigation = new NavigationTree(tree: [$node], activeKey: 'audience.segments.index');
// {tree: [...], activeKey: 'audience.segments.index', footer: []}
Shared Props
SharedProps describes the props shared with every page, next to the page contract. schema/shared-props.json publishes it, with the same x-contract-version as the page and fragment bundles. Every slot is optional and a null slot is omitted from the wire; scope is always emitted. The root is open, so hosts and products can add their own keys; the typed slots stay strict.
| Slot | Type | Wire shape |
|---|---|---|
auth |
SharedAuth |
Flat: id (string), name, optional email, avatarUrl, roles; capabilities (list<string>, always emitted); optional logoutUrl. |
theme |
SharedTheme |
Optional appearance (ThemeMode) and a strings map, {} when empty. |
flash |
FlashMessages |
At most one string per key; the only keys are success, error, info, warning. Empty and whitespace-only values are dropped; fromArray() also drops other keys and non-string values. {} when empty. |
errors |
FormErrors or FormErrorBags |
With the X-Inertia-Error-Bag header, bag name to a FormErrors map; otherwise field name to a message, a structured message or a list of either (string | FieldMessage | (string|FieldMessage)[]); _ is form-level. {} when empty. |
csrf_token |
string | |
locale |
string | |
scope |
object | Open object, {} when empty. |
navigation |
NavigationTree |
See Navigation. |
use Middag\Ui\Shared\ValueObject\FlashMessages;
use Middag\Ui\Shared\ValueObject\Identity;
use Middag\Ui\Shared\ValueObject\SharedAuth;
use Middag\Ui\Shared\ValueObject\SharedProps;
$shared = new SharedProps(
auth: new SharedAuth(new Identity(id: '42', name: 'Ada'), capabilities: ['orders.view']),
flash: new FlashMessages(success: 'Saved.'),
navigation: $navigation,
);
// {auth: {id: '42', name: 'Ada', capabilities: ['orders.view']}, flash: {success: 'Saved.'}, scope: {}, navigation: {...}}
ui defines these shapes only; filling them is the host adapter's job. Identity, capabilities, theme and locale travel in the shared props.
Form System
This library provides contracts and value objects only — renderers live in middag-io/framework (Inertia) and the host adapters.
Contracts
| Interface | Role |
|---|---|
FormInterface |
schema() → hydrate() → validate() → validated() |
FieldInterface |
toDefinition(): FieldDefinition — produces the boundary object |
FormRendererInterface |
target(): RenderTarget + render(Form): RendererOutput |
LayoutElementInterface |
id() + children() — Section and Group implement this |
Value Objects
| Class | Notes |
|---|---|
FieldDefinition |
Immutable boundary object between DSL and renderers. No JsonSerializable — renderers map manually. |
Condition |
field + operator (ConditionOperator enum) + value + kind. Kinds: visible_when, hidden_when, required_when, disabled_when. |
FormState |
Immutable readonly VO. withValues() / withErrors() return a new instance. Carries values, errors, submitted. |
RendererOutput |
Static factories ::html() and ::props() for the two render targets. html() carries a body a renderer downstream produced, as opaque data; no ui contract produces markup. |
FileValue |
A file field value: url plus optional name, size, type, id and uploadToken, an opaque string the host adapter maps to its pending-upload storage. |
Layout Primitives
$section = Section::of('personal')
->label(Translatable::of('personal_info_section', 'forms')) // or a literal string
->fields($nameField, $emailField, Group::of('phone')->fields($countryCode, $number));
Section::label() takes a string|Translatable like every other label in the
contract; labelData() serializes it via Label (a {key, domain} payload for
an intent, a raw string for a literal).
Field Types (FieldType enum)
A backed enum of field types (Text, Textarea, Select, Date,
Richtext, Time, Autocomplete, Tags, …; a new case ships in a MINOR release) — see src/Shared/Enum/FieldType.php
for the full catalogue.
Adding a type requires a new field class, matching renderer-side mappers, and the client component — most of which live downstream.
Table Builder
Fluent API for producing TableConfig consumed by dense table blocks:
$config = TableBuilder::make()
->column('name', 'Name', ['sortable' => true, 'searchable' => true])
->column('amount', 'Amount', ['sortable' => true, 'format' => ValueFormat::Currency, 'formatOptions' => ['currency' => 'BRL']])
->filter('status', 'Status', FilterType::Select, [
['value' => 'active', 'label' => 'Active'],
['value' => 'inactive', 'label' => 'Inactive'],
])
->rowAction(PageBuilder::action('edit', 'Edit', ActionTarget::link('/invoices/{id}/edit')))
->bulkAction(PageBuilder::action('delete', 'Delete', ActionTarget::request('/invoices/bulk/delete'), ActionIntent::Danger))
->options(new TableDisplayOptions(perPage: 25, sortColumn: 'name', selectable: true))
->build();
Installation
Requires PHP ^8.3. Install via Composer:
composer require middag-io/ui
Development
composer install
composer test # PHPUnit
composer check # style + rector + stan + schema drift
composer fix # style + rector (apply)
composer lint:php83 # parse every file (incl. tooling configs) on real PHP 8.3 (Docker)
The dev toolchain may run a newer PHP than the supported floor (^8.3). Newer
syntax such as new X()->method() parses on 8.4 but is a fatal error on 8.3, so
composer check alone will not catch it. Two guards keep the floor honest:
composer lint:php83 runs php -l under a real PHP 8.3 interpreter over the
source, tests, and the .php-cs-fixer.dist.php / .php-rector.php configs; and
the static checks of the CI run on PHP 8.3, the floor. PHPStan targets the
floor (phpVersion: 80300); it does not catch syntax-level issues, which is
the lint's job. A second PHPStan pass targets the ceiling (phpVersion: 80600,
composer check:stan:ceiling) and runs in the PHP 8.6 CI job. CI runs the tests
on PHP 8.3 to 8.6, and a highest job resolves the highest dependency versions
on 8.4, 8.5 and 8.6 without the platform pin.
Git hooks configured automatically via post-install-cmd. commit-msg enforces Conventional Commits.
type(scope): description
Types: feat, fix, chore, docs, style, refactor, perf, test, build, ci, revert
Releases managed by release-please.
Versioning
Support starts at 2.0.0; the 1.x line is pre-stable and unsupported, and the cut to 2.0.0 is clean. From 2.0.0, the open-source middag-php-* libraries form one version family that shares only the MAJOR: MINOR and PATCH releases are per library, a patch carries fixes only and a minor never breaks. Require middag-io/ui with ^2.0, or with the MINOR whose features you use. The PHP API and the wire JSON follow the same rules; the wire evolution and enum policy are in API-STABILITY.md. Support covers the @api surface only. Rules: https://docs.middag.dev/libraries/reference/versioning-and-compatibility. Details: API-STABILITY.md and CONTRIBUTING.md §Versioning.
Help and status
- Status: the 1.x line is pre-stable and unsupported; support starts at 2.0.0. See https://docs.middag.dev/libraries/reference/versioning-and-compatibility
- Questions and bugs: https://github.com/middag-io/middag-php-ui/issues
- Changes: see
CHANGELOG.md. - Security reports: see
SECURITY.md(do not open a public issue).
Maintenance
These libraries are maintained by MIDDAG for its own products. External issues and pull requests are handled on a best-effort basis. Security reports follow SECURITY.md (contact security@middag.io). For anything else, write to opensource@middag.io. The family versioning policy is at https://docs.middag.dev/libraries/reference/versioning-and-compatibility/
License
Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE.
Copyright 2026 MIDDAG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Contributing
See CONTRIBUTING.md.
Related Packages
Form validation and generation for PHP with custom frontend generators
An elegant Laravel scaffolding for your next single-page application.
Version History
| Version | Released | PHP | License |
|---|---|---|---|
| v1.15.0 | ^8.3 | Apache-2.0 | |
| v1.14.1 | ^8.3 | Apache-2.0 | |
| v1.14.0 | ^8.3 | Apache-2.0 | |
| v1.13.1 | ^8.3 | Apache-2.0 | |
| v1.13.0 | ^8.3 | Apache-2.0 | |
| v1.12.0 | ^8.3 | Apache-2.0 | |
| v1.11.0 | ^8.3 | Apache-2.0 | |
| v1.10.3 | ^8.3 | Apache-2.0 | |
| v1.10.2 | ^8.3 | Apache-2.0 | |
| v1.10.1 | ^8.3 | Apache-2.0 | |
| v1.10.0 | ^8.3 | Apache-2.0 | |
| v1.9.0 | ^8.3 | Apache-2.0 | |
| v1.8.4 | ^8.3 | Apache-2.0 | |
| v1.8.3 | ^8.3 | Apache-2.0 | |
| v1.8.2 | ^8.3 | Apache-2.0 | |
| v1.8.1 | ^8.3 | Apache-2.0 | |
| v1.8.0 | ^8.3 | Apache-2.0 | |
| v1.7.0 | ^8.2 | Apache-2.0 | |
| v1.6.0 | ^8.2 | Apache-2.0 | |
| v1.5.1 | ^8.2 | Apache-2.0 | |
| v1.5.0 | ^8.2 | Apache-2.0 | |
| v1.4.0 | ^8.2 | Apache-2.0 | |
| v1.3.1 | ^8.2 | Apache-2.0 | |
| v1.3.0 | ^8.2 | Apache-2.0 | |
| v1.2.4 | ^8.2 | Apache-2.0 | |
| v1.2.3 | ^8.2 | Apache-2.0 | |
| v1.2.2 | ^8.2 | Apache-2.0 | |
| v1.2.1 | ^8.2 | Apache-2.0 | |
| v1.2.0 | ^8.2 | Apache-2.0 | |
| v1.1.1 | ^8.2 | Apache-2.0 |
Showing the latest 30 of 47. See every release on Packagist
Pre-releases (2)
| Version | Released | PHP | License |
|---|---|---|---|
| v2.0.0-rc.2 | ^8.3 | Apache-2.0 | |
| v2.0.0-rc.1 | ^8.3 | Apache-2.0 |