get_status = $get_status; $this->variable_names_by_id = $variable_names_by_id; $this->is_deleted_variable = $is_deleted_variable; $this->scalar_value = $scalar_value; $this->variable_name = $variable_name; } /** * Return fallback variable declarations for contexts where Elementor's * generated kit stylesheet is not available (such as an editor preview). */ public function get_fallback_variables_css(): string { $settings = Plugin::get_settings(); $variables = $settings['fallback_payload']['variables'] ?? []; if ( empty( $variables ) || ! is_array( $variables ) ) { return ''; } $entries = []; foreach ( $variables as $variable ) { $name = $variable['name'] ?? ''; $value = $variable['value'] ?? ''; if ( ! is_string( $name ) || ! is_string( $value ) || ! CSS_Value_Utils::is_safe_css_variable_name( $name ) ) { continue; } $value = CSS_Value_Utils::sanitize_css_variable_value( $value ); if ( '' === $value ) { continue; } $entries[] = $name . ':' . $value . ';'; } return empty( $entries ) ? '' : ':root{' . implode( '', $entries ) . '}'; } /** * @param array|null $exclude Class names to leave out because Elementor already * renders them (null: none). That is every class Elementor holds, so an edit made in * Elementor's own class editor is never overridden. */ public function get_fallback_classes_css( ?array $exclude = null ): string { $settings = Plugin::get_settings(); $classes = $settings['fallback_payload']['classes'] ?? []; if ( empty( $classes ) || ! is_array( $classes ) ) { return ''; } if ( null !== $exclude ) { $held = array_flip( array_map( 'strval', $exclude ) ); $classes = array_values( array_filter( $classes, static fn( $class ): bool => ! is_array( $class ) || ! isset( $held[ (string) ( $class['class_name'] ?? '' ) ] ) ) ); if ( empty( $classes ) ) { return ''; } } // The '3|' prefix is the compiler generation. This key is otherwise a hash of the // class payload alone, which does not change when the COMPILER changes — so a fix to // the emitted CSS would stay invisible on every existing install until the day-long // transient expired or the user re-saved their settings. Bump the prefix whenever // build_fallback_classes_css() changes the CSS it emits. // 2 — admin-bar exclusion added. // 3 — blanket !important removed. // 4 — media blocks ordered by narrowing scope instead of payload order. $cache_key = 'v4studio_fallback_css_' . md5( '4|' . (string) wp_json_encode( $classes ) ); $cached = get_transient( $cache_key ); if ( is_string( $cached ) ) { return $cached; } $css = $this->build_fallback_classes_css( $classes ); // The key is a content hash, so every edit would otherwise leave its predecessor // behind in wp_options until it expired. Retire the previous key as the new one // is written so exactly one of these rows exists at a time. $previous_key = get_option( 'v4studio_fallback_css_key', '' ); if ( is_string( $previous_key ) && '' !== $previous_key && $previous_key !== $cache_key ) { delete_transient( $previous_key ); } set_transient( $cache_key, $css, DAY_IN_SECONDS ); update_option( 'v4studio_fallback_css_key', $cache_key, false ); return $css; } public function build_fallback_classes_css( array $classes ): string { $rules_by_media = []; foreach ( $classes as $class ) { $selector = $class['selector'] ?? ''; $media_query = $this->sanitize_media_query( (string) ( $class['media_query'] ?? '' ) ); $declarations = $class['declarations'] ?? []; $entries = []; if ( ! is_string( $selector ) || ! CSS_Value_Utils::is_safe_class_state_selector( $selector ) || ! is_array( $declarations ) ) { continue; } foreach ( $declarations as $property => $value ) { $property = CSS_Value_Utils::sanitize_css_property( (string) $property ); $value = CSS_Value_Utils::sanitize_css_declaration_value( (string) $value ); if ( '' === $property || '' === $value ) { continue; } // Emitted WITHOUT a blanket !important. An !important already in the stored value // survives inside $value untouched. // // The blanket !important was never needed to beat Elementor: the companion // `.elementor .x` rule below ties Elementor's own global classes at (0,2,0) and // this stylesheet loads after them, so it already wins on source order. What the // blanket DID beat was WordPress core chrome — core sizes the toolbar avatar at // (2,2,3) — and it also made design-system classes // impossible for a site owner to override from Customizer Additional CSS. // // Measured in a real browser before this change (F5A): 0 computed-style changes // across 8,280 probes on an Elementor-canvas page and 4,968 more inside a theme // header, against 22,619 and 16,534 declarations the fallback genuinely wins. $entries[] = $property . ':' . $value; } if ( empty( $entries ) ) { continue; } // Design-system class names are bare and every declaration is emitted !important, // so a name that collides with WordPress chrome overrides core. `.avatar` is the // live case: core renders the toolbar user icon as img.avatar at 26px, and our // .avatar utility resized it to var(--size-4xl). Excluding the admin bar keeps the // design system off WordPress's own furniture without touching the site's markup. // // :where() is deliberate. A bare :not(#wpadminbar *) takes the specificity of its // argument, adding an ID's worth of weight to all 500+ emitted utilities and // silently letting them beat site CSS that previously won. :where() contributes // zero specificity, so every rule keeps the weight it had before this fix. $scoped = $this->browser_state_selector( $selector ) . ':where(:not(#wpadminbar *))'; $rules_by_media[ $media_query ][] = $scoped . ',.elementor ' . $scoped . '{' . implode( ';', $entries ) . '}'; } $rules = $rules_by_media[''] ?? []; /* * Media blocks are ORDERED, not emitted in the order classes happened to be parsed. * * Every rule here carries the same specificity, so among the queries that match a given * viewport the LAST one wins. `$rules_by_media` is keyed by query string and was iterated * in insertion order, which is payload order — so a narrower query could be emitted before * a wider one and lose to it. Measured on /bento/ at 500px wide: `.bento-modular` emitted * max-width 767 before max-width 1024, both matched, the 1024 rule came last and won, and * the mobile layout rendered two columns instead of one. Elementor's own stylesheet had it * right; this stylesheet loads after Elementor's and overrode it. * * Correct order is by narrowing scope: max-width descending, then min-width ascending, so * the most specific match for any viewport is always last. Queries that name neither — a * range, orientation, or any other feature — keep their relative order and follow, since * nothing can be inferred about how they nest. */ $media_queries = []; foreach ( array_keys( $rules_by_media ) as $media_query ) { if ( '' === $media_query || empty( $rules_by_media[ $media_query ] ) ) { continue; } $media_queries[] = $media_query; } $media_queries = $this->order_media_queries( $media_queries ); foreach ( $media_queries as $media_query ) { $rules[] = '@media ' . $media_query . '{' . implode( '', $rules_by_media[ $media_query ] ) . '}'; } return implode( "\n", $rules ); } /** * The selector a browser matches for a stored class-state selector. * * The stored source and Elementor's records spell the Selected state like a pseudo-class, * `.accordion-header-default:e--selected`, because the parser and the exporter read and write * every state as `.class:state`. Elementor renders that state as a CLASS, `.e--selected`, which its * accordion and tab scripts toggle. Emitted as written, the selector is invalid CSS and the * browser drops the whole rule, so the fallback stylesheet would carry the open state for nothing. */ private function browser_state_selector( string $selector ): string { return (string) preg_replace( '/:e--selected$/', '.e--selected', $selector ); } /** * Order media queries by narrowing scope. * * Every rule the compiler emits carries the same specificity, so among the queries that * match a given viewport the LAST one wins. Emitting them in payload order lets a * narrower query be written before a wider one and lose to it. Measured on /bento/ at * 500px wide: `.bento-modular` emitted max-width 767 before max-width 1024, both * matched, the 1024 rule came last and won, and the mobile layout rendered two columns * instead of one. Elementor's own stylesheet had it right; this stylesheet loads after * Elementor's and overrode it. * * Correct order is max-width descending, then min-width ascending, so the most specific * match for any viewport is always last. Queries naming neither — a range, orientation, * or any other feature — keep their relative order and follow, since nothing can be * inferred about how they nest. * * @param string[] $media_queries * @return string[] */ public function order_media_queries( array $media_queries ): array { $order = array_flip( array_values( $media_queries ) ); usort( $media_queries, static function ( string $a, string $b ) use ( $order ): int { $rank = static function ( string $query ): array { if ( preg_match( '/max-width\s*:\s*(\d+(?:\.\d+)?)/i', $query, $m ) ) { // Descending: the widest ceiling first, so narrower ceilings win later. return [ 0, -1 * (float) $m[1] ]; } if ( preg_match( '/min-width\s*:\s*(\d+(?:\.\d+)?)/i', $query, $m ) ) { return [ 1, (float) $m[1] ]; } return [ 2, 0.0 ]; }; $rank_a = $rank( $a ); $rank_b = $rank( $b ); if ( $rank_a[0] !== $rank_b[0] ) { return $rank_a[0] <=> $rank_b[0]; } if ( $rank_a[1] !== $rank_b[1] ) { return $rank_a[1] <=> $rank_b[1]; } // Stable for equal ranks, so the emitted CSS is byte-deterministic. return $order[ $a ] <=> $order[ $b ]; } ); return $media_queries; } /** * Why the last normalize_media_order() call declined to reorder, or '' if it did. * * A diagnostic, inspected when debugging; not part of the stored settings. * * @var string */ private string $last_normalize_bail_reason = ''; /** * Record why normalisation was declined and hand back the untouched document. */ private function bail_normalize( string $css, string $reason ): string { $this->last_normalize_bail_reason = $reason; return $css; } /** * Consolidate and order the @media blocks in a CSS document. * * Class CSS can arrive one rule at a time, each responsive rule carrying its own * `@media` wrapper, emitted in field order. That yields dozens of single-rule blocks with * `max-width: 767px` appearing before `max-width: 1024px` — both match a phone, equal * specificity, last one wins, so the tablet rule beats the mobile rule and the mobile * layout renders the tablet grid. It is the same defect the compiler and exporter already * guard against, arriving through a third door. * * Base rules keep their original order and position. Media rules are grouped by query and * re-emitted in narrowing-scope order after them. * * Idempotent: normalising an already-normalised document returns the same text. * * Fails safe. The scanner can only reason about a balanced document; on an unterminated * comment, a missing `{` or a missing `}` it cannot know where the malformed construct * ends. It used to `break`, and the return value was assembled from what it had collected * so far — silently discarding everything after the break point, which `save_css()` then * persisted. A mid-edit `/*` in a document that already contained `@media` therefore * destroyed the rest of the stylesheet. Now it returns the input untouched, which is what * the no-`@media` path at the end of the scan has always done. The reason is recorded on * {@see self::$last_normalize_bail_reason}. */ public function normalize_media_order( string $css ): string { $this->last_normalize_bail_reason = ''; $length = strlen( $css ); $i = 0; $base = []; $by_query = []; while ( $i < $length ) { if ( ctype_space( $css[ $i ] ) ) { $i++; continue; } if ( '/' === $css[ $i ] && $i + 1 < $length && '*' === $css[ $i + 1 ] ) { $close = strpos( $css, '*/', $i ); if ( false === $close ) { return $this->bail_normalize( $css, 'unterminated comment' ); } $base[] = substr( $css, $i, $close + 2 - $i ); $i = $close + 2; continue; } $brace = strpos( $css, '{', $i ); if ( false === $brace ) { return $this->bail_normalize( $css, 'missing opening brace' ); } $is_at = '@' === $css[ $i ]; if ( ! $is_at ) { $close = strpos( $css, '}', $brace ); if ( false === $close ) { return $this->bail_normalize( $css, 'missing closing brace' ); } $base[] = trim( substr( $css, $i, $close + 1 - $i ) ); $i = $close + 1; continue; } // Walk to the balanced close of the at-block. $depth = 0; $j = $brace; for ( ; $j < $length; $j++ ) { if ( '{' === $css[ $j ] ) { $depth++; } elseif ( '}' === $css[ $j ] ) { $depth--; if ( 0 === $depth ) { break; } } } $prelude = trim( substr( $css, $i, $brace - $i ) ); $body = substr( $css, $brace + 1, $j - $brace - 1 ); if ( 0 === stripos( $prelude, '@media' ) ) { $query = trim( substr( $prelude, 6 ) ); $by_query[ $query ][] = trim( $body ); } else { // Any other at-rule is opaque; keep it where it is. $base[] = trim( substr( $css, $i, $j + 1 - $i ) ); } $i = $j + 1; } if ( empty( $by_query ) ) { return $css; } $rules = $base; foreach ( $this->order_media_queries( array_keys( $by_query ) ) as $query ) { $inner = []; foreach ( $by_query[ $query ] as $body ) { // Strip any indentation the previous pass added before re-indenting, or // normalising an already-normalised document keeps deepening it and the // operation stops being idempotent. $body = trim( preg_replace( '/^[ \t]+/m', '', $body ) ?? $body ); if ( '' !== $body ) { // Indent only non-empty lines: indenting a blank separator line leaves // trailing spaces that the next pass cannot remove, which alone would // break idempotence. $inner[] = preg_replace( '/^(?=.)/m', ' ', $body ) ?? $body; } } if ( ! empty( $inner ) ) { $rules[] = '@media ' . $query . " {\n" . implode( "\n\n", $inner ) . "\n}"; } } return implode( "\n\n", $rules ) . "\n"; } public function sanitize_media_query( string $media_query ): string { $media_query = trim( wp_strip_all_tags( $media_query ) ); if ( preg_match( '/^\((?:min|max)-width:\s*\d+(?:\.\d+)?px\)$/i', $media_query ) ) { return $media_query; } return ''; } public function export_variables_css( array $ignored_labels = [] ): string { $status = call_user_func( $this->get_status ); $ignored_labels = array_flip( array_map( 'sanitize_key', $ignored_labels ) ); if ( ! $status['elementor_active'] || ! $status['variables_rest_api'] ) { return ":root {\n}"; } $request = new WP_REST_Request( 'GET', '/elementor/v1/variables/list' ); $response = rest_do_request( $request ); if ( $response->is_error() || $response->get_status() >= 400 ) { return ":root {\n}"; } $data = $response->get_data(); $variables = $data['data']['variables'] ?? []; $lines = []; if ( ! is_array( $variables ) ) { return ":root {\n}"; } foreach ( $variables as $variable ) { if ( ! is_array( $variable ) || call_user_func( $this->is_deleted_variable, $variable ) ) { continue; } $name = call_user_func( $this->variable_name, $variable ); $value = call_user_func( $this->scalar_value, $variable ); $label = sanitize_key( ltrim( $name, '-' ) ); if ( '' === $name || '' === $value || isset( $ignored_labels[ $label ] ) ) { continue; } $lines[ $label ] = ' ' . $name . ': ' . CSS_Value_Utils::sanitize_css_variable_value( $value ) . ';'; } return ":root {\n" . implode( "\n", array_values( $lines ) ) . "\n}"; } }