Skip to content

UI PHP components: Add a base for rendering @wordpress/ui components in PHP - #85756

Open
juanfra wants to merge 24 commits into
trunkfrom
try/84036-ui-components-php-base
Open

juanfra wants to merge 24 commits into
trunkfrom
try/84036-ui-components-php-base

Conversation

@juanfra

@juanfra juanfra commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

What?

See #84036

A base for rendering @wordpress/ui components on PHP admin screens, behind the gutenberg-ui-php-components experiment, starting with Button. PHP renders each component from a small template and 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.

  • A stylesheet compiled from @wordpress/ui's CSS modules, with the same class names React uses.
  • gutenberg_get_ui_component( $name, $props, $content ), which returns the HTML, and gutenberg_ui_component which prints it with prop validation and escaping by default.
  • Parity tests that compare the PHP output with React's render of every combination of variants.
  • A preview page under Tools, with each example rendered by PHP next to React.

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?

  • Stylesheet. @wordpress/build gets 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 write build-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 after wp-theme when it's registered, so the design tokens apply.
  • Recipe and Template. Each component PHP can render has a packages/ui/php/<name>/component.json with its content, props and a recipe: the classes it always has, and the classes each variant value adds ("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, 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 (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 in try/ds-php-components-claude, but checked by tests instead.
  • Content. Content is its own argument, escaped as text, so it's never treated like other props.
  • Validation. Props are validated against the schema in 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.
  • Parity tests. The build renders every combination of variants with React, plus a custom class and content that needs escaping, as fixtures. PHPUnit checks that PHP renders the same markup for each one. If React's Button changes and the recipe or template doesn't follow, a test fails.
  • Preview page. Tools → UI Components shows a classic form with the PHP Button next to a classic one, and an Examples table with each example rendered by PHP next to React's render. The build writes those examples to build-php/examples.json, which ships with the plugin so the comparison also works in Playground.
  • Button matches React's Button with focusableWhenDisabled off, so a disabled button is natively disabled and works without JavaScript.

Trade-offs and notes

  • The recipe template is kept in sync by hand. When React's markup or classes change, someone updates the recipe or the 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.
  • Props and recipe are kept apart. props is 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's button class for the unstyled variant, so the recipe lists it under the other variants instead. Variants that change structure would need logic in the template.
  • loading and links aren't supported. loading relies 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.
  • Styles and the head. Rendering a component enqueues its stylesheet, but if the head is already printed, it loads in the footer. Screens that render components should call gutenberg_ui_components_enqueue_assets() on admin_enqueue_scripts, as the preview page does.
  • Watch mode. The PHP output is built by npm run build, not by npm start. After changing a component's CSS or recipe, run npm run build again.
  • One stylesheet for all components for now. It could be split per component as more are added.
  • New react options aren't caught yet. The fixtures cover the values in component.json so if React adds a avalue, PHP keeps rejecting it until someone adds it there.

Testing Instructions

Testing Instructions for Keyboard

  1. Run npm run build.
  2. Go to Settings → Experiments and enable "UI components for PHP screens".
  3. Go to Tools → UI Components.
  4. Check that the Button in the classic form looks like the design system Button, next to a classic button.
  5. In the Examples table, check that each PHP render looks the same as React's.

Automated checks:

  • npm run test:unit:php:base -- --filter Gutenberg_UI_Components_Test
  • npm run test:unit -- packages/wp-build/lib/test

Screenshots or screencast

Screenshot 2026-10-27 at 14-53-41 UI Components ‹ Stories® — WordPress

Use of AI Tools

I used Claude Code to help prototype and write parts of this code. I reviewed and tested all of it.

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.
@juanfra juanfra added [Type] Technical Prototype Offers a technical exploration into an idea as an example of what's possible [Package] UI /packages/ui [Package] wp-build /packages/wp-build labels Oct 27, 2026
@github-actions

ghost commented Oct 27, 2026 •

Copy link
Copy Markdown

🤖 PR meta 🤖

Preview in WordPress Playground

🎉 Props

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: juanfra <juanfra@git.wordpress.org>
Co-authored-by: ciampo <mciampini@git.wordpress.org>
Co-authored-by: aduth <aduth@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

Updated as activity occurs, without notifying anyone named here. Add the props-bot label to refresh.

📦 Bundle size

Size Change: 0 B

Total Size: 8.64 MB

9548145 Run

⚡ Performance

Show the results

Client side metrics exclude the server response time.

front-end-block-theme

Metric 4c679b0 trunk % Change
timeToFirstByte 55.6 ms +10.34% -2.79% 55.9 ms +11.54% -2.5% -0.54%
largestContentfulPaint 88 ms +4.55% -4.55% 88 ms +9.09% -4.55% 0%
lcpMinusTtfb 30.7 ms +14.01% -11.24% 30.1 ms +26.08% -7.64% 1.99%
wpBeforeTemplate 29.04 ms +9.5% -1.79% 28.97 ms +14.88% -1.66% 0.24%
wpTemplate 22.92 ms +1.92% -5.1% 22.47 ms +4.09% -4.23% 2%
wpTotal 52.08 ms +9.95% -3.61% 52.03 ms +11.4% -2.52% 0.1%
wpMemoryUsage 7.72 MB +0% -0% 7.69 MB +0% -0% 0.43%
wpDbQueries 16 +0% -0% 16 +0% -0% 0%

front-end-classic-theme

Metric 4c679b0 trunk % Change
timeToFirstByte 46.8 ms +4.7% -2.14% 46.8 ms +2.78% -2.88% 0%
largestContentfulPaint 80 ms +5% -0% 80 ms +2.5% -0% 0%
lcpMinusTtfb 34.65 ms +2.74% -2.74% 34.3 ms +2.92% -3.5% 1.02%
wpBeforeTemplate 26.53 ms +4.9% -0.98% 26.14 ms +4.36% -1.22% 1.49%
wpTemplate 16.56 ms +2.48% -2.66% 16.47 ms +5.77% -4.07% 0.55%
wpTotal 43.64 ms +4.56% -2.45% 43.48 ms +3.38% -2.51% 0.37%
wpMemoryUsage 6.41 MB +0% -0% 6.38 MB +0% -0% 0.53%
wpDbQueries 13 +0% -0% 13 +0% -0% 0%

media-processing

Metric 4c679b0 trunk % Change
mediaProcessingJpeg 408.69 ms +0.58% -0.75% 401.66 ms +0.48% -0.08% 1.75%
mediaProcessingAvif 6170.32 ms +0.53% -0.36% 6171.97 ms +0.2% -0.09% -0.03%
mediaProcessingJpegToAvif 4252.08 ms +0.45% -0.14% 4254.37 ms +0.21% -0.12% -0.05%

media-upload

Metric 4c679b0 trunk % Change
jpegUploadProcessing 1994.8 ms +3.61% -0.92% 1970.35 ms +0.56% -23.23% 1.24%
pngUploadProcessing 284.66 ms +1.24% -1.84% 274.39 ms +2.16% -1.78% 3.74%
largeJpegUploadProcessing 1507.5 ms +30.8% -0.51% 1947.42 ms +1.04% -22.41% -22.59%
multipleImageUploadProcessing 2087.18 ms +4.73% -1.02% 2095.1 ms +0.38% -0.82% -0.38%

post-editor

Metric 4c679b0 trunk % Change
serverResponse 319.64 ms +4.32% -7.63% 310.85 ms +5.99% -4.25% 2.83%
firstPaint 326.35 ms +15.08% -6.89% 349.14 ms +9.24% -10.19% -6.53%
domContentLoaded 656 ms +2.63% -1.17% 660.67 ms +0.52% -2.12% -0.71%
loaded 657.03 ms +2.61% -1.18% 661.57 ms +0.55% -2.1% -0.69%
firstContentfulPaint 369.2 ms +1.72% -0.98% 374.79 ms +3.46% -0.96% -1.49%
firstBlock 1750.55 ms +6.75% -2.13% 1734.13 ms +2.03% -0.87% 0.95%
type 15 ms +9.87% -10.27% 16.04 ms +11.53% -7.98% -6.48%
typeWithoutInspector 14.45 ms +11.56% -3.32% 16.4 ms +7.01% -14.82% -11.89%
typeWithTopToolbar 19.24 ms +4.83% -5.72% 22.25 ms +5.08% -10.74% -13.53%
typeContainer 7.49 ms +7.61% -17.09% 7.33 ms +8.19% -4.64% 2.18%
focus 107.27 ms +2.58% -5.18% 102.13 ms +1.49% -0.99% 5.03%
firstFocus 209.68 ms +0% -0% 228.41 ms +0% -0% -8.2%
selectAll 325.86 ms +6.85% -0.32% 328.77 ms +0.37% -0.61% -0.89%
undo 24.32 ms +6.46% -2.47% 25.01 ms +9.52% -4.44% -2.76%
listViewOpen 68.33 ms +19.3% -6.06% 65.53 ms +3.46% -12.45% 4.27%
inserterOpen 37.93 ms +6.91% -4.32% 34.42 ms +11.8% -4.79% 10.2%
inserterHover 9.82 ms +6.92% -5.91% 10.36 ms +8.69% -5.79% -5.21%
inserterSearch 6.8 ms +8.24% -4.41% 7.71 ms +7.13% -3.76% -11.8%
loadPatterns 522.29 ms +2.53% -1.83% 526.17 ms +3.3% -1.28% -0.74%
wpTotal 311.02 ms +4.41% -7.9% 302.31 ms +6.18% -4.42% 2.88%
wpMemoryUsage 14.78 MB +0% -0% 14.74 MB +0% -0% 0.24%
wpDbQueries 55 +0% -0% 55 +0% -0% 0%

site-editor

Metric 4c679b0 trunk % Change
serverResponse 316.93 ms +1.04% -9.58% 312.34 ms +1.53% -8.34% 1.47%
firstPaint 358.31 ms +4.18% -12.81% 360.74 ms +4.08% -16.03% -0.67%
domContentLoaded 655.65 ms +1.56% -0.58% 647.46 ms +2.52% -1.45% 1.26%
loaded 656.51 ms +1.55% -0.57% 648.31 ms +2.5% -1.45% 1.26%
firstContentfulPaint 371.66 ms +1.35% -1.36% 365.41 ms +3.95% -2.58% 1.71%
firstBlock 2019.18 ms +0.63% -1.96% 1961.85 ms +0.9% -0.24% 2.92%
type 15.33 ms +8.68% -11.29% 15.18 ms +4.02% -5.93% 0.99%
navigate 94.95 ms +7.32% -2.66% 89.08 ms +15.96% -8.45% 6.59%
loadPatterns 1081.25 ms +12.85% -8.71% 1116.72 ms +4.2% -8.28% -3.18%
loadPages 988.49 ms +1% -2.48% 992.18 ms +2.97% -1.66% -0.37%
wpTotal 308.62 ms +1.01% -9.9% 304.1 ms +1.5% -9.01% 1.49%
wpMemoryUsage 12.80 MB +0% -0% 12.76 MB +0% -0% 0.31%
wpDbQueries 45 +0% -0% 45 +0% -0% 0%

9548145 Run

🏁 Flaky tests

Some 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 /test/e2e/specs/site-editor/dataviews-list-layout-keyboard.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeFocused() failed

Locator:  getByRole('row', { name: 'Page Two Edit Actions' }).getByRole('button', { name: 'Edit' })
Expected: focused
Received: inactive
Timeout:  5000ms

Call log:
  - Expect "toBeFocused" getByRole('row', { name: 'Page Two Edit Actions' }).getByRole('button', { name: 'Edit' }) with timeout 5000ms
  - waiting for getByRole('row', { name: 'Page Two Edit Actions' }).getByRole('button', { name: 'Edit' })
    14 × locator resolved to <button type="button" tabindex="-1" class="components-button is-small" id="view-list-0-175-primary-action-edit-post">Edit</button>
       - unexpected value "inactive"

    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/dataviews-list-layout-keyboard.spec.js:243:5
Undo restores the post selection when another synced entity is loaded (RTC WebSocket) in /test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts, passed after 1 failed attempt.
Error: expect(received).toMatchObject(expected)

- Expected  - 2
+ Received  + 2

  Object {
    "attributeKey": "content",
    "blockIndex": 0,
    "content": "abcdef",
-   "endOffset": 3,
-   "offset": 3,
+   "endOffset": 4,
+   "offset": 4,
  }

Call Log:
- Timeout 5000ms exceeded while waiting on the predicate
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts:363:5
does not select blocks in the canvas preview when editing from the sidebar in /test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeFocused() failed

Locator: getByRole('combobox', { name: 'Search or type URL' })
Expected: focused
Timeout: 5000ms
Error: element(s) not found

Call log:
  - Expect "toBeFocused" getByRole('combobox', { name: 'Search or type URL' }) with timeout 5000ms
  - waiting for getByRole('combobox', { name: 'Search or type URL' })

    at LinkControl.useLinkControlSearch (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:416:47)
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:179:21
three users concurrently edit a large post with diverse blocks in /test/e2e/specs/editor/collaboration/collaboration-stress.spec.ts, passed after 1 failed attempt.
TimeoutError: locator.waitFor: Timeout 17500ms exceeded.
Call log:
  - waiting for getByRole('button', { name: /Collaborators list/ }) to be visible

    at map (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/fixtures/collaboration-utils.ts:193:7)
    at CollaborationUtils.waitForMutualDiscovery (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/fixtures/collaboration-utils.ts:188:10)
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/collaboration-stress.spec.ts:416:28

9548145 Run

esc_attr( $props['type'] ),
esc_attr( implode( ' ', $classes ) ),
$props['disabled'] ? ' data-disabled="" disabled=""' : '',
esc_html( $content )

ghost Nov 1, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

esc_html() preserves existing HTML entities (eg, passing the plain-text label A &amp; B displays A & B, while React displays the original A &amp; B).

Can we preserve literal entity text here and add it to the parity fixtures?

ghost Nov 2, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Marco! And sorry for the repeat, got lost when I rebuilt the base. Fixed c26047f

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Juan Aldasoro added 2 commits November 2, 2026 09:24
# 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 &amp; 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.
@juanfra
juanfra requested review from a team and removed request for desrosj, manzoorwanijk and spacedmonkey November 2, 2026 10:13

ghost left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +74 to +75
* @param {Array} variants `[ prop, values ]` pairs.
* @return {Object[]} Combinations, as props.

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/ui/bin/build-php.mjs Outdated
Comment on lines +107 to +110
// 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 } ) => {

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/ui/bin/build-php.mjs Outdated
*/
async function compileStylesheets() {
const stylesheets = new Map();
const files = await glob( 'src/**/*.module.{css,scss}', {

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. Now that component.json list the stylesheets each component uses and the build compiles them, usedStylesheets isn't needed anymore

6791e77

Comment thread lib/experimental/ui-components/load.php Outdated
/**
* Returns the HTML of a `@wordpress/ui` component.
*
* The content is plain text, escaped when rendered. Entities show as written,

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment on lines +198 to +211
// 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-&amp;' },
content: 'A &amp; B &hellip; &#8217;',
},
];

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread packages/ui/php/button/component.json Outdated
Comment on lines +28 to +51
"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" ]
}
}
},

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'],
                )
        );

        // ...
}

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ) {

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 😂

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice, I didn't know about it either 😅 Fixed 12eb22e

Comment on lines +51 to +52
function gutenberg_ui_components_print( $html ) {
echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, much nicer and it follows core 👍

03dd986

* @param string $content Label, as plain text.
* @return string HTML.
*/
function gutenberg_ui_render_button( $props, $classes, $content ) {

ghost Nov 2, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As an internal API, should this be prefixed with _ as conventional with other private APIs?

ghost Nov 3, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, definitely 🫡 03dd986

Juan Aldasoro added 5 commits November 3, 2026 12:07
# 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.
@juanfra

ghost commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review @aduth! I replied and addressed the comments, and updated the PR description to match.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Package] UI /packages/ui [Package] wp-build /packages/wp-build [Type] Technical Prototype Offers a technical exploration into an idea as an example of what's possible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants