Opened 5 weeks ago
Closed 7 hours ago
#66246 closed enhancement (fixed)
Interactivity API: Add server-side processing for the new data-wp-html directive
| Reported by: | darerodz | Owned by: | luisherranz |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | Interactivity API | Version: | trunk |
| Severity: | normal | Keywords: | has-patch has-unit-tests |
| Cc: | Focuses: |
Description
WordPress 7.2 is planned to introduce data-wp-html, a new Interactivity API directive for rendering trusted HTML inside interactive regions, such as a formatted field inside a data-wp-each list. It complements data-wp-text, which always renders its value as text. The use case is described in Gutenberg #70531 and in the directives roadmap in Gutenberg #52904.
The client implementation was merged in Gutenberg PR #83092. This ticket adds the matching server-side processing to Core, so that the HTML is present in the server-rendered page and the client keeps it when it hydrates. The server part should ship together with the client or after it, never before.
Proposal
A new function marks HTML as trusted:
wp_interactivity_as_dangerous_html( string $html ): WP_Interactivity_Dangerous_HTML
It returns an opaque token. The token holds no HTML; the server records the HTML against the token's identity for the current request. When a data-wp-html reference resolves to such a token during directive processing, the element's content is replaced with that HTML, byte for byte.
<?php
wp_interactivity_state(
'myPlugin',
array(
'descriptions' => array(
'a' => wp_kses_post( $description_a ),
'b' => wp_kses_post( $description_b ),
),
'description' => function () {
$state = wp_interactivity_state();
$context = wp_interactivity_get_context();
$html = $state['descriptions'][ $context['item']['id'] ] ?? null;
return null === $html ? null : wp_interactivity_as_dangerous_html( $html );
},
)
);
?>
<ul data-wp-interactive="myPlugin">
<template data-wp-each="state.items">
<li data-wp-html="state.description">Loading…</li>
</template>
</ul>
Behavior
- Only tokens returned by
wp_interactivity_as_dangerous_html()render. Strings, including sanitized ones, never render, and neither do cloned, unserialized or reconstructed objects. - The HTML is neither sanitized nor validated. Preparing it is the caller's responsibility, as with HTML echoed from a filter.
- Directives inside the inserted HTML are not processed on the server.
- The host element keeps its tag and attributes, including
data-wp-html. Its other directives, and the rest of the region, are processed as usual. It works per item insidedata-wp-each. - Neither the token nor its HTML is written to the Interactivity data printed for the client. The client creates its own token, for example in a derived-state getter. * When the directive does not render, the element keeps its existing content. A
_doing_it_wrong()notice is raised when:- the value is not a token;
- the element cannot hold content (void elements and
script,style,textarea,title,iframe,noembed,noframes,xmp); - the element also carries
data-wp-text, or is atemplatecarryingdata-wp-each.
nullor unresolved values are silent.
Security
The token is the only trust boundary. The function's documentation states the risks: passing untrusted data creates an XSS vulnerability, malformed HTML can break the page, and tags such as body can affect the page's root elements. It also states that a value read from context must never be passed to the function, because any ancestor block can override context. Context should only select which value to show; the HTML itself should come from state.
Implementation notes
- The processor writes an inert placeholder comment as the element's content and swaps the trusted HTML in with a single
strtr()pass after directive processing finishes. Core therefore never tokenizes the trusted HTML, and the processing loop,data-wp-eachand the balanced-tag helper are unchanged. - Tests are PHPUnit only. Hydration in the browser is covered by the Gutenberg PR.
Change History (11)
This ticket was mentioned in PR #14012 on WordPress/wordpress-develop by @darerodz.
5 weeks ago
#1
- Keywords has-patch has-unit-tests added
This ticket was mentioned in PR #14301 on WordPress/wordpress-develop by @darerodz.
4 weeks ago
#2
Adds server-side processing for the data-wp-html directive, whose client implementation was merged in WordPress/gutenberg#83092, so that trusted HTML produced in PHP is present in the server-rendered page, including inside data-wp-each items (WordPress/gutenberg#70531).
What it adds
wp_interactivity_as_dangerous_html( string $html ): returns aWP_Interactivity_Dangerous_HTMLtoken that marks the HTML as trusted. The token keeps the HTML in a private property, so encoding it as JSON never includes it.- A
data-wp-htmldirective processor. When the reference resolves to a token, the element's content is replaced with the token's HTML, as given. The element keeps its tag and attributes, and its other directives are processed as usual.
Behavior
- Only tokens render. Strings (sanitized or not), arrays, other objects, values from
data-wp-context, and anything produced byjson_decode()never render. - Unserializing a token does not throw. Its
__wakeup()clears the HTML and raises a_doing_it_wrong()notice, so a page that cached a token keeps working, and the unserialized token never renders. - The HTML is neither sanitized nor validated, and directives inside it are not processed on the server.
- Neither the token nor its HTML is written into the Interactivity data printed for the client or into attributes: a token prints as
{}. - The path of a token reached through
stateis listed inderivedStateClosures, the same way a derived-state closure's path is, so the client keeps the server-rendered content until its store supplies a value. Tokens reached throughcontext, or through the result of a derived-state closure, are not listed. - When the directive does not render, the element keeps its existing content. A
_doing_it_wrong()notice is raised when the value is not a token, when the element cannot hold content (void elements andscript,style,textarea,title,iframe,noembed,noframes,xmp), or when the element also carriesdata-wp-textor is atemplatewithdata-wp-each.nulland unresolved references keep the content without a notice. - No other directive changes.
Implementation notes
The processor writes an inert placeholder comment as the element's content, and process_directives() swaps each placeholder for its HTML with a single strtr() pass once processing has finished. The trusted HTML is therefore never scanned, and the processing loop and data-wp-each are unchanged. The placeholder marker is chosen so that it never occurs in the input. A new set_raw_content_between_balanced_tags() helper writes the placeholder without escaping.
Known limitations, left out of scope:
- A derived-state closure that calls
wp_interactivity_process_directives()starts a new call, so the outer call's placeholders are not substituted. Re-entrant processing is already broken in trunk, because the inner call resets the namespace and context stacks. data-wp-stylereferencing a token fails as it does for any object in trunk (a warning on PHP 7.4, aTypeErroron PHP 8 and later). The general fix, treating every non-scalardata-wp-stylevalue asnull, belongs in a separate ticket.
Testing
PHPUnit only; hydration in the browser is covered by the Gutenberg PR.
npm run test:php -- --group interactivity-api
New test classes: Tests_WP_Interactivity_API_WP_Html and Tests_Interactivity_API_WpInteractivityDangerousHtml.
Use of AI Tools
AI assistance: Yes
Tool(s): OpenCode, running an autonomous multi-agent pipeline (Radical Pipelines) that wrote and reviewed each stage separately
Model(s): Claude Opus 5.5, Claude Sonnet 5.5, GPT-6.1 Sol
Used for: This pull request was authored by AI end to end: specification, design and implementation plan (Claude Opus 5.5), implementation, PHPUnit tests and inline documentation (Claude Sonnet 5.5), reviews of the specification, design and plan (GPT-6.1 Sol), and review of the implementation (Claude Opus 5.5). This pull request was prepared with Claude Opus 5.5. I have reviewed the result and take responsibility for it.
@darerodz commented on PR #14012:
4 weeks ago
#3
Superseded by #14301, which reworks this change after review: the token keeps its HTML in a private property instead of a static registry, unserializing a token leaves it inert with a notice instead of throwing, data-wp-style is left as in trunk, and token paths reached through state are announced in derivedStateClosures.
#5
@
3 weeks ago
- Resolution fixed
- Status closed → reopened
Reopening for a follow-up to [64386].
In [64386], a token created with wp_interactivity_as_dangerous_html() prints as {} in the client data, and tokens reached through state are listed in derivedStateClosures so the client keeps their server-rendered content until a store supplies a value. Tokens reached through context can't be listed, for example context.item.html in a data-wp-each item. They reach the client as {}, and the client empties the element on hydration.
The follow-up prints every token as a marker, {"wpServerHtml":true}, which the client recognizes wherever it appears and treats like a pending value: the element keeps its server-rendered content until a client value replaces it. The client side is https://github.com/WordPress/gutenberg/pull/84889.
A PR from @santosguillamot will follow.
This ticket was mentioned in PR #14489 on WordPress/wordpress-develop by @santosguillamot.
3 weeks ago
#6
Follow-up to #14301 (r64386), which added server-side processing of the data-wp-html directive. The client side of this change is Gutenberg #84889; both sides share the {"wpServerHtml":true} representation.
What
A WP_Interactivity_Dangerous_HTML token now prints as the marker {"wpServerHtml":true} wherever the server sends it to the browser: in the Interactivity client data and in the attribute wp_interactivity_data_wp_context() prints, at any depth. The server stops listing token paths under derivedStateClosures; derived-state closures are listed as before.
Why
Before this change a token printed as {}, and the server listed each token's state path under derivedStateClosures so the client would keep the server-rendered content of the host element. That could not cover a token reached through context, such as context.item.html inside a data-wp-each loop: the client received a plain {} and, with the client-side data-wp-html directive from Gutenberg #84652, emptied the element on hydration.
With the marker, the client (Gutenberg #84889) recognizes a token's place wherever the reference reaches it and keeps the element's content until the client store supplies a value. The marker carries no HTML, and the derivedStateClosures workaround is no longer needed.
How
WP_Interactivity_Dangerous_HTMLimplementsJsonSerializable, sojson_encode()prints the marker, andIteratorAggregate, so the fallback path ofwp_json_encode(), which rebuilds objects withforeachwhen a string is not valid UTF-8, prints it too. The HTML stays in a private property and never reaches JSON.WP_Interactivity_API::evaluate()drops the step that listed token state paths, together with its flag and@sinceline. Closure tracking is unchanged.- No directive processor, call site, or trust check changes. A marker-shaped value coming back from JSON (a
data-wp-contextattribute,json_decode()output in state) is an array orstdClass, not a token, so it never renders anddata-wp-htmlraises its existing non-token notice.
Tests
tests/phpunit/tests/interactivity-api/wpInteractivityAPI-wp-html.php: the {} expectations become the marker, the path-listing assertions go away with the listing, and new coverage checks the marker on both encoding paths of wp_json_encode(), iteration of a token, and a marker decoded from JSON being refused as a non-token.
Testing instructions
Tested against a Gutenberg build that includes #84889, with a block temporarily modified to render three data-wp-html elements: one bound to a token in state, two generated by data-wp-each over items whose html is a token (context.item.html), and one bound to a token passed through a data-wp-context attribute generated with wp_interactivity_data_wp_context(). The same page was loaded on trunk and on this branch.
Server HTML (view source, or JavaScript disabled)
| Element | trunk | this branch |
|---|---|---|
| Bound to a token in state | renders the server HTML | same |
data-wp-each items | both render the server HTML | same |
Bound to a token from data-wp-context | keeps its fallback; the attribute carries {"h":{}} | keeps its fallback; the attribute carries {"h":{"wpServerHtml":true}}
|
After hydration (JavaScript enabled)
| Element | trunk | this branch |
|---|---|---|
| Bound to a token in state | keeps its content, through the derivedStateClosures workaround | keeps its content, through the marker |
data-wp-each items | emptied, with a console warning under SCRIPT_DEBUG | keep their content, no warning |
Bound to a token from data-wp-context | emptied | keeps its fallback |
The data-wp-each items are the bug this fixes. The element bound through data-wp-context shows that a forged marker is harmless: it can only keep content the element already has.
Use of AI Tools
AI assistance: Yes
Tool(s): OpenCode and Claude Code, running an autonomous multi-agent pipeline (Radical Pipelines) that wrote and reviewed each stage separately
Model(s): Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1, GPT-6 Luna, GPT-6.1 Sol
Used for: 100% of the code, tests, and comments in this PR were autonomously generated by AI and reviewed by @SantosGuillamot before the PR was opened.
This ticket was mentioned in PR #15737 on WordPress/wordpress-develop by @santosguillamot.
3 days ago
#8
[64386] added server-side processing of the data-wp-html directive before the client's behavior was settled in Gutenberg. In several cases the server and the client disagree, so hydration changes what the server rendered: the fallback disappears, the trusted HTML disappears, or content the server processed is rendered again by the client.
This makes the server follow the client's rules (Gutenberg trunk, packages/interactivity), so the HTML a data-wp-html element is served with is what the client keeps after hydration.
Behavior changes against trunk
- Values. Only a token from
wp_interactivity_as_dangerous_html()renders HTML, as before.nulland references that resolve to nothing empty the element without a notice: a missing path, a derived-state closure that throws, a__proto__,constructororprototypepath segment or namespace, an empty or missing attribute value.- Any other value that is not a token empties the element with a notice. Previously the fallback was kept in all these cases.
- References are read raw.
data-wp-html='"state.html"'no longer renders the token: the value is never JSON-decoded. A!applies after the reserved-name check, and!!state.xresolves to nothing, as in the client. - Conflicts.
data-wp-htmlis ignored, with a notice, when the element also carriesdata-wp-text,data-wp-eachordata-wp-router-regionin any form (with a suffix or a unique ID, anddata-wp-eachon any element). - Inert content. Directives inside a
data-wp-htmlelement are never processed, and derived-state closures referenced only there are not listed in the client data. - Namespaces. An unprefixed reference resolves in the namespace of the nearest
data-wp-interactiveonly. When that attribute names no namespace (no value, an empty value, invalid JSON, a reserved word), the element is emptied as the client empties it. Core produces this markup: the fit-text typography support adds a valuelessdata-wp-interactive. A suffixeddata-wp-interactive--xordata-wp-interactive---xdoes not start an island, as in the client. - Raw-text and void elements. A
textarea,title,scriptor other raw-text element is emptied for a value that is not a token, and keeps its text, with a notice, for a token. Void elements are left as written. - Any number of elements. The content of each
data-wp-htmlelement is replaced in one forward pass instead of seeking back per element, so a call with more than 1,000data-wp-htmlelements is processed instead of being returned unchanged. - Nested calls. A
wp_interactivity_process_directives()call made while another is running, for example from a derived-state closure, saves and restores the state of the outer call. Previously the outer call either ended in a fatal error or printed a rawplaceholder.
Performance
Measured on the same machine against trunk:
- The benchmark from the ticket (24,000 directive-bearing tags) takes the same time as trunk (about 2.2–2.5 s).
- A page of 24,000
data-wp-htmlelements is processed in about 1.8–3.5 s; trunk returns it unprocessed. - Pages made only of
data-wp-htmlelements are slightly slower at small sizes: about 60 ms more at 1,000 elements. There is no difference at 100 elements.
Not in scope
- Directives inside
svgandmathelements are still not processed, as for every other directive. - The handling of a self-closed
<svg />or<math />. - How other directives treat reserved names.
Testing
npm run test:php -- --group interactivity-api
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code, running an autonomous multi-agent pipeline (Radical Pipelines) that wrote and reviewed each stage separately
Model(s): (to be filled in by @SantosGuillamot)
Used for: 100% of the code, tests, and comments in this PR were autonomously generated by AI and reviewed by @SantosGuillamot before the PR was opened.
---
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.
🤖 Generated with Claude Code
#9
@
9 hours ago
Reopening for a follow-up to [64386] and [64501].
The server-side behavior of data-wp-html does not yet match the client in several hydration cases. @santosguillamot has opened https://github.com/WordPress/wordpress-develop/pull/15737 to align the server processing with the client behavior.
The PR is ready for review and testing.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
Adds server-side processing for the new
data-wp-htmldirective, whose client implementation was merged in WordPress/gutenberg#83092, so that trusted HTML produced in PHP is present in the server-rendered page, including insidedata-wp-eachitems.What it adds
wp_interactivity_as_dangerous_html( string $html ): returns an opaqueWP_Interactivity_Dangerous_HTMLtoken. The token holds no HTML; the server records the HTML against the token's identity for the current request.data-wp-htmldirective processor. When the reference resolves to a token, the element's content is replaced with its HTML, byte for byte. The element keeps its tag and attributes, and its other directives are processed as usual.Behavior
_doing_it_wrong()notice is raised when the value is not a token, when the element cannot hold content (void elements andscript,style,textarea,title,iframe,noembed,noframes,xmp), or when the element also carriesdata-wp-textor is atemplatewithdata-wp-each.nullor unresolved values are silent.Implementation notes
The processor writes an inert placeholder comment as the element's content, and
process_directives()swaps the trusted HTML in with a singlestrtr()pass once processing has finished. Core therefore never tokenizes the trusted HTML, and the processing loop,data-wp-each, and the balanced-tag helper are unchanged. A newset_raw_content_between_balanced_tags()helper writes the placeholder without escaping.Testing
PHPUnit only; hydration in the browser is covered by the Gutenberg PR.
New test classes:
Tests_Interactivity_API_WpInteractivityAsDangerousHtml,Tests_WP_Interactivity_API_WP_HTML,Tests_WP_Interactivity_API_Client_Data_WP_HTML, plus new cases inwpInteractivityAPIDirectivesProcessor.php.Use of AI Tools
AI assistance: Yes
Tool(s): OpenCode, running an autonomous multi-agent pipeline (Radical Pipelines) that wrote and reviewed each stage separately
Model(s): Claude Opus 5.5, Claude Sonnet 5.5, GPT-6 Astra, GPT-6.1 Sol
Used for: This pull request was authored by AI end to end: specification and design (Claude Opus 5.5), implementation plan (Claude Opus 5.5), implementation and PHPUnit tests (GPT-6.1 Sol), inline documentation (Claude Sonnet 5.5), and the reviews of every stage (GPT-6 Astra and GPT-6.1 Sol). Orchestration used Claude Opus 5.5. I have reviewed the result and take responsibility for it.