diff --git a/classes/models/FrmStyleCssMerger.php b/classes/models/FrmStyleCssMerger.php new file mode 100644 index 0000000000..f8964b4539 --- /dev/null +++ b/classes/models/FrmStyleCssMerger.php @@ -0,0 +1,497 @@ + + */ + private $blocks = array(); + + /** + * @since x.x + * + * @param string $style_class The style class without the leading dot, like frm_style_formidable-style. + * @param string $css The CSS printed for this style. + * + * @return void + */ + public function add_style( $style_class, $css ) { + $this->blocks[] = array( + 'class' => $style_class, + 'css' => $css, + ); + } + + /** + * @since x.x + * + * @return string + */ + public function get_css() { + $original = implode( "\n", wp_list_pluck( $this->blocks, 'css' ) ); + + /** + * Allows the per style rules in the generated stylesheet to be printed unmerged. + * + * @since x.x + * + * @param bool $merge True to combine rules with identical declarations. + */ + if ( count( $this->blocks ) < 2 || ! apply_filters( 'frm_merge_style_css', true ) ) { + return $original; + } + + $parsed = array(); + $isolated = array(); + $classes = wp_list_pluck( $this->blocks, 'class' ); + $pattern = '/\.(' . implode( '|', array_map( array( self::class, 'quote_class' ), $classes ) ) . ')(?![\w-])/'; + + foreach ( $this->blocks as $index => $block ) { + $rules = self::parse_rules( $block['css'], $index ); + + if ( false === $rules ) { + return $original; + } + + foreach ( $rules as $rule_index => $rule ) { + preg_match_all( $pattern, $rule['selector'], $matches ); + $foreign = array_diff( $matches[1], array( $block['class'] ) ); + + if ( ! $foreign ) { + continue; + } + + // A rule for another style has to keep its order with that style's rules. + $rules[ $rule_index ]['mergeable'] = false; + $isolated += array_fill_keys( $foreign, true ); + } + + $parsed[ $index ] = $rules; + }//end foreach + + $sequences = array(); + + foreach ( $this->blocks as $index => $block ) { + $sequences[] = self::key_rules( $parsed[ $index ], $block['class'], $index, ! isset( $isolated[ $block['class'] ] ) ); + } + + $order = self::merge_order( $sequences ); + + return self::build_css( $order, $sequences ); + } + + /** + * @since x.x + * + * @param string $style_class + * + * @return string + */ + private static function quote_class( $style_class ) { + return preg_quote( $style_class, '/' ); + } + + /** + * Splits CSS into rules, each with the at-rule blocks it is nested in. + * + * @since x.x + * + * @param string $css + * @param int $block_index The position of the style in the output. + * + * @return array|false False when the CSS uses syntax this parser does not handle. + */ + private static function parse_rules( $css, $block_index ) { + $css = preg_replace( '/\/\*.*?\*\//s', '', $css ); + + // A brace inside a quoted string would be read as a block boundary. + preg_match_all( '/"[^"]*"|\'[^\']*\'/', $css, $strings ); + + foreach ( $strings[0] as $string ) { + if ( strpbrk( $string, '{}' ) ) { + return false; + } + } + + $rules = array(); + $context = array(); + $offset = 0; + $at_blocks = 0; + + while ( true ) { + $close = strpos( $css, '}', $offset ); + + if ( false === $close ) { + break; + } + + $open = strpos( $css, '{', $offset ); + + if ( false === $open || $open > $close ) { + // The end of an at-rule block. + if ( ! $context || '' !== trim( substr( $css, $offset, $close - $offset ) ) ) { + return false; + } + + array_pop( $context ); + $offset = $close + 1; + continue; + } + + $prelude = self::clean_whitespace( substr( $css, $offset, $open - $offset ) ); + + if ( '' === $prelude || str_contains( $prelude, ';' ) ) { + return false; + } + + $next_open = strpos( $css, '{', $open + 1 ); + + if ( '@' === $prelude[0] && false !== $next_open && $next_open < $close ) { + // An at-rule like @media that holds rules. + if ( preg_match( '/^@layer\b/i', $prelude ) ) { + // The first @layer block with a name sets the order of that layer, and merging can + // move one style's block ahead of another style's block for a different layer. + return false; + } + + if ( preg_match( '/^@(-[a-z]+-)?keyframes\b/i', $prelude ) ) { + // A later @keyframes block with the same name replaces an earlier one instead of + // adding to it, so each block is kept apart from other blocks with the same prelude. + $prelude .= self::BLOCK_MARKER . $block_index . '-' . $at_blocks; + } + + $context[] = $prelude; + $offset = $open + 1; + ++$at_blocks; + continue; + } + + $rules[] = array( + 'context' => $context, + 'selector' => $prelude, + 'body' => self::clean_whitespace( substr( $css, $open + 1, $close - $open - 1 ) ), + 'mergeable' => true, + ); + $offset = $close + 1; + }//end while + + if ( $context || '' !== trim( substr( $css, $offset ) ) ) { + return false; + } + + return $rules; + } + + /** + * Removes the same whitespace FrmStyle::get_css_content() removes from the saved file. + * + * @since x.x + * + * @param string $text + * + * @return string + */ + private static function clean_whitespace( $text ) { + return trim( str_replace( array( "\r\n", "\r", "\n", "\t", ' ' ), '', $text ) ); + } + + /** + * Gives each rule a key that matches the same template rule in other styles. + * + * @since x.x + * + * @param array $rules + * @param string $style_class + * @param int $block_index The position of the style in the output. + * @param bool $mergeable False when another style's CSS has rules for this style, so its rules keep their order with those. + * + * @return array Rules keyed in their original order. + */ + private static function key_rules( $rules, $style_class, $block_index, $mergeable ) { + $pattern = '/\.' . preg_quote( $style_class, '/' ) . '(?![\w-])/'; + $keyed = array(); + $occurrences = array(); + + foreach ( $rules as $rule ) { + $selector = preg_replace( $pattern, self::PLACEHOLDER, $rule['selector'] ); + // A style class inside a quoted attribute value is text to match, not the style class. + $scoped = $mergeable && $rule['mergeable'] && str_contains( $selector, self::PLACEHOLDER ) && ! strpbrk( $rule['selector'], '"\'' ); + $key = implode( "\x01", $rule['context'] ) . "\x02" . $selector; + + if ( ! $scoped ) { + // Only rules scoped to the style are combined with other styles. + $key .= "\x04" . $block_index; + } + + $occurrences[ $key ] = isset( $occurrences[ $key ] ) ? $occurrences[ $key ] + 1 : 0; + $key .= "\x03" . $occurrences[ $key ]; + + $rule['selector'] = $selector; + $rule['class'] = $style_class; + $rule['scoped'] = $scoped; + $keyed[ $key ] = $rule; + } + + return $keyed; + } + + /** + * Builds one rule order that keeps the original order of every style's rules. + * + * Each style is lined up with the order built from the styles before it. A rule that + * would have to move to share a position is renamed so it stays with its own style. + * Rules that are not scoped to a style also keep their order across styles. + * + * @since x.x + * + * @param array> $sequences Rules keyed by rule key, in order. Renamed keys are updated. + * + * @return array + */ + private static function merge_order( &$sequences ) { + /** + * @var array $order + */ + $order = array(); + $last_unscoped = null; + + foreach ( $sequences as $index => $rules ) { + $positions = array_flip( $order ); + $shared = array(); + + foreach ( $rules as $key => $rule ) { + if ( $rule['scoped'] && isset( $positions[ $key ] ) ) { + $shared[ $key ] = $positions[ $key ]; + } + } + + $keep = self::longest_increasing( $shared ); + $cursor = -1; + $renamed = array(); + + foreach ( $rules as $key => $rule ) { + if ( isset( $keep[ $key ] ) && $positions[ $key ] > $cursor ) { + $cursor = $positions[ $key ]; + $renamed[ $key ] = $rule; + continue; + } + + if ( isset( $positions[ $key ] ) ) { + $key .= "\x05" . $index; + } + + if ( ! $rule['scoped'] && null !== $last_unscoped ) { + $cursor = max( $cursor, $positions[ $last_unscoped ] ); + } + + array_splice( $order, $cursor + 1, 0, array( $key ) ); + $positions = array_flip( $order ); + ++$cursor; + $renamed[ $key ] = $rule; + + if ( ! $rule['scoped'] ) { + $last_unscoped = $key; + } + }//end foreach + + $sequences[ $index ] = $renamed; + }//end foreach + + return $order; + } + + /** + * Finds the longest run of keys whose positions go up, in their given order. + * + * @since x.x + * + * @param array $positions Positions keyed by rule key. + * + * @return array + */ + private static function longest_increasing( $positions ) { + $keys = array_keys( $positions ); + $values = array_values( $positions ); + $tails = array(); + $previous = array(); + + foreach ( $values as $i => $value ) { + $low = 0; + $high = count( $tails ); + + while ( $low < $high ) { + $middle = intdiv( $low + $high, 2 ); + + if ( $values[ $tails[ $middle ] ] < $value ) { + $low = $middle + 1; + } else { + $high = $middle; + } + } + + $previous[ $i ] = $low > 0 ? $tails[ $low - 1 ] : -1; + $tails[ $low ] = $i; + } + + $keep = array(); + $i = $tails ? end( $tails ) : -1; + + while ( $i >= 0 ) { + $keep[ $keys[ $i ] ] = true; + $i = $previous[ $i ]; + } + + return $keep; + } + + /** + * @since x.x + * + * @param array $order + * @param array> $sequences + * + * @return string + */ + private static function build_css( $order, $sequences ) { + $entries = array(); + + foreach ( $order as $key ) { + $groups = array(); + + foreach ( $sequences as $rules ) { + if ( ! isset( $rules[ $key ] ) ) { + continue; + } + + $rule = $rules[ $key ]; + + if ( ! isset( $groups[ $rule['body'] ] ) ) { + $groups[ $rule['body'] ] = $rule; + $groups[ $rule['body'] ]['classes'] = array(); + } + + $groups[ $rule['body'] ]['classes'][] = '.' . $rule['class']; + } + + foreach ( $groups as $body => $group ) { + $selector = str_replace( self::PLACEHOLDER, self::class_selector( $group['classes'] ), $group['selector'] ); + $entries[] = array( + 'context' => $group['context'], + 'rule' => $selector . '{' . $body . '}', + ); + } + }//end foreach + + return self::entries_to_css( $entries ); + } + + /** + * Prints the rules, keeping only the last copy of a rule that is printed more than once. + * The last copy sets the same values after anything in between, so the earlier ones have no effect. + * + * @since x.x + * + * @param array, rule: string}> $entries + * + * @return string + */ + private static function entries_to_css( $entries ) { + $last = array(); + + foreach ( $entries as $index => $entry ) { + $last[ implode( "\x01", $entry['context'] ) . "\x02" . $entry['rule'] ] = $index; + } + + $css = ''; + $context = array(); + + foreach ( $entries as $index => $entry ) { + if ( $last[ implode( "\x01", $entry['context'] ) . "\x02" . $entry['rule'] ] !== $index ) { + continue; + } + + $css .= self::switch_context( $context, $entry['context'] ); + $context = $entry['context']; + $css .= $entry['rule'] . "\n"; + } + + return $css . self::switch_context( $context, array() ); + } + + /** + * Matches any of the style classes. :is() takes the specificity of a single class, + * so the merged rule keeps the specificity of each original rule. + * + * @since x.x + * + * @param array $classes Style classes with the leading dot. + * + * @return string + */ + private static function class_selector( $classes ) { + if ( 1 === count( $classes ) ) { + return reset( $classes ); + } + + return ':is(' . implode( ',', $classes ) . ')'; + } + + /** + * Closes and opens at-rule blocks to move from one rule's nesting to the next one's. + * + * @since x.x + * + * @param array $from + * @param array $to + * + * @return string + */ + private static function switch_context( $from, $to ) { + $shared = 0; + + while ( isset( $from[ $shared ], $to[ $shared ] ) && $from[ $shared ] === $to[ $shared ] ) { + ++$shared; + } + + $css = str_repeat( "}\n", count( $from ) - $shared ); + + foreach ( array_slice( $to, $shared ) as $prelude ) { + $css .= explode( self::BLOCK_MARKER, $prelude )[0] . '{'; + } + + return $css; + } +} diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 9e64f2be47..8bb4debb40 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -761,11 +761,18 @@ add_style( 'frm_style_' . $style->post_name, ob_get_clean() ); unset( $style ); } +echo $style_css_merger->get_css(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped +unset( $style_css_merger ); + // Set it again since it may have been overridden. $important = ! empty( $defaults['important_style'] ) ? ' !important' : ''; ?> diff --git a/tests/phpunit/styles/test_FrmStyleCssMerger.php b/tests/phpunit/styles/test_FrmStyleCssMerger.php new file mode 100644 index 0000000000..817c1fd34b --- /dev/null +++ b/tests/phpunit/styles/test_FrmStyleCssMerger.php @@ -0,0 +1,174 @@ +add_style( 'frm_style_a', ".frm_style_a.with_frm_style{--color:red;}\n.frm_style_a.with_frm_style .frm_label{color:var(--color);}" ); + $merger->add_style( 'frm_style_b', ".frm_style_b.with_frm_style{--color:blue;}\n.frm_style_b.with_frm_style .frm_label{color:var(--color);}" ); + + $css = $merger->get_css(); + + $this->assertStringContainsString( ':is(.frm_style_a,.frm_style_b).with_frm_style .frm_label{color:var(--color);}', $css ); + $this->assertStringContainsString( '.frm_style_a.with_frm_style{--color:red;}', $css ); + $this->assertStringContainsString( '.frm_style_b.with_frm_style{--color:blue;}', $css ); + $this->assertSame( 1, substr_count( $css, '.frm_label' ) ); + } + + public function test_rules_that_differ_by_important_are_not_merged() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a.with_frm_style .frm_label{color:var(--color);}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b.with_frm_style .frm_label{color:var(--color) !important;}' ); + $merger->add_style( 'frm_style_c', '.frm_style_c.with_frm_style .frm_label{color:var(--color) !important;}' ); + + $css = $merger->get_css(); + + $this->assertStringContainsString( '.frm_style_a.with_frm_style .frm_label{color:var(--color);}', $css ); + $this->assertStringContainsString( ':is(.frm_style_b,.frm_style_c).with_frm_style .frm_label{color:var(--color) !important;}', $css ); + } + + public function test_each_style_keeps_its_rule_order() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a .one{color:red;} .frm_style_a .two{color:blue;}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b .two{color:blue;} .frm_style_b .one{color:red;}' ); + + // Style b prints the rules in the other order, so only one of them can be shared + // without reordering a style. Style b's .two stays separate, before the shared .one. + $expected = ".frm_style_b .two{color:blue;}\n:is(.frm_style_a,.frm_style_b) .one{color:red;}\n.frm_style_a .two{color:blue;}\n"; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_only_the_last_copy_of_an_unscoped_rule_is_kept() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_total input{font-size:32px;} .frm_style_a .x{color:red;}' ); + $merger->add_style( 'frm_style_b', '.frm_total input{font-size:32px;} .frm_style_b .x{color:red;}' ); + + $this->assertSame( 1, substr_count( $merger->get_css(), '.frm_total input{font-size:32px;}' ) ); + } + + public function test_rules_in_media_queries_are_merged_inside_the_query() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '@media (max-width:600px){.frm_style_a .x{width:100%;}}' ); + $merger->add_style( 'frm_style_b', '@media (max-width:600px){.frm_style_b .x{width:100%;}}' ); + + $this->assertSame( "@media (max-width:600px){:is(.frm_style_a,.frm_style_b) .x{width:100%;}\n}\n", $merger->get_css() ); + } + + public function test_keyframes_with_the_same_name_stay_separate_blocks() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '@keyframes foo{0%{opacity:0;}50%{opacity:1;}100%{opacity:0;}} .frm_style_a .x{animation:foo 1s;}' ); + $merger->add_style( 'frm_style_b', '@keyframes foo{0%{opacity:0;}100%{opacity:1;}} .frm_style_b .x{animation:foo 1s;}' ); + + // The last @keyframes foo block replaces the earlier one, so style b's block must not include style a's 50% frame. + $expected = "@keyframes foo{0%{opacity:0;}\n50%{opacity:1;}\n100%{opacity:0;}\n}\n@keyframes foo{0%{opacity:0;}\n100%{opacity:1;}\n}\n"; + $expected .= ":is(.frm_style_a,.frm_style_b) .x{animation:foo 1s;}\n"; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_style_with_rules_in_another_style_css_is_not_merged() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a .x{color:red;} .frm_style_b .x{color:green;}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b .x{color:red;}' ); + $merger->add_style( 'frm_style_c', '.frm_style_c .x{color:red;}' ); + + // Style b's own rule must stay after the rule style a prints for it, so style b keeps the red color. + $expected = ":is(.frm_style_a,.frm_style_c) .x{color:red;}\n.frm_style_b .x{color:green;}\n.frm_style_b .x{color:red;}\n"; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_rule_naming_another_style_is_not_merged() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a .frm_style_b .x{color:red;}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b .x{color:green;}' ); + $merger->add_style( 'frm_style_c', '.frm_style_c .frm_style_b .x{color:red;}' ); + + // Each rule that names style b keeps its place around style b's own rule. + $expected = ".frm_style_a .frm_style_b .x{color:red;}\n.frm_style_b .x{color:green;}\n.frm_style_c .frm_style_b .x{color:red;}\n"; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_style_class_in_quoted_attribute_value_is_not_rewritten() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a [data-k=".frm_style_a"]{color:red;}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b [data-k=".frm_style_b"]{color:red;}' ); + + $expected = ".frm_style_a [data-k=\".frm_style_a\"]{color:red;}\n.frm_style_b [data-k=\".frm_style_b\"]{color:red;}\n"; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_css_with_layer_blocks_is_printed_unchanged() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '@layer base{.frm_style_a .x{color:red;}} @layer over{.frm_style_a .x{color:blue;}}' ); + $merger->add_style( 'frm_style_b', '@layer over{.frm_style_b .x{color:blue;}} @layer base{.frm_style_b .x{color:red;}}' ); + + // The first block for each layer sets the layer order, so style b's over block must not move ahead of style a's base block. + $expected = '@layer base{.frm_style_a .x{color:red;}} @layer over{.frm_style_a .x{color:blue;}}' . "\n"; + $expected .= '@layer over{.frm_style_b .x{color:blue;}} @layer base{.frm_style_b .x{color:red;}}'; + + $this->assertSame( $expected, $merger->get_css() ); + } + + public function test_unsupported_css_is_printed_unchanged() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a .x::before{content:"{";}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b .x::before{content:"{";}' ); + + $this->assertSame( ".frm_style_a .x::before{content:\"{\";}\n.frm_style_b .x::before{content:\"{\";}", $merger->get_css() ); + } + + public function test_generated_stylesheet_merges_style_rules() { + $default_style = ( new FrmStyle() )->get_default_style(); + $this->factory->post->create( + array( + 'post_type' => FrmStylesController::$post_type, + 'post_status' => 'publish', + 'post_name' => 'merge-test', + 'post_content' => FrmAppHelper::prepare_and_encode( $default_style->post_content ), + ) + ); + wp_cache_flush(); + + // Per form styles are only printed with Pro. + add_filter( 'frm_pro_installed', '__return_true' ); + + try { + $css = $this->run_private_method( + array( new FrmStyle(), 'get_css_content' ), + array( FrmAppHelper::plugin_path() . '/css/custom_theme.css.php' ) + ); + } finally { + remove_filter( 'frm_pro_installed', '__return_true' ); + } + + $both_styles = ':is(.frm_style_' . $default_style->post_name . ',.frm_style_merge-test).with_frm_style'; + + $this->assertStringContainsString( $both_styles . ' .frm_form_field.frm_left_container{', $css ); + $this->assertStringNotContainsString( '.frm_style_merge-test.with_frm_style .frm_form_field.frm_left_container', $css ); + } + + public function test_merging_can_be_turned_off() { + $merger = new FrmStyleCssMerger(); + $merger->add_style( 'frm_style_a', '.frm_style_a .x{color:red;}' ); + $merger->add_style( 'frm_style_b', '.frm_style_b .x{color:red;}' ); + + add_filter( 'frm_merge_style_css', '__return_false' ); + + try { + $this->assertSame( ".frm_style_a .x{color:red;}\n.frm_style_b .x{color:red;}", $merger->get_css() ); + } finally { + remove_filter( 'frm_merge_style_css', '__return_false' ); + } + } +}