Repository navigation
Conversation
Adds `@wordpress/build/compile-style`, with `compileStyleFile()` and `compileCss()`, so a package can emit its styles in another form with the same scoped class names the JavaScript build injects at runtime. `compileInlineStyle()` now uses `compileCss()`, and `getSassOptions()` moves next to the shared Sass compiler so both can use it.
Each component PHP can render has a `php/<name>/component.json` with its props and a recipe: the classes it always has, and the classes each variant value adds. The build compiles the package's CSS modules to `build-php/style.css`, resolves the recipes to the same scoped class names React uses, and renders every combination of variants with React as fixtures for the parity tests. Starts with Button.
Behind the `gutenberg-ui-php-components` experiment. `gutenberg_get_ui_component()` validates props against the component's schema, falls back to defaults with `_doing_it_wrong()`, renders the component's PHP template with the classes from its recipe, and enqueues the stylesheet. Button's template matches React's Button with `focusableWhenDisabled` off, so it works without JavaScript. Adds a preview page under Tools.
Checks that PHP renders the same markup as React for every combination of variants, plus a custom class and text that needs escaping, so the recipes and templates can't drift from React without a failing test. Also checks prop validation, escaping and the stylesheet. CI passes the built `packages/ui/build-php` to the PHPUnit jobs.
Button's label is now the content argument of gutenberg_get_ui_component() instead of a prop, so content is never treated like other props. Also fixes recipe lookups for boolean variants, and loads the stylesheet after wp-theme when it's registered.
The preview page now lists each component's default and each variant value on its own, rendered by PHP next to the markup React rendered at build time. The build writes these examples to `build-php/examples.json`, which ships with the plugin so the comparison also works in the plugin zip and Playground. Also documents that screens rendering components should enqueue the styles on `admin_enqueue_scripts`, so they load in the head.
`gutenberg_ui_render_button()` is called by `gutenberg_get_ui_component()`, which validates the props first, so it isn't meant to be called directly.
A plain name refers to the component's own stylesheet, so Button's recipe says is-brand instead of button/style:is-brand. Shared utilities keep the stylesheet:class form, which makes them stand out.
Props are the public contract and the recipe is how each value looks, so they're kept apart. The build now fails if the recipe uses a prop or value that isn't allowed, or misses one, so the two can't drift.
🤖 PR meta 🤖🎉 PropsIf you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. Props Bot commandsYou can trigger Props Bot actions by commenting on this PR:
Updated as activity occurs, without notifying anyone named here. Add the 📦 Bundle sizeSize Change: 0 B Total Size: 8.64 MB
⚡ PerformanceShow the resultsClient side metrics exclude the server response time. front-end-block-theme
front-end-classic-theme
media-processing
media-upload
post-editor
site-editor
🏁 Flaky testsSome tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information. Navigates the list via UP/DOWN arrow keys from action buttons in
|
| esc_attr( $props['type'] ), | ||
| esc_attr( implode( ' ', $classes ) ), | ||
| $props['disabled'] ? ' data-disabled="" disabled=""' : '', | ||
| esc_html( $content ) |
There was a problem hiding this comment.
esc_html() preserves existing HTML entities (eg, passing the plain-text label A & B displays A & B, while React displays the original A & B).
Can we preserve literal entity text here and add it to the parity fixtures?
There was a problem hiding this comment.
Thanks Marco! And sorry for the repeat, got lost when I rebuilt the base. Fixed c26047f
There was a problem hiding this comment.
Reflecting on where this ended up with gutenberg_ui_components_esc_plain_text and putting the decode requirement on the consumer, I wonder if we really need to preserve React parity here, or if we can lean on more conventional and well-understood functions and their behavior like esc_attr and esc_html, particularly in a sensitive context like escaping.
In practice, with PHP & JavaScript call-sites, it's not really clear to me when the described issue would ever come up.
If the concern is contexts where React components are initialized using props passed from PHP as in #85941 interactive components (specifically gutenberg_ui_components_wrap_interactive), then maybe we can address that on the other end of things by decoding content there?
There was a problem hiding this comment.
That's a fair point. Like you said it's hard to see when the issue would actually come up. I think the WP convention also has some advantage of familiarity, which matters for escaping.
@ciampo does this work for you too? I'll switch back to esc_html() esc_attr() for now and we can discuss the props case in #85941
# Conflicts: # packages/wp-build/lib/compile-inline-style.mjs # packages/wp-build/lib/test/compile-inline-style.test.js
esc_html() and esc_attr() leave existing entities alone, so a label of `A & B` displayed as `A & B`, while React displays it as written. Escape the button's label and class the way React does, and add a parity fixture and a regression test for it.
…independent of order
left a comment
There was a problem hiding this comment.
Despite the number of comments in my review, I'm rather optimistic about this direction overall 👍 The parity tests in particular, combined with the props validation, provides some good assurance that component implementations could be kept in sync between React and PHP. From a maintenance standpoint, that feels like it'll be the bigger focus: not so much the code implementations themselves and what they contain, but the triggers for when they should be updated.
| * @param {Array} variants `[ prop, values ]` pairs. | ||
| * @return {Object[]} Combinations, as props. |
There was a problem hiding this comment.
Minor: I think we could author this file as TypeScript .ts (leveraging native type-stripping), which would allow us to use better typings. Personally I find that Array and Object are anti-patterns, both because they don't mean what we think they do (despite our lint rules enforcing the uppercase) and because we can be more precise with the shape of the object, particularly for objects and tuples.
There was a problem hiding this comment.
Agreed, makes sense. I'd leave the move to ts for a follow-up so this PR doesn't grow, if that works for you.
| // Props are the public contract and the recipe is how each value looks, so | ||
| // they're kept apart. Check they agree, so a value can't be added to one | ||
| // and forgotten in the other. | ||
| const checkRecipe = ( { name, props, classes } ) => { |
There was a problem hiding this comment.
What are your thoughts on whether this makes sense here as part of the build process, or separately in e.g. as part of tests or general JSON schema validation tooling.
There was a problem hiding this comment.
What's the coverage story for when a new option is added to the React component? I gather that we don't expect full parity of support for all props, but I wonder if that extends to props that do we support, particularly those with enumerable values (something like intent).
There was a problem hiding this comment.
What are your thoughts on whether this makes sense here as part of the build process, or separately in e.g. as part of tests or general JSON schema validation tooling.
This went away with the class mapping change, since there's no recipe to check anymore 6791e77
What's the coverage story for when a new option is added to the React component?
Right now there isn't one. If react adds a new tone, PHP treats it as invalid and the tests still pass. Maybe the build could compare values from component.json with Reacts? Definitely something that we should take care as a follow-up.
| */ | ||
| async function compileStylesheets() { | ||
| const stylesheets = new Map(); | ||
| const files = await glob( 'src/**/*.module.{css,scss}', { |
There was a problem hiding this comment.
This compiles stylesheets for every component, even if we're only ultimately building a couple of them. Thankfully the built stylesheet only writes with the styles for the components that are used, but I wonder if we could be more efficient here with e.g. building stylesheets on demand. Especially since #85476 added the shared style compiler (which I didn't realize until reviewing this 😄 ). This might also simplify the handling around usedStylesheets.
There was a problem hiding this comment.
Good catch. Now that component.json list the stylesheets each component uses and the build compiles them, usedStylesheets isn't needed anymore
| /** | ||
| * Returns the HTML of a `@wordpress/ui` component. | ||
| * | ||
| * The content is plain text, escaped when rendered. Entities show as written, |
There was a problem hiding this comment.
Just to clarify my understanding of the trade-offs we've arrived at here and in context of your comment at #84036 (comment) : We recognize that "content is plain text, escaped when rendered" is a short-term limitation for the scope of this first step, and that we we'll need to be able to support safely-rendered HTML child content as part of subsequent improvements to support composability. Escaping is the right default, and we expect that "safe HTML" would be a distinctly handled exception to that.
There was a problem hiding this comment.
That's the idea, yes. Escaping stays the default and safe HTML would be an explicit exception. Ideally that would come from Core, with something like the HTML templating in WordPress/wordpress-develop#5949 (once it supports composing HTML)
| // Plus a custom class, and content that needs escaping, so the tests | ||
| // also check that PHP escapes it the way React does. | ||
| const cases = [ | ||
| ...getCombinations( variants ).map( ( values ) => ( { | ||
| props: values, | ||
| content: 'Save changes', | ||
| } ) ), | ||
| { props: { class: 'my-plugin-button' }, content: 'Save changes' }, | ||
| { props: {}, content: 'Save & <continue> "now"' }, | ||
| { | ||
| props: { class: 'is-&' }, | ||
| content: 'A & B … ’', | ||
| }, | ||
| ]; |
There was a problem hiding this comment.
A couple thoughts:
- This build script is doing a lot for different audiences, covering runtime usage, test consumers through fixtures, and the experiments page. Particularly as we work toward making this a more standard feature I'd wonder how we would think about splitting up these concerns. Or perhaps we don't need to run fixtures build for production builds, for example.
- These examples feel pretty targeted to the Button component specifically. While I think it's fair to separate certain concerns as follow-ons (particularly around component composition), I'd expect what's here to cover a breadth of "basic" components. For example, a Spinner component that has no child content would fail tests in this pull request because the tests are assuming that every component has content to be rendered, which isn't really a basic requirement of every component.
There was a problem hiding this comment.
Good points, and good catch with Spinner. I fixed it to pass content only when component.json declares it 12eb22e
Agreed on splitting up the concerns of the build. I'd leave that as a follow-up once the base is merged, if that works for you
| "classes": { | ||
| "base": [ | ||
| "utils/css/global-css-defense:button", | ||
| "utils/css/resets:box-sizing", | ||
| "utils/css/focus:outset-ring--focus-except-active" | ||
| ], | ||
| "variants": { | ||
| "tone": { | ||
| "brand": [ "is-brand" ], | ||
| "neutral": [ "is-neutral" ] | ||
| }, | ||
| "variant": { | ||
| "solid": [ "button", "is-solid" ], | ||
| "outline": [ "button", "is-outline" ], | ||
| "minimal": [ "button", "is-minimal" ], | ||
| "unstyled": [ "is-unstyled" ] | ||
| }, | ||
| "size": { | ||
| "default": [], | ||
| "compact": [ "is-compact" ], | ||
| "small": [ "is-small" ] | ||
| } | ||
| } | ||
| }, |
There was a problem hiding this comment.
Looking at this and how $classes is passed as an argument to the function, I wonder if the recipe is doing more than it needs to in ways that the function could be handling. unstyled is an interesting example where we have to emulate logic for omitting the component's inherent styles.
I wonder if instead it'd be better to keep the recipe focused on its allowlisting behavior, remove the special $classes argument, and handle the logic of class mapping in the function itself.
So something like...
component.json:
{
"styles": [
"button/style",
"utils/css/global-css-defense",
"utils/css/resets",
"utils/css/focus"
],
// ...
}button.php:
function gutenberg_ui_render_button( $props, $content ) {
$styles = gutenberg_ui_components_get_styles( 'button/style' );
$defense = gutenberg_ui_components_get_styles( 'utils/css/global-css-defense' );
$resets = gutenberg_ui_components_get_styles( 'utils/css/resets' );
$focus = gutenberg_ui_components_get_styles( 'utils/css/focus' );
$classes = array_filter(
array(
$defense['button'],
$resets['box-sizing'],
$focus['outset-ring--focus-except-active'],
'unstyled' !== $props['variant'] ? $styles['button'] : '',
$styles[ 'is-' . $props['tone'] ],
$styles[ 'is-' . $props['variant'] ],
// There's no `is-default` class, as in React.
$styles[ 'is-' . $props['size'] ] ?? '',
$props['class'],
)
);
// ...
}There was a problem hiding this comment.
Went back and forth on this becase I was trying to keep the PHP side as thin as possible, with things in the JSON. But in reality, that would make sense if React reads it too, which isn't the case. The suggestion makes sense and I'm moving it into the template 6791e77
If we want React and PHP to share one description of the variants at some point we could think about recipes and changing it.
| * @param string $html HTML. | ||
| * @return array Tokens. | ||
| */ | ||
| private static function normalize_html( $html ) { |
There was a problem hiding this comment.
We could probably simplify these tests a fair bit using assertEqualHTML ?
Aside: I'm co-reviewing this pull request with a local AI agent, and I flagged this as something I vaguely recalled being available for this purpose, and it counter-flagged that it wasn't aware of this function existing and that it could benefit from some project-wide testing context encouraging it 😂
There was a problem hiding this comment.
Nice, I didn't know about it either 😅 Fixed 12eb22e
| function gutenberg_ui_components_print( $html ) { | ||
| echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped |
There was a problem hiding this comment.
Thinking about this and public APIs in general: As I understand, this is a workaround to the fact that if we didn't do this, then each call-site would have to disable the PHPCS rule itself, which feels like it's surfacing a friction point.
I'm also drawn to some of the specific words, "print" here.
What if we followed the established convention for get_-prefixed and get_-omitted functions for HTML-returning and HTML-echoing functions respectively, e.g. get_submit_button and submit_button.
So instead of:
gutenberg_ui_components_print(
gutenberg_get_ui_component( 'button', array( 'type' => 'submit' ), __( 'Save changes', 'gutenberg' ) )
);We'd have:
gutenberg_ui_component( 'button', array( 'type' => 'submit' ), __( 'Save changes', 'gutenberg' ) );And gutenberg_ui_component internally calls gutenberg_get_ui_component and echos it.
There was a problem hiding this comment.
Yes, much nicer and it follows core 👍
| * @param string $content Label, as plain text. | ||
| * @return string HTML. | ||
| */ | ||
| function gutenberg_ui_render_button( $props, $classes, $content ) { |
There was a problem hiding this comment.
As an internal API, should this be prefixed with _ as conventional with other private APIs?
# Conflicts: # packages/ui/CHANGELOG.md
…ivate Follow Core's get_/echo pair, like get_submit_button() and submit_button(): gutenberg_get_ui_component() returns the HTML and gutenberg_ui_component() prints it. Call sites no longer need a PHPCS ignore, so the preview page's print helper is gone. Templates are internal, so they're now prefixed with an underscore, as other private functions in lib/ are.
…ontent The parity tests now use assertEqualHTML(), which also ignores the order of attributes and classes, instead of their own normalizer. The fixtures and preview examples only pass content when the component declares it, so a component without content, like Spinner, is rendered and tested without it.
The recipe in component.json mapped props to classes, but React doesn't read it, so it was a second copy of React's class logic in a format that can't express conditions, such as `unstyled` dropping the button's base class. component.json now lists the stylesheets a component uses, and the build compiles only those and writes their class names to the manifest. The template picks its classes the same way button.tsx does, and the parity tests catch any difference.
Most strings a PHP screen passes are already encoded, such as post titles, so escaping them as WordPress usually does shows them correctly without decoding them first. A literal entity in plain text now displays as the character, unlike React, so the fixture for it is removed.
commented
Nov 3, 2026
|
Thanks for the review @aduth! I replied and addressed the comments, and updated the PR description to match. |
What?
See #84036
A base for rendering
@wordpress/uicomponents on PHP admin screens, behind thegutenberg-ui-php-componentsexperiment, starting with Button. PHP renders each component from a small templateand a recipe of class names, using the same stylesheet and class names as React, and parity tests check that the output matches React's own render.@wordpress/ui's CSS modules, with the same class names React uses.gutenberg_get_ui_component( $name, $props, $content ), which returns the HTML, andgutenberg_ui_componentwhich prints it with prop validation and escaping by default.Why?
We're exploring ways to make the design system's components available on PHP admin screens, without ending up with a second set of components that drifts apart from React. Whichever way we go, a few pieces seem needed: one shared stylesheet, one PHP function to render a component, and tests that show PHP matches React. This PR starts with just those, so it can be reviewed and merged on its own, and how the markup is produced can still change later without changing the API.
This comes out of the exploration in #84714, which generated the markup from React at build time. That approach could still sit on top of this PR as an alternative to the recipe, so both can be compared on the same component with the same tests.
How?
@wordpress/buildgets a small export,@wordpress/build/compile-style, that compiles a stylesheet the way the JavaScript build does and returns the CSS and class names as data. The UI package uses it to writebuild-php/style.css. This is the only change to shared build code, and it doesn't change what wp-build outputs. In WordPress, the stylesheet loads afterwp-themewhen it's registered, so the design tokens apply.Recipe andTemplate. Each component PHP can render has apackages/ui/php/<name>/component.jsonwith its content, propsand a recipe: the classes it always has, and the classes each variant value adds (and the stylesheets it uses. The build compiles those and writes their class names to the manifest, and PHP renders the markup from a small template ("tone": { "neutral": [ "is-neutral" ] }). Classes are named as in the component's own stylesheet, or as<stylesheet>:<class>for shared utilities like the focus ring. The build resolves the recipe to the scoped class names,lib/experimental/ui-components/components/button.php) which picks its classes the same way the react component does. Templates are internal:gutenberg_get_ui_component()is the only API. React isn't changed. This is close to the prototype intry/ds-php-components-claude, but checked by tests instead.as text, so it's never treated like other props.component.json. Unknown or invalid props fall back to their default with_doing_it_wrong(), so the screen still renders. Missing required content renders nothing.recipe ortemplate doesn't follow, a test fails.build-php/examples.json, which ships with the plugin so the comparison also works in Playground.focusableWhenDisabledoff, so a disabled button is natively disabled and works without JavaScript.Trade-offs and notes
recipetemplate is kept in sync by hand. When React's markup or classes change, someone updatesthe recipe orthe template, and the parity tests point at what changed. (PoC) UI PHP components: Render @wordpress/ui components on PHP admin screens #84714 explored generating the markup from React instead.propsis the public contract, validated and later locked; the recipe is how each value looks today, and follows React. The build checks they agree, so a value can't be added to one and forgotten in the other.Prop interactions live in the recipe. React drops Button'sbuttonclass for theunstyledvariant, so the recipe lists it under the other variants instead. Variants that change structure would need logic in the template.loadingand links aren't supported.loadingrelies on JavaScript to announce the state, so it could be added once there's a direction for interactive components. Links have their own component,ButtonLink, which could be added the same way as Button.gutenberg_ui_components_enqueue_assets()onadmin_enqueue_scripts, as the preview page does.npm run build, not bynpm start. After changing a component's CSSor recipe, runnpm run buildagain.component.jsonso if React adds a avalue, PHP keeps rejecting it until someone adds it there.Testing Instructions
Testing Instructions for Keyboard
npm run build.Automated checks:
npm run test:unit:php:base -- --filter Gutenberg_UI_Components_Testnpm run test:unit -- packages/wp-build/lib/testScreenshots or screencast
Use of AI Tools
I used Claude Code to help prototype and write parts of this code. I reviewed and tested all of it.