From 0dab3d9d24f9233d2da654b7305ae9a3ebc80ba0 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:16:11 +0400 Subject: [PATCH 1/9] Skip UTF-8 decoding of ASCII bytes after an identifier consume_ident_sequence() scans ASCII name bytes with strspn() and then asks consume_ident_start_codepoint() about the byte that stopped the scan. For an ASCII byte such as `,` `:` or a space, that method ran _wp_scan_utf8() and utf8_ord() before returning 0. An ASCII byte other than a letter, `_` or NUL never starts an identifier, so the method returns 0 for it before decoding. Tokenizing a 70 KB stylesheet (a generated global stylesheet with the admin-bar and buttons styles, 15,979 tokens) took 6.2 ms before and 4.9 ms after, best of 10 runs on PHP 8.5. --- src/wp-includes/css-api/class-wp-css-token-processor.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php index 4463542c984b1..dcb9ed85529c8 100644 --- a/src/wp-includes/css-api/class-wp-css-token-processor.php +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -1461,6 +1461,11 @@ private function consume_ident_start_codepoint( $at ): int { return 1; } + // Other ASCII code points do not start an identifier. + if ( $this->css[ $at ] < "\x80" ) { + return 0; + } + $new_at = $at; $invalid_length = 0; if ( 1 !== _wp_scan_utf8( $this->css, $new_at, $invalid_length, null, 1 ) ) { From a72493d4cadd5c6cd5b172832ad256e08734dca3 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:16:28 +0400 Subject: [PATCH 2/9] Decode an identifier only when a url token may follow consume_ident_like() decoded every identifier to compare it with "url", and used the result only when the next byte is `(`. Checking that byte first skips the decoding for every identifier that is not followed by `(`, which is most of them. Tokenizing the 70 KB stylesheet from the previous commit took 4.9 ms before and 4.5 ms after, best of 10 runs on PHP 8.5. --- src/wp-includes/css-api/class-wp-css-token-processor.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php index dcb9ed85529c8..10c0c4c194f4c 100644 --- a/src/wp-includes/css-api/class-wp-css-token-processor.php +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -1131,11 +1131,14 @@ private function consume_ident_like(): bool { // Consume an ident sequence, and let string be the result. $ident_start = $this->at; $this->consume_ident_sequence(); - $string = self::decode_range( $this->css, $ident_start, $this->at - $ident_start ); // If string's value is an ASCII case-insensitive match for "url", // and the next input code point is U+0028 LEFT PARENTHESIS ((). - if ( 0 === strcasecmp( $string, 'url' ) && $this->at < $this->length && '(' === $this->css[ $this->at ] ) { + if ( + $this->at < $this->length && + '(' === $this->css[ $this->at ] && + 0 === strcasecmp( self::decode_range( $this->css, $ident_start, $this->at - $ident_start ), 'url' ) + ) { // Consume it. ++$this->at; From a0d0dd065ef4598ef719e28086a1ce63cc7912d3 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:17:21 +0400 Subject: [PATCH 3/9] Add WP_CSS_Token_Processor::split_comma_separated_list() Selector lists in theme.json, block supports, duotone and the style engine are split with explode( ',' ) or with scanners that track some nesting. Their callers need the source text of each selector, as written, to prepend or append to it; parse_comma_separated_list() returns tokens, and a caller that only needs the text pays for one WP_CSS_Token per token. The method returns the groups of parse_comma_separated_list() as substrings of the input. When the input has no string, comment, escape or url token, every comma and bracket byte is a token of its own, so a strcspn() scan over those bytes finds the groups without tokenizing. Theme selector lists rarely hold any of those, so the scan handles most calls. On the 348 selector lists that WP_Theme_JSON::split_selector_list() receives while building the twentytwentyfour and twentytwentyfive stylesheets, the scan takes 0.7 us per call; tokenizing every input takes 11 us. 600,000 random inputs over CSS syntax characters gave the same groups as parse_comma_separated_list(). --- .../css-api/class-wp-css-token-processor.php | 108 ++++++++++++++++++ .../tests/css-api/wpCssTokenProcessor.php | 46 ++++++++ 2 files changed, 154 insertions(+) diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php index 10c0c4c194f4c..362c00392994e 100644 --- a/src/wp-includes/css-api/class-wp-css-token-processor.php +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -860,6 +860,114 @@ public static function parse_comma_separated_list( string $css ): array { return $groups; } + /** + * Splits CSS into the source text between its top-level commas. + * + * The groups are the groups of parse_comma_separated_list(), returned as + * their source text: the bytes of the input between two top-level commas, + * with whitespace, comments and escapes as written. Joining the result + * with commas reproduces the input. + * + * Example: + * + * ```php interactive + * $items = WP_CSS_Token_Processor::split_comma_separated_list( '[title="a,b"], :is(c, d) e,f\,g' ); + * foreach ( $items as $item ) { + * echo "[{$item}]\n"; + * } + * // Outputs: + * // [[title="a,b"]] + * // [ :is(c, d) e] + * // [f\,g] + * ``` + * + * A comma at the end of the input produces a final empty string. Empty + * input produces an empty array. + * + * @since 7.3.0 + * + * @see WP_CSS_Token_Processor::parse_comma_separated_list() + * + * @param string $css CSS source to split. + * @return string[] Source text of each group, in source order. + */ + public static function split_comma_separated_list( string $css ): array { + $length = strlen( $css ); + if ( 0 === $length ) { + return array(); + } + + /* + * Without strings, comments, escapes and url tokens, each `,` `(` `)` + * `[` `]` `{` `}` byte is a token of its own or ends a function token, + * so scanning those bytes finds the groups the tokenizer finds. + */ + if ( strcspn( $css, '"\'\\/' ) === $length && false === stripos( $css, 'url(' ) ) { + $items = array(); + $item_at = 0; + + // Closing bytes of the open blocks and functions, innermost last. + $closers = ''; + + $at = strcspn( $css, ',()[]{}' ); + while ( $at < $length ) { + $byte = $css[ $at ]; + if ( ',' === $byte ) { + if ( '' === $closers ) { + $items[] = substr( $css, $item_at, $at - $item_at ); + $item_at = $at + 1; + } + } elseif ( '' !== $closers && $closers[-1] === $byte ) { + $closers = substr( $closers, 0, -1 ); + } elseif ( '(' === $byte ) { + $closers .= ')'; + } elseif ( '[' === $byte ) { + $closers .= ']'; + } elseif ( '{' === $byte ) { + $closers .= '}'; + } + $at += 1 + strcspn( $css, ',()[]{}', $at + 1 ); + } + + $items[] = substr( $css, $item_at ); + return $items; + } + + $processor = new self( $css ); + $items = array(); + $item_at = 0; + + // Closing token types of the open blocks and functions, innermost last. + $closers = array(); + + while ( $processor->next_token() ) { + $type = $processor->token_type; + + if ( self::TOKEN_COMMA === $type && array() === $closers ) { + $items[] = substr( $css, $item_at, $processor->token_starts_at - $item_at ); + $item_at = $processor->at; + continue; + } + + // A closing token ends a block only when it matches the innermost open block. + if ( array() !== $closers && end( $closers ) === $type ) { + array_pop( $closers ); + } elseif ( self::TOKEN_FUNCTION === $type || self::TOKEN_LEFT_PAREN === $type ) { + $closers[] = self::TOKEN_RIGHT_PAREN; + } elseif ( self::TOKEN_LEFT_BRACKET === $type ) { + $closers[] = self::TOKEN_RIGHT_BRACKET; + } elseif ( self::TOKEN_LEFT_BRACE === $type ) { + $closers[] = self::TOKEN_RIGHT_BRACE; + } + } + + if ( $item_at < $processor->length || array() !== $items ) { + $items[] = substr( $css, $item_at ); + } + + return $items; + } + /** * Clears token state between tokens. * diff --git a/tests/phpunit/tests/css-api/wpCssTokenProcessor.php b/tests/phpunit/tests/css-api/wpCssTokenProcessor.php index cfb303cebc9f4..367c46192fb83 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenProcessor.php +++ b/tests/phpunit/tests/css-api/wpCssTokenProcessor.php @@ -2675,4 +2675,50 @@ public static function data_parse_comma_separated_list(): array { 'unterminated string holds comma' => array( '"a,b', array( '"a,b' ) ), ); } + + /** + * Tests that the source text of each group matches the groups of + * parse_comma_separated_list(). + * + * @ticket 65738 + * @dataProvider data_parse_comma_separated_list + * @dataProvider data_split_comma_separated_list + * + * @covers ::split_comma_separated_list + * + * @param string $css CSS to split. + * @param string[] $expected Source text of each group. + */ + public function test_split_comma_separated_list( string $css, array $expected ): void { + $this->assertSame( $expected, WP_CSS_Token_Processor::split_comma_separated_list( $css ), 'Wrong groups.' ); + + $groups = array(); + foreach ( WP_CSS_Token_Processor::parse_comma_separated_list( $css ) as $group ) { + $text = ''; + foreach ( $group as $token ) { + $text .= substr( $css, $token->get_start(), $token->get_length() ); + } + $groups[] = $text; + } + $this->assertSame( $groups, WP_CSS_Token_Processor::split_comma_separated_list( $css ), 'Groups differ from parse_comma_separated_list().' ); + } + + /** + * Data provider for test_split_comma_separated_list(). + * + * @return array[] + */ + public static function data_split_comma_separated_list(): array { + return array( + 'whitespace around commas' => array( ' , ', array( ' ', ' ' ) ), + 'selector list' => array( 'h1, h2,h3', array( 'h1', ' h2', 'h3' ) ), + 'attribute selectors in a function' => array( 'input:where([type=a],[type=b]), textarea', array( 'input:where([type=a],[type=b])', ' textarea' ) ), + 'comma in an uppercase url token' => array( 'URL(a,b),c', array( 'URL(a,b)', 'c' ) ), + 'comma in a quoted url argument' => array( 'url("a,b"),c', array( 'url("a,b")', 'c' ) ), + 'bad url ends at its first closer' => array( 'url(a(b),c', array( 'url(a(b)', 'c' ) ), + 'escaped url name' => array( 'u\rl(a(b),c', array( 'u\rl(a(b)', 'c' ) ), + 'comma in an attribute string' => array( '[title="a,b"],c', array( '[title="a,b"]', 'c' ) ), + 'string holds a closer' => array( ':is("(",a),b', array( ':is("(",a)', 'b' ) ), + ); + } } From a541bcaf78d77227e4ef10d743a3c76a180f7040 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:18:38 +0400 Subject: [PATCH 4/9] Theme JSON: Split selector lists with the CSS API WP_Theme_JSON has a hand-written selector list scanner in split_selector_list(), a regular expression path in append_to_selector() and prepend_to_selector(), and explode( ',' ) in get_block_element_selectors(). The scanner tracks only parentheses, and explode() splits inside functions and strings: get_block_element_selectors( '.wp-block-a,.wp-block-b' )['h1'] '.wp-block-a h1,.wp-block-b h1' get_block_element_selectors( ':is(.wp-block-a,.wp-block-b)' )['h1'] ':is(.wp-block-a h1,.wp-block-b) h1' All three use WP_CSS_Token_Processor::split_comma_separated_list(), which splits where the CSS tokenizer finds top-level commas. split_selector_list() keeps its trimming and drops the empty selector after a trailing comma, as before. The regular expression path in append_to_selector() and prepend_to_selector() is gone: for the inputs it handled, the split gives the same result. Measured on the 348 split_selector_list() and 3,248 prepend_to_selector() calls made while building the twentytwentyfour and twentytwentyfive stylesheets and block metadata, one PHP 8.5 process per variant, best of 15: split_selector_list() 0.49 us -> 0.73 us per call prepend_to_selector() 0.17 us -> 0.27 us per call Both functions return the same strings as before on all of these inputs. --- src/wp-includes/class-wp-theme-json.php | 175 +++--------------- .../tests/theme/wpThemeJsonSelectorList.php | 32 ++++ 2 files changed, 53 insertions(+), 154 deletions(-) diff --git a/src/wp-includes/class-wp-theme-json.php b/src/wp-includes/class-wp-theme-json.php index 15d08fba457a9..af00baee62d72 100644 --- a/src/wp-includes/class-wp-theme-json.php +++ b/src/wp-includes/class-wp-theme-json.php @@ -1660,29 +1660,6 @@ protected static function append_to_selector( $selector, $to_append ) { return trim( $selector, " \t\n" ) . $to_append; } - /** - * Check for an opportunity to skip the more-costly selector splitting. - * This should be possible if there are no comments, strings, functions, - * URLs, escapes, or comment declaration openers (CDOs). - * - * Note that this means the fast-path will not apply for selectors like - * the following incomplete list: - * - * - `[class ~= "wide"]` - * - `.wp-block:is(.is-style-a, .is-style-b)` - * - `:nth-child(1)` - * - * These syntax forms all present opportunities where a comma may not - * separate selectors. If none of the start characters are present, - * there should be no way for a comma to mean anything other than a - * comma token. The exception are syntax errors, which are not handled here. - * - * @link https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values - */ - if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) { - return preg_replace( '~[ \t\n]*,[ \t\n]*~', "{$to_append}, ", trim( $selector, " \t\n" ) ) . $to_append; - } - $new_selectors = array(); $selectors = static::split_selector_list( $selector ); foreach ( $selectors as $sel ) { @@ -1709,29 +1686,6 @@ protected static function prepend_to_selector( $selector, $to_prepend ) { return $to_prepend . trim( $selector, " \t\n" ); } - /** - * Check for an opportunity to skip the more-costly selector splitting. - * This should be possible if there are no comments, strings, functions, - * URLs, escapes, or comment declaration openers (CDOs). - * - * Note that this means the fast-path will not apply for selectors like - * the following incomplete list: - * - * - `[class ~= "wide"]` - * - `.wp-block:is(.is-style-a, .is-style-b)` - * - `:nth-child(1)` - * - * These syntax forms all present opportunities where a comma may not - * separate selectors. If none of the start characters are present, - * there should be no way for a comma to mean anything other than a - * comma token. The exception are syntax errors, which are not handled here. - * - * @link https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values - */ - if ( strlen( $selector ) === strcspn( $selector, '/\'"(<\\' ) ) { - return $to_prepend . preg_replace( '~[ \t\n]*,[ \t\n]*~', ", {$to_prepend}", trim( $selector, " \t\n" ) ); - } - $new_selectors = array(); $selectors = static::split_selector_list( $selector ); foreach ( $selectors as $sel ) { @@ -1781,119 +1735,30 @@ protected static function prepend_to_selector( $selector, $to_prepend ) { */ protected static function split_selector_list( $selector ): array { if ( ! str_contains( $selector, ',' ) ) { - // See note on trimming CSS whitespace in main loop. return array( trim( $selector, " \t\n" ) ); } - $selectors = array(); - $selector_length = strlen( $selector ); - $parentheses_depth = 0; - $at = 0; - $was_at = 0; - - while ( $at < $selector_length ) { - $next_at = $at + strcspn( $selector, '/,\'"()<-\\', $at ); - if ( $next_at >= $selector_length ) { - break; - } - - $next_cp = $selector[ $next_at ]; - - // Escaped syntax characters do not act as delimiters. - if ( '\\' === $next_cp ) { - $at = min( $next_at + 2, $selector_length ); - continue; - } - - /* - * Start of a parenthesized expression, which maintains a stack of parentheses. - * For the sake of this function, no selector list will be split inside parentheses. - * Therefore it’s possible to jump ahead until this list completes. - */ - if ( '(' === $next_cp || ')' === $next_cp ) { - $parentheses_depth += '(' === $next_cp ? 1 : -1; - $at = $next_at + 1; - continue; - } + $selectors = WP_CSS_Token_Processor::split_comma_separated_list( $selector ); - // Start of a string, which will be incorporated into the selector in which it’s found. - if ( "'" === $next_cp || '"' === $next_cp ) { - $end_of_string = $next_at + 1; - while ( $end_of_string < $selector_length ) { - $end_of_string += strcspn( $selector, "{$next_cp}\\", $end_of_string ); - if ( $end_of_string >= $selector_length ) { - break; - } - - $end_cp = $selector[ $end_of_string ]; - - // Skip escaped characters. - if ( '\\' === $end_cp ) { - $end_of_string = $end_of_string + 2; - continue; - } - - if ( $next_cp === $end_cp ) { - ++$end_of_string; - break; - } - - ++$end_of_string; - } - - $at = $end_of_string; - continue; - } - - // Start of a comment, which will be incorporated into the selector in which it’s found. - if ( '/' === $next_cp && ( $next_at + 1 ) < $selector_length && '*' === $selector[ $next_at + 1 ] ) { - $comment_end_at = strpos( $selector, '*/', $next_at + 1 ); - $is_terminated = false !== $comment_end_at; - $after_comment = $is_terminated ? $comment_end_at + 2 : strlen( $selector ); - $at = $after_comment; - continue; - } - - // Start of a CDO or CDC, which will be incorporated into the selector in which it’s found. - if ( - ( '<' === $next_cp && 0 === substr_compare( $selector, '', $next_at, 3 ) ) - ) { - $at = $next_at + ( '<' === $next_cp ? 4 : 3 ); - continue; - } - - // Everything else is either a comma token or part of a selector. - if ( ',' === $next_cp && 0 === $parentheses_depth ) { - /** - * Trim each selector so that downstream code doesn’t see whitespace - * as the first character in a selector and get confused. - * - * There is inconsistency in this because comments and other syntax - * are included which are also not part of the selector itself, but - * a tradeoff is made between removing common syntax which carries - * no meaning and rarer syntax which leaves auxiliary information. - * - * > A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE. - * > Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are - * > not included in this definition, as they are converted - * > to U+000A LINE FEED during preprocessing. - * - * @link https://www.w3.org/TR/css-syntax/#whitespace - * @link https://www.w3.org/TR/css-syntax/#newline - */ - $selectors[] = trim( substr( $selector, $was_at, $next_at - $was_at ), " \t\n" ); - $at = $next_at + 1; - $was_at = $at; - continue; - } - - $at = $next_at + 1; + // A comma at the end of the list does not start another selector. + if ( '' === end( $selectors ) ) { + array_pop( $selectors ); } - if ( $was_at < $selector_length ) { - // See note on trimming CSS whitespace in main loop. - $selectors[] = trim( substr( $selector, $was_at ), " \t\n" ); + /* + * Trim CSS whitespace so that callers do not see it as the first + * character of a selector. Comments stay in the selector they follow. + * + * > A newline, U+0009 CHARACTER TABULATION, or U+0020 SPACE. + * > Note that U+000D CARRIAGE RETURN and U+000C FORM FEED are + * > not included in this definition, as they are converted + * > to U+000A LINE FEED during preprocessing. + * + * @link https://www.w3.org/TR/css-syntax/#whitespace + * @link https://www.w3.org/TR/css-syntax/#newline + */ + foreach ( $selectors as $i => $item ) { + $selectors[ $i ] = trim( $item, " \t\n" ); } return $selectors; @@ -6031,7 +5896,9 @@ protected static function get_block_element_selectors( $root_selector ) { * If the block selector is compounded, will append the element to each * individual block selector. */ - $block_selectors = explode( ',', $root_selector ); + $block_selectors = str_contains( $root_selector, ',' ) + ? WP_CSS_Token_Processor::split_comma_separated_list( $root_selector ) + : array( $root_selector ); $element_selectors = array(); foreach ( static::ELEMENTS as $el_name => $el_selector ) { $element_selector = array(); diff --git a/tests/phpunit/tests/theme/wpThemeJsonSelectorList.php b/tests/phpunit/tests/theme/wpThemeJsonSelectorList.php index eb23e0c55c180..62315907e25ee 100644 --- a/tests/phpunit/tests/theme/wpThemeJsonSelectorList.php +++ b/tests/phpunit/tests/theme/wpThemeJsonSelectorList.php @@ -130,4 +130,36 @@ public static function data_prepend_to_selector_uses_safe_splitting() { ), ); } + + /** + * @dataProvider data_get_block_element_selectors_splits_top_level_commas + * + * @param string $root_selector Block root selector. + * @param string $expected Expected heading element selector. + */ + public function test_get_block_element_selectors_splits_top_level_commas( $root_selector, $expected ) { + $selectors = self::invoke_theme_json_method( 'get_block_element_selectors', $root_selector ); + + $this->assertSame( $expected, $selectors['h1'] ); + } + + /** + * @return array + */ + public static function data_get_block_element_selectors_splits_top_level_commas() { + return array( + 'selector list' => array( + 'root_selector' => '.wp-block-a,.wp-block-b', + 'expected' => '.wp-block-a h1,.wp-block-b h1', + ), + 'selector list in a function' => array( + 'root_selector' => ':is(.wp-block-a,.wp-block-b)', + 'expected' => ':is(.wp-block-a,.wp-block-b) h1', + ), + 'comma in an attribute string' => array( + 'root_selector' => '[data-a="b,c"]', + 'expected' => '[data-a="b,c"] h1', + ), + ); + } } From b214c484fa9398fbf4a38ad7ab6b19b26e42a8eb Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:20:27 +0400 Subject: [PATCH 5/9] States: Split selector lists with the CSS API wp_split_selector_list() tracks parentheses only, so it splits at commas inside attribute strings, escapes, comments and brackets: wp_split_selector_list( 'a[title=x]' ) array( 'a[title=x]' ) wp_split_selector_list( 'a[title="x,y"]' ) array( 'a[title="x', 'y"]' ) It uses WP_CSS_Token_Processor::split_comma_separated_list(), which splits where the CSS tokenizer finds top-level commas. Each selector keeps its surrounding whitespace, and a trailing comma still gives a final empty selector, so callers see the same strings for every input the parenthesis count split correctly. wp_get_block_state_element_selectors() checked for a comma before splitting an element selector. wp_split_selector_list() returns the selector unchanged when it has no comma, so the check is gone. https://github.com/WordPress/wordpress-develop/pull/12610 fixes the same defect by calling WP_Theme_JSON::split_selector_list() instead and removing wp_split_selector_list(), which shipped in 7.1. Its test is included here unchanged. --- src/wp-includes/block-supports/states.php | 36 +++---------- tests/phpunit/tests/block-supports/states.php | 54 +++++++++++++++++++ 2 files changed, 60 insertions(+), 30 deletions(-) diff --git a/src/wp-includes/block-supports/states.php b/src/wp-includes/block-supports/states.php index 809072fd5612e..47ef6b8fd2aaf 100644 --- a/src/wp-includes/block-supports/states.php +++ b/src/wp-includes/block-supports/states.php @@ -431,12 +431,7 @@ function wp_get_block_state_element_selectors( $root_selector ) { break; } - $selector_prefix = "$block_selector "; - if ( ! str_contains( $element_selector, ',' ) ) { - $selectors[] = $selector_prefix . $element_selector; - continue; - } - + $selector_prefix = "$block_selector "; $prepended_selectors = array(); foreach ( wp_split_selector_list( $element_selector ) as $selector ) { $prepended_selectors[] = $selector_prefix . $selector; @@ -577,7 +572,11 @@ function wp_get_block_state_unique_class( $block_name, $css_rules ) { /** * Splits a selector list by top-level commas. * + * Commas inside strings, comments, escapes, functions and blocks do not + * split the list. Each selector keeps its surrounding whitespace. + * * @since 7.1.0 + * @since 7.3.0 Ignores commas inside strings, comments, escapes, brackets and braces. * * @param string $selector CSS selector list. * @return string[] Selectors. @@ -587,30 +586,7 @@ function wp_split_selector_list( $selector ) { return array( $selector ); } - $selectors = array(); - $current_selector = ''; - $parentheses_depth = 0; - $selector_length = strlen( $selector ); - - for ( $i = 0; $i < $selector_length; $i++ ) { - $char = $selector[ $i ]; - - if ( '(' === $char ) { - ++$parentheses_depth; - } elseif ( ')' === $char && $parentheses_depth > 0 ) { - --$parentheses_depth; - } elseif ( ',' === $char && 0 === $parentheses_depth ) { - $selectors[] = $current_selector; - $current_selector = ''; - continue; - } - - $current_selector .= $char; - } - - $selectors[] = $current_selector; - - return $selectors; + return WP_CSS_Token_Processor::split_comma_separated_list( $selector ); } /** diff --git a/tests/phpunit/tests/block-supports/states.php b/tests/phpunit/tests/block-supports/states.php index eacd5d7c893d1..d4551c002591b 100644 --- a/tests/phpunit/tests/block-supports/states.php +++ b/tests/phpunit/tests/block-supports/states.php @@ -645,6 +645,60 @@ public function test_build_state_selector_splits_selector_lists_without_splittin ); } + /** + * Tests that a comma inside an attribute selector string does not split the + * selector when scoping a state selector to the block wrapper. + * + * @covers ::wp_build_state_selector + * + * @ticket 65669 + */ + public function test_build_state_selector_does_not_split_attribute_string_comma() { + $actual = wp_build_state_selector( + '.wp-states-test', + '[data-label="Save, continue"]', + ':hover' + ); + + $this->assertSame( '.wp-states-test:hover', $actual ); + } + + /** + * Tests that a selector list splits only at top-level commas and that + * each selector keeps its surrounding whitespace. + * + * @covers ::wp_split_selector_list + * + * @ticket 65669 + * + * @dataProvider data_split_selector_list + * + * @param string $selector Selector list. + * @param string[] $expected Selectors. + */ + public function test_split_selector_list( $selector, $expected ) { + $this->assertSame( $expected, wp_split_selector_list( $selector ) ); + } + + /** + * Data provider for test_split_selector_list(). + * + * @return array + */ + public static function data_split_selector_list() { + return array( + 'empty' => array( '', array( '' ) ), + 'one selector' => array( '.a', array( '.a' ) ), + 'selector list' => array( '.a, .b', array( '.a', ' .b' ) ), + 'trailing comma' => array( '.a,', array( '.a', '' ) ), + 'comma in a function' => array( ':is(a, b) img', array( ':is(a, b) img' ) ), + 'comma in an attribute string' => array( 'a[title="x,y"]', array( 'a[title="x,y"]' ) ), + 'escaped comma' => array( '.a\\,b', array( '.a\\,b' ) ), + 'comma in a comment' => array( '.a/* x, y */', array( '.a/* x, y */' ) ), + 'unquoted comma in brackets' => array( '[a,b]', array( '[a,b]' ) ), + ); + } + /** * Tests that a leading compound naming a different block is kept as an * ancestor, and the instance class goes on the block's own compound. From 7e26aef055bdadd27cf9c3a09f3f2e9625410190 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:20:49 +0400 Subject: [PATCH 6/9] States: Find the state selector ancestor with the CSS tokenizer wp_get_state_selector_ancestor() reads a selector byte by byte and treats any space as a combinator, including a space inside a comment or after a backslash. For a comment before the combinator, the instance class lands inside the comment and the state rule matches every list item: .wp-block-list> li .wp-block-list> .wp-states-test:hover .wp-block-list/* x */> li .wp-block-list/* .wp-states-test */> li:hover The function walks CSS tokens instead. Whitespace tokens and the >, + and ~ delimiters at the top level are combinators, comments next to a combinator join the ancestor, and an escaped space stays in its identifier. Functions and brackets are skipped as before. For the selectors in the existing tests and the core block selectors, the result is unchanged. --- src/wp-includes/block-supports/states.php | 59 ++++++++++++++----- tests/phpunit/tests/block-supports/states.php | 15 +++++ 2 files changed, 60 insertions(+), 14 deletions(-) diff --git a/src/wp-includes/block-supports/states.php b/src/wp-includes/block-supports/states.php index 47ef6b8fd2aaf..873cf90257281 100644 --- a/src/wp-includes/block-supports/states.php +++ b/src/wp-includes/block-supports/states.php @@ -614,26 +614,57 @@ function wp_get_state_selector_ancestor( $selector, $block_name ) { return ''; } + /* + * - `$ancestor_length`: bytes up to the end of the first top-level combinator, + * including the whitespace and comments around it. + * - `$next_compound`: source text of the compound after that combinator, + * without the contents of its functions and brackets. + * + * .wp-block-list > li:not(.x) a + * ╰──── ancestor ─╯╰─ next ──╯ + */ + $processor = new WP_CSS_Token_Processor( $selector ); $ancestor_length = 0; $next_compound = ''; $depth = 0; - $selector_length = strlen( $selector ); - for ( $i = 0; $i < $selector_length; $i++ ) { - $char = $selector[ $i ]; + while ( $processor->next_token() ) { + $type = $processor->get_token_type(); + $token_end = $processor->get_token_start() + $processor->get_token_length(); - if ( '(' === $char || '[' === $char ) { - ++$depth; - } elseif ( ( ')' === $char || ']' === $char ) && $depth > 0 ) { - --$depth; - } elseif ( 0 === $depth && str_contains( " \t\n\r\f>+~", $char ) ) { - if ( $ancestor_length ) { - break; + if ( $depth > 0 ) { + if ( WP_CSS_Token_Processor::TOKEN_RIGHT_PAREN === $type || WP_CSS_Token_Processor::TOKEN_RIGHT_BRACKET === $type ) { + --$depth; + } elseif ( WP_CSS_Token_Processor::TOKEN_FUNCTION === $type || WP_CSS_Token_Processor::TOKEN_LEFT_PAREN === $type || WP_CSS_Token_Processor::TOKEN_LEFT_BRACKET === $type ) { + ++$depth; + } + continue; + } + + $is_combinator = ( + WP_CSS_Token_Processor::TOKEN_WHITESPACE === $type || + ( WP_CSS_Token_Processor::TOKEN_DELIM === $type && str_contains( '>+~', $selector[ $processor->get_token_start() ] ) ) + ); + + if ( $is_combinator || WP_CSS_Token_Processor::TOKEN_COMMENT === $type ) { + if ( '' !== $next_compound ) { + if ( $is_combinator ) { + break; + } + continue; } - $ancestor_length = $i + strspn( $selector, " \t\n\r\f>+~", $i ); - $i = $ancestor_length - 1; - } elseif ( 0 === $depth && $ancestor_length ) { - $next_compound .= $char; + if ( $is_combinator || $ancestor_length > 0 ) { + $ancestor_length = $token_end; + } + continue; + } + + if ( $ancestor_length > 0 ) { + $next_compound .= substr( $selector, $processor->get_token_start(), $processor->get_token_length() ); + } + + if ( WP_CSS_Token_Processor::TOKEN_FUNCTION === $type || WP_CSS_Token_Processor::TOKEN_LEFT_PAREN === $type || WP_CSS_Token_Processor::TOKEN_LEFT_BRACKET === $type ) { + ++$depth; } } diff --git a/tests/phpunit/tests/block-supports/states.php b/tests/phpunit/tests/block-supports/states.php index d4551c002591b..5ff3e7af66f41 100644 --- a/tests/phpunit/tests/block-supports/states.php +++ b/tests/phpunit/tests/block-supports/states.php @@ -773,6 +773,21 @@ public static function data_build_state_selector_with_block_name() { 'block_selector' => '.wp-block-list > li, .wp-block-list-item .inner', 'expected' => '.wp-block-list > .wp-states-test:hover, .wp-states-test .inner:hover', ), + 'comment before the combinator' => array( + 'block_name' => 'core/list-item', + 'block_selector' => '.wp-block-list/* x */> li', + 'expected' => '.wp-block-list/* x */> .wp-states-test:hover', + ), + 'nested block element with a class' => array( + 'block_name' => 'core/list-item', + 'block_selector' => '.wp-block-list > .a.wp-block-b', + 'expected' => '.wp-states-test > .a.wp-block-b:hover', + ), + 'nested block element with an escape' => array( + 'block_name' => 'core/list-item', + 'block_selector' => '.wp-block-list > .a\\ .wp-block-b', + 'expected' => '.wp-states-test > .a\\ .wp-block-b:hover', + ), ); } From 37032a721daa587009fb172f9392c68a0eb6a690 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:22:08 +0400 Subject: [PATCH 7/9] Duotone: Split the duotone selector list with the CSS API WP_Duotone::enqueue_block_css() splits a block's duotone selector with explode( ',' ) and adds the filter class to each part. A comma inside an attribute string or an escape puts the class inside the selector: [data-x="a"] img .wp-duotone-unset-1[data-x="a"] img [data-x="a,b"] img .wp-duotone-unset-1[data-x="a, .wp-duotone-unset-1b"] img It uses WP_CSS_Token_Processor::split_comma_separated_list(), which splits where the CSS tokenizer finds top-level commas. A selector with no comma is used as is, as before. --- src/wp-includes/class-wp-duotone.php | 4 +- .../phpunit/tests/block-supports/duotone.php | 52 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-duotone.php b/src/wp-includes/class-wp-duotone.php index 49cf221c11af6..fd0cd4c223c17 100644 --- a/src/wp-includes/class-wp-duotone.php +++ b/src/wp-includes/class-wp-duotone.php @@ -846,7 +846,9 @@ private static function get_global_styles_presets( $sources ) { */ private static function enqueue_block_css( $filter_id, $duotone_selector, $filter_value ) { // Build the CSS selectors to which the filter will be applied. - $selectors = explode( ',', $duotone_selector ); + $selectors = str_contains( $duotone_selector, ',' ) + ? WP_CSS_Token_Processor::split_comma_separated_list( $duotone_selector ) + : array( $duotone_selector ); $selectors_scoped = array(); foreach ( $selectors as $selector_part ) { diff --git a/tests/phpunit/tests/block-supports/duotone.php b/tests/phpunit/tests/block-supports/duotone.php index 0aed3b7e3dcff..dc6e5d6162768 100644 --- a/tests/phpunit/tests/block-supports/duotone.php +++ b/tests/phpunit/tests/block-supports/duotone.php @@ -188,6 +188,58 @@ public function test_css_declarations_are_generated_even_with_empty_block_conten $this->assertNotEmpty( $actual ); } + /** + * Tests that the filter class is added to each selector in a duotone + * selector list, and that commas inside strings and escapes do not + * split the list. + * + * @ticket 65669 + * + * @covers ::render_duotone_support + * + * @dataProvider data_duotone_selector_list + * + * @param string $duotone_selector Duotone selector of the block type. + * @param string $expected Expected selector, with `ID` in place of the filter class. + */ + public function test_duotone_selector_list( $duotone_selector, $expected ) { + register_block_type( + 'test/duotone-selector-list', + array( + 'api_version' => 3, + 'supports' => array( 'filter' => array( 'duotone' => true ) ), + 'selectors' => array( 'filter' => array( 'duotone' => $duotone_selector ) ), + ) + ); + + $block = array( + 'blockName' => 'test/duotone-selector-list', + 'attrs' => array( 'style' => array( 'color' => array( 'duotone' => 'unset' ) ) ), + ); + $wp_block = new WP_Block( $block ); + WP_Duotone::render_duotone_support( '
', $block, $wp_block ); + WP_Duotone::output_block_styles(); + $css = wp_style_engine_get_stylesheet_from_context( 'block-supports', array( 'prettify' => false ) ); + + unregister_block_type( 'test/duotone-selector-list' ); + + $rule = str_replace( 'ID', 'wp-duotone-unset-[0-9]+', preg_quote( $expected . '{filter:unset;}', '/' ) ); + $this->assertMatchesRegularExpression( "/(?:^|}){$rule}/", $css ); + } + + /** + * Data provider for test_duotone_selector_list(). + * + * @return array + */ + public static function data_duotone_selector_list() { + return array( + 'selector list' => array( '.a img, .b img', '.ID.a img, .ID.b img' ), + 'comma in an attribute string' => array( '[data-x="a,b"] img', '.ID[data-x="a,b"] img' ), + 'escaped comma' => array( '.a\\,b img', '.ID.a\\,b img' ), + ); + } + /** * @dataProvider data_is_preset */ From ffd92125177e7961ee689cb7ad642b40b8d86295 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 11:23:21 +0400 Subject: [PATCH 8/9] Style Engine: Split prettified selector lists with the CSS API WP_Style_Engine_CSS_Rule::get_css() prettifies a selector list with explode( ',' ) and str_replace( ',', ",\n" ), so it breaks lines inside functions and attribute strings. A line break inside a string ends the string, and the browser drops the rule: [title="x"] [title="x"] { [title="x, y"] [title="x, y"] { It splits the list with WP_CSS_Token_Processor::split_comma_separated_list() and joins the trimmed selectors with ",\n". Selector lists without commas inside functions, strings or escapes give the same output. --- .../class-wp-style-engine-css-rule.php | 7 ++-- .../style-engine/wpStyleEngineCssRule.php | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/style-engine/class-wp-style-engine-css-rule.php b/src/wp-includes/style-engine/class-wp-style-engine-css-rule.php index a483911335ad9..0b9dd4f017e98 100644 --- a/src/wp-includes/style-engine/class-wp-style-engine-css-rule.php +++ b/src/wp-includes/style-engine/class-wp-style-engine-css-rule.php @@ -177,9 +177,10 @@ public function get_css( $should_prettify = false, $indent_count = 0 ) { $nested_declarations_indent = $should_prettify ? $indent_count + 2 : 0; $suffix = $should_prettify ? "\n" : ''; $spacer = $should_prettify ? ' ' : ''; - // Trims any multiple selectors strings. - $selector = $should_prettify ? implode( ',', array_map( 'trim', explode( ',', $this->get_selector() ) ) ) : $this->get_selector(); - $selector = $should_prettify ? str_replace( array( ',' ), ",\n", $selector ) : $selector; + // Puts each selector of a selector list on its own line. + $selector = $should_prettify + ? implode( ",\n", array_map( 'trim', WP_CSS_Token_Processor::split_comma_separated_list( $this->get_selector() ) ) ) + : $this->get_selector(); $rules_group = $this->get_rules_group(); $has_rules_group = ! empty( $rules_group ); $css_declarations = $this->declarations->get_declarations_string( $should_prettify, $has_rules_group ? $nested_declarations_indent : $declarations_indent ); diff --git a/tests/phpunit/tests/style-engine/wpStyleEngineCssRule.php b/tests/phpunit/tests/style-engine/wpStyleEngineCssRule.php index a9de39392ade0..9e50539855d42 100644 --- a/tests/phpunit/tests/style-engine/wpStyleEngineCssRule.php +++ b/tests/phpunit/tests/style-engine/wpStyleEngineCssRule.php @@ -176,4 +176,36 @@ public function test_should_prettify_css_rule_output() { $this->assertSameIgnoreEOL( $expected, $css_rule->get_css( true ) ); } + + /** + * Tests that prettified output puts each selector of a selector list on its + * own line, and keeps commas inside functions and strings in place. + * + * @ticket 65669 + * + * @covers ::get_css + * + * @dataProvider data_should_prettify_selector_list + * + * @param string $selector Selector list. + * @param string $expected Prettified selector. + */ + public function test_should_prettify_selector_list( $selector, $expected ) { + $css_rule = new WP_Style_Engine_CSS_Rule( $selector, array( 'color' => 'red' ) ); + + $this->assertSameIgnoreEOL( "{$expected} {\n\tcolor: red;\n}", $css_rule->get_css( true ) ); + } + + /** + * Data provider for test_should_prettify_selector_list(). + * + * @return array + */ + public static function data_should_prettify_selector_list() { + return array( + 'selector list' => array( '.a , .b', ".a,\n.b" ), + 'comma in a function' => array( ':is(.a, .b) img', ':is(.a, .b) img' ), + 'comma in an attribute string' => array( '[title="x, y"]', '[title="x, y"]' ), + ); + } } From 870829364415f2fbc3ff0e5c6808160d6859fba9 Mon Sep 17 00:00:00 2001 From: Jon Surrell Date: Tue, 17 Nov 2026 16:44:40 +0400 Subject: [PATCH 9/9] Add WP_CSS_Token_Processor::split_comma_separated_list() Selector lists in theme.json, block supports, duotone and the style engine are split with explode( ',' ) or with scanners that track some nesting, which split inside strings, escapes, comments or blocks. Their callers need the source text of each selector, as written, to prepend or append to it. The method returns the source text between top-level commas, found by tokenizing the input. Joining the items with commas reproduces the input. A comma at the end of the input produces a final empty item, as the selector grammar rejects a trailing comma and the CSS Syntax 3 algorithm does not show one. --- .../css-api/class-wp-css-token-processor.php | 69 +++++++++++++++++++ .../tests/css-api/wpCssTokenProcessor.php | 57 +++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/src/wp-includes/css-api/class-wp-css-token-processor.php b/src/wp-includes/css-api/class-wp-css-token-processor.php index e9b0e27e4bd7e..3100250ed86d0 100644 --- a/src/wp-includes/css-api/class-wp-css-token-processor.php +++ b/src/wp-includes/css-api/class-wp-css-token-processor.php @@ -786,6 +786,75 @@ public function get_token_length(): ?int { return $this->token_length; } + /** + * Splits CSS into the source text between its top-level commas. + * + * A comma inside a string, comment, escape, url token, function, `()`, + * `[]` or `{}` block belongs to the item that holds it. Each item is + * the bytes of the input between two top-level commas, with whitespace, + * comments and escapes as written, so joining the items with commas + * reproduces the input. + * + * Example: + * + * ```php interactive + * $items = WP_CSS_Token_Processor::split_comma_separated_list( '[title="a,b"], :is(c, d) e,f\\,g' ); + * foreach ( $items as $item ) { + * echo "[{$item}]\n"; + * } + * // Outputs: + * // [[title="a,b"]] + * // [ :is(c, d) e] + * // [f\,g] + * ``` + * + * Unlike the CSS Syntax 3 algorithm, a comma at the end of the input + * produces a final empty item, so a caller whose grammar forbids a + * trailing comma can reject it. Empty input produces no items. + * + * @since 7.3.0 + * + * @link https://www.w3.org/TR/css-syntax-3/#parse-comma-separated-list-of-component-values + * + * @param string $css CSS source to split. + * @return string[] Source text of each item, in source order. + */ + public static function split_comma_separated_list( string $css ): array { + $processor = new self( $css ); + $items = array(); + $item_at = 0; + + // Closing token types of the open blocks and functions, innermost last. + $closers = array(); + + while ( $processor->next_token() ) { + $type = $processor->token_type; + + if ( self::TOKEN_COMMA === $type && array() === $closers ) { + $items[] = substr( $css, $item_at, $processor->token_starts_at - $item_at ); + $item_at = $processor->at; + continue; + } + + // A closing token ends a block only when it matches the innermost open block. + if ( array() !== $closers && end( $closers ) === $type ) { + array_pop( $closers ); + } elseif ( self::TOKEN_FUNCTION === $type || self::TOKEN_LEFT_PAREN === $type ) { + $closers[] = self::TOKEN_RIGHT_PAREN; + } elseif ( self::TOKEN_LEFT_BRACKET === $type ) { + $closers[] = self::TOKEN_RIGHT_BRACKET; + } elseif ( self::TOKEN_LEFT_BRACE === $type ) { + $closers[] = self::TOKEN_RIGHT_BRACE; + } + } + + if ( $item_at < strlen( $css ) || array() !== $items ) { + $items[] = substr( $css, $item_at ); + } + + return $items; + } + /** * Clears token state between tokens. * diff --git a/tests/phpunit/tests/css-api/wpCssTokenProcessor.php b/tests/phpunit/tests/css-api/wpCssTokenProcessor.php index c4c190e87cec9..c3071abffc16b 100644 --- a/tests/phpunit/tests/css-api/wpCssTokenProcessor.php +++ b/tests/phpunit/tests/css-api/wpCssTokenProcessor.php @@ -2619,4 +2619,61 @@ public function test_ident_start_codepoint_bounds_check(): void { ); $this->assertSame( $expected_tokens, $actual_tokens ); } + + /** + * Tests that a comma-separated list splits at its top-level commas only. + * + * @ticket 65738 + * @dataProvider data_split_comma_separated_list + * + * @covers ::split_comma_separated_list + * + * @param string $css CSS to split. + * @param string[] $expected Source text of each item. + */ + public function test_split_comma_separated_list( string $css, array $expected ): void { + $items = WP_CSS_Token_Processor::split_comma_separated_list( $css ); + + $this->assertSame( $expected, $items, 'Wrong items.' ); + $this->assertSame( $css, implode( ',', $items ), 'Joining the items with commas must reproduce the input.' ); + } + + /** + * Data provider for test_split_comma_separated_list(). + * + * @return array[] + */ + public static function data_split_comma_separated_list(): array { + return array( + 'empty input' => array( '', array() ), + 'whitespace only' => array( ' ', array( ' ' ) ), + 'one item' => array( 'a', array( 'a' ) ), + 'items keep their whitespace' => array( 'a , b', array( 'a ', ' b' ) ), + 'whitespace around commas' => array( ' , ', array( ' ', ' ' ) ), + 'selector list' => array( 'h1, h2,h3', array( 'h1', ' h2', 'h3' ) ), + 'trailing comma' => array( 'a,', array( 'a', '' ) ), + 'leading comma' => array( ',a', array( '', 'a' ) ), + 'empty item' => array( 'a,,b', array( 'a', '', 'b' ) ), + 'comma in a string' => array( '"a,b",c', array( '"a,b"', 'c' ) ), + 'comma in an attribute string' => array( '[title="a,b"],c', array( '[title="a,b"]', 'c' ) ), + 'escaped comma' => array( 'a\\,b,c', array( 'a\\,b', 'c' ) ), + 'comma in a comment' => array( 'a/*,*/,b', array( 'a/*,*/', 'b' ) ), + 'comma in a function' => array( 'var(--a, b), c', array( 'var(--a, b)', ' c' ) ), + 'comma in a url token' => array( 'url(a,b),c', array( 'url(a,b)', 'c' ) ), + 'comma in an uppercase url token' => array( 'URL(a,b),c', array( 'URL(a,b)', 'c' ) ), + 'comma in a quoted url argument' => array( 'url("a,b"),c', array( 'url("a,b")', 'c' ) ), + 'bad url ends at its first closer' => array( 'url(a(b),c', array( 'url(a(b)', 'c' ) ), + 'escaped url name' => array( 'u\\rl(a(b),c', array( 'u\\rl(a(b)', 'c' ) ), + 'comma in parentheses' => array( ':is(a, b), c', array( ':is(a, b)', ' c' ) ), + 'comma in brackets' => array( '[a, b], c', array( '[a, b]', ' c' ) ), + 'comma in braces' => array( '{a, b}, c', array( '{a, b}', ' c' ) ), + 'attribute selectors in a function' => array( 'input:where([type=a],[type=b]), textarea', array( 'input:where([type=a],[type=b])', ' textarea' ) ), + 'nested blocks' => array( 'f(a,[b,{c,d}],e),g', array( 'f(a,[b,{c,d}],e)', 'g' ) ), + 'string holds a closer' => array( ':is("(",a),b', array( ':is("(",a)', 'b' ) ), + 'stray closer at the top level' => array( 'a),b', array( 'a)', 'b' ) ), + 'mismatched closer in a block' => array( '(a]b,c),d', array( '(a]b,c)', 'd' ) ), + 'unclosed block holds the rest' => array( 'f(a,b', array( 'f(a,b' ) ), + 'unterminated string holds comma' => array( '"a,b', array( '"a,b' ) ), + ); + } }